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

+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