feat(library): projects & archive UI — S2 (#108)
CI / ci (push) Canceled after 0s

Variant B per the #104 prototype verdict: the library column groups
pieces by project (serif lowercase heads, collapse toggle, Pass-State
groups inside, 2px edge-bar selection shared with the new Archive
pane via LibraryPostRow). Move to Project / Archive / Move Back /
whole-project Unarchive are folder moves — post.md bytes untouched,
never clobbering, ids globally unique. File ▸ New Post ⌘N and New
Project… ⌥⌘N (CommandGroup, never CommandMenu per #84).

Every folder move flushes pending edits first and aborts when the
write failed — nothing moves without its text. Project membership and
the archived-refusal derive from freshly resolved disk paths, never
the scan snapshot. Slug and project-name comparisons fold through one
canonical key (NFC + lowercase). Two reviewer fanouts this session;
their findings are all fixed or visibly parked.

144/144 tests green (run twice), swiftformat/swiftlint clean.

Closes #108
This commit is contained in:
AlexKucera committed 2026-10-13 22:18:24 +02:00
1 parent 9da3a07f4a
commit e55747e7fe
15 files changed
+1205 -68

No files matched your search

+2 -1
View File
@@ -21,7 +21,8 @@ Owned by the root AGENTS.md contract.
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt`, default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. Only `acpTempDir` remains as a helper; crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path. **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract).
- `PostsModelTests.swift` (#108 audits) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included).
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
+6 -1
View File
@@ -39,7 +39,12 @@ struct EditorSessionTests {
session.edit("# Alpha\n\nOne. Two.")
#expect(session.saveState == .changed) // #83: dirty shows while the debounce holds
try await Task.sleep(for: .milliseconds(200))
// Await the flush rather than sleeping a fixed window — under suite
// load the main actor can starve the debounce Task past any constant.
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
while session.saveState != .saved, ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(20))
}
#expect(session.saveState == .saved) // Changed → flush → Saved lands here
#expect(PostStore.readBody(id: "alpha", home: home) == "# Alpha\n\nOne. Two.")
+203
View File
@@ -6,6 +6,7 @@
// projects/ and archive/, writeNew re-rooted to projects/<name>/<id>/,
// the #59 stamp with type first, rename = retitle + move within the same
// project (#60), Trash delete, save-time normalization.
// #108: project moves, archive/restore, project unarchive + creation.
//
import Foundation
@@ -289,3 +290,205 @@ private func readPost(_ home: URL, _ id: String) throws -> String {
_ = try PostStore.writeNew(body: "# Blocked\n", home: home)
}
}
// MARK: Project moves & archive (#108)
/// readPost's path-aware sibling: any piece under any root/project.
private func readPiece(_ home: URL, root: String, project: String, _ id: String) throws -> String {
try String(
contentsOf: home.appendingPathComponent("\(root)/\(project)/\(id)/post.md", isDirectory: false),
encoding: .utf8,
)
}
@Test func `move sends piece to another project`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Traveler\n\nBody.", project: "essays", home: home)
let original = try readPiece(home, root: "projects", project: "essays", post.id)
try PostStore.move(post, to: "posts", home: home)
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/essays/\(post.id)").path))
#expect(try readPiece(home, root: "projects", project: "posts", post.id) == original) // bytes untouched
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.project == "posts")
#expect(!scanned.isArchived)
// Same-project confirm in the picker is a no-op, not a "file exists" error.
try PostStore.move(post, to: "posts", home: home)
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path))
}
@Test func `archive and restore round-trip a piece`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Round Trip\n", home: home)
try PostStore.archive(post, home: home)
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/posts/\(post.id)/post.md").path))
var scanned = try #require(Post.scan(home: home).first)
#expect(scanned.isArchived)
#expect(scanned.project == "posts")
try PostStore.restore(post, home: home)
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path))
scanned = try #require(Post.scan(home: home).first)
#expect(!scanned.isArchived)
#expect(scanned.project == "posts")
}
@Test func `move refuses an archived piece`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# No Escape\n", home: home)
try PostStore.archive(post, home: home)
#expect(throws: CocoaError(.featureUnsupported)) {
try PostStore.move(post, to: "essays", home: home)
}
// Still where archive left it.
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/posts/\(post.id)/post.md").path))
}
@Test func `unarchiveProject moves the whole project folder`() throws {
let home = try storeHome { home in
try FileManager.default.createDirectory(
at: home.appendingPathComponent("archive/awards/laurel", isDirectory: true),
withIntermediateDirectories: true,
)
try "# Laurel\n".write(
to: home.appendingPathComponent("archive/awards/laurel/post.md"),
atomically: true,
encoding: .utf8,
)
}
try PostStore.unarchiveProject("awards", home: home)
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/laurel/post.md").path))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/awards").path))
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.id == "laurel")
#expect(scanned.project == "awards")
#expect(!scanned.isArchived)
}
@Test func `unarchiveProject merges when the project exists`() throws {
let home = try storeHome { home in
for path in ["projects/awards/kept", "archive/awards/back"] {
try FileManager.default.createDirectory(
at: home.appendingPathComponent(path, isDirectory: true),
withIntermediateDirectories: true,
)
try "# Piece\n".write(
to: home.appendingPathComponent("\(path)/post.md"),
atomically: true,
encoding: .utf8,
)
}
}
try PostStore.unarchiveProject("awards", home: home)
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/kept/post.md").path))
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/back/post.md").path))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/awards").path))
#expect(Post.scan(home: home).count == 2)
#expect(Post.scan(home: home).allSatisfy { !$0.isArchived && $0.project == "awards" })
}
@Test func `unarchiveProject skips finder dotfiles in the merge`() throws {
let home = try storeHome { home in
for path in ["projects/awards/kept", "archive/awards/back"] {
try FileManager.default.createDirectory(
at: home.appendingPathComponent(path, isDirectory: true),
withIntermediateDirectories: true,
)
try "# Piece\n".write(
to: home.appendingPathComponent("\(path)/post.md"),
atomically: true,
encoding: .utf8,
)
// Finder drops these when it browses a folder.
try "junk".write(
to: home.appendingPathComponent("\(path)/.DS_Store"),
atomically: true,
encoding: .utf8,
)
}
}
try PostStore.unarchiveProject("awards", home: home)
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/back/post.md").path))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/awards").path)) // the .DS_Stores didn't wedge it open
#expect(Post.scan(home: home).count == 2)
}
@Test func `unarchiveProject keeps hidden user folders instead of destroying them`() throws {
// removeItem is permanent — a Finder-hidden folder inside the archived
// project must survive the unarchive, not die with the emptied source.
let home = try storeHome { home in
for path in ["projects/awards/kept", "archive/awards/back"] {
try FileManager.default.createDirectory(
at: home.appendingPathComponent(path, isDirectory: true),
withIntermediateDirectories: true,
)
try "# Piece\n".write(
to: home.appendingPathComponent("\(path)/post.md"),
atomically: true,
encoding: .utf8,
)
}
try FileManager.default.createDirectory(
at: home.appendingPathComponent("archive/awards/.research", isDirectory: true),
withIntermediateDirectories: true,
)
}
try PostStore.unarchiveProject("awards", home: home)
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/awards/back/post.md").path))
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/awards/.research").path)) // survived
}
@Test func `slug collisions fold unicode normalization`() throws {
// Decomposed-jamo folder on disk vs a precomposed title — one folder to
// normalization-insensitive APFS; the fold makes the -2 fire instead of
// the TOCTOU guard surfacing a baffling "file exists".
let decomposed = "한국".decomposedStringWithCanonicalMapping
let home = try storeHome { home in
try FileManager.default.createDirectory(
at: home.appendingPathComponent("projects/posts/\(decomposed)", isDirectory: true),
withIntermediateDirectories: true,
)
}
#expect(!decomposed.utf8.elementsEqual("한국".utf8)) // two byte sequences, one name — Swift ==/Set already fold; the explicit key pins the contract
#expect(PostStore.availableSlug(for: "한국", home: home) == "한국-2")
}
@Test func `createProject materializes and validates`() throws {
let home = try storeHome()
try PostStore.createProject(named: "foo", home: home)
#expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/foo").path))
#expect(throws: CocoaError(.fileWriteFileExists)) {
try PostStore.createProject(named: "FOO", home: home) // case-insensitive duplicate
}
// #108 audit 2: NFD duplicate — "café" typed/pasted decomposed reads
// identical but is one folder on normalization-insensitive APFS.
try PostStore.createProject(named: "café", home: home) // NFC variant first
#expect(throws: CocoaError(.fileWriteFileExists)) {
try PostStore.createProject(named: "cafe\u{0301}", home: home) // NFD twin
}
#expect(throws: CocoaError(.fileWriteInvalidFileName)) {
try PostStore.createProject(named: "a:b", home: home) // Finder shows ":" as "/"
}
#expect(throws: CocoaError(.fileWriteInvalidFileName)) {
try PostStore.createProject(named: " ", home: home) // empty after trimming
}
#expect(throws: CocoaError(.fileWriteInvalidFileName)) {
try PostStore.createProject(named: "a/b", home: home) // path separator
}
#expect(throws: CocoaError(.fileWriteInvalidFileName)) {
try PostStore.createProject(named: ".x", home: home) // hidden — scan skips dot-dirs
}
}
+121
View File
@@ -0,0 +1,121 @@
//
// PostsModelTests.swift
// MuseionTests
//
// #108 audit: the model-layer lifecycle the store tests can't see —
// archive clearing the open session, move reopening it at the new parent,
// restore keeping the writer in the piece, New Project's draft targeting.
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Home + model (EditorSessionTests convention: direct @MainActor
/// instantiation, no app gate).
@MainActor
private func makeModelHome() throws -> (PostsModel, URL) {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("postsmodel-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
let model = PostsModel()
model.bind(home: home)
return (model, home)
}
@Test @MainActor func `archiving the open piece clears selection and session`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Gone Soon\n", home: home)
model.select(post.id, home: home)
#expect(model.session?.postID == post.id)
model.archivePost(post, home: home)
#expect(model.selectedPostID == nil)
#expect(model.session == nil)
#expect(model.lastError == nil)
#expect(Post.scan(home: home).first?.isArchived == true)
}
@Test @MainActor func `moving the open piece reopens its session at the new parent`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Traveler\n", project: "essays", home: home)
model.select(post.id, home: home)
#expect(model.session?.folderURL.path.contains("projects/essays") == true)
model.moveToProject(post, project: "posts", home: home)
#expect(model.session?.postID == post.id) // same piece, fresh session
#expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true)
#expect(model.lastError == nil)
}
@Test @MainActor func `restore reopens the session off the archive path`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Revived\n", home: home)
try PostStore.archive(post, home: home)
model.select(post.id, home: home) // opened from the Archive pane
#expect(model.session?.folderURL.path.contains("archive/") == true)
model.restorePost(post, home: home)
#expect(model.selectedPostID == post.id) // the writer stays in it
#expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true)
#expect(model.lastError == nil)
}
@Test @MainActor func `new project draft lands in the named project`() throws {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "essays", home: home)
model.newProjectPending(named: "essays")
#expect(model.draft?.project == "essays")
model.updateDraft("# Fresh\n")
model.saveDraft(home: home)
let scanned = Post.scan(home: home)
#expect(scanned.first?.project == "essays")
#expect(scanned.first?.id == "fresh")
}
@Test @MainActor func `abandoning the draft for an external file drops the pending target`() throws {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "essays", home: home)
model.newProjectPending(named: "essays")
#expect(model.draft?.project == "essays")
// The external guest takes the column; the draft dies — its target must too.
let external = home.appendingPathComponent("outside.md")
try "# foreign\n".write(to: external, atomically: true, encoding: .utf8)
model.openExternal(external)
#expect(model.draft == nil)
model.newPost()
#expect(model.draft?.project == Post.defaultProject) // not the abandoned essays
}
@Test @MainActor func `unarchive flushes the dirty open piece before moving`() throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Keeper\n", home: home)
try PostStore.archive(post, home: home)
model.select(post.id, home: home)
model.session?.edit("# Keeper\n\nDirty.") // inside the debounce window
model.unarchiveProject("posts", home: home)
// The edits landed on disk (readBody resolves by id — through the move).
#expect(PostStore.readBody(id: post.id, home: home) == "# Keeper\n\nDirty.")
#expect(model.lastError == nil)
// The reopen swapped in a fresh session over the same piece.
#expect(model.session?.postID == post.id)
#expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true)
}
@Test @MainActor func `moveTargets lists empty projects from disk`() throws {
let (model, home) = try makeModelHome()
try PostStore.createProject(named: "essays", home: home) // empty — no pieces
#expect(model.moveTargets(home: home) == ["essays", "posts"])
// "posts" exists too (bind created it); a dot-project never shows.
}