// // PostsModelRepointTests.swift // MuseionTests // // brief-28 (home-repoint-retains-old-editor-target): a Home repoint is a // document departure. Settings used to commit the new Home and flip // `watchedHome` (bind → startWatching) without departing the open // session: the session's immutable target kept the OLD Home, a same-slug // piece in the new library made the ID-only reselect return it, and // autosave/Save/quit wrote the old library while structural operations // resolved against the new one (#198's departure gate never saw this // seam). Pins: the gate runs BEFORE anything changes (a refused repoint // leaves Home A, the binding, the session's (Home, ID) target and its // buffer untouched — all three `sessionMayDepart` legs), an accepted // repoint lands the edits on A first and leaves no live session targeting // an A piece under B, the same-slug piece opens from B and saves there // (flush AND quit), a no-collision repoint tears down cleanly (the old // vanish path dropped the dirty buffer), a card scan from the old library // never lands on the new library's piece (identity re-check at // COMPLETION — the scan seam holds it past the repoint), and a pass // started after the repoint runs against the new library. // // Two-Home rig: `projects/posts/shared/post.md` in BOTH libraries — the // collision shape the finding names; differing bodies so a wrong-library // read is observable. The Settings path in these pins is the model's two // steps — `repoint(to:)` (the gate) then `bind` (the commit) — exactly as // WorkspaceView's binding and root `.task(id:)` drive them. // import Foundation @testable import Museion import Testing /// brief-28 rig: a Sendable one-shot flag the stale card-scan pin's park /// probe reads (the detached scanner sets it from off-main; pollUntil's /// per-iteration probe must not consume anything). private final class ParkedFlag: @unchecked Sendable { private let lock = NSLock() private var value = false var isSet: Bool { lock.withLock { value } } func set() { lock.withLock { value = true } } } @Suite("PostsModelRepointTests") @MainActor struct PostsModelRepointTests { private func denyWrites(to dir: URL) throws { try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: dir.path) } private func allowWrites(to dir: URL) throws { try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) } /// Two Homes holding the SAME slug — `writeNew` derives `shared` from /// the `# Shared` title in both (a non-Shared bodyA makes a unique /// slug instead: the no-collision shape). The model is bound to A. // swiftlint:disable:next large_tuple private func makeTwoHomes(bodyA: String, bodyB: String) throws -> (model: PostsModel, homeA: URL, homeB: URL) { let base = FileManager.default.temporaryDirectory .appendingPathComponent("repoint-\(UUID().uuidString)", isDirectory: true) let homeA = base.appendingPathComponent("A", isDirectory: true) let homeB = base.appendingPathComponent("B", isDirectory: true) for home in [homeA, homeB] { try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) } _ = try PostStore.writeNew(body: bodyA, home: homeA) _ = try PostStore.writeNew(body: bodyB, home: homeB) let model = PostsModel() model.bind(home: homeA) return (model, homeA, homeB) } @Test func `a same-slug piece opens from the new library after a repoint and saves there, never the old one`() throws { let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n") model.select("shared") #expect(model.session?.text == "# Shared\n\nA body\n") model.session?.edit("# Shared\n\nA body, typed in A\n") // The Settings repoint: the gate first, the binding after. #expect(model.repoint(to: homeB)) // Ordering: the departure landed on A and NOTHING has moved yet — // watchedHome is still A until the binding commits, and no live // session targets an A piece. #expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n") #expect(model.watchedHome == homeA) #expect(model.session == nil) #expect(model.selectedPostID == nil) model.bind(home: homeB) #expect(model.watchedHome == homeB) model.select("shared") // B's piece opened from B — not the retained A session (whose // ID-only reselect used to return it under the new UI). #expect(model.session?.text == "# Shared\n\nB body\n") #expect(model.session?.targets(postID: "shared", home: homeB) == true) model.session?.edit("# Shared\n\nB body, typed in B\n") model.session?.flush() // ⌘S — the debounce's own sink #expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body, typed in B\n") // A holds exactly what the departure flushed — never B's edits. #expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n") model.session?.edit("# Shared\n\nB body, typed in B again\n") model.shutdown() // quit rides the departure gate (#200) #expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body, typed in B again\n") #expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n") } @Test func `repoint refuses when the open piece's flush fails and changes nothing`() throws { let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n") model.select("shared") model.session?.edit("# Shared\n\nA body, typed in A\n") let pieceDir = try #require(PostStore.folder(of: "shared", home: homeA)) try denyWrites(to: pieceDir) defer { try? allowWrites(to: pieceDir) } // The Settings repoint — refused: the gate fires before any change. #expect(model.repoint(to: homeB) == false) // ORDERING: the gate fired before ANY state changed — the binding, // the selection, the session's (Home, ID) target and its buffer. #expect(model.watchedHome == homeA) #expect(model.selectedPostID == "shared") #expect(model.session?.postID == "shared") #expect(model.session?.targets(postID: "shared", home: homeA) == true) #expect(model.session?.text == "# Shared\n\nA body, typed in A\n") #expect(model.session?.saveState == .failed) #expect(model.lastError != nil) #expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body\n") // Writability restored → the edits land on A first (watchedHome // still A until the binding commits), then the repoint departs. try allowWrites(to: pieceDir) #expect(model.repoint(to: homeB)) #expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body, typed in A\n") #expect(model.watchedHome == homeA) model.bind(home: homeB) #expect(model.session == nil) #expect(model.selectedPostID == nil) #expect(model.watchedHome == homeB) } @Test func `repoint refuses while the conflict alert is unanswered`() throws { let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n") model.select("shared") model.session?.edit("# Shared\n\nA body, typed in A\n") // #67: a foreign disk body arrived — the alert is up, unanswered. model.session?.diskDidChange(diskText: "foreign body from disk") // The Settings repoint — refused. #expect(model.repoint(to: homeB) == false) #expect(model.watchedHome == homeA) #expect(model.selectedPostID == "shared") #expect(model.session?.postID == "shared") #expect(model.session?.targets(postID: "shared", home: homeA) == true) #expect(model.session?.conflictAlert == true) #expect(model.session?.text == "# Shared\n\nA body, typed in A\n") #expect(model.lastError != nil) // Never over the foreign body, never into the new library. #expect(PostStore.readBody(id: "shared", home: homeA) == "# Shared\n\nA body\n") #expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body\n") } @Test func `repoint refuses over a never-loaded session with retyped text`() throws { let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n") // The file turns unreadable between scan and open: the session // opens empty (loadFailed), the writer retypes into it (#200's leg). let file = try #require(PostStore.folder(of: "shared", home: homeA)) .appendingPathComponent("post.md") try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: file.path) defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: file.path) } model.select("shared") #expect(model.session?.loadFailed == true) model.session?.edit("# Retyped words over a file that never loaded") // The Settings repoint — refused: the retype is the only copy. #expect(model.repoint(to: homeB) == false) #expect(model.watchedHome == homeA) #expect(model.selectedPostID == "shared") #expect(model.session?.targets(postID: "shared", home: homeA) == true) #expect(model.session?.text == "# Retyped words over a file that never loaded") #expect(model.lastError != nil) } @Test func `a no-collision repoint lands the open piece's edits first and tears it down cleanly`() async throws { let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Unique\n\nA body\n", bodyB: "# Shared\n\nB body\n") model.select("unique") model.session?.edit("# Unique\n\nA body, typed in A\n") // The Settings repoint — accepted: the old session's edits landed // on A BEFORE anything moved (the vanish path used to tear it down // without a flush). #expect(model.repoint(to: homeB)) #expect(PostStore.readBody(id: "unique", home: homeA) == "# Unique\n\nA body, typed in A\n") #expect(model.session == nil) #expect(model.selectedPostID == nil) model.bind(home: homeB) // No ghost: the new library's rescan leaves nothing selected, nothing open. try await pollUntil { model.posts.contains { $0.id == "shared" } } #expect(model.session == nil) #expect(model.selectedPostID == nil) #expect(model.watchedHome == homeB) } @Test func `a card scan from the old library never lands on the new library's same-slug piece`() async throws { let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Shared\n\nA body\n", bodyB: "# Shared\n\nB body\n") let folderA = try #require(PostStore.folder(of: "shared", home: homeA)) let folderB = try #require(PostStore.folder(of: "shared", home: homeB)) _ = try FixCardStore.submit(piecePath: folderA.path, cards: [card(pattern: "Hedging", quote: "A body")]) _ = try FixCardStore.submit(piecePath: folderB.path, cards: [card(pattern: "Telling", quote: "B body")]) // HOLD the old library's scan past the repoint: the injected scanner // parks on A's folder until the test releases it (a detached disk // read is otherwise faster than any arrangement); B's scans run // free. The park probe is a flag, never a consuming semaphore wait — // pollUntil re-evaluates its condition per iteration. let parked = ParkedFlag() let release = DispatchSemaphore(value: 0) model.scanPieceCards = { url in if url == folderA { parked.set() _ = release.wait(timeout: .now() + 30) // bounded: a failed test must not leak a parked thread } return FixCardStore.scan(pieceURL: url) } model.select("shared") // the A scan parks inside the detached read try await pollUntil { parked.isSet } // The repoint, then B's same-slug piece opens and ITS scan lands. #expect(model.repoint(to: homeB)) model.bind(home: homeB) model.select("shared") try await pollUntil { model.openPieceCards.map(\.pattern) == ["Telling"] } #expect(model.openPieceCards.map(\.pattern) == ["Telling"]) // Release the stale A scan: its continuation completes AFTER the new // library's piece is open — identity at completion, never the id. release.signal() release.signal() // a second A scan, if one ever queued, must not park the teardown try await Task.sleep(nanoseconds: 200_000_000) // let the hop-back land #expect(model.openPieceCards.map(\.pattern) == ["Telling"]) // never A's cards } @Test func `a pass started after the repoint runs against the new library`() async throws { let (model, homeA, mentor) = try makePassRig() defer { mentor.shutdown() } await mentor.openSession() _ = try PostStore.writeNew(body: "# Shared\n\nA body\n", home: homeA) let homeB = FileManager.default.temporaryDirectory .appendingPathComponent("repoint-pass-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: homeB, withIntermediateDirectories: true) _ = try PostStore.writeNew(body: "# Shared\n\nB body\n", home: homeB) model.select("shared") #expect(model.session?.text == "# Shared\n\nA body\n") // The Settings repoint: gate, then binding. #expect(model.repoint(to: homeB)) model.bind(home: homeB) model.select("shared") #expect(model.session?.text == "# Shared\n\nB body\n") await model.runPass(.pass1, mentor: mentor) // Snapshot and the advance landed on B's piece with B's body — the // retained A session used to hand its text to the new library. let snapshot = try String( contentsOf: homeB.appendingPathComponent("projects/posts/shared/passes/pass-1.md"), encoding: .utf8, ) #expect(snapshot.contains("B body")) let onDiskB = try String(contentsOf: homeB.appendingPathComponent("projects/posts/shared/post.md"), encoding: .utf8) #expect(onDiskB.contains("pass_state: Pass-1 Done")) let onDiskA = try String(contentsOf: homeA.appendingPathComponent("projects/posts/shared/post.md"), encoding: .utf8) #expect(onDiskA.contains("pass_state: First Draft")) #expect(!FileManager.default.fileExists(atPath: homeA.appendingPathComponent("projects/posts/shared/passes/pass-1.md").path)) } }