refactor(session): extract the engine host
CI / ci (push) Canceled after 0s

Engine lifecycle policy — spawn, handshake, respawn-on-crash, teardown,
and the per-surface residency rules (resident chat engine; one-shot
pass engines spawned per run, torn down at the verdict, ADR-0014) —
moves out of MentorSessionModel into EngineHost behind the
EngineTransport seam. The model keeps session + turn coordination and
stays the only observable the panes see; ACPEngineClient becomes the
seam's production adapter, and a scripted in-process engine
(ScriptedEngine) becomes the second adapter — engine-behaviour tests
(streaming, crash, cancel, restart, per-surface spawn) now run without
child processes, retiring the zsh fake-server rigs from logic tests
(#30 flake family). Exactly one real-process wire smoke per LLM
surface survives (chat two-act + parameterized pass1/pass2): the
held-turn cancel contract, hung-child SIGTERM teardown, handshake,
streamed turn, crash, restart.

One-shot teardown is structural (withOneShot closes at body end, every
exit path); the one-shot slot is claimed before the first suspension so
the at-most-one invariant holds across the spawn/handshake awaits.

Suite: 652 executed / 652 passed / 0 failed (653 argument cases),
counted from the xcresult; swiftformat idempotent, swiftlint clean on
touched files.

Closes #178
This commit is contained in:
AlexKucera committed 2026-11-09 18:26:16 +01:00
1 parent d14cb40e73
commit 627ecf515e
18 files changed
+1663 -639

No files matched your search

+21 -13
View File
@@ -108,6 +108,11 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
var onCrash: (@Sendable () -> Void)?
/// stderr lines (engine logs) — surfaced for the restart prompt's details.
var onStderrLine: (@Sendable (String) -> Void)?
/// Every notification (method + params), in wire order (#178: the
/// EngineTransport seam's message rail). Always set before start() — the
/// host does it from MainActor, and process.run() provides the
/// happens-before for the queue-confined reads below.
var onMessage: (@Sendable (String, JSONValue?) -> Void)?
/// #137 (S4, ADR-0014): one Hermes profile per LLM surface — the chat
/// engine keeps the default `museion`; pass engines spawn `-p museion-passN`.
@@ -124,9 +129,9 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
process.processIdentifier
}
/// Spawn the child. `onMessage` receives every notification (method +
/// params), in wire order.
func start(onMessage: @escaping @Sendable (_ method: String, _ params: JSONValue?) -> Void) throws {
/// Spawn the child. Notifications (method + params) arrive on `onMessage`
/// in wire order; set it before calling.
func start() throws {
guard !started else { return }
started = true
// A crashed engine closes the pipe; ignoring SIGPIPE turns a kill-signal
@@ -137,13 +142,15 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
self?.queue.async { self?.failAll("engine exited (code \(self?.process.terminationStatus ?? 0))") }
}
readStderr()
readStdout(onMessage: onMessage)
readStdout()
}
/// Send a JSON-RPC request and await its matching response result.
/// A request that gets no answer within `timeout` fails — a hung engine
/// must surface as an error (→ restart prompt), never an eternal await.
func request(_ method: String, params: JSONValue? = nil, timeout: TimeInterval = 15) async throws -> JSONValue? {
/// (No default arguments: the only caller is EngineHost, which rides the
/// seam — `EngineTransport.request`'s convenience owns the default shape.)
func request(_ method: String, params: JSONValue?, timeout: TimeInterval) async throws -> JSONValue? {
let id = queue.sync {
currentID += 1
return currentID
@@ -178,8 +185,9 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
}
}
/// Send a JSON-RPC notification (no id, no response).
func notify(_ method: String, params: JSONValue? = nil) {
/// Send a JSON-RPC notification (no id, no response). Always called with
/// explicit params (session/cancel) — no default, same reasoning as request.
func notify(_ method: String, params: JSONValue?) {
let payload: [String: Any] = [
"jsonrpc": "2.0",
"method": method,
@@ -261,7 +269,7 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
}
}
private func readStdout(onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
private func readStdout() {
stdoutPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in
let data = handle.availableData
guard !data.isEmpty else {
@@ -269,12 +277,12 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
self?.queue.async { self?.failAll("engine stdout closed (EOF)") }
return
}
self?.queue.async { self?.ingest(data, onMessage: onMessage) }
self?.queue.async { self?.ingest(data) }
}
}
/// Buffer incoming bytes, split on \n, decode each line as one JSON-RPC message.
private func ingest(_ data: Data, onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
private func ingest(_ data: Data) {
buffer.append(data)
// ponytail: 1 MB line cap — a corrupt/hostile engine streaming one
// newline-free line would otherwise grow the buffer unbounded.
@@ -288,11 +296,11 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
guard !line.isEmpty,
let json = try? JSONSerialization.jsonObject(with: line),
let object = json as? [String: Any] else { continue }
dispatch(object, onMessage: onMessage)
dispatch(object)
}
}
private func dispatch(_ object: [String: Any], onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
private func dispatch(_ object: [String: Any]) {
let id = object["id"] as? Int
let method = object["method"] as? String
@@ -327,7 +335,7 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
// Notification.
if let method {
onMessage(method, object["params"].map { JSONValue($0) })
onMessage?(method, object["params"].map { JSONValue($0) })
}
}
}