// // 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 /// `/learnings//` (literal plurals: "posts", /// "outlines"), named `YYYYMMDD-.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 = PostFrontmatter.parse(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 `/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("."), 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 } /// Parens load-bearing for readability — `&&` out-binds `??` (probed; /// a finish-audit misread the bare form as a dead symlink clause). /// lstat semantics: a symlink-to-dir reports isDirectory=false, so /// both halves refuse it; the link clause is the belt for any future /// resolved-URL caller. 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. // One shared leading edge (26): pane title, group headings, and // entry text all start at the same x. // r8 (argon#9, mercury#18/19): the hairline is bounded to the // SAME 720pt reading column the entries sit in — one framed block. PaneHeader(title: "Learnings", titleInset: 26, hairlineMaxWidth: 720) 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) { // r6 (argon#17, mercury#26 — rhythm): the FIRST // group sits 10pt under the pane header; every // later group breaks with a column-bounded // hairline above its head (~22pt above the // rule, ~18pt below — LearningSection). ForEach(Array(groups.enumerated()), id: \.element.type) { index, group in LearningSection(group: group, isFirst: index == 0) { entry in dismiss(entry, in: group.type) } } } // ui-polish r2: bounded reading column (~720pt, the // transcript's measure language), left-anchored — entries // never stretch across the whole canvas. .frame(maxWidth: 720, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading) .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). r5 (argon#17, mercury#26): /// `isFirst` picks the rhythm — 10pt under the pane header (no rule; the /// header's own hairline is right above), or a 32pt break with a /// column-bounded hairline above the head. private struct LearningSection: View { let group: LearningsIndex.Group let isFirst: Bool let onDismiss: (LearningsIndex.Entry) -> Void var body: some View { VStack(alignment: .leading, spacing: 4) { if !isFirst { // r6 (argon#16, mercury#26): the break hairline is BOUNDED // to the content column — same leading x as the entry text // (26), same right edge as the 720 column (it used to start // 27px LEFT of the text and end mid-window). Rectangle() .fill(DesignTokens.border) .frame(height: 1) .padding(.leading, 26) } SectionHeadView(type: group.type, count: group.entries.count) // r7 (argon#15, mercury#49): the FIRST category label // sits 24pt under the header hairline (the r6 10 clung // to the rule); later groups keep their break rhythm. .padding(.top, isFirst ? 24 : 14) .padding(.horizontal, 26) .padding(.bottom, 2) // 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) } } // r6 rhythm (sol#36, mercury#54): above the rule = last row's // bottom 10 + stack spacing 4 + this 8 ≈ 22pt (was ~36); below // the rule = spacing 4 + head top 14 ≈ 18pt (was ~7) — balanced // per the 20-24/16-20 ruling; label → first entry = head bottom // 2 + spacing 4 + row top 10 ≈ 16 (was ~25, tighter). .padding(.top, isFirst ? 0 : 8) } } /// The section-head voice, DEMOTED below the pane title (serif-15): /// ui-polish r2 — the library's pass-state voice (tracked UPPERCASE /// mono micro-label) + mono-11 `· N` count. r4 (sol#4, argon#49): 11pt /// medium — a touch MORE weight than the filenames beneath, which /// step down (LearningRow) so the category always wins the hierarchy. /// r6: full muted ink (contrast final). The category break (22/18pt /// margins + a column-bounded hairline) lives in LearningSection. /// Shares the pane's single leading edge (26). private struct SectionHeadView: View { let type: String let count: Int var body: some View { HStack(alignment: .firstTextBaseline, spacing: 8) { Text(type) .font(.system(size: 11, weight: .medium, design: DesignTokens.mono)) .kerning(0.6) .textCase(.uppercase) // display-only — the dir name keeps its case // r6 (sol#6/21 — contrast final): full muted ink; the r4 // 0.9 wash died here (the weight step below still wins the // hierarchy). .foregroundStyle(DesignTokens.muted) .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) { // r7 (mercury#49, argon#15): serif-13 semibold — the // pane title keeps the serif-15 rung; hierarchy rides // the rung gap (r6's sans-14 sat too close to it). Text(entry.pattern) .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) if let problem = entry.problem { // r7 (sol#34): descriptions at an explicit 13pt. Text(problem) .font(.system(size: 13)) .foregroundStyle(DesignTokens.muted) .lineLimit(2) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) } // r7 (sol#34): description → filename gap +5 (spacing 5 // + this 5 = 10) — the meta line reads as the entry's // footnote, not a third body line. Text(metaLine) // r4 (mercury#59 tail): the filename/meta line recedes one // more step — 10.5, beneath the 11pt medium category labels. .font(.system(size: 10.5, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) .padding(.top, 5) } 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)") } } // One leading edge with the pane title and group headings (26). .padding(EdgeInsets(top: 10, leading: 26, bottom: 10, trailing: 14)) // Dismissed rows dim to the 0.85 floor (r6 contrast final — // deliberately-receding chrome never sits below 0.85; the r2 // 0.6 dim died) — visible as dimmed, never washed out. .opacity(entry.resurfacesIn == nil ? 1 : 0.85) } 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 } }