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

+186 -18
View File
@@ -17,25 +17,17 @@ import Testing
/// Builds a fake engine binary that speaks enough ACP for the M0 client.
/// `mode`: `full` answers everything; `crashAfterHandshake` exits 1 right
/// after answering initialize; `hangOnPrompt` sleeps 30 s inside prompt.
/// after answering initialize; `hangOnPrompt` sleeps 30 s inside prompt;
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled";
/// `refuseOnPrompt` answers stopReason "refusal" (no chunks).
/// The mode travels in a file next to the fake (self-locating — race-free
/// under parallel suites, same convention as ProfileProvisionerTests).
/// The fix-card payload travels base64-encoded so shell quoting can't break.
private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "full") -> String {
/// Internal (not private) so later test files can reuse the fake (#24).
func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "full") -> String {
let path = (dir as NSString).appendingPathComponent(name)
let modeFile = (dir as NSString).appendingPathComponent("\(name)-mode")
// ponytail: built field-by-field so the line stays under the lint cap.
let card: [(String, String)] = [
("pattern", "Blame tense"),
("problem", "Never pivots to choice"),
("diagnosticQuestion", "What tense?"),
("fix", "Pivot on the hinge"),
("anchor", "We should stop listening."),
("provenance", "posts/x · pass 1"),
("status", "proposed"),
]
let fixCard = card.map { "\"\($0.0)\":\"\($0.1)\"" }.joined(separator: ",")
let fixCardB64 = Data(("{" + fixCard + "}").utf8).base64EncodedString()
let fixCardB64 = fixCardPayloadB64()
// ponytail: one echo per wire message — long payloads ride shell vars so
// each line stays under the lint cap and inspectable against the schema.
let script = """
@@ -45,18 +37,31 @@ private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: Stri
card=$(print -- '\(fixCardB64)' | base64 -d)
framing='{"jsonrpc":"2.0","id":'
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-1","update":'
while IFS= read -r line; do
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \n escapes of multi-line prompts
[[ -z "$line" ]] && continue
method=$(echo "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(echo "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
if [[ "$method" == "initialize" ]]; then
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
[[ "$mode" == "crashAfterHandshake" ]] && exit 1
elif [[ "$method" == "session/new" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
elif [[ "$method" == "session/prompt" ]]; then
if [[ "$mode" == "refuseOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"refusal"}}'
continue
fi
echo $notify'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"echo"},"messageId":"u1"}}}'
echo $notify'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"weighing the structure"},"messageId":"t1"}}}'
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello "},"messageId":"m1"}}}'
if [[ "$mode" == "cancelOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"cancelled"}}'
continue
fi
if [[ "$mode" == "noStopReason" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
continue
fi
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}'
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
if [[ "$mode" == "hangOnPrompt" ]]; then
@@ -76,7 +81,20 @@ private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: Stri
return path
}
private func acpTempDir(_ label: String) -> String {
/// The fix-card payload for the fake's tool call, base64-encoded so shell
/// quoting can never break the wire JSON. The REAL submit_fix_cards
/// argument shape (snake_case, anchor as object) — pins the nested parse;
/// the flat #14-era shape was a regression the parser never matched the
/// live rail (review).
private func fixCardPayloadB64() -> String {
let card = #"{"pattern":"Blame tense","problem":"Never pivots to choice","# +
#""diagnostic_question":"What tense?","fix":"Pivot on the hinge","# +
#""anchor":{"quote":"We should stop listening.","occurrence":1}}"#
let json = #"{"piece_path":"/tmp/piece","cards":["# + card + #"]}"#
return Data(json.utf8).base64EncodedString()
}
func acpTempDir(_ label: String) -> String {
let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)"
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
return dir
@@ -187,6 +205,156 @@ struct ACPClientTests {
}
#expect(gone)
}
// MARK: - Turn outcome seam (#24 S3.1: sendPrompt → TurnOutcome)
// The suite hosts these model tests (not free functions like the model
// tests below) so the suite-name test filter runs them.
@MainActor
@Test func `sendPrompt returns ended end_turn and streams text`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-ended"))
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let streamed = model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("Hello mentor.")
}
return false
}
#expect(streamed)
model.shutdown()
}
@MainActor
@Test func `labeled prompt renders the label not the wire stub`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-label"))
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
// The pass orchestrator sends a long wire stub; only the label may land.
await model.sendPrompt("STUB-WIRE-PROMPT that must never surface", label: "Pass 1 · My Post")
var texts: [String] = []
for row in model.rows {
if case let .text(text) = row.content {
texts.append(text)
}
}
#expect(texts.contains("Pass 1 · My Post"))
#expect(!texts.contains { $0.contains("STUB-WIRE-PROMPT") })
model.shutdown()
}
@MainActor
@Test func `cancelled stopReason maps to TurnOutcome cancelled`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-cancel"), mode: "cancelOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .cancelled)
model.shutdown()
}
/// Review pin: a prompt response without stopReason is NOT a completed
/// turn — .failed, so a pass never advances on a maybe.
@MainActor
@Test func `missing stopReason maps to failed`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-nostop"), mode: "noStopReason")
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .failed)
model.shutdown()
}
/// #23 dogfood regression pin: session/prompt's response arrives when the
/// TURN ends — minutes into a pass. The client's 15 s request default
/// abandoned live turns ("connection lost" while the engine kept working,
/// Stop vanished with isStreaming). sendPrompt must wait pass-length.
@Test func `prompt deadline is pass length not the request default`() {
#expect(MentorSessionModel.promptTimeout >= 600)
}
/// #23 dogfood: the writing-session filter — prose + card events stay,
/// raw session/tool rows and thinking are debug-only.
@Test func `writing-session filter keeps prose and cards, hides raw and thought`() {
#expect(MentorPaneView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
#expect(MentorPaneView.isWritingRow(SessionRow(content: .fixCard(
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
))))
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .thought("thinking…"))))
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
}
@MainActor
@Test func `refusal maps to ended refusal and still renders the refusal row`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-refusal"), mode: "refuseOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "refusal"))
let refused = model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("(refused the prompt)")
}
return false
}
#expect(refused)
model.shutdown()
}
@MainActor
@Test func `thought chunks land in a collapsed thought row not the critique`() async {
let fake = makeFakeACP(at: acpTempDir("thought-lane"))
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
// The fake streams a thought chunk BEFORE the message chunks — the
// live shape of a pass turn (long thinking, then the critique).
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let thought = model.rows.contains { row in
if case let .thought(text) = row.content {
return text == "weighing the structure"
}
return false
}
#expect(thought)
// The critique text stays clean — thinking never bleeds into it.
let critique = model.rows.contains { row in
if case let .text(text) = row.content {
return text == "Mentor: Hello mentor."
}
return false
}
#expect(critique)
#expect(!model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("weighing")
}
return false
})
model.shutdown()
}
@MainActor
@Test func `transport failure mid-turn maps to TurnOutcome failed`() async throws {
let fake = makeFakeACP(at: acpTempDir("outcome-failed"), mode: "hangOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
// Deterministic transport failure through the model: hangOnPrompt keeps
// the turn pending, then shutdown() closes the client — the in-flight
// session/prompt fails with a transport error, the same route a mid-turn
// engine error takes. crashAfterHandshake can't pin this: after the crash
// the phase is .crashed and sendPrompt's guard refuses before any request.
let promptTask = Task { await model.sendPrompt("hello mentor") }
for _ in 0 ..< 100 where !model.isStreaming {
try await Task.sleep(for: .milliseconds(50))
}
model.shutdown()
let outcome = await promptTask.value
#expect(outcome == .failed)
}
}
// MARK: - Model tests