test(mentor): cancel-ack fake + deferred teardown
CI / ci (push) Canceled after 0s

The fake ACP engine's hangOnPrompt mode slept oblivious to
session/cancel, so a cancelled turn was only observable through
teardown and the pass bar's Cancel rail was never individually
discriminated. hangOnPrompt now holds the turn reading: session/cancel
answers the hanging prompt with stopReason "cancelled" (the real
engine's contract); stdin EOF without a cancel answers end_turn so
the child exits.

New pin 'cancelling a held pass ends the turn cancelled with no
advance' (RED->GREEN; bounded polls, so an emptied cancelPass fails
the pin instead of hanging the suite). Every fake-spawning test (27
rigs across ACPClientTests + PassRunTests) tears down via defer at
rig creation — a cancelled or interrupted test cannot leak the child;
trailing happy-path teardowns removed, mechanism/bound teardowns kept
and commented. Harness docs updated to match; 316 tests green.

Closes #124
This commit is contained in:
AlexKucera committed 2026-10-20 19:35:17 +02:00
1 parent 4d33676a08
commit 154bb8a114
6 files changed
+191 -34

No files matched your search

+50 -20
View File
@@ -7,23 +7,37 @@
// 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
// "cancelled") — a sleep-oblivious hold can't pin the Cancel rail.
//
// swiftlint:disable file_length
// One file: the shared fake harness (makeFakeACP/acpTempDir — other test
// files build rigs on it) + the client/model suites that pin its contract.
import Foundation
@testable import Museion
import Testing
// MARK: - Fake ACP server + helpers
// swiftlint:disable function_body_length
/// Builds a fake engine binary that speaks enough ACP for the M0 client.
/// `mode`: `full` answers everything; `crashAfterHandshake` exits 1 right
/// after answering initialize; `hangOnPrompt` sleeps 30 s inside prompt;
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled";
/// `refuseOnPrompt` answers stopReason "refusal" (no chunks).
/// after answering initialize; `hangOnPrompt` streams, then HOLDS the turn
/// open reading — session/cancel answers the hanging prompt with stopReason
/// "cancelled" (the real engine's contract, #124), stdin EOF without a
/// cancel (teardown) answers end_turn, and during the hold ONLY
/// session/cancel is answered — any other request waits until teardown;
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled"
/// with no cancel needed; `refuseOnPrompt` answers stopReason "refusal" (no
/// chunks).
/// The mode travels in a file next to the fake (self-locating — race-free
/// under parallel suites, same convention as ProfileProvisionerTests).
/// The fix-card payload travels base64-encoded so shell quoting can't break.
/// Internal (not private) so later test files can reuse the fake (#24).
/// One contiguous zsh program — splitting the script string would break the
/// wire-line inspectability the script's own comment pins.
func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "full") -> String {
let path = (dir as NSString).appendingPathComponent(name)
let modeFile = (dir as NSString).appendingPathComponent("\(name)-mode")
@@ -65,7 +79,18 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}'
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
if [[ "$mode" == "hangOnPrompt" ]]; then
sleep 30
# #124: the cancel-acknowledging hold — the real engine answers its
# hanging prompt with stopReason "cancelled" the moment session/cancel
# arrives; a sleep-oblivious fake can't pin the Cancel rail. EOF with
# no cancel (teardown closed stdin) ends the turn so the child exits.
while IFS= read -r held; do
[[ -z "$held" ]] && continue
hm=$(print -r -- "$held" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
if [[ "$hm" == "session/cancel" ]]; then
echo $framing"$rid",'"result":{"stopReason":"cancelled"}}'
continue 2
fi
done
fi
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
elif [[ "$method" == "session/cancel" ]]; then
@@ -81,6 +106,8 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
return path
}
// 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;
@@ -139,19 +166,20 @@ 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")]),
]))
client.close()
#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.
@@ -160,15 +188,15 @@ struct ACPClientTests {
_ = try? await client.request("initialize", params: nil)
try? await Task.sleep(for: .milliseconds(500))
}
client.close()
}
@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")]))
// Prompt hangs (sleep 30) — drive it in the background, then cancel.
// 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")])]),
@@ -176,7 +204,7 @@ struct ACPClientTests {
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() // also resumes the hung prompt task with an error
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.
@@ -186,6 +214,7 @@ struct ACPClientTests {
@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([
@@ -215,6 +244,7 @@ struct ACPClientTests {
@Test func `sendPrompt returns ended end_turn and streams text`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-ended"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
@@ -225,13 +255,13 @@ struct ACPClientTests {
return false
}
#expect(streamed)
model.shutdown()
}
@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)
defer { model.shutdown() }
await model.openSession()
// The pass orchestrator sends a long wire stub; only the label may land.
await model.sendPrompt("STUB-WIRE-PROMPT that must never surface", label: "Pass 1 · My Post")
@@ -243,17 +273,16 @@ struct ACPClientTests {
}
#expect(texts.contains("Pass 1 · My Post"))
#expect(!texts.contains { $0.contains("STUB-WIRE-PROMPT") })
model.shutdown()
}
@MainActor
@Test func `cancelled stopReason maps to TurnOutcome cancelled`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-cancel"), mode: "cancelOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .cancelled)
model.shutdown()
}
/// Review pin: a prompt response without stopReason is NOT a completed
@@ -262,10 +291,10 @@ struct ACPClientTests {
@Test func `missing stopReason maps to failed`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-nostop"), mode: "noStopReason")
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .failed)
model.shutdown()
}
/// #23 dogfood regression pin: session/prompt's response arrives when the
@@ -291,6 +320,7 @@ struct ACPClientTests {
@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)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "refusal"))
@@ -301,13 +331,13 @@ struct ACPClientTests {
return false
}
#expect(refused)
model.shutdown()
}
@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)
defer { model.shutdown() }
await model.openSession()
// The fake streams a thought chunk BEFORE the message chunks — the
// live shape of a pass turn (long thinking, then the critique).
@@ -334,13 +364,13 @@ struct ACPClientTests {
}
return false
})
model.shutdown()
}
@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)
defer { model.shutdown() }
await model.openSession()
// Deterministic transport failure through the model: hangOnPrompt keeps
// the turn pending, then shutdown() closes the client — the in-flight
@@ -363,6 +393,7 @@ struct ACPClientTests {
@Test func `model handshake renders version and streams fix card`() async {
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
await model.openSession()
guard case let .ready(sessionId) = model.phase else {
Issue.record("expected ready, got \(model.phase)")
@@ -385,13 +416,13 @@ struct ACPClientTests {
return false
}
#expect(hasText)
model.shutdown()
}
@MainActor
@Test func `model surfaces advisory version drift note`() async {
let fake = makeFakeACP(at: acpTempDir("drift"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
// Running 9.9.9 vs recorded 0.20.6 → the advisory note fires, never blocks.
model.recordedVersionProvider = { "0.20.6" }
await model.openSession()
@@ -401,13 +432,13 @@ struct ACPClientTests {
}
#expect(model.versionNote?.contains("9.9.9") == true)
#expect(model.versionNote?.contains("0.20.6") == true)
model.shutdown()
}
@MainActor
@Test func `build metadata does not fabricate version drift`() async {
let fake = makeFakeACP(at: acpTempDir("metadata-drift"))
let model = MentorSessionModel(binaryPath: fake)
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" }
@@ -417,7 +448,6 @@ struct ACPClientTests {
return
}
#expect(model.versionNote == nil)
model.shutdown()
}
@MainActor
@@ -432,13 +462,13 @@ struct ACPClientTests {
@Test func `session new against strict mcpServers schema reaches ready`() async {
let fake = makeStrictFakeACP(at: acpTempDir("strict"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
guard case let .ready(sessionId) = model.phase else {
Issue.record("expected ready against strict engine, got \(model.phase); stderr: \(model.stderrTail)")
return
}
#expect(sessionId == "sess-1")
model.shutdown()
}
@MainActor
@@ -446,6 +476,7 @@ struct ACPClientTests {
let dir = acpTempDir("restart")
let crashing = makeFakeACP(at: dir, name: "hermes-acp-crash", mode: "crashAfterHandshake")
let model = MentorSessionModel(binaryPath: crashing)
defer { model.shutdown() }
await model.openSession()
for _ in 0 ..< 100 {
if case .crashed = model.phase {
@@ -461,11 +492,10 @@ struct ACPClientTests {
// 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)")
return
}
model.shutdown()
model2.shutdown()
}