Files
museion/MuseionTests/MCPServerWireTests.swift
T
AlexKucera b02d36bb5d
CI / ci (push) Canceled after 0s
feat(mentor): research & library-light (S8) (#29)
The mentor researches mid-pass and its findings arrive as candidate
source-notes with provenance inside their Session. A third museion-
tools tool, submit_research_notes, is the typed rail (ADR-0006
posture): decode-validate only, reply {"received": N}, write NOTHING
— the session is the holding area, and keeping is the writer's act.

Candidates ride the transcript as first-class rows (researchNote):
parsed from the tool call's rawInput by payload shape — the notes
array routes before the fix-card parse, titles are display text —
one row per note, all-or-nothing per batch, the wire's whitespace
rule mirrored so both boundaries agree. Resume re-materializes them
for free: replays re-run the same parse; dispositions reset honestly
(they were never persisted — engine-owned cargo, ADR-0007).

The writer curates in place (full cards in the shared transcript, no
palette — a handful curates where it lands): Keep opens the
ask-before sheet (G9; PromoteAskSheet posture — inline refusal,
buttons kept) and ONE confirm lands one plain markdown note with
provenance into the piece's research/ via writeResearchNote — the
one folder(of:) id lookup anchors it inside this Home, a symlinked
research/ refuses, collision -2; Reject vanishes, recording nothing.
The pass stub names the rail and forbids the engine writing
candidates itself; kept notes flip hasResearch, so every later pass
sees the research/ path (S8.3 at v1 depth).

Finish-audit (three reviewers) drove the whitespace-parity and
shape-routing fixes, the ResearchNoteContent dedup, and a poll-loop
fix for the debounce rig's sidecar half that the larger suite's load
had pushed past its fixed sleep — full suite green (373 tests).

Closes #29
2026-10-22 14:06:16 +02:00

320 lines
14 KiB
Swift

//
// MCPServerWireTests.swift
// MuseionTests
//
// #23 (M2, slice 1): the museion-tools wire contract, in-process through
// MCPServer.run(lines:write:) over real JSON-RPC lines — echoed
// protocolVersion, silent notifications, typed tools/list, the full
// submit round-trip with the card on disk, isError tool failures,
// -32601 unknown method, -32700 garbage. Wire facts verified live
// against the real hermes MCP client.
//
// ## Scenario: candidate rail and the keep write
// From #29 (S8.1/S8.2)
// Given a piece in the library and the mentor researching mid-pass
// When the engine delivers findings as submit_research_notes tool calls
// Then well-formed candidates are accepted with a received count and
// nothing is written anywhere; malformed ones answer a tool error
// And the pass prompt names that rail
// And when the writer keeps one, one plain markdown note with provenance
// lands in the piece's research/ — nothing else auto-saves.
//
import Foundation
@testable import Museion
import Testing
/// Run lines through the server loop, parsing every reply as JSON objects.
private func runWire(_ lines: [String]) throws -> [[String: Any]] {
var replies: [String] = []
MCPServer.run(lines: AnyIterator(lines.makeIterator())) { replies.append($0) }
return try replies.compactMap {
try JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any]
}
}
/// Review pin (DoS): a line over the 1 MB frame cap answers -32600 —
/// never reaches JSONSerialization.
@Test func `oversized line answers line too long`() throws {
let big = String(repeating: "a", count: 1_048_577)
let replies = try runWire([big])
let error = replies[0]["error"] as? [String: Any]
#expect((error?["code"] as? Int) == -32600)
}
private let initializeLine = #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#
private let initializedLine = #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#
private let toolsListLine = #"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#
/// The text payload of a tools/call result.
private func toolText(_ result: [String: Any]) throws -> String {
let content = try #require(result["content"] as? [[String: Any]])
return try #require(content.first?["text"] as? String)
}
struct MCPServerWireTests {
@Test func `initialize echoes client protocol version`() throws {
let replies = try runWire([initializeLine])
#expect(replies.count == 1)
#expect(replies[0]["id"] as? Int == 1)
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["protocolVersion"] as? String == "2025-06-18")
let info = try #require(result["serverInfo"] as? [String: Any])
#expect(info["name"] as? String == "museion-tools")
#expect(result["capabilities"] is [String: Any])
}
@Test func `initialize falls back to pinned protocol version`() throws {
let replies = try runWire([#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["protocolVersion"] as? String == "2025-11-25")
}
@Test func `notifications never reply`() throws {
#expect(try runWire([initializedLine]).isEmpty)
}
@Test func `ping answers empty result`() throws {
let replies = try runWire([#"{"jsonrpc":"2.0","id":9,"method":"ping"}"#])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result.isEmpty)
}
@Test func `tools list exposes all three tools with schemas`() throws {
let replies = try runWire([toolsListLine])
let result = try #require(replies[0]["result"] as? [String: Any])
let tools = try #require(result["tools"] as? [[String: Any]])
#expect(
Set(tools.compactMap { $0["name"] as? String })
== ["query_learnings", "submit_fix_cards", "submit_research_notes"],
)
let submit = try #require(tools.first { $0["name"] as? String == "submit_fix_cards" })
let schema = try #require(submit["inputSchema"] as? [String: Any])
let required = try #require(schema["required"] as? [String])
#expect(required.contains("piece_path"))
#expect(required.contains("cards"))
let properties = try #require(schema["properties"] as? [String: Any])
let cardsProp = try #require(properties["cards"] as? [String: Any])
let cardItems = try #require(cardsProp["items"] as? [String: Any])
let cardRequired = try #require(cardItems["required"] as? [String])
#expect(cardRequired.contains("pattern"))
#expect(cardRequired.contains("problem"))
#expect(cardRequired.contains("anchor"))
#expect(cardRequired.contains("lane"))
#expect(cardRequired.contains("emitter"))
let cardProps = try #require(cardItems["properties"] as? [String: Any])
let anchor = try #require(cardProps["anchor"] as? [String: Any])
let anchorProps = try #require(anchor["properties"] as? [String: Any])
let occurrence = try #require(anchorProps["occurrence"] as? [String: Any])
#expect(occurrence["type"] as? String == "integer")
#expect(occurrence["default"] as? Int == 1)
let query = try #require(tools.first { $0["name"] as? String == "query_learnings" })
let querySchema = try #require(query["inputSchema"] as? [String: Any])
#expect(try #require(querySchema["required"] as? [String]) == ["piece_path"])
// #29 (S8.1): the research rail requires piece_path + notes, and a
// note item requires title + url.
let research = try #require(tools.first { $0["name"] as? String == "submit_research_notes" })
let researchSchema = try #require(research["inputSchema"] as? [String: Any])
let researchRequired = try #require(researchSchema["required"] as? [String])
#expect(researchRequired.contains("piece_path"))
#expect(researchRequired.contains("notes"))
let researchProps = try #require(researchSchema["properties"] as? [String: Any])
let notesProp = try #require(researchProps["notes"] as? [String: Any])
let noteItems = try #require(notesProp["items"] as? [String: Any])
let noteRequired = try #require(noteItems["required"] as? [String])
#expect(noteRequired.contains("title"))
#expect(noteRequired.contains("url"))
}
/// One throwaway wire piece: home + `projects/posts/<name>/post.md`
/// (the round-trip test adds its learnings dir on top).
private func seedWirePiece(_ name: String) throws -> (home: URL, piece: URL) {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("mcp-wire-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
let piece = home.appendingPathComponent("projects/posts/\(name)", isDirectory: true)
try FileManager.default.createDirectory(at: piece, withIntermediateDirectories: true)
try "---\ntype: post\n---\nThe repeated anchor line.\n"
.write(to: piece.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
return (home, piece)
}
@Test func `submit and query round trip through the wire`() throws {
let (home, piece) = try seedWirePiece("test-piece")
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: learnings, withIntermediateDirectories: true)
try "wire learning".write(to: learnings.appendingPathComponent("l.md"), atomically: true, encoding: .utf8)
// swiftlint:disable line_length
let submit = """
{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"submit_fix_cards","arguments":{"piece_path":"\(piece.path)","cards":[{"pattern":"Hedging","problem":"The hedge weakens the claim.","anchor":{"quote":"repeated anchor line"},"lane":"mechanical","emitter":"lint"}]}}}
"""
// swiftlint:enable line_length
let query = """
{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"query_learnings","arguments":{"piece_path":"\(piece.path)"}}}
"""
let replies = try runWire([initializeLine, initializedLine, submit, query])
// initialize + two tool results; the notification stayed silent.
#expect(replies.count == 3)
let submitResult = try #require(replies[1]["result"] as? [String: Any])
#expect(submitResult["isError"] == nil)
let payload = try #require(
try JSONSerialization.jsonObject(with: Data(toolText(submitResult).utf8)) as? [String: Any],
)
let cards = try #require(payload["cards"] as? [[String: Any]])
#expect(cards.first?["anchor_status"] as? String == "valid")
let file = try #require(cards.first?["file"] as? String)
#expect(file.hasSuffix("-hedging.json"))
#expect(
FileManager.default.fileExists(atPath: piece.appendingPathComponent("cards/\(file)").path),
)
let queryResult = try #require(replies[2]["result"] as? [String: Any])
let learned = try #require(
try JSONSerialization.jsonObject(with: Data(toolText(queryResult).utf8)) as? [String: Any],
)
let learningsPayload = try #require(learned["learnings"] as? [[String: Any]])
#expect(learningsPayload.first?["markdown"] as? String == "wire learning")
}
@Test func `tool failures set is error`() throws {
let lines = [
// Missing piece.
// swiftlint:disable:next line_length
#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"submit_fix_cards","arguments":{"piece_path":"/nonexistent/piece","cards":[{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"lint"}]}}}"#,
// Unknown tool name.
#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"wat","arguments":{}}}"#,
// Malformed arguments (piece_path missing).
#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"query_learnings","arguments":{}}}"#,
]
for line in lines {
let replies = try runWire([line])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["isError"] as? Bool == true, "expected isError for: \(line)")
#expect(replies[0]["error"] == nil)
let text = try toolText(result)
#expect(!text.isEmpty)
}
}
@Test func `unknown method errors 32601`() throws {
let replies = try runWire([#"{"jsonrpc":"2.0","id":6,"method":"wat/thing"}"#])
let error = try #require(replies[0]["error"] as? [String: Any])
#expect(error["code"] as? Int == -32601)
#expect(replies[0]["result"] == nil)
}
@Test func `garbage line errors 32700 with null id`() throws {
let replies = try runWire(["not json at all"])
let error = try #require(replies[0]["error"] as? [String: Any])
#expect(error["code"] as? Int == -32700)
#expect(replies[0]["id"] is NSNull)
}
/// #25 (S3.2): the ceiling backstop is honest on the wire — 11 valid cards
/// submit, the ranked head (10) lands on disk, the reply says one dropped.
@Test func `submit over the ceiling drops the tail and reports it`() throws {
let (_, piece) = try seedWirePiece("ceiling-piece")
let cards = (1 ... 11).map { index in
[
"pattern": "Pattern \(index)",
"problem": "The problem \(index).",
"anchor": ["quote": "repeated anchor line"],
"lane": "mechanical",
"emitter": "lint",
] as [String: Any]
}
let request: [String: Any] = [
"jsonrpc": "2.0",
"id": 12,
"method": "tools/call",
"params": ["name": "submit_fix_cards", "arguments": ["piece_path": piece.path, "cards": cards] as [String: Any]],
]
let line = try #require(String(data: JSONSerialization.data(withJSONObject: request), encoding: .utf8))
let replies = try runWire([line])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["isError"] == nil)
let payload = try #require(
try JSONSerialization.jsonObject(with: Data(toolText(result).utf8)) as? [String: Any],
)
let landed = try #require(payload["cards"] as? [[String: Any]])
#expect(landed.count == 10)
#expect(payload["dropped_over_ceiling"] as? Int == 1)
let onDisk = ((try? FileManager.default.contentsOfDirectory(
atPath: piece.appendingPathComponent("cards").path,
)) ?? []).filter { $0.hasSuffix(".json") }
#expect(onDisk.count == 10)
}
/// #29 (S8.1): one submit_research_notes wire line over the given
/// arguments (JSONSerialization-built — no line_length fights).
private func researchCall(id: Int, arguments: [String: Any]) throws -> String {
let request: [String: Any] = [
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": ["name": "submit_research_notes", "arguments": arguments] as [String: Any],
]
return try #require(String(data: JSONSerialization.data(withJSONObject: request), encoding: .utf8))
}
/// #29 (S8.1): well-formed candidates answer a received count — and
/// create NOTHING on disk (candidates live in their session; keeping
/// is the writer's separate act).
@Test func `research notes reply received and write nothing`() throws {
let (_, piece) = try seedWirePiece("research-piece")
let note = [
"title": "The Long Now",
"url": "https://example.org/long-now",
"quote": "pace layers",
"note": "Supports the slowness claim.",
] as [String: Any]
let line = try researchCall(id: 21, arguments: ["piece_path": piece.path, "notes": [note]])
let replies = try runWire([initializeLine, initializedLine, line])
#expect(replies.count == 2)
let result = try #require(replies[1]["result"] as? [String: Any])
#expect(result["isError"] == nil)
let payload = try #require(
try JSONSerialization.jsonObject(with: Data(toolText(result).utf8)) as? [String: Any],
)
#expect(payload["received"] as? Int == 1)
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("research").path))
}
/// #29 (S8.1): malformed candidates answer a tool error — the trust
/// boundary. Missing fields fail decode; a whitespace-only title is
/// refused; none of them writes anything.
@Test func `malformed research notes answer a tool error`() throws {
let (_, piece) = try seedWirePiece("research-error-piece")
let lines = try [
// notes item missing url → decode fails.
researchCall(id: 31, arguments: ["notes": [["title": "T"]]]),
// notes item missing title → decode fails.
researchCall(id: 32, arguments: ["notes": [["url": "https://example.org"]]]),
// whitespace-only title → CardError.
researchCall(id: 33, arguments: [
"piece_path": piece.path,
"notes": [["title": " ", "url": "https://example.org"]],
]),
// piece_path missing → decode fails.
researchCall(id: 34, arguments: [
"notes": [["title": "T", "url": "https://example.org"]],
]),
]
for line in lines {
let replies = try runWire([line])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["isError"] as? Bool == true, "expected isError for: \(line)")
#expect(replies[0]["error"] == nil)
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("research").path))
}
}
}