Files
museion/MuseionTests/ACPClientTests.swift
AlexKucera 33b7fe0f9f
CI / ci (push) Canceled after 0s
test(acp): pin blocked-writer backpressure regressions
RED at base for the acp-backpressure finding: on the unfixed
transport a hung engine that stops reading stdin fills its pipe,
and the synchronous send wedges the client's one serial queue —
the request deadline never fires, follow-up bookkeeping starves,
and close() blocks behind the stuck write (argus probe: 2M-char
request, 0.1 s timeout, watchdog close never returned).

Three smokes over the existing rig, using a new neverRead fake
mode (execs /bin/sleep — the probe's inert non-reading child;
never a real profile): deadline fires while blocked, Stop +
bookkeeping answer while blocked, close returns bounded and reaps
the child. A fourth smoke (new serverPing fake mode) pins the
healthy contract — round trip, -32601 reply delivery over the
wire, idempotent clean close — and passes at base.

Focused serialized run at base: 6 executed / 3 passed / 3 failed
— exactly the three blocked-writer smokes fail, on mechanism.
2026-11-17 22:26:05 +01:00

670 lines
30 KiB
Swift

//
// ACPClientTests.swift
// MuseionTests
//
// 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.
//
// 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 SwiftUI
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` 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); `loadReplay` (#28) adds the lifecycle wire: session/new/load/fork
/// all require `mcpServers` (-32602 without, the #44 invariant), session ids
/// are minted uniquely (sess-1, sess-2, …), session/load replays
/// user+thought+message chunks PLUS one submit_research_notes tool call
/// (#29 — candidates re-materialize on resume) for ANY minted sess-* id
/// then answers its id
/// (a relaunch default-open resumes the newest rostered entry, #28 review
/// fix; any other id answers with NO sessionId = unknown), and session/fork
/// of sess-1 returns a fresh F-<n> (any other source id returns ""). load/fork
/// log "load <id>" / "fork <id>" to stderr so tests can pin the wire call.
/// Mode `loadReplayHold` = loadReplay with session/load PARKED (after a
/// "hold-load" stderr line) until a `load-go` file lands beside the fake —
/// the finish-audit interleaving pin's in-flight observable.
/// Mode `neverRead` (brief-27): execs /bin/sleep 30 without reading one
/// line — the inert non-reading child of the backpressure smokes (the
/// pipe fills, the client's writer blocks; the finding's probe shape).
/// Mode `serverPing` (brief-27): full behaviour PLUS one server→client
/// request (id 900) emitted at initialize — the client must answer -32601
/// over the wire; the fake logs our reply line to `<name>-reply-log`
/// (the reply-delivery pin).
/// 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.
/// Every spawn appends its argv line to `<name>-spawn-log` beside the fake
/// (#137) — the "which engine (profile) ran" observable.
/// 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")
let fixCardB64 = fixCardPayloadB64()
let researchB64 = researchPayloadB64()
// ponytail: one echo per wire message — long payloads ride shell vars so
// each line stays under the lint cap and inspectable against the schema.
let script = """
#!/bin/zsh
mode="full"
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
print -- "$@" >> "${0:h}/\(name)-spawn-log" # #137: every spawn's argv — tests pin which engine (profile) ran
if [[ "$mode" == "neverRead" ]]; then
# brief-27: /bin/sleep never reads stdin — the pipe fills and the client's writer blocks.
# exec keeps sleep the DIRECT child (close SIGTERMs it; no orphan holds the pipe open).
exec /bin/sleep 30
fi
card=$(print -- '\(fixCardB64)' | base64 -d)
research=$(print -- '\(researchB64)' | base64 -d)
researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d)
framing='{"jsonrpc":"2.0","id":'
sessn=0
forkn=0
mcpcheck='import json,sys; print("1" if "mcpServers" in json.load(sys.stdin).get("params",{}) else "0")'
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \\n escapes of multi-line prompts
[[ -z "$line" ]] && continue
method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
if [[ "$mode" == "serverPing" && "$rid" == "900" && -z "$method" ]]; then
print -r -- "$line" >> "${0:h}/\(name)-reply-log" # brief-27: the client's -32601 reply to our server request, on the wire
continue
fi
if [[ "$method" == "initialize" ]]; then
[[ "$mode" == "serverPing" ]] && echo '{"jsonrpc":"2.0","id":900,"method":"client/ping"}'
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
[[ "$mode" == "crashAfterHandshake" ]] && exit 1
elif [[ "$method" == "session/new" ]]; then
if [[ "$mode" == "loadReplay" ]]; then # #44 invariant: mcpServers required
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
if [[ "$ok" == "0" ]]; then
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
continue
fi
fi
sessn=$((sessn+1)) # #28: unique id per new — multi-session rosters need distinct ids
echo $framing"$rid",'"result":{"sessionId":"sess-'"$sessn"'"}}'
elif [[ "$method" == "session/prompt" ]]; then
print -r -- "$line" >> "${0:h}/\(name)-prompt-log" # every prompt's wire line — tests pin what the engine was asked (#122)
psid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$psid"'","update":'
if [[ "$mode" == "refuseOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"refusal"}}'
continue
fi
echo $notify'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"echo"},"messageId":"u1"}}}'
echo $notify'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"weighing the structure"},"messageId":"t1"}}}'
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello "},"messageId":"m1"}}}'
if [[ "$mode" == "cancelOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"cancelled"}}'
continue
fi
if [[ "$mode" == "noStopReason" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
continue
fi
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}'
if [[ "$mode" == "strayResearchOnPrompt" ]]; then
# #29 audit pin: a research payload carrying stray fix-card keys at
# the top level must route by shape (notes array), not vanish into
# a card row.
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_research_notes","rawInput":'"$researchstray"'}}}'
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
continue
fi
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
if [[ "$mode" == "hangOnPrompt" ]]; then
# #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/load" ]]; then
if [[ "$mode" != loadReplay* ]]; then continue; fi
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
if [[ "$ok" == "0" ]]; then
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
continue
fi
lsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
print -u2 -- "load $lsid" # the wire call, visible in model.stderrTail
if [[ "$mode" == "loadReplayHold" ]]; then
# Finish-audit pin support: park the replay until `load-go` lands
# beside the fake; the pre-hold stderr line above is the observable
# that the load (and the model's replay slot) is in flight.
print -u2 -- "hold-load"
while [[ ! -f "${0:h}/load-go" ]]; do sleep 0.05; done
fi
# Any MINTED id replays: a relaunch default-open resumes the newest
# rostered session (review fix), so load answers every id session/new
# ever issued, not one planted id.
rnot='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$lsid"'","update":'
if [[ "$lsid" == sess-* ]]; then
# Full history replay, wire order, BEFORE the load response — the
# real adapter's contract (#28). The load RESPONSE carries NO
# top-level sessionId (0.21.5 live-verified, #30 dogfood): the id
# rides _meta.hermes.sessionProvenance.acpSessionId — resuming a
# minted id must ACCEPT this shape; an empty result stays the
# unknown-refusal.
echo $rnot'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"earlier ask"}}}}'
echo $rnot'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"old thinking"}}}}'
echo $rnot'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"earlier verdict"}}}}'
echo $rnot'{"sessionUpdate":"tool_call","toolCallId":"tc2","title":"submit_research_notes","rawInput":'"$research"'}}}'
if [[ "$mode" == "loadReplayLegacy" ]]; then
# #30 audit knob: the OLDER contract - top-level sessionId, no
# provenance. resumeSession must accept BOTH shapes.
echo $framing"$rid\",'\"result\":{\"sessionId\":\"'"$lsid"'\"}}'
continue
fi
echo $framing"$rid\",'\"result\":{\"modes\":[],\"_meta\":{\"hermes\":{\"sessionProvenance\":{\"acpSessionId\":\"'\"$lsid\"'\"}}}}}'
else
echo $framing"$rid",'"result":{}}' # unknown session — no sessionId
fi
elif [[ "$method" == "session/fork" ]]; then
if [[ "$mode" != "loadReplay" ]]; then continue; fi
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
if [[ "$ok" == "0" ]]; then
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
continue
fi
fsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
print -u2 -- "fork $fsid"
if [[ "$fsid" == "sess-1" ]]; then
forkn=$((forkn+1))
echo $framing"$rid",'"result":{"sessionId":"F-'"$forkn"'"}}'
else
echo $framing"$rid",'"result":{"sessionId":""}}' # empty = fork refused
fi
elif [[ "$method" == "session/cancel" ]]; then
print -u2 -- "cancel received"
fi
done
exit 0
"""
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
try? mode.write(toFile: modeFile, atomically: true, encoding: .utf8)
try? script.write(toFile: path, atomically: true, encoding: .utf8)
_ = try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path)
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 JSON itself lives in
/// ScriptedPayloads (#178) — the scripted engine ships the identical bytes.
private func fixCardPayloadB64() -> String {
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.
private func researchPayloadB64() -> String {
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 {
Data(ScriptedPayloads.strayResearchJSON.utf8).base64EncodedString()
}
func acpTempDir(_ label: String) -> String {
let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)"
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
return dir
}
// 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 {
/// 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
engine.onCrash = { crashed() }
_ = try? await engine.request("initialize", params: nil, timeout: 15)
}
#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"))
}
}
// MARK: - Turn outcome seam (#24 S3.1: sendPrompt → TurnOutcome)
// The suite hosts these model tests (not free functions like the model
// tests below) so the suite-name test filter runs them.
@MainActor
@Test func `sendPrompt returns ended end_turn and streams text`() async {
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let streamed = model.rows.contains { row in
if case let .text(text, _, _) = row.content {
return text.contains("Hello mentor.")
}
return false
}
#expect(streamed)
}
@MainActor
@Test func `labeled prompt renders the label not the wire stub`() async {
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.
await model.sendPrompt("STUB-WIRE-PROMPT that must never surface", label: "Pass 1 · My Post")
var texts: [String] = []
for row in model.rows {
if case let .text(text, _, _) = row.content {
texts.append(text)
}
}
#expect(texts.contains("Pass 1 · My Post"))
#expect(!texts.contains { $0.contains("STUB-WIRE-PROMPT") })
}
@MainActor
@Test func `cancelled stopReason maps to TurnOutcome cancelled`() async {
let engines = ScriptedEngines(mode: "cancelOnPrompt")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .cancelled)
}
/// Review pin: a prompt response without stopReason is NOT a completed
/// turn — .failed, so a pass never advances on a maybe.
@MainActor
@Test func `missing stopReason maps to failed`() async {
let engines = ScriptedEngines(mode: "noStopReason")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .failed)
}
/// #23 dogfood regression pin: session/prompt's response arrives when the
/// TURN ends — minutes into a pass. The client's 15 s request default
/// abandoned live turns ("connection lost" while the engine kept working,
/// Stop vanished with isStreaming). sendPrompt must wait pass-length.
@Test func `prompt deadline is pass length not the request default`() {
#expect(MentorSessionModel.promptTimeout >= 600)
}
/// #23 dogfood: the writing-session filter — prose + card events stay,
/// raw session/tool rows and thinking are debug-only.
@Test func `writing-session filter keeps prose and cards, hides raw and thought`() {
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece", .system, .plain))))
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .fixCard(
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
))))
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .thought("thinking…"))))
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
}
/// Round-6 ui-polish (all seats): the warning row's headline/detail
/// split — the first ": " separates the headline from the muted detail
/// line (no ": " → headline only). #177 (S2): bodies arrive unprefixed.
@Test func `warningParts splits headline from detail`() {
let interrupted = SessionTranscriptView.warningParts(
"Operation interrupted: waiting for model response (61.6s elapsed).",
)
#expect(interrupted.headline == "Operation interrupted")
#expect(interrupted.detail == "waiting for model response (61.6s elapsed).")
let lost = SessionTranscriptView.warningParts("connection lost")
#expect(lost.headline == "connection lost")
#expect(lost.detail == nil)
}
/// #177 (S2): the kick-off pill's display text — first line only, the
/// doubled "Pass Pass N" collapsed to "Pass N". Precondition: the body
/// of a .kickoff row (the append seam already sniffed it — the prefix
/// is unconditional here).
@Test func `kickoffDisplayText collapses to first line`() {
#expect(SessionTranscriptView.kickoffDisplayText("Pass Pass 2 — deep.\nThe full prompt never renders.") == "Pass 2 — deep.")
}
/// Round-8 ui-polish (argon#8 — calm copy): the engine's own
/// interruption detail, rephrased verbatim-safe — only the known
/// "waiting for model response (X elapsed)" phrasing rewrites; any
/// other detail passes through untouched (no invented states).
@Test func `calmDetail rephrases only the engine's known phrasing`() {
#expect(SessionTranscriptView.calmDetail("waiting for model response (61.6s elapsed).")
== "waiting on the model — 61.6s")
#expect(SessionTranscriptView.calmDetail("waiting for model response (2m 10s elapsed)")
== "waiting on the model — 2m 10s")
#expect(SessionTranscriptView.calmDetail("the engine process exited")
== "the engine process exited")
#expect(SessionTranscriptView.calmDetail("waiting for model response ( elapsed)")
== "waiting for model response ( elapsed)")
}
/// #155 audit (security): the link-open gate — interpreted markdown
/// opens http(s) only; every other scheme (file:, mailto:, custom app
/// schemes) is discarded. Engine prose echoes imported content, so a
/// lying `[label](scheme:…)` link must never reach a handler.
@Test func `linkVerdict discards non-http schemes from interpreted markdown`() throws {
#expect(try SessionTranscriptView.linkVerdict(for: #require(URL(string: "https://mentor.dev/critique"))) == .open)
#expect(try SessionTranscriptView.linkVerdict(for: #require(URL(string: "http://mentor.dev/critique"))) == .open)
// Scheme matching is case-insensitive on the wire.
#expect(try SessionTranscriptView.linkVerdict(for: #require(URL(string: "HTTPS://MENTOR.DEV/x"))) == .open)
for scheme in ["file:///etc/passwd", "mailto:x@y.dev", "notesapp://open", "javascript:alert(1)"] {
#expect(try SessionTranscriptView.linkVerdict(for: #require(URL(string: scheme))) == .discard, "\(scheme) should be discarded")
}
}
/// #155 audit: the Return split — Caps Lock must not turn Shift+Return
/// into a send (an exact `==` did).
@Test func `returnIntent masks caps lock and splits plain vs shift return`() {
#expect(SessionTranscriptView.returnIntent(for: []) == .send)
#expect(SessionTranscriptView.returnIntent(for: .shift) == .lineBreak)
#expect(SessionTranscriptView.returnIntent(for: [.shift, .capsLock]) == .lineBreak)
#expect(SessionTranscriptView.returnIntent(for: .capsLock) == .send)
#expect(SessionTranscriptView.returnIntent(for: .option) == .passthrough)
#expect(SessionTranscriptView.returnIntent(for: [.command]) == .passthrough)
}
@MainActor
@Test func `refusal maps to ended refusal and still renders the refusal row`() async {
let engines = ScriptedEngines(mode: "refuseOnPrompt")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "refusal"))
let refused = model.rows.contains { row in
if case let .text(text, _, _) = row.content {
return text.contains("(refused the prompt)")
}
return false
}
#expect(refused)
}
/// #29 audit pin: a research payload with stray fix-card keys routes by
/// SHAPE (the notes array) — it renders candidates, never a card row.
/// Title-based routing would also work on the fake but titles are
/// display text; the payload is the contract.
@MainActor
@Test func `research payload with stray card keys renders candidates not a card`() async {
let engines = ScriptedEngines(mode: "strayResearchOnPrompt")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("research this")
guard case .ended = outcome else {
Issue.record("turn did not end: \(outcome)")
return
}
var hasCandidates = false
var hasCard = false
for _ in 0 ..< 250 {
hasCandidates = model.rows.contains {
if case .researchNote = $0.content {
return true
}; return false
}
hasCard = model.rows.contains {
if case .fixCard = $0.content {
return true
}; return false
}
if hasCandidates {
break
}
try? await Task.sleep(nanoseconds: 20_000_000)
}
#expect(hasCandidates, "the stray-key research batch never rendered as candidates")
#expect(!hasCard, "the research payload was swallowed by the fix-card parser")
}
@MainActor
@Test func `thought chunks land in a collapsed thought row not the critique`() async {
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
// 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"))
let thought = model.rows.contains { row in
if case let .thought(text) = row.content {
return text == "weighing the structure"
}
return false
}
#expect(thought)
// The critique text stays clean — thinking never bleeds into it.
let critique = model.rows.contains { row in
if case let .text(text, _, _) = row.content {
return text == "Hello mentor."
}
return false
}
#expect(critique)
#expect(!model.rows.contains { row in
if case let .text(text, _, _) = row.content {
return text.contains("weighing")
}
return false
})
}
@MainActor
@Test func `transport failure mid-turn maps to TurnOutcome failed`() async throws {
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 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.
let promptTask = Task { await model.sendPrompt("hello mentor") }
for _ in 0 ..< 100 where !model.isStreaming {
try await Task.sleep(for: .milliseconds(50))
}
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 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)")
return
}
#expect(model.activeEntry?.sessionId == "sess-1")
#expect(model.engineVersion == "9.9.9")
await model.sendPrompt("hello mentor")
// 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
if case let .fixCard(card) = row.content {
return card.pattern == "Blame tense"
}
return false
}
if !hasCard {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
#expect(hasCard)
let hasText = model.rows.contains { row in
if case let .text(text, _, _) = row.content {
return text.contains("Hello mentor.")
}
return false
}
#expect(hasText)
}
@MainActor
@Test func `model surfaces advisory version drift note`() async {
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.host.recordedVersionProvider = { "0.20.6" }
await model.openSession()
guard case .ready = model.phase else {
Issue.record("expected ready despite drift, got \(model.phase)")
return
}
#expect(model.versionNote?.contains("9.9.9") == true)
#expect(model.versionNote?.contains("0.20.6") == true)
}
@MainActor
@Test func `build metadata does not fabricate version drift`() async {
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.host.recordedVersionProvider = { "9.9.9+2177.g735e426" }
await model.openSession()
guard case .ready = model.phase else {
Issue.record("expected ready, got \(model.phase)")
return
}
#expect(model.versionNote == nil)
}
@MainActor
@Test func `real base-version drift still fires the note`() {
#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 {
// 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 {
Issue.record("expected ready against strict engine, got \(model.phase); stderr: \(model.stderrTail)")
return
}
#expect(model.activeEntry?.sessionId == "sess-1")
}
@MainActor
@Test func `model crash surfaces restart prompt and fresh engine recovers`() async throws {
let engines = ScriptedEngines(mode: "crashAfterHandshake")
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
for _ in 0 ..< 100 {
if case .crashed = model.phase {
break
}
try await Task.sleep(for: .milliseconds(50))
}
guard case .crashed = model.phase else {
Issue.record("expected crashed after engine exit, got \(model.phase)")
return
}
// 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
}
}