Files
museion/MuseionTests/MCPToolsPromoteTests.swift
AlexKucera 78c8844184
CI / ci (push) Canceled after 0s
feat(mentor): dismiss & decay Learnings (#27)
Dismissed patterns fade instead of haunting. Dismissing a Learning
stamps decay state into its own frontmatter (dismissed date,
dismiss_count, dismissed_at_pass — every other line preserved
verbatim, hand-editable, git-diffable) and hides it from every pass:
query_learnings serves only visible learnings. Resurfacing is an
output clock, not a calendar — a per-type counter under
<home>/learnings/pass-counts.json, ticked by every completed pass
(cancels and refusals never advance, so never tick), returns the
Learning after 10 subsequent passes of its content type; each
re-dismiss doubles the interval (10→20→40…), and a per-Learning
resurface_after frontmatter key overrides the base. Hand-edited decay
state reads leniently: garbage means visible, absurd values clamp, a
hand-edit can never trap the pane or the rail. The Learnings pane
rows dismiss (no confirm — low-stakes, self-healing), dim while
hidden with a resurfaces-in-N countdown, and foreign unclocked type
dirs neither offer Dismiss nor show a verdict — their clock can never
advance. Two review waves (two-axis implement review + three-reviewer
finish-audit: security clean) produced five fixes, each pinned or
noted in the session log.

Closes #27
2026-10-21 14:19:43 +02:00

281 lines
12 KiB
Swift

//
// MCPToolsPromoteTests.swift
// MuseionTests
//
// #26 (M3, S4.1/S4.3/S4.4): the promote rail's store pins — one confirm
// writes ONE plain markdown Learning under <home>/learnings/<type>s/,
// the consult rail reads it back, and pre-#26 card JSON stays readable.
// Own file (MCPToolsTests was past its type-body ceiling): the
// temp-home/piece/card helpers stay in MCPToolsTests (cross-file
// convention).
//
import Foundation
@testable import Museion
import Testing
/// A fully-stamped card for hand-written fixtures (scan tests). Defaults
/// match the historical shape; apply tests override anchor/lane, the rank
/// pins override submittedAt/rank. Internal — FixCardApplyTests shares it
/// (the card()/makeModelHome cross-file convention).
func storedCard(
pattern: String = "P",
quote: String = "q",
occurrence: Int = 1,
fix: String = "",
lane: FixCardStore.StoredFixCard.Lane = .mechanical,
submittedAt: Date = Date(timeIntervalSince1970: 0),
rank: Int? = nil,
) -> FixCardStore.StoredFixCard {
FixCardStore.StoredFixCard(
id: UUID(),
submittedAt: submittedAt,
rank: rank,
pattern: pattern,
problem: "p",
diagnosticQuestion: "",
fix: fix,
anchor: .init(quote: quote, occurrence: occurrence),
lane: lane,
emitter: .lint,
provenance: nil,
status: .open,
anchorStatus: .valid,
promotedAt: nil,
)
}
struct MCPToolsPromoteTests {
// MARK: Promote (#26, S4.1/S4.3/S4.4)
/// Scenario: one confirm writes one learning — given a submitted card
/// on a piece under a temp Home, when the writer confirms promotion,
/// then exactly ONE plain markdown Learning exists under
/// `<home>/learnings/posts/<yyyyMMdd>-<slug>.md` with the pinned
/// frontmatter shape and a `# <pattern>` body, the card carries
/// promotedAt, and a second confirm is refused with no second file —
/// never a repetition counter.
@Test func `promote writes one learning and stamps the card`() 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?",
fix: "Cut the hedge.",
provenance: .init(piece: "test-piece", date: "2026-08-27", engine: "hermes", pass: 1),
),
],
)
let now = Date(timeIntervalSince1970: 1_800_000_000)
let promoted = try FixCardStore.promote(pieceURL: piece, card: written[0].card, now: now)
// ONE file, the pinned name shape.
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
let name = "\(FixCardStore.formatted(now, "yyyyMMdd"))-hedging.md"
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") } == [name])
let markdown = try String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8)
#expect(markdown.contains("pattern: Hedging\n"))
#expect(markdown.contains("problem: The hedge weakens the claim.\n"))
#expect(markdown.contains("diagnostic_question: Is the hedge load-bearing?\n"))
#expect(markdown.contains("lane: mechanical\n"))
#expect(markdown.contains("emitter: lint\n"))
#expect(markdown.contains("piece: test-piece\n"))
#expect(markdown.contains("pass: 1\n"))
#expect(markdown.contains("engine: hermes\n"))
#expect(markdown.contains("promoted: \(FixCardStore.formatted(now, "yyyy-MM-dd"))\n"))
#expect(markdown.contains("from_card: \(written[0].card.id.uuidString)\n"))
// The Learning teaches, it never re-quotes the instance: a
// mechanical fix is a literal replacement string from one piece
// and the anchor is apply-machinery — both stay on the card JSON.
#expect(!markdown.contains("fix:"))
#expect(!markdown.contains("anchor"))
#expect(!markdown.contains("repeated anchor line"))
#expect(!markdown.contains("Cut the hedge."))
#expect(markdown.contains("\n# Hedging\n"))
#expect(markdown.contains("**Problem.** The hedge weakens the claim."))
#expect(markdown.contains("*Promoted from test-piece · Pass 1 · \(FixCardStore.formatted(now, "yyyy-MM-dd")).*"))
// The returned card carries promotedAt; so does the re-scan.
#expect(promoted.promotedAt == now)
#expect(FixCardStore.scan(pieceURL: piece).first?.promotedAt == now)
// A second confirm is refused at the store level — no second file.
#expect(throws: FixCardStore.CardError(message: "card already promoted")) {
try FixCardStore.promote(pieceURL: piece, card: promoted, now: now)
}
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") }.count == 1)
// A missing piece is a thrown error, never a silent no-op.
#expect(throws: Error.self) {
try FixCardStore.promote(pieceURL: home.appendingPathComponent("gone"), card: storedCard())
}
}
/// Scenario: the mentor remembers — after promotion,
/// learnings(piecePath:) returns the Learning's raw markdown: the pass
/// rail consults exactly these files (S4.3/S4.4 — the engine reads
/// them via query_learnings, unchanged).
@Test func `promoted learnings are consultable`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
_ = try FixCardStore.promote(pieceURL: piece, card: written[0].card)
let learned = try FixCardStore.learnings(piecePath: piece.path)
#expect(learned.count == 1)
#expect(learned[0].file.hasSuffix("-hedging.md"))
#expect(learned[0].markdown.contains("# Hedging"))
}
/// An outline-typed piece promotes into learnings/outlines/ — the
/// Learning lands with the piece's own content type (learningsDir).
@Test func `promote follows the piece content type`() throws {
let home = try toolsHome()
let piece = try writePiece(home, id: "outline-piece", type: "outline")
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
_ = try FixCardStore.promote(pieceURL: piece, card: written[0].card)
#expect(FixCardStore.learningsDir(home: home, type: .post).lastPathComponent == "posts")
let dir = FixCardStore.learningsDir(home: home, type: .outline)
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") }.count == 1)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1)
}
/// Same-day, same-pattern: the second Learning takes the -2 suffix
/// (uniqueFile's collision pattern, .md edition).
@Test func `promote suffixes same-day same-pattern collisions`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(
piecePath: piece.path,
cards: [card(), card(problem: "A different problem.")],
)
let now = Date()
_ = try FixCardStore.promote(pieceURL: piece, card: written[0].card, now: now)
_ = try FixCardStore.promote(pieceURL: piece, card: written[1].card, now: now)
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
let base = "\(FixCardStore.formatted(now, "yyyyMMdd"))-hedging"
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).sorted() == ["\(base)-2.md", "\(base).md"])
}
/// Frontmatter values are single-line: any newline in a pattern, problem,
/// or example flattens to a space — the file stays parseable. Demonstration
/// lanes keep their fix (the example rewrite teaches); it lands as `fix:`
/// frontmatter and an `**Example.**` body line.
@Test func `promote flattens newlines and keeps the demonstration example`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(
piecePath: piece.path,
cards: [
card(
pattern: "Hedging\nacross lines",
problem: "Two-line\nproblem.",
fix: "Rewritten\nas the master would pace it.",
lane: .demonstration,
),
],
)
let now = Date()
_ = try FixCardStore.promote(pieceURL: piece, card: written[0].card, now: now)
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
let files = try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") }
let markdown = try String(contentsOf: dir.appendingPathComponent(files[0]), encoding: .utf8)
#expect(markdown.contains("pattern: Hedging across lines\n"))
#expect(markdown.contains("problem: Two-line problem.\n"))
#expect(markdown.contains("lane: demonstration\n"))
#expect(markdown.contains("fix: Rewritten as the master would pace it.\n"))
#expect(markdown.contains("**Example.** Rewritten as the master would pace it."))
#expect(markdown.contains("# Hedging across lines\n"))
// No provenance → the footer's piece falls back to "a fix card".
#expect(markdown.contains("*Promoted from a fix card · \(FixCardStore.formatted(now, "yyyy-MM-dd")).*"))
}
/// Pre-#26 card JSON (no promoted_at key) decodes promotedAt nil; a
/// promoted card round-trips the stamp (snake_case promoted_at).
@Test func `old card json decodes promoted at nil`() throws {
let legacy = try FixCardStore.decoder.decode(
FixCardStore.StoredFixCard.self,
from: FixCardStore.encoder.encode(storedCard()),
)
#expect(legacy.promotedAt == nil)
var promotedCard = storedCard()
promotedCard.promotedAt = Date(timeIntervalSince1970: 1_800_000_000)
let data = try FixCardStore.encoder.encode(promotedCard)
let json = try #require(
try JSONSerialization.jsonObject(with: data) as? [String: Any],
)
#expect(json["promoted_at"] is String)
#expect(
try FixCardStore.decoder.decode(FixCardStore.StoredFixCard.self, from: data).promotedAt
== promotedCard.promotedAt,
)
}
/// Scenario: the on-disk card is the truth — a STALE palette copy
/// (promotedAt nil while disk is already stamped, the async refresh
/// gap) must refuse with no second Learning (audit: the double-write
/// window, closed at the store seam).
@Test func `a stale unstamped copy cannot double-promote`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
_ = try FixCardStore.promote(pieceURL: piece, card: written[0].card)
// The caller's copy is the pre-promote one — the disk check must refuse.
#expect(throws: FixCardStore.CardError(message: "card already promoted")) {
try FixCardStore.promote(pieceURL: piece, card: written[0].card)
}
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".md") }.count == 1)
}
/// Scenario: a vanished (or undecodable) card JSON refuses BEFORE the
/// Learning is written — a retry can never accumulate orphan files.
@Test func `a vanished card refuses before writing anything`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
let cardsDir = piece.appendingPathComponent("cards", isDirectory: true)
let json = try #require(try FileManager.default.contentsOfDirectory(atPath: cardsDir.path).first)
try FileManager.default.removeItem(at: cardsDir.appendingPathComponent(json))
#expect(throws: FixCardStore.CardError(message: "card not found: \(written[0].card.id)")) {
try FixCardStore.promote(pieceURL: piece, card: written[0].card)
}
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings").path))
}
/// Scenario: a pre-planted symlinked learnings component must not turn
/// promote into a file-plant primitive (security audit) — refuse
/// before any write, nothing lands in the link's target.
@Test func `a symlinked learnings dir refuses to promote`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card()])
let target = home.appendingPathComponent("elsewhere", isDirectory: true)
try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
try FileManager.default.createDirectory(
at: home.appendingPathComponent("learnings", isDirectory: true),
withIntermediateDirectories: true,
)
try FileManager.default.createSymbolicLink(
at: home.appendingPathComponent("learnings/posts"),
withDestinationURL: target,
)
let planted = home.appendingPathComponent("learnings/posts").path
#expect(throws: FixCardStore.CardError(message: "learnings path is a symlink: \(planted)")) {
try FixCardStore.promote(pieceURL: piece, card: written[0].card)
}
#expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty)
}
}