Files
museion/MuseionTests/PostsModelRepointTests.swift
AlexKucera 92344e224c
CI / ci (push) Canceled after 0s
test(editor): pin the rescan stale-Home verdict and the draft-survives repoint (review r1)
MF-1: the hoisted `guard watchedHome == home` in rescan was live logic
with no pin — the only new guard still observable after the gate (a
scan started under A can sit in its detached hop while the gate passes
and bind flips to B; landing after B's own scan it would hold A's list
under the B binding until the next B-side event, which with nothing
open is never). `scanLibrary` is the per-model injectable library
scanner beside `scanPieceCards` (captured before the hop); the pin
parks an A scan past the repoint, lets B's scan land, releases, and
asserts the list is still B's and `contentRevision` did not move.

Mutation check: hoist removed → rail-filtered `9 executed / 8 passed /
1 failed`, ONLY that pin, `posts.map(\.id) → ["alpha"]` and
`contentRevision → 3` vs `revision → 2`; restored byte-exact (sha256
prefix d86ce09d6b7e6bd2 before and after).

N-1: the draft-survives-repoint decision pinned — newPost targets the
selected A piece's project, the draft rides the repoint intact, and
`saveDraft()` lands under B only, in the draft's OWN project even
though B does not have it (materialize creates with intermediates).

Filtered GREEN: PostsModelRepointTests + PostsModelDepartureTests
19/19. swiftformat 0/152, swiftlint 0.
2026-11-23 22:34:23 +01:00

352 lines
17 KiB
Swift

//
// 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.
// r1 (athena MF-1/N-1): the hoisted stale-Home verdict in `rescan` (the
// library-scan sibling of the card hop-back — the per-model `scanLibrary`
// seam holds it past the repoint) and the draft-survives decision are
// pinned too.
//
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))
}
/// r1 (MF-1): the hoisted stale-Home verdict in `rescan` — the sibling
/// continuation of the card hop-back, and the one guard still observable
/// in production after the gate. A scan started under A sits in its
/// detached hop while the gate passes and `bind` flips to B; landing
/// after B's own scan it would put A's list under the B binding until
/// the next B-side event — which, with nothing open, can be never.
@Test func `a library scan from the old Home lands nothing under the new binding`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Alpha\n\nA body\n", bodyB: "# Bravo\n\nB body\n")
// The rig's first rescan lands first: posts is A's list, steady state.
try await pollUntil { model.posts.map(\.id) == ["alpha"] }
// HOLD the next A scan past the repoint (the card pin's shape).
let parked = ParkedFlag()
let release = DispatchSemaphore(value: 0)
model.scanLibrary = { home, cache in
if home == homeA {
parked.set()
_ = release.wait(timeout: .now() + 30) // bounded: a failed test must not leak a parked thread
}
return Post.scan(home: home, cache: cache)
}
Task { await model.rescan() } // parks inside the detached scan
try await pollUntil { parked.isSet }
// The Settings repoint: gate, then binding; B's own scan lands.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
try await pollUntil { model.posts.map(\.id) == ["bravo"] }
let revision = model.contentRevision
// Release the stale A scan: its continuation completes AFTER B's scan
// — the hoisted verdict applies nothing it found (list, revision).
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 continuation land
#expect(model.posts.map(\.id) == ["bravo"]) // never A's list under the B binding
#expect(model.contentRevision == revision) // and no revision bump for it
}
/// r1 (N-1): the draft-survives decision, pinned — a draft has no Home
/// until first save (#62), so the repoint leaves its buffer alone and
/// the lazy folder lands under B, in the draft's OWN project even when
/// B does not have it yet (materialize creates with intermediates).
@Test func `an in-memory draft survives a repoint and first-saves into the new library only`() async throws {
let (model, homeA, homeB) = try makeTwoHomes(bodyA: "# Piece\n\nA body\n", bodyB: "# Bravo\n\nB body\n")
// A holds `projects/alpha/in-alpha` — a project B does not have.
let alphaPiece = try PostStore.writeNew(body: "# In Alpha\n\nA body\n", project: "alpha", home: homeA)
try await pollUntil { model.posts.contains { $0.id == alphaPiece.id } } // the list must know the piece (targetProject reads it)
model.select(alphaPiece.id)
model.newPost() // targets the selected piece's project
#expect(model.draft?.project == "alpha")
model.updateDraft("# Draft Words\n\nTyped in A, saved in B")
// The Settings repoint: gate, then binding — the draft rides along.
#expect(model.repoint(to: homeB))
model.bind(home: homeB)
#expect(model.draft?.text == "# Draft Words\n\nTyped in A, saved in B") // intact
model.saveDraft()
#expect(PostStore.readBody(id: "draft-words", home: homeB) == "# Draft Words\n\nTyped in A, saved in B")
#expect(PostStore.readBody(id: "draft-words", home: homeA) == nil) // never A
#expect(Post.scan(home: homeB).contains { $0.id == "draft-words" && $0.project == "alpha" }) // B-absent project created
#expect(model.session?.targets(postID: "draft-words", home: homeB) == true) // and it opens there
#expect(model.draft == nil)
}
}