Files
museion/MuseionTests/MCPToolsTests.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

265 lines
12 KiB
Swift

//
// MCPToolsTests.swift
// MuseionTests
//
// #23 (M2, slice 1): the museion-tools tool layer — pure anchor
// validation, the submit round-trip (one snake_case JSON file per card
// under <piece>/cards/), scan ordering, and the learnings reader.
// Temp-home convention (PostStoreTests).
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Home in a temp dir (PostStoreTests convention).
private func toolsHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("mcp-tools-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
try write(home)
return home
}
/// One piece under projects/posts/<id>/post.md; returns the piece folder.
/// `type: nil` writes no frontmatter block at all.
@discardableResult
private func writePiece(
_ home: URL,
id: String = "test-piece",
type: String? = "post",
body: String = "# Title\n\nThe repeated anchor line.\nAgain the repeated anchor line.\n",
) throws -> URL {
let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let block = type.map { "---\ntype: \($0)\npass_state: First Draft\norigin: writer\n---\n" } ?? ""
try (block + body).write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
return dir
}
/// One wire-shaped card with test-friendly defaults. Internal — shared
/// with PostsModelTests (review: a hand-copy drifted here).
func card(
pattern: String = "Hedging",
problem: String = "The hedge weakens the claim.",
diagnosticQuestion: String? = nil,
quote: String = "repeated anchor line",
occurrence: Int = 1,
) -> FixCardStore.Input {
FixCardStore.Input(
pattern: pattern,
problem: problem,
diagnosticQuestion: diagnosticQuestion,
fix: nil,
anchor: .init(quote: quote, occurrence: occurrence),
lane: .mechanical,
emitter: .lint,
provenance: nil,
)
}
/// A fully-stamped card for hand-written fixtures (scan tests).
private func storedCard(pattern: String) -> FixCardStore.StoredFixCard {
FixCardStore.StoredFixCard(
id: UUID(),
submittedAt: Date(timeIntervalSince1970: 0),
pattern: pattern,
problem: "p",
diagnosticQuestion: "",
fix: "",
anchor: .init(quote: "q", occurrence: 1),
lane: .mechanical,
emitter: .lint,
provenance: nil,
status: "open",
anchorStatus: .valid,
)
}
struct MCPToolsTests {
@Test func `anchor validation`() {
let text = "alpha anchor beta anchor gamma"
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 1) == .valid)
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 2) == .valid) // 2 of 2
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 3) == .stale) // 3 of 2
#expect(FixCardStore.anchorStatus(text: text, quote: "vanished", occurrence: 1) == .stale)
#expect(FixCardStore.anchorStatus(text: text, quote: "", occurrence: 1) == .stale)
// Non-overlapping counting: "a a" fits "a a a" only once.
#expect(FixCardStore.anchorStatus(text: "a a a", quote: "a a", occurrence: 2) == .stale)
}
@Test func `input decode defaults occurrence and rejects unknown enums`() throws {
let minimal = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"lint"}"#
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(minimal.utf8))
#expect(input.anchor.occurrence == 1)
#expect(input.diagnosticQuestion == nil)
let badLane = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"nope","emitter":"lint"}"#
#expect(throws: DecodingError.self) {
_ = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(badLane.utf8))
}
}
/// #23 follow-up: pass differentiation — `provenance.pass` rides the
/// wire; pre-schema cards (no pass key) decode to nil, never error.
@Test func `provenance pass rides the wire and old cards decode without it`() throws {
let wire = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a","pass":2}}"#
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(wire.utf8))
#expect(input.provenance?.pass == 2)
let old = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a"}}"#
let oldInput = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(old.utf8))
#expect(oldInput.provenance?.pass == nil)
}
@Test func `submit writes snake case card file`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(
piecePath: piece.path,
cards: [card(diagnosticQuestion: "Is the hedge load-bearing?")],
)
#expect(written.count == 1)
#expect(written[0].card.anchorStatus == .valid)
#expect(written[0].card.status == "open")
#expect(written[0].file.hasSuffix("-hedging.json"))
let cardsDir = piece.appendingPathComponent("cards", isDirectory: true)
let files = try FileManager.default.contentsOfDirectory(atPath: cardsDir.path)
.filter { $0.hasSuffix(".json") }
#expect(files == [written[0].file])
let json = try #require(
try JSONSerialization.jsonObject(
with: Data(contentsOf: cardsDir.appendingPathComponent(written[0].file)),
) as? [String: Any],
)
#expect(json["pattern"] as? String == "Hedging")
#expect(json["diagnostic_question"] as? String == "Is the hedge load-bearing?")
#expect(json["anchor_status"] as? String == "valid")
#expect(json["status"] as? String == "open")
#expect(json["submitted_at"] is String)
#expect(json["id"] is String)
}
@Test func `submit flags stale anchors but still lands`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
// A post.md path is accepted directly, not just the piece folder.
let written = try FixCardStore.submit(
piecePath: piece.appendingPathComponent("post.md").path,
cards: [card(quote: "this quote is nowhere")],
)
#expect(written[0].card.anchorStatus == .stale)
#expect(
FileManager.default.fileExists(
atPath: piece.appendingPathComponent("cards/\(written[0].file)").path,
),
)
}
@Test func `submit throws on missing piece`() throws {
let home = try toolsHome()
// A lazy piece folder without post.md is not a piece.
let noPost = home.appendingPathComponent("projects/posts/ghost", isDirectory: true)
try FileManager.default.createDirectory(at: noPost, withIntermediateDirectories: true)
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: noPost.path, cards: [card()]) }
#expect(throws: Error.self) {
try FixCardStore.submit(piecePath: home.appendingPathComponent("nowhere").path, cards: [card()])
}
}
/// Security pins (review MEDIUM-1/-2): a readable foreign file must not
/// pass as a "piece" — submit beside it = JSON-drop, anchor check =
/// substring oracle. One resolvePostURL guard closes both.
@Test func `submit refuses foreign files and loose post md`() throws {
let home = try toolsHome()
let foreign = home.appendingPathComponent("notes.md")
try "not a piece".write(to: foreign, atomically: true, encoding: .utf8)
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: foreign.path, cards: [card()]) }
let loose = home.appendingPathComponent("loose", isDirectory: true)
try FileManager.default.createDirectory(at: loose, withIntermediateDirectories: true)
try "x".write(to: loose.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: loose.path, cards: [card()]) }
}
@Test func `submit throws on malformed cards and writes nothing`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(pattern: " ")]) }
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(problem: "")]) }
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(quote: "")]) }
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(occurrence: 0)]) }
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("cards").path))
}
@Test func `submit suffixes same second collisions`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card(), card()])
#expect(written[0].file.hasSuffix("-hedging.json"))
#expect(written[1].file.hasSuffix("-hedging-2.json"))
#expect(written[0].file != written[1].file)
}
@Test func `scan returns newest first and skips undecodable`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let dir = piece.appendingPathComponent("cards", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try FixCardStore.encoder.encode(storedCard(pattern: "New"))
.write(to: dir.appendingPathComponent("20260102-000000-new.json"))
try FixCardStore.encoder.encode(storedCard(pattern: "Old"))
.write(to: dir.appendingPathComponent("20260101-000000-old.json"))
try "{ not json".write(to: dir.appendingPathComponent("junk.json"), atomically: true, encoding: .utf8)
try "note".write(to: dir.appendingPathComponent("note.txt"), atomically: true, encoding: .utf8)
#expect(FixCardStore.scan(pieceURL: piece).map(\.pattern) == ["New", "Old"])
// A post.md URL is tolerated (the app-side call sites hold the file URL).
#expect(FixCardStore.scan(pieceURL: piece.appendingPathComponent("post.md")).count == 2)
}
@Test func `learnings read raw markdown name sorted`() throws {
let home = try toolsHome { home in
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "beta body".write(to: dir.appendingPathComponent("b.md"), atomically: true, encoding: .utf8)
try "# Alpha\n\nraw *markdown*".write(to: dir.appendingPathComponent("a.md"), atomically: true, encoding: .utf8)
}
let piece = try writePiece(home)
let learned = try FixCardStore.learnings(piecePath: piece.path)
#expect(learned.map(\.file) == ["a.md", "b.md"])
#expect(learned[0].markdown == "# Alpha\n\nraw *markdown*")
}
@Test func `learnings follow content type`() throws {
let home = try toolsHome { home in
let outlines = home.appendingPathComponent("learnings/outlines", isDirectory: true)
try FileManager.default.createDirectory(at: outlines, withIntermediateDirectories: true)
try "- outline learning".write(to: outlines.appendingPathComponent("o.md"), atomically: true, encoding: .utf8)
let posts = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: posts, withIntermediateDirectories: true)
try "post learning".write(to: posts.appendingPathComponent("p.md"), atomically: true, encoding: .utf8)
}
let piece = try writePiece(home, id: "outline-piece", type: "outline")
#expect(try FixCardStore.learnings(piecePath: piece.path).map(\.markdown) == ["- outline learning"])
}
@Test func `learnings missing dir is empty and type defaults to post`() throws {
let home = try toolsHome { home in
let outlines = home.appendingPathComponent("learnings/outlines", isDirectory: true)
try FileManager.default.createDirectory(at: outlines, withIntermediateDirectories: true)
try "outline learning".write(to: outlines.appendingPathComponent("o.md"), atomically: true, encoding: .utf8)
}
// No type key → post → looks in learnings/posts/, which doesn't exist.
let piece = try writePiece(home, type: nil)
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty)
// A missing piece is still an error, not an empty answer.
#expect(throws: Error.self) {
try FixCardStore.learnings(piecePath: home.appendingPathComponent("gone").path)
}
}
}