diff --git a/AGENTS.md b/AGENTS.md index b4ed37a..0e94628 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (6596 symbols, 30075 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (6752 symbols, 31140 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -179,6 +179,8 @@ This project is indexed by GitNexus as **museion** (6596 symbols, 30075 relation - A model-owned real-clock ticker races a test's injected decisive ticks — a >1 s main-actor stall lets the live ticker complete a met goal first, flipping pins on elapsed-time text; give `start(...)` a `spawnsTicker: Bool = true` seam and opt machine tests out (#162) - Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30) - Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134) +- `xcresulttool totalTestCount` counts a Swift Testing parameterized `@Test` as ONE test — its per-argument executions are `nodeType: "Arguments"` children; reconcile executed-count arithmetic from the children, not the function total (#178) +- A scripted transport double fires onCrash/onMessage BEFORE resuming the continuation it answers — resume-first lets the awaiting task close its assertion window (confirmation count 0) before the callback lands (#178) - Read the xcresult bundle only AFTER xcodebuild exits — `ls -td | head -1` inside the test command races bundle finalization and reports a phantom missing path while the run itself is green (#33) - A `grep -c` printing 0 exits nonzero and breaks a `&&` chain — the later suite never runs and its stale xcresult reads as the final result; run each verification gate as its own command (#177) - Under the delegation harness's ~420 s foreground cap a cold full `xcodebuild test` dies mid-build — `build-for-testing` then `test-without-building` splits the cost and the warm suite stays under (#177) @@ -203,6 +205,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-09 | [20261109-issue178-extract-engine-host-transport-seam_log.md](docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md) | | 2026-11-09 | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](docs/devlog/20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | | 2026-11-09 | [20261109-issue183-shrink-agentsmd_log.md](docs/devlog/20261109-issue183-shrink-agentsmd_log.md) | | 2026-11-05 | [20261105-issue175-nous-portal-provider_log.md](docs/devlog/20261105-issue175-nous-portal-provider_log.md) | @@ -213,5 +216,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-11-04 | [20261104-issue163-cold-turkey-calibration-gate-calm_log.md](docs/devlog/20261104-issue163-cold-turkey-calibration-gate-calm_log.md) | | 2026-11-04 | [20261104-issue162-cold-turkey-writing-lock-integration_log.md](docs/devlog/20261104-issue162-cold-turkey-writing-lock-integration_log.md) | | 2026-11-04 | [20261104-issue161-cold-turkey-goal-engine_log.md](docs/devlog/20261104-issue161-cold-turkey-goal-engine_log.md) | -| 2026-11-04 | [20261104-issue160-cold-turkey-contract-render_log.md](docs/devlog/20261104-issue160-cold-turkey-contract-render_log.md) | diff --git a/Museion/ACPEngineClient.swift b/Museion/ACPEngineClient.swift index 5c79dfa..a57e535 100644 --- a/Museion/ACPEngineClient.swift +++ b/Museion/ACPEngineClient.swift @@ -108,6 +108,11 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { var onCrash: (@Sendable () -> Void)? /// stderr lines (engine logs) — surfaced for the restart prompt's details. var onStderrLine: (@Sendable (String) -> Void)? + /// Every notification (method + params), in wire order (#178: the + /// EngineTransport seam's message rail). Always set before start() — the + /// host does it from MainActor, and process.run() provides the + /// happens-before for the queue-confined reads below. + var onMessage: (@Sendable (String, JSONValue?) -> Void)? /// #137 (S4, ADR-0014): one Hermes profile per LLM surface — the chat /// engine keeps the default `museion`; pass engines spawn `-p museion-passN`. @@ -124,9 +129,9 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { process.processIdentifier } - /// Spawn the child. `onMessage` receives every notification (method + - /// params), in wire order. - func start(onMessage: @escaping @Sendable (_ method: String, _ params: JSONValue?) -> Void) throws { + /// Spawn the child. Notifications (method + params) arrive on `onMessage` + /// in wire order; set it before calling. + func start() throws { guard !started else { return } started = true // A crashed engine closes the pipe; ignoring SIGPIPE turns a kill-signal @@ -137,13 +142,15 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { self?.queue.async { self?.failAll("engine exited (code \(self?.process.terminationStatus ?? 0))") } } readStderr() - readStdout(onMessage: onMessage) + readStdout() } /// Send a JSON-RPC request and await its matching response result. /// A request that gets no answer within `timeout` fails — a hung engine /// must surface as an error (→ restart prompt), never an eternal await. - func request(_ method: String, params: JSONValue? = nil, timeout: TimeInterval = 15) async throws -> JSONValue? { + /// (No default arguments: the only caller is EngineHost, which rides the + /// seam — `EngineTransport.request`'s convenience owns the default shape.) + func request(_ method: String, params: JSONValue?, timeout: TimeInterval) async throws -> JSONValue? { let id = queue.sync { currentID += 1 return currentID @@ -178,8 +185,9 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { } } - /// Send a JSON-RPC notification (no id, no response). - func notify(_ method: String, params: JSONValue? = nil) { + /// Send a JSON-RPC notification (no id, no response). Always called with + /// explicit params (session/cancel) — no default, same reasoning as request. + func notify(_ method: String, params: JSONValue?) { let payload: [String: Any] = [ "jsonrpc": "2.0", "method": method, @@ -261,7 +269,7 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { } } - private func readStdout(onMessage: @escaping @Sendable (String, JSONValue?) -> Void) { + private func readStdout() { stdoutPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in let data = handle.availableData guard !data.isEmpty else { @@ -269,12 +277,12 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { self?.queue.async { self?.failAll("engine stdout closed (EOF)") } return } - self?.queue.async { self?.ingest(data, onMessage: onMessage) } + self?.queue.async { self?.ingest(data) } } } /// Buffer incoming bytes, split on \n, decode each line as one JSON-RPC message. - private func ingest(_ data: Data, onMessage: @escaping @Sendable (String, JSONValue?) -> Void) { + private func ingest(_ data: Data) { buffer.append(data) // ponytail: 1 MB line cap — a corrupt/hostile engine streaming one // newline-free line would otherwise grow the buffer unbounded. @@ -288,11 +296,11 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { guard !line.isEmpty, let json = try? JSONSerialization.jsonObject(with: line), let object = json as? [String: Any] else { continue } - dispatch(object, onMessage: onMessage) + dispatch(object) } } - private func dispatch(_ object: [String: Any], onMessage: @escaping @Sendable (String, JSONValue?) -> Void) { + private func dispatch(_ object: [String: Any]) { let id = object["id"] as? Int let method = object["method"] as? String @@ -327,7 +335,7 @@ final nonisolated class ACPEngineClient: @unchecked Sendable { // Notification. if let method { - onMessage(method, object["params"].map { JSONValue($0) }) + onMessage?(method, object["params"].map { JSONValue($0) }) } } } diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 915bff1..8731e97 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -72,8 +72,9 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te ## ACP bridge -- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p `; no Swift SDK exists). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. -- `MentorSessionModel.swift` — @MainActor @Observable. Lazy spawn on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state). Handshake compares BASE versions (the gate records the derived `0.21.5+build`, the handshake answers the base — raw equality fabricates drift; never blocks). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot`) over their own client into a TRANSIENT unrostered transcript, torn down at the verdict (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session). `PassReadiness` per kind: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path). +- `EngineHost.swift` — #178: the engine lifecycle owner + the `EngineTransport` seam. The seam is the whole engine surface — `onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()` — with two adapters: `ACPEngineClient` (real stdio, production) and `ScriptedEngine` (in-process, MuseionTests — engine-behaviour tests run without child processes). `EngineHost` (@MainActor) owns spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived `0.21.5+build`, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (`startChat()`/`killChat()`) plus at most one one-shot engine (`withOneShot(profile:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides `DispatchQueue.main.async`, never `Task { @MainActor }` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` ONLY — a pass crash must not flip the pane. `nonisolated(unsafe)` mirrors close children in deinit. +- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p `; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. +- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path). - `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm). - Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss). diff --git a/Museion/EngineHost.swift b/Museion/EngineHost.swift new file mode 100644 index 0000000..b0dfea4 --- /dev/null +++ b/Museion/EngineHost.swift @@ -0,0 +1,282 @@ +// +// EngineHost.swift +// Museion +// +// #178 (slice A): the engine lifecycle policy, extracted from +// MentorSessionModel. The host owns spawn/handshake/teardown for the +// resident chat engine and the one-shot pass engines, entirely behind the +// EngineTransport seam; the model keeps session + turn coordination only. +// + +import Foundation +import os + +/// The transport seam (#178): everything an engine speaks, nothing about +/// processes. Two adapters: ACPEngineClient (real stdio, production) and +/// the scripted in-process engine (MuseionTests, engine-behaviour tests). +nonisolated protocol EngineTransport: AnyObject, Sendable { + /// Every notification, in wire order. + var onMessage: (@Sendable (String, JSONValue?) -> Void)? { get set } + /// Fires when the engine dies unexpectedly — never on close(). + var onCrash: (@Sendable () -> Void)? { get set } + /// stderr lines (engine logs). + var onStderrLine: (@Sendable (String) -> Void)? { get set } + /// Spawn the engine. Idempotent per lifecycle. Throws on spawn failure. + func start() throws + func request(_ method: String, params: JSONValue?, timeout: TimeInterval) async throws -> JSONValue? + /// Fire-and-forget notification (session/cancel). + func notify(_ method: String, params: JSONValue?) + /// Graceful teardown. Idempotent; never fires onCrash. + func close() +} + +extension ACPEngineClient: EngineTransport {} + +extension EngineTransport { + /// The seam's default request timeout (15 s — ACPEngineClient's own + /// default; a protocol witness's default is invisible through the + /// existential, so the convenience restores the pre-seam call shape). + /// Turns and resumes pass their own explicit long timeouts. + func request(_ method: String, params: JSONValue?) async throws -> JSONValue? { + try await request(method, params: params, timeout: 15) + } +} + +/// The engine lifecycle owner (#178): one resident chat transport plus at +/// most one one-shot pass transport, spawn/handshake/teardown policy for +/// both. Session and turn coordination stay in MentorSessionModel — the +/// host knows profiles and handshakes, never transcripts. +@MainActor +final class EngineHost { + struct HostError: Error, CustomStringConvertible { + let message: String + var description: String { + message + } + } + + enum ChatStart { + // swiftlint:disable:next identifier_name + case up(version: String?, note: String?) + case failed(String) // the stderr line for the crash card + } + + /// initialize params (both handshakes) — protocolVersion 1, no client + /// capabilities, clientInfo Museion/0.1; exactly the model's original + /// handshake (#14). + nonisolated static let initializeParams: JSONValue = .object([ + "protocolVersion": .number(1), + "clientCapabilities": .object([:]), + "clientInfo": .object([ + "name": .string("Museion"), + "title": .string("Museion"), + "version": .string("0.1"), + ]), + ]) + + /// The initialize request timeout — the client's own 15 s default, + /// stated here because the seam's witness takes no defaults. + private static let initializeTimeout: TimeInterval = 15 + + /// profile -> transport factory. Production default: + /// ACPEngineClient(binaryPath:profile:). Reads binaryPath at SPAWN time + /// (the pane writes the path after the host exists). + var makeTransport: (String) -> any EngineTransport = { profile in + // Placeholder required so init may form the weak-self closure below; + // unreachable — init rebinds immediately. + ACPEngineClient(binaryPath: "", profile: profile) + } + + var binaryPath: String? + /// The gate's recorded engine version (state.json) — injectable for tests. + var recordedVersionProvider: () -> String? = { EngineProbe.readStateRecord()?.engineVersion } + + // MainActor hooks; the HOST wraps each in DispatchQueue.main.async when + // wiring a transport (the #28 main-queue FIFO wire-order finding — do NOT + // use Task { @MainActor }). + var onNotification: ((String, JSONValue?) -> Void)? + var onCrash: (() -> Void)? + var onStderrLine: ((String) -> Void)? + + private(set) var chat: (any EngineTransport)? + private(set) var oneShot: (any EngineTransport)? + + /// ponytail: a deinit can't touch MainActor state — the transport + /// references are held in these unsafe mirrors solely so deinit can close + /// them. Assigned wherever chat/oneShot is assigned. + private nonisolated(unsafe) var chatRef: (any EngineTransport)? + private nonisolated(unsafe) var oneShotRef: (any EngineTransport)? + + init() { + // Reads binaryPath at spawn time, not capture time. The empty-path + // fallback is unreachable: both spawners guard binaryPath != nil + // before calling the factory. + makeTransport = { [weak self] profile in + ACPEngineClient(binaryPath: self?.binaryPath ?? "", profile: profile) + } + } + + deinit { + // close() is thread-safe (the transport's own serial queue) and idempotent. + chatRef?.close() + oneShotRef?.close() + } + + var hasChat: Bool { + chat != nil + } + + var isOneShotRunning: Bool { + oneShot != nil + } + + /// The chat child's pid — internal observation surface for the + /// finish-audit restart pin (tests kill the child to drive a real crash). + var chatChildPid: pid_t? { + (chat as? ACPEngineClient)?.childProcessIdentifier + } + + var oneShotChildPid: pid_t? { + (oneShot as? ACPEngineClient)?.childProcessIdentifier + } + + /// Spawn + handshake the resident chat engine. + /// - nil binaryPath -> .failed("no engine binary path available") + /// - spawn throws -> .failed("spawn failed: ") + /// - initialize request fails -> .failed("handshake failed: ") + /// - success -> .up(version:note:) where note is the ADVISORY drift note. + /// On any failure leave NOTHING half-spawned (close + drop the transport). + func startChat() async -> ChatStart { + // Defensive only — unreachable via the model's phase machine (openSession + // guards .idle; respawn/shutdown kill first); keeps a racing caller from + // spawning a second engine and leaking the first. + guard chat == nil else { return .failed("chat engine already running") } + guard binaryPath != nil else { return .failed("no engine binary path available") } + let transport = makeTransport("museion") + wireChatHooks(transport) + do { + try transport.start() + } catch { + transport.close() + return .failed("spawn failed: \(error.localizedDescription)") + } + do { + let version = try await handshake(transport) + chat = transport + chatRef = transport + return .up(version: version, note: driftNote(for: version)) + } catch { + transport.close() + return .failed("handshake failed: \(error.localizedDescription)") + } + } + + /// Teardown of the resident engine (respawn, shutdown). Idempotent. + func killChat() { + chat?.close() + chat = nil + chatRef = nil + } + + /// One-shot residency (ADR-0014): fresh transport on `profile`, slim + /// initialize handshake (version NOT recorded — engineVersion/versionNote + /// display the chat engine), run `body`, then teardown — spawn per run, + /// never resident past the body's end, even on thrown errors. + func withOneShot(profile: String, _ body: @MainActor (any EngineTransport) async -> R) async throws -> R { + guard oneShot == nil else { throw HostError(message: "one-shot engine already running") } + guard binaryPath != nil else { throw HostError(message: "no engine binary path available") } + let transport = makeTransport(profile) + // onMessage ONLY — onCrash/onStderrLine stay nil for the one-shot: a + // pass crash must NOT flip the pane; the failed pending request lands + // the honest row instead (KNOWN EDGE #137, accepted v1). + transport.onMessage = { [weak self] method, params in + DispatchQueue.main.async { + self?.onNotification?(method, params) + } + } + // The slot is claimed BEFORE the spawn awaits (review #178: the old + // model set passClient before any suspension; claiming only after the + // handshake left `oneShot` false — and the at-most-one contract + // unenforced — across spawn+handshake). The defer sits with the claim + // so every exit path (throw included) closes and releases. + oneShot = transport + oneShotRef = transport + defer { + transport.close() + oneShot = nil + oneShotRef = nil + } + do { + try transport.start() + } catch { + throw HostError(message: "spawn failed: \(error.localizedDescription)") + } + do { + _ = try await transport.request("initialize", params: Self.initializeParams, timeout: Self.initializeTimeout) + } catch { + throw HostError(message: "handshake failed: \(error.localizedDescription)") + } + return await body(transport) + } + + /// App-quit teardown: everything closed, idempotent. + func shutdownAll() { + killChat() + oneShot?.close() + oneShot = nil + oneShotRef = nil + } + + /// Base version of a version string — the part before `+` build metadata + /// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`. + nonisolated static func baseVersion(of version: String) -> String { + version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version + } + + /// Resident-chat hook wiring: onMessage + onCrash + onStderrLine, each + /// host-wrapped in DispatchQueue.main.async. NOT Task { @MainActor }: a + /// Task must first win cooperative-pool time, which hundreds of parallel + /// jobs can starve for seconds (#28 test finding); the main queue is FIFO + /// with the continuation resume, so wire order — replay updates before + /// the load response — is guaranteed, not probable. + private func wireChatHooks(_ transport: any EngineTransport) { + transport.onMessage = { [weak self] method, params in + DispatchQueue.main.async { + self?.onNotification?(method, params) + } + } + transport.onCrash = { [weak self] in + DispatchQueue.main.async { + self?.onCrash?() + } + } + transport.onStderrLine = { [weak self] line in + DispatchQueue.main.async { + self?.onStderrLine?(line) + } + } + } + + /// initialize (map decisions: advisory version verify). Sessions are + /// created separately — the bridge is session-agnostic. + private func handshake(_ transport: any EngineTransport) async throws -> String? { + let result = try await transport.request("initialize", params: Self.initializeParams, timeout: Self.initializeTimeout) + return result?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue + } + + /// Advisory version verify against state.json's recorded version (map + /// decision: one os_log line + both versions in the pane; never blocks). + /// The gate records the derived version (`acp --version` → + /// 0.21.5+2177.g735e426); the handshake answers the base version + /// (agentInfo.version → 0.21.5) — compare bases so build metadata never + /// fabricates drift. + private func driftNote(for version: String?) -> String? { + guard let version, let recorded = recordedVersionProvider() else { return nil } + let recordedBase = Self.baseVersion(of: recorded) + let runningBase = Self.baseVersion(of: version) + guard recordedBase != runningBase else { return nil } + Logger(subsystem: "com.babylondreams.Museion", category: "acp") + .warning("engine version drift: running \(version, privacy: .public), recorded \(recorded, privacy: .public)") + return "Engine \(version) differs from the recorded \(recorded)" + } +} diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift index 5730319..e88a28a 100644 --- a/Museion/MentorSessionModel.swift +++ b/Museion/MentorSessionModel.swift @@ -14,26 +14,28 @@ // filter, and New Post prefill switch on typed data with identical // rendering. // -// M0 ACP bridge (#14): the pane's @Observable model — lazy bridge lifecycle, -// prompt streaming, fix-card render, crash → restart prompt. +// M0 ACP bridge (#14): the pane's @Observable model — session + turn +// coordination. The engine lifecycle itself lives in EngineHost behind +// the EngineTransport seam (#178): the model owns transcripts, sessions, +// and turn outcomes; the host owns spawn/handshake/teardown. // #28 (S2.3): multi-session — a persisted roster of engine-owned sessions // (session/new, session/load, session/fork, /compress on the wire), one // transcript per session, and the same-named ACTIVE surface (rows, buffers, // sendPrompt, stop) so the pane and every existing test read unchanged. // #137 (S4): per-surface engines — passes run on their own one-shot -// engine and stream into a transient unrostered transcript; the chat -// engine gains the model-change restart posture (requestRestart). +// engine (host.withOneShot) and stream into a transient unrostered +// transcript; the chat engine gains the model-change restart posture +// (requestRestart). // // swiftlint:disable file_length // One model, one lifecycle story: the class body (state + session rail) and -// the same-file turn-core/engine-lifecycle extension read together; the pass -// engine's stored state can't live in another file (private, MainActor). +// the same-file turn-core extension read together; the pass surface's stored +// state can't live in another file (private, MainActor). // Extraction ticket follows PostsModel's precedent if the file keeps growing. import Foundation import Observation -import os /// One rendered row in the pane transcript. Text + tool calls first-class, /// the rest raw (map decision: rendering fidelity). Nonisolated (#177 S2, @@ -261,12 +263,15 @@ final class MentorSessionModel { /// (ponytail: redirect here instead of making every rig inject a directory). private let rosterDirectory: String? - private var client: ACPEngineClient? + /// #178: the engine lifecycle owner — chat + one-shot transports, + /// handshakes, teardown. The model is its sole owner (model deallocation + /// closes the children via the host's deinit mirrors). + let host: EngineHost private var lastPrompt: String? - /// #137 (S4): the TRANSIENT pass engine — spawned per pass run on its - /// own profile, torn down at the verdict, never rostered (#129: passes + /// #137 (S4): the TRANSIENT pass rail — the pass engine itself lives in + /// the host (withOneShot); these two stay model state because + /// stopStreaming and handleNotification read them mid-run (#137: passes /// are one-shot; only the chat engine's sessions are rostered). - private var passClient: ACPEngineClient? private var passWireId: String? private var passCancelRequested = false /// #137: a model-change restart requested mid-turn — fires at turn end @@ -286,16 +291,18 @@ final class MentorSessionModel { /// fallback — injectable so tests never read the machine's real login. var portalAuthPath: String = PortalAuth.defaultAuthPath - /// The gate's winning binary path (no re-probe — map decision). Set by the - /// app when the gate passes; tests inject directly. - var binaryPath: String? + /// The gate's winning binary path (no re-probe — map decision). Set by + /// the app when the gate passes; tests inject directly. didSet forwards + /// to the host (init sets the host directly — didSet doesn't fire there). + var binaryPath: String? { + didSet { host.binaryPath = binaryPath } + } /// Session cwd is ~ — neutral for a resident mentor with no Piece context (map decision). var cwdProvider: () -> String = { NSHomeDirectory() } - /// The gate's recorded engine version (state.json) — injectable for tests. - var recordedVersionProvider: () -> String? = { EngineProbe.readStateRecord()?.engineVersion } - init(binaryPath: String? = nil, rosterDirectory: String? = nil) { + init(host: EngineHost = EngineHost(), binaryPath: String? = nil, rosterDirectory: String? = nil) { + self.host = host self.binaryPath = binaryPath if let rosterDirectory { self.rosterDirectory = rosterDirectory @@ -305,48 +312,36 @@ final class MentorSessionModel { self.rosterDirectory = nil } roster = SessionRoster.load(directory: self.rosterDirectory) + // Wire the host last — the hook closures capture self, which Swift + // only allows once every stored property is initialized. + host.binaryPath = binaryPath + host.onNotification = { [weak self] method, params in + self?.handleNotification(method: method, params: params) + } + host.onCrash = { [weak self] in + self?.handleCrash() + } + host.onStderrLine = { [weak self] line in + self?.appendStderr(line) + } } private var activeTranscript: SessionTranscript? { activeEntry.flatMap { transcripts[$0.sessionId] } } - deinit { - // nonisolated deinit (Swift 6): close() is nonisolated-safe on the client. - shutdownClientDirectly() - } - /// The engine child's pid — internal observation surface for the /// finish-audit restart pin (kills the child to drive a real crash). var childProcessIdentifier: pid_t? { - client?.childProcessIdentifier + host.chatChildPid } /// App-quit teardown (#14): close the engine children cleanly. Idempotent. func shutdown() { - teardownPassEngine() - shutdownClientDirectly() - client = nil - clientRef = nil + host.shutdownAll() phase = .idle } - /// nonisolated deinit + MainActor shutdown share this: client.close() is - /// thread-safe (its own serial queue) and idempotent. The pass child - /// rides the same rail (#137) — deinit must close it too. - private nonisolated func shutdownClientDirectly() { - clientRef?.close() - passClientRef?.close() - } - - /// ponytail: a deinit can't touch MainActor state — the client reference is - /// held in this unsafe mirror solely so deinit can close it. Assigned - /// wherever `client` is assigned. - private nonisolated(unsafe) var clientRef: ACPEngineClient? - - /// The pass engine's deinit mirror (clientRef pattern, #137). - private nonisolated(unsafe) var passClientRef: ACPEngineClient? - /// Lazy spawn on first session open. Idempotent per lifecycle. Ensures /// ONE session exists: the default freeform 'Mentor' session on first /// open, otherwise the newest rostered entry activated with a FRESH @@ -354,8 +349,10 @@ final class MentorSessionModel { func openSession() async { guard phase == .idle else { return } phase = .starting - await startEngine() - guard case .starting = phase else { return } // startEngine crashed instead + guard await applyChatStart(host.startChat()) else { return } + // A crash during startup flipped the phase — handleCrash owns that + // path; never hand a crashed engine to ensureDefaultSession. + guard case .starting = phase else { return } await ensureDefaultSession() } @@ -367,81 +364,22 @@ final class MentorSessionModel { await respawn() } - private func startEngine() async { - guard let binaryPath else { - phase = .crashed(lastPrompt: nil) - stderrTail = ["no engine binary path available"] - return - } - let client = ACPEngineClient(binaryPath: binaryPath) - self.client = client - clientRef = client - // All three hops ride DispatchQueue.main.async, NOT Task { @MainActor }: - // a Task must first win cooperative-pool time, which hundreds of - // parallel jobs can starve for seconds (#28 test finding); the main - // queue is FIFO with the continuation resume, so wire order — replay - // updates before the load response — is guaranteed, not probable. - client.onCrash = { [weak self] in - DispatchQueue.main.async { - self?.handleCrash() - } - } - client.onStderrLine = { [weak self] line in - DispatchQueue.main.async { - self?.appendStderr(line) - } - } - do { - try client.start { [weak self] method, params in - DispatchQueue.main.async { - self?.handleNotification(method: method, params: params) - } - } - } catch { + /// Map a host chat start onto the phase surfaces: .failed lands the + /// crash posture (phase + stderrTail — the stderr line for the crash + /// card), .up records the version pair. Returns false on failure. Only + /// .up writes engineVersion/versionNote — a failed respawn keeps the old + /// values (today's semantics). + private func applyChatStart(_ start: EngineHost.ChatStart) -> Bool { + if case let .failed(line) = start { phase = .crashed(lastPrompt: lastPrompt) - stderrTail = ["spawn failed: \(error.localizedDescription)"] - return + stderrTail = [line] + return false } - - do { - try await handshake(client) - } catch { - phase = .crashed(lastPrompt: lastPrompt) - stderrTail = ["handshake failed: \(error.localizedDescription)"] + if case let .up(version, note) = start { + engineVersion = version + versionNote = note } - } - - /// initialize (map decisions: advisory version verify). Sessions are - /// created separately (#28) — the bridge is session-agnostic. - private func handshake(_ client: ACPEngineClient) async throws { - let params: JSONValue = .object([ - "protocolVersion": .number(1), - "clientCapabilities": .object([:]), - "clientInfo": .object([ - "name": .string("Museion"), - "title": .string("Museion"), - "version": .string("0.1"), - ]), - ]) - let result = try await client.request("initialize", params: params) - let version = result?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue - engineVersion = version - - // Advisory version verify against state.json's recorded version - // (map decision: one os_log line + both versions in the pane; never blocks). - // The gate records the derived version (`acp --version` → 0.21.5+2177.g735e426); - // the handshake answers the base version (agentInfo.version → 0.21.5) — compare - // bases so build metadata never fabricates drift. - var note: String? - if let version { - let recorded = recordedVersionProvider() - if let recorded, Self.baseVersion(of: recorded) != Self.baseVersion(of: version) { - note = "Engine \(version) differs from the recorded \(recorded)" - Logger(subsystem: "com.babylondreams.Museion", category: "acp") - .warning("engine version drift: running \(version, privacy: .public), recorded \(recorded, privacy: .public)") - } - } - versionNote = note + return true } /// After an engine start: exactly one active session (#28). The newest @@ -478,7 +416,7 @@ final class MentorSessionModel { /// newest-first, activate. Nil when the engine isn't ready or refuses. @discardableResult func newSession(name: String, pieceTitle: String?) async -> SessionEntry? { - guard phase.isReady, client != nil else { return nil } + guard phase.isReady, host.hasChat else { return nil } return await createSession(name: name, pieceTitle: pieceTitle) } @@ -510,11 +448,11 @@ final class MentorSessionModel { appendRow(.text("Session refused — the mentor is mid-turn.", .system, .refused), to: activeEntry?.sessionId) return nil } - guard let client else { return nil } + guard let chat = host.chat else { return nil } do { // Adapter ≥0.21.5 requires mcpServers on every session/new (#44 // invariant); Museion ships none, so the honest empty list. - let result = try await client.request( + let result = try await chat.request( "session/new", params: .object([ "cwd": .string(cwdProvider()), @@ -552,7 +490,7 @@ final class MentorSessionModel { /// the entry stays and an explanatory row lands; never a fabricated /// empty session. func resumeSession(_ entry: SessionEntry) async -> Bool { - guard phase.isReady, let client else { return false } + guard phase.isReady, let chat = host.chat else { return false } guard !isStreaming else { // "Not now" refusals target the ACTIVE session — they are about // the writer's action right now, not the entry's state. @@ -574,7 +512,7 @@ final class MentorSessionModel { // Replay ordering: the adapter writes the history notifications // BEFORE the load response, and the MainActor Task pipeline // preserves that order — same reliance as live streaming. - let result = try await client.request( + let result = try await chat.request( "session/load", params: .object([ "cwd": .string(cwdProvider()), @@ -675,9 +613,9 @@ final class MentorSessionModel { /// sessionId from the wire is a refusal (honest row, nil return). @discardableResult func forkActiveSession() async -> SessionEntry? { - guard phase.isReady, let client, let source = activeEntry, !isStreaming else { return nil } + guard phase.isReady, let chat = host.chat, let source = activeEntry, !isStreaming else { return nil } do { - let result = try await client.request( + let result = try await chat.request( "session/fork", params: .object([ "cwd": .string(cwdProvider()), @@ -767,12 +705,12 @@ extension MentorSessionModel { /// The pass engine's pid — internal test observable (teardown pins). var passEngineChildPid: pid_t? { - passClient?.childProcessIdentifier + host.oneShotChildPid } /// True while a pass engine is resident (spawn → verdict). var isPassEngineRunning: Bool { - passClient != nil + host.isOneShotRunning } /// #137 (S4): the Run Pass posture — is the pass profile's provider @@ -871,7 +809,7 @@ extension MentorSessionModel { appendRow(.text("Pick or start a session to chat — the pass transcript is read-only.", .system, .refused), to: sid) return .failed } - guard let client else { return .failed } + guard let chat = host.chat else { return .failed } isStreaming = true defer { isStreaming = false @@ -882,7 +820,7 @@ extension MentorSessionModel { firePendingScopeIfRequested() } return await turnCore( - client: client, + transport: chat, wireSid: sid, key: sid, prompt: prompt, @@ -899,7 +837,7 @@ extension MentorSessionModel { /// buffer flush — one implementation, two engines. #177 (S2): the label /// row arrives fully typed; its body is the display text alone. private func turnCore( - client: ACPEngineClient, + transport: any EngineTransport, wireSid: String, key: String, prompt: String, @@ -923,7 +861,7 @@ extension MentorSessionModel { isStreaming = false } do { - let result = try await client.request( + let result = try await transport.request( "session/prompt", params: .object([ "sessionId": .string(wireSid), @@ -1003,14 +941,15 @@ extension MentorSessionModel { } /// The shared ONE-SHOT engine rail (#137 passes, #122 Blind Read): a - /// fresh engine on `profile`, a transient unrostered transcript, one - /// turn, teardown at its end. Same lifecycles for both riders — the - /// cancel rail (stopStreaming) and the read-only composer guard key on - /// the transient entry and need no per-rider branches. `name` ("Pass 1" - /// / "Blind Read") composes the entry label — callers can't pass a - /// title-inconsistent one. + /// fresh engine on `profile` via the host (spawn → slim handshake → + /// body → teardown — never resident past the body's end, even on thrown + /// errors), a transient unrostered transcript, one turn. Same lifecycles + /// for both riders — the cancel rail (stopStreaming) and the read-only + /// composer guard key on the transient entry and need no per-rider + /// branches. `name` ("Pass 1" / "Blind Read") composes the entry label — + /// callers can't pass a title-inconsistent one. private func runOneShot(profile: String, name: String, prompt: String, pieceTitle: String) async -> TurnOutcome { - guard phase.isReady, !isStreaming, passClient == nil, let binaryPath else { return .failed } + guard phase.isReady, !isStreaming, !host.isOneShotRunning, host.binaryPath != nil else { return .failed } let label = "\(name) · \(pieceTitle)" // The transient surface: a fresh transcript under the pass key and a // pass entry that lives only for this run — never rostered, never @@ -1022,44 +961,46 @@ extension MentorSessionModel { isStreaming = true defer { isStreaming = false - teardownPassEngine() + // The host's own teardown ran when the body returned — BEFORE + // this defer — so the engine is already down when the pending + // rails fire (the old teardownPassEngine ordering, preserved). firePendingRestartIfRequested() // Owner ruling (2026-11-07): a piece switch deferred behind the // pass fires at the verdict — the in-flight transcript was never // interrupted. firePendingScopeIfRequested() } - let pass = ACPEngineClient(binaryPath: binaryPath, profile: profile) - passClient = pass - passClientRef = pass - // KNOWN EDGE (#137, accepted v1): a CHAT-engine crash mid-pass flips - // the pane to the crash card while the pass keeps streaming — the - // pass turn still completes and advances state. Symmetrically, a - // pass-engine crash must NOT flip the pane: onCrash stays nil here — - // the failed pending request lands the honest row below instead. + let outcome: TurnOutcome do { - // Same routing as the chat client (DispatchQueue.main.async keeps - // wire order — see startEngine). - try pass.start { [weak self] method, params in - DispatchQueue.main.async { - self?.handleNotification(method: method, params: params) - } + outcome = try await host.withOneShot(profile: profile) { transport in + await self.oneShotTurn(transport: transport, label: label, prompt: prompt) } - // Slim initialize — engineVersion/versionNote display the CHAT - // engine and must not be overwritten by the pass engine's answer. - _ = try await pass.request("initialize", params: .object([ - "protocolVersion": .number(1), - "clientCapabilities": .object([:]), - "clientInfo": .object([ - "name": .string("Museion"), - "title": .string("Museion"), - "version": .string("0.1"), + } catch { + appendRow(.text("\(label) failed — \(error.localizedDescription)", .system, .failed), to: Self.passTranscriptKey) + outcome = .failed + } + // The run is over (success OR throw): the one-shot rail resets. + passWireId = nil + passCancelRequested = false + return outcome + } + + /// The one-shot body (#178): session/new on the fresh transport, the + /// spawn-window cancel check, then the turn. Runs inside + /// host.withOneShot — engine teardown is the host's, never this rail's. + private func oneShotTurn( + transport: any EngineTransport, + label: String, + prompt: String, + ) async -> TurnOutcome { + do { + let result = try await transport.request( + "session/new", + params: .object([ + "cwd": .string(cwdProvider()), + "mcpServers": .array([]), ]), - ])) - let result = try await pass.request("session/new", params: .object([ - "cwd": .string(cwdProvider()), - "mcpServers": .array([]), - ])) + ) guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else { appendRow(.text("\(label) failed — the engine refused a session.", .system, .failed), to: Self.passTranscriptKey) return .failed @@ -1075,18 +1016,13 @@ extension MentorSessionModel { appendRow(.text("\(label) cancelled.", .system, .plain), to: Self.passTranscriptKey) return .cancelled } - return await turnCore(client: pass, wireSid: passWireId ?? "", key: Self.passTranscriptKey, - prompt: prompt, labelContent: .text(label, .system, .plain)) - } - - /// Kill the pass engine and clear its rail — at the verdict (the defer - /// above) and at shutdown. Idempotent. - private func teardownPassEngine() { - passClient?.close() - passClient = nil - passClientRef = nil - passWireId = nil - passCancelRequested = false + return await turnCore( + transport: transport, + wireSid: passWireId ?? "", + key: Self.passTranscriptKey, + prompt: prompt, + labelContent: .text(label, .system, .plain), + ) } /// Stop button while a turn streams (map decision: cancel wired to @@ -1104,12 +1040,12 @@ extension MentorSessionModel { if activeEntry?.sessionId == Self.passTranscriptKey { passCancelRequested = true if let passSid = passWireId { - passClient?.notify("session/cancel", params: .object(["sessionId": .string(passSid)])) + host.oneShot?.notify("session/cancel", params: .object(["sessionId": .string(passSid)])) } return } guard let sid = activeEntry?.sessionId else { return } - client?.notify("session/cancel", params: .object(["sessionId": .string(sid)])) + host.chat?.notify("session/cancel", params: .object(["sessionId": .string(sid)])) } /// #137 (S4): the model-change restart posture — Settings fires this @@ -1138,16 +1074,16 @@ extension MentorSessionModel { /// to the newest entry (strictly better UX; the single-session crash /// tests keep passing because active == newest there). private func respawn() async { - client?.close() - client = nil - clientRef = nil + host.killChat() for sid in transcripts.keys { transcripts[sid]?.streamingText = "" transcripts[sid]?.streamingThought = "" } phase = .starting - await startEngine() - guard case .starting = phase else { return } // startEngine crashed instead + guard await applyChatStart(host.startChat()) else { return } + // A crash during startup flipped the phase — handleCrash owns that + // path; never hand a crashed engine to the resume/default rail. + guard case .starting = phase else { return } if let active = activeEntry, roster.contains(active) { phase = .ready _ = await resumeSession(active) @@ -1173,12 +1109,6 @@ extension MentorSessionModel { Task { await scopeHostedSession(toOpenPieceTitle: title) } } - /// Base version of a version string — the part before `+` build metadata - /// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`. - nonisolated static func baseVersion(of version: String) -> String { - version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version - } - /// #177 (S2): the ONE agent-text sniff, shared by the live flush /// (turnCore) and the replayed agent chunk (handleNotification) — the /// engine's operational "Operation interrupted:" notice is system diff --git a/MuseionTests/ACPClientTests.swift b/MuseionTests/ACPClientTests.swift index 1cce7ab..543b84a 100644 --- a/MuseionTests/ACPClientTests.swift +++ b/MuseionTests/ACPClientTests.swift @@ -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 } } diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 117451b..00e5a40 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -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 `-spawn-log` and every `session/prompt` to `-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, `-spawn-log`, `-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/`) 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. diff --git a/MuseionTests/BlindReadTests.swift b/MuseionTests/BlindReadTests.swift index 887e5e8..e9ae459 100644 --- a/MuseionTests/BlindReadTests.swift +++ b/MuseionTests/BlindReadTests.swift @@ -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. diff --git a/MuseionTests/EngineLifecycleTests.swift b/MuseionTests/EngineLifecycleTests.swift index 9ec08d8..2b3b1b4 100644 --- a/MuseionTests/EngineLifecycleTests.swift +++ b/MuseionTests/EngineLifecycleTests.swift @@ -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) diff --git a/MuseionTests/EngineSmokeTests.swift b/MuseionTests/EngineSmokeTests.swift new file mode 100644 index 0000000..efd32e4 --- /dev/null +++ b/MuseionTests/EngineSmokeTests.swift @@ -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) + } +} diff --git a/MuseionTests/PassRunTests.swift b/MuseionTests/PassRunTests.swift index acbd355..d90e3f1 100644 --- a/MuseionTests/PassRunTests.swift +++ b/MuseionTests/PassRunTests.swift @@ -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 diff --git a/MuseionTests/ResearchCandidateTests.swift b/MuseionTests/ResearchCandidateTests.swift index 33f907c..de71789 100644 --- a/MuseionTests/ResearchCandidateTests.swift +++ b/MuseionTests/ResearchCandidateTests.swift @@ -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() diff --git a/MuseionTests/ScriptedEngine.swift b/MuseionTests/ScriptedEngine.swift new file mode 100644 index 0000000..cd2d245 --- /dev/null +++ b/MuseionTests/ScriptedEngine.swift @@ -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] = [:] + /// 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, + ) { + 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, + ) { + 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, + ) { + 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, + ) { + // 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) { + 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) +} diff --git a/MuseionTests/SessionLifecycleTests.swift b/MuseionTests/SessionLifecycleTests.swift index 7be39e3..7837d88 100644 --- a/MuseionTests/SessionLifecycleTests.swift +++ b/MuseionTests/SessionLifecycleTests.swift @@ -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)) diff --git a/MuseionTests/SessionScopeTests.swift b/MuseionTests/SessionScopeTests.swift index b035679..f679ecf 100644 --- a/MuseionTests/SessionScopeTests.swift +++ b/MuseionTests/SessionScopeTests.swift @@ -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 { diff --git a/MuseionTests/TranscriptRailTests.swift b/MuseionTests/TranscriptRailTests.swift index d203837..3ef4554 100644 --- a/MuseionTests/TranscriptRailTests.swift +++ b/MuseionTests/TranscriptRailTests.swift @@ -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") diff --git a/docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md b/docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md new file mode 100644 index 0000000..203a97f --- /dev/null +++ b/docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md @@ -0,0 +1,69 @@ +# Extract the engine host — per-surface lifecycle policy behind a transport seam + +> **Date:** 2026-11-09 +> **Type:** issue +> **Reference:** Closes #178 (git.babylondreams.de/AlexKucera/Museion, from the 2026-11-09 architecture review, mentor line step 2 of 3) + +## Goal + +Move the engine lifecycle policy — spawn, handshake, respawn-on-crash, teardown, and the per-surface residency rules (resident chat engine; on-demand one-shot pass engines per ADR-0014) — out of `MentorSessionModel` into an engine-host module over the ACP client through a narrow transport seam. A scripted in-process transport becomes the seam's second adapter so engine-behaviour tests (streaming, crash, cancel, restart, per-surface spawn) run without child processes; exactly one real-process end-to-end smoke per LLM Surface survives as the wire-contract guard, retiring the zsh fake-server rigs from logic tests (the documented real-process flake family, #30). + +## What Was Done + +- **`Museion/EngineHost.swift` (new)** — the `EngineTransport` seam (`onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()`) and `EngineHost` (@MainActor), owner of spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note, moved verbatim from the model), teardown, and per-surface residency: one resident chat engine (`startChat()` → `ChatStart` / `killChat()`) plus at most one one-shot engine (`withOneShot(profile:_:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring rides `DispatchQueue.main.async` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` only (KNOWN EDGE #137: a pass crash must not flip the pane). `nonisolated(unsafe)` mirrors close children in deinit (the old model's `clientRef` pattern relocated). +- **`ACPEngineClient`** — conforms to `EngineTransport`; `start(onMessage:)` became an `onMessage` property + `start()` (always set before start; `process.run()` provides the happens-before). Concrete `request`/`notify` default arguments cut — the seam's protocol extension owns the default shape (finish-audit: defaults were dead with the host as sole caller). +- **`MentorSessionModel`** — all process lifecycle deleted (−211 lines): `client`/`passClient`/`clientRef`/`passClientRef`, `startEngine`, `handshake`, `teardownPassEngine`, `shutdownClientDirectly`, the deinit body. Session + turn coordination stays: phase machine fed by `host.startChat()` outcomes (`applyChatStart`), `runOneShot` rides `host.withOneShot` with the body holding session/new + the spawn-window cancel + `turnCore`; `respawn` = `killChat` → clear buffers → `startChat` → resume PRE-restart active. The model stays the ONLY observable the panes see. +- **`MuseionTests/ScriptedEngine.swift` (new)** — the scripted in-process adapter: mode strings mirroring the retired zsh fake (full/crashAfterHandshake/hangOnPrompt/cancelOnPrompt/refuseOnPrompt/noStopReason/strayResearchOnPrompt/loadReplay*/strictMcp), `ScriptedPayloads` (one home for the wire payloads — the zsh b64 helpers delegate to it), a lock-protected `ScriptedBook` captured STRONGLY by the factory, and the rig roots. Observables: spawned-profiles record (which engine ran), transport identity where pid pins used to live, `isClosed` for reaped, `prompts` for what the engine was asked, `releaseHeldLoad()` for the parked-load interleavings. +- **8 suites migrated in-process** — ACPClientTests (turn-outcome + view predicates; the zsh harness stays as the shared wire fixture), EngineLifecycleTests, PassRunTests, BlindReadTests, SessionLifecycleTests, SessionScopeTests, TranscriptRailTests, ResearchCandidateTests. All pins kept their meaning; pid/kill pins became transport-identity/isClosed pins; the load-go mode-file flip became the rig's mutable mode + `releaseHeldLoad()`. +- **`MuseionTests/EngineSmokeTests.swift` (new)** — the ONLY child-spawning suite: one real-process wire smoke per LLM surface. Chat (two acts over one fake: held-turn fire-and-forget cancel → `.cancelled` + shutdown SIGTERMs a parked child → reaped, then mode flip to loadReplay for handshake/stream/crash/restart/teardown on a fresh model) + one parameterized pass smoke over `[PassKind.pass1, .pass2]` (own engine under its profile, spawn-log pins, teardown reap, chat engine untouched). +- **DOX** — `Museion/AGENTS.md` ACP-bridge section rewritten (EngineHost bullet added; model bullet re-scoped to "the only observable the panes see"); `MuseionTests/AGENTS.md` conventions + suite map updated (in-process seam rigs; EngineSmokeTests as the only child-spawning suite). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Seam = the client's own surface (hooks + request/notify/close), not a smaller one | The model needed exactly that shape through `turnCore`; inventing a narrower protocol would duplicate the client's API. Two adapters, both exercised — the seam earns its existence | +| Host not `@Observable`; model copies `engineVersion`/`versionNote` from `startChat()`'s `.up` | Keeps observation 100% on the model (acceptance: "no pane observes the host directly") without proxy-property tracking subtleties | +| One-shot teardown inside `withOneShot` (scoped-resource pattern) | Guarantees "torn down at the verdict" structurally — teardown at body end on every exit path including throws — instead of trusting every future caller to remember | +| One-shot slot claimed BEFORE the spawn/handshake awaits (review fix) | Old model set `passClient` before any suspension; claiming after the handshake left `isOneShotRunning` false and the at-most-one contract unenforced across the await. Defer registered with the claim so all four exits release | +| Rig factory holds the ScriptedBook STRONGLY (no `[weak self]`) | The original rig dropped to nil mid-test when a 3-tuple shape didn't retain it — every later spawn silently fell back to "full" mode; poisoned holds. Rig lifetime must not matter | +| Chat smoke in two acts with a mid-test mode-file flip | One smoke per surface is the ceiling; the flip (each fake child reads the mode at startup — the old interleaving-test convention) lets one fake serve both the cancel/hold contracts and the restart-resume contract | +| Deferred: `LocalizedError` on TransportError/HostError so failure rows render the message | Pre-existing user-visible string behavior faithfully ported; changing row text exceeds #178's scope. Noted for #181's guard-dedupe rider | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Every scripted spawn answered as "full" mode mid-test; a parked 1800 s load poisoned cross-suite runs | Rig factory's `[weak self]` went nil when the makePassRig 3-tuple dropped the rig object | Lock-protected `ScriptedBook` captured strongly by `host.makeTransport`; no MainActor closure in the factory | +| `crash after handshake fires onCrash exactly once` failed with confirmation count 0 | The scripted engine resumed the initialize continuation before firing onCrash; the awaiting task ended the confirmation body first | Latch + fire onCrash BEFORE resuming the continuation (mirror of the wire-order rule) | +| Suite SIGTRAP: every test crashed at payload decode | Backslash-escaped quotes inside raw string literals produced invalid JSON → `preconditionFailure` | Fixed literals; green full run confirms | +| 652 executed after parameterizing the pass smoke (expected 653) | `xcresulttool totalTestCount` counts a Swift Testing parameterized `@Test` as ONE test; per-argument executions are `nodeType: "Arguments"` children | Reconciled programmatically: 652 functions = 653 argument cases (`.pass1`/`.pass2` children individually Passed). Count convention updated in MuseionTests verification practice | +| One-shot engine identity not observable mid-run in-process | A full-mode scripted turn completes inside one 20 ms poll sleep (no child-process latency) | The pin captures the pass engine from the spawn records post-run (profile, `isClosed`, `host.oneShot == nil`) — same facts, timing-free | +| Chat smoke restart would hang on the default fake | `restart()` resumes via `session/load`, which "full" mode never answers (1800 s timeout) | Mode `loadReplay` answers everything Act 2 drives; Act 1's holds use `hangOnPrompt` before the flip | +| `function_body_length` (53 > 50) introduced by the audit's smoke restructure | The skill's own warning: an audit fix can add a violation | Act 1 extracted to a file-local helper (`heldTurnWireContracts`) | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/EngineHost.swift` | NEW — the `EngineTransport` seam + the engine lifecycle owner | +| `Museion/ACPEngineClient.swift` | Conformance; `onMessage` property + `start()`; concrete defaults cut | +| `Museion/MentorSessionModel.swift` | Lifecycle removed (−211 lines); all engine work routed through `host` | +| `MuseionTests/ScriptedEngine.swift` | NEW — scripted in-process adapter, payloads, rig roots | +| `MuseionTests/EngineSmokeTests.swift` | NEW — one real-process wire smoke per surface (chat two-act + parameterized passes) | +| `MuseionTests/ACPClientTests.swift` | Migrated in-process; zsh harness retained as the wire fixture | +| `MuseionTests/{EngineLifecycle,PassRun,BlindRead,SessionLifecycle,SessionScope,TranscriptRail,ResearchCandidate}Tests.swift` | Migrated to scripted rigs; pid pins → identity/isClosed pins | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX: ACP-bridge section, test conventions + suite map | +| `AGENTS.md` | gitnexus index stat line (auto) | + +## Open Items & Next Steps + +- [ ] #181 (Provider descriptor + Pass Readiness, blocked-by #178) is unblocked by this merge. +- [ ] Deferred: `LocalizedError` on engine error types so failure rows render the real message (pre-existing cosmetic; candidate rider on #181). +- [ ] Deferred (taste, rejected by audit): folding `hasChat`/`isOneShotRunning` into bare `!= nil` reads. + +--- + +**Verification** (final tree, cited from the session's last run): `build-for-testing` + `test-without-building` — **652 executed / 652 passed / 0 failed** (653 argument cases; the pass smoke's `.pass1`/`.pass2` children individually Passed), counted via `xcrun xcresulttool get test-results summary`, never the SUCCEEDED banner. swiftformat idempotent; swiftlint 0 violations in touched files (model's two pre-existing warnings reduced: type_body_length 346→296). `gitnexus detect-changes` before the final analyze reported exactly the intended blast radius (lifecycle symbols over the RunPass/RunBlindRead/SendPrompt flows). + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 4c490aa..e538aec 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-09 | issue | [20261109-issue178-extract-engine-host-transport-seam_log.md](20261109-issue178-extract-engine-host-transport-seam_log.md) | Engine lifecycle → EngineHost behind the EngineTransport seam; scripted in-process tests, one real smoke per surface | | 2026-11-09 | issue | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | SessionRow text rows typed (speaker+notice), kick-off sniffed at append seam, one ToolPayloads decoder both rails read | | 2026-11-09 | issue | [20261109-issue183-shrink-agentsmd_log.md](20261109-issue183-shrink-agentsmd_log.md) | AGENTS.md rails shrunk 206 KB → 36 KB — contracts and rulings kept, per-issue diaries cut; serif payload untouched (#183) | | 2026-11-05 | issue | [20261105-issue175-nous-portal-provider_log.md](20261105-issue175-nous-portal-provider_log.md) | Fourth provider `nous`: plain chat-completions probe, session-key fallback gated to the official endpoint, keyless readiness (#175) |