feat(mentor): promote & consult Learnings (#26)
CI / ci (push) Canceled after 0s

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
This commit is contained in:
AlexKucera committed 2026-10-21 12:13:24 +02:00
1 parent 154bb8a114
commit 0e5c28ad95
18 files changed
+1133 -82

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@ Owned by the root AGENTS.md contract.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test).
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1.
- `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses.
- `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation.
+37
View File
@@ -283,4 +283,41 @@ struct FixCardApplyTests {
#expect(try FixCardStore.scan(pieceURL: folder).first?.status == .open) // card stays open
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("post.md").path)) // nothing written
}
// MARK: Promote (#26, S4.1)
/// Scenario: the mentor remembers — promoting through the model writes
/// the Learning under the open piece's Home, refreshes the palette's
/// cards (promotedAt visible), and refuses a second confirm; with no
/// open piece it refuses before touching anything.
@Test @MainActor func `promote through the model writes one learning and refuses repeats`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()])
model.select(post.id, home: home)
#expect(model.promoteCard(written[0].card, home: home) == .promoted)
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
#expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1)
try await pollUntil { model.openPieceCards.first(where: { $0.id == written[0].card.id })?.promotedAt != nil }
#expect(model.lastError == nil)
// Already promoted → refused, no second file (one confirm = one entry).
let scanned = try #require(FixCardStore.scan(pieceURL: folder).first)
#expect(model.promoteCard(scanned, home: home) == .refused("card already promoted"))
#expect(try FileManager.default.contentsOfDirectory(atPath: learnings.path).filter { $0.hasSuffix(".md") }.count == 1)
}
@Test @MainActor func `promote without an open piece refuses and writes nothing`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
let written = try FixCardStore.submit(piecePath: folder.path, cards: [card()])
#expect(model.promoteCard(written[0].card, home: home) == .refused("open the piece to work its cards"))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings").path))
#expect(model.lastError == nil)
}
}
+126
View File
@@ -0,0 +1,126 @@
//
// LearningsPaneTests.swift
// MuseionTests
//
// #26 (S4.4, ADR-0005): the Learnings pane's disk reader — one plain
// markdown file per Learning under <home>/learnings/<type-plural>/,
// frontmatter read leniently (a stranger's hand-edit never surfaces
// wrong or crashes the pane).
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Homes with hand-written .md Learning fixtures — the format
/// contract the promote rail writes: frontmatter pattern/problem/promoted
/// (all optional, quoted or bare), file named YYYYMMDD-<slug>.md,
/// dir = the content-type plural.
private func makeHome(_ write: (URL) throws -> Void) throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("learnings-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
try write(home)
return home
}
/// Seeds <home>/learnings/<type>/<file> with raw markdown.
private func writeLearning(_ home: URL, _ type: String, _ file: String, _ markdown: String) throws {
let dir = home.appendingPathComponent("learnings/\(type)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try markdown.write(to: dir.appendingPathComponent(file), atomically: true, encoding: .utf8)
}
struct LearningsPaneTests {
@Test func `scan groups by type dir and orders entries newest first`() throws {
// Scenario: two content-type dirs; within posts three files — the
// YYYYMMDD prefix orders newest-first and an undated file sorts last.
let home = try makeHome { home in
try writeLearning(home, "posts", "20261020-late-scene-reveal.md", """
---
pattern: "Open on the reveal"
problem: "Scenes opened after the reveal"
promoted: 2026-10-20
---
""")
try writeLearning(home, "posts", "20261021-fold-the-ladder.md", """
---
pattern: Fold the ladder
problem: Ladders left standing
promoted: "2026-10-21"
---
""")
try writeLearning(home, "posts", "undated-note.md", "# just a hand edit\n")
try writeLearning(home, "outlines", "20261019-parallel-arcs.md", """
---
pattern: Parallel arcs
promoted: 2026-10-19
---
""")
}
let groups = LearningsIndex.scan(home: home)
#expect(groups.map(\.type) == ["outlines", "posts"])
let posts = try #require(groups.first { $0.type == "posts" })
#expect(posts.entries.map(\.id) == [
"20261021-fold-the-ladder.md",
"20261020-late-scene-reveal.md",
"undated-note.md",
])
let newest = try #require(posts.entries.first)
#expect(newest.pattern == "Fold the ladder") // bare value, not just the quoted form
#expect(newest.problem == "Ladders left standing")
#expect(newest.promoted == "2026-10-21")
let outlines = try #require(groups.first { $0.type == "outlines" })
#expect(outlines.entries.count == 1)
#expect(outlines.entries.first?.problem == nil) // absent key omits the line
}
@Test func `scan reads leniently - noise never surfaces or crashes`() throws {
// Scenario: a stranger hand-edits the vault — a dated file with no
// frontmatter (pattern derives from the filename), non-md and hidden
// files, a hidden dir, a loose file directly under learnings/.
let home = try makeHome { home in
try writeLearning(home, "posts", "20261018-dated-without-frontmatter.md", "# note\n")
try writeLearning(home, "posts", ".DS_Store", "junk")
try writeLearning(home, "posts", "draft.txt", "not markdown")
try writeLearning(home, ".git", "20260101-x.md", "---\npattern: hidden\n---\n")
// A symlinked type-dir with FULL payload (a real .md behind the
// link) never surfaces — Post.scan posture, pinned.
let linkedTo = home.appendingPathComponent("real-drafts", isDirectory: true)
try FileManager.default.createDirectory(at: linkedTo, withIntermediateDirectories: true)
try "---\npattern: behind the link\n---\n".write(
to: linkedTo.appendingPathComponent("20261016-linked.md"),
atomically: true,
encoding: .utf8,
)
try FileManager.default.createSymbolicLink(
at: home.appendingPathComponent("learnings/linked-posts"),
withDestinationURL: linkedTo,
)
try writeLearning(home, "outlines", "20261017-outline-edge.md", """
---
promoted: 2026-10-17
---
""")
try "stray".write(
to: home.appendingPathComponent("learnings/loose.md"),
atomically: true,
encoding: .utf8,
)
}
let groups = LearningsIndex.scan(home: home)
#expect(groups.map(\.type) == ["outlines", "posts"]) // hidden dir + loose file: no group
let posts = try #require(groups.first { $0.type == "posts" })
#expect(posts.entries.map(\.pattern) == ["dated-without-frontmatter"]) // date+hyphen stripped, ext gone
#expect(posts.entries.first?.promoted == nil)
let outlines = try #require(groups.first { $0.type == "outlines" })
#expect(outlines.entries.first?.pattern == "outline-edge") // no pattern key → filename, date+hyphen stripped
}
@Test func `missing learnings dir scans empty`() throws {
// Scenario: a fresh Home before the first promotion — nothing to
// read, no crash.
let home = try makeHome { _ in }
#expect(LearningsIndex.scan(home: home).isEmpty)
}
}
+289
View File
@@ -0,0 +1,289 @@
//
// 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
/// The store's stamp conventions (en_US_POSIX, per access) — expected
/// learning filenames/dates in the #26 promote pins.
private func stamped(_ date: Date, _ format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.string(from: date)
}
/// 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 = "\(stamped(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: \(stamped(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 · \(stamped(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 = "\(stamped(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 · \(stamped(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)
}
}
+10 -36
View File
@@ -12,8 +12,9 @@ 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 {
/// 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)
@@ -22,9 +23,10 @@ private func toolsHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL {
}
/// One piece under projects/posts/<id>/post.md; returns the piece folder.
/// `type: nil` writes no frontmatter block at all.
/// `type: nil` writes no frontmatter block at all. Internal —
/// MCPToolsPromoteTests shares it (cross-file convention).
@discardableResult
private func writePiece(
func writePiece(
_ home: URL,
id: String = "test-piece",
type: String? = "post",
@@ -39,7 +41,8 @@ private func writePiece(
/// 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.
/// 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.",
@@ -48,6 +51,7 @@ func card(
quote: String = "repeated anchor line",
occurrence: Int = 1,
lane: FixCardStore.StoredFixCard.Lane = .mechanical,
provenance: FixCardStore.StoredFixCard.Provenance? = nil,
) -> FixCardStore.Input {
FixCardStore.Input(
pattern: pattern,
@@ -57,37 +61,7 @@ func card(
anchor: .init(quote: quote, occurrence: occurrence),
lane: lane,
emitter: .lint,
provenance: nil,
)
}
/// 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,
provenance: provenance,
)
}