Files
museion/Museion/MentorSessionModel.swift
T
AlexKucera 683ddf8426
CI / ci (push) Canceled after 0s
feat(mentor): museion-tools MCP server (#23)
Headless --serve-mcp role in the app binary: NDJSON JSON-RPC on stdio
exposing query_learnings and submit_fix_cards (ADR-0006 cards,
anchor-validated; stale lands flagged, never rejected), registered
into the museion profile at provisioning. Cards persist per piece
under <piece>/cards/ and surface in a floating Fix Cards palette
with pass-stamped provenance.

Live dogfood drove the shape: session/prompt waits pass length (the
15 s request default abandoned working turns), a liveness row and a
persisted Debug checkbox (off) split writing sessions from debug
chatter, the verdict references findings by title only while the
cards carry the detail (persona v1.3 — tools work in silence), and
the #24 pass rails (pass bar, TurnOutcome seam, snapshots) ride in.

Three-reviewer audit round: piece-path shape guard closes the
JSON-drop and substring-oracle holes, nested submit rawInput parsing
(the flat parser never matched the live rail), missing stopReason
never advances a pass, 1 MB stdin cap, card scan off MainActor.
296 tests green; every behavioral fix flip-verified.

Closes #23
2026-10-20 12:20:54 +02:00

413 lines
15 KiB
Swift

//
// MentorSessionModel.swift
// Museion
//
// M0 ACP bridge (#14): the pane's @Observable model — lazy bridge lifecycle,
// one session, prompt streaming, fix-card render, crash → restart prompt.
//
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)
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
}
/// 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
}
/// 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).
@MainActor
@Observable
final class MentorSessionModel {
enum Phase: Equatable {
case idle
case starting
case ready(sessionId: String)
case crashed(lastPrompt: String?)
var isReady: Bool {
if case .ready = self {
return true
}
return false
}
}
private(set) var phase: Phase = .idle
/// True while a turn streams — the Stop button's target.
private(set) var isStreaming = false
private(set) var rows: [SessionRow] = []
/// Streaming buffer for the in-flight agent message; flushed to a row on completion.
private(set) var 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.
private(set) var streamingThought = ""
/// 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 client: ACPEngineClient?
private var sessionId: String?
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) {
self.binaryPath = binaryPath
}
deinit {
// nonisolated deinit (Swift 6): close() is nonisolated-safe on the client.
shutdownClientDirectly()
}
/// 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.
func openSession() async {
guard phase == .idle else { return }
phase = .starting
await startEngine()
}
/// Restart after a crash — keeps the transcript (never data loss) 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
sessionId = nil
streamingText = ""
streamingThought = ""
phase = .starting
await startEngine()
}
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
client.onCrash = { [weak self] in
Task { @MainActor in
self?.handleCrash()
}
}
client.onStderrLine = { [weak self] line in
Task { @MainActor in
self?.appendStderr(line)
}
}
do {
try client.start { [weak self] method, params in
Task { @MainActor in
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 + session/new (map decisions: advisory version verify; cwd ~).
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
// New session — cwd ~ (map decision). Adapter ≥0.21.5 requires mcpServers
// (ACP SDK NewSessionRequest); Museion ships none, so the honest empty list.
let newResult = try await client.request(
"session/new",
params: .object([
"cwd": .string(cwdProvider()),
"mcpServers": .array([]),
]),
)
guard let sid = newResult?.objectValue?["sessionId"]?.stringValue else {
throw ACPEngineClient.TransportError(message: "session/new returned no sessionId")
}
sessionId = sid
phase = .ready(sessionId: sid)
}
/// Send a prompt and stream the reply. 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, case let .ready(sid) = phase, !isStreaming else { return .failed }
lastPrompt = prompt
rows.append(SessionRow(content: .text(label ?? "You: \(prompt)")))
isStreaming = true
defer {
// Flush the thinking first (it preceded the message), collapsed.
if !streamingThought.isEmpty {
rows.append(SessionRow(content: .thought(streamingThought)))
streamingThought = ""
}
// Flush any streamed-but-unfinished agent text into a row.
if !streamingText.isEmpty {
rows.append(SessionRow(content: .text("Mentor: \(streamingText)")))
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" {
rows.append(SessionRow(content: .text("Mentor: (refused the prompt)")))
}
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 {
rows.append(SessionRow(content: .text("Mentor: connection lost — \(error.localizedDescription)")))
}
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 = sessionId else { return }
client?.notify("session/cancel", params: .object(["sessionId": .string(sid)]))
}
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)
}
}
/// 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: - Notification decoding
private func handleNotification(method: String, params: JSONValue?) {
guard method == "session/update",
let params,
let sessionId = params.objectValue?["sessionId"]?.stringValue,
sessionId == self.sessionId else { return }
guard let update = params.objectValue?["update"]?.objectValue else { return }
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
switch kind {
case "agent_message_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
streamingText += text
case "agent_thought_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
streamingThought += text
case "user_message_chunk":
// The engine echoes the user message; we already rendered it.
break
case "tool_call":
appendToolCall(update)
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()
rows.append(SessionRow(content: .raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? "")))
}
}
/// 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]) {
let title = update["title"]?.stringValue ?? "tool call"
let rawInput = update["rawInput"]
if let card = FixCard(rawInput: rawInput) {
rows.append(SessionRow(content: .fixCard(card)))
return
}
let json = (try? JSONSerialization.data(withJSONObject: rawInput?.any ?? [:], options: [.sortedKeys])) ?? Data()
rows.append(SessionRow(content: .raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? "")))
}
}
/// 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"
}
}