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

+98 -169
View File
@@ -2,12 +2,16 @@
// ACPClientTests.swift
// MuseionTests
//
// M0 ACP bridge (#14): the fake ACP server test double — a zsh script
// speaking real NDJSON JSON-RPC on stdio (map decision: extends the
// fake-binary Process pattern from EngineGateTests). Exercises the client
// and model against the real Process path: handshake, prompt + streamed
// updates + fix-card tool call, crash, teardown.
// #124: hangOnPrompt now acknowledges session/cancel (stopReason
// M0 ACP bridge (#14), #178 split: engine BEHAVIOUR (streaming, crash,
// cancel, restart, thought lane, refusal, stray-research routing, strict
// session/new) runs IN-PROCESS against ScriptedEngine rigs
// (ScriptedEngine.swift) at the EngineTransport seam — no child process
// ever spawns from this suite. The file still OWNS the zsh fake harness
// (makeFakeACP/acpTempDir + the payload b64 helpers): the real-process
// smokes (EngineSmokeTests) reuse it to guard the actual stdio wire
// contract — handshake, stream, crash, restart, fire-and-forget cancel,
// teardown reaping the hung child — one smoke per LLM surface.
// #124: hangOnPrompt acknowledges session/cancel (stopReason
// "cancelled") — a sleep-oblivious hold can't pin the Cancel rail.
//
@@ -205,35 +209,23 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
// swiftlint:enable function_body_length
/// The fix-card payload for the fake's tool call, base64-encoded so shell
/// quoting can never break the wire JSON. The REAL submit_fix_cards
/// argument shape (snake_case, anchor as object) — pins the nested parse;
/// the flat #14-era shape was a regression the parser never matched the
/// live rail (review).
/// quoting can never break the wire JSON. The JSON itself lives in
/// ScriptedPayloads (#178) — the scripted engine ships the identical bytes.
private func fixCardPayloadB64() -> String {
let card = #"{"pattern":"Blame tense","problem":"Never pivots to choice","# +
#""diagnostic_question":"What tense?","fix":"Pivot on the hinge","# +
#""anchor":{"quote":"We should stop listening.","occurrence":1}}"#
let json = #"{"piece_path":"/tmp/piece","cards":["# + card + #"]}"#
return Data(json.utf8).base64EncodedString()
Data(ScriptedPayloads.fixCardJSON.utf8).base64EncodedString()
}
/// The research-notes payload for the fake's replayed tool call (#29) —
/// base64 like the fix card so shell quoting can never break the wire JSON.
/// Two notes: one complete, one with quote/note absent (the "" defaults).
private func researchPayloadB64() -> String {
let json = #"{"piece_path":"/tmp/piece","notes":["# +
#"{"title":"Hinge Study","url":"https://example.org/hinge","quote":"We should stop listening.","note":"Counts the pivot tense."},"# +
#"{"title":"Second Source","url":"https://example.org/second"}]}"#
return Data(json.utf8).base64EncodedString()
Data(ScriptedPayloads.researchJSON.utf8).base64EncodedString()
}
/// The #29 routing pin's payload: a research batch that ALSO carries stray
/// fix-card keys at the top level (LLM tool calls pick up stray keys). The
/// notes-array shape must win over the pattern/problem match.
private func strayResearchPayloadB64() -> String {
let json = #"{"pattern":"stray","problem":"stray","piece_path":"/tmp/piece","notes":["# +
#"{"title":"Hinge Study","url":"https://example.org/hinge"}]}"#
return Data(json.utf8).base64EncodedString()
Data(ScriptedPayloads.strayResearchJSON.utf8).base64EncodedString()
}
func acpTempDir(_ label: String) -> String {
@@ -242,112 +234,46 @@ func acpTempDir(_ label: String) -> String {
return dir
}
/// A strict `session/new` guard, mirroring the ACP SDK's required mcpServers
/// (adapter ≥0.21.5 rejects the field's absence with -32602). The lenient
/// fake above accepts anything and can't catch this bug class.
private func makeStrictFakeACP(at dir: String, name: String = "hermes-acp-strict") -> String {
let path = (dir as NSString).appendingPathComponent(name)
let script = """
#!/bin/zsh
framing='{"jsonrpc":"2.0","id":'
jq=/usr/bin/python3
while IFS= read -r line; do
[[ -z "$line" ]] && continue
method=$(echo "$line" | $jq -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(echo "$line" | $jq -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
if [[ "$method" == "initialize" ]]; then
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
elif [[ "$method" == "session/new" ]]; then
ok=$(echo "$line" | $jq -c 'import json,sys; print("1" if "mcpServers" in json.load(sys.stdin).get("params",{}) else "0")')
if [[ "$ok" == "1" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
else
echo $framing"$rid",'"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}'
fi
fi
done
exit 0
"""
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
try? script.write(toFile: path, atomically: true, encoding: .utf8)
_ = try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path)
return path
}
// MARK: - Client tests
//
// The real-process client wire tests (handshake, crash-after-handshake,
// fire-and-forget cancel, teardown kills the hung child) are RETIRED to
// EngineSmokeTests (slice B2, one real-process smoke per LLM surface).
// Their behaviour classes stay pinned in-process here: the handshake via
// `model handshake renders version and streams fix card`, the crash rail
// via the scripted pin below + `model crash surfaces restart prompt and
// fresh engine recovers`, the cancel acknowledgement via the hangOnPrompt
// suites (PassRunTests/EngineLifecycleTests), and teardown failing pending
// requests via `transport failure mid-turn maps to TurnOutcome failed`
// (now also pinning isClosed).
@Suite("ACPClientTests")
struct ACPClientTests {
@Test func `handshake returns agent version`() async throws {
let fake = makeFakeACP(at: acpTempDir("handshake"))
let client = ACPEngineClient(binaryPath: fake)
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
try client.start { _, _ in }
let result = try await client.request("initialize", params: .object([
"protocolVersion": .number(1),
"clientCapabilities": .object([:]),
"clientInfo": .object(["name": .string("Museion"), "title": .string("Museion"), "version": .string("0.1")]),
]))
#expect(result?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue == "9.9.9")
}
@Test func `crash after handshake fires onCrash`() async throws {
let fake = makeFakeACP(at: acpTempDir("crash"), mode: "crashAfterHandshake")
let client = ACPEngineClient(binaryPath: fake)
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
try client.start { _, _ in }
// Hook FIRST, then trigger: the fake exits right after answering
// initialize, so the crash can beat a hook attached after the request.
/// In-process port of the retired `crash after handshake fires onCrash`
/// client test: the engine answers initialize, then dies — onCrash fires
/// EXACTLY once (confirmation enforces the count) and every subsequent
/// request fails with the exited-engine error.
@Test func `crash after handshake fires onCrash exactly once`() async throws {
let engine = ScriptedEngine(profile: "museion", mode: "crashAfterHandshake")
defer { engine.close() }
engine.onMessage = { _, _ in }
await confirmation("onCrash fires once") { crashed in
client.onCrash = { crashed() }
_ = try? await client.request("initialize", params: nil)
try? await Task.sleep(for: .milliseconds(500))
engine.onCrash = { crashed() }
_ = try? await engine.request("initialize", params: nil, timeout: 15)
}
}
@Test func `cancel is fire-and-forget`() async throws {
let fake = makeFakeACP(at: acpTempDir("cancel"), mode: "hangOnPrompt")
let client = ACPEngineClient(binaryPath: fake)
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
try client.start { _, _ in }
_ = try? await client.request("session/new", params: .object(["cwd": .string("/tmp")]))
// The prompt holds — drive it in the background, then cancel.
let promptTask = Task { try? await client.request("session/prompt", params: .object([
"sessionId": .string("sess-1"),
"prompt": .array([.object(["type": .string("text"), "text": .string("hello")])]),
])) }
try await Task.sleep(for: .milliseconds(300))
client.notify("session/cancel", params: .object(["sessionId": .string("sess-1")]))
try await Task.sleep(for: .milliseconds(200))
client.close() // bound only — the fake answers the prompt on cancel
_ = await promptTask.value
// ponytail: reaching here without deadlock IS the cancel test — a
// notification produces no response and the client never waits for one.
#expect(true)
}
@Test func `teardown kills a hung child and fails pending requests`() async throws {
let fake = makeFakeACP(at: acpTempDir("teardown"), mode: "hangOnPrompt")
let client = ACPEngineClient(binaryPath: fake)
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
try client.start { _, _ in }
_ = try? await client.request("session/new", params: .object(["cwd": .string("/tmp")]))
let promptTask = Task { try? await client.request("session/prompt", params: .object([
"sessionId": .string("sess-1"),
"prompt": .array([.object(["type": .string("text"), "text": .string("hello")])]),
])) }
try await Task.sleep(for: .milliseconds(300))
let pid = client.childProcessIdentifier
client.close()
_ = await promptTask.value
var gone = false
for _ in 0 ..< 50 where kill(pid, 0) != 0 {
try await Task.sleep(for: .milliseconds(100))
#expect(engine.crashedOnce)
do {
_ = try await engine.request(
"session/new",
params: .object(["cwd": .string("/tmp"), "mcpServers": .array([])]),
timeout: 15,
)
Issue.record("a crashed engine answered session/new")
} catch {
// TransportError-parity: the message rides the description.
#expect(String(describing: error).contains("engine exited"))
}
if kill(pid, 0) != 0 {
gone = true
}
#expect(gone)
}
// MARK: - Turn outcome seam (#24 S3.1: sendPrompt → TurnOutcome)
@@ -357,8 +283,8 @@ struct ACPClientTests {
@MainActor
@Test func `sendPrompt returns ended end_turn and streams text`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-ended"))
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
@@ -374,8 +300,8 @@ struct ACPClientTests {
@MainActor
@Test func `labeled prompt renders the label not the wire stub`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-label"))
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
// The pass orchestrator sends a long wire stub; only the label may land.
@@ -392,8 +318,8 @@ struct ACPClientTests {
@MainActor
@Test func `cancelled stopReason maps to TurnOutcome cancelled`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-cancel"), mode: "cancelOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines(mode: "cancelOnPrompt")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
@@ -404,8 +330,8 @@ struct ACPClientTests {
/// turn — .failed, so a pass never advances on a maybe.
@MainActor
@Test func `missing stopReason maps to failed`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-nostop"), mode: "noStopReason")
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines(mode: "noStopReason")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
@@ -495,8 +421,8 @@ struct ACPClientTests {
@MainActor
@Test func `refusal maps to ended refusal and still renders the refusal row`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-refusal"), mode: "refuseOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines(mode: "refuseOnPrompt")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
@@ -516,8 +442,8 @@ struct ACPClientTests {
/// display text; the payload is the contract.
@MainActor
@Test func `research payload with stray card keys renders candidates not a card`() async {
let fake = makeFakeACP(at: acpTempDir("stray-research"), mode: "strayResearchOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines(mode: "strayResearchOnPrompt")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("research this")
@@ -549,11 +475,11 @@ struct ACPClientTests {
@MainActor
@Test func `thought chunks land in a collapsed thought row not the critique`() async {
let fake = makeFakeACP(at: acpTempDir("thought-lane"))
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
// The fake streams a thought chunk BEFORE the message chunks — the
// The engine streams a thought chunk BEFORE the message chunks — the
// live shape of a pass turn (long thinking, then the critique).
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
@@ -582,12 +508,13 @@ struct ACPClientTests {
@MainActor
@Test func `transport failure mid-turn maps to TurnOutcome failed`() async throws {
let fake = makeFakeACP(at: acpTempDir("outcome-failed"), mode: "hangOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines(mode: "hangOnPrompt")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let engine = try #require(engines.engines.last)
// Deterministic transport failure through the model: hangOnPrompt keeps
// the turn pending, then shutdown() closes the client — the in-flight
// the turn pending, then shutdown() closes the engine — the in-flight
// session/prompt fails with a transport error, the same route a mid-turn
// engine error takes. crashAfterHandshake can't pin this: after the crash
// the phase is .crashed and sendPrompt's guard refuses before any request.
@@ -598,15 +525,18 @@ struct ACPClientTests {
model.shutdown()
let outcome = await promptTask.value
#expect(outcome == .failed)
// The in-process teardown pin (was: teardown kills a hung child):
// close() both closed the engine and failed the pending request.
#expect(engine.isClosed)
}
}
// MARK: - Model tests
@Test @MainActor func `model handshake renders version and streams fix card`() async throws {
let fake = makeFakeACP(at: acpTempDir("model"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() } // #124: at rig creation — the child dies with the test, however it exits
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
guard case .ready = model.phase else {
Issue.record("expected ready, got \(model.phase)")
@@ -615,9 +545,9 @@ struct ACPClientTests {
#expect(model.activeEntry?.sessionId == "sess-1")
#expect(model.engineVersion == "9.9.9")
await model.sendPrompt("hello mentor")
// The card row lands via a client notification Task that can settle just
// after the response resumes this test under full-suite load — bounded
// settle (house poll pattern); the pin itself is unchanged.
// The card row lands via a notification hop that can settle just after
// the response resumes this test under full-suite load — bounded settle
// (house poll pattern); the pin itself is unchanged.
var hasCard = false
for _ in 0 ..< 250 where !hasCard {
hasCard = model.rows.contains { row in
@@ -642,11 +572,11 @@ struct ACPClientTests {
@MainActor
@Test func `model surfaces advisory version drift note`() async {
let fake = makeFakeACP(at: acpTempDir("drift"))
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
// Running 9.9.9 vs recorded 0.20.6 → the advisory note fires, never blocks.
model.recordedVersionProvider = { "0.20.6" }
model.host.recordedVersionProvider = { "0.20.6" }
await model.openSession()
guard case .ready = model.phase else {
Issue.record("expected ready despite drift, got \(model.phase)")
@@ -658,12 +588,12 @@ struct ACPClientTests {
@MainActor
@Test func `build metadata does not fabricate version drift`() async {
let fake = makeFakeACP(at: acpTempDir("metadata-drift"))
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
// The gate records the derived version; the handshake answers the base —
// same engine, strings differ only in +build metadata → no note.
model.recordedVersionProvider = { "9.9.9+2177.g735e426" }
model.host.recordedVersionProvider = { "9.9.9+2177.g735e426" }
await model.openSession()
guard case .ready = model.phase else {
Issue.record("expected ready, got \(model.phase)")
@@ -674,16 +604,18 @@ struct ACPClientTests {
@MainActor
@Test func `real base-version drift still fires the note`() {
#expect(MentorSessionModel.baseVersion(of: "0.21.5+2177.g735e426") == "0.21.5")
#expect(MentorSessionModel.baseVersion(of: "0.21.5") == "0.21.5")
#expect(MentorSessionModel.baseVersion(of: "unknown") == "unknown")
#expect(MentorSessionModel.baseVersion(of: "0.20.6") != MentorSessionModel.baseVersion(of: "0.21.5"))
#expect(EngineHost.baseVersion(of: "0.21.5+2177.g735e426") == "0.21.5")
#expect(EngineHost.baseVersion(of: "0.21.5") == "0.21.5")
#expect(EngineHost.baseVersion(of: "unknown") == "unknown")
#expect(EngineHost.baseVersion(of: "0.20.6") != EngineHost.baseVersion(of: "0.21.5"))
}
@MainActor
@Test func `session new against strict mcpServers schema reaches ready`() async {
let fake = makeStrictFakeACP(at: acpTempDir("strict"))
let model = MentorSessionModel(binaryPath: fake)
// strictMcp: session/new without mcpServers → -32602 (the ACP SDK's
// required field, adapter ≥0.21.5); Museion ships [] and reaches ready.
let engines = ScriptedEngines(mode: "strictMcp")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
guard case .ready = model.phase else {
@@ -695,9 +627,8 @@ struct ACPClientTests {
@MainActor
@Test func `model crash surfaces restart prompt and fresh engine recovers`() async throws {
let dir = acpTempDir("restart")
let crashing = makeFakeACP(at: dir, name: "hermes-acp-crash", mode: "crashAfterHandshake")
let model = MentorSessionModel(binaryPath: crashing)
let engines = ScriptedEngines(mode: "crashAfterHandshake")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
for _ in 0 ..< 100 {
@@ -710,14 +641,12 @@ struct ACPClientTests {
Issue.record("expected crashed after engine exit, got \(model.phase)")
return
}
// A fresh model against a healthy fake at a different path stands in for
// restart recovery (the pane's Restart button drives model.restart()).
let healthy = makeFakeACP(at: dir, name: "hermes-acp-ok")
let model2 = MentorSessionModel(binaryPath: healthy)
defer { model2.shutdown() }
await model2.openSession()
guard case .ready = model2.phase else {
Issue.record("expected ready on healthy engine, got \(model2.phase)")
// Recovery now drives the pane's own Restart rail: a healthy engine is
// spawned in place (the rig's mode flip replaces the second fake).
engines.mode = "full"
await model.restart()
guard case .ready = model.phase else {
Issue.record("expected ready after restart, got \(model.phase); stderr: \(model.stderrTail)")
return
}
}