refactor(session): extract the engine host
CI / ci (push) Canceled after 0s

Engine lifecycle policy — spawn, handshake, respawn-on-crash, teardown,
and the per-surface residency rules (resident chat engine; one-shot
pass engines spawned per run, torn down at the verdict, ADR-0014) —
moves out of MentorSessionModel into EngineHost behind the
EngineTransport seam. The model keeps session + turn coordination and
stays the only observable the panes see; ACPEngineClient becomes the
seam's production adapter, and a scripted in-process engine
(ScriptedEngine) becomes the second adapter — engine-behaviour tests
(streaming, crash, cancel, restart, per-surface spawn) now run without
child processes, retiring the zsh fake-server rigs from logic tests
(#30 flake family). Exactly one real-process wire smoke per LLM
surface survives (chat two-act + parameterized pass1/pass2): the
held-turn cancel contract, hung-child SIGTERM teardown, handshake,
streamed turn, crash, restart.

One-shot teardown is structural (withOneShot closes at body end, every
exit path); the one-shot slot is claimed before the first suspension so
the at-most-one invariant holds across the spawn/handshake awaits.

Suite: 652 executed / 652 passed / 0 failed (653 argument cases),
counted from the xcresult; swiftformat idempotent, swiftlint clean on
touched files.

Closes #178
This commit is contained in:
AlexKucera committed 2026-11-09 18:26:16 +01:00
1 parent d14cb40e73
commit 627ecf515e
18 files changed
+1663 -639

No files matched your search

+21 -13
View File
@@ -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) })
}
}
}
+3 -2
View File
@@ -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 <profile>`; 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 <profile>`; 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).
+282
View File
@@ -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: <desc>")
/// - initialize request fails -> .failed("handshake failed: <desc>")
/// - 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<R: Sendable>(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)"
}
}
+121 -191
View File
@@ -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