feat(mentor): dismiss & decay Learnings (#27)
CI / ci (push) Canceled after 0s

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
This commit is contained in:
AlexKucera committed 2026-10-21 14:19:43 +02:00
1 parent 0e5c28ad95
commit 78c8844184
15 files changed
+911 -66

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. **#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.
- `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. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `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.
+400
View File
@@ -0,0 +1,400 @@
//
// LearningDecayTests.swift
// MuseionTests
//
// #27 (M3, S4.2): Dismiss & Decay — the pass clock, the dismiss stamp,
// and the resurface math. Temp homes via toolsHome/writePiece (the
// MCPToolsTests cross-file convention).
//
import Foundation
@testable import Museion
import Testing
/// A promote-shaped Learning (the #26 format contract) for hand-written
/// fixtures — frontmatter + a human-readable body. Seeding uses
/// LearningsPaneTests' `writeLearning`, internal (cross-file convention);
/// date-stamp expectations call the prod `FixCardStore.formatted` — the
/// format literals stay pinned (#27 audit: no test-side formatter copy).
private let learning = """
---
pattern: Hedging
problem: The hedge weakens the claim.
lane: mechanical
promoted: 2026-10-21
from_card: 6D9DB4F2-82F9-4C64-9C2B-1A21B4E9B5D0
---
# Hedging
**Problem.** The hedge weakens the claim.
*Promoted from test-piece · Pass 1 · 2026-10-21.*
"""
/// Reads the decay-stamped Learning back.
private func readLearning(_ home: URL, _ file: String) throws -> String {
try String(contentsOf: home.appendingPathComponent("learnings/posts/\(file)"), encoding: .utf8)
}
struct LearningDecayTests {
// MARK: Pass clock (#27 S4.2)
/// Scenario: the clock counts COMPLETED passes per content type —
/// every advancePassState ticks its type's counter (re-runs included),
/// types are independent, and a fresh Home reads empty.
@Test func `completed passes tick the per-type clock`() throws {
let home = try toolsHome()
_ = try writePiece(home)
_ = try writePiece(home, id: "outline-piece", type: "outline")
try PostStore.advancePassState(id: "test-piece", kind: .pass1, home: home)
try PostStore.advancePassState(id: "test-piece", kind: .pass2, home: home) // re-run counts
try PostStore.advancePassState(id: "outline-piece", kind: .pass1, home: home)
#expect(LearningDecay.passCounts(home: home) == ["posts": 2, "outlines": 1])
#expect(try LearningDecay.passCounts(home: toolsHome()) == [:])
}
// MARK: Dismiss (#27 S4.2)
/// Scenario: dismiss stamps decay state IN the Learning's own
/// frontmatter — dismissed date, dismiss_count, dismissed_at_pass
/// matching the clock — while every other frontmatter key and the
/// body stay byte-identical; the consult rail stops returning it.
@Test func `dismiss stamps decay frontmatter in place and hides the learning`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
try PostStore.advancePassState(id: "test-piece", kind: .pass1, home: home) // clock: posts = 1
let file = "20261021-hedging.md"
try writeLearning(home, "posts", file, learning)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // visible before
let now = Date(timeIntervalSince1970: 1_800_000_000)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file, now: now)
let stampedText = try readLearning(home, file)
let frontmatter = Post.frontmatter(of: stampedText)
#expect(frontmatter["dismissed"] == FixCardStore.formatted(now, "yyyy-MM-dd"))
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "1")
// Other keys untouched, still in place.
#expect(frontmatter["pattern"] == "Hedging")
#expect(frontmatter["problem"] == "The hedge weakens the claim.")
#expect(frontmatter["lane"] == "mechanical")
#expect(frontmatter["promoted"] == "2026-10-21")
#expect(frontmatter["from_card"] == "6D9DB4F2-82F9-4C64-9C2B-1A21B4E9B5D0")
// The body is byte-identical.
#expect(PostStore.splitFrontmatter(stampedText).body == PostStore.splitFrontmatter(learning).body)
// Hidden from the pass rail.
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty)
}
// MARK: Resurface (#27 S4.2)
/// Scenario: a dismissed learning (anchor P) stays hidden through
/// P+9 completed passes of its content type and resurfaces at P+10 —
/// an output clock, not a calendar.
@Test func `a dismissed learning resurfaces after ten passes of its type`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
try writeLearning(home, "posts", "20261021-hedging.md", learning)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "20261021-hedging.md") // anchor 0
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) // hidden at P
for _ in 0 ..< 9 {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) // hidden through P+9
try LearningDecay.recordPass(home: home, type: .post)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // visible at P+10
}
/// Scenario: each re-dismiss doubles the interval — after the first
/// resurface a second dismiss stamps dismiss_count: 2 (anchor P) and
/// the learning stays hidden for 20 more passes, surfacing at P+20.
@Test func `re-dismissing doubles the interval`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let file = "20261021-hedging.md"
try writeLearning(home, "posts", file, learning)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file) // count 1, anchor 0
for _ in 0 ..< 10 {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // resurfaced
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let frontmatter = try Post.frontmatter(of: readLearning(home, file))
#expect(frontmatter["dismiss_count"] == "2")
#expect(frontmatter["dismissed_at_pass"] == "10") // re-anchored at the current clock
for _ in 0 ..< 19 {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) // hidden through 19
try LearningDecay.recordPass(home: home, type: .post)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // visible at 20
}
/// Scenario: a per-Learning `resurface_after` frontmatter key
/// overrides the base 10 — hand-editable decay (#27 S4.2).
@Test func `resurface_after overrides the base interval`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
try writeLearning(home, "posts", "20261021-hedging.md", """
---
pattern: Hedging
dismiss_count: 1
dismissed_at_pass: 0
resurface_after: 3
---
# Hedging
""")
for _ in 0 ..< 2 {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) // hidden at 2
try LearningDecay.recordPass(home: home, type: .post)
#expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // visible at 3
}
// MARK: Lenient reads (#27 S4.2)
/// Scenario: hand-edited decay state never traps or surfaces wrong —
/// garbage ints default per contract, a missing anchor means visible,
/// an absurd dismiss_count stays hidden without overflow, and a
/// corrupt clock reads as 0 / partial.
@Test func `lenient reads never trap or surface wrong`() throws {
// Garbage dismiss_count with an anchor present → default 1 → 10-pass interval.
#expect(LearningDecay.passesHidden(
["dismiss_count": "ten", "dismissed_at_pass": "4"],
currentPass: 5,
) == 9)
// Missing anchor → visible, whatever the count says.
#expect(LearningDecay.passesHidden(["dismiss_count": "3"], currentPass: 100) == nil)
// No decay state at all → visible.
#expect(LearningDecay.passesHidden(["pattern": "Hedging"], currentPass: 0) == nil)
// Garbage anchor → visible.
#expect(LearningDecay.passesHidden(["dismiss_count": "1", "dismissed_at_pass": "ten"], currentPass: 5) == nil)
// Hand-edited dismiss_count 9999 — no Int overflow trap, stays hidden.
#expect(LearningDecay.passesHidden(
["dismiss_count": "9999", "dismissed_at_pass": "0"],
currentPass: 1000,
) != nil)
// Huge hand-edited ints clamp at parse — no arithmetic trap anywhere.
#expect(LearningDecay.passesHidden(
["resurface_after": String(Int.max), "dismiss_count": "5", "dismissed_at_pass": "0"],
currentPass: 3,
) != nil)
// A negative anchor clamps to 0 — the interval counts from zero
// (unclamped, elapsed 45 would already have resurfaced it).
#expect(LearningDecay.passesHidden(
["dismiss_count": "1", "dismissed_at_pass": "-40"],
currentPass: 5,
) != nil)
// A corrupt clock reads empty; non-integer values read partial —
// never throws (a lagging clock only delays resurfacing).
let home = try toolsHome()
try FileManager.default.createDirectory(at: home.appendingPathComponent("learnings"), withIntermediateDirectories: true)
let counts = home.appendingPathComponent("learnings/pass-counts.json")
try "not json at all".write(to: counts, atomically: true, encoding: .utf8)
#expect(LearningDecay.passCounts(home: home) == [:])
try "{\"posts\": 2, \"outlines\": \"later\"}".write(to: counts, atomically: true, encoding: .utf8)
#expect(LearningDecay.passCounts(home: home) == ["posts": 2])
// A huge hand-edited dismiss_count is permanently hidden (the
// 30-doubling cap turns ANY base into ≥ 2^30) and dismiss REFUSES
// it — the count+1 stamp can never see an absurd value, so no
// arithmetic in the stamp path can trap; the file stays untouched.
let hugeHome = try toolsHome()
try writeLearning(hugeHome, "posts", "20261021-huge.md", """
---
pattern: Huge
dismiss_count: \(Int.max)
dismissed_at_pass: 0
---
""")
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: hugeHome, typeDir: "posts", file: "20261021-huge.md")
}
#expect(try Post.frontmatter(of: readLearning(hugeHome, "20261021-huge.md"))["dismiss_count"] == String(Int.max))
}
/// Scenario: dismiss is a write-path trust boundary — traversal-shaped
/// or hidden names refuse, a missing file refuses, and nothing lands
/// outside the learnings tree.
@Test func `dismiss refuses hostile paths and missing files`() throws {
let home = try toolsHome()
let file = "20261021-hedging.md"
try writeLearning(home, "posts", file, learning)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "../x.md")
}
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "../learnings", file: "x.md")
}
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "", file: "x.md")
}
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: ".hidden.md")
}
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "20260101-gone.md")
}
// Nothing escaped the learnings tree; the real learning is untouched.
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("x.md").path))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings/x.md").path))
#expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == nil)
}
/// Scenario: a pre-planted symlinked learnings component must not
/// turn dismiss into a file-plant primitive (promote's guard posture).
@Test func `a symlinked learnings dir refuses to dismiss`() throws {
let home = try toolsHome()
try writeLearning(home, "posts", "20261021-hedging.md", learning)
let target = home.appendingPathComponent("elsewhere", isDirectory: true)
try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
try FileManager.default.removeItem(at: home.appendingPathComponent("learnings/posts"))
try FileManager.default.createSymbolicLink(
at: home.appendingPathComponent("learnings/posts"),
withDestinationURL: target,
)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "20261021-hedging.md")
}
#expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty)
}
/// Scenario: a symlinked learning FILE must not become a copy-into-the-
/// consult-tree primitive — dismiss reads through a planted link and
/// the stamped write would materialize the target's content as a real
/// file the engine then serves. It refuses; the link and its target
/// stay untouched (#27 audit).
@Test func `a symlinked learning file refuses to dismiss`() throws {
let home = try toolsHome()
let secret = home.appendingPathComponent("secret.txt")
try "private stuff".write(to: secret, atomically: true, encoding: .utf8)
let posts = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: posts, withIntermediateDirectories: true)
let link = posts.appendingPathComponent("20261021-link.md")
try FileManager.default.createSymbolicLink(at: link, withDestinationURL: secret)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: "20261021-link.md")
}
let values = try link.resourceValues(forKeys: [.isSymbolicLinkKey])
#expect(values.isSymbolicLink == true) // still a link, not a copied file
#expect(try String(contentsOf: secret, encoding: .utf8) == "private stuff")
}
/// Scenario: the per-pass tick writes through a pre-planted symlinked
/// learnings dir if nothing guards it — recordPass refuses (promote's
/// posture), and the target dir stays empty (#27 audit).
@Test func `a symlinked learnings dir refuses to record a pass`() throws {
let home = try toolsHome()
let elsewhere = home.appendingPathComponent("elsewhere", isDirectory: true)
try FileManager.default.createDirectory(at: elsewhere, withIntermediateDirectories: true)
try FileManager.default.createSymbolicLink(
at: home.appendingPathComponent("learnings"),
withDestinationURL: elsewhere,
)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.recordPass(home: home, type: .post)
}
#expect(!FileManager.default.fileExists(atPath: elsewhere.appendingPathComponent("pass-counts.json").path))
}
/// Scenario: re-dismiss means AFTER the resurface (CONTEXT.md) — a
/// second dismiss while hidden (double-click, impatient tap) refuses
/// and changes nothing; a negative hand-edited dismiss_count clamps at
/// parse so the stamp still lands (#27 audit).
@Test func `re-dismiss refuses while hidden and negative counts clamp`() throws {
let home = try toolsHome()
let file = "20261021-hedging.md"
try writeLearning(home, "posts", file, learning)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
}
#expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == "1")
// A negative hand-edited count clamps to 0 at parse → stamp writes 1.
let negHome = try toolsHome()
try writeLearning(negHome, "posts", file, """
---
pattern: Neg
dismiss_count: -5
dismissed_at_pass: 0
---
""")
try LearningDecay.dismiss(home: negHome, typeDir: "posts", file: file)
#expect(try Post.frontmatter(of: readLearning(negHome, file))["dismiss_count"] == "1")
}
/// Scenario: decay is defined per pass-clocked content type — a foreign
/// learnings dir (a hand-made `essays/`) is pane-visible but never
/// clocked; dismissing there would hide the Learning forever behind a
/// lying countdown, so the store refuses (#27 audit).
@Test func `a foreign type dir refuses to dismiss`() throws {
#expect(LearningDecay.isClocked("posts"))
#expect(LearningDecay.isClocked("outlines"))
#expect(!LearningDecay.isClocked("essays"))
let home = try toolsHome()
let file = "20261021-musing.md"
try writeLearning(home, "essays", file, learning)
#expect(throws: FixCardStore.CardError.self) {
try LearningDecay.dismiss(home: home, typeDir: "essays", file: file)
}
let text = try String(
contentsOf: home.appendingPathComponent("learnings/essays/\(file)"),
encoding: .utf8,
)
#expect(Post.frontmatter(of: text)["dismiss_count"] == nil)
}
/// Scenario: a Learning with NO frontmatter (a hand-made file) still
/// dismisses — stampingFrontmatter prepends a fresh block and the body
/// rides verbatim below it (#27 audit: the prepend branch pinned).
@Test func `dismiss prepends a fresh block on a frontmatter-less file`() throws {
let home = try toolsHome()
let file = "20261021-bare.md"
let body = "# Just a hand edit\n\nSome prose.\n"
try writeLearning(home, "posts", file, body)
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let stampedText = try readLearning(home, file)
let frontmatter = Post.frontmatter(of: stampedText)
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "0")
#expect(PostStore.splitFrontmatter(stampedText).body == body)
}
/// Scenario: lines ABOVE the opening `---` (a hand-edit blank —
/// Post.frontmatter tolerates one) belong to neither block nor body;
/// the stamp keeps them — the "every other line verbatim" contract
/// (#27 review pin).
@Test func `dismiss preserves lines above the frontmatter block`() throws {
let home = try toolsHome()
let file = "20261021-blank.md"
try writeLearning(home, "posts", file, "\n---\npattern: Blank\n---\n\n# Blank\n")
try LearningDecay.dismiss(home: home, typeDir: "posts", file: file)
let stampedText = try readLearning(home, file)
#expect(stampedText.hasPrefix("\n---\n")) // the leading blank survived
#expect(Post.frontmatter(of: stampedText)["dismiss_count"] == "1")
#expect(stampedText.hasSuffix("\n\n# Blank\n")) // body untouched
}
}
+64 -1
View File
@@ -25,7 +25,7 @@ private func makeHome(_ write: (URL) throws -> Void) throws -> URL {
}
/// Seeds <home>/learnings/<type>/<file> with raw markdown.
private func writeLearning(_ home: URL, _ type: String, _ file: String, _ markdown: String) throws {
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)
@@ -123,4 +123,67 @@ struct LearningsPaneTests {
let home = try makeHome { _ in }
#expect(LearningsIndex.scan(home: home).isEmpty)
}
// MARK: Decay surface (#27, S4.2)
/// Scenario: Entry carries the decay verdict — visible learnings read
/// resurfacesIn nil; a dismissed one (anchor 2, once-dismissed =
/// interval 10) at pass 5 has 7 passes left; a twice-dismissed one
/// (interval 20) has 17.
@Test func `entry resurfacesIn pins the remaining-pass math`() {
#expect(LearningsIndex.Entry(
file: "20261021-fold-the-ladder.md",
text: "---\npattern: Fold the ladder\n---\n",
).resurfacesIn == nil)
#expect(LearningsIndex.Entry(
file: "20261020-hedging.md",
text: "---\npattern: Hedging\ndismiss_count: 1\ndismissed_at_pass: 2\n---\n",
currentPass: 5,
).resurfacesIn == 7)
#expect(LearningsIndex.Entry(
file: "20261020-hedging.md",
text: "---\npattern: Hedging\ndismiss_count: 2\ndismissed_at_pass: 2\n---\n",
currentPass: 5,
).resurfacesIn == 17)
}
/// Scenario: scan feeds the pass clock from pass-counts.json — the
/// dismissed fixture computes against the Home's counts, not zero.
/// Foreign (unclocked) dirs carry NO verdict even when hand-edited
/// decay state sits in the file — their clock never advances, a
/// countdown would lie (the store refuses to dismiss there; #27 audit).
@Test func `scan carries the pass clock into entries`() throws {
let home = try makeHome { home in
try writeLearning(home, "posts", "20261020-hedging.md", """
---
pattern: Hedging
dismiss_count: 1
dismissed_at_pass: 2
---
# Hedging
""")
try writeLearning(home, "posts", "20261021-fold.md", "---\npattern: Fold\n---\n")
try writeLearning(home, "essays", "20261019-musing.md", """
---
pattern: Musing
dismiss_count: 1
dismissed_at_pass: 2
---
""")
}
try "{\"outlines\": 99, \"posts\": 5}".write(
to: home.appendingPathComponent("learnings/pass-counts.json"),
atomically: true,
encoding: .utf8,
)
let posts = try #require(LearningsIndex.scan(home: home).first { $0.type == "posts" })
#expect(posts.entries.first { $0.id == "20261020-hedging.md" }?.resurfacesIn == 7)
#expect(posts.entries.first { $0.id == "20261021-fold.md" }?.resurfacesIn == nil)
let essays = try #require(LearningsIndex.scan(home: home).first { $0.type == "essays" })
#expect(essays.entries.first?.resurfacesIn == nil) // foreign: no verdict, no lying countdown
}
}
+5 -14
View File
@@ -14,15 +14,6 @@ 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
@@ -83,7 +74,7 @@ struct MCPToolsPromoteTests {
// ONE file, the pinned name shape.
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
let name = "\(stamped(now, "yyyyMMdd"))-hedging.md"
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)
@@ -95,7 +86,7 @@ struct MCPToolsPromoteTests {
#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("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
@@ -106,7 +97,7 @@ struct MCPToolsPromoteTests {
#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")).*"))
#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)
@@ -168,7 +159,7 @@ struct MCPToolsPromoteTests {
_ = 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"
let base = "\(FixCardStore.formatted(now, "yyyyMMdd"))-hedging"
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).sorted() == ["\(base)-2.md", "\(base).md"])
}
@@ -203,7 +194,7 @@ struct MCPToolsPromoteTests {
#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")).*"))
#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