// // 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 /// `/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 `"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 = Post.frontmatter(of: 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) let stamped = stampingFrontmatter( of: 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) } /// The surgical frontmatter rewrite (mergedFrontmatter's line-walk, /// generalized to ordered pairs): set-overwrite the keys in place, /// insert absent ones before the closing `---`, preserve every other /// line verbatim (leading hand-edit lines above the opening `---` /// included), keep the block's trailing newline. No frontmatter /// block at all → prepend a fresh one. Internal since #31: the /// first-draft stats capture is the third caller. // ponytail: PostStore.mergedFrontmatter's line-walk duplicated and // generalized — extraction would grow PostStore at its type-body // ceiling; #31's capture is the third caller and it STILL isn't // extracted (LearningDecay + PostStore stay the two owners; the // type-body ceilings named above are unchanged). static func stampingFrontmatter(of text: String, with pairs: [(key: String, value: String)]) -> String { let (block, body) = PostStore.splitFrontmatter(text) guard !block.isEmpty else { return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body } // Lines ABOVE the opening `---` (a hand-edit blank line — // Post.frontmatter tolerates one) fall in neither block nor // body; keep them verbatim so the rewrite loses nothing (#27 review). let prefix = text.range(of: block).map { String(text[..<$0.lowerBound]) } ?? "" var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) // Drop the empty tail the block's final newline produced — re-added below. if let last = lines.last, last.isEmpty { lines.removeLast() } let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first }) var seen = Set() for (index, line) in lines.enumerated() { let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty, trimmed != "---" else { continue } let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces) if let value = oursByKey[key] { lines[index] = "\(key): \(value)" seen.insert(key) } } let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" } if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 { lines.insert(contentsOf: insertions, at: close) } return prefix + lines.joined(separator: "\n") + "\n" + body } }