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
}
}
+5 -3
View File
@@ -22,14 +22,16 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- One runnable check per non-trivial fact: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
- Never touch the real machine: throwaway Homes in temp dirs (`makeHome`, `storeHome`, `makeModelHome`, `makeSessionHome`, `importHome`); every `ProfileProvisioner.perform` call injects `masterRoot` (the default writes the REAL Application Support); keychain tests inject their OWN account slot (a live production token is never read, replaced, or deleted); roster/defaults under hosted tests redirect to temp or assert `.standard` byte-unchanged; `psScan` is stubbed (a dev machine may run the real engine).
- Shared helpers are `internal` in the founding file. When a suite crosses a file-length or type-body ceiling, split the new pins into their own file and keep the helpers where they are (PostStorePassTests, MicropubModelTests, MCPToolsPromoteTests, SettingsModelWritePathTests precedents).
- Fake child processes (the fake `hermes` CLI, the fake ACP zsh server) speak the live-probed wire shapes over the real `Process` path; payloads ride base64 so shell quoting can never break the wire JSON; every spawn appends to `<name>-spawn-log` and every `session/prompt` to `<name>-prompt-log` (the which-engine-ran / what-it-was-asked observables). Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent).
- Engine tests run IN-PROCESS at the `EngineTransport` seam (#178): `ScriptedEngine.swift` holds the scripted adapter (mode strings mirroring the retired zsh fake: full/crashAfterHandshake/hangOnPrompt/cancelOnPrompt/refuseOnPrompt/noStopReason/strayResearchOnPrompt/loadReplay*/strictMcp), the shared payloads (`ScriptedPayloads`), and the rig roots — build rigs there, never duplicate. Spawn observables: the rig's spawned-profiles record (which engine ran), transport identity (`mentor.host.chat`/`oneShot`) where pid pins used to live, `isClosed` for reaped. Child processes appear in EXACTLY ONE suite — `EngineSmokeTests`, one real-process wire smoke per LLM Surface (chat/pass1/pass2, ADR-0014) over the zsh fake (`makeFakeACP`/`acpTempDir`, defined in ACPClientTests.swift, kept as the wire fixture). The fake-`hermes` CLI harness (ProfileProvisioner/Backup suites) still speaks real `Process` with base64 payloads, `<name>-spawn-log`, `<name>-prompt-log`, and `defer` teardown at rig creation.
- Waiting: bounded poll loops, each arming its OWN deadline; poll for the watcher rescan after disk writes. Lock/goal machine tests pass `spawnsTicker: false` — the real 1 s ticker could complete a met goal before an injected tick (the #30/#147 flake family).
- Suite-name filters (`-only-testing:MuseionTests/<Suite>`) do not run free functions — pin things as suite members.
### Suite map
- `EngineGateTests`, `GatelessLaunchTests` — engine probe; gateless launch seam, status-pill and header state mappings.
- `ACPClientTests` — fake ACP server + client wire contract (handshake, streaming, thought lane, crash, cancel, teardown; `makeFakeACP` helpers shared repo-wide).
- `ACPClientTests` — turn-outcome seam + view predicates over the scripted engine (#178: the client wire contract itself lives in EngineSmokeTests; `makeFakeACP`/`acpTempDir` remain here as the shared wire fixture).
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on.
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched).
- `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness).
- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests` — scan, write side, pass substrate, stats capture, research notes.
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
@@ -37,7 +39,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay.
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle.
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration: passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the fake ACP, prefix-free invariant, append-seam classifiers).
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers).
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import + image ingest.
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
+21 -38
View File
@@ -3,7 +3,9 @@
// MuseionTests
//
// #122: the Blind Read — a writer-triggered, whole-document A/B judgment
// (advisory). From user story #122 / decision #120.
// (advisory). From user story #122 / decision #120. #178: the advisory
// run rides the in-process ScriptedEngines rig — the rig's spawnedProfiles
// pin which engine judged, the engines' promptLog pins what it was asked.
//
// ## Scenario: the blind judge prompt
// Given a Pass-start snapshot and the current document
@@ -109,17 +111,6 @@ struct BlindReadTests {
// MARK: Scenario 3 — the advisory run (mentor rail)
/// makePassRig + the fake's directory (the spawn/prompt logs live
/// beside the fake — makePassRig doesn't expose it).
// swiftlint:disable:next large_tuple
private func makeBlindRig(mode: String = "full") throws -> (model: PostsModel, home: URL, mentor: MentorSessionModel, fakeDir: String) {
let (model, home) = try makeModelHome()
let dir = acpTempDir("blindread")
let fake = makeFakeACP(at: dir, mode: mode)
let mentor = MentorSessionModel(binaryPath: fake)
return (model, home, mentor, dir)
}
/// Open a piece with a planted snapshot and a differing buffer — the
/// blind read's given state. Returns the piece id.
@discardableResult
@@ -133,13 +124,14 @@ struct BlindReadTests {
return post.id
}
// swiftlint:disable:next large_tuple
private func spawnLog(_ rig: (model: PostsModel, home: URL, mentor: MentorSessionModel, fakeDir: String)) throws -> String {
try String(contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-spawn-log"), encoding: .utf8)
/// How many `museion` (chat-profile) engines spawned — the fresh-judge
/// pin's countable (was: grep of the fake's spawn log).
private func museionSpawns(_ rig: ScriptedRig) -> Int {
rig.engines.spawnedProfiles.filter { $0 == "museion" }.count
}
@Test func `blind read judges on a fresh chat-profile engine never rostered`() async throws {
let rig = try makeBlindRig()
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
@@ -159,18 +151,12 @@ struct BlindReadTests {
#expect(rig.mentor.roster.count == rosterBefore)
// A fresh CHAT-profile engine judged (the resident engine is the
// only other `museion` spawn; pass profiles never ran).
let spawns = try spawnLog(rig)
#expect(spawns.components(separatedBy: "\n").filter { $0.contains("acp -p museion") }.count == 2)
#expect(!containsPassProfile(spawns))
}
/// Non-`museion` (pass-profile) spawns — negation helper.
private func containsPassProfile(_ spawns: String) -> Bool {
spawns.components(separatedBy: "\n").contains { $0.contains("museion-pass") }
#expect(museionSpawns(rig) == 2)
#expect(!rig.engines.spawnedProfiles.contains { $0.contains("museion-pass") })
}
@Test func `cancelled blind read leaves no reveal`() async throws {
let rig = try makeBlindRig(mode: "cancelOnPrompt")
let rig = try makeScriptedRig(mode: "cancelOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
@@ -188,7 +174,7 @@ struct BlindReadTests {
// MARK: Audit pins (finish-audit: the refusal gate + the Cancel rail)
@Test func `refused blind read reveals nothing`() async throws {
let rig = try makeBlindRig(mode: "refuseOnPrompt")
let rig = try makeScriptedRig(mode: "refuseOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
@@ -208,7 +194,7 @@ struct BlindReadTests {
}
@Test func `cancel ends a held blind read and the rail is exclusive`() async throws {
let rig = try makeBlindRig(mode: "hangOnPrompt")
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
@@ -243,7 +229,7 @@ struct BlindReadTests {
// MARK: Scenario 3 (model half) — the advisory orchestration
@Test func `blind read sends both bodies blind and records nothing`() async throws {
let rig = try makeBlindRig()
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(
@@ -254,14 +240,11 @@ struct BlindReadTests {
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
// The prompt carried BOTH bodies inline — and no path: the judge
// cannot learn which file is which.
let promptLog = try String(
contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-prompt-log"),
encoding: .utf8,
)
#expect(promptLog.contains("MARKER-the-older-text"))
#expect(promptLog.contains("MARKER-the-newer-text"))
#expect(!promptLog.contains(".md"))
// cannot learn which file is which (the engines' prompt log).
let asked = rig.engines.engines.flatMap(\.promptLog).map(\.text).joined()
#expect(asked.contains("MARKER-the-older-text"))
#expect(asked.contains("MARKER-the-newer-text"))
#expect(!asked.contains(".md"))
// The reveal landed below the verdict.
#expect(textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
// Records nothing: Pass State untouched, rail idle, no error.
@@ -275,7 +258,7 @@ struct BlindReadTests {
}
@Test func `blind read refuses without a snapshot or without edits`() async throws {
let rig = try makeBlindRig()
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let post = try PostStore.writeNew(body: "# Fresh\n\nNo pass yet.", home: rig.home)
@@ -287,7 +270,7 @@ struct BlindReadTests {
// No pass ever ran — refuse, spawn nothing beyond the resident engine.
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("run a Pass") == true)
#expect(try spawnLog(rig).components(separatedBy: "\n").filter { $0.contains("acp -p museion") }.count == 1)
#expect(museionSpawns(rig) == 1)
// Snapshot exists but the document is unchanged since — a vacuous
// read refuses honestly.
+76 -106
View File
@@ -6,39 +6,33 @@
// own ONE-SHOT engines (spawned per run on the pass profile, torn down at
// the verdict, never rostered per #129) and the Chat model-change restart
// posture (restart in place when idle, defer to turn end while streaming).
// Real client + fake ACP path; the fake's spawn log pins WHICH engine ran.
// #178: runs IN-PROCESS over ScriptedEngines rigs at the EngineTransport
// seam — the rig's spawnedProfiles pin WHICH engine ran; pid pins became
// transport-identity/closed pins (host.chat/host.oneShot identity +
// ScriptedEngine.isClosed).
//
import Foundation
@testable import Museion
import Testing
/// makePassRig's shape plus the fake's directory — the spawn log beside
/// the fake is the "which engine (profile) spawned" observable (#137).
/// Poll for the pass engine's transport while the run is in flight —
/// host.oneShot is only observable mid-run (the host nils it at teardown).
/// For HELD passes only: a full-mode scripted pass can complete inside a
/// single 20 ms poll sleep, so completed runs capture via spawnedProfiles.
@MainActor
private struct EngineRig {
let model: PostsModel
let home: URL
let mentor: MentorSessionModel
let fakeDir: String
}
@MainActor
private func makeEngineRig(mode: String = "full") throws -> EngineRig {
let (model, home) = try makeModelHome()
let dir = acpTempDir("engine-lifecycle")
let fake = makeFakeACP(at: dir, mode: mode)
return EngineRig(model: model, home: home, mentor: MentorSessionModel(binaryPath: fake), fakeDir: dir)
}
/// Bounded poll until a child is reaped (kill(pid, 0) fails) — the house
/// 250×20 ms pattern, 100 rounds for a close() that reaps synchronously.
@MainActor
private func pollReaped(_ pid: pid_t) async throws -> Bool {
for _ in 0 ..< 100 where kill(pid, 0) == 0 {
try await Task.sleep(nanoseconds: 20_000_000)
private func pollOneShot(of mentor: MentorSessionModel) async throws -> ScriptedEngine? {
var engine: ScriptedEngine?
var polls = 0
while engine == nil, polls < 250 {
if let transport = mentor.host.oneShot, let scripted = transport as? ScriptedEngine {
engine = scripted
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
return kill(pid, 0) != 0
return engine
}
// Scenario: A pass run lives on its own engine
@@ -51,10 +45,10 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
// engine keeps running untouched.
@Test @MainActor func `a pass run lives on its own engine and rosters nothing`() async throws {
let rig = try makeEngineRig()
defer { rig.mentor.shutdown() } // #124: at rig creation — the children die with the test
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let chatPid = try #require(rig.mentor.childProcessIdentifier)
let chatBefore = rig.mentor.host.chat
let rosterBefore = rig.mentor.roster.count
let post = try PostStore.writeNew(body: "# Own Engine\n\nVerdict me.", home: rig.home)
rig.model.select(post.id, home: rig.home)
@@ -62,18 +56,13 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
try await Task.sleep(nanoseconds: 20_000_000)
}
// In a Task — the pass child's pid is only observable while it runs.
// In a Task — a full-mode scripted pass can complete inside one poll
// sleep (no child-process latency anymore), so the pass ENGINE is
// captured after the run from the spawn records, not polled mid-flight.
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
passPid = rig.mentor.passEngineChildPid
polls += 1
if passPid == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
_ = await run.value
let passEngine = rig.engines.engines.last { $0.spawnedProfile == "museion-pass1" }
let passEngineClosed = try #require(passEngine, "pass engine never spawned")
// The run completed as today: snapshot landed, Pass-1 Done stamped.
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
@@ -82,22 +71,15 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: Pass-1 Done"))
// The pass engine spawned under its own profile; the chat engine under museion.
let lines = try String(
contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-spawn-log"),
encoding: .utf8,
).split(separator: "\n").map(String.init)
#expect(lines.contains("acp -p museion-pass1"))
#expect(lines.contains("acp -p museion"))
#expect(rig.engines.spawnedProfiles.contains("museion-pass1"))
#expect(rig.engines.spawnedProfiles.contains("museion"))
// Nothing pass-shaped stays resident…
#expect(rig.mentor.roster.count == rosterBefore)
#expect(!rig.mentor.isPassEngineRunning)
if let passPid {
#expect(try await pollReaped(passPid))
} else {
Issue.record("pass engine pid never observed while the run was in flight")
}
// …and the chat engine is untouched.
#expect(kill(chatPid, 0) == 0)
#expect(rig.mentor.host.oneShot == nil)
#expect(passEngineClosed.isClosed) // the in-process reaped pin
// …and the chat engine is untouched (identity, not pid).
#expect(rig.mentor.host.chat === chatBefore)
#expect(rig.mentor.phase.isReady)
// The label row and the streamed critique rendered on the active surface.
#expect(textRows(of: rig.mentor).contains("Pass 1 · \(post.title)"))
@@ -114,10 +96,10 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
}
/// A1 cancel: the pass bar's Cancel reaches the PASS engine — the held turn
/// ends cancelled, the pass child is reaped, the roster never grew, and the
/// pre-pass snapshot still landed (pre-pass is unconditional).
/// ends cancelled, the pass engine is torn down, the roster never grew, and
/// the pre-pass snapshot still landed (pre-pass is unconditional).
@Test @MainActor func `cancelling a live pass cancels the turn and reaps the pass engine`() async throws {
let rig = try makeEngineRig(mode: "hangOnPrompt")
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
@@ -125,16 +107,7 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
rig.model.select(post.id, home: rig.home)
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
passPid = rig.mentor.passEngineChildPid
polls += 1
if passPid == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
let heldPid = try #require(passPid, "pass engine never spawned")
let heldEngine = try #require(await pollOneShot(of: rig.mentor), "pass engine never spawned")
#expect(rig.mentor.isPassEngineRunning)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
@@ -150,7 +123,8 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(!rig.mentor.isPassEngineRunning)
#expect(try await pollReaped(heldPid))
#expect(rig.mentor.host.oneShot == nil)
#expect(heldEngine.isClosed) // the in-process reaped pin
#expect(rig.mentor.roster.count == rosterBefore)
}
@@ -163,32 +137,32 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
// place and replays the active rostered session — while idle, it restarts
// immediately.
/// A2 idle: requestRestart re-spawns in place — old child reaped, new child
/// alive, phase back to .ready, and the PRE-restart active rostered session
/// is resumed with its transcript replayed from the engine.
/// A2 idle: requestRestart re-spawns in place — old engine closed, new
/// transport resident, phase back to .ready, and the PRE-restart active
/// rostered session is resumed with its transcript replayed from the engine.
@Test @MainActor func `idle requestRestart respawns in place and replays the active rostered session`() async throws {
let rig = try makeEngineRig(mode: "loadReplay")
let rig = try makeScriptedRig(mode: "loadReplay")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let active = try #require(rig.mentor.activeEntry)
_ = await rig.mentor.sendPrompt("hello mentor") // history in the active session
let oldPid = try #require(rig.mentor.childProcessIdentifier)
let oldEngine = try #require(rig.mentor.host.chat as? ScriptedEngine)
rig.mentor.requestRestart()
var newPid: pid_t?
var newChat: (any EngineTransport)?
var polls = 0
while newPid == nil, polls < 250 {
if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != oldPid {
newPid = pid
while newChat == nil, polls < 250 {
if rig.mentor.phase.isReady, let chat = rig.mentor.host.chat, chat !== oldEngine {
newChat = chat
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
let respawned = try #require(newPid, "chat engine never re-spawned")
#expect(try await pollReaped(oldPid))
#expect(kill(respawned, 0) == 0)
let respawned = try #require(newChat, "chat engine never re-spawned")
#expect(oldEngine.isClosed) // the in-process reaped pin
#expect(rig.mentor.host.chat === respawned) // the new engine stays resident
// The writer stays where they were: same rostered session, replayed.
#expect(rig.mentor.activeEntry == active)
var replayed = false
@@ -203,13 +177,14 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
}
/// A2 deferred ordering pin: requested mid-turn, the restart holds (same
/// child, still streaming) until the turn ends — the pid swap happens only
/// AFTER the turn.
/// transport, still streaming) until the turn ends — the engine swap
/// happens only AFTER the turn.
@Test @MainActor func `requestRestart mid-turn defers the respawn until the turn ends`() async throws {
let rig = try makeEngineRig(mode: "hangOnPrompt")
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let chatPid = try #require(rig.mentor.childProcessIdentifier)
let chatBefore = rig.mentor.host.chat
let oldEngine = try #require(chatBefore as? ScriptedEngine)
let turn = Task { await rig.mentor.sendPrompt("hold this") }
for _ in 0 ..< 250 where !rig.mentor.isStreaming {
@@ -219,27 +194,26 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
rig.mentor.requestRestart() // Settings fires — mid-turn
try await Task.sleep(for: .milliseconds(300))
// Still streaming, same child: the restart deferred, never mid-reply.
// Still streaming, same engine: the restart deferred, never mid-reply.
#expect(rig.mentor.isStreaming)
#expect(rig.mentor.childProcessIdentifier == chatPid)
#expect(kill(chatPid, 0) == 0)
#expect(rig.mentor.host.chat === chatBefore)
rig.mentor.stopStreaming() // ends the held turn — the restart fires now
_ = await turn.value
#expect(!rig.mentor.isStreaming)
var newPid: pid_t?
var newChat: (any EngineTransport)?
var polls = 0
while newPid == nil, polls < 250 {
if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != chatPid {
newPid = pid
while newChat == nil, polls < 250 {
if rig.mentor.phase.isReady, let chat = rig.mentor.host.chat, chat !== chatBefore {
newChat = chat
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
#expect(newPid != nil, "the deferred pid swap never happened after turn end")
#expect(try await pollReaped(chatPid))
#expect(newChat != nil, "the deferred engine swap never happened after turn end")
#expect(oldEngine.isClosed) // the in-process reaped pin
}
// Scenario: Run Pass names the missing key instead of failing silently
@@ -309,7 +283,7 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
/// provider in lastError — and fires BEFORE the open-piece guard's
/// snapshot, so nothing lands on disk.
@Test @MainActor func `run pass names the missing provider key and writes nothing`() async throws {
let rig = try makeEngineRig()
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let writer = RecordingWriter()
@@ -336,11 +310,11 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
/// #137 audit (finish): a session/load that STARTED before a pass and
/// COMPLETES mid-pass must not steal the pass surface — the post-await
/// claimActive guard refuses, Cancel keeps routing to the pass engine.
/// loadReplayHold parks the load until `load-go` lands beside the fake
/// (SessionLifecycleTests' in-flight seam), which makes the interleaving
/// deterministic instead of lucky.
/// loadReplayHold parks the load until releaseHeldLoad() (the rig's
/// in-flight seam), which makes the interleaving deterministic instead of
/// lucky.
@Test @MainActor func `a resume completing mid-pass does not steal the pass surface`() async throws {
let rig = try makeEngineRig(mode: "loadReplayHold")
let rig = try makeScriptedRig(mode: "loadReplayHold")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession() // default Mentor session (sess-1)
_ = await rig.mentor.newSession(name: "Second", pieceTitle: nil) // sess-2 active
@@ -351,7 +325,7 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
try await Task.sleep(nanoseconds: 20_000_000)
}
// Park a resume of sess-1. The fake announces the park with a
// Park a resume of sess-1. The engine announces the park with a
// `hold-load` stderr line (the chat engine's stderrTail surfaces it).
let resume = Task { await rig.mentor.resumeSession(target) }
for _ in 0 ..< 250 where !rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
@@ -359,15 +333,11 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
}
try #require(rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }))
// Deterministic window: flip the mode file to hangOnPrompt BEFORE the
// pass engine spawns (each child reads the mode at startup) — the pass
// prompt then HOLDS, so isStreaming is guaranteed when the parked load
// completes, and the #124 Cancel rail frees it afterwards.
try "hangOnPrompt".write(
toFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-mode"),
atomically: true,
encoding: .utf8,
)
// Deterministic window: flip the rig's mode to hangOnPrompt BEFORE the
// pass engine spawns (each spawn reads the mode at factory time) — the
// pass prompt then HOLDS, so isStreaming is guaranteed when the parked
// load completes, and the #124 Cancel rail frees it afterwards.
rig.engines.mode = "hangOnPrompt"
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.mentor.isPassEngineRunning {
try await Task.sleep(nanoseconds: 20_000_000)
@@ -376,7 +346,7 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
// Free the parked load — its completion lands while the pass holds
// (nothing blocks the load; the held pass makes the direct await safe).
try Data().write(to: URL(fileURLWithPath: (rig.fakeDir as NSString).appendingPathComponent("load-go")))
rig.engines.releaseHeldLoad()
// The resume refused post-await while the pass still held the surface…
#expect(await resume.value == false)
#expect(rig.mentor.activeEntry?.sessionId == MentorSessionModel.passTranscriptKey)
+217
View File
@@ -0,0 +1,217 @@
//
// EngineSmokeTests.swift
// MuseionTests
//
// Scenario: one real-process wire smoke per LLM surface
// From #178
// Given every engine-behaviour test now runs in-process at the transport seam
// When the real stdio wire contract must be guarded
// Then exactly one real-process end-to-end smoke per surface (chat on museion,
// pass1, pass2) drives the real ACPEngineClient + the zsh fake — the only
// child-spawning tests left in the suite.
//
import Foundation
@testable import Museion
import Testing
/// Bounded poll until a child is reaped (kill(pid, 0) fails) — the house
/// 250×20 ms pattern, 100 rounds for a close() that reaps synchronously.
/// Local to this file: only the smokes observe real child pids anymore.
@MainActor
private func pollReaped(_ pid: pid_t) async throws -> Bool {
for _ in 0 ..< 100 where kill(pid, 0) == 0 {
try await Task.sleep(nanoseconds: 20_000_000)
}
return kill(pid, 0) != 0
}
/// Bounded settle for the streamed turn: the text row and the fix-card row
/// land via notification hops that can settle just after the response
/// resumes the test (the house poll pattern).
@MainActor
private func pollStreamedTurn(of mentor: MentorSessionModel) async throws -> (streamed: Bool, card: Bool) {
var streamed = false
var card = false
for _ in 0 ..< 250 where !(streamed && card) {
streamed = mentor.rows.contains { row in
if case let .text(text, _, _) = row.content {
return text.contains("Hello mentor.")
}
return false
}
card = mentor.rows.contains { row in
if case let .fixCard(fix) = row.content {
return fix.pattern == "Blame tense"
}
return false
}
if !(streamed && card) {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
return (streamed, card)
}
/// Bounded poll for the .crashed phase after the child kill.
@MainActor
private func pollCrashed(_ mentor: MentorSessionModel) async -> Bool {
for _ in 0 ..< 250 {
if case .crashed = mentor.phase {
return true
}
try? await Task.sleep(nanoseconds: 20_000_000)
}
return false
}
@Suite("EngineSmokeTests")
struct EngineSmokeTests {
/// Act 1 of the chat smoke, extracted (function_body_length): the two
/// held-turn wire contracts on the cancel-holding fake — see the test
/// below for the contracts' meaning.
@MainActor
private func heldTurnWireContracts(fake: String) async throws {
let held = MentorSessionModel(binaryPath: fake)
defer { held.shutdown() }
await held.openSession()
let heldTurn = Task { await held.sendPrompt("hold this") }
for _ in 0 ..< 250 where !held.isStreaming {
try await Task.sleep(nanoseconds: 20_000_000)
}
held.stopStreaming() // fire-and-forget session/cancel over the real pipe
#expect(await heldTurn.value == .cancelled)
// A second held turn, ended by teardown: shutdown SIGTERMs the parked
// child and reaps it — no child outlives the app.
let holdPid = try #require(held.childProcessIdentifier)
let holdTurn = Task { await held.sendPrompt("hold for teardown") }
for _ in 0 ..< 250 where !held.isStreaming {
try await Task.sleep(nanoseconds: 20_000_000)
}
held.shutdown()
_ = await holdTurn.value
#expect(try await pollReaped(holdPid))
}
/// The chat surface over the REAL stdio path, in two acts over one fake:
/// (1) the cancel + hung-teardown wire contracts — a held turn ends
/// `.cancelled` the moment the fire-and-forget session/cancel arrives
/// (#124), and shutdown SIGTERMs a child parked mid-hold (the
/// SIGTERM→grace→SIGKILL escalation, previously pinned by the retired
/// client tests); then the mode file flips and (2) a fresh model runs
/// the full lifecycle — handshake + version, a streamed turn (text +
/// fix card), a hard child kill (the real crash rail), restart onto a
/// fresh child with the OLD pid reaped, and teardown reaping the new
/// one. Mode `loadReplay` for act 2: restart() resumes the newest
/// rostered session over session/load, which the fake's default mode
/// never answers — this mode answers EVERYTHING act 2 drives.
@MainActor
@Test func `chat surface smoke — cancel, teardown, handshake, stream, crash, restart`() async throws {
let dir = acpTempDir("smoke-chat")
let fake = makeFakeACP(at: dir, mode: "hangOnPrompt")
// Act 1 — the held-turn wire contracts on the cancel-holding fake.
try await heldTurnWireContracts(fake: fake)
// Act 2 — the full chat lifecycle; the fresh child reads loadReplay.
try "loadReplay".write(
toFile: (dir as NSString).appendingPathComponent("hermes-acp-mode"),
atomically: true,
encoding: .utf8,
)
let mentor = MentorSessionModel(binaryPath: fake)
defer { mentor.shutdown() }
await mentor.openSession()
guard case .ready = mentor.phase else {
Issue.record("expected ready, got \(mentor.phase); stderr: \(mentor.stderrTail)")
return
}
#expect(mentor.engineVersion == "9.9.9")
let outcome = await mentor.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let turn = try await pollStreamedTurn(of: mentor)
#expect(turn.streamed)
#expect(turn.card)
// The real crash rail: kill the child, the connection loss must land.
let pid = try #require(mentor.childProcessIdentifier)
kill(pid, SIGKILL)
#expect(await pollCrashed(mentor))
await mentor.restart()
var newPid: pid_t?
for _ in 0 ..< 250 {
if mentor.phase.isReady, let respawned = mentor.childProcessIdentifier, respawned != pid {
newPid = respawned
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(newPid != nil, "chat engine never re-spawned onto a new child")
// The crashed child is reaped; teardown reaps the replacement.
#expect(try await pollReaped(pid))
mentor.shutdown()
#expect(try await pollReaped(#require(newPid)))
}
/// The Pass 1/Pass 2 surfaces over the REAL stdio path (parameterized —
/// one smoke case per surface): a one-shot pass engine spawns under its
/// own profile beside the resident chat engine (the spawn log pins
/// both), the verdict completes the pass (snapshot + the monotonic
/// stamp — passes run in any order, so both kinds stamp from First
/// Draft), and BOTH children die honestly — the pass child reaped at
/// the verdict, the chat child still alive at teardown.
@MainActor
@Test(arguments: [PassKind.pass1, PassKind.pass2])
func `pass surface smoke — own engine, spawn profile, teardown reap`(kind: PassKind) async throws {
let passNumber = kind == .pass1 ? 1 : 2
let dir = acpTempDir("smoke-pass\(passNumber)")
let fake = makeFakeACP(at: dir)
let (model, home) = try makeModelHome()
let mentor = MentorSessionModel(binaryPath: fake)
defer { mentor.shutdown() }
await mentor.openSession() // the resident chat engine
let chatPid = try #require(mentor.childProcessIdentifier)
let post = try PostStore.writeNew(body: "# Smoke Pass\n\nVerdict me.", home: home)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
// In a Task — the pass child's pid is only observable while it runs
// (the old EngineLifecycleTests poll; the zsh wire latency holds the
// turn open long enough to catch it).
let run = Task { await model.runPass(kind, home: home, mentor: mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
passPid = mentor.passEngineChildPid
polls += 1
if passPid == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
_ = await run.value
// The verdict completed the pass: snapshot landed, the kind's stamp.
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(
contentsOf: piece.appendingPathComponent("passes/pass-\(passNumber).md"), encoding: .utf8,
)
#expect(snapshot.contains("Verdict me."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: Pass-\(passNumber) Done"))
// Both engines spawned over the real wire, each under its profile.
let lines = try String(
contentsOfFile: (dir as NSString).appendingPathComponent("hermes-acp-spawn-log"),
encoding: .utf8,
).split(separator: "\n").map(String.init)
#expect(lines.contains("acp -p museion-pass\(passNumber)"))
#expect(lines.contains("acp -p museion"))
// The pass child is reaped at the verdict; the chat child lives on.
#expect(try await pollReaped(#require(passPid, "pass child pid never observed mid-run")))
#expect(kill(chatPid, 0) == 0)
#expect(mentor.phase.isReady)
}
}
+11 -11
View File
@@ -2,26 +2,26 @@
// PassRunTests.swift
// MuseionTests
//
// #24 (S3.1): the pass orchestration — PostsModel.runPass over the real
// client + fake ACP server (ACPClientTests' fake, PostsModelTests' temp-home
// model). Pre-pass snapshot before the engine sees the text, Pass State
// advancing only on a completed turn, order-free. #124: teardown defers at
// rig creation — the fake child dies with the test however it exits.
// #24 (S3.1): the pass orchestration — PostsModel.runPass over the
// in-process scripted engine (#178: ScriptedEngines rig at the
// EngineTransport seam, no child process; makePassRig keeps its
// (model, home, mentor) shape). Pre-pass snapshot before the engine sees
// the text, Pass State advancing only on a completed turn, order-free.
// #124: teardown defers at rig creation.
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Home + model + mentor over the fake engine (makeModelHome +
/// makeFakeACP, one rig).
/// Throwaway Home + model + mentor over the scripted engines
/// (makeModelHome + makeScriptedRig, one rig; the 3-tuple shape is what
/// the tests below read).
@MainActor
// swiftlint:disable:next large_tuple
func makePassRig(mode: String = "full") throws -> (PostsModel, URL, MentorSessionModel) {
let (model, home) = try makeModelHome()
let fake = makeFakeACP(at: acpTempDir("passrun"), mode: mode)
let mentor = MentorSessionModel(binaryPath: fake)
return (model, home, mentor)
let rig = try makeScriptedRig(mode: mode)
return (rig.model, rig.home, rig.mentor)
}
/// Internal (shared-helper convention): EngineLifecycleTests reads the same
+6 -5
View File
@@ -4,7 +4,8 @@
//
// #29 (S8.1–S8.3): the research-candidate pins, own file —
// SessionLifecycleTests crossed its type-body ceiling (MCPToolsPromoteTests
// precedent). Reuses the shared fake ACP harness. The payload SHAPE pins
// precedent). #178: runs IN-PROCESS over ScriptedEngines rigs at the
// EngineTransport seam — no child process. The payload SHAPE pins
// live in ToolPayloadsTests (#177); this file pins the curation behavior.
//
@@ -24,8 +25,8 @@ struct ResearchCandidateTests {
let rosterDir = acpTempDir("research-roster")
let entry = SessionEntry(sessionId: "sess-1", name: "Research", pieceTitle: nil, createdAt: Date())
SessionRoster.save([entry], directory: rosterDir)
let fake = makeFakeACP(at: acpTempDir("research"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
let engines = ScriptedEngines(mode: "loadReplay")
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession()
@@ -64,8 +65,8 @@ struct ResearchCandidateTests {
let rosterDir = acpTempDir("disposition-roster")
let entry = SessionEntry(sessionId: "sess-1", name: "Research", pieceTitle: nil, createdAt: Date())
SessionRoster.save([entry], directory: rosterDir)
let fake = makeFakeACP(at: acpTempDir("disposition"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
let engines = ScriptedEngines(mode: "loadReplay")
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession()
+604
View File
@@ -0,0 +1,604 @@
//
// ScriptedEngine.swift
// MuseionTests
//
// Scenario: engine behaviour runs in-process at the transport seam
// From #178
// Given the engine host owns lifecycle behind the EngineTransport seam
// When engine-behaviour tests stream, crash, cancel, restart, or spawn
// per-surface
// Then a scripted in-process adapter answers at the seam — no child
// process ever spawns — while one real-process smoke per LLM surface
// (EngineSmokeTests, slice B2) guards the real stdio wire contract.
//
// Rig shapes:
// - `ScriptedEngine` — one in-process engine. Its `mode` mirrors the zsh
// fake's modes (makeFakeACP in ACPClientTests is the wire-shape SPEC);
// mutable state is confined to a serial queue exactly like
// ACPEngineClient's (request runs nonisolated on the global executor
// while notify/close/start arrive from MainActor). Within request(),
// scripted notifications fire through onMessage BEFORE the continuation
// resumes — the host's main-queue wrappers then guarantee the model's
// handleNotification runs before the awaiting model code continues
// (the #28 wire-order guarantee, same as production).
// - `ScriptedEngines` — the rig root: mutable `mode` (read at FACTORY
// time, so a test flips it mid-run in place of the old mode file),
// `spawnedProfiles` (the which-engine-ran pin, replacing the fake's
// spawn-log file), `engines` (spawn order), `host` (binaryPath
// "scripted").
// - `makeScriptedRig` — EngineLifecycleTests' EngineRig shape:
// `ScriptedRig(model: PostsModel, home: URL, mentor:
// MentorSessionModel, engines: ScriptedEngines)` over makeModelHome
// (PostStore/PostsModel reuse stays as-is).
//
// swiftlint:disable file_length
// One file: the scripted engine + its payload rig + the shared test rig —
// one lifecycle story (the zsh fake's modes ARE this class's branches;
// splitting them off would break the wire-shape parity review).
import Foundation
@testable import Museion
// MARK: - Shared wire payloads
/// The tool-call payloads shared by the zsh fake (base64 over the real
/// stdio wire) and the scripted engine (#178). The JSON is byte-identical
/// between both paths — the zsh script's behavior never changes.
enum ScriptedPayloads {
/// The REAL submit_fix_cards argument shape (snake_case, anchor as
/// object) — pins the nested parse.
static let fixCardJSON = #"{"piece_path":"/tmp/piece","cards":["# + cardJSON + #"]}"#
// ponytail: raw strings, plain quotes — a backslash would ride the JSON.
private static let cardJSON = #"{"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}}"#
/// The research-notes payload: two notes — one complete, one with
/// quote/note absent (the "" defaults).
static let researchJSON = #"{"piece_path":"/tmp/piece","notes":["# + noteJSON + #","# + secondNoteJSON + #"]}"#
private static let noteJSON = #"{"title":"Hinge Study","url":"https://example.org/hinge","# +
#""quote":"We should stop listening.","# +
#""note":"Counts the pivot tense."}"#
private static let secondNoteJSON = #"{"title":"Second Source","url":"https://example.org/second"}"#
/// A research batch that ALSO carries stray fix-card keys at the top
/// level — the notes-array shape must win over the pattern/problem
/// match (#29 routing pin).
static let strayResearchJSON = #"{"pattern":"stray","problem":"stray","# +
#""piece_path":"/tmp/piece","# +
#""notes":[{"title":"Hinge Study","url":"https://example.org/hinge"}]}"#
static var fixCard: JSONValue {
payload(fixCardJSON)
}
static var research: JSONValue {
payload(researchJSON)
}
static var strayResearch: JSONValue {
payload(strayResearchJSON)
}
private static func payload(_ json: String) -> JSONValue {
guard let any = try? JSONSerialization.jsonObject(with: Data(json.utf8)) else {
preconditionFailure("scripted payload is not JSON: \(json)")
}
return JSONValue(any)
}
}
// MARK: - The scripted engine
/// The in-process scripted engine (#178): a faithful port of makeFakeACP's
/// zsh modes to the EngineTransport seam. No child process ever spawns —
/// the real stdio contract is guarded later by EngineSmokeTests (B2).
final class ScriptedEngine: EngineTransport, @unchecked Sendable {
struct ScriptedError: Error, CustomStringConvertible {
let message: String
var description: String {
message
}
}
var onMessage: (@Sendable (String, JSONValue?) -> Void)?
var onCrash: (@Sendable () -> Void)?
var onStderrLine: (@Sendable (String) -> Void)?
private let queue = DispatchQueue(label: "com.babylondreams.MuseionTests.scripted-engine")
private let profile: String
private let mode: String
// All mutable state below is confined to `queue`.
private var currentID = 0
private var sessionCounter = 0
private var forkCounter = 0
private var closed = false
private var crashed = false
private var prompts: [(sessionId: String, text: String)] = []
private var parked: [Int: CheckedContinuation<JSONValue?, any Error>] = [:]
/// The held session/prompt (hangOnPrompt) — resumed by session/cancel.
private var heldPromptID: Int?
/// The held session/load (loadReplayHold) — resumed by releaseHeldLoad().
private var heldLoad: (id: Int, sessionId: String)?
init(profile: String, mode: String) {
self.profile = profile
self.mode = mode
}
/// The profile this engine was spawned for — the spawn-log tail.
var spawnedProfile: String {
profile
}
/// Every session/prompt's wire sessionId + text — the what-it-was-asked
/// pin (replaces the fake's prompt-log file).
var promptLog: [(sessionId: String, text: String)] {
queue.sync { prompts }
}
/// True after close() — the in-process reaped pin.
var isClosed: Bool {
queue.sync { closed }
}
var crashedOnce: Bool {
queue.sync { crashed }
}
/// True while a loadReplayHold load is parked — the rig's release
/// targeting (the newest PARKED engine, not the newest spawn).
var hasHeldLoad: Bool {
queue.sync { heldLoad != nil }
}
// MARK: EngineTransport
/// The fake always spawns cleanly — there is no process.
func start() throws {}
func request(_ method: String, params: JSONValue?, timeout: TimeInterval) async throws -> JSONValue? {
let id = queue.sync {
currentID += 1
return currentID
}
return try await withCheckedThrowingContinuation { continuation in
queue.async {
guard !self.closed else {
continuation.resume(throwing: ScriptedError(message: "engine closed before \(method)"))
return
}
guard !self.crashed else {
continuation.resume(throwing: ScriptedError(message: "engine exited (code 1)"))
return
}
self.answer(id: id, method: method, params: params, continuation: continuation)
// ponytail: ACPEngineClient's deadline posture — a parked
// (held) request can never hang a suite forever.
self.queue.asyncAfter(deadline: .now() + timeout) {
guard self.parked.removeValue(forKey: id) != nil else { return }
if self.heldPromptID == id {
self.heldPromptID = nil
}
if self.heldLoad?.id == id {
self.heldLoad = nil
}
continuation.resume(
throwing: ScriptedError(message: "\(method) timed out after \(Int(timeout)) s"),
)
}
}
}
}
func notify(_ method: String, params _: JSONValue?) {
queue.async {
guard method == "session/cancel" else { return }
self.onStderrLine?("cancel received")
// #124: the cancel-acknowledging hold — the real engine answers
// its hanging prompt the moment session/cancel arrives.
guard self.mode == "hangOnPrompt", let id = self.heldPromptID,
let continuation = self.parked.removeValue(forKey: id) else { return }
self.heldPromptID = nil
continuation.resume(returning: .object(["stopReason": .string("cancelled")]))
}
}
func close() {
queue.sync {
guard !closed else { return }
closed = true
for (_, continuation) in parked {
continuation.resume(throwing: ScriptedError(message: "engine closed"))
}
parked.removeAll()
heldPromptID = nil
heldLoad = nil
}
}
/// Test hook (loadReplayHold): release the parked session/load — the
/// replay notifications fire, THEN the load response resumes.
func releaseHeldLoad() {
queue.async {
guard let held = self.heldLoad,
let continuation = self.parked.removeValue(forKey: held.id) else { return }
self.heldLoad = nil
self.replayHistory(held.sessionId)
continuation.resume(returning: self.loadResult(for: held.sessionId))
}
}
/// Test hook: the kill(pid, SIGKILL) rail's in-process twin (#178 B2) —
/// the engine dies unexpectedly: onCrash fires, every pending request
/// fails. The crash-restart pins drive real crashes through this.
func crashNow() {
queue.async {
self.crash()
}
}
}
// MARK: Mode dispatch (queue-confined — mirrors makeFakeACP's zsh)
//
// File-scope extension — type_body_length posture (MentorSessionModel
// precedent); the mode branches and the wire helpers they drive read as
// one zsh-script port, same file.
extension ScriptedEngine {
private static let initializeResult: JSONValue = .object([
"protocolVersion": .number(1),
"agentInfo": .object([
"name": .string("hermes-agent"),
"title": .string("Hermes"),
"version": .string("9.9.9"),
]),
])
private func answer(
id: Int,
method: String,
params: JSONValue?,
continuation: CheckedContinuation<JSONValue?, any Error>,
) {
switch method {
case "initialize":
// crashAfterHandshake answers, then dies. The crash latches and
// fires BEFORE the handshake continuation resumes — onCrash must
// be observable the moment initialize returns (the host's
// main.async wrapper lands before the awaiting task continues).
if mode == "crashAfterHandshake" {
crash()
}
continuation.resume(returning: Self.initializeResult)
case "session/new":
// #44 invariant: the lifecycle modes + strictMcp require
// mcpServers (-32602 without); Museion always ships [].
let strict = mode == "strictMcp" || mode.hasPrefix("loadReplay")
guard !strict || hasMcpServers(params) else {
continuation.resume(throwing: ScriptedError(message: "-32602: Invalid params: mcpServers required"))
return
}
sessionCounter += 1 // #28: unique id per new
continuation.resume(returning: .object(["sessionId": .string("sess-\(sessionCounter)")]))
case "session/prompt":
prompt(id: id, params: params, continuation: continuation)
case "session/load":
load(id: id, params: params, continuation: continuation)
case "session/fork":
fork(id: id, params: params, continuation: continuation)
default:
park(id: id, continuation: continuation)
}
}
private func prompt(
id: Int,
params: JSONValue?,
continuation: CheckedContinuation<JSONValue?, any Error>,
) {
let sid = params?.objectValue?["sessionId"]?.stringValue ?? ""
prompts.append((sid, Self.promptText(params)))
if mode == "refuseOnPrompt" {
continuation.resume(returning: .object(["stopReason": .string("refusal")]))
return
}
chunk(sid, "user_message_chunk", "echo")
chunk(sid, "agent_thought_chunk", "weighing the structure")
chunk(sid, "agent_message_chunk", "Hello ")
if mode == "cancelOnPrompt" {
continuation.resume(returning: .object(["stopReason": .string("cancelled")]))
return
}
if mode == "noStopReason" {
// A response without stopReason is NOT a completed turn — the
// .failed mapping pin's wire shape.
continuation.resume(returning: .object(["sessionId": .string("sess-1")]))
return
}
chunk(sid, "agent_message_chunk", "mentor.")
if mode == "strayResearchOnPrompt" {
// #29 audit pin: a research payload carrying stray fix-card
// keys must route by shape (notes array), not vanish into a
// card row.
toolCall(sid, title: "submit_research_notes", rawInput: ScriptedPayloads.strayResearch)
continuation.resume(returning: .object(["stopReason": .string("end_turn")]))
return
}
toolCall(sid, title: "submit_fix_cards", rawInput: ScriptedPayloads.fixCard)
if mode == "hangOnPrompt" {
park(id: id, continuation: continuation)
heldPromptID = id
return
}
continuation.resume(returning: .object(["stopReason": .string("end_turn")]))
}
private func load(
id: Int,
params: JSONValue?,
continuation: CheckedContinuation<JSONValue?, any Error>,
) {
guard mode.hasPrefix("loadReplay") else {
park(id: id, continuation: continuation) // the zsh never answers
return
}
guard hasMcpServers(params) else {
continuation.resume(throwing: ScriptedError(message: "-32602: Invalid params: mcpServers required"))
return
}
let sid = params?.objectValue?["sessionId"]?.stringValue ?? ""
onStderrLine?("load \(sid)") // the wire call, visible in stderrTail
if mode == "loadReplayHold" {
// The finish-audit interleaving pin's in-flight observable:
// park after the pre-hold stderr lines, until releaseHeldLoad().
onStderrLine?("hold-load")
park(id: id, continuation: continuation)
heldLoad = (id, sid)
return
}
replayHistory(sid)
continuation.resume(returning: loadResult(for: sid))
}
/// The load response: the real 0.21.5 shape (the id rides
/// _meta.hermes.sessionProvenance) or the older top-level contract
/// (loadReplayLegacy); an unknown id answers {} — no sessionId anywhere.
private func loadResult(for sid: String) -> JSONValue {
guard sid.hasPrefix("sess-") else { return .object([:]) }
if mode == "loadReplayLegacy" {
return .object(["sessionId": .string(sid)])
}
return .object([
"modes": .array([]),
"_meta": .object([
"hermes": .object([
"sessionProvenance": .object(["acpSessionId": .string(sid)]),
]),
]),
])
}
/// Full history replay, wire order, BEFORE the load response — the real
/// adapter's contract (#28). Candidates re-materialize on resume (#29).
private func replayHistory(_ sid: String) {
guard sid.hasPrefix("sess-") else { return }
chunk(sid, "user_message_chunk", "earlier ask")
chunk(sid, "agent_thought_chunk", "old thinking")
chunk(sid, "agent_message_chunk", "earlier verdict")
toolCall(sid, title: "submit_research_notes", rawInput: ScriptedPayloads.research)
}
private func fork(
id: Int,
params: JSONValue?,
continuation: CheckedContinuation<JSONValue?, any Error>,
) {
// The zsh answers fork ONLY in loadReplay (not the hold/legacy modes).
guard mode == "loadReplay" else {
park(id: id, continuation: continuation)
return
}
guard hasMcpServers(params) else {
continuation.resume(throwing: ScriptedError(message: "-32602: Invalid params: mcpServers required"))
return
}
let sid = params?.objectValue?["sessionId"]?.stringValue ?? ""
onStderrLine?("fork \(sid)")
if sid == "sess-1" {
forkCounter += 1
continuation.resume(returning: .object(["sessionId": .string("F-\(forkCounter)")]))
} else {
continuation.resume(returning: .object(["sessionId": .string("")])) // empty = refused
}
}
/// Park a request the mode never answers — only close() (or the mode's
/// release path) resumes it, bounded by the request timeout armed in
/// request().
private func park(id: Int, continuation: CheckedContinuation<JSONValue?, any Error>) {
parked[id] = continuation
}
private func crash() {
guard !crashed else { return }
crashed = true
for (_, continuation) in parked {
continuation.resume(throwing: ScriptedError(message: "engine exited (code 1)"))
}
parked.removeAll()
heldPromptID = nil
heldLoad = nil
onCrash?()
}
// MARK: Wire-shaped notifications (queue-confined, wire order)
private func chunk(_ sid: String, _ kind: String, _ text: String) {
update(sid, .object([
"sessionUpdate": .string(kind),
"content": .object(["type": .string("text"), "text": .string(text)]),
"messageId": .string("m1"),
]))
}
private func toolCall(_ sid: String, title: String, rawInput: JSONValue) {
update(sid, .object([
"sessionUpdate": .string("tool_call"),
"toolCallId": .string("tc1"),
"title": .string(title),
"rawInput": rawInput,
]))
}
private func update(_ sid: String, _ payload: JSONValue) {
onMessage?("session/update", .object([
"sessionId": .string(sid),
"update": payload,
]))
}
private func hasMcpServers(_ params: JSONValue?) -> Bool {
params?.objectValue?["mcpServers"] != nil
}
private static func promptText(_ params: JSONValue?) -> String {
guard case let .array(items)? = params?.objectValue?["prompt"],
case let .object(first)? = items.first else { return "" }
return first["text"]?.stringValue ?? ""
}
}
// MARK: - The rig root
/// The lock-protected core both the rig and the host's factory hold. The
/// factory must NOT capture the @MainActor rig weakly: a rig that goes out
/// of scope mid-test (makePassRig's 3-tuple drops it) would silently
/// revert every later spawn to a "full" fallback — the mode and the spawn
/// records must outlive the rig, held by the host itself.
private final class ScriptedBook: @unchecked Sendable {
private let lock = NSLock()
private var modeValue: String
private var profiles: [String] = []
private var spawned: [ScriptedEngine] = []
init(mode: String) {
modeValue = mode
}
var mode: String {
get {
lock.lock()
defer { lock.unlock() }
return modeValue
}
set {
lock.lock()
defer { lock.unlock() }
modeValue = newValue
}
}
var spawnedProfiles: [String] {
lock.lock()
defer { lock.unlock() }
return profiles
}
var engines: [ScriptedEngine] {
lock.lock()
defer { lock.unlock() }
return spawned
}
func spawn(profile: String) -> ScriptedEngine {
lock.lock()
defer { lock.unlock() }
let engine = ScriptedEngine(profile: profile, mode: modeValue)
profiles.append(profile)
spawned.append(engine)
return engine
}
}
/// The in-process rig root (#178): the host's transport factory spawns
/// ScriptedEngines — every spawn records its profile (the which-engine-ran
/// pin, replacing the fake's spawn-log file) and reads `mode` at FACTORY
/// time (a test flips `mode` mid-run in place of the old mode file).
@MainActor
final class ScriptedEngines {
private let book: ScriptedBook
var mode: String {
get { book.mode }
set { book.mode = newValue }
}
var spawnedProfiles: [String] {
book.spawnedProfiles
}
var engines: [ScriptedEngine] {
book.engines
}
lazy var host: EngineHost = {
let host = EngineHost()
host.binaryPath = "scripted" // non-nil so startChat's guard passes
let book = self.book
host.makeTransport = { profile in
book.spawn(profile: profile)
}
return host
}()
init(mode: String = "full") {
book = ScriptedBook(mode: mode)
}
/// A mentor over this host — binaryPath keeps the "scripted" sentinel
/// (the model's init re-sets host.binaryPath from its own argument).
/// `rosterDirectory` plants a roster (the resume/fork rigs' seeded
/// entries).
func makeMentor(rosterDirectory: String? = nil) -> MentorSessionModel {
MentorSessionModel(host: host, binaryPath: "scripted", rosterDirectory: rosterDirectory)
}
/// Release the newest PARKED engine's session/load (loadReplayHold —
/// the parked chat engine, not the newest spawn: a pass engine may have
/// spawned in between).
func releaseHeldLoad() {
for engine in engines.reversed() where engine.hasHeldLoad {
engine.releaseHeldLoad()
return
}
}
}
// MARK: - Rig
/// makeScriptedRig's shape — EngineLifecycleTests' EngineRig with the fake
/// directory swapped for the engines rig (the spawn/prompt observables).
@MainActor
struct ScriptedRig {
let model: PostsModel
let home: URL
let mentor: MentorSessionModel
let engines: ScriptedEngines
}
/// Throwaway Home + model + mentor over the scripted engines (PostsModel's
/// makeModelHome + the in-process host, one rig).
@MainActor
func makeScriptedRig(mode: String = "full") throws -> ScriptedRig {
let (model, home) = try makeModelHome()
let engines = ScriptedEngines(mode: mode)
let mentor = engines.makeMentor()
return ScriptedRig(model: model, home: home, mentor: mentor, engines: engines)
}
+104 -84
View File
@@ -6,10 +6,15 @@
// freeform new + piece association, resume of engine-owned history
// (user turns included) with an honest refusal for unknown sessions,
// fork, compact over the prompt rail, and roster persistence across
// model instances. Runs over the real client + fake ACP server
// (ACPClientTests' fake in its `loadReplay` lifecycle mode).
// model instances. #178: runs IN-PROCESS over ScriptedEngines rigs at
// the EngineTransport seam (the `loadReplay` lifecycle mode) — no child
// process; the real stdio wire contract is guarded by EngineSmokeTests.
//
// swiftlint:disable file_length
// One lifecycle story: the roster/resume/fork/compact pins + the
// finish-audit and draft-candidate extensions — same suite, same file.
import Foundation
@testable import Museion
import Testing
@@ -91,8 +96,8 @@ struct SessionLifecycleTests {
let rosterDir = acpTempDir("resume-roster")
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
SessionRoster.save([ghost], directory: rosterDir)
let fake = makeFakeACP(at: acpTempDir("resume"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
let engines = ScriptedEngines(mode: "loadReplay")
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession()
// The rostered entry is back and active — and the default open
@@ -160,8 +165,8 @@ struct SessionLifecycleTests {
let rosterDir = acpTempDir("fork-roster")
let source = SessionEntry(sessionId: "sess-1", name: "Essay", pieceTitle: "Pt", createdAt: Date())
SessionRoster.save([source], directory: rosterDir)
let fake = makeFakeACP(at: acpTempDir("fork"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
let engines = ScriptedEngines(mode: "loadReplay")
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession()
_ = await mentor.sendPrompt("hello mentor") // history in the original's transcript
@@ -181,10 +186,8 @@ struct SessionLifecycleTests {
let refusalDir = acpTempDir("fork-refusal")
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
SessionRoster.save([ghost], directory: refusalDir)
let refuser = MentorSessionModel(
binaryPath: makeFakeACP(at: acpTempDir("fork-refuser"), mode: "loadReplay"),
rosterDirectory: refusalDir,
)
let refuserEngines = ScriptedEngines(mode: "loadReplay")
let refuser = refuserEngines.makeMentor(rosterDirectory: refusalDir)
defer { refuser.shutdown() }
await refuser.openSession()
let refused = await refuser.forkActiveSession()
@@ -281,8 +284,8 @@ struct SessionLifecycleTests {
/// history replays from the engine (nothing fabricated locally).
@Test @MainActor func `roster survives relaunch transcripts do not`() async throws {
let rosterDir = acpTempDir("relaunch-roster")
let fake = makeFakeACP(at: acpTempDir("relaunch"), mode: "loadReplay")
let first = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
let firstEngines = ScriptedEngines(mode: "loadReplay")
let first = firstEngines.makeMentor(rosterDirectory: rosterDir)
defer { first.shutdown() }
await first.openSession() // creates + persists the default 'Mentor'
let notes = await first.newSession(name: "Notes", pieceTitle: "Essay X")
@@ -295,7 +298,8 @@ struct SessionLifecycleTests {
let firstEntry = (raw as? [[String: Any]])?.first ?? [:]
#expect(Set(firstEntry.keys) == ["sessionId", "name", "pieceTitle", "createdAt"])
let second = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
let secondEngines = ScriptedEngines(mode: "loadReplay")
let second = secondEngines.makeMentor(rosterDirectory: rosterDir)
defer { second.shutdown() }
#expect(second.roster.count == 2)
#expect(second.roster.first == notes) // newest-first, all four fields equal
@@ -333,70 +337,6 @@ struct SessionLifecycleTests {
#expect(SessionsPaneView.openPiece(in: model)?.id == post.id)
}
/// Finish-audit (converged, 3 reviewers): ONE replay slot — a second
/// resume while a session/load is in flight refuses instead of diverting
/// the first's replayed chunks into live streaming buffers.
/// `loadReplayHold` parks the load until `load-go` lands beside the
/// fake; the pre-hold "hold-load" stderr line is the in-flight
/// observable.
@Test @MainActor func `concurrent resume refuses while a replay is in flight`() async throws {
let dir = acpTempDir("hold-load")
let fake = makeFakeACP(at: dir, mode: "loadReplayHold")
let rosterDir = acpTempDir("hold-roster")
let known = SessionEntry(sessionId: "sess-9", name: "Known", pieceTitle: nil, createdAt: Date())
SessionRoster.save([known], directory: rosterDir)
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { mentor.shutdown() }
_ = Task { await mentor.openSession() } // parks inside the auto-resume's load
var inFlight = false
for _ in 0 ..< 250 {
if mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
inFlight = true
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(inFlight)
// The slot is taken: the second resume refuses honestly.
let other = SessionEntry(sessionId: "ghost-2", name: "Other", pieceTitle: nil, createdAt: Date())
let ok = await mentor.resumeSession(other)
#expect(!ok)
#expect(texts(in: mentor.transcriptRows(of: known)).contains { $0.contains("another session is loading") })
// Release the hold: the parked resume completes and replays.
try "go".write(toFile: (dir as NSString).appendingPathComponent("load-go"), atomically: true, encoding: .utf8)
var replayed = false
for _ in 0 ..< 250 {
if texts(in: mentor.transcriptRows(of: known)).contains(where: { $0.contains("earlier ask") }) {
replayed = true
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(replayed)
}
/// Finish-audit: resume refusals belong to the ENTRY — a dead row's
/// refusal lands in its own store, never in the active session's
/// transcript.
@Test @MainActor func `resume refusal is attributed to the entry not the active session`() async throws {
let rosterDir = acpTempDir("attrib-roster")
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
SessionRoster.save([ghost], directory: rosterDir)
let fake = makeFakeACP(at: acpTempDir("attrib"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession() // activates ghost; its load refuses (unknown id)
let second = await mentor.newSession(name: "Second", pieceTitle: nil)
#expect(second != nil)
_ = await mentor.resumeSession(ghost) // refuses again
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
let secondEntry = try #require(second)
#expect(!texts(in: mentor.transcriptRows(of: secondEntry)).contains { $0.contains("does not know") })
}
/// Finish-audit: the creation rail refuses while a turn streams — a
/// programmatic caller must not switch the active session out from
/// under a live turn (Stop would cancel the wrong session).
@@ -426,22 +366,91 @@ struct SessionLifecycleTests {
let perms = try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? Int
#expect(perms == 0o600)
}
}
// Scenario: the one replay slot + the crash-restart rail — finish-audit
// pins over the loadReplay modes. File-scope extension —
// type_body_length posture; same suite, same file.
@MainActor
extension SessionLifecycleTests {
/// Finish-audit (converged, 3 reviewers): ONE replay slot — a second
/// resume while a session/load is in flight refuses instead of diverting
/// the first's replayed chunks into live streaming buffers.
/// `loadReplayHold` parks the load until the rig's `releaseHeldLoad()`;
/// the pre-hold "hold-load" stderr line is the in-flight observable.
@Test func `concurrent resume refuses while a replay is in flight`() async throws {
let rosterDir = acpTempDir("hold-roster")
let engines = ScriptedEngines(mode: "loadReplayHold")
let known = SessionEntry(sessionId: "sess-9", name: "Known", pieceTitle: nil, createdAt: Date())
SessionRoster.save([known], directory: rosterDir)
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
defer { mentor.shutdown() }
_ = Task { await mentor.openSession() } // parks inside the auto-resume's load
var inFlight = false
for _ in 0 ..< 250 {
if mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
inFlight = true
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(inFlight)
// The slot is taken: the second resume refuses honestly.
let other = SessionEntry(sessionId: "ghost-2", name: "Other", pieceTitle: nil, createdAt: Date())
let secondLoad = await mentor.resumeSession(other)
#expect(!secondLoad)
#expect(texts(in: mentor.transcriptRows(of: known)).contains { $0.contains("another session is loading") })
// Release the hold: the parked resume completes and replays.
engines.releaseHeldLoad()
var replayed = false
for _ in 0 ..< 250 {
if texts(in: mentor.transcriptRows(of: known)).contains(where: { $0.contains("earlier ask") }) {
replayed = true
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(replayed)
}
/// Finish-audit: resume refusals belong to the ENTRY — a dead row's
/// refusal lands in its own store, never in the active session's
/// transcript.
@Test func `resume refusal is attributed to the entry not the active session`() async throws {
let rosterDir = acpTempDir("attrib-roster")
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
SessionRoster.save([ghost], directory: rosterDir)
let engines = ScriptedEngines(mode: "loadReplay")
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession() // activates ghost; its load refuses (unknown id)
let second = await mentor.newSession(name: "Second", pieceTitle: nil)
#expect(second != nil)
_ = await mentor.resumeSession(ghost) // refuses again
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
let secondEntry = try #require(second)
#expect(!texts(in: mentor.transcriptRows(of: secondEntry)).contains { $0.contains("does not know") })
}
/// Finish-audit: restart() REPLAYS the active transcript from the
/// engine (ADR-0007 — the engine owns the words; the pre-crash local
/// rows are replaced by the replay, not preserved).
@Test @MainActor func `restart replays the active transcript from the engine`() async throws {
/// rows are replaced by the replay, not preserved). #178: the crash is
/// driven in-process (crashNow — the kill(pid, SIGKILL) rail's twin);
/// the pid pins became transport-identity/isClosed pins.
@Test func `restart replays the active transcript from the engine`() async throws {
let rosterDir = acpTempDir("restart-roster")
let fake = makeFakeACP(at: acpTempDir("restart"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
let engines = ScriptedEngines(mode: "loadReplay")
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession()
_ = await mentor.sendPrompt("hello") // a turn lands in the active session
#expect(try !mentor.transcriptRows(of: #require(mentor.activeEntry)).isEmpty)
if let pid = mentor.childProcessIdentifier {
kill(pid, SIGKILL) // crash the child
}
let oldEngine = try #require(mentor.host.chat as? ScriptedEngine)
oldEngine.crashNow()
var crashed = false
for _ in 0 ..< 250 {
if case .crashed = mentor.phase {
@@ -453,6 +462,17 @@ struct SessionLifecycleTests {
#expect(crashed)
await mentor.restart()
// Ready again on a NEW transport; the old one is closed (the reaped pin).
var respawned = false
for _ in 0 ..< 250 {
if mentor.phase.isReady, mentor.host.chat !== oldEngine {
respawned = true
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(respawned)
#expect(oldEngine.isClosed)
// The post-restart transcript is the ENGINE's replay — the replay
// marker proves the words came from the engine, not the local copy.
let rows = try mentor.transcriptRows(of: #require(mentor.activeEntry))
+8 -6
View File
@@ -5,6 +5,8 @@
// Owner ruling (2026-11-07): the Mentor pane hosts the OPEN PIECE's
// session — the pure seam over the roster (exact pieceTitle match,
// newest-first) pinned here: match, no-match, and title-with-no-roster.
// #178: the defer pin runs IN-PROCESS over a ScriptedEngines rig at the
// EngineTransport seam — no child process.
//
import Foundation
@@ -43,14 +45,14 @@ struct SessionScopeTests {
/// replay slot is busy (another session's session/load in flight), the
/// switch DEFERS like a stream (old behavior: resumeSession refused and
/// appended a user-visible "Resume refused" row for an action the writer
/// never took). Pinned over the real client path with the fake's
/// `loadReplayHold` mode parking the replay; teardown kills the parked
/// child, so the resume task is deliberately never awaited.
/// never took). Pinned over the scripted rig's `loadReplayHold` mode
/// parking the replay; teardown closes the parked engine, so the resume
/// task is deliberately never awaited.
@MainActor
@Test func `scope switch defers behind an in-flight replay without refusing`() async throws {
let dir = acpTempDir("scope-defer")
let fake = makeFakeACP(at: dir, mode: "loadReplayHold")
let model = MentorSessionModel(binaryPath: fake, rosterDirectory: dir)
let rosterDir = acpTempDir("scope-defer")
let engines = ScriptedEngines(mode: "loadReplayHold")
let model = engines.makeMentor(rosterDirectory: rosterDir)
defer { model.shutdown() }
await model.openSession() // empty roster — creates the default session, completes
guard case .ready = model.phase else {
+12 -9
View File
@@ -4,7 +4,9 @@
//
// #177 (S2): the typed transcript rail's pins, own file — ACPClientTests
// crossed its type-body ceiling with them (MCPToolsPromoteTests split
// precedent; the shared fake-ACP helpers stay in ACPClientTests).
// precedent). #178: runs IN-PROCESS over ScriptedEngines rigs at the
// EngineTransport seam — no child process; the real stdio wire contract
// is guarded by EngineSmokeTests.
//
// ## Scenario: typed transcript rail (mirror — source: MentorSessionModel.swift)
// From #177
@@ -22,14 +24,15 @@ import Foundation
import Testing
struct TranscriptRailTests {
/// #177 (S2): the typed rail's type-fact pins, driven through the fake
/// ACP — a completed turn's rows carry speaker and notice as data: the
/// prompt renders as the user row (unprefixed), the streamed reply as
/// agent conversation, and NO stored body holds a speaker prefix.
/// #177 (S2): the typed rail's type-fact pins, driven through the
/// scripted engine — a completed turn's rows carry speaker and notice
/// as data: the prompt renders as the user row (unprefixed), the
/// streamed reply as agent conversation, and NO stored body holds a
/// speaker prefix.
@MainActor
@Test func `completed turn types rows and stores no speaker prefix`() async {
let fake = makeFakeACP(at: acpTempDir("typed-turn"))
let model = MentorSessionModel(binaryPath: fake)
let engines = ScriptedEngines()
let model = engines.makeMentor()
defer { model.shutdown() }
await model.openSession()
await model.sendPrompt("hello mentor")
@@ -53,8 +56,8 @@ struct TranscriptRailTests {
/// by data).
@MainActor
@Test func `refusal mode lands the typed agent refusal row`() async {
let fake = makeFakeACP(at: acpTempDir("typed-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")