Files
museion/MuseionTests/MCPToolsTests.swift
T
AlexKucera 0e5c28ad95
CI / ci (push) Canceled after 0s
feat(mentor): promote & consult Learnings (#26)
Only the writer's explicit confirmation promotes a Fix Card into a
Learning — one confirm, one entry, never a repetition counter. The
Learning is a plain markdown file under <home>/learnings/<type>s/
carrying the card's teaching fields (pattern, problem, diagnostic
question, the demonstration example) plus promotion provenance; the
instance-bound anchor and mechanical replacement stay on the card.
Every pass consults these files via query_learnings; the Learnings
pane replaces its placeholder. Promote consults the on-disk card as
the truth and rejects symlinked learnings paths before any write
(finish-audit round). Dismiss/decay follows in #27.

Closes #26
2026-10-21 12:13:24 +02:00

368 lines
17 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). Internal —
/// MCPToolsPromoteTests shares it (cross-file convention).
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. Internal —
/// MCPToolsPromoteTests shares it (cross-file convention).
@discardableResult
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 and FixCardApplyTests (review: a hand-copy drifted
/// here). #25: `fix`/`lane` feed the apply pins; #26: `provenance` feeds
/// the promote pins.
func card(
pattern: String = "Hedging",
problem: String = "The hedge weakens the claim.",
diagnosticQuestion: String? = nil,
fix: String? = nil,
quote: String = "repeated anchor line",
occurrence: Int = 1,
lane: FixCardStore.StoredFixCard.Lane = .mechanical,
provenance: FixCardStore.StoredFixCard.Provenance? = nil,
) -> FixCardStore.Input {
FixCardStore.Input(
pattern: pattern,
problem: problem,
diagnosticQuestion: diagnosticQuestion,
fix: fix,
anchor: .init(quote: quote, occurrence: occurrence),
lane: lane,
emitter: .lint,
provenance: provenance,
)
}
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)
}
/// #25 (S3.2): the pass ceiling — an attention budget, not infinite
/// scroll. The backstop keeps the ranked HEAD (submit order = rank,
/// pass-persona doctrine); tail cards drop before validation, so a
/// malformed 12th card never errors an otherwise-fine submit.
@Test func `submit caps at the ten-card pass ceiling keeping the ranked head`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
var cards = (1 ... 11).map { card(pattern: "P\($0)") }
cards.append(card(pattern: " ")) // malformed — and beyond the ceiling
let written = try FixCardStore.submit(piecePath: piece.path, cards: cards)
#expect(written.map(\.card.pattern) == (1 ... 10).map { "P\($0)" })
let files = try FileManager.default.contentsOfDirectory(atPath: piece.appendingPathComponent("cards").path)
.filter { $0.hasSuffix(".json") }
#expect(files.count == 10)
}
/// #25 (S3.2): rank is the submit's array order (the persona's ranked
/// call) — the store stamps it 1-based like id/submittedAt. Optional on
/// decode: pre-#25 cards on disk carry no rank key.
@Test func `submit stamps rank in submit order and old cards decode without it`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(
piecePath: piece.path,
cards: [card(pattern: "Top"), card(pattern: "Mid"), card(pattern: "Tail")],
)
#expect(written.map(\.card.rank) == [1, 2, 3])
// The disk round-trip carries it (snake_case "rank").
let json = try #require(
try JSONSerialization.jsonObject(
with: Data(contentsOf: piece.appendingPathComponent("cards/\(written[0].file)")),
) as? [String: Any],
)
#expect(json["rank"] as? Int == 1)
// A pre-schema card (no rank key) decodes with rank nil, never errors.
let oldData = try FixCardStore.encoder.encode(storedCard(pattern: "Old"))
let stripped = try #require(
try JSONSerialization.jsonObject(with: oldData) as? [String: Any],
).filter { $0.key != "rank" }
let decoded = try FixCardStore.decoder.decode(
FixCardStore.StoredFixCard.self,
from: JSONSerialization.data(withJSONObject: stripped),
)
#expect(decoded.rank == nil)
}
/// #25 (S3.2/S3.3): the pure Apply — the mechanical edit a card makes
/// in a text: the anchored occurrence replaced by the fix, nothing
/// else. nil = the card must not touch text: a demonstration lane
/// (only a mechanical fix is ever applied, ADR-0006) or an anchor that
/// no longer resolves (edits between issue and accept degrade to a
/// loud no-match, never a wrong-span patch).
@Test func `applied text replaces only the anchored occurrence`() {
let text = "alpha anchor beta anchor gamma"
// The nth occurrence, not the first.
#expect(
FixCardStore.appliedText(of: storedCard(quote: "anchor", occurrence: 2, fix: "FIX"), in: text)
== "alpha anchor beta FIX gamma",
)
#expect(
FixCardStore.appliedText(of: storedCard(quote: "anchor", fix: "FIX"), in: text)
== "alpha FIX beta anchor gamma",
)
// An empty fix cuts the span.
#expect(
FixCardStore.appliedText(of: storedCard(quote: "anchor ", occurrence: 2), in: text)
== "alpha anchor beta gamma",
)
// Beyond-count occurrence, vanished quote, empty quote: no edit.
#expect(FixCardStore.appliedText(of: storedCard(quote: "anchor", occurrence: 3, fix: "FIX"), in: text) == nil)
#expect(FixCardStore.appliedText(of: storedCard(quote: "gone", fix: "FIX"), in: text) == nil)
#expect(FixCardStore.appliedText(of: storedCard(quote: "", fix: "FIX"), in: text) == nil)
// Demonstration lane never applies (ADR-0006).
#expect(FixCardStore.appliedText(of: storedCard(quote: "anchor", fix: "FIX", lane: .demonstration), in: text) == nil)
}
/// #25 (S3.3): the in-place close — Skip/Done/Apply flip the card's
/// status in its own JSON file; every other field travels unchanged
/// (Skip records nothing beyond the flip, CONTEXT.md).
@Test func `close rewrites the card status in place`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
let closed = try FixCardStore.close(pieceURL: piece, id: written[0].card.id, status: .skipped)
#expect(closed.status == .skipped)
#expect(closed.rank == 1)
#expect(closed.pattern == "Hedging")
// The SAME single file, status flipped, everything else intact.
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["status"] as? String == "skipped")
#expect(json["pattern"] as? String == "Hedging")
#expect(json["rank"] as? Int == 1)
// Scan sees the closed card; a foreign id errors, file untouched.
#expect(FixCardStore.scan(pieceURL: piece).first?.status == .skipped)
#expect(throws: Error.self) {
try FixCardStore.close(pieceURL: piece, id: UUID(), status: .done)
}
}
@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)
}
}
}