Files
museion/Museion/PostLibrary.swift
T
AlexKucera 530f852f75
CI / ci (push) Canceled after 0s
feat(workspace): land Post lifecycle (S1.1)
Posts become writable end to end per the #18 map decisions:
New Post holds an in-memory draft (folder appears only on first
save), first save stamps the flat frontmatter block the #17
reader already parses (pass_state First Draft, origin writer,
immutable after stamping), and the Post ID is the Title slug with
case-insensitive collision suffixes. Explicit Rename retitles the
# Title line and moves the folder (post.md stays); Delete goes to
Trash. A recursive FSEvents stream keeps the list mirroring
posts/ — external Finder edits included.

Editor is a deliberate TextEditor stub; #19's TextKit2 editor
replaces it in place while the lifecycle machinery below the view
survives the swap.

Two review rounds (standards/spec + finish-audit fanout) fixed:
watcher start-order bug, writeNew clobber race, overwrite
resurrecting vanished posts with reset origin, rename destroying
non-heading first lines, draft hijacking the editor, debounce
starvation under churn.

Tests: 75/75 (17 new). Closes #18.
2026-10-03 13:34:00 +02:00

110 lines
4.2 KiB
Swift

//
// PostLibrary.swift
// Museion
//
// #17 (S1.1): the Posts list mirrors what is on disk under the Museion Home.
//
import Foundation
/// One Post on disk: `<home>/posts/<id>/post.md` (ADR-0004 shape).
nonisolated struct Post: Identifiable, Equatable {
/// The post folder's name — the Post's durable identity (CONTEXT.md).
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
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
}
/// Reads every `posts/<id>/post.md` into Posts (sorted by title, Finder order).
/// Read-only for #17 — create/rename/delete round-trips are #18. Symlinks and
/// hidden dirs are skipped; folders without `post.md` (lazy) aren't Posts;
/// a malformed folder can't crash the list.
static func scan(home: URL) -> [Post] {
let postsURL = home.appendingPathComponent("posts", isDirectory: true)
guard let entries = try? FileManager.default.contentsOfDirectory(
at: postsURL,
includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
) else { return [] }
var posts: [Post] = []
for dir in entries {
let values = try? dir.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard values?.isDirectory ?? false, !(values?.isSymbolicLink ?? false),
!dir.lastPathComponent.hasPrefix(".") else { continue }
let fileURL = dir.appendingPathComponent("post.md")
guard let text = try? String(contentsOf: fileURL, encoding: .utf8) 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,
),
)
}
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 {
trimmingCharacters(in: .whitespacesAndNewlines)
}
}