// // MentorSessionModel.swift // Museion // // M0 ACP bridge (#14): the pane's @Observable model — lazy bridge lifecycle, // prompt streaming, fix-card render, crash → restart prompt. // #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). // // 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). // 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). struct SessionRow: Identifiable { enum Content { case text(String) /// #24 fix: the engine's thinking for one turn — rendered collapsed, /// never mixed into the critique text. case thought(String) case fixCard(FixCard) /// #29 (S8.2): a candidate research note from the session's research /// tool call — lives in THIS session until the writer keeps or /// rejects it (engine-owned cargo; replay re-materializes it). case researchNote(ResearchCandidate) case raw(kind: String, json: String) } let id = UUID() var content: Content } /// A Fix Card as defined by CONTEXT.md — pattern, problem, diagnostic /// question, fix, anchor, provenance, status — riding a typed tool call /// (ADR-0006), parsed from `rawInput` as data, never prose. struct FixCard { var pattern: String var problem: String var diagnosticQuestion: String var fix: String var anchor: String var provenance: String var status: String } /// #29 (S8.2) one candidate research note: a source finding the mentor /// surfaced mid-pass. Candidates wait in their SESSION until kept — nothing /// auto-saves (CONTEXT.md's Research Note: kept ones land in the piece's /// research/ via the store rail; rejected ones vanish). Nonisolated: a wire /// value parsed from rawInput and asserted from tests (SessionEntry rule). nonisolated struct ResearchCandidate: Equatable { enum Disposition: Equatable { case pending; case kept(fileName: String); case rejected } var piecePath: String var title: String var url: String var quote: String var note: String var disposition: Disposition = .pending } /// How a turn ended — the pass orchestrator's seam (#24): a pass advances /// Pass State only when the engine's turn completed, never on cancel/crash. enum TurnOutcome: Equatable { /// Turn ended; stopReason as answered on the wire (e.g. "end_turn", "refusal"). case ended(stopReason: String) /// The engine acknowledged a session/cancel (stopReason "cancelled"). case cancelled /// Transport error / crash mid-turn (the failure row is already appended). case failed } /// One rostered mentor session (#28, S2.3). Piece association is by /// convention — the entry's `pieceTitle` field only, no filesystem linkage. /// History is engine-owned; only these four fields persist. nonisolated struct SessionEntry: Identifiable, Equatable, Codable { let sessionId: String let name: String var pieceTitle: String? let createdAt: Date var id: String { sessionId } } /// The persisted roster (#28) — a JSON array of entries at a /// caller-injectable directory, default `~/Library/Application /// Support/Museion/sessions.json`. EngineGate's state.json posture: wholesale /// replace, atomic, a write failure must never crash the app. nonisolated enum SessionRoster { static func load(directory: String? = nil) -> [SessionEntry] { guard let data = try? Data(contentsOf: rosterURL(directory)) else { return [] } return (try? JSONDecoder().decode([SessionEntry].self, from: data)) ?? [] } static func save(_ entries: [SessionEntry], directory: String? = nil) { let dir = directory ?? defaultDirectory do { try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) try JSONEncoder().encode(entries).write( to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"), options: .atomic, ) // Finish-audit: names+ids only, but piece titles are the writer's // business — the default umask would hand them to every local user. try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json").path) } catch { // ponytail: the roster is a convenience index; a write failure must not crash the gate. } } private static var defaultDirectory: String { ("~/Library/Application Support/Museion" as NSString).expandingTildeInPath } private static func rosterURL(_ directory: String?) -> URL { URL(fileURLWithPath: directory ?? defaultDirectory).appendingPathComponent("sessions.json") } } /// Pane + bridge state machine. Lazy lifecycle: the engine spawns when the /// pane opens its first session and stays alive for the app's life (map /// decision: child lifecycle). The engine bridge is session-agnostic — /// session ids live in the roster (#28), the phase only says the engine is up. @MainActor @Observable final class MentorSessionModel { enum Phase: Equatable { case idle case starting case ready case crashed(lastPrompt: String?) var isReady: Bool { if case .ready = self { return true } return false } } /// Per-session transcript state (#28) — the model used to hold ONE /// session's rows and streaming buffers; now keyed by sessionId. The /// active session's entries surface through the same-named proxies below. private struct SessionTranscript { var rows: [SessionRow] = [] var streamingText = "" var streamingThought = "" } private(set) var phase: Phase = .idle /// True while a turn streams — the Stop button's target. One engine /// child, so at most one turn streams at a time across all sessions. private(set) var isStreaming = false /// The roster, newest-first (#28). Persisted via SessionRoster. private(set) var roster: [SessionEntry] = [] /// The session the pane reads and new prompts target (#28). private(set) var activeEntry: SessionEntry? /// The ACTIVE session's transcript — the same-named pane surface over /// the per-session store (#28). MentorPaneView and every existing test /// keep reading these untouched. var rows: [SessionRow] { activeTranscript?.rows ?? [] } /// Streaming buffer for the in-flight agent message of the ACTIVE /// session; flushed to a row on completion. var streamingText: String { activeTranscript?.streamingText ?? "" } /// #24 fix: streaming buffer for the engine's THINKING — kept out of the /// critique stream. A pass runs to hundreds of thought lines; conflating /// them with `agent_message_chunk` made the transcript one giant blob. var streamingThought: String { activeTranscript?.streamingThought ?? "" } /// A new session may start: engine up, no turn in flight (#28). var canStartSession: Bool { phase.isReady && !isStreaming } /// Advisory engine-version verdict (map decision: advisory, never blocks). private(set) var versionNote: String? /// The running engine's version, from the initialize handshake (always visible). private(set) var engineVersion: String? /// Last stderr lines from the engine — the restart prompt's technical details. private(set) var stderrTail: [String] = [] private var transcripts: [String: SessionTranscript] = [:] /// While a session/load is in flight, its replayed updates render as rows /// instead of feeding the streaming buffers (#28). private var replayingSessionId: String? /// The resolved roster directory (nil = SessionRoster's default). Under /// hosted tests a unique temp dir keeps suites off the real roster /// (ponytail: redirect here instead of making every rig inject a directory). private let rosterDirectory: String? private var client: ACPEngineClient? 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 /// 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 /// (firePendingRestartIfRequested), whichever engine streamed. private var pendingRestart = false /// #137 (S4): per-pass readiness (refreshPassReadiness, same-file #137 /// extension) + the injectable read seam (tests). Stored in the class /// body — extensions carry no stored state. private(set) var passReadiness: [PassKind: PassReadiness] = [:] var passReadinessWriter: (any SettingsWriting)? /// 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? /// 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) { self.binaryPath = binaryPath if let rosterDirectory { self.rosterDirectory = rosterDirectory } else if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil { self.rosterDirectory = NSTemporaryDirectory() + "museion-roster-\(UUID().uuidString)" } else { self.rosterDirectory = nil } roster = SessionRoster.load(directory: self.rosterDirectory) } 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 } /// App-quit teardown (#14): close the engine children cleanly. Idempotent. func shutdown() { teardownPassEngine() shutdownClientDirectly() client = nil clientRef = nil 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 /// transcript — history is engine-owned and comes back on resume (#28). func openSession() async { guard phase == .idle else { return } phase = .starting await startEngine() guard case .starting = phase else { return } // startEngine crashed instead await ensureDefaultSession() } /// Restart after a crash — re-spawns the engine and REPLAYS every /// transcript from it (ADR-0007: the engine owns the words), and /// remembers the last prompt so the writer can resend it. func restart() async { guard case .crashed = phase else { return } 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 { phase = .crashed(lastPrompt: lastPrompt) stderrTail = ["spawn failed: \(error.localizedDescription)"] return } do { try await handshake(client) } catch { phase = .crashed(lastPrompt: lastPrompt) stderrTail = ["handshake failed: \(error.localizedDescription)"] } } /// 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 } /// After an engine start: exactly one active session (#28). The newest /// rostered entry activates and RESUMES — session/load replays its /// history (user turns included), so prompt/fork/compact never run /// against unloaded state; a first open creates the default freeform /// 'Mentor' session. private func ensureDefaultSession() async { // #137 audit fix: a restart completing while a pass runs (crash → // Restart mid-pass) — the engine is up, mark ready and leave the // pass surface alone; the newest entry activates on the next open. guard !isStreaming else { phase = .ready return } if let newest = roster.first { activate(newest) // The resume REPLAYS, unconditionally (finish-audit): the deleted // rows.isEmpty skip was dead — activate() resets the store one // line above it — and restart()'s kept rows are intentionally // replaced by the engine's replay (ADR-0007: the engine owns the // words; a diverging local copy would lie). An engine-unknown id // lands the honest refusal row; the entry stays rostered. _ = await resumeSession(newest) return } if await createSession(name: "Mentor", pieceTitle: nil) == nil { phase = .crashed(lastPrompt: nil) stderrTail = ["no session — the engine refused session/new"] } } /// A fresh freeform session (#28): wire session/new, roster it /// 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 } return await createSession(name: name, pieceTitle: pieceTitle) } /// #30 (S2.7): the brainstorm flavor — a plain freeform session whose /// first turn is the brainstorm prompt (PRD S2.8: no new machinery). /// Nil when the session couldn't be created; the opener rides the /// normal prompt rail and streams like any turn. @discardableResult func beginBrainstormSession(pieceTitle: String?) async -> SessionEntry? { guard let entry = await newSession(name: "Brainstorm", pieceTitle: pieceTitle) else { return nil } _ = await sendPrompt(Self.brainstormPrompt, label: "Brainstorm") return entry } /// #30 (S2.7): the brainstorm opener — questions over prose. nonisolated static let brainstormPrompt = "Let's brainstorm together. Ask me one question at a time to draw out ideas " + "and angles for what I want to write — keep replies short and generative, " + "and don't draft prose unless I ask." /// The shared creation rail behind newSession (#137: beginPassSession /// died with per-surface engines — passes never mint sessions). private func createSession(name: String, pieceTitle: String?) async -> SessionEntry? { // Finish-audit backstop: fork guards !isStreaming; the views disable // these controls mid-turn. A programmatic caller must not switch the // active session out from under a live turn — Stop would then cancel // the wrong session. guard !isStreaming else { appendRow(.text("Session refused — the mentor is mid-turn."), to: activeEntry?.sessionId) return nil } guard let client 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( "session/new", params: .object([ "cwd": .string(cwdProvider()), "mcpServers": .array([]), ]), ) guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else { // #28 review fix: a refused session speaks like its siblings — // resume/fork append honest rows; New Session must never be a // silent nil. (Nothing active yet → the row drops; the crash // posture owns that path in ensureDefaultSession.) appendRow(.text("Session refused — the engine returned no id."), to: activeEntry?.sessionId) return nil } let entry = SessionEntry(sessionId: sid, name: name, pieceTitle: pieceTitle, createdAt: Date()) // #137 audit fix: the session/new await above is a suspension — // a pass may have started under it. Re-check ownership before // rostering/activating (the entry guard at the top can't see // this window); claimActive refuses with this function's voice. guard claimActive(entry, refusedNote: "Session refused — the mentor is mid-turn.") else { return nil } roster.insert(entry, at: 0) saveRoster() return entry } catch { appendRow(.text("Session refused — \(error.localizedDescription)"), to: activeEntry?.sessionId) return nil } } /// Resume a rostered session (#28): session/load, the engine replays its /// history into the transcript (user turns included), Museion owns none /// of it. A session the engine does NOT know returns false honestly — /// 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 !isStreaming else { // "Not now" refusals target the ACTIVE session — they are about // the writer's action right now, not the entry's state. appendRow(.text("Resume refused — the mentor is mid-turn."), to: activeEntry?.sessionId) return false } guard replayingSessionId == nil else { // Finish-audit (converged, 3 reviewers): one replay slot — a // second session/load in flight would divert the first's replayed // chunks into live streaming buffers. Refuse; the winner's // completion frees the slot and the next click just works. appendRow(.text("Resume refused — another session is loading."), to: activeEntry?.sessionId) return false } do { // Replay fills this fresh store; a failed resume leaves nothing fabricated. transcripts[entry.sessionId] = SessionTranscript() replayingSessionId = entry.sessionId // 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( "session/load", params: .object([ "cwd": .string(cwdProvider()), "sessionId": .string(entry.sessionId), "mcpServers": .array([]), ]), // Finish-audit: the adapter replays the FULL history before // responding — #23's exact shape (response arrives when the // work ends). The client's 15 s default would abort a long // session's resume mid-replay. timeout: Self.promptTimeout, ) replayingSessionId = nil // The real adapter (0.21.5, live-verified #30 dogfood) answers // session/load WITHOUT a top-level sessionId — the id rides // `_meta.hermes.sessionProvenance.acpSessionId`. The fake's // top-level shape stays accepted (the older contract). let resultObject = result?.objectValue let provenance = resultObject?["_meta"]? .objectValue?["hermes"]? .objectValue?["sessionProvenance"]? .objectValue let sid = resultObject?["sessionId"]?.stringValue ?? provenance?["acpSessionId"]?.stringValue ?? "" // null/absent everywhere = the engine does not know it. guard !sid.isEmpty else { // The refusal belongs to the ENTRY — attributed, and visible // on its next row click (the store is kept, not discarded). appendRow( .text("The engine does not know “\(entry.name)” — its history is no longer on the engine."), to: entry.sessionId, ) return false } // Activate WITHOUT resetting the transcript — activate() is for // fresh-transcript activations; the replay already filled this one. // #137 audit fix: the session/load await can span a whole pass — // a resume completing mid-turn must not steal the pass surface // (a lost Cancel reopens the #124 hole); the replayed rows stay // in the entry's store for its next click. guard claimActive(entry, freshTranscript: false, refusedNote: "Resume refused — the mentor is mid-turn.") else { return false } return true } catch { replayingSessionId = nil // Partial replay rows (if any) + the failure row stay in the // ENTRY's store — attributed, visible on its next row click. appendRow(.text("Resume failed — \(error.localizedDescription)"), to: entry.sessionId) return false } } /// Fork the active session (#28): the engine copies its history to a NEW /// sessionId (session/fork); Museion rosters ' (fork)' with the /// same pieceTitle and activates it with a FRESH transcript — the /// original entry and transcript stay untouched. An empty-string /// 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 } do { let result = try await client.request( "session/fork", params: .object([ "cwd": .string(cwdProvider()), "sessionId": .string(source.sessionId), "mcpServers": .array([]), ]), ) guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else { appendRow(.text("Fork refused — the engine returned no new session."), to: source.sessionId) return nil } let entry = SessionEntry( sessionId: sid, name: "\(source.name) (fork)", pieceTitle: source.pieceTitle, createdAt: Date(), ) // #137 audit fix: same post-await ownership re-check as // createSession/resumeSession — the fork await is a suspension. guard claimActive(entry, refusedNote: "Fork refused — the mentor is mid-turn.") else { return nil } roster.insert(entry, at: 0) saveRoster() return entry } catch { appendRow(.text("Fork failed — \(error.localizedDescription)"), to: source.sessionId) return nil } } /// Compact the active idle session (#28): the engine's /compress dispatch /// rides the existing prompt rail; the label keeps the raw slash command /// out of the transcript and the summary streams back as ordinary chunks. /// Refused while a turn streams (idle-only engine-side, too). func compactActiveSession() async { guard canStartSession, activeEntry != nil else { return } _ = await sendPrompt("/compress", label: "Compact…") } /// Read-only transcript of ANY rostered session (#28) — the Sessions pane /// and tests read without activating. func transcriptRows(of entry: SessionEntry) -> [SessionRow] { transcripts[entry.sessionId]?.rows ?? [] } private func activate(_ entry: SessionEntry) { transcripts[entry.sessionId] = SessionTranscript() activeEntry = entry phase = .ready } /// #137 audit fix: the ONE activation gate every post-await writer routes /// through — a session/new/load/fork completing while ANY turn streams /// (a pass holds the surface for its whole run) must not steal the active /// entry: Cancel would misroute to the wrong engine (#124 class) and the /// pane would flip mid-run. Refuses with the caller's row, activates /// (fresh or replay-filled transcript) otherwise. private func claimActive(_ entry: SessionEntry, freshTranscript: Bool = true, refusedNote: String) -> Bool { guard !isStreaming else { appendRow(.text(refusedNote), to: activeEntry?.sessionId) return false } if freshTranscript { transcripts[entry.sessionId] = SessionTranscript() } activeEntry = entry phase = .ready return true } private func saveRoster() { SessionRoster.save(roster, directory: rosterDirectory) } } // MARK: Turn core + per-surface engine lifecycle (#137, S4) /// Same-file extension — type_body_length posture (MentorPaneView precedent); /// the turn pipeline and the #137 engine lifecycle read as one unit. extension MentorSessionModel { /// #137: the transient pass transcript's key. A pass never mints a /// roster entry (#129: passes run on their own one-shot engines) — the /// pass entry lives under this key only for the run; the view layer /// hides the session chip on it (next slice). nonisolated static let passTranscriptKey = "pass" /// The pass engine's pid — internal test observable (teardown pins). var passEngineChildPid: pid_t? { passClient?.childProcessIdentifier } /// True while a pass engine is resident (spawn → verdict). var isPassEngineRunning: Bool { passClient != nil } /// #137 (S4): the Run Pass posture — is the pass profile's provider /// keyed? .unknown NEVER blocks (our own read failure — the spawn's /// honest failure row owns that path); .missingKey names the provider /// so the pane can say what's missing and link to Settings. enum PassReadiness: Equatable { case ready case missingKey(providerLabel: String) case unknown } // Per-pass readiness (stored in the class body), refreshed at pane // entry (re-entry re-fires the pane's .task — the key-added-in- // Settings re-enable path). `passReadinessWriter` is the injectable // read seam; nil at refresh time → an ad-hoc HermesSettingsWriter // over the gate's binary (profileRoot default). func readiness(for kind: PassKind) -> PassReadiness { passReadiness[kind] ?? .unknown } /// Read each pass profile's provider (readSurface, one task group), /// then each DISTINCT provider's key (readProviderKey). A surface we /// can't read maps .unknown; a non-empty key maps .ready; no key maps /// .missingKey with the provider's label. No binaryPath and no /// injected writer → readiness stays empty (.unknown everywhere). func refreshPassReadiness() async { guard let writer = passReadinessWriter ?? binaryPath.map({ HermesSettingsWriter(hermesBinary: $0) }) else { return } var providers: [ProfileSurface: ModelProvider] = [:] await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in for surface in [ProfileSurface.pass1, .pass2] { group.addTask { await (surface, try? writer.readSurface(surface)) } } for await (surface, read) in group { providers[surface] = read?.config.provider } } var keys: [ModelProvider: String] = [:] for provider in Set(providers.values.compactMap(\.self)) { keys[provider] = await (try? writer.readProviderKey(provider: provider)) ?? "" } for surface in [ProfileSurface.pass1, .pass2] { let kind: PassKind = surface == .pass1 ? .pass1 : .pass2 guard let provider = providers[surface] else { passReadiness[kind] = .unknown continue } if let key = keys[provider], !key.isEmpty { passReadiness[kind] = .ready } else { passReadiness[kind] = .missingKey(providerLabel: provider.label) } } } /// Send a prompt and stream the reply into the ACTIVE session's /// transcript. Appends the user row first — a non-nil `label` renders /// verbatim INSTEAD of the raw prompt (pass prompts are long wire stubs /// that must not land in the transcript); the stop_reason response ends /// the turn (refusal maps to a plain note — wire-verified edge /// semantics). Returns how the turn ended (#24 seam): a pass advances /// only on a completed turn, never on cancel/crash. session/prompt's /// response arrives only when the TURN ends — a pass legitimately runs /// minutes of tool work between prompt and stop reason. The client's /// 15 s request default would abandon the wait mid-stream (observed /// live, #23 dogfood: "connection lost" while the engine kept working, /// Stop vanished with isStreaming). Long-but-finite so a truly stuck /// engine still surfaces; Stop is the live-turn exit. nonisolated static let promptTimeout: TimeInterval = 1800 @discardableResult func sendPrompt(_ text: String, label: String? = nil) async -> TurnOutcome { let prompt = text.trimmingCharacters(in: .whitespacesAndNewlines) // Guard refusal: the turn never ran — .failed is the closest of the // three buckets (the seam has no "never started" case; callers that // check phase before prompting never land here). guard !prompt.isEmpty, phase.isReady, !isStreaming, let sid = activeEntry?.sessionId else { return .failed } // #137: the transient pass transcript is surface-only — the pass // engine is gone after teardown, so the composer must refuse with // the words visible, never silently drop the text. guard sid != Self.passTranscriptKey else { appendRow(.text("Pick or start a session to chat — the pass transcript is read-only."), to: sid) return .failed } guard let client else { return .failed } isStreaming = true defer { isStreaming = false // #137: a model-change restart requested mid-turn fires now. firePendingRestartIfRequested() } return await turnCore( client: client, wireSid: sid, key: sid, prompt: prompt, label: label ?? "You: \(prompt)", ) } /// The ONE turn pipeline behind sendPrompt and the pass run (#137): the /// label row, session/prompt, stopReason mapping, and the streaming- /// buffer flush — one implementation, two engines. private func turnCore( client: ACPEngineClient, wireSid: String, key: String, prompt: String, label: String, ) async -> TurnOutcome { lastPrompt = prompt appendRow(.text(label), to: key) isStreaming = true defer { // Flush the thinking first (it preceded the message), collapsed. if let pending = transcripts[key], !pending.streamingThought.isEmpty { appendRow(.thought(pending.streamingThought), to: key) transcripts[key]?.streamingThought = "" } // Flush any streamed-but-unfinished agent text into a row. if let pending = transcripts[key], !pending.streamingText.isEmpty { appendRow(.text("Mentor: \(pending.streamingText)"), to: key) transcripts[key]?.streamingText = "" } isStreaming = false } do { let result = try await client.request( "session/prompt", params: .object([ "sessionId": .string(wireSid), "prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]), ]), timeout: Self.promptTimeout, ) let stopReason = result?.objectValue?["stopReason"]?.stringValue ?? "" // A completed turn always carries stopReason (ACP spec). An // engine that omits it did not complete the turn — the pass // must not advance on a maybe (review: empty-stopReason bug). guard !stopReason.isEmpty else { return .failed } if stopReason == "refusal" { appendRow(.text("Mentor: (refused the prompt)"), to: key) } if stopReason == "cancelled" { return .cancelled } return .ended(stopReason: stopReason) } catch { // Transport failure mid-turn: the crash path owns the UX; keep the // partial transcript (never data loss). if case .crashed = phase { // Crash card already owns the failure surface. } else { appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: key) } return .failed } } /// #137 (S4, ADR-0014): run one pass on its OWN one-shot engine — /// spawn `hermes acp -p museion-passN`, stream the verdict into the /// transient pass transcript, tear the engine down at the verdict. /// The pass entry is never rostered (#129); the chat engine keeps /// running untouched. @discardableResult func runPass(kind: PassKind, stub: String, pieceTitle: String) async -> TurnOutcome { // #137 audit: no force-unwrap — the map is total over today's two // kinds, but a future PassKind case must refuse, not trap. guard let surface = ProfileSurface(passKind: kind) else { return .failed } return await runOneShot( profile: surface.profileName, name: kind.rawValue, prompt: stub, pieceTitle: pieceTitle, ) } /// #122: run one Blind Read — a whole-document A/B judgment by a FRESH /// session of the SAME museion profile (the chat surface: context-free /// means no editing history, not a different judge — decision #120; the /// Knife floor + no-flattery personas ride the profile). The verdict and /// the app-side reveal stream into the shared transient transcript; /// the reveal lands only on a completed turn. Never rostered, never /// saved — advisory-only, records nothing. @discardableResult func runBlindRead(prompt: String, pieceTitle: String, reveal: String) async -> TurnOutcome { let outcome = await runOneShot( profile: ProfileSurface.chat.profileName, name: "Blind Read", prompt: prompt, pieceTitle: pieceTitle, ) // The mapping the writer reads — appended AFTER the turn so it can // never leak to the judge. Cancelled/refused turns reveal nothing // (a refusal still ends .ended — gate on the stopReason, runPass's // advance posture; a 2×-document prompt makes context-length // refusals a realistic path). if case let .ended(stopReason) = outcome, stopReason != "refusal" { appendRow(.text(reveal), to: Self.passTranscriptKey) } return outcome } /// 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. private func runOneShot(profile: String, name: String, prompt: String, pieceTitle: String) async -> TurnOutcome { guard phase.isReady, !isStreaming, passClient == nil, let binaryPath 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 // saved (#129: one-shot runs, the chat engine owns sessions). transcripts[Self.passTranscriptKey] = SessionTranscript() activeEntry = SessionEntry( sessionId: Self.passTranscriptKey, name: label, pieceTitle: pieceTitle, createdAt: Date(), ) isStreaming = true defer { isStreaming = false teardownPassEngine() firePendingRestartIfRequested() } 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. 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) } } // 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"), ]), ])) 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."), to: Self.passTranscriptKey) return .failed } passWireId = sid } catch { appendRow(.text("\(label) failed — \(error.localizedDescription)"), to: Self.passTranscriptKey) return .failed } // Cancel clicked while the engine was spawning: stop before the // prompt — the run ends cancelled, nothing streams. if passCancelRequested { appendRow(.text("\(label) cancelled."), to: Self.passTranscriptKey) return .cancelled } return await turnCore(client: pass, wireSid: passWireId ?? "", key: Self.passTranscriptKey, prompt: prompt, label: label) } /// 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 } /// Stop button while a turn streams (map decision: cancel wired to /// session/cancel, a notification — no response expected). The engine /// ends the turn (PromptResponse) as its acknowledgement. #137: while a /// pass runs, the PASS engine owns the live turn — Cancel must reach it. func stopStreaming() { guard isStreaming else { return } // #137 fix: key the branch on the TRANSIENT ENTRY, not passWireId — // the wire id is nil until session/new lands, so a Cancel clicked in // the spawn window fell through to the chat engine and was LOST (the // pass then held until promptTimeout). The pass entry owns the active // surface for the run's WHOLE span, and sendPrompt refuses chat turns // under it — no chat stream can race this branch. if activeEntry?.sessionId == Self.passTranscriptKey { passCancelRequested = true if let passSid = passWireId { passClient?.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)])) } /// #137 (S4): the model-change restart posture — Settings fires this /// when the Chat model changes (the next slice wires the UI). Re-spawns /// the resident chat engine in place when idle; while a turn streams /// (either engine), the restart defers to turn end so a reply is never /// cut mid-stream. .idle/.starting are ignored — a future spawn reads /// fresh config anyway. func requestRestart() { switch phase { case .ready, .crashed: break case .idle, .starting: return } if isStreaming { pendingRestart = true } else { Task { await respawn() } } } /// The restart body behind crash-restart and requestRestart (#137): /// teardown, fresh spawn, then resume the PRE-restart active session /// when it is rostered — the writer stays where they were, not jumped /// 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 for sid in transcripts.keys { transcripts[sid]?.streamingText = "" transcripts[sid]?.streamingThought = "" } phase = .starting await startEngine() guard case .starting = phase else { return } // startEngine crashed instead if let active = activeEntry, roster.contains(active) { phase = .ready _ = await resumeSession(active) } else { await ensureDefaultSession() } } /// A deferred restart fires at turn end — from BOTH turn-end defers /// (chat sendPrompt and the pass run), whichever engine streamed (#137). private func firePendingRestartIfRequested() { guard pendingRestart else { return } pendingRestart = false Task { await respawn() } } /// 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 } } // MARK: - Crash, stderr, and notification decoding (same-file extension — // the class body keeps lifecycle + turn operations) extension MentorSessionModel { private func handleCrash() { guard case .ready = phase else { // A crash during startup also lands in the restart prompt. if case .starting = phase { phase = .crashed(lastPrompt: lastPrompt) } return } phase = .crashed(lastPrompt: lastPrompt) } private func appendStderr(_ line: String) { stderrTail.append(line) if stderrTail.count > 20 { stderrTail.removeFirst(stderrTail.count - 20) } } /// Route by the session id FROM THE PARAMS (#28) — a replay for a /// background session lands in ITS transcript, never the active one's. /// #137: the pass engine's wire sid maps onto the transient pass key — /// everything downstream addresses transcripts by that key (passWireId /// is Optional; nil never equals a real sid). private func handleNotification(method: String, params: JSONValue?) { guard method == "session/update", let params, let sid = params.objectValue?["sessionId"]?.stringValue, let update = params.objectValue?["update"]?.objectValue else { return } let key = sid == passWireId ? Self.passTranscriptKey : sid guard transcripts[key] != nil else { return } let kind = update["sessionUpdate"]?.stringValue ?? "unknown" let replaying = key == replayingSessionId switch kind { case "agent_message_chunk": let text = update["content"]?.objectValue?["text"]?.stringValue ?? "" if replaying { // ponytail: one row per replayed chunk — a chunked engine message // renders as several rows; wire order stays faithful. Coalesce // only if a real adapter chunks replayed turns. appendRow(.text("Mentor: \(text)"), to: key) } else { transcripts[key]?.streamingText += text } case "agent_thought_chunk": let text = update["content"]?.objectValue?["text"]?.stringValue ?? "" if replaying { appendRow(.thought(text), to: key) } else { transcripts[key]?.streamingThought += text } case "user_message_chunk": // Live: the engine echoes the user message; the label row already // rendered. During replay there IS no rendered row — the engine // owns the turn, so it renders (#28: user turns included). if replaying { let text = update["content"]?.objectValue?["text"]?.stringValue ?? "" appendRow(.text("You: \(text)"), to: key) } case "tool_call": appendToolCall(update, to: key) default: // Every other update type: collapsible raw-JSON row (map decision). let object = params.objectValue?.mapValues { $0.any } ?? [:] let json = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data() appendRow(.raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? ""), to: key) } } /// Tool-call decoding — the fix-card rail (ADR-0006): a tool call whose /// `rawInput` decodes to fix-card fields renders as a card; any other tool /// call renders as a raw row. private func appendToolCall(_ update: [String: JSONValue], to sid: String) { let title = update["title"]?.stringValue ?? "tool call" let rawInput = update["rawInput"] // #29: the research rail routes on PAYLOAD SHAPE, not the title (a // tool_call's title is display text, not guaranteed to be the raw // tool name) and before the fix-card parse — a research payload with // stray pattern/problem keys must not vanish into a card row. The // notes-array presence gate keeps fix-card payloads out of the // research parser; a batch that fails to parse falls through. var candidates: [ResearchCandidate] = [] if case .array? = rawInput?.objectValue?["notes"] { candidates = ResearchCandidate.batch(rawInput) } if !candidates.isEmpty { for candidate in candidates { appendRow(.researchNote(candidate), to: sid) } return } if let card = FixCard(rawInput: rawInput) { appendRow(.fixCard(card), to: sid) return } let json = (try? JSONSerialization.data(withJSONObject: rawInput?.any ?? [:], options: [.sortedKeys])) ?? Data() appendRow(.raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid) } /// Append one row to a session's transcript; nil targets the ACTIVE one. private func appendRow(_ content: SessionRow.Content, to sid: String?) { guard let sid else { return } transcripts[sid, default: SessionTranscript()].rows.append(SessionRow(content: content)) } } /// Fix Card parsing from a tool call's rawInput — the fields per CONTEXT.md. private extension FixCard { init?(rawInput: JSONValue?) { guard let object = rawInput?.objectValue else { return nil } // Two shapes reach here: the museion-tools submit arguments // {piece_path, cards: [{pattern, …, anchor: {quote}}]} (snake_case, // the live rail) and the flat #14-era fake {pattern, problem, …}. // Card rail first; flat shape stays for older engines/tests. var card = object if case let .array(items)? = object["cards"], let nested = items.first?.objectValue { card = nested } // A fix-card-shaped payload carries at least pattern + problem. guard let patternValue = card["pattern"]?.stringValue, let problemValue = card["problem"]?.stringValue else { return nil } pattern = patternValue problem = problemValue diagnosticQuestion = card["diagnosticQuestion"]?.stringValue ?? card["diagnostic_question"]?.stringValue ?? "" fix = card["fix"]?.stringValue ?? "" anchor = card["anchor"]?.stringValue ?? card["anchor"]?.objectValue?["quote"]?.stringValue ?? "" provenance = card["provenance"]?.stringValue ?? "engine" status = card["status"]?.stringValue ?? "proposed" } } /// Flip a research candidate's disposition (#29 S8.3): replaces the /// row's content in the ACTIVE session's transcript (rows are structs; /// the store is keyed by wire sessionId). No-op on an unknown row id. /// File-scope extension — type_body_length posture (PostsModel's guards /// precedent); the API is unchanged for callers. extension MentorSessionModel { func setResearchDisposition(rowID: UUID, _ disposition: ResearchCandidate.Disposition) { guard let sid = activeEntry?.sessionId, var rows = transcripts[sid]?.rows, let index = rows.firstIndex(where: { $0.id == rowID }), case let .researchNote(candidate) = rows[index].content else { return } var updated = candidate updated.disposition = disposition rows[index].content = .researchNote(updated) transcripts[sid]?.rows = rows } } // MARK: New Post from Session (#30, S2.7) extension MentorSessionModel { /// The draft candidate for New Post from Session: the ACTIVE session's /// last mentor text row, "Mentor: " prefix stripped. Feeds the ask /// sheet's prefill. func draftCandidateText() -> String? { Self.draftCandidateText(in: rows) } /// The pure extraction (test seam): scan backwards — the LAST mentor /// text row wins; user rows and thought/card/research/raw rows never /// prefill. Blank bodies are skipped so a whitespace leftover can't /// blank the prefill while an earlier real reply still exists. static func draftCandidateText(in rows: [SessionRow]) -> String? { for row in rows.reversed() { guard case let .text(text) = row.content, text.hasPrefix("Mentor: ") else { continue } // ponytail: refusal/connection rows share the display prefix — // excluded by their known shapes until SessionRow carries speaker // identity (an enum reshape is its own ticket). if text.hasPrefix("Mentor: (refused") || text.hasPrefix("Mentor: connection lost") { continue } let body = text.dropFirst("Mentor: ".count).trimmingCharacters(in: .whitespacesAndNewlines) if !body.isEmpty { return String(body) } } return nil } } /// Research-candidate batch parsing (#29): the submit_research_notes wire /// shape {piece_path, notes: [{title, url, quote?, note?}]} — one candidate /// PER note. Lenient: a missing piece_path, an empty/absent notes array, or /// any note missing a NON-BLANK title/url yields NO candidates /// (appendToolCall falls through to the raw row) — the same trim rule the /// MCP wire enforces, so both boundaries agree (audit: a whitespace title /// used to render an invisible-titled card and keep as `-untitled.md`). /// Absent quote/note become "". nonisolated extension ResearchCandidate { static func batch(_ rawInput: JSONValue?) -> [ResearchCandidate] { guard let object = rawInput?.objectValue, let piecePath = object["piece_path"]?.stringValue, case let .array(notes)? = object["notes"], !notes.isEmpty else { return [] } var candidates: [ResearchCandidate] = [] for note in notes { guard let fields = note.objectValue, let title = fields["title"]?.stringValue, !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, let url = fields["url"]?.stringValue, !url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] } candidates.append(ResearchCandidate( piecePath: piecePath, title: title, url: url, quote: fields["quote"]?.stringValue ?? "", note: fields["note"]?.stringValue ?? "", )) } return candidates } }