Files
museion/Museion/MentorSessionModel.swift
T
AlexKuceraandClaude f21d3a6844
CI / ci (push) Canceled after 0s
feat(acp): add M0 ACP bridge — engine child + mentor pane (fixes #14)
Spawn hermes acp -p museion over NDJSON JSON-RPC stdio via a
hand-rolled thin client (no Swift SDK exists). The mentor debug
pane streams replies, renders fix-card tool calls as structured
cards (ADR-0006), cancels via session/cancel, tears down on quit
(willTerminate), and surfaces a restart prompt on engine crash —
never data loss. Version verify against state.json is advisory.

Fake ACP server test double (zsh speaking real NDJSON) covers
handshake, streaming + fix-card, drift, crash latch, cancel,
teardown. 36/36 tests green; finish-audit fixes included (wired
binaryPath, focus-loss teardown bug, double onCrash latch).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-16 18:57:41 +02:00

331 lines
11 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)
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
}
/// 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 = ""
/// 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 = ""
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).
var note: String?
if let version {
let recorded = recordedVersionProvider()
if let recorded, recorded != 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).
let newResult = try await client.request(
"session/new",
params: .object(["cwd": .string(cwdProvider())]),
)
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; the
/// stop_reason response ends the turn (refusal maps to a plain note —
/// wire-verified edge semantics).
func sendPrompt(_ text: String) async {
let prompt = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !prompt.isEmpty, case let .ready(sid) = phase, !isStreaming else { return }
lastPrompt = prompt
rows.append(SessionRow(content: .text("You: \(prompt)")))
isStreaming = true
defer {
// Flush any streamed-but-unfinished agent text into a row.
if !streamingText.isEmpty {
rows.append(SessionRow(content: .text("Mentor: \(streamingText)")))
streamingText = ""
}
isStreaming = false
}
do {
let result = try await client!.request("session/prompt", params: .object([
"sessionId": .string(sid),
"prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]),
]))
let stopReason = result?.objectValue?["stopReason"]?.stringValue ?? ""
if stopReason == "refusal" {
rows.append(SessionRow(content: .text("Mentor: (refused the prompt)")))
}
} catch {
// Transport failure mid-turn: the crash path owns the UX; keep the
// partial transcript (never data loss).
guard case .crashed = phase else {
rows.append(SessionRow(content: .text("Mentor: connection lost — \(error.localizedDescription)")))
return
}
}
}
/// 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)
}
}
// 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", "agent_thought_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
streamingText += 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 }
// A fix-card-shaped payload carries at least pattern + problem.
guard let patternValue = object["pattern"]?.stringValue,
let problemValue = object["problem"]?.stringValue else { return nil }
pattern = patternValue
problem = problemValue
diagnosticQuestion = object["diagnosticQuestion"]?.stringValue ?? ""
fix = object["fix"]?.stringValue ?? ""
anchor = object["anchor"]?.stringValue ?? ""
provenance = object["provenance"]?.stringValue ?? "engine"
status = object["status"]?.stringValue ?? "proposed"
}
}