Files
museion/MuseionTests/LearningDecayTests.swift
AlexKucera 218e2db397
CI / ci (push) Canceled after 0s
refactor(posts): one frontmatter read/write codec
#180: one PostFrontmatter module now owns the lenient read
(parse/split/decoded) and every write posture — fresh stamp,
merge-import, update-keys — behind one known-key table (type,
pass_state, origin; one insertion order). The three near-twin walkers
are deleted byte-identically: PostStore.stamped/splitFrontmatter/
mergedFrontmatter, LearningDecay.stampingFrontmatter,
Post.frontmatter(of:) — 21 call sites swept across seven production
files and eight test files.

The Unaided First Draft eligibility is named once and consumed by both
gates: isUnaidedFirstDraftPair (writer ∧ post — the scan's read-back
gate) and isCaptureEligible (pair ∧ First Draft — the capture gate at
pass invocation). The lenient ?? default stamp decode is extracted
with it (the third copy's deferred extraction).

One deliberate divergence from the absorbed writer, doc-commented and
pinned: mergingImport now preserves hand-edit lines above the opening
--- on import where the old split-first shape silently dropped them —
lossless through every posture is the ticket's contract. Seven codec
pins (PostFrontmatterTests) cover the posture round-trip (foreign keys
verbatim through import → save → advance → micropub), the lenient
unknown-type decode, and the predicates' truth table.

Existing pieces are untouched on disk: every posture moved verbatim
and the full suite pins the byte shapes (664/664 green; the one
under-load flake in the #179 repoint pin is pre-existing on main,
proven by a stashed-tree control run).

Closes #180
2026-11-10 10:21:32 +01:00

401 lines
17 KiB
Swift

//
// 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 = PostFrontmatter.parse(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(PostFrontmatter.split(stampedText).body == PostFrontmatter.split(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 PostFrontmatter.parse(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 PostFrontmatter.parse(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 PostFrontmatter.parse(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 PostFrontmatter.parse(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 PostFrontmatter.parse(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(PostFrontmatter.parse(text)["dismiss_count"] == nil)
}
/// Scenario: a Learning with NO frontmatter (a hand-made file) still
/// dismisses — the update walk 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 = PostFrontmatter.parse(stampedText)
#expect(frontmatter["dismiss_count"] == "1")
#expect(frontmatter["dismissed_at_pass"] == "0")
#expect(PostFrontmatter.split(stampedText).body == body)
}
/// Scenario: lines ABOVE the opening `---` (a hand-edit blank —
/// PostFrontmatter.parse tolerates any count) 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(PostFrontmatter.parse(stampedText)["dismiss_count"] == "1")
#expect(stampedText.hasSuffix("\n\n# Blank\n")) // body untouched
}
}