// // MentorSessionModel.swift // Museion // // ## Scenario: typed transcript rail // From #177 // // Given a session transcript built from live turns and engine replay // When rows are appended // Then every text row carries its speaker and notice as data — no stored // row holds a "Mentor: "/"You: " prefix — the replayed pass kick-off is // typed at the append seam, and the transcript view, writing-session // filter, and New Post prefill switch on typed data with identical // rendering. // // 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 (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 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 /// One rendered row in the pane transcript. Text + tool calls first-class, /// the rest raw (map decision: rendering fidelity). Nonisolated (#177 S2, /// the SessionEntry rule): a pure transcript value asserted from tests /// off the main actor. nonisolated struct SessionRow: Identifiable { /// #177 (S2): who spoke a text row — the render seam's three voices. nonisolated enum Speaker: Equatable { case agent case user case system } /// #177 (S2): the operational notice a text row carries — pure /// consumers (draft extraction, the warning treatment) switch on this /// data, never on prefix matching. nonisolated enum NoticeKind: Equatable { case refused case interrupted case connectionLost case kickoff case failed case plain } nonisolated enum Content: Equatable { /// #177 (S2): the body is UNPREFIXED display text; speaker and /// notice travel as data. case text(String, Speaker, NoticeKind) /// #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. Nonisolated: /// a wire value parsed by ToolPayloads (#177) and asserted from tests /// (SessionEntry rule). Equatable (#177 S2): typed-row equality pins. nonisolated struct FixCard: Equatable { 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) let rosterURL = URL(fileURLWithPath: dir).appendingPathComponent("sessions.json") try JSONEncoder().encode(entries).write( to: rosterURL, 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. // ponytail: post-hoc chmod leaves a sub-second world-readable window // between write and chmod — createFile(0600)+rename if a hostile // local account ever matters. try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: rosterURL.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") } } /// Owner ruling (2026-11-07): the Mentor pane hosts the OPEN PIECE's /// session — this is the pure seam the pane's scoping rides. The roster is /// newest-first, so the FIRST exact `pieceTitle` match is the newest /// session for the piece; nil (no open piece, or no match) hosts nothing — /// the pane's honest empty presentation, never a foreign transcript. /// Pinned in SessionScopeTests. nonisolated extension SessionRoster { static func hostedSessionId(forOpenPieceTitle title: String?, in entries: [SessionEntry]) -> String? { guard let title else { return nil } return entries.first { $0.pieceTitle == title }?.sessionId } } /// 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? /// #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 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 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 /// Owner ruling (2026-11-07): an open-piece switch that arrived while a /// turn or pass streamed — fires at turn end /// (firePendingScopeIfRequested); an in-flight transcript is never /// torn down mid-stream. Pending-ness rides the enum, NEVER the /// target's optionality: a nil target is an explicit clear (nothing /// open hosts nothing), not "no pending request". private enum PendingScope { case none case scope(String?) } private var pendingScope: PendingScope = .none /// #137: per-pass readiness — refreshed at pane entry (re-entry /// re-fires the pane's .task — the key-added-in-Settings re-enable /// path). #181: computed in the PassReadiness module over the provider /// descriptor (the model reads no keys and no auth files); stored here /// because the pane observes it. `passReadinessWriter` is the /// injectable read seam (tests). private(set) var passReadiness: [PassKind: PassReadiness] = [:] var passReadinessWriter: (any SettingsWriting)? /// #175: the shared Portal auth store — handed to the readiness /// module's credential resolution; 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. 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() } init(host: EngineHost = EngineHost(), binaryPath: String? = nil, rosterDirectory: String? = nil) { self.host = host 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) // 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] } } /// 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? { host.chatChildPid } /// App-quit teardown (#14): close the engine children cleanly. Idempotent. func shutdown() { host.shutdownAll() phase = .idle } /// 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 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() } /// 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() } /// 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 = [line] return false } if case let .up(version, note) = start { engineVersion = version versionNote = note } return true } /// 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, host.hasChat 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.", .system, .refused), to: activeEntry?.sessionId) 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 chat.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.", .system, .refused), 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)", .system, .refused), 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 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. appendRow(.text("Resume refused — the mentor is mid-turn.", .system, .refused), 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.", .system, .refused), 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 chat.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 // Finish-audit: the replay slot is free — a scope switch that // deferred BEHIND this replay applies now. firePendingScopeIfRequested() // 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.", .system, .refused), 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 firePendingScopeIfRequested() // 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)", .system, .failed), to: entry.sessionId) return false } } /// Owner ruling (2026-11-07): the Mentor pane hosts the OPEN PIECE's /// session, never the engine's latest unconditionally — editing one /// piece must not show a conversation about another. The target is the /// pure seam's answer over the roster (`hostedSessionId` — exact /// pieceTitle match, newest first); the switch rides `resumeSession`. /// No match (or nothing open) hosts NOTHING — `activeEntry` clears and /// the pane renders its honest empty presentation; the roster is /// untouched (the Sessions pane stays the unscoped archive). Guards: a /// streaming turn or in-flight pass transcript is never interrupted — /// the switch defers to turn end; not-ready is a no-op (the pane's /// engine states own that path). func scopeHostedSession(toOpenPieceTitle pieceTitle: String?) async { guard phase.isReady else { return } guard !isStreaming else { pendingScope = .scope(pieceTitle) return } // Finish-audit: a replay in flight defers the switch too — the // scope rail is an AUTOMATIC action and must never leak a // "Resume refused" row into the transcript (the replay's // completion re-fires the pending scope). guard replayingSessionId == nil else { pendingScope = .scope(pieceTitle) return } pendingScope = .none let target = SessionRoster.hostedSessionId(forOpenPieceTitle: pieceTitle, in: roster) guard activeEntry?.sessionId != target else { return } guard let entry = roster.first(where: { $0.sessionId == target }) else { activeEntry = nil return } _ = await resumeSession(entry) } /// 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 chat = host.chat, let source = activeEntry, !isStreaming else { return nil } do { let result = try await chat.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.", .system, .refused), 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)", .system, .failed), 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, .system, .refused), 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? { host.oneShotChildPid } /// True while a pass engine is resident (spawn → verdict). var isPassEngineRunning: Bool { host.isOneShotRunning } // #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. // #181: the enum and the refresh live in the PassReadiness module. func readiness(for kind: PassKind) -> PassReadiness { passReadiness[kind] ?? .unknown } /// #181: thin delegate — the reads and the keyless fallback live in /// the PassReadiness module over the provider descriptor. 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 } passReadiness = await PassReadiness.refresh( writer: writer, portalAuthPath: portalAuthPath, ) } /// 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.", .system, .refused), to: sid) return .failed } guard let chat = host.chat else { return .failed } isStreaming = true defer { isStreaming = false // #137: a model-change restart requested mid-turn fires now. firePendingRestartIfRequested() // Owner ruling (2026-11-07): a piece switch deferred behind the // turn fires now too. firePendingScopeIfRequested() } return await turnCore( transport: chat, wireSid: sid, key: sid, prompt: prompt, // #177 (S2): the label row — an explicit label ("Compact…") is // the system's status voice, exactly as its unprefixed render // read before the typed rail; a plain prompt is the user // capsule with the prompt text as the body. labelContent: .text(label ?? prompt, label == nil ? .user : .system, .plain), ) } /// 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. #177 (S2): the label /// row arrives fully typed; its body is the display text alone. private func turnCore( transport: any EngineTransport, wireSid: String, key: String, prompt: String, labelContent: SessionRow.Content, ) async -> TurnOutcome { lastPrompt = prompt appendRow(labelContent, 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 { let (speaker, notice) = Self.agentSpeakerNotice(pending.streamingText) appendRow(.text(pending.streamingText, speaker, notice), to: key) transcripts[key]?.streamingText = "" } isStreaming = false } do { let result = try await transport.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" { // #177 (S2): agent voice with a refusal notice — renders as // serif prose exactly as before; the notice lets pure // consumers exclude it by data. appendRow(.text("(refused the prompt)", .agent, .refused), 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("connection lost — \(error.localizedDescription)", .agent, .connectionLost), 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, .system, .plain), to: Self.passTranscriptKey) } return outcome } /// The shared ONE-SHOT engine rail (#137 passes, #122 Blind Read): a /// 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, !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 // 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 // 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 outcome: TurnOutcome do { outcome = try await host.withOneShot(profile: profile) { transport in await self.oneShotTurn(transport: transport, label: label, prompt: prompt) } } 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([]), ]), ) 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 } passWireId = sid } catch { appendRow(.text("\(label) failed — \(error.localizedDescription)", .system, .failed), 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.", .system, .plain), to: Self.passTranscriptKey) return .cancelled } 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 /// 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 { host.oneShot?.notify("session/cancel", params: .object(["sessionId": .string(passSid)])) } return } guard let sid = activeEntry?.sessionId else { return } host.chat?.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 { host.killChat() for sid in transcripts.keys { transcripts[sid]?.streamingText = "" transcripts[sid]?.streamingThought = "" } phase = .starting 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) } 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() } } /// Owner ruling (2026-11-07): a deferred open-piece switch fires at turn /// end — from BOTH turn-end defers (chat sendPrompt and the pass run), /// after `isStreaming` cleared, so the scope rail re-evaluates for real. /// A deferred nil target drains too — it is an explicit clear, so the /// old piece's hosting must not survive the drain. Ceiling: a /// same-turn pendingRestart drains first and respawn's `.starting` /// window makes the scope Task no-op AFTER consumption — the scope /// is lost (pre-existing rail shape, titled and nil alike; /// ponytail: consume-at-apply is the upgrade path). private func firePendingScopeIfRequested() { guard case let .scope(title) = pendingScope else { return } pendingScope = .none Task { await scopeHostedSession(toOpenPieceTitle: title) } } /// #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 /// status; every other agent body is conversation. Static, /// nonisolated — pure, test-pinned. nonisolated static func agentSpeakerNotice( _ body: String, ) -> (speaker: SessionRow.Speaker, notice: SessionRow.NoticeKind) { body.hasPrefix("Operation interrupted:") ? (.system, .interrupted) : (.agent, .plain) } /// #177 (S2): the replayed user turn's typed content — a pass kick-off /// body is the system's status pill; any other body is the user's /// capsule. Static, nonisolated — pure, test-pinned. nonisolated static func replayedUserContent(_ body: String) -> SessionRow.Content { isPassKickoff(body) ? .text(body, .system, .kickoff) : .text(body, .user, .plain) } /// #177 (S2): a replayed pass kick-off — the engine replays the pass /// prompt as a user turn whose body opens with PassContext's fixed /// "Pass Pass N — ." line. Moved from SessionTranscriptView: /// the sniff lives at the append seam now. Static, nonisolated — pure. nonisolated static func isPassKickoff(_ body: String) -> Bool { body.hasPrefix("Pass Pass ") } } // 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. // #177 (S2): typed at the append seam — the shared agent sniff. let (speaker, notice) = Self.agentSpeakerNotice(text) appendRow(.text(text, speaker, notice), 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). // #177 (S2): the pass kick-off is typed AT THE APPEND SEAM — the // one place a replayed user turn is classified. if replaying { let text = update["content"]?.objectValue?["text"]?.stringValue ?? "" appendRow(Self.replayedUserContent(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 = ToolPayloads.researchCandidates(from: rawInput) } if !candidates.isEmpty { for candidate in candidates { appendRow(.researchNote(candidate), to: sid) } return } if let card = ToolPayloads.fixCard(from: 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)) } } /// 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 agent text row. Feeds the ask sheet's prefill. func draftCandidateText() -> String? { Self.draftCandidateText(in: rows) } /// The pure extraction (test seam): scan backwards — the LAST agent /// conversation row (.agent, .plain) wins; user rows, noticed agent /// rows (refusals, connection losses — data, not prefixes), 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(body, .agent, .plain) = row.content else { continue } let trimmed = body.trimmingCharacters(in: .whitespacesAndNewlines) if !trimmed.isEmpty { return trimmed } } return nil } }