// // PostStoreTests.swift // MuseionTests // // #18/#107: the Post lifecycle write side — global slug namespace across // projects/ and archive/, writeNew re-rooted to projects///, // 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. // // ## Scenario: candidate rail and the keep write // From #29 (S8.1/S8.2) // Given a piece in the library and the mentor researching mid-pass // When the engine delivers findings as submit_research_notes tool calls // Then well-formed candidates are accepted with a received count and // nothing is written anywhere; malformed ones answer a tool error // And the pass prompt names that rail // And when the writer keeps one, one plain markdown note with provenance // lands in the piece's research/ — nothing else auto-saves. // import Foundation @testable import Museion import Testing /// Throwaway Home in a temp dir (PostLibraryTests convention). private func storeHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL { let home = FileManager.default.temporaryDirectory .appendingPathComponent("poststore-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) try write(home) return home } private func readPost(_ home: URL, _ id: String) throws -> String { try String(contentsOf: home.appendingPathComponent("projects/posts/\(id)/post.md"), encoding: .utf8) } @Test func `slug algorithm per #60`() { #expect(PostStore.slug(from: "The Cartographer's Error") == "the-cartographers-error") #expect(PostStore.slug(from: "A Short Defence of Footnotes") == "a-short-defence-of-footnotes") #expect(PostStore.slug(from: "Café naïve résumé") == "cafe-naive-resume") // diacritic-fold #expect(PostStore.slug(from: "Hello — World!") == "hello-world") // em-dash dropped, space hyphenated #expect(PostStore.slug(from: " leading and trailing ") == "leading-and-trailing") #expect(PostStore.slug(from: "Multiple spaces") == "multiple-spaces") // runs → one hyphen #expect(PostStore.slug(from: "北京 Notes") == "北京-notes") // CJK kept #expect(PostStore.slug(from: String(repeating: "a", count: 100)) == String(repeating: "a", count: 80)) // 80-char cap #expect(PostStore.slug(from: "!!!") == "untitled") #expect(PostStore.slug(from: "") == "untitled") } @Test func `first write is lazy stamps frontmatter and slugs the folder`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# My First Post\n\nBody.", home: home) #expect(post.id == "my-first-post") #expect(post.passState == .firstDraft) #expect(post.origin == .writer) #expect(post.title == "My First Post") #expect(post.project == Post.defaultProject) #expect(!post.isArchived) #expect(post.type == .post) let file = try readPost(home, "my-first-post") #expect(file == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# My First Post\n\nBody.") // The #17 reader round-trips what the write side stamps. let scanned = Post.scan(home: home) #expect(scanned.count == 1) #expect(scanned.first?.title == "My First Post") #expect(scanned.first?.passState == .firstDraft) #expect(scanned.first?.origin == .writer) } @Test func `untitled draft first save uses untitled fallback`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "\n\n", home: home) #expect(post.id == "untitled") #expect(post.title == "untitled") #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/untitled/post.md").path)) } @Test func `collision appends -2 -3 case-insensitively`() throws { let home = try storeHome { home in try FileManager.default.createDirectory( at: home.appendingPathComponent("projects/posts/my-post", isDirectory: true), withIntermediateDirectories: true, ) // The taken set spans every project, not just posts/. try FileManager.default.createDirectory( at: home.appendingPathComponent("projects/other/My-Post-2", isDirectory: true), withIntermediateDirectories: true, ) try "x".write(to: home.appendingPathComponent("projects/posts/my-post/post.md"), atomically: true, encoding: .utf8) } // existing: posts/my-post, other/My-Post-2 → next free: my-post-3 #expect(PostStore.availableSlug(for: "My Post", home: home) == "my-post-3") let post = try PostStore.writeNew(body: "# My Post\n", home: home) #expect(post.id == "my-post-3") } @Test func `archived slug is never reused`() throws { let home = try storeHome { home in try FileManager.default.createDirectory( at: home.appendingPathComponent("archive/done/my-post", isDirectory: true), withIntermediateDirectories: true, ) try "x".write(to: home.appendingPathComponent("archive/done/my-post/post.md"), atomically: true, encoding: .utf8) try FileManager.default.createDirectory( at: home.appendingPathComponent("projects/posts/other-piece", isDirectory: true), withIntermediateDirectories: true, ) } // Archive counts as taken — restore of the archived piece must not collide. #expect(PostStore.availableSlug(for: "My Post", home: home) == "my-post-2") } @Test func `writeNew lands in the given project`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Mine\n", project: "essays", home: home) #expect(post.project == "essays") #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/essays/mine/post.md").path)) let scanned = Post.scan(home: home) #expect(scanned.count == 1) #expect(scanned.first?.project == "essays") } @Test func `writeNew with type outline stamps scans back and lands in the project`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "- Root\n\t- Child", project: "essays", type: .outline, home: home) #expect(post.type == .outline) #expect(post.id == "root") #expect(post.project == "essays") #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/essays/root/post.md").path)) // #59 stamp with type first, outline rawValue. #expect(try readPiece(home, root: "projects", project: "essays", post.id) == "---\ntype: outline\npass_state: First Draft\norigin: writer\n---\n- Root\n\t- Child") // The #17 reader round-trips the outline type and the project. let scanned = try #require(Post.scan(home: home).first) #expect(scanned.type == .outline) #expect(scanned.project == "essays") } @Test func `writeNew default still stamps type post`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Plain\n", home: home) #expect(post.type == .post) #expect(try readPost(home, post.id).hasPrefix("---\ntype: post\n")) } // Scenario: New Post from Session — from #30 (S2.7). Given a freeform // session whose transcript holds mentor text, when the writer picks // "New Post from Session" and confirms the ask sheet, then a piece folder // materializes under projects/posts/ with the draft body and origin: ai // stamped, and Museion opens the piece in Posts. @Test func `writeNew origin ai stamps the session-born piece and scans back`() throws { let home = try storeHome() let post = try PostStore.writeNew( body: "# From the Session\n\nMentor text becomes the draft.", origin: .ai, home: home, ) #expect(post.origin == .ai) #expect(post.id == "from-the-session") #expect(post.project == Post.defaultProject) // default posts/ landing #expect(post.passState == .firstDraft) #expect(try readPost(home, post.id) == "---\ntype: post\npass_state: First Draft\norigin: ai\n---\n# From the Session\n\nMentor text becomes the draft.") // The #17 reader reads it back as an ai piece. let scanned = try #require(Post.scan(home: home).first) #expect(scanned.origin == .ai) } @Test func `writeNew default origin stays writer for existing callers`() throws { let home = try storeHome() // #30: the additive parameter — saveDraft's call shape is unchanged. let post = try PostStore.writeNew(body: "# Plain\n", home: home) #expect(post.origin == .writer) #expect(try readPost(home, post.id).contains("origin: writer")) } @Test func `a session-born ai piece keeps origin ai through overwrite`() throws { // #30: immutability is the AC — the save path preserves the ai stamp. let home = try storeHome() let post = try PostStore.writeNew(body: "# From the Session\n\nv1", origin: .ai, home: home) try PostStore.overwrite(id: post.id, body: "# From the Session\n\nedited v2", home: home) let scanned = try #require(Post.scan(home: home).first) #expect(scanned.origin == .ai) #expect(try readPost(home, post.id).contains("origin: ai\n")) } @Test func `rename retitles moves folder and keeps frontmatter`() throws { let home = try storeHome() let original = try PostStore.writeNew(body: "# Old Name\n\nBody.", home: home) let moved = try PostStore.rename(original, to: "New Name", home: home) #expect(moved.id == "new-name") #expect(moved.title == "New Name") #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/old-name").path)) let file = try readPost(home, "new-name") #expect(file == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# New Name\n\nBody.") } @Test func `rename moves within the same project and archive stays archived`() throws { let home = try storeHome() // Same project: rename must not bounce the piece to the default project. let original = try PostStore.writeNew(body: "# Old Essay\n", project: "essays", home: home) let moved = try PostStore.rename(original, to: "New Essay", home: home) #expect(moved.project == "essays") #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/essays/new-essay/post.md").path)) #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/new-essay").path)) // Archived piece: stays under archive//, still flagged archived. try FileManager.default.createDirectory( at: home.appendingPathComponent("archive/done/old-thing", isDirectory: true), withIntermediateDirectories: true, ) try "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Old Thing\n" .write(to: home.appendingPathComponent("archive/done/old-thing/post.md"), atomically: true, encoding: .utf8) let archived = try #require(Post.scan(home: home).first { $0.id == "old-thing" }) let renamed = try PostStore.rename(archived, to: "New Thing", home: home) #expect(renamed.isArchived) #expect(renamed.project == "done") #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/done/new-thing/post.md").path)) #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/done/old-thing").path)) } @Test func `rename inserts title line when body had none`() throws { let home = try storeHome() let original = try PostStore.writeNew(body: "\n\n", home: home) #expect(original.id == "untitled") let moved = try PostStore.rename(original, to: "Given Title", home: home) #expect(moved.id == "given-title") let file = try readPost(home, "given-title") #expect(file.hasPrefix("---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Given Title")) } @Test func `rename keeps non-heading first line and inserts title above`() throws { let home = try storeHome() let original = try PostStore.writeNew(body: "Call mom tomorrow\n\nSecond line.", home: home) let moved = try PostStore.rename(original, to: "Errands", home: home) #expect(moved.id == "errands") let file = try readPost(home, "errands") #expect(file == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Errands\nCall mom tomorrow\n\nSecond line.") } @Test func `overwrite on vanished post throws instead of resurrecting`() throws { let home = try storeHome() #expect(throws: CocoaError(.fileReadNoSuchFile)) { try PostStore.overwrite(id: "ghost", body: "# Ghost\n", home: home) } #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/ghost").path)) } @Test func `collision routing consults a fresh listing`() throws { let home = try storeHome() _ = try PostStore.writeNew(body: "# Mine\n", home: home) // mine _ = try PostStore.writeNew(body: "# Mine\n", home: home) // mine-2 // An external write lands a folder the app didn't create — the next // slug pick must see it. (The in-writeNew existence guard covers the // race where the folder appears after the pick; that window isn't // deterministically reachable from a black-box test.) let racedDir = home.appendingPathComponent("projects/posts/mine-3", isDirectory: true) try FileManager.default.createDirectory(at: racedDir, withIntermediateDirectories: true) try "external".write(to: racedDir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) #expect(PostStore.availableSlug(for: "Mine", home: home) == "mine-4") _ = try PostStore.writeNew(body: "# Mine\n", home: home) #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/mine-4/post.md").path)) } @Test func `rename to same slug only retitles`() throws { let home = try storeHome() let original = try PostStore.writeNew(body: "# Same Name\n\nBody.", home: home) // Title slugs to same id → rewrite # line, no move. let moved = try PostStore.rename(original, to: "Same name!", home: home) #expect(moved.id == "same-name") #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/same-name/post.md").path)) } @Test func `rename collision takes -2`() throws { let home = try storeHome() let alpha = try PostStore.writeNew(body: "# Alpha\n", home: home) try PostStore.writeNew(body: "# Beta\n", home: home) let moved = try PostStore.rename(alpha, to: "Beta", home: home) #expect(moved.id == "beta-2") let renamed = try readPost(home, "beta-2") #expect(renamed.hasPrefix("---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Beta")) } @Test func `trash moves folder out of posts recoverably`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Gone Soon\n", home: home) try PostStore.trash(post, home: home) #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)").path)) #expect(Post.scan(home: home).isEmpty) } @Test func `trash resolves pieces in the archive`() throws { let home = try storeHome { home in try FileManager.default.createDirectory( at: home.appendingPathComponent("archive/done/doomed", isDirectory: true), withIntermediateDirectories: true, ) try "# Doomed\n".write( to: home.appendingPathComponent("archive/done/doomed/post.md"), atomically: true, encoding: .utf8, ) } let doomed = try #require(Post.scan(home: home).first) try PostStore.trash(doomed, home: home) #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("archive/done/doomed").path)) #expect(Post.scan(home: home).isEmpty) } @Test func `overwrite preserves pass_state and origin normalizing bare posts`() throws { let home = try storeHome() // A bare corpus post on disk (no frontmatter). let dir = home.appendingPathComponent("projects/posts/bare-one", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try "# Bare\n\nCorpus body.".write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) try PostStore.overwrite(id: "bare-one", body: "# Bare\n\nEdited body.", home: home) let file = try readPost(home, "bare-one") #expect(file == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Bare\n\nEdited body.") let scanned = try #require(Post.scan(home: home).first) #expect(scanned.passState == .firstDraft) #expect(scanned.origin == .writer) } @Test func `overwrite preserves existing pass_state and origin values`() throws { let home = try storeHome { home in let dir = home.appendingPathComponent("projects/posts/stamped", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try "---\npass_state: Pass-1 Done\norigin: ai\n---\n# Stamped\n\nBody." .write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } try PostStore.overwrite(id: "stamped", body: "# Stamped\n\nNew body.", home: home) let post = try #require(Post.scan(home: home).first) #expect(post.passState == .pass1Done) #expect(post.origin == .ai) } @Test func `readBody strips frontmatter for editing`() throws { let home = try storeHome() _ = try PostStore.writeNew(body: "# Editable\n\nSome text.", home: home) #expect(PostStore.readBody(id: "editable", home: home) == "# Editable\n\nSome text.") #expect(PostStore.readBody(id: "missing", home: home) == nil) } @Test func `writeNew failure does not leave a half post`() throws { // A file where the default project dir should go: writeNew must fail cleanly. let home = try storeHome() try FileManager.default.createDirectory( at: home.appendingPathComponent("projects", isDirectory: true), withIntermediateDirectories: true, ) let postsPath = home.appendingPathComponent("projects/posts").path try "blocker".write(to: URL(fileURLWithPath: postsPath), atomically: true, encoding: .utf8) #expect(throws: Error.self) { _ = 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 } } @Test func `convert flips type transforms the body once and keeps identity`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Chapter\n- one\n - nested", type: .outline, home: home) // verbatim: body unchanged, type flips, stamp keeps its own values try PostStore.convert(id: post.id, headingsLadder: false, home: home) let verbatim = try readPost(home, post.id) #expect(verbatim.hasPrefix("---\ntype: post\n")) #expect(verbatim.contains("pass_state: First Draft")) #expect(verbatim.contains("origin: writer")) #expect(PostStore.splitFrontmatter(verbatim).body == "# Chapter\n- one\n - nested") // folder never moved; scan reads the new type on rescan #expect(Post.scan(home: home).first?.id == post.id) #expect(Post.scan(home: home).first?.type == .post) // ladder: the headings mapping, preamble above try PostStore.convert(id: post.id, headingsLadder: true, home: home) let ladder = try readPost(home, post.id) #expect(ladder.hasPrefix("---\ntype: post\n")) #expect(PostStore.splitFrontmatter(ladder).body == "# Chapter\n## one\n### nested") // a vanished piece throws, never resurrects #expect(throws: CocoaError(.fileReadNoSuchFile)) { try PostStore.convert(id: "no-such-piece", headingsLadder: true, home: home) } } @Test func `convert works on an archived piece without moving it`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Filed\n- one", type: .outline, home: home) try PostStore.archive(post, home: home) try PostStore.convert(id: post.id, headingsLadder: true, home: home) let onDisk = try String(contentsOf: home.appendingPathComponent("archive/posts/\(post.id)/post.md"), encoding: .utf8) #expect(onDisk.hasPrefix("---\ntype: post\n")) #expect(onDisk.contains("## one")) #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)").path)) } // MARK: Pass substrate (#24) @Test func `snapshotPass writes the pre-pass body verbatim under passes`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Snapshot\n\nPre-pass body.", home: home) try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snapshot\n\nPre-pass body.", home: home) let snapshot = try String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"), encoding: .utf8, ) #expect(snapshot == "# Snapshot\n\nPre-pass body.") // body only, no frontmatter } @Test func `snapshotPass re-run overwrites keeping latest per pass type`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Snap\n\nBefore.", home: home) try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nBefore.", home: home) try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nAfter the first pass.", home: home) let snapshot = try String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"), encoding: .utf8, ) #expect(snapshot == "# Snap\n\nAfter the first pass.") } @Test func `pass snapshots coexist per pass type`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Both\n\nBody.", home: home) let passes = home.appendingPathComponent("projects/posts/\(post.id)/passes", isDirectory: true) try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "before pass one", home: home) try PostStore.snapshotPass(id: post.id, kind: .pass2, body: "before pass two", home: home) #expect(try String(contentsOf: passes.appendingPathComponent("pass-1.md"), encoding: .utf8) == "before pass one") #expect(try String(contentsOf: passes.appendingPathComponent("pass-2.md"), encoding: .utf8) == "before pass two") } @Test func `snapshotPass on vanished piece throws`() throws { let home = try storeHome() #expect(throws: CocoaError(.fileReadNoSuchFile)) { try PostStore.snapshotPass(id: "ghost", kind: .pass1, body: "x", home: home) } #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/ghost").path)) } @Test func `advancePassState stamps Pass-1 Done preserving origin type and body`() throws { let home = try storeHome { home in let dir = home.appendingPathComponent("projects/essays/essay", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try "---\ntype: outline\npass_state: First Draft\norigin: ai\n---\n# Essay\n\nArgued body." .write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } let newState = try PostStore.advancePassState(id: "essay", kind: .pass1, home: home) #expect(newState == .pass1Done) // Stamp round-trip: pass_state advanced, origin/type/body byte-preserved. #expect(try readPiece(home, root: "projects", project: "essays", "essay") == "---\ntype: outline\npass_state: Pass-1 Done\norigin: ai\n---\n# Essay\n\nArgued body.") #expect(PostStore.readBody(id: "essay", home: home) == "# Essay\n\nArgued body.") let scanned = try #require(Post.scan(home: home).first) #expect(scanned.passState == .pass1Done) #expect(scanned.origin == .ai) #expect(scanned.type == .outline) } @Test func `advancePassState reaches Pass-2 Done straight from First Draft`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Direct\n\nBody.", home: home) // Passes run in any order — Pass 2 first is legal. #expect(try PostStore.advancePassState(id: post.id, kind: .pass2, home: home) == .pass2Done) #expect(Post.scan(home: home).first?.passState == .pass2Done) } @Test func `advancePassState never regresses a higher state`() throws { let home = try storeHome { home in let dir = home.appendingPathComponent("projects/posts/done-both", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try "---\ntype: post\npass_state: Pass-2 Done\norigin: writer\n---\n# Done\n\nBody." .write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } // A Pass 1 completing on a Pass-2 Done piece keeps the higher state. let newState = try PostStore.advancePassState(id: "done-both", kind: .pass1, home: home) #expect(newState == .pass2Done) #expect(Post.scan(home: home).first?.passState == .pass2Done) #expect(try readPost(home, "done-both").contains("pass_state: Pass-2 Done")) } @Test func `advancePassState is idempotent on re-run`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home) _ = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) let first = try readPost(home, post.id) #expect(try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) == .pass1Done) #expect(try readPost(home, post.id) == first) } @Test func `advancePassState on vanished piece throws`() throws { let home = try storeHome() #expect(throws: CocoaError(.fileReadNoSuchFile)) { _ = try PostStore.advancePassState(id: "ghost", kind: .pass1, home: home) } } @Test func `stub carries pass name piece path research rail and fix-card reminder`() { let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md") let stub = PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false) #expect(stub.contains("Pass 1 — paragraph level and up.")) #expect(stub.contains("Piece: /vault/projects/essays/essay/post.md")) #expect(!stub.contains("Research notes:")) // #29: the typed research rail is named in the closing block — the // engine delivers findings, it never writes candidates itself. let closing = "Critique the piece for this pass. Fact-check claims where needed — research findings " + "travel as candidate source-note tool calls (submit_research_notes), never written to disk. " + "Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). " + "Do not write to the piece folder." #expect(stub.contains(closing)) #expect(PassContext.stub(kind: .pass2, pieceURL: pieceURL, hasResearch: false) .contains("Pass 2 — sentence level and below.")) } @Test func `stub adds the research line only when research exists`() { let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md") let research = "/vault/projects/essays/essay/research" #expect(PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: true) .contains("Research notes: \(research)")) #expect(!PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false).contains(research)) } @Test func `estimateTokens is stub plus body chars over four rounded up`() { let pieceURL = URL(fileURLWithPath: "/vault/essay/post.md") let body = "# Title\n\nTwo paragraphs of argued prose." for kind in PassKind.allCases { for hasResearch in [true, false] { let total = PassContext.stub(kind: kind, pieceURL: pieceURL, hasResearch: hasResearch).count + body.count let expected = total % 4 == 0 ? total / 4 : total / 4 + 1 // ceil — derived independently of the impl #expect(PassContext.estimateTokens(kind: kind, body: body, pieceURL: pieceURL, hasResearch: hasResearch) == expected) } } } // MARK: Research notes (#29) /// The keep writes "today" — computed at test time like promote's day /// stamp (a midnight rollover mid-suite is tolerated). private func researchDay() -> String { FixCardStore.formatted(Date(), "yyyyMMdd") } @Test func `writeResearchNote lands the pinned markdown shape in research`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Kept\n", home: home) let name = try PostStore.writeResearchNote( piecePath: home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true).path, title: "The Long Now", url: "https://example.org/long-now", quote: "pace layers", note: "Supports the slowness claim.", home: home, ) let day = researchDay() #expect(name == "\(day)-the-long-now.md") let markdown = try String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)"), encoding: .utf8, ) let expected = "---\nsource: https://example.org/long-now\nkept: \(day)\n---\n\n" + "# The Long Now\n\nSupports the slowness claim.\n\n> pace layers\n" #expect(markdown == expected) } @Test func `writeResearchNote omits absent note and quote sections`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Bare\n", home: home) let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true) // Both absent: frontmatter + heading, nothing else. let name = try PostStore.writeResearchNote( piecePath: pieceDir.path, title: "Only A Link", url: "https://example.org/one", quote: "", note: "", home: home, ) let bare = try String(contentsOf: pieceDir.appendingPathComponent("research/\(name)"), encoding: .utf8) #expect(bare == "---\nsource: https://example.org/one\nkept: \(researchDay())\n---\n\n# Only A Link\n") // Quote without note: the note section goes, the quote stays. let quoted = try PostStore.writeResearchNote( piecePath: pieceDir.path, title: "Quoted", url: "https://example.org/two", quote: "citation needed", note: "", home: home, ) let text = try String(contentsOf: pieceDir.appendingPathComponent("research/\(quoted)"), encoding: .utf8) #expect(text.hasSuffix("\n\n# Quoted\n\n> citation needed\n")) } @Test func `writeResearchNote collision takes -2`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Twice\n", home: home) let piecePath = home.appendingPathComponent("projects/posts/\(post.id)").path let first = try PostStore.writeResearchNote( piecePath: piecePath, title: "Same Source", url: "https://example.org/same", quote: "", note: "", home: home, ) let second = try PostStore.writeResearchNote( piecePath: piecePath, title: "Same Source", url: "https://example.org/same", quote: "", note: "", home: home, ) let day = researchDay() #expect(first == "\(day)-same-source.md") #expect(second == "\(day)-same-source-2.md") } @Test func `writeResearchNote accepts the post.md file form`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# File Form\n", home: home) let name = try PostStore.writeResearchNote( piecePath: home.appendingPathComponent("projects/posts/\(post.id)/post.md").path, title: "Via File", url: "https://example.org/file", quote: "", note: "", home: home, ) #expect(FileManager.default.fileExists( atPath: home.appendingPathComponent("projects/posts/\(post.id)/research/\(name)").path, )) } @Test func `writeResearchNote on vanished piece throws`() throws { let home = try storeHome() #expect(throws: FixCardStore.CardError(message: "piece not found: /nowhere/post.md")) { try PostStore.writeResearchNote( piecePath: "/nowhere/post.md", title: "Ghost", url: "https://example.org", quote: "", note: "", home: home, ) } } @Test func `writeResearchNote refuses a symlinked research dir`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Guarded\n", home: home) let pieceDir = home.appendingPathComponent("projects/posts/\(post.id)", isDirectory: true) let target = home.appendingPathComponent("elsewhere", isDirectory: true) try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true) try FileManager.default.createSymbolicLink( at: pieceDir.appendingPathComponent("research"), withDestinationURL: target, ) let planted = pieceDir.appendingPathComponent("research").path #expect(throws: FixCardStore.CardError(message: "research path is a symlink: \(planted)")) { try PostStore.writeResearchNote( piecePath: pieceDir.path, title: "Planted", url: "https://example.org", quote: "", note: "", home: home, ) } #expect(try FileManager.default.contentsOfDirectory(atPath: target.path).isEmpty) } // MARK: First-draft stats capture (#31, S5.1) /// Every `stats_` value is the store-time `%.3f` shape (a period, never a /// localized comma) — the trend view (S5.2) parses them back as Doubles. private func threeDecimals(_ value: String) -> Bool { value.range(of: #"^-?\d+\.\d{3}$"#, options: .regularExpression) != nil } @Test func `capture stamps five stats keys in place and preserves foreign frontmatter`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Draft\n\nOne two three. Four five! Six?", home: home) let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false) // Hand-add a foreign key INSIDE the block before capturing — the // in-place stamp must keep it byte-identical. let withForeign = try String(contentsOf: url, encoding: .utf8) .replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post") try withForeign.write(to: url, atomically: true, encoding: .utf8) let bodyBefore = PostStore.splitFrontmatter(withForeign).body let captured = PostStore.captureFirstDraftStats( id: post.id, body: "# Draft\n\nOne two three. Four five! Six?", home: home, ) #expect(captured) let after = try String(contentsOf: url, encoding: .utf8) let matter = Post.frontmatter(of: after) // the trend-view readiness read #expect(matter["foreign_key"] == "keep-me") #expect(matter["stats_captured"]?.count == 19) // yyyy-MM-dd'T'HH:mm:ss, lexically sortable #expect(matter["stats_burstiness"].map(threeDecimals) == true) #expect(matter["stats_type_token_ratio"].map(threeDecimals) == true) #expect(matter["stats_sentence_variation"].map(threeDecimals) == true) #expect(matter["stats_trigram_repetition"].map(threeDecimals) == true) #expect(matter["type"] == "post") #expect(matter["pass_state"] == "First Draft") #expect(matter["origin"] == "writer") // Body byte-identical — the stamp never touches content (#31 in-place proof). #expect(PostStore.splitFrontmatter(after).body == bodyBefore) } @Test func `capture refuses an ai origin piece untouched`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Machine\n\nAI-born text.", origin: .ai, home: home) let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") let before = try String(contentsOf: url, encoding: .utf8) #expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home)) #expect(try String(contentsOf: url, encoding: .utf8) == before) } @Test func `capture refuses a piece past first draft`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Done Once\n\nAlready critiqued.", home: home) try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") let before = try String(contentsOf: url, encoding: .utf8) #expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home)) #expect(try String(contentsOf: url, encoding: .utf8) == before) } @Test func `capture refuses an outline piece`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "- an outline item", type: .outline, home: home) let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") let before = try String(contentsOf: url, encoding: .utf8) #expect(!PostStore.captureFirstDraftStats(id: post.id, body: "x", home: home)) #expect(try String(contentsOf: url, encoding: .utf8) == before) } @Test func `recapture while still first draft overwrites latest draft state wins`() throws { let home = try storeHome() let post = try PostStore.writeNew(body: "# Evolving\n\nOne two three. Four five! Six?", home: home) #expect(PostStore.captureFirstDraftStats(id: post.id, body: "One two three. Four five! Six?", home: home)) #expect(PostStore.captureFirstDraftStats(id: post.id, body: "a b c. a b c.", home: home)) let matter = try Post.frontmatter(of: String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, )) #expect(matter["stats_burstiness"] == "-1.000") // σ = 0 over [3, 3] — the second body won #expect(matter["stats_type_token_ratio"] == "0.500") #expect(matter["stats_trigram_repetition"] == "0.250") } @Test func `capture qualifies a bare legacy post through the lenient defaults`() throws { // A bare corpus post (no frontmatter at all) scans writer/First // Draft/post — the capture gate must reach the same verdict, not // demand stamps that legacy files never carried. let home = try storeHome { home in let dir = home.appendingPathComponent("projects/posts/bare-legacy", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try "# Bare\n\nNo frontmatter here.".write( to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8, ) } #expect(PostStore.captureFirstDraftStats(id: "bare-legacy", body: "No frontmatter here.", home: home)) let after = try String( contentsOf: home.appendingPathComponent("projects/posts/bare-legacy/post.md"), encoding: .utf8, ) let matter = Post.frontmatter(of: after) #expect(matter["stats_captured"] != nil) #expect(after.contains("# Bare")) // the body survived the fresh-block prepend } @Test func `advance pass state preserves stats and foreign keys in place`() throws { // The #31 regression pin: the advance used to rewrite the block from // its three parsed fields, erasing the stats captured at the pass's // own invocation (and any foreign frontmatter). The in-place stamp // keeps every other line byte-identical. let home = try storeHome() let post = try PostStore.writeNew(body: "# Kept\n\nBody stays.", home: home) let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") let seeded = try String(contentsOf: url, encoding: .utf8) .replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post") try seeded.write(to: url, atomically: true, encoding: .utf8) #expect(PostStore.captureFirstDraftStats(id: post.id, body: "Body stays.", home: home)) let advanced = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) #expect(advanced == .pass1Done) let after = try String(contentsOf: url, encoding: .utf8) let matter = Post.frontmatter(of: after) #expect(matter["pass_state"] == "Pass-1 Done") #expect(matter["stats_captured"] != nil) // survived the advance #expect(matter["stats_trigram_repetition"] != nil) #expect(matter["foreign_key"] == "keep-me") // foreign keys too — the latent #24 loss #expect(matter["origin"] == "writer") #expect(matter["type"] == "post") #expect(PostStore.splitFrontmatter(after).body == "# Kept\n\nBody stays.") } @Test func `overwrite preserves stats and foreign keys while swapping the body`() throws { // The #31 finish-audit regression pin: an editor save mid-pass used to // route through the stamped() rewrite and erase the stats captured at // the invocation (plus foreign frontmatter). The in-place update keeps // every non-owned key and swaps only the body. let home = try storeHome() let post = try PostStore.writeNew(body: "# Draft\n\nFirst words.", home: home) let url = home.appendingPathComponent("projects/posts/\(post.id)/post.md") let seeded = try String(contentsOf: url, encoding: .utf8) .replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post") try seeded.write(to: url, atomically: true, encoding: .utf8) #expect(PostStore.captureFirstDraftStats(id: post.id, body: "First words.", home: home)) try PostStore.overwrite(id: post.id, body: "# Draft\n\nEdited mid-pass words.", home: home) let after = try String(contentsOf: url, encoding: .utf8) let matter = Post.frontmatter(of: after) #expect(matter["stats_captured"] != nil) // survived the editor save #expect(matter["foreign_key"] == "keep-me") #expect(matter["pass_state"] == "First Draft") #expect(matter["origin"] == "writer") #expect(matter["type"] == "post") #expect(PostStore.splitFrontmatter(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed } @Test func `overwrite normalizes a bare post with the full stamp`() throws { // The bare-post branch of the #31 audit fix: no block → the #59 stamp // shape (type first), exactly as before the fix. let home = try storeHome { home in let dir = home.appendingPathComponent("projects/posts/bare-overwrite", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try "Bare body.".write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } try PostStore.overwrite(id: "bare-overwrite", body: "Bare body, edited.", home: home) let after = try String( contentsOf: home.appendingPathComponent("projects/posts/bare-overwrite/post.md"), encoding: .utf8, ) let matter = Post.frontmatter(of: after) #expect(matter["type"] == "post") #expect(matter["pass_state"] == "First Draft") #expect(matter["origin"] == "writer") #expect(PostStore.splitFrontmatter(after).body == "Bare body, edited.") }