Files
museion/Museion/PostLibrary.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

157 lines
6.5 KiB
Swift

//
// PostLibrary.swift
// Museion
//
// #17 (S1.1): the Posts list mirrors what is on disk under the Museion Home.
// #107 (ADR-0012): pieces live under projects/<name>/<id>/ and
// archive/<name>/<id>/ — both roots are scanned.
//
import Foundation
/// One Post on disk: `<home>/{projects|archive}/<project>/<id>/post.md`
/// (ADR-0012 shape; the folder name under either root is the project).
nonisolated struct Post: Identifiable, Equatable {
/// The post folder's name — the Post's durable identity (CONTEXT.md).
/// Unique across projects AND archive: the slug namespace is global
/// (ADR-0012), so the id alone resolves the folder.
let id: String
/// The Post's Title: first non-empty line after any frontmatter, heading markers stripped.
var title: String
/// Pass State from frontmatter; First Draft when absent (explicit, never inferred).
var passState: PassState
/// Origin from frontmatter; writer when absent. Immutable once set (CONTEXT.md).
var origin: Origin
/// Content Type from frontmatter `type` (#107); post when absent.
var type: ContentType
/// The containing folder's name under projects/ or archive/ (#107).
var project: String
/// True when the piece lives under archive/ (#107).
var isArchived: Bool
/// New pieces land here when no project is selected (#107).
static let defaultProject = "posts"
/// The two roots that hold pieces, in resolution order (#107): projects/
/// is searched before archive/.
static let containerRoots = ["projects", "archive"]
nonisolated enum PassState: String, Equatable, CaseIterable {
case firstDraft = "First Draft"
case pass1Done = "Pass-1 Done"
case pass2Done = "Pass-2 Done"
}
nonisolated enum Origin: String, Equatable {
case writer
/// PRD S5.1 pins the frontmatter vocabulary: `origin: writer|ai`.
// swiftlint:disable:next identifier_name
case ai
}
nonisolated enum ContentType: String, CaseIterable {
case post
case outline
}
/// Reads every `<root>/<project>/<id>/post.md` (roots: projects/, then
/// archive/ — ADR-0012) into Posts (sorted by title, Finder order).
/// Same skip rules at both levels: symlinks, hidden dirs, loose files;
/// folders without `post.md` (lazy) aren't Posts; a malformed folder
/// can't crash the list. Read-only for #17.
static func scan(home: URL) -> [Post] {
var posts: [Post] = []
// #107 audit: duplicate ids can appear on disk (Finder copy across
// projects, partial restore) — first-wins dedupe, in the SAME
// projects-before-archive, name-sorted order folder(of:) resolves
// by, so the row shown is always the piece written. Later twins are
// invisible until renamed in Finder.
var seen: Set<String> = []
for root in containerRoots {
let isArchived = root == "archive"
let rootURL = home.appendingPathComponent(root, isDirectory: true)
guard let projects = try? FileManager.default.contentsOfDirectory(
at: rootURL,
includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
) else { continue }
for projectDir in projects.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
let values = try? projectDir.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard values?.isDirectory ?? false, !(values?.isSymbolicLink ?? false),
!projectDir.lastPathComponent.hasPrefix(".") else { continue }
guard let entries = try? FileManager.default.contentsOfDirectory(
at: projectDir,
includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
) else { continue }
for dir in entries.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
let pieceValues = try? dir.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard pieceValues?.isDirectory ?? false, !(pieceValues?.isSymbolicLink ?? false),
!dir.lastPathComponent.hasPrefix(".") else { continue }
let fileURL = dir.appendingPathComponent("post.md")
guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { continue }
guard seen.insert(dir.lastPathComponent).inserted else { continue }
let frontmatter = frontmatter(of: text)
posts.append(
Post(
id: dir.lastPathComponent,
title: title(of: text),
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
origin: Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer,
type: ContentType(rawValue: frontmatter["type"] ?? "") ?? .post,
project: projectDir.lastPathComponent,
isArchived: isArchived,
),
)
}
}
}
return posts.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
}
/// The `---`-delimited frontmatter block if present; empty otherwise.
/// Quoted scalar values (`origin: "ai"`) are unquoted — lenient YAML.
static func frontmatter(of text: String) -> [String: String] {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
guard lines.first(where: { !$0.trimmed().isEmpty })?.trimmed() == "---" else { return [:] }
var map: [String: String] = [:]
for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() {
let trimmed = line.trimmed()
guard trimmed != "---" else { break }
guard let colon = trimmed.firstIndex(of: ":") else { continue }
let key = trimmed[..<colon].trimmingCharacters(in: .whitespaces)
let value = trimmed[trimmed.index(after: colon)...]
.trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
map[key] = value
}
return map
}
/// The Post's Title: first non-empty line after any frontmatter block,
/// `#` heading markers stripped; `untitled` when nothing readable remains.
static func title(of text: String) -> String {
var lines = text.split(separator: "\n", omittingEmptySubsequences: false)[...]
if let open = lines.firstIndex(where: { !$0.trimmed().isEmpty }), lines[open].trimmed() == "---" {
if let close = lines[(open + 1)...].firstIndex(where: { $0.trimmed() == "---" }) {
lines = lines[(close + 1)...]
} else {
return "untitled" // unterminated block: nothing trustworthy follows
}
}
for line in lines {
let trimmed = line.trimmed()
guard !trimmed.isEmpty else { continue }
let stripped = trimmed.trimmingCharacters(in: CharacterSet(charactersIn: "#").union(.whitespaces))
return stripped.isEmpty ? "untitled" : stripped
}
return "untitled"
}
}
nonisolated extension Substring {
func trimmed() -> String {
// whitespacesAndNewlines, not .whitespaces: a CRLF file's lines carry
// a trailing \r that would defeat every "---" boundary check.
trimmingCharacters(in: .whitespacesAndNewlines)
}
}