CI / ci (push) Canceled after 0s
#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
184 lines
8.4 KiB
Swift
184 lines
8.4 KiB
Swift
//
|
|
// LearningDecay.swift
|
|
// Museion
|
|
//
|
|
// #27 (M3, S4.2): Dismiss & Decay — a dismissed Learning stops feeding
|
|
// passes and resurfaces after N completed passes of its content type
|
|
// (an output clock, not a calendar). Decay state lives in the
|
|
// Learning's own frontmatter (survives restarts, hand-editable); the
|
|
// pass clock is one JSON file per Home. Own file — FixCardStore is at
|
|
// its type-body ceiling.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
/// #27: Dismiss & Decay. nonisolated (FixCardStore posture) — the
|
|
/// headless MCP consult rail and off-main pane scans call this.
|
|
nonisolated enum LearningDecay {
|
|
/// Base resurface interval: completed passes of the content type.
|
|
/// Each re-dismiss doubles it; `resurface_after` overrides it
|
|
/// per-Learning.
|
|
private static let baseInterval = 10
|
|
|
|
/// Hand-editable ints clamp into this band at their parse sites so no
|
|
/// decay arithmetic can trap (Swift `*`/`+`/`-` crash the process on
|
|
/// overflow — a hostile or fat-fingered frontmatter value must not take
|
|
/// down the pane scan or the MCP rail); a billion passes is beyond any
|
|
/// real Home.
|
|
private static let valueCeiling = 1_000_000_000
|
|
|
|
/// The pass-counts key for a content type — the LITERAL plural dir name
|
|
/// ("posts"/"outlines"), `learningsDir`'s convention. One place so the
|
|
/// clock's writer and readers can never drift apart.
|
|
static func passKey(_ type: Post.ContentType) -> String {
|
|
"\(type.rawValue)s"
|
|
}
|
|
|
|
/// Whether a learnings/ dir name carries a pass clock — only the
|
|
/// content-type plurals do (`recordPass` ticks exactly these). A foreign
|
|
/// dir (a hand-made `essays/`) is pane-visible but never decay-clocked:
|
|
/// its clock reads 0 forever, so a dismiss there would hide the Learning
|
|
/// permanently — the store refuses (#27 audit).
|
|
static func isClocked(_ typeDir: String) -> Bool {
|
|
Post.ContentType.allCases.contains { passKey($0) == typeDir }
|
|
}
|
|
|
|
// MARK: - Pass clock
|
|
|
|
/// `<home>/learnings/pass-counts.json` — a flat {typeDir: count} of
|
|
/// completed passes (keys "posts"/"outlines"). Missing file/dir,
|
|
/// undecodable JSON, or non-integer values read as absent: a corrupt
|
|
/// clock reads as 0 and a lagging clock only delays resurfacing (safe
|
|
/// direction). Never throws.
|
|
static func passCounts(home: URL) -> [String: Int] {
|
|
let url = home.appendingPathComponent("learnings/pass-counts.json")
|
|
guard let data = try? Data(contentsOf: url),
|
|
let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
|
|
else { return [:] }
|
|
var counts: [String: Int] = [:]
|
|
for (key, value) in object {
|
|
guard let value = value as? Int else { continue }
|
|
// Hand-editable: clamp into the safe band (negative → 0).
|
|
counts[key] = min(max(value, 0), valueCeiling)
|
|
}
|
|
return counts
|
|
}
|
|
|
|
/// Increment `"<type>s"` by 1, creating learnings/ if missing. The
|
|
/// decay clock counts COMPLETED passes per content type (#27) —
|
|
/// advancePassState ticks it after its stamped write.
|
|
static func recordPass(home: URL, type: Post.ContentType) throws {
|
|
let learnings = home.appendingPathComponent("learnings", isDirectory: true)
|
|
// Same symlink posture as dismiss/promote: a pre-planted link must
|
|
// not turn the per-pass tick into a write outside the Home's tree
|
|
// (#27 audit).
|
|
let linkValues = try? learnings.resourceValues(forKeys: [.isSymbolicLinkKey])
|
|
if linkValues?.isSymbolicLink == true {
|
|
throw FixCardStore.CardError(message: "learnings path is a symlink: \(learnings.path)")
|
|
}
|
|
try FileManager.default.createDirectory(at: learnings, withIntermediateDirectories: true)
|
|
var counts = passCounts(home: home)
|
|
let key = passKey(type)
|
|
counts[key] = (counts[key] ?? 0) + 1
|
|
let data = try JSONSerialization.data(withJSONObject: counts, options: [.sortedKeys])
|
|
try data.write(to: learnings.appendingPathComponent("pass-counts.json"), options: .atomic)
|
|
}
|
|
|
|
// MARK: - Visibility (pure)
|
|
|
|
/// nil = visible now; positive = passes still hidden. Pure — the
|
|
/// pane's rows, the consult rail, and the dismiss stamp all agree
|
|
/// through this one function. Lenient reads via `Int(_:)`: a garbage
|
|
/// `dismiss_count` defaults to 1 when an anchor exists (else 0), a
|
|
/// missing/garbage anchor means visible, and the doubling caps at 30
|
|
/// iterations so a hand-edited `dismiss_count` can't overflow Int.
|
|
static func passesHidden(_ frontmatter: [String: String], currentPass: Int) -> Int? {
|
|
guard let parsedAnchor = frontmatter["dismissed_at_pass"].flatMap({ Int($0) }) else { return nil }
|
|
let dismissedAt = min(max(parsedAnchor, 0), valueCeiling)
|
|
let dismissCount = dismissCount(in: frontmatter)
|
|
guard dismissCount > 0 else { return nil }
|
|
let override = frontmatter["resurface_after"]
|
|
.flatMap { Int($0) }
|
|
.map { min(max($0, 0), valueCeiling) }
|
|
var interval = override ?? baseInterval
|
|
for _ in 0 ..< min(dismissCount - 1, 30) {
|
|
interval *= 2
|
|
}
|
|
let elapsed = currentPass - dismissedAt
|
|
return elapsed >= interval ? nil : interval - elapsed
|
|
}
|
|
|
|
/// The parsed `dismiss_count` — garbage defaults to 1 when an anchor
|
|
/// exists (a half-done hand-edit still dismisses once), else 0. Negative
|
|
/// hand-edits clamp at parse (a `-5` must not make Dismiss a silent
|
|
/// no-op — #27 audit). The ONE parse both the visibility math and the
|
|
/// dismiss stamp ride; they must agree.
|
|
private static func dismissCount(in frontmatter: [String: String]) -> Int {
|
|
if let count = frontmatter["dismiss_count"].flatMap({ Int($0) }) {
|
|
return max(count, 0)
|
|
}
|
|
return frontmatter["dismissed_at_pass"] != nil ? 1 : 0
|
|
}
|
|
|
|
// MARK: - Dismiss
|
|
|
|
/// #27: stamp decay state IN the Learning's own file — `dismissed`
|
|
/// (date), `dismiss_count` (+1), `dismissed_at_pass` (the type's
|
|
/// current clock) — every other line preserved verbatim. Write-path
|
|
/// trust boundary (promote's guard posture): hostile names refuse, a
|
|
/// foreign (unclocked) type dir refuses, a symlinked learnings
|
|
/// component OR learning file refuses, a missing/unreadable file
|
|
/// throws, and a currently-hidden Learning refuses (re-dismiss
|
|
/// lands after the resurface so doubling starts from a fresh
|
|
/// anchor; this also makes a double-click's second stamp
|
|
/// harmless) — never a write outside the learnings tree.
|
|
static func dismiss(home: URL, typeDir: String, file: String, now: Date = Date()) throws {
|
|
for name in [typeDir, file] {
|
|
guard !name.isEmpty, !name.contains("/"), !name.contains(".."), !name.hasPrefix(".") else {
|
|
throw FixCardStore.CardError(message: "invalid learning path: \(typeDir)/\(file)")
|
|
}
|
|
}
|
|
// Decay is defined per pass-clocked content type — a foreign dir's
|
|
// clock reads 0 forever, so a dismiss there would hide permanently
|
|
// (#27 audit).
|
|
guard isClocked(typeDir) else {
|
|
throw FixCardStore.CardError(message: "not a pass-clocked content type: \(typeDir)")
|
|
}
|
|
let learnings = home.appendingPathComponent("learnings", isDirectory: true)
|
|
let dir = learnings.appendingPathComponent(typeDir, isDirectory: true)
|
|
let url = dir.appendingPathComponent(file)
|
|
// The FILE rides the same symlink check as the dirs: reading through
|
|
// a planted link and writing the stamped copy back would materialize
|
|
// a foreign file's content into the engine-served tree (#27 audit).
|
|
for component in [learnings, dir, url] {
|
|
let values = try? component.resourceValues(forKeys: [.isSymbolicLinkKey])
|
|
if values?.isSymbolicLink == true {
|
|
throw FixCardStore.CardError(message: "learnings path is a symlink: \(component.path)")
|
|
}
|
|
}
|
|
guard let text = try? String(contentsOf: url, encoding: .utf8) else {
|
|
throw FixCardStore.CardError(message: "learning not found: \(file)")
|
|
}
|
|
|
|
let frontmatter = PostFrontmatter.parse(text)
|
|
let clock = passCounts(home: home)[typeDir] ?? 0
|
|
if let remaining = passesHidden(frontmatter, currentPass: clock) {
|
|
throw FixCardStore.CardError(message: "already dismissed — resurfaces in \(remaining) \(remaining == 1 ? "pass" : "passes")")
|
|
}
|
|
// Clamped before +1 — an absurd hand-edited dismiss_count must not
|
|
// trap the stamp.
|
|
let count = min(dismissCount(in: frontmatter), valueCeiling)
|
|
// #180: the codec's update-keys posture (the mechanical walk this
|
|
// file used to own); the Learning document shape is unchanged.
|
|
let stamped = PostFrontmatter.updating(
|
|
text: text,
|
|
with: [
|
|
("dismissed", FixCardStore.formatted(now, "yyyy-MM-dd")),
|
|
("dismiss_count", "\(count + 1)"),
|
|
("dismissed_at_pass", "\(clock)"),
|
|
],
|
|
)
|
|
try stamped.write(to: url, atomically: true, encoding: .utf8)
|
|
}
|
|
}
|