Files
museion/Museion/MentorSessionModel.swift
T
AlexKucera ae234350ef
CI / ci (push) Canceled after 0s
feat(sessions): new post from session & drills (S2.7-8) (#30)
A freeform Session births a Post. "New Post" in the Sessions pane
opens an ask-before sheet prefilled with the session's last mentor
reply (editable, G9); ONE confirm materializes the piece under
projects/posts/ stamped origin: ai - immutable frontmatter, never
stats-eligible - and opens it in Posts; a failed write keeps the
sheet up with the reason inline and the draft intact. writeNew
gains an origin parameter (additive default .writer, every existing
caller compiles).

"New Brainstorm" is a session started with an opener prompt - no new
machinery (beginBrainstormSession over the normal new+prompt rails).
The freeform composer (input, liveness, Stop) moved from
MentorPaneView into the shared SessionTranscriptView: one
conversation surface, two panes - the Sessions pane stops being a
read-only transcript. Drill offers (S2.8) wire as one pass-persona
section (v1.4): the seeded micro-drill doctrine owns the motivation
moment, the two-minute bound, the single shelf, and the vanish -
session flavor, no machinery beyond S2.3.

Resume now speaks the real adapter wire. Live-probed against the
engine: 0.21.5 answers session/load with the id at
_meta.hermes.sessionProvenance.acpSessionId and NO top-level
sessionId - resumeSession accepts both shapes; every prior
real-engine resume misread as "engine does not know this session".
The fake ACP server answers load in the real shape (a
loadReplayLegacy knob pins the older contract), so the whole resume
suite guards the live wire.

New pins: draft-candidate extraction (last mentor row wins; thought/
card/research/raw lanes and refusal/connection rows never prefill),
ai-stamp write + immutability through overwrite, brainstorm roster +
labeled opener, legacy-shape resume. Finish-audit (three
reviewers, parallel) converged on the confirm() dismissal that
destroyed the edited draft on a failed write - fixed with
sheet-local error state (stale-refusal re-show dies with the
presentation) - and surfaced the missing brainstorm and legacy-shape
pins; the resume fix was flip-verified (removing the provenance
fallback fails the provenance pins). Full suite green (379 tests).

Closes #30
2026-10-22 17:04:12 +02:00

917 lines
36 KiB
Swift

//
// 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.
//
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?
/// 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 child cleanly. Idempotent.
func shutdown() {
shutdownClientDirectly()
client = nil
clientRef = nil
phase = .idle
}
/// nonisolated deinit + MainActor shutdown share this: client.close() is
/// thread-safe (its own serial queue) and idempotent.
private nonisolated func shutdownClientDirectly() {
clientRef?.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?
/// 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 }
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 }
await ensureDefaultSession()
}
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 {
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)
}
/// The pass's own session (#28): wire session/new + roster
/// 'Pass N · <title>' + activate, so the pass prompt streams into ITS
/// transcript. Nil when the engine isn't ready or refuses.
@discardableResult
func beginPassSession(kind: PassKind, pieceTitle: String) async -> SessionEntry? {
guard phase.isReady, client != nil else { return nil }
return await createSession(name: "\(kind.rawValue) · \(pieceTitle)", 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/beginPassSession.
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())
roster.insert(entry, at: 0)
transcripts[sid] = SessionTranscript()
activeEntry = entry
phase = .ready
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.
activeEntry = entry
phase = .ready
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 '<name> (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(),
)
roster.insert(entry, at: 0)
transcripts[sid] = SessionTranscript()
activeEntry = entry
phase = .ready
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
}
private func saveRoster() {
SessionRoster.save(roster, directory: rosterDirectory)
}
/// 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
}
lastPrompt = prompt
appendRow(.text(label ?? "You: \(prompt)"), to: sid)
isStreaming = true
defer {
// Flush the thinking first (it preceded the message), collapsed.
if let pending = transcripts[sid], !pending.streamingThought.isEmpty {
appendRow(.thought(pending.streamingThought), to: sid)
transcripts[sid]?.streamingThought = ""
}
// Flush any streamed-but-unfinished agent text into a row.
if let pending = transcripts[sid], !pending.streamingText.isEmpty {
appendRow(.text("Mentor: \(pending.streamingText)"), to: sid)
transcripts[sid]?.streamingText = ""
}
isStreaming = false
}
// Parity with the phase guard above: never lean on two invariants
// (.ready ⇒ client) where one guard suffices.
guard let client else { return .failed }
do {
let result = try await client.request(
"session/prompt",
params: .object([
"sessionId": .string(sid),
"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: sid)
}
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: sid)
}
return .failed
}
}
/// 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.
func stopStreaming() {
guard isStreaming, let sid = activeEntry?.sessionId else { return }
client?.notify("session/cancel", params: .object(["sessionId": .string(sid)]))
}
/// 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.
private func handleNotification(method: String, params: JSONValue?) {
guard method == "session/update",
let params,
let sid = params.objectValue?["sessionId"]?.stringValue,
transcripts[sid] != nil else { return }
guard let update = params.objectValue?["update"]?.objectValue else { return }
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
let replaying = sid == 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: sid)
} else {
transcripts[sid]?.streamingText += text
}
case "agent_thought_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
if replaying {
appendRow(.thought(text), to: sid)
} else {
transcripts[sid]?.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: sid)
}
case "tool_call":
appendToolCall(update, to: sid)
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: sid)
}
}
/// 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
}
}