// // 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)" } }