Files
museion/Museion/LearningsPaneView.swift
T
AlexKucera 78c8844184
CI / ci (push) Canceled after 0s
feat(mentor): dismiss & decay Learnings (#27)
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
2026-10-21 14:19:43 +02:00

324 lines
12 KiB
Swift

//
// LearningsPaneView.swift
// Museion
//
// #26 (S4.4, ADR-0005): the Learnings pane — the writer's per-writer
// portable critique memory as plain files. List-only (Archive pane
// precedent): read side; promotion (the fix-card rail) writes the files.
//
import SwiftUI
/// The pane's disk reader. One markdown file per Learning under
/// `<home>/learnings/<type-plural>/` (literal plurals: "posts",
/// "outlines"), named `YYYYMMDD-<pattern-slug>.md` — hand-editable,
/// git-diffable, surviving restarts. Every read is lenient: a
/// stranger's hand-edit never crashes the pane.
nonisolated enum LearningsIndex {
/// One Learning on disk. `pattern` falls back to the filename
/// (extension and leading date + hyphen stripped); `problem`/
/// `promoted` omit when the frontmatter key is absent. #27:
/// `resurfacesIn` is the decay verdict — nil = visible now,
/// positive = passes until resurface. `currentPass: nil` = an
/// unclocked (foreign) type dir: never a verdict, so the pane
/// cannot show a countdown that could never advance (#27 audit —
/// the store refuses to dismiss there for the same reason).
nonisolated struct Entry: Identifiable {
/// The file name (with extension) — unique within its group.
let id: String
let pattern: String
var problem: String?
var promoted: String?
let resurfacesIn: Int?
init(file: String, text: String, currentPass: Int? = nil) {
let frontmatter = Post.frontmatter(of: text)
id = file
pattern = frontmatter["pattern"] ?? Self.pattern(fromFilename: file)
problem = frontmatter["problem"].flatMap { $0.isEmpty ? nil : $0 }
promoted = frontmatter["promoted"].flatMap { $0.isEmpty ? nil : $0 }
resurfacesIn = currentPass.flatMap { LearningDecay.passesHidden(frontmatter, currentPass: $0) }
}
/// "20261021-fold-the-ladder.md" → "fold-the-ladder".
static func pattern(fromFilename file: String) -> String {
let stem = (file as NSString).deletingPathExtension
guard Self.isDated(file) else { return stem }
return String(stem.dropFirst(9))
}
/// The filename contract: a `YYYYMMDD-` prefix (8 digits + hyphen).
static func isDated(_ file: String) -> Bool {
let stem = (file as NSString).deletingPathExtension
let digits = stem.prefix(8)
return digits.count == 8 && digits.allSatisfy(\.isNumber) && stem.dropFirst(8).first == "-"
}
}
/// One content-type section, keyed by the directory name.
nonisolated struct Group {
let type: String
var entries: [Entry]
}
/// Scans `<home>/learnings/*/` — groups keyed by directory name
/// (type-sorted), entries newest-first (the YYYYMMDD prefix sorts
/// lexicographically desc; undated files last). Missing learnings/ →
/// empty; hidden dirs/files, non-.md, loose files, and unreadable
/// files never surface. Same skip posture as `Post.scan`.
static func scan(home: URL) -> [Group] {
let counts = LearningDecay.passCounts(home: home) // #27: the pass clock feeds the decay verdict
let root = home.appendingPathComponent("learnings", isDirectory: true)
guard let typeDirs = try? FileManager.default.contentsOfDirectory(
at: root,
includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
) else { return [] }
var groups: [Group] = []
for dir in typeDirs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix(".") else { continue }
guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
else { continue }
// #27: the pass clock feeds the decay verdict — clocked dirs
// carry their count, foreign dirs nil (no verdict; Entry's audit).
let currentPass = LearningDecay.isClocked(dir.lastPathComponent)
? counts[dir.lastPathComponent] ?? 0
: nil
let entries = files
.filter {
!$0.lastPathComponent.hasPrefix(".")
&& $0.pathExtension.caseInsensitiveCompare("md") == .orderedSame
}
.compactMap { file in
// ponytail: unbounded read, file symlinks followed — same
// ceiling as Post.scan/FixCardStore.learnings (systemic,
// local-Home threat only); isSymbolicLink + size cap if a
// hostile Home ever matters.
(try? String(contentsOf: file, encoding: .utf8))
.map { Entry(file: file.lastPathComponent, text: $0, currentPass: currentPass) }
}
guard !entries.isEmpty else { continue }
groups.append(Group(
type: dir.lastPathComponent,
// Dated files first (newest first — lexicographic desc on
// the name), undated hand-edits last.
entries: entries.sorted { lhs, rhs in
let (lhsDated, rhsDated) = (Entry.isDated(lhs.id), Entry.isDated(rhs.id))
return lhsDated == rhsDated ? lhs.id > rhs.id : lhsDated
},
))
}
return groups
}
private static func isPlainDirectory(_ url: URL) -> Bool {
let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
return values?.isDirectory ?? false && !(values?.isSymbolicLink ?? false)
}
}
/// #26: the Learnings pane — list-only, like the Archive pane. #27:
/// rows dismiss learnings (decay state stamps into the file's
/// frontmatter; the pane re-scans after).
struct LearningsPaneView: View {
let home: URL
@State private var groups: [LearningsIndex.Group] = []
@State private var lastError: String?
/// The home the LAST-enqueued scan is for — a dismiss Task captures the
/// OLD home, and Task.isCancelled cannot reach it, so the assignment
/// gates on this instead (#27 audit).
@State private var scannedHome: URL?
var body: some View {
VStack(spacing: 0) {
// No New button — learnings arrive by promotion, not creation.
PaneHeader(title: "Learnings")
if let lastError {
Text(lastError)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(.orange)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 14)
.padding(.bottom, 6)
}
if groups.isEmpty {
emptyState
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
ForEach(groups, id: \.type) { group in
LearningSection(group: group) { entry in
dismiss(entry, in: group.type)
}
}
}
.padding(.bottom, 12)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.background)
// Disk I/O stays off MainActor (rescan posture, PostsModel) — the
// .task body is MainActor, so the scan hops to a detached task and
// the assignment lands back on the main actor.
// ponytail: no FSEvents watcher — the pane re-scans on .task(id: home)
// each time it appears; a promote landing while the pane stays open
// goes stale until the pane is re-entered. Add a watcher if that
// ever annoys.
.task(id: home) {
scannedHome = home
await rescan(home)
}
}
/// The detached scan + cancellation-gated assignment both entries into
/// the list share (.task and post-dismiss refresh).
private func rescan(_ target: URL) async {
let scanned = await Task.detached(priority: .userInitiated) {
LearningsIndex.scan(home: target)
}.value
// A home repoint cancels the awaiting .task, but a detached scan is
// not cancellation-aware — and a dismiss Task holds the OLD home
// unreached by that cancellation. Either way: a scan that is not for
// the Home we last entered must not overwrite its groups.
guard !Task.isCancelled, scannedHome == target else { return }
groups = scanned
lastError = nil // a successful rescan clears the strip
}
/// #27: dismissal is low-stakes and self-healing (it decays back) —
/// no confirm sheet. Failures land in the orange strip, never an alert.
private func dismiss(_ entry: LearningsIndex.Entry, in typeDir: String) {
Task {
var failure: String?
do {
try await Task.detached(priority: .userInitiated) {
try LearningDecay.dismiss(home: home, typeDir: typeDir, file: entry.id)
}.value
} catch {
failure = error.localizedDescription
}
await rescan(home)
// #27 review: a repointed Home must not inherit the old
// Home's failure — the same gate rescan enforces for groups.
if scannedHome == home {
lastError = failure
}
}
}
private var emptyState: some View {
VStack(spacing: 8) {
Text("No learnings yet.")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Promoting a fix card writes one plain markdown Learning here.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// One content-type section: the head + its rows. A child view so the
/// lazy stack sees one view per group (its inner ForEach is the view's
/// own body, not uneven outer-row content).
private struct LearningSection: View {
let group: LearningsIndex.Group
let onDismiss: (LearningsIndex.Entry) -> Void
var body: some View {
SectionHeadView(type: group.type, count: group.entries.count)
.padding(.top, 16)
.padding(.horizontal, 14)
.padding(.bottom, 6)
// Foreign (unclocked) dirs never offer Dismiss — their clock
// reads 0 forever, a dismiss there would hide permanently (the
// store refuses too; #27 audit).
let dismissable = LearningDecay.isClocked(group.type)
ForEach(group.entries) { entry in
LearningRow(entry: entry, onDismiss: dismissable ? { onDismiss(entry) } : nil)
}
}
}
/// The library's section-head voice: serif-15 semibold name
/// (display-lowercased) + mono-11 `· N` count.
private struct SectionHeadView: View {
let type: String
let count: Int
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text(type)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
.textCase(.lowercase) // display-only — the dir name keeps its case
.lineLimit(1)
.truncationMode(.tail)
Text("· \(count)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer(minLength: 0)
}
}
}
/// One Learning row: pattern as the title, problem as the secondary
/// line, promoted date + file name in mono-11. #27: visible rows offer
/// a mono-11 Dismiss (the Archive pane's Unarchive voice); dismissed
/// rows dim (closed-card voice) and count down their resurface.
private struct LearningRow: View {
let entry: LearningsIndex.Entry
/// nil = foreign dir, never decay-clocked (#27 audit).
let onDismiss: (() -> Void)?
var body: some View {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 5) {
Text(entry.pattern)
.font(.callout.weight(.semibold))
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
if let problem = entry.problem {
Text(problem)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.lineLimit(2)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
}
Text(metaLine)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
}
if entry.resurfacesIn == nil, let onDismiss {
Button("Dismiss", action: onDismiss)
.buttonStyle(.plain)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.help("Hide this learning from passes until it resurfaces")
.accessibilityLabel("Dismiss \(entry.pattern)")
}
}
.padding(10)
.opacity(entry.resurfacesIn == nil ? 1 : 0.45)
}
private var metaLine: String {
if let remaining = entry.resurfacesIn {
return "dismissed · resurfaces in \(remaining) \(remaining == 1 ? "pass" : "passes") · " + metaTail
}
return metaTail
}
private var metaTail: String {
entry.promoted.map { "promoted · \($0) · \(entry.id)" } ?? entry.id
}
}