Files
museion/Museion/PostStore.swift
T
AlexKucera 46e87e678c fix(editor): editor owns file drops on macOS 27.2
Dropping an image file on the prose editor pasted the file path
instead of ingesting it (#141 follow-up, unticketed; dogfood on
macOS 27.2.1). #141 was field-verified on 27.0.1, where the
window-level SwiftUI dropDestination starved every deeper
destination; 27.2 routes a drag to the deepest destination, and a
live NSTextView registers itself for drag types, so its stock
performDragOperation pasted the path and the window destination
never fired — the same for a markdown file dropped on the editor.

The editor text views now share a FileDropTextView base that owns
the drops landing on them: URL-bearing drags route (never super) —
the prose editor through the one new AppGateState.routeFileDrop
(Cold Turkey guard, markdown → guest, anything else → ingestDrop),
which the window destination also uses for drops landing outside
the editor; the outline rows bounce; text-only drags keep the stock
drop; the pasteboard probe is memoized per changeCount. A web URL
refuses with the type strip, a vanished file refuses as missing.

+9 tests (a real NSDraggingInfo mock drives the overrides; the
router's guest/lock/ingest branches pinned), all flip-verified.
Finish-audit: three reviewers; the text-drag regression and the
outline rows' identical exposure fixed, two pre-existing ceilings
deferred in the devlog. Rail 729/729, swiftformat 0/153, swiftlint 0.
2026-12-03 16:36:47 +01:00

825 lines
39 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// PostStore.swift
// Museion
//
// #18 (S1.1): the write side of the Post lifecycle — slug naming, lazy folder
// materialization on first write, frontmatter stamping (#59), Explicit Rename
// = retitle + move (#60), Trash delete. Pure disk operations, no UI state.
// #107 (ADR-0012): pieces live under projects/<project>/<slug>/ (archive/
// mirrors the shape); the slug namespace is global across both roots.
// #108: project moves and archive/restore are plain folder moves between
// those roots — post.md bytes are never rewritten.
//
import Foundation
import UniformTypeIdentifiers
/// Write-side Post lifecycle (#18 map decisions #59/#60). One canonical write
/// path: every file that leaves here carries the flat frontmatter block the
/// #17 reader already parses. #22: import copies external markdown in (#94/#95).
/// #107: the Piece ID is the durable identity — write paths resolve the folder
/// from the id by searching both roots; nothing threads (project, id) around.
nonisolated enum PostStore {
/// #96: .md/.markdown only — every entry point (Open panel, Import panel,
/// drag-drop filter) shares this list.
static let openableTypes: [UTType] = markdownExtensions.compactMap { UTType(filenameExtension: $0) }
/// #91: drag-drop filter — local file URLs only (a dragged web link is
/// not a document; `String(contentsOf:)` would fetch it), extension
/// checked case-insensitively (UTType conformance on the pasteboard is
/// unreliable).
static func isMarkdown(_ url: URL) -> Bool {
url.isFileURL && markdownExtensions.contains(url.pathExtension.lowercased())
}
private static let markdownExtensions = ["md", "markdown"]
/// ADR-0012 id→folder resolution: the id is globally unique, so the
/// folder is found by searching the container roots in order (projects/
/// before archive/, project names sorted for determinism). nil when the
/// id lives under neither root.
// ponytail: linear walk of projects/ then archive/ per call — one
// debounced flush = 2–3 walks (overwrite + sidecar). Fine at human
// project counts; cache id→folder if it ever measures hot.
// Audit: project-level guards mirror scan's skips (hidden dirs,
// symlinks) so write paths and the library agree on what exists —
// a piece in a dot-project must never shadow a visible one. The
// piece-level check resolves symlinks (only a stale-selection race
// reaches one — scan never lists symlinked pieces).
static func folder(of id: String, home: URL) -> URL? {
for root in Post.containerRoots {
let rootURL = home.appendingPathComponent(root, isDirectory: true)
guard let projects = try? FileManager.default.contentsOfDirectory(
at: rootURL,
includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
) else { continue }
for project in projects.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
let values = try? project.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard values?.isDirectory ?? false, !(values?.isSymbolicLink ?? false),
!project.lastPathComponent.hasPrefix(".") else { continue }
let dir = rootURL.appendingPathComponent(project.lastPathComponent, isDirectory: true)
.appendingPathComponent(id, isDirectory: true)
var isDir: ObjCBool = true
if FileManager.default.fileExists(atPath: dir.path, isDirectory: &isDir), isDir.boolValue {
return dir
}
}
}
return nil
}
/// The shared slug function (#60): lowercase, diacritic-fold, strip
/// punctuation, whitespace runs → single hyphens, keep CJK, cap 80.
/// A slugless title (blank, punctuation-only) is `untitled` (CONTEXT.md).
static func slug(from title: String) -> String {
let folded = title
.folding(options: .diacriticInsensitive, locale: Locale(identifier: "en_US_POSIX"))
.lowercased()
var result = ""
var lastWasHyphen = true // swallows leading hyphens
for scalar in folded.unicodeScalars {
if CharacterSet.whitespacesAndNewlines.contains(scalar) {
if !lastWasHyphen {
result.append("-"); lastWasHyphen = true
}
} else if CharacterSet.alphanumerics.contains(scalar) {
result.unicodeScalars.append(scalar)
lastWasHyphen = false
}
// Everything else (punctuation, symbols) is dropped.
}
result = String(result.prefix(80))
while result.hasSuffix("-") {
result.removeLast()
}
return result.isEmpty ? "untitled" : result
}
/// First free slug for a title: base slug, then `-2`, `-3`… (#60), over
/// the GLOBAL namespace (#107) — every entry under `projects/*/` and
/// `archive/*/` (an archived slug must never be reused; restore would
/// collide). Case-insensitive existence check (#60), independent of the
/// volume's case sensitivity. `excluding` skips a folder (the renamer's
/// own, still present).
// ponytail: O(all pieces) per call — enumerates every project's entries
// to build the taken set. Fine at human scale (new-piece / rename only);
// index the namespace if it ever measures hot.
static func availableSlug(for title: String, home: URL, excluding ownID: String? = nil) -> String {
var taken = Set<String>()
for root in Post.containerRoots {
let rootURL = home.appendingPathComponent(root, isDirectory: true)
guard let projects = try? FileManager.default.contentsOfDirectory(atPath: rootURL.path) else { continue }
for project in projects {
let entries = (try? FileManager.default.contentsOfDirectory(
atPath: rootURL.appendingPathComponent(project, isDirectory: true).path,
)) ?? []
for entry in entries {
// #108 audit: all slug-space comparisons through `folded` —
// NFC + lowercase. Swift's == and Set hashing already fold
// canonical equivalence, so this is the explicit, tested
// contract rather than a behavior change; the load-bearing
// part is the lowercase (APFS is case-insensitive).
taken.insert(folded(entry))
}
}
}
let base = slug(from: title) // as-produced — the folder matches the title's bytes
let key = folded(base)
if !taken.contains(key) || key == ownID.flatMap(folded) {
return base
}
var suffix = 2
while taken.contains(folded("\(base)-\(suffix)")) {
suffix += 1
}
return "\(base)-\(suffix)"
}
/// #108 audit: the canonical compare key — case-folded + Unicode-normalization
/// folded (NFC). APFS is normalization-insensitive, so two byte-sequences can
/// be one folder; every name-uniqueness check must compare through this.
private static func folded(_ name: String) -> String {
name.precomposedStringWithCanonicalMapping.lowercased()
}
/// First write (#62): lazily materialize `projects/<project>/<slug>/post.md`
/// with the #59 block stamped (plus `type`, #107). Pass State First
/// Draft, origin writer — the only values #18 writes; the folder appears
/// here, never on New Post. #109: `type` lets the outliner birth outline
/// pieces; prose pieces keep the default. #30 (S2.7): `origin` lets a
/// session-born Post stamp `origin: ai` (never stats-eligible); the
/// default stays `.writer`, so every existing caller compiles unchanged.
static func writeNew(
body: String, project: String = Post.defaultProject, type: Post.ContentType = .post,
origin: Post.Origin = .writer, home: URL,
) throws -> Post {
try materialize(
text: PostFrontmatter.stamped(body: body, passState: .firstDraft, origin: origin, type: type),
title: Post.title(of: body),
origin: origin,
project: project,
type: type,
home: home,
)
}
/// #22/#94/#95: import one external markdown file as a Post — copy, never
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
/// verbatim with `type: post`, `pass_state: First Draft` and
/// `origin: <chosen>` set / overwritten (our three keys win); id = Title
/// slug at import; collisions `-2`/`-3`… (#60 machinery); a fresh copy,
/// no mtime preservation (#96).
static func importFile(at url: URL, origin: Post.Origin, project: String = Post.defaultProject, home: URL) throws -> Post {
var raw = try String(contentsOf: url, encoding: .utf8)
// ponytail: normalize line endings + strip BOM at the import boundary —
// in Swift a CRLF pair is ONE grapheme, so every "\n" split in the
// corpus machinery sees a CRLF file as a single line (mangled id and
// title); true CRLF preservation would need grapheme-aware joins
// everywhere. Lone-CR (pre-OSX) files still degrade to `untitled` —
// ceiling named, add a "\r" pass if one ever shows up.
if raw.hasPrefix("\u{FEFF}") {
raw.removeFirst()
}
raw = raw.replacingOccurrences(of: "\r\n", with: "\n")
let text = PostFrontmatter.mergingImport(text: raw, origin: origin)
return try materialize(
text: text,
title: Post.title(of: PostFrontmatter.split(raw).body),
origin: origin,
project: project,
type: .post, // #95: our keys win — external `type: outline` still imports as post
home: home,
)
}
/// #62/#95: lazily materialize `projects/<project>/<slug>/post.md` with
/// the given (already stamped/merged) text. Shared by `writeNew` and
/// `importFile` — one lazy-folder path, TOCTOU-guarded, never clobbering.
/// Returns the created Post (id, title, First Draft, origin, type).
// swiftlint:disable:next function_parameter_count
private static func materialize(
text: String, title: String, origin: Post.Origin, project: String, type: Post.ContentType, home: URL,
) throws -> Post {
let projectsRoot = home.appendingPathComponent("projects", isDirectory: true)
try FileManager.default.createDirectory(
at: projectsRoot.appendingPathComponent(project, isDirectory: true),
withIntermediateDirectories: true,
)
let id = availableSlug(for: title, home: home)
let dir = projectsRoot.appendingPathComponent(project, isDirectory: true)
.appendingPathComponent(id, isDirectory: true)
let fileURL = dir.appendingPathComponent("post.md")
// TOCTOU guard (audit): a folder appearing between slug pick and write
// must fail loudly, never clobber another post's content.
guard !FileManager.default.fileExists(atPath: fileURL.path) else {
throw CocoaError(.fileWriteFileExists)
}
do {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try text.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
// Don't strand an empty slug folder on partial failure (it would
// occupy the slug and push the retry to -2).
if !FileManager.default.fileExists(atPath: fileURL.path) {
try? FileManager.default.removeItem(at: dir)
}
throw error
}
return Post(id: id, title: title, passState: .firstDraft, origin: origin, type: type, project: project, isArchived: false)
}
/// Save an existing Post: body-only text in, file normalized out. The
/// file's present `pass_state`/`origin`/`type` are preserved (origin
/// immutable, CONTEXT.md; bare corpus posts normalize on save, #59).
/// **#31 audit fix: blocked files update the three owned keys IN PLACE
/// (PostFrontmatter.updating) and swap in the caller's body — the old
/// stamped() round-trip rebuilt the block from three parsed fields,
/// erasing the first-draft stats captured at the pass invocation and
/// any foreign frontmatter on every editor save.** A vanished post
/// throws — `writeNew` is the only creator; saving must never
/// resurrect a deleted post with reset metadata.
static func overwrite(id: String, body: String, home: URL) throws {
let piece = try existingStamp(id: id, home: home)
let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8)
// #180: the codec's postures — bare files take the fresh stamp,
// blocked files update the owned keys in place (the update walk)
// and swap in the caller's body.
let text = PostFrontmatter.split(raw).block.isEmpty
? PostFrontmatter.stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type)
: PostFrontmatter.split(PostFrontmatter.updating(text: raw, with: PostFrontmatter.ownedKeys(
type: piece.type, passState: piece.passState, origin: piece.origin,
))).block + body
try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
/// #114: the shared read behind `overwrite` and `convert` — resolve the
/// folder, read the file (vanished → throw: a write never resurrects,
/// #18), derive the preserved stamp values. The caller stamps its own
/// type and body.
// swiftlint:disable:next large_tuple
private static func existingStamp(id: String, home: URL) throws -> (
dir: URL, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType, body: String,
) {
guard let dir = folder(of: id, home: home),
let existing = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
throw CocoaError(.fileReadNoSuchFile)
}
let matter = PostFrontmatter.parse(existing)
let stamp = PostFrontmatter.decoded(matter)
return (
dir,
stamp.passState,
stamp.origin,
stamp.type,
PostFrontmatter.split(existing).body,
)
}
/// Body text (frontmatter stripped) for editing; nil when unreadable.
/// Bare corpus posts return whole — they normalize on save (#59).
static func readBody(id: String, home: URL) -> String? {
guard let dir = folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return nil }
return PostFrontmatter.split(text).body
}
/// #114 (S4): Convert to Post — the one-time in-place transform. The
/// file's own `pass_state`/`origin` are kept (the stamp re-derives
/// them from the file, same as overwrite), id and folder never move,
/// `type` flips to `post`, the body transforms once. Ladder = the
/// headings mapping; verbatim = body unchanged. One-way in v1.
static func convert(id: String, headingsLadder: Bool, home: URL) throws {
let piece = try existingStamp(id: id, home: home)
let transformed = headingsLadder ? OutlineTree.headingsLadderBody(piece.body) : piece.body
try PostFrontmatter.stamped(body: transformed, passState: piece.passState, origin: piece.origin, type: .post)
.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
/// Explicit Rename (#60): rewrite the `# Title` line as the first
/// non-empty body line, then move the folder to the new slug — within
/// the SAME parent (ADR-0012: the piece stays in its project, archived
/// stays archived). The file stays `post.md`; a title that slugs to the
/// current id only retitles.
static func rename(_ post: Post, to title: String, home: URL) throws -> Post {
guard let dir = folder(of: post.id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
let fileURL = dir.appendingPathComponent("post.md")
let text = try String(contentsOf: fileURL, encoding: .utf8)
let (block, body) = PostFrontmatter.split(text)
try (block + replacingTitleLine(of: body, with: "# \(title)"))
.write(to: fileURL, atomically: true, encoding: .utf8)
// availableSlug excludes our own (still-present) folder: a retitle
// whose slug matches the current id (any case) keeps the clean name
// (no -2 against ourselves); a genuine collision lands on -2 (#60).
let newID = availableSlug(for: title, home: home, excluding: post.id)
guard newID != post.id else {
return Post(id: post.id, title: title, passState: post.passState, origin: post.origin,
type: post.type, project: post.project, isArchived: post.isArchived)
}
try FileManager.default.moveItem(at: dir, to: dir.deletingLastPathComponent().appendingPathComponent(newID, isDirectory: true))
return Post(id: newID, title: title, passState: post.passState, origin: post.origin,
type: post.type, project: post.project, isArchived: post.isArchived)
}
/// Delete = move the Post folder to the Trash (recoverable in Finder) —
/// never permanent removal (#18 AC).
static func trash(_ post: Post, home: URL) throws {
guard let dir = folder(of: post.id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
var trashed: NSURL?
try FileManager.default.trashItem(at: dir, resultingItemURL: &trashed)
}
// MARK: Project moves & archive (#108)
/// #108: move an active piece to another project — projects/<old>/<id> →
/// projects/<project>/<id>/ (folder move, post.md untouched, frontmatter
/// preserved). Destination project folder lazily created. Throws when the
/// piece is archived (restore is the archived move) or unresolvable, or
/// the destination already exists (disk anomaly — never clobber). A move
/// to the piece's own project is a no-op (the picker shows it, the writer
/// might confirm it — not an error). The current project derives from the
/// freshly resolved folder, not the scan snapshot (a Finder-side move
/// between scan and click must not misfile the piece).
static func move(_ post: Post, to project: String, home: URL) throws {
guard let dir = folder(of: post.id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
// #108 audit 2: the refusal derives from the resolved path, not the
// scan snapshot — a stale isArchived=false must not smuggle an
// archived piece back into projects/ (restore is the archived move).
let projectDir = dir.deletingLastPathComponent()
guard projectDir.deletingLastPathComponent().lastPathComponent != "archive" else {
throw CocoaError(.featureUnsupported)
}
let target = try validatedProject(project)
guard folded(target) != folded(projectDir.lastPathComponent) else { return }
try relocate(dir, id: post.id, toRoot: "projects", project: target, home: home)
}
/// #108: archive one piece — projects/<p>/<id> → archive/<p>/<id>/ (folder
/// move; lazily creates archive/<p>/). The project derives from the
/// freshly resolved folder (not the scan snapshot).
static func archive(_ post: Post, home: URL) throws {
guard let dir = folder(of: post.id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
try relocate(dir, id: post.id, toRoot: "archive",
project: dir.deletingLastPathComponent().lastPathComponent, home: home)
}
/// #108: put an archived piece back — archive/<p>/<id> → projects/<p>/<id>/.
static func restore(_ post: Post, home: URL) throws {
guard let dir = folder(of: post.id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
try relocate(dir, id: post.id, toRoot: "projects",
project: dir.deletingLastPathComponent().lastPathComponent, home: home)
}
/// #108: unarchive a whole project — archive/<name>/ → projects/<name>/.
/// When projects/<name>/ already exists, merge child-by-child instead of
/// failing (ids are globally unique, so real collisions are disk anomalies
/// that throw honestly). The emptied archive/<name>/ is removed.
static func unarchiveProject(_ name: String, home: URL) throws {
var isDir: ObjCBool = false
let source = home.appendingPathComponent("archive", isDirectory: true)
.appendingPathComponent(name, isDirectory: true)
guard FileManager.default.fileExists(atPath: source.path, isDirectory: &isDir), isDir.boolValue else {
throw CocoaError(.fileReadNoSuchFile)
}
// One code path for both cases: dest created (or already there), every
// child moved, the emptied source removed. moveItem throws on an
// existing destination child — a duplicate id from a Finder copy
// surfaces loudly instead of being clobbered mid-merge.
let dest = home.appendingPathComponent("projects", isDirectory: true)
.appendingPathComponent(name, isDirectory: true)
try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: true)
for child in try FileManager.default.contentsOfDirectory(atPath: source.path) {
// #108 audit: Finder metadata (.DS_Store) browsed into both halves
// would collide forever — dot-entries are invisible to the app
// everywhere else (scan, folder(of:)); skip them here too.
guard !child.hasPrefix(".") else { continue }
try FileManager.default.moveItem(
atPath: source.appendingPathComponent(child).path,
toPath: dest.appendingPathComponent(child).path,
)
}
// #108 audit 2: removeItem is permanent — only take the source down
// when the loop emptied it. Dot-entries skipped above (and any hidden
// user folder, .git, .research) stay where they are instead of being
// silently destroyed with the folder.
if (try? FileManager.default.contentsOfDirectory(atPath: source.path))?.isEmpty != false {
try FileManager.default.removeItem(at: source)
}
}
/// #108: materialize an empty projects/<name>/. Throws on a name that is
/// empty after trimming, contains "/", starts with ".", or collides with an
/// existing project under projects/ (case-insensitive, matching the volume).
static func createProject(named name: String, home: URL) throws {
let project = try validatedProject(name)
let projectsRoot = home.appendingPathComponent("projects", isDirectory: true)
// Case-insensitive (#60's rule for slugs, same reason): APFS is
// case-insensitive by default — "Foo" next to "foo" is one folder on
// disk but two projects in the UI. Independent of the volume's actual
// sensitivity, same as availableSlug.
let existing = (try? FileManager.default.contentsOfDirectory(atPath: projectsRoot.path)) ?? []
// #108 audit: fold Unicode normalization before the case-insensitive
// compare — NFC vs NFD "café" reads identical but makes two folders
// on normalization-insensitive APFS (and two indistinguishable
// sections). availableSlug folds through the same `folded` key.
guard !existing.contains(where: { folded($0) == folded(project) }) else {
throw CocoaError(.fileWriteFileExists)
}
try FileManager.default.createDirectory(
at: projectsRoot.appendingPathComponent(project, isDirectory: true),
withIntermediateDirectories: true,
)
}
/// The shared #108 relocation: resolve once, then a plain FileManager move
/// of the whole piece folder into <root>/<project>/<id>/ — lazy parent,
/// never clobbering, post.md bytes untouched.
private static func relocate(
_ dir: URL, id: String, toRoot root: String, project: String, home: URL,
) throws {
let parent = home.appendingPathComponent(root, isDirectory: true)
.appendingPathComponent(project, isDirectory: true)
try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
let dest = parent.appendingPathComponent(id, isDirectory: true)
// ids are globally unique — an existing destination is a disk anomaly
// (duplicate id from a Finder copy) or a self-move; fail loudly.
guard !FileManager.default.fileExists(atPath: dest.path) else {
throw CocoaError(.fileWriteFileExists)
}
try FileManager.default.moveItem(at: dir, to: dest)
}
/// #108: a project name becomes a folder name — trim, then reject empty,
/// path separators (traversal), hidden names (scan skips dot-dirs), and
/// ":"/control characters (Finder displays ":" as "/" — a legal APFS name
/// that round-trips confusingly).
private static func validatedProject(_ name: String) throws -> String {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, !trimmed.contains("/"), !trimmed.hasPrefix("."),
!trimmed.contains(":"),
!trimmed.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
else {
throw CocoaError(.fileWriteInvalidFileName)
}
return trimmed
}
/// Replace the body's Title heading with `line`; a body whose first
/// non-empty line is NOT a heading keeps that line (it's content) and
/// gets the heading inserted above it. An empty body becomes just `line`.
private static func replacingTitleLine(of body: String, with line: String) -> String {
var lines = body.split(separator: "\n", omittingEmptySubsequences: false)
if let titleIndex = lines.firstIndex(where: { !$0.trimmed().isEmpty }) {
if lines[titleIndex].trimmed().hasPrefix("#") {
lines[titleIndex] = Substring(line)
} else {
lines.insert(Substring(line), at: titleIndex)
}
} else {
lines = [Substring(line)]
}
return lines.joined(separator: "\n")
}
}
// MARK: Pass substrate (#24)
/// #24 (S3.1): the pass write side — pre-pass snapshots and monotonic
/// Pass State advancement. Same file as the enum: `private` members
/// (folder/existingStamp/stamped) stay reachable at file scope.
nonisolated extension PostStore {
/// #24 (S3.1): pre-pass snapshot — the body exactly as it stood when
/// the pass was invoked, written verbatim to
/// `<piece>/passes/<kind.snapshotFileName>`. Fixed filename per pass
/// type: a re-run overwrites, so the LATEST pre-pass body per type
/// survives (running a pass never destroys text). Body only, no
/// frontmatter — it is the writer's diff anchor against post.md. A
/// vanished piece throws (a snapshot never resurrects, #18).
static func snapshotPass(id: String, kind: PassKind, body: String, home: URL) throws {
guard let dir = folder(of: id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
let passes = dir.appendingPathComponent("passes", isDirectory: true)
try FileManager.default.createDirectory(at: passes, withIntermediateDirectories: true)
try body.write(to: passes.appendingPathComponent(kind.snapshotFileName), atomically: true, encoding: .utf8)
}
/// #122: the Blind Read's comparison base — the newest pre-pass
/// snapshot on disk, either pass kind (a re-run overwrites in place,
/// so the newest file IS the latest Pass-start). Nil when no pass ever
/// ran over the piece. Read-only; the Blind Read records nothing.
static func latestPassSnapshot(id: String, home: URL) -> (kind: PassKind, body: String)? {
guard let dir = folder(of: id, home: home) else { return nil }
let passesDir = dir.appendingPathComponent("passes")
var newest: (kind: PassKind, date: Date)?
for kind in PassKind.allCases {
let url = passesDir.appendingPathComponent(kind.snapshotFileName)
guard let date = try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]
as? Date else { continue }
if newest == nil || date > newest!.date {
newest = (kind, date)
}
}
guard let newest else { return nil }
// ponytail: read-after-stat race is a stale base at worst — the
// snapshot only changes at a pass invocation, never mid-read.
guard let body = try? String(
contentsOf: passesDir.appendingPathComponent(newest.kind.snapshotFileName),
encoding: .utf8,
) else { return nil }
return (kind: newest.kind, body: body)
}
/// #24 (S3.1): advance `pass_state` when a pass completes. Monotonic:
/// the new state is the higher of the file's current state and the
/// pass's doneState — passes run in ANY order, so a Pass 1 completing
/// on a Pass-2 Done piece never regresses it. **#31 (S5.1): the state
/// update is an IN-PLACE key stamp (PostFrontmatter.updating), not the
/// existingStamp→stamped block rewrite — the rewrite carried only
/// type/pass_state/origin and silently erased the first-draft stats
/// captured at the invocation (and any foreign frontmatter).** Bare
/// posts (no block) still normalize through the full #59 stamp.
/// Returns the state now stamped. A vanished piece throws.
static func advancePassState(id: String, kind: PassKind, home: URL) throws -> Post.PassState {
let piece = try existingStamp(id: id, home: home)
let advanced = higherState(piece.passState, kind.doneState)
let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8)
let text = PostFrontmatter.split(raw).block.isEmpty
? PostFrontmatter.stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
: PostFrontmatter.updating(text: raw, with: [("pass_state", advanced.rawValue)])
try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
// The decay clock counts completed passes per content type (#27).
// try?: a failed clock bump must never fail a completed pass, and
// a lagging clock only delays resurfacing (safe direction).
try? LearningDecay.recordPass(home: home, type: piece.type)
return advanced
}
/// #24: Pass State maturity order — First Draft < Pass-1 Done <
/// Pass-2 Done. Private: state advancement is the only consumer (making
/// `Post.PassState` Comparable would widen the public surface for it).
private static func higherState(_ current: Post.PassState, _ completed: Post.PassState) -> Post.PassState {
func rank(_ state: Post.PassState) -> Int {
switch state {
case .firstDraft: 0
case .pass1Done: 1
case .pass2Done: 2
}
}
return rank(current) >= rank(completed) ? current : completed
}
}
// MARK: Research notes (#29)
/// #29 (S8.2): the keep write — the writer's explicit act. One plain
/// markdown Research Note with provenance per keep, landed in
/// `<piece>/research/`; the candidates themselves wait in their session
/// and are never persisted by the tool rail (CONTEXT.md). Same-file
/// extension like the pass substrate: the enum's private members stay
/// reachable at file scope.
nonisolated extension PostStore {
/// Write ONE kept research note. `piecePath` is the piece folder or its
/// post.md — resolved through the ONE id→folder resolver so the write
/// anchors to THIS Home (a garbage path fails the id lookup honestly).
/// Returns the landed file NAME inside `<piece>/research/`.
/// `quote`/`note` arrive as "" when the candidate carried none; empty
/// sections are omitted. A vanished piece throws (a keep never
/// resurrects, #18's rule).
// swiftlint:disable:next function_parameter_count
static func writeResearchNote(
piecePath: String, title: String, url: String, quote: String, note: String, home: URL,
) throws -> String {
let given = URL(fileURLWithPath: piecePath)
let pieceDir = given.lastPathComponent == "post.md" ? given.deletingLastPathComponent() : given
guard let dir = folder(of: pieceDir.lastPathComponent, home: home) else {
throw FixCardStore.CardError(message: "piece not found: \(piecePath)")
}
let research = dir.appendingPathComponent("research", isDirectory: true)
// Security (promote's posture): a pre-planted symlinked research/
// must not turn the keep into a write-outside-Home primitive —
// refuse before any write.
let values = try? research.resourceValues(forKeys: [.isSymbolicLinkKey])
if values?.isSymbolicLink == true {
throw FixCardStore.CardError(message: "research path is a symlink: \(research.path)")
}
try FileManager.default.createDirectory(at: research, withIntermediateDirectories: true)
let day = FixCardStore.formatted(Date(), "yyyyMMdd")
// Flat single-line structural fields (Learning-file precedent): a
// newline in a hostile title/url must not break the heading or the
// frontmatter shape. Note/quote stay verbatim — they are content.
func flat(_ value: String) -> String {
value.components(separatedBy: .newlines).joined(separator: " ")
}
var body = "# \(flat(title))"
if !note.isEmpty {
body += "\n\n\(note)"
}
if !quote.isEmpty {
body += "\n\n> \(quote)"
}
let markdown = "---\nsource: \(flat(url))\nkept: \(day)\n---\n\n\(body)\n"
let name = FixCardStore.uniqueFile(research, base: "\(day)-\(slug(from: title))", ext: "md")
try markdown.write(to: research.appendingPathComponent(name), atomically: true, encoding: .utf8)
return name
}
}
// MARK: First-draft stats capture (#31)
/// #31 (S5.1): the unaided-first-draft capture write side (CONTEXT.md
/// 'Unaided First Draft'). Same file as the pass substrate: the enum's
/// private helpers (folder(of:)) stay reachable at file scope.
nonisolated extension PostStore {
/// Compute the four `DraftStats` over `body` and stamp them into the
/// piece's frontmatter — runPass fires this at the invocation, before
/// the prompt crosses the bridge. Eligibility is decided by the FILE's
/// own frontmatter alone (same lenient defaults as Post.scan — a bare
/// legacy post qualifies): origin writer, Pass State First Draft, type
/// post. Not eligible → false, file untouched. The stamp is in place
/// (PostFrontmatter.updating): every non-stats line byte-identical, so a
/// re-invocation while still First Draft overwrites — latest draft
/// state wins. Any read/write failure → false: a failed capture must
/// never fail the pass (the decay-clock posture).
@discardableResult
static func captureFirstDraftStats(id: String, body: String, home: URL) -> Bool {
guard let dir = folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
// #180: the named capture predicate — pair ∧ First Draft, leniently
// decoded (a bare legacy post qualifies).
guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
let stats = DraftStats.compute(body: body)
let stamped = PostFrontmatter.updating(text: text, with: [
("stats_captured", FixCardStore.formatted(Date(), "yyyy-MM-dd'T'HH:mm:ss")), // lexically sortable
("stats_burstiness", String(format: "%.3f", stats.burstiness)),
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)),
("stats_trigram_repetition", String(format: "%.3f", stats.trigramRepetition)),
])
guard (try? stamped.write(
to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8,
)) != nil else { return false }
return true
}
// MARK: #33 (S6.1) — the remembered Micro.blog draft URL
/// Stamp `micropub_url` in place on a successful draft send — the
/// publish step's target (a frontmatter-only change: the body and
/// every other key stay byte-identical, so the open session's
/// readBody-based echo check never fires). A vanished piece throws
/// (write-never-resurrects, `writeNew` is the only creator).
static func stampMicropubURL(id: String, url: String, home: URL) throws {
guard let dir = folder(of: id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
let file = dir.appendingPathComponent("post.md")
let raw = try String(contentsOf: file, encoding: .utf8)
try PostFrontmatter.updating(text: raw, with: [("micropub_url", url)])
.write(to: file, atomically: true, encoding: .utf8)
}
}
// MARK: Cursor-state sidecar (#66)
/// #66: the sidecar group, moved to a same-file extension at the enum's
/// type-body ceiling (#147) — the PostsModel treatment. Same file as the
/// enum: `private` members stay reachable at file scope.
nonisolated extension PostStore {
/// Cursor state for one post: selection + scroll, `.museion-state.json`
/// in the post folder — Finder-invisible, human-diffable, dies with the
/// folder on Trash. Drafts skip it (#62).
struct CursorState: Codable, Equatable {
var selectionLocation: Int = 0
var selectionLength: Int = 0
var scrollOffset: Double = 0
}
private static func stateURL(id: String, home: URL) -> URL? {
folder(of: id, home: home)?.appendingPathComponent(".museion-state.json")
}
/// Read the sidecar; nil when absent or corrupt (a fresh cursor is fine).
static func readCursor(id: String, home: URL) -> CursorState? {
guard let url = stateURL(id: id, home: home),
let data = try? Data(contentsOf: url)
else { return nil }
return try? JSONDecoder().decode(CursorState.self, from: data)
}
/// Write the sidecar. Best-effort by design — a failed cursor write must
/// never read as a failed content save, so failures are swallowed here.
static func writeCursor(_ state: CursorState, id: String, home: URL) {
guard let url = stateURL(id: id, home: home),
let data = try? JSONEncoder().encode(state)
else { return }
try? data.write(to: url, options: .atomic)
}
}
// MARK: - #141 Illustration ingest
/// #141's refusal reasons — the drop surface shows `localizedDescription`
/// as its visible feedback (CardError/WriteError voice).
struct IngestError: LocalizedError {
let message: String
var errorDescription: String? {
message
}
static func notPublishable(_ name: String) -> IngestError {
IngestError(message: "“\(name.prefix(40))” isn’t publishable — PNG, JPEG, GIF, WebP, or SVG.")
}
/// A dropped symlink (e.g. an unzipped archive entry) — copyItem would
/// land the LINK itself in assets/; the #34 rail then refuses the send.
static func isLink(_ name: String) -> IngestError {
IngestError(message: "“\(name.prefix(40))” is a link, not an image file.")
}
/// A Finder folder with an image extension — the extension gate
/// alone would copyItem a whole directory into assets/.
static func isFolder(_ name: String) -> IngestError {
IngestError(message: "“\(name.prefix(40))” is a folder, not an image.")
}
/// A file the drag named but the disk can no longer stat — moved or
/// deleted between drag and drop (or a URL that never was a file).
static func missing(_ name: String) -> IngestError {
IngestError(message: "“\(name.prefix(40))” couldn’t be read — it may have moved since the drag began.")
}
/// assets/ exists as a symlink or a file — never write through it
/// (research/promote posture: the #34 rail would refuse the send).
static func hostileAssets() -> IngestError {
IngestError(message: "assets/ isn’t a plain folder in this piece.")
}
}
nonisolated extension PostStore {
/// The inserted ref for a landed asset: `![alt](assets/…)` with
/// `alt` as the selected placeholder for immediate type-over. The
/// destination is parser-clean BY CONSTRUCTION (see `ingestImage`),
/// so this exact string rides #34's rail — one helper so the drop
/// surface and the tests can never drift.
static func illustrationRef(_ destination: String) -> String {
"![alt](\(destination))"
}
/// #141: copy a dropped image into the piece's `assets/` — copy,
/// never move — and return the ref destination that names it. The
/// base name goes through the shared `slug` (whitespace→hyphens and
/// more: lowercase, diacritic-fold, 80-char cap) because the #34
/// parser never matches space-bearing destinations — the ref and
/// the file must agree at ingest. Collisions suffix `-2`/`-3`…
/// within `assets/`. Type gate = #34's publish-able set, checked
/// BEFORE anything lands.
static func ingestImage(from source: URL, pieceFolder: URL) throws -> String {
let name = source.lastPathComponent
guard Micropub.mimeType(forDestination: name) != nil else {
throw IngestError.notPublishable(name)
}
// The source must be a plain file: copyItem would land a symlink
// AS a link (finish-audit 2026-11-02), and the #34 rail then
// refuses the whole send — nothing enters assets/ that can't ship.
let values = try? source.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard source.isFileURL, let values else { throw IngestError.missing(name) }
if values.isSymbolicLink == true {
throw IngestError.isLink(name)
}
if values.isDirectory == true {
throw IngestError.isFolder(name)
}
let assets = pieceFolder.appendingPathComponent("assets", isDirectory: true)
if FileManager.default.fileExists(atPath: assets.path) {
// A symlinked or file-shaped assets/ never takes the write.
guard let values = try? assets.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
values.isDirectory == true, values.isSymbolicLink != true
else {
throw IngestError.hostileAssets()
}
} else {
try FileManager.default.createDirectory(at: assets, withIntermediateDirectories: true)
}
let ext = source.pathExtension.lowercased()
let base = slug(from: source.deletingPathExtension().lastPathComponent)
let landed = FixCardStore.uniqueFile(assets, base: base, ext: ext)
let destination = "assets/\(landed)"
try FileManager.default.copyItem(at: source, to: assets.appendingPathComponent(landed))
return destination
}
}