feat(mentor): museion-tools MCP server (#23)
CI / ci (push) Canceled after 0s

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
This commit is contained in:
AlexKucera committed 2026-10-20 12:20:54 +02:00
1 parent c2e94fd825
commit 683ddf8426
29 files changed
+2626 -169

No files matched your search

+88 -19
View File
@@ -15,6 +15,9 @@ import os
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)
}
@@ -36,6 +39,17 @@ struct FixCard {
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).
@@ -62,6 +76,10 @@ final class MentorSessionModel {
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).
@@ -126,6 +144,7 @@ final class MentorSessionModel {
clientRef = nil
sessionId = nil
streamingText = ""
streamingThought = ""
phase = .starting
await startEngine()
}
@@ -216,16 +235,36 @@ final class MentorSessionModel {
phase = .ready(sessionId: sid)
}
/// Send a prompt and stream the reply. Appends the user row first; the
/// 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).
func sendPrompt(_ text: String) async {
/// 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 !prompt.isEmpty, case let .ready(sid) = phase, !isStreaming else { return }
// 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("You: \(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)")))
@@ -233,22 +272,39 @@ final class MentorSessionModel {
}
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)])]),
]))
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).
guard case .crashed = phase else {
if case .crashed = phase {
// Crash card already owns the failure surface.
} else {
rows.append(SessionRow(content: .text("Mentor: connection lost — \(error.localizedDescription)")))
return
}
return .failed
}
}
@@ -294,9 +350,12 @@ final class MentorSessionModel {
guard let update = params.objectValue?["update"]?.objectValue else { return }
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
switch kind {
case "agent_message_chunk", "agent_thought_chunk":
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
@@ -329,15 +388,25 @@ final class MentorSessionModel {
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 = object["pattern"]?.stringValue,
let problemValue = object["problem"]?.stringValue else { return nil }
guard let patternValue = card["pattern"]?.stringValue,
let problemValue = card["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"
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"
}
}