Files
museion/MuseionTests/PostLibraryTests.swift
AlexKucera 218e2db397
CI / ci (push) Canceled after 0s
refactor(posts): one frontmatter read/write codec
#180: one PostFrontmatter module now owns the lenient read
(parse/split/decoded) and every write posture — fresh stamp,
merge-import, update-keys — behind one known-key table (type,
pass_state, origin; one insertion order). The three near-twin walkers
are deleted byte-identically: PostStore.stamped/splitFrontmatter/
mergedFrontmatter, LearningDecay.stampingFrontmatter,
Post.frontmatter(of:) — 21 call sites swept across seven production
files and eight test files.

The Unaided First Draft eligibility is named once and consumed by both
gates: isUnaidedFirstDraftPair (writer ∧ post — the scan's read-back
gate) and isCaptureEligible (pair ∧ First Draft — the capture gate at
pass invocation). The lenient ?? default stamp decode is extracted
with it (the third copy's deferred extraction).

One deliberate divergence from the absorbed writer, doc-commented and
pinned: mergingImport now preserves hand-edit lines above the opening
--- on import where the old split-first shape silently dropped them —
lossless through every posture is the ticket's contract. Seven codec
pins (PostFrontmatterTests) cover the posture round-trip (foreign keys
verbatim through import → save → advance → micropub), the lenient
unknown-type decode, and the predicates' truth table.

Existing pieces are untouched on disk: every posture moved verbatim
and the full suite pins the byte shapes (664/664 green; the one
under-load flake in the #179 repoint pin is pre-existing on main,
proven by a stashed-tree control run).

Closes #180
2026-11-10 10:21:32 +01:00

397 lines
17 KiB
Swift

//
// PostLibraryTests.swift
// MuseionTests
//
// #17/#107: the Posts list mirrors <home>/projects/<name>/<id>/ and
// <home>/archive/<name>/<id>/ on disk (two-level scan, global slug space).
//
import Foundation
@testable import Museion
import Testing
/// Builds throwaway Homes in a temp dir: pieces written bare (corpus shape,
/// no frontmatter) or with frontmatter; noise entries that must not crash or
/// surface as Posts.
private func makeHome(_ write: (URL) throws -> Void) throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("postlib-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
try write(home)
return home
}
/// Seeds <home>/<root>/<project>/<id>/post.md (root: "projects" or "archive").
private func writePiece(_ home: URL, _ root: String, _ project: String, _ id: String, _ body: String) throws {
let dir = home.appendingPathComponent("\(root)/\(project)/\(id)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try body.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
private func writePost(_ home: URL, _ id: String, _ body: String) throws {
try writePiece(home, "projects", "posts", id, body)
}
@Test func `bare post is first draft writer with heading title`() throws {
let home = try makeHome { home in
try writePost(home, "the-new-reeder", "## The New Reeder\n\nBody text.")
}
let posts = Post.scan(home: home)
#expect(posts.count == 1)
let post = try #require(posts.first)
#expect(post.id == "the-new-reeder")
#expect(post.title == "The New Reeder")
#expect(post.passState == .firstDraft)
#expect(post.origin == .writer)
}
@Test func `frontmatter keys are read leniently`() throws {
let home = try makeHome { home in
try writePost(
home,
"a-short-defence-of-footnotes",
"---\npass_state: Pass-1 Done\norigin: ai\ntitle: ignored — body wins\n---\n\n# A Short Defence of Footnotes\n\nBody.",
)
}
let post = try #require(Post.scan(home: home).first)
#expect(post.passState == .pass1Done)
#expect(post.origin == .ai)
#expect(post.title == "A Short Defence of Footnotes")
}
@Test func `quoted frontmatter values are unquoted`() throws {
let home = try makeHome { home in
try writePost(home, "quoted", "---\npass_state: \"Pass-2 Done\"\norigin: 'ai'\n---\n\n## Quoted\n")
}
let post = try #require(Post.scan(home: home).first)
#expect(post.passState == .pass2Done)
#expect(post.origin == .ai)
}
@Test func `empty home is empty and missing home is empty`() throws {
let empty = try makeHome { _ in }
#expect(Post.scan(home: empty).isEmpty)
let missing = FileManager.default.temporaryDirectory
.appendingPathComponent("postlib-missing-\(UUID().uuidString)")
#expect(Post.scan(home: missing).isEmpty)
}
@Test func `scan enumerates two levels across projects and archive`() throws {
let home = try makeHome { home in
try writePiece(home, "projects", "alpha", "one", "## One\n\nBody.")
try writePiece(home, "projects", "beta", "two", "## Two\n\nBody.")
try writePiece(home, "archive", "gamma", "three", "## Three\n\nBody.")
// Noise at the new level: loose file at projects/ root, lazy piece
// folder, hidden project dir.
try "loose".write(
to: home.appendingPathComponent("projects/loose.md"),
atomically: true,
encoding: .utf8,
)
try FileManager.default.createDirectory(
at: home.appendingPathComponent("projects/alpha/not-yet", isDirectory: true),
withIntermediateDirectories: true,
)
try writePiece(home, "projects", ".trash", "four", "## Four\n")
}
let posts = Post.scan(home: home)
#expect(posts.count == 3)
let one = try #require(posts.first { $0.id == "one" })
#expect(one.project == "alpha")
#expect(!one.isArchived)
let two = try #require(posts.first { $0.id == "two" })
#expect(two.project == "beta")
#expect(!two.isArchived)
let three = try #require(posts.first { $0.id == "three" })
#expect(three.project == "gamma")
#expect(three.isArchived)
}
@Test func `type frontmatter is read leniently`() throws {
let home = try makeHome { home in
try writePost(home, "outlined", "---\ntype: outline\n---\n\n## Outlined\n")
try writePost(home, "untyped", "---\npass_state: First Draft\n---\n\n## Plain\n")
try writePost(home, "essay", "---\ntype: essay\n---\n\n## Essay\n")
}
let posts = Post.scan(home: home)
#expect(posts.first { $0.id == "outlined" }?.type == .outline)
#expect(posts.first { $0.id == "untyped" }?.type == .post) // absent key
#expect(posts.first { $0.id == "essay" }?.type == .post) // unknown value
}
@Test func `lazy folders, hidden dirs and noise are not posts`() throws {
let home = try makeHome { home in
try writePost(home, "one", "One")
// Lazy folder: no post.md yet (created lazily on first write, #18).
try FileManager.default.createDirectory(
at: home.appendingPathComponent("projects/posts/not-yet", isDirectory: true),
withIntermediateDirectories: true,
)
// Hidden dir WITH a post.md — must not surface.
try writePost(home, ".trash", "---\n---\n## Hidden\n")
// Noise: loose file at the piece level.
try "loose".write(
to: home.appendingPathComponent("projects/posts/loose.md"),
atomically: true,
encoding: .utf8,
)
}
#expect(Post.scan(home: home).map(\.id) == ["one"])
}
@Test func `symlinked post dir is not followed`() throws {
let home = try makeHome { home in
try writePost(home, "one", "One")
// A post.md outside the Home, linked into the project by symlink.
let outside = home.deletingLastPathComponent()
.appendingPathComponent("postlib-outside-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)
try "## Stolen\n".write(
to: outside.appendingPathComponent("post.md"),
atomically: true,
encoding: .utf8,
)
try FileManager.default.createSymbolicLink(
at: home.appendingPathComponent("projects/posts/linked", isDirectory: true),
withDestinationURL: outside,
)
}
#expect(Post.scan(home: home).map(\.id) == ["one"])
}
@Test func `posts sort by title locally`() throws {
let home = try makeHome { home in
try writePost(home, "z-id", "## Alpha\n")
try writePost(home, "a-id", "## Beta 2\n")
try writePost(home, "m-id", "## beta 10\n")
}
// localizedStandardCompare: case-insensitive, numeric-aware (Finder order).
#expect(Post.scan(home: home).map(\.title) == ["Alpha", "Beta 2", "beta 10"])
}
@Test func `blank draft title is untitled`() {
#expect(Post.title(of: "\n\n \n") == "untitled")
#expect(Post.title(of: "---\npass_state: Pass-2 Done\n---\n") == "untitled")
#expect(Post.title(of: "") == "untitled")
#expect(Post.title(of: "#\n") == "untitled") // heading marker only, no text
// Frontmatter-first title: first non-empty line after the block.
#expect(Post.title(of: "---\norigin: writer\n---\n\n## Named\n\nBody") == "Named")
}
@Test func `unterminated frontmatter is untitled, never leaked`() {
// No closing ---: frontmatter lines must never leak as the Title.
#expect(Post.title(of: "---\npass_state: First Draft\norigin: writer\n") == "untitled")
#expect(PostFrontmatter.parse("---\npass_state: First Draft\n")["pass_state"] == "First Draft")
}
@Test func `leading blank line still opens frontmatter`() throws {
// A leading newline before --- must not defeat frontmatter detection.
let text = "\n---\npass_state: Pass-1 Done\n---\n\n## After Blank\n"
let home = try makeHome { try writePost($0, "blank-open", text) }
let post = try #require(Post.scan(home: home).first)
#expect(post.passState == .pass1Done)
#expect(post.title == "After Blank")
}
// MARK: #171 fresh-install Home resolution
// Scenario: a fresh install with no stored override resolves its Home once —
// legacy ~/Documents/Museion wins if it exists (existing Homes migrate
// manually, never silently), else <CloudDocs>/Museion when iCloud Drive is
// present, else the silent Documents fallback; the winner is PINNED so the
// Home never silently moves after.
/// A throwaway defaults suite per test — the pin must land in the test's
/// own sandbox, never the runner app's real defaults.
private func homeDefaults(_ name: String) -> UserDefaults {
let suite = "home171-\(name)"
let defaults = UserDefaults(suiteName: suite)!
defaults.removePersistentDomain(forName: suite)
return defaults
}
@Test func `home resolution guards the legacy documents home first`() {
// iCloud available AND a legacy Home exists → the legacy Home wins.
let resolved = AppGateState.resolvedInitialHome(legacyHomeExists: { true }, cloudDocsDir: {
URL(fileURLWithPath: "/tmp/irrelevant-clouddocs")
})
#expect(resolved == AppGateState.defaultMuseionHome)
}
@Test func `home resolution pins clouddocs museion without a legacy home`() {
let cloudDocs = URL(fileURLWithPath: "/tmp/clouddocs")
let resolved = AppGateState.resolvedInitialHome(legacyHomeExists: { false }, cloudDocsDir: { cloudDocs })
#expect(resolved == cloudDocs.appendingPathComponent("Museion", isDirectory: true))
}
@Test func `home resolution silently falls back to documents museion`() {
let resolved = AppGateState.resolvedInitialHome(legacyHomeExists: { false }, cloudDocsDir: { nil })
#expect(resolved == AppGateState.defaultMuseionHome)
}
@Test func `clouddocs probe requires a real directory`() throws {
// The live probe's dir-ness gate, driven on temp paths — hosted tests
// never touch the machine's real iCloud state.
let dir = try makeHome { _ in }
#expect(AppGateState.existingDirectory(dir) == dir)
let file = dir.appendingPathComponent("plain-file")
try "not a dir".write(to: file, atomically: true, encoding: .utf8)
#expect(AppGateState.existingDirectory(file) == nil)
#expect(AppGateState.existingDirectory(dir.appendingPathComponent("missing")) == nil)
}
@Test @MainActor func `stored home override wins over the resolution ladder`() {
let defaults = homeDefaults("stored-wins")
let custom = URL(fileURLWithPath: "/tmp/museion-custom-home")
defaults.set(custom.absoluteString, forKey: "museionHome")
let gate = AppGateState(defaults: defaults, legacyHomeExists: { true }, cloudDocsDir: { nil })
#expect(gate.museionHome == custom)
}
@Test @MainActor func `non-file stored home falls through to the ladder`() {
let defaults = homeDefaults("non-file-stored")
defaults.set("https://not.a/home", forKey: "museionHome")
let gate = AppGateState(defaults: defaults, legacyHomeExists: { false }, cloudDocsDir: { nil })
#expect(gate.museionHome == AppGateState.defaultMuseionHome)
#expect(defaults.string(forKey: "museionHome") == AppGateState.defaultMuseionHome.absoluteString)
}
@Test @MainActor func `fresh install pins once and never silently moves`() throws {
let defaults = homeDefaults("pin-once")
let cloudDocs = try makeHome { _ in }
let first = AppGateState(defaults: defaults, legacyHomeExists: { false }, cloudDocsDir: { cloudDocs })
#expect(first.museionHome == cloudDocs.appendingPathComponent("Museion", isDirectory: true))
#expect(defaults.string(forKey: "museionHome") == first.museionHome.absoluteString)
// A legacy Home "appears" after the pin — the stored winner stands.
let second = AppGateState(defaults: defaults, legacyHomeExists: { true }, cloudDocsDir: { nil })
#expect(second.museionHome == first.museionHome)
}
@Test @MainActor func `default construction never writes the real defaults under hosted tests`() {
// The init guard protecting the runner app's real state — pinned
// without touching it: whatever .standard holds before a default
// construction must hold after (a deleted guard resolves + PINS,
// changing the stored value wherever the resolved Home differs).
let real = UserDefaults.standard
let before = real.string(forKey: "museionHome")
_ = AppGateState() // default construction — no probes, no pin
#expect(real.string(forKey: "museionHome") == before)
}
@Test func `clouddocs path is the unprefixed mobile documents form`() {
// #171: never a hard-coded `iCloud~` form — the prefixed spelling
// varies per account and would silently disable iCloud detection.
#expect(
AppGateState.cloudDocsURL(under: URL(fileURLWithPath: "/h"))
== URL(fileURLWithPath: "/h/Library/Mobile Documents/com~apple~CloudDocs", isDirectory: true),
)
}
@Test func `duplicate id on disk dedupes to the folder-of winner`() throws {
// Audit: a Finder copy can duplicate an id across projects (or into
// archive/). scan keeps ONE row — the same projects-before-archive,
// name-sorted winner folder(of:) writes to — so the row shown is
// always the piece written.
let home = try makeHome { home in
try writePiece(home, "projects", "beta", "same-id", "## From Beta\n")
try writePiece(home, "projects", "alpha", "same-id", "## From Alpha\n")
try writePiece(home, "archive", "zeta", "same-id", "## From Archive\n")
}
let posts = Post.scan(home: home)
#expect(posts.count == 1)
#expect(posts.first?.project == "alpha") // alpha < beta; archive never wins
#expect(PostStore.folder(of: "same-id", home: home)?
.lastPathComponent == "same-id")
#expect(PostStore.folder(of: "same-id", home: home)?
.pathComponents.suffix(2).first == "alpha")
}
@Test func `hidden project folder never shadows a visible piece`() throws {
// Audit: folder(of:) skips dot-projects like scan does — a piece under
// projects/.trash/ must not capture writes meant for the visible twin.
let home = try makeHome { home in
try writePiece(home, "projects", ".trash", "mine", "## Hidden\n")
try writePiece(home, "projects", "posts", "mine", "## Visible\n")
}
let posts = Post.scan(home: home)
#expect(posts.map(\.id) == ["mine"])
#expect(posts.first?.title == "Visible")
#expect(PostStore.folder(of: "mine", home: home)?
.pathComponents.suffix(2).first == "posts")
}
// MARK: #143 scan cache (OPT-F3)
@Test func `unchanged files parse once then serve from cache`() throws {
let home = try makeHome { home in
try writePost(home, "one", "## One\n")
try writePost(home, "two", "## Two\n")
try writePost(home, "three", "## Three\n")
}
let cache = PostScanCache()
let first = Post.scan(home: home, cache: cache)
#expect(cache.misses == 3) // cold scan: every file read + parsed once
let second = Post.scan(home: home, cache: cache)
#expect(cache.hits == 3) // warm scan: zero re-reads
#expect(second == first) // identical result through the cache
}
@Test func `changed file re-parses while untouched files hit`() throws {
let home = try makeHome { home in
try writePost(home, "one", "## One\n")
try writePost(home, "two", "## Two\n")
}
let cache = PostScanCache()
_ = Post.scan(home: home, cache: cache)
// The autosave echo: one post.md rewritten (mtime + size both move).
try "## Two Retitled\n".write(
to: home.appendingPathComponent("projects/posts/two/post.md"),
atomically: true,
encoding: .utf8,
)
let posts = Post.scan(home: home, cache: cache)
#expect(posts.first { $0.id == "two" }?.title == "Two Retitled")
#expect(cache.misses == 3) // one re-read for the changed file
#expect(cache.hits == 1) // one reuse for the untouched one
}
@Test func `moved piece re-parses at its new path`() throws {
// The cache is keyed by the post.md PATH — a folder move (archive,
// move-to-project) keeps bytes and mtime but changes the path, so the
// stale entry can never answer and isArchived re-derives from disk.
let home = try makeHome { home in
try writePost(home, "one", "## One\n")
}
let cache = PostScanCache()
_ = Post.scan(home: home, cache: cache)
try FileManager.default.createDirectory(
at: home.appendingPathComponent("archive/posts", isDirectory: true),
withIntermediateDirectories: true,
)
try FileManager.default.moveItem(
at: home.appendingPathComponent("projects/posts/one", isDirectory: true),
to: home.appendingPathComponent("archive/posts/one", isDirectory: true),
)
let posts = Post.scan(home: home, cache: cache)
#expect(posts.first?.isArchived == true)
#expect(posts.first?.project == "posts")
}
@Test func `a late store carrying a stale stamp never pins stale content`() throws {
// The overlapping-rescan race, pinned at its end-state: scan A reads
// v1 and stalls, the file rewrites (v2), scan B caches v2, then A's
// late store lands keyed on ITS pre-read (v1) stamp — the next scan
// must mismatch, re-read, and serve disk truth, never v1.
let home = try makeHome { home in
try writePost(home, "one", "## One\n")
}
let cache = PostScanCache()
let stale = try #require(Post.scan(home: home, cache: cache).first)
let url = home.appendingPathComponent("projects/posts/one/post.md")
let staleStamp = PostScanCache.stamp(at: url) // captured pre-rewrite
try "## Two\n".write(to: url, atomically: true, encoding: .utf8)
cache.store(stale, at: url, stamp: staleStamp) // A's late store
#expect(Post.scan(home: home, cache: cache).first?.title == "Two")
}