// // 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 (#179 audit): release a held prompt as a NORMALLY ended /// turn — session/cancel answers "cancelled"; the mid-pass repoint pin /// needs the turn to end .ended after the hold. Returns false (and /// no-ops) when nothing is held — e.g. the parked request already hit /// its deadline under machine load — so the caller can fail loudly /// instead of reading a confusing nil strip. @discardableResult func endHeldPrompt() -> Bool { queue.sync { guard let id = self.heldPromptID, let continuation = self.parked.removeValue(forKey: id) else { return false } self.heldPromptID = nil continuation.resume(returning: .object(["stopReason": .string("end_turn")])) return true } } /// 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) }