// // 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/// and // archive/// — both roots are scanned. // import Foundation /// One Post on disk: `/{projects|archive}///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 /// #33 (S6.1): the remembered Micro.blog draft URL (frontmatter /// `micropub_url`) — set when a draft was sent, the target the /// publish step updates. Inert to everything else. var micropubURL: String? /// #32 (S5.2): the captured first-draft stats — present ONLY when /// `captureFirstDraftStats` stamped the piece at a pass invocation /// (writer origin, First Draft, post type, decided there against the /// file's own frontmatter), and read back only for the same immutable /// pair (scan's gate — see `Post.scan`). Presence is the trend view's /// whole eligibility story: app-internal edit paths never grow these /// keys, and non-writer or outline pieces never render them. var firstDraftStats: FirstDraftStats? /// New pieces land here when no project is selected (#107). static let defaultProject = "posts" /// One stats capture, read back from the five flat `stats_*` /// frontmatter keys (#31 wrote them; #32 reads them back). nonisolated struct FirstDraftStats: Equatable { /// When the pass invocation captured the draft /// (`yyyy-MM-dd'T'HH:mm:ss`, lexically sortable — #31's stamp). let captured: Date let stats: DraftStats /// Nil unless EVERY key parses to a finite Double — a half-loaded /// arc would lie, and `Double("nan")`/`Double("inf")` DO parse: /// a non-finite peak traps the chart's y-domain construction and /// reads "steady" in the verdict (finish-audit #32). init?(frontmatter: [String: String]) { guard let captured = frontmatter["stats_captured"].flatMap(Self.parseCaptured), let burstiness = frontmatter["stats_burstiness"].flatMap(Self.finite), let typeTokenRatio = frontmatter["stats_type_token_ratio"].flatMap(Self.finite), let sentenceVariation = frontmatter["stats_sentence_variation"].flatMap(Self.finite), let trigramRepetition = frontmatter["stats_trigram_repetition"].flatMap(Self.finite) else { return nil } self.captured = captured stats = DraftStats( burstiness: burstiness, typeTokenRatio: typeTokenRatio, sentenceVariation: sentenceVariation, trigramRepetition: trigramRepetition, ) } /// The symmetric read of the capture stamp (`FixCardStore.formatted`, /// local time) — per-access formatter, the repo's no-static convention. private static func parseCaptured(_ stamp: String) -> Date? { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" formatter.locale = Locale(identifier: "en_US_POSIX") return formatter.date(from: stamp) } /// Frontmatter is external data (hand-edits, imports): reject the /// non-finite doubles Swift's `Double(String)` happily parses. private static func finite(_ raw: String) -> Double? { guard let value = Double(raw), value.isFinite else { return nil } return value } } /// 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 `///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. /// #143: pass a `cache` to reuse parses of files whose path, mtime, /// and size are unchanged (nil, the default, reads everything — /// every existing caller's behavior). static func scan(home: URL, cache: PostScanCache? = nil) -> [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 = [] 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("."), 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") // #143: unchanged post.md (path + mtime + size) → reuse // the prior parse. The walk stays the truth; only the // read is skipped. One stamp serves consult AND store — // taken before both, so a mid-scan rewrite can never be // pinned as fresh (see store). let stamp = PostScanCache.stamp(at: fileURL) if let cached = cache?.cachedPost(at: fileURL, stamp: stamp) { guard seen.insert(dir.lastPathComponent).inserted else { continue } posts.append(cached) continue } guard let text = try? String(contentsOf: fileURL, encoding: .utf8), seen.insert(dir.lastPathComponent).inserted else { continue } let post = parse( text: text, id: dir.lastPathComponent, project: projectDir.lastPathComponent, isArchived: isArchived, ) cache?.store(post, at: fileURL, stamp: stamp) posts.append(post) } } } return posts.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } } /// One post.md's text parsed into a Post — the scan's miss path (#143 /// kept this a pure function of (text, location); the cache memoizes /// its output, nothing else). private static func parse(text: String, id: String, project: String, isArchived: Bool) -> Post { let frontmatter = PostFrontmatter.parse(text) let stamp = PostFrontmatter.decoded(frontmatter) return Post( id: id, title: title(of: text), passState: stamp.passState, origin: stamp.origin, type: stamp.type, project: project, isArchived: isArchived, // #33: the remembered Micro.blog draft URL — // one flat key, read leniently like the rest. // #33 audit: imported frontmatter rides // verbatim, so the read-back gates on the same // format guard the decode applies — a hostile // value never pre-arms the publish sheet. micropubURL: frontmatter["micropub_url"].flatMap { Micropub.trustworthyURL($0) ? $0 : nil }, // #32/#180 read-back gate: the named immutable pair // (origin writer, type post) — NOT pass_state, which // legitimately advances after the capture. `stats_*` // keys can arrive by import (external YAML rides // verbatim), so an imported ai piece or outline // carrying hand-stamped keys still never renders; // a migrated writer piece keeps its real arc. firstDraftStats: PostFrontmatter.isUnaidedFirstDraftPair(frontmatter) ? Post.FirstDraftStats(frontmatter: frontmatter) : nil, ) } /// 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" } } /// #143 (OPT-F3): parse memo for `Post.scan`. A post.md whose PATH, /// mtime, and size are unchanged since the last parse is not re-read — /// the prior `Post` is reused — so a watcher burst (the autosave echo) /// costs the readdir walk plus the changed files, not O(library bytes). /// Path-keyed: a moved piece always re-parses and re-derives its /// project/isArchived from disk. Held by `PostsModel` across rescans. /// /// ponytail: mtime+size is the invalidation key (make/rsync class) — a /// same-size rewrite inside APFS timestamp granularity could serve a stale /// parse; key on a content hash if that ever bites. Entries for vanished /// paths are never consulted again and merely linger (bytes each). /// final nonisolated class PostScanCache: @unchecked Sendable { private struct Entry { let modified: Date let size: Int let post: Post } private var entries: [String: Entry] = [:] private let lock = NSLock() /// Hit/miss observables (a miss = one disk read + parse); test-facing. private var hitCount = 0 private var missCount = 0 var hits: Int { lock.lock(); defer { lock.unlock() } return hitCount } var misses: Int { lock.lock(); defer { lock.unlock() } return missCount } /// The cached parse when (path, mtime, size) all match the caller's /// pre-captured stamp; nil = re-read. No I/O here — the stamp travels /// with the scan loop's consult and store alike. func cachedPost(at url: URL, stamp: Stamp) -> Post? { lock.lock(); defer { lock.unlock() } guard let entry = entries[url.path], stamp.modified == entry.modified, stamp.size == entry.size else { return nil } hitCount += 1 return entry.post } /// Remember a fresh parse under the caller's PRE-READ stamp; one store /// = one counted miss (disk read). Overlapping rescans can interleave: /// a store that stamped the file itself could key a pre-rewrite parse /// as the post-rewrite version and pin stale content until the next /// write. Keying the pre-read stamp instead makes a mid-flight rewrite /// mismatch on the next scan — a miss, self-healed. func store(_ post: Post, at url: URL, stamp: Stamp) { lock.lock(); defer { lock.unlock() } missCount += 1 guard let modified = stamp.modified, let size = stamp.size else { return } entries[url.path] = Entry(modified: modified, size: size, post: post) } /// A file's (mtime, size) at one moment — the invalidation key. struct Stamp { let modified: Date? let size: Int? } /// Capture the stamp for a file (nils when it can't be read — the /// store then caches nothing, a conservative miss). static func stamp(at url: URL) -> Stamp { let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey]) return Stamp(modified: values?.contentModificationDate, size: values?.fileSize) } } 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) } }