From 8b0d43aed8ba3c7c3ae7e67853639451763d4c6f Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 23 Nov 2026 20:23:57 +0100 Subject: [PATCH] fix(editor): Home repoint rides the departure gate; document identity is (Home, ID) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings committed the new Home and bind flipped watchedHome 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; a no-collision piece was torn down by the vanish path with its dirty buffer dropped. The gate runs BEFORE anything commits. PostsModel.repoint(to:) is a document departure through the same sessionMayDepart (all three legs: unanswered #67, failed flush, never-loaded retype — no parallel gate); on refusal nothing changes (preference, watchedHome, the session's (A, id) target, its buffer), on acceptance the departed piece's state dies with it. AppGateState.repointMuseionHome(to:) commits the preference and its persistence only after the gate; WorkspaceView's Settings binding routes through it and the root .task(id:) binds the model after that commit — the dumb binder. A refusal speaks the #198 reason the way #200's quit refusal does (hosted-guarded alert: no Posts strip is in sight from Settings). Nothing auto-reopens after an accepted repoint — the writer picks from the new list; the in-memory draft survives (no Home until first save; dropping it would drop the only copy). Document identity is (Home, ID) everywhere — EditorSession.targets is the pair, PostsModel.openSessionTargets the model-side question; every ID-only session comparison is retired: select's reselect no-op, openUnguarded, the structural rail (rename/trash/move/archive/ restore/unarchive + flushOrAbort), conversion, the pass guard (its answer now carries the Home it validated), Micropub's launch, the lock's arm/body reads. Async continuations re-validate identity at COMPLETION: refreshCards (launch and hop-back — the old ID-only guard let a scan from the previous library land its cards on the new library's same-slug piece) and rescan (the stale-Home verdict is hoisted: a scan that outlived a repoint applies nothing, not just the vanish check; the #67 disk read runs only for a session targeting the scan's own Home). scanPieceCards is the per-model injectable scanner the deterministic stale-scan pin needs. Tests: PostsModelRepointTests (7) move to the gated entry and go green (17/17 with PostsModelDepartureTests — the #198 matrix stays green and composes); the stale-scan pin's RED is a mutation check (completion guard reverted to ID-only → only that pin fails, cards → ["Hedging"]; restored byte-exact). The #179 mid-pass repoint pin drives the real Settings path now (repoint + bind). swiftformat 0/152, swiftlint 0. --- Museion/HomeResolution.swift | 15 ++++ Museion/Micropub.swift | 10 ++- Museion/PostsModel.swift | 18 ++-- Museion/PostsModelCards.swift | 19 ++-- Museion/PostsModelIdentity.swift | 25 ++++++ Museion/PostsModelOutline.swift | 14 +-- Museion/PostsModelPasses.swift | 32 +++---- Museion/PostsModelWatcher.swift | 77 +++++++++++++--- Museion/PostsModelWrites.swift | 16 ++-- Museion/WorkspaceView.swift | 36 +++++++- MuseionTests/PostsModelRepointTests.swift | 103 ++++++++++++++++++---- MuseionTests/PostsModelTests.swift | 5 +- 12 files changed, 298 insertions(+), 72 deletions(-) create mode 100644 Museion/PostsModelIdentity.swift diff --git a/Museion/HomeResolution.swift b/Museion/HomeResolution.swift index cd0f491..ae08203 100644 --- a/Museion/HomeResolution.swift +++ b/Museion/HomeResolution.swift @@ -80,4 +80,19 @@ extension AppGateState { nonisolated static func storeHome(_ home: URL, in defaults: UserDefaults) { defaults.set(home.absoluteString, forKey: "museionHome") } + + /// brief-28 (home-repoint-retains-old-editor-target): the ONE repoint + /// entry at runtime — the departure gate runs FIRST (`posts.repoint`: + /// every open document lands, or nothing changes and `posts.lastError` + /// names the piece); the preference and its persistence (`museionHome`'s + /// didSet) commit only after. True = committed. WorkspaceView's Settings + /// binding routes through here; the root `.task(id: museionHome)` binds + /// the model after the commit, so `watchedHome` can never move past a + /// live session again. + @discardableResult + func repointMuseionHome(to newHome: URL) -> Bool { + guard posts.repoint(to: newHome) else { return false } + museionHome = newHome + return true + } } diff --git a/Museion/Micropub.swift b/Museion/Micropub.swift index 6f531e4..0f19c66 100644 --- a/Museion/Micropub.swift +++ b/Museion/Micropub.swift @@ -250,9 +250,16 @@ extension PostsModel { token: String, transport: Micropub.Transport = Micropub.urlSessionTransport, ) async -> Micropub.Outcome { + // brief-28: identity — the open session must target THIS library's + // selected piece (Home, ID); the wire below reads the session's OWN + // library, never the current Home's same-slug file. The completion + // stamp targets the same captured pair — the piece actually sent, + // wherever the writer has since pointed the app. guard let session, let id = session.postID, + let home = watchedHome, id == selectedPostID, + session.targets(postID: id, home: home), draft == nil, externalSession == nil, outlineGuardPieceID == nil @@ -267,8 +274,7 @@ extension PostsModel { // name) and the frontmatter-stripped body (the stamp is // bookkeeping, never prose; the body itself is never stripped, // GLOSSARY). No scan dependency: the list can lag the open piece. - guard let home = watchedHome, - let dir = PostStore.folder(of: id, home: home), + guard let dir = PostStore.folder(of: id, home: home), let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8) else { return .refused("Couldn't read the piece before sending.") diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 5f60072..ec74ac5 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -154,6 +154,11 @@ final class PostsModel { /// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed /// post.md files, not the library (see PostScanCache). let scanCache = PostScanCache() + /// brief-28: the card scanner behind `refreshCards` — injectable so the + /// stale-result pin can HOLD an old-library scan past a repoint (a + /// detached disk read is otherwise faster than any test can arrange). + /// Per-model, never static (the hosted suite runs tests in parallel). + var scanPieceCards: @Sendable (URL) -> [FixCardStore.StoredFixCard] = FixCardStore.scan /// #93: per-file watcher on the open external file — the #67 conflict /// check reused verbatim for foreign files. var externalWatcher = PostsWatcher() @@ -260,7 +265,9 @@ final class PostsModel { // guarded one: the piece is open under a prior answer, and firing // the ask again would nil its session without teardown (the armed // debounce would then flush mid-ask, outside any owned session). - if let session, session.postID == id { + // brief-28: identity, not id — only THIS library's piece counts as + // open; a session born under another Home departs below. + if let session, let home = watchedHome, session.targets(postID: id, home: home) { return } if let session { @@ -306,9 +313,10 @@ final class PostsModel { if externalSession != nil { return true } - guard let session, session.postID == selectedPostID else { return false } - let outline = session.postID != proseOverridePostID - && (lastDraftWasOutline || posts.first(where: { $0.id == session.postID })?.type == .outline) + // brief-28: this library's piece, by identity (Home, ID). + guard let session, let id = selectedPostID, openSessionTargets(id) else { return false } + let outline = id != proseOverridePostID + && (lastDraftWasOutline || posts.first(where: { $0.id == id })?.type == .outline) return !outline } @@ -322,7 +330,7 @@ final class PostsModel { if let externalSession { return externalSession.text } - if let session, session.postID == selectedPostID { + if let session, let id = selectedPostID, openSessionTargets(id) { // brief-28: this library's piece, by identity return session.text } return nil diff --git a/Museion/PostsModelCards.swift b/Museion/PostsModelCards.swift index 9bc303f..c7e6a80 100644 --- a/Museion/PostsModelCards.swift +++ b/Museion/PostsModelCards.swift @@ -20,9 +20,14 @@ extension PostsModel { /// transitions — the piece-roots watcher already fires on cards/ writes. /// #122: the same pass also derives `openPieceHasSnapshot` (the Blind /// Read's base) — one detached read of the open piece's disk facts. + /// brief-28: identity at BOTH ends. At launch the open session must + /// target (watchedHome, id) — a session born under another Home has no + /// cards here. At COMPLETION the re-check is identity too: the old + /// ID-only guard let a scan started under the previous library land its + /// cards on the new library's same-slug piece after a repoint. func refreshCards() { - guard let id = session?.postID, - let home = watchedHome, + guard let session, let id = session.postID, let home = watchedHome, + session.targets(postID: id, home: home), // brief-28 let folder = PostStore.folder(of: id, home: home) else { openPieceCards = [] @@ -31,13 +36,15 @@ extension PostsModel { } // Plain disk reads re-run on every watcher burst (typing retriggers // rescan) — keep the I/O off MainActor, same posture as rescan's - // Post.scan. The id re-check on hop-back drops a scan that raced a - // piece switch. + // Post.scan. The identity re-check on hop-back drops a scan that + // raced a piece switch or a Home repoint. + let scan = scanPieceCards // detached capture, not a property read Task.detached { [weak self] in - let cards = FixCardStore.scan(pieceURL: folder) + let cards = scan(folder) let hasSnapshot = PostStore.latestPassSnapshot(id: id, home: home) != nil await MainActor.run { [weak self] in - guard let self, session?.postID == id else { return } + // brief-28: (Home, ID) at completion, never the id alone. + guard let self, self.session?.targets(postID: id, home: home) == true else { return } openPieceCards = cards openPieceHasSnapshot = hasSnapshot } diff --git a/Museion/PostsModelIdentity.swift b/Museion/PostsModelIdentity.swift new file mode 100644 index 0000000..26be0cf --- /dev/null +++ b/Museion/PostsModelIdentity.swift @@ -0,0 +1,25 @@ +// +// PostsModelIdentity.swift +// Museion +// +// brief-28 (home-repoint-retains-old-editor-target): document identity for +// the open session. Every "is this piece open" question in the model +// routes through here — select, the structural rail, the pass guard, the +// card refresh, Micropub. The bare `session.postID == id` comparison is +// retired: two libraries can hold the same slug, and the id alone matched +// a session retained from another library (the repoint finding's seam). +// + +import Foundation + +extension PostsModel { + /// brief-28: is the open session THIS library's piece `id`? Identity is + /// (Home, ID) — `watchedHome` is the Home half, so the answer is "the + /// buffer belongs to the piece the current library lists under that id". + /// A session born under another Home (or an external guest) is never + /// the open piece, whatever its id says; nothing bound = nothing open. + func openSessionTargets(_ id: String) -> Bool { + guard let session, let home = watchedHome else { return false } + return session.targets(postID: id, home: home) + } +} diff --git a/Museion/PostsModelOutline.swift b/Museion/PostsModelOutline.swift index 8fee1b6..75564ee 100644 --- a/Museion/PostsModelOutline.swift +++ b/Museion/PostsModelOutline.swift @@ -67,13 +67,15 @@ extension PostsModel { /// this one open body. func openUnguarded(_ id: String) { guard let home = watchedHome, dismissExternal() else { return } // brief-25: the guest's edits land or the open aborts - if let session, session.postID != id { + // brief-28: identity — a session born under another Home is never + // "the same piece", whatever its id says; it departs here too. + if let session, !session.targets(postID: id, home: home) { // brief-25: a failed flush (or an unanswered #67 conflict) // aborts here — the dirty session stays up and honest. guard sessionMayDepart(session) else { return } session.teardown(flushFirst: false) // the gate already flushed } - session = id == session?.postID ? session : EditorSession(postID: id, home: home) + session = session?.targets(postID: id, home: home) == true ? session : EditorSession(postID: id, home: home) draft = nil pendingProject = nil lastDraftWasOutline = false @@ -101,7 +103,7 @@ extension PostsModel { /// for prose typed since the last flush (#114 audit). func stageConversion(_ post: Post) { guard post.type == .outline else { return } - let body: String = if let session, session.postID == post.id { + let body: String = if let session, openSessionTargets(post.id) { // brief-28: identity session.text } else if let home = watchedHome { PostStore.readBody(id: post.id, home: home) ?? "" @@ -143,9 +145,9 @@ extension PostsModel { } performWrite { home in try PostStore.convert(id: pending.id, headingsLadder: headingsLadder, home: home) - if session?.postID == pending.id { - session?.teardown(flushFirst: false) // flushOrAbort already wrote - session = nil + if let session, openSessionTargets(pending.id) { // brief-28: identity + session.teardown(flushFirst: false) // flushOrAbort already wrote + self.session = nil proseOverridePostID = pending.id openUnguarded(pending.id) } diff --git a/Museion/PostsModelPasses.swift b/Museion/PostsModelPasses.swift index cbd93fc..d0eb11f 100644 --- a/Museion/PostsModelPasses.swift +++ b/Museion/PostsModelPasses.swift @@ -19,12 +19,13 @@ extension PostsModel { /// Read, named honestly whichever runner asks), the mentor not /// mid-reply with its engine ready, and an open SAVED piece (never a /// draft, the external guest, or a held #111 guard ask). The refusal - /// lands in lastError naming the blocker; answers the open piece's id - /// and session — the run's target — or nil (refused). - func guardOpenPieceRun( - _ action: String, - mentor: MentorSessionModel, - ) -> (id: String, session: EditorSession)? { + /// lands in lastError naming the blocker; answers the open piece's id, + /// session and Home — the run's target — or nil (refused). + /// brief-28: identity — the open session must target THIS library's + /// selected piece (Home, ID); a session born under another Home never + /// runs (its snapshot/stats/lint would land in the wrong library). + // swiftlint:disable:next large_tuple + func guardOpenPieceRun(_ action: String, mentor: MentorSessionModel) -> (id: String, session: EditorSession, home: URL)? { guard runningPass == nil else { lastError = "A pass is already running." return nil @@ -43,7 +44,9 @@ extension PostsModel { } guard let session, let id = session.postID, + let home = watchedHome, id == selectedPostID, + session.targets(postID: id, home: home), // brief-28 draft == nil, externalSession == nil, outlineGuardPieceID == nil @@ -51,7 +54,7 @@ extension PostsModel { lastError = "Open a saved post to run \(action)." return nil } - return (id, session) + return (id, session, home) } } @@ -64,7 +67,7 @@ extension PostsModel { /// and never when fix cards resolve. Passes run in any order /// (advancePassState is monotonic). func runPass(_ kind: PassKind, mentor: MentorSessionModel) async { - guard let (id, session) = guardOpenPieceRun("a pass", mentor: mentor) else { return } + guard let (id, session, home) = guardOpenPieceRun("a pass", mentor: mentor) else { return } // #137 (S4): the pass profile's provider has no key — name it and // point at Settings. Nothing has touched disk yet (the snapshot // comes after this guard). @@ -73,8 +76,8 @@ extension PostsModel { return } guard flushOrAbort(id) else { return } // the engine reads disk - // #179: the model owns the Home; an open piece implies a bound one. - guard let home = watchedHome else { return } + // #179: the model owns the Home — the guard answered the session's + // OWN library (brief-28 identity); every write below lands there. do { try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home) } catch { @@ -137,12 +140,11 @@ extension PostsModel { /// the transient transcript and die with it. The writer stays judge of /// record. func blindRead(mentor: MentorSessionModel) async { - guard let (id, session) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return } + guard let (id, session, home) = guardOpenPieceRun("a Blind Read", mentor: mentor) else { return } guard flushOrAbort(id) else { return } - // #179: the model owns the Home; an open piece implies a bound one. - guard let home = watchedHome, - let base = PostStore.latestPassSnapshot(id: id, home: home) - else { + // #179: the model owns the Home — the guard answered the session's + // OWN library (brief-28 identity). + guard let base = PostStore.latestPassSnapshot(id: id, home: home) else { lastError = "No Pass snapshot yet — run a Pass first." return } diff --git a/Museion/PostsModelWatcher.swift b/Museion/PostsModelWatcher.swift index 6669176..3cd1791 100644 --- a/Museion/PostsModelWatcher.swift +++ b/Museion/PostsModelWatcher.swift @@ -67,11 +67,55 @@ extension PostsModel { /// scan + start (or restart) the watcher. Called from WorkspaceView's /// root `.task(id: museionHome)` — first frame and every Home repoint, /// pane-independent. + /// brief-28: the dumb binder — it flips `watchedHome` unconditionally. + /// A REPOINT reaches it only after `repoint(to:)` passed its departure + /// gate (the Settings binding runs the gate before committing the + /// preference; the `.task` fires after that commit). func bind(home: URL) { startWatching(home: home) Task { await rescan() } } + /// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is + /// a DOCUMENT DEPARTURE — the gate runs FIRST, the binding commits + /// after. The Settings path used to flip `watchedHome` under 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; a no-collision piece was torn down by the vanish + /// path with its dirty buffer dropped). + /// True = every open document landed through `sessionMayDepart` (the + /// three legs: unanswered #67, failed flush, never-loaded retype) and + /// the departed piece's state is cleared — the caller may bind the new + /// Home. False = `lastError` says why and NOTHING changed: the + /// preference stays A, `watchedHome` stays A, the session keeps its + /// (A, id) target and its buffer. No parallel gate — the same one + /// `select`/`newPost`/quit ride. + /// The in-memory draft survives: it has no Home until first save (#62) + /// and lands in the new library — the only alternative is dropping the + /// only copy. A running pass or Blind Read keeps its own completion + /// guard (#179: the advance refuses once `watchedHome` moved). + @discardableResult + func repoint(to newHome: URL) -> Bool { + guard newHome != watchedHome else { return true } // first bind / the same folder: nothing departs + guard departOpenDocuments() else { return false } + // The departed piece's state dies with it: a stale id under the new + // library is a ghost selection (a same-slug piece would read as + // open over an empty editor) and a stale ask would act on the new + // library's piece. Nothing auto-reopens — the writer picks from + // the new list (the reopen machinery stays where it is). + selectedPostID = nil + openPieceCards = [] + openPieceHasSnapshot = false + outlineGuardPieceID = nil + proseOverridePostID = nil + pendingConversion = nil + lastDraftWasOutline = false + pendingProject = nil + return true + } + private func startWatching(home: URL) { guard watchedHome != home else { return } watchedHome = home @@ -91,11 +135,16 @@ extension PostsModel { guard let home = watchedHome else { return } // Scan + the #67 disk read both run off-main (a synced large post.md // must never stall the UI on a watcher burst). - let openPostID = session?.postID // #114 audit: identity, not id — a same-id reopen (convert/restore/ // move) must not receive the OLD session's stale disk text as a // spurious #67 conflict. let openSession = session + // brief-28: the Home half of that identity — the open post's disk + // text is read from the session's OWN library. A session targeting + // another Home has no piece in this scan's tree; reading the + // current Home's same-slug file for it raised a spurious #67 on the + // old session. + let openPostID = openSession?.targets(home: home) == true ? openSession?.postID : nil let scanMemo = scanCache // detached capture, not a property read // The search's content signal: a re-read post.md (a cache miss) // changed library content even when its Post compares equal. Read @@ -108,6 +157,18 @@ extension PostsModel { return (posts, disk) }.value guard !Task.isCancelled else { return } + // Stale-scan guard (#137 suite find / finish): the snapshot can + // PREDATE the current selection, and a scan that outlived a Home + // repoint speaks for the OLD tree — bind's initial rescan (detached + // scan over the empty tree) can land its continuation after a + // select its scan never saw, "vanishing" a piece that exists, and a + // pre-repoint scan would land the old library's list under the new + // binding. Disk is the truth for vanished; a stale snapshot must + // not kill a live session (teardown cancels the debounce — + // unflushed edits would die with it); the new Home's own rescan + // owns everything (brief-28: hoisted — the list, the revision and + // the #67 text ride the same verdict, not just the vanish check). + guard watchedHome == home else { return } // #143: @Observable invalidates on assignment regardless of equality — // skip the no-op so panes don't regroup on our own autosave echoes. let listChanged = scanned != posts @@ -122,19 +183,9 @@ extension PostsModel { if listChanged || scanMemo.misses > missesBefore { contentRevision += 1 } - // Stale-scan guard (#137 suite find): the snapshot can PREDATE the - // current selection — bind's initial rescan (detached scan over the - // empty tree) can land its continuation after a select its scan never - // saw, "vanishing" a piece that exists. Disk is the truth for - // vanished; a stale snapshot must not kill a live session (teardown - // cancels the debounce — unflushed edits would die with it). - // #137 audit (finish): a scan that outlived a Home repoint speaks - // for the OLD tree — never let it kill a session selected under - // the NEW home (the id is missing from the old snapshot by - // construction); the next rescan under the new home owns it. - if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil { + if let id = selectedPostID, !posts.contains(where: { $0.id == id }), PostStore.folder(of: id, home: home) == nil { selectedPostID = nil // the post vanished (deleted in Finder or here) - if let open = session, open.postID == id { + if let open = session, open.targets(postID: id, home: home) { open.teardown(flushFirst: false) // post is gone; cancel the debounce session = nil } diff --git a/Museion/PostsModelWrites.swift b/Museion/PostsModelWrites.swift index 08802fb..68500a9 100644 --- a/Museion/PostsModelWrites.swift +++ b/Museion/PostsModelWrites.swift @@ -57,7 +57,7 @@ extension PostsModel { let moved = try PostStore.rename(post, to: title, home: home) if selectedPostID == post.id { selectedPostID = moved.id - if session?.postID == post.id { + if openSessionTargets(post.id) { // brief-28: identity session = EditorSession(postID: moved.id, home: home) wireSession() } @@ -74,7 +74,7 @@ extension PostsModel { try PostStore.trash(post, home: home) if selectedPostID == post.id { selectedPostID = nil - if let open = session, open.postID == post.id { + if let open = session, openSessionTargets(post.id) { // brief-28: identity open.teardown(flushFirst: false) session = nil } @@ -129,7 +129,9 @@ extension PostsModel { /// #33: internal — the Micropub draft flow (Micropub.swift) flushes /// through the same rail. func flushOrAbort(_ postID: String) -> Bool { - guard let session, session.postID == postID else { return true } + // brief-28: identity — only THIS library's open piece flushes here; a + // session born under another Home is not the caller's piece. + guard let session, openSessionTargets(postID) else { return true } return sessionMayDepart(session) } @@ -208,7 +210,7 @@ extension PostsModel { guard flushOrAbort(post.id) else { return } performWrite { home in try PostStore.move(post, to: project, home: home) - if session?.postID == post.id { + if openSessionTargets(post.id) { // brief-28: identity session = EditorSession(postID: post.id, home: home) wireSession() } @@ -226,7 +228,7 @@ extension PostsModel { if selectedPostID == post.id { selectedPostID = nil } - if let open = session, open.postID == post.id { + if let open = session, openSessionTargets(post.id) { // brief-28: identity open.teardown(flushFirst: false) // already flushed above session = nil } @@ -242,7 +244,7 @@ extension PostsModel { guard flushOrAbort(post.id) else { return } performWrite { home in try PostStore.restore(post, home: home) - if let open = session, open.postID == post.id { + if openSessionTargets(post.id) { // brief-28: identity session = EditorSession(postID: post.id, home: home) wireSession() } else { @@ -263,7 +265,7 @@ extension PostsModel { // invisible. dir − 1 = project dir (…/archive/), − 2 = root. guard let boundHome = watchedHome else { return } func openPieceInArchivedProject() -> String? { - guard let id = session?.postID, + guard let id = session?.postID, openSessionTargets(id), // brief-28: identity let projectDir = PostStore.folder(of: id, home: boundHome)?.deletingLastPathComponent(), projectDir.lastPathComponent == name, projectDir.deletingLastPathComponent().lastPathComponent == "archive" diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift index a126643..7ba362e 100644 --- a/Museion/WorkspaceView.swift +++ b/Museion/WorkspaceView.swift @@ -12,6 +12,7 @@ // WorkspaceChrome.swift; RailButton stays (the rail is its only caller). // +import AppKit import SwiftUI /// The post-gate main surface. Posts shows the full four-column workspace; @@ -248,6 +249,37 @@ struct WorkspaceView: View { ) } + /// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is a + /// document departure. The binding's setter IS the gate — + /// `repointMuseionHome` runs the departure gate first and commits the + /// preference (and its persistence) only when every open document + /// landed; the root `.task(id: museionHome)` binds the model after that + /// commit. A refusal keeps Home A and every buffer, and speaks the #198 + /// reason the way #200's quit refusal does — the Posts strip that shows + /// `lastError` is not in sight from Settings. + private var homeRepointBinding: Binding { + Binding( + get: { gate.museionHome }, + set: { newHome in + guard gate.repointMuseionHome(to: newHome) else { + presentRepointRefusal() + return + } + }, + ) + } + + /// Hosted tests never present (the quit refusal's guard convention). + private func presentRepointRefusal() { + guard !AppGateState.hostedTestRun else { return } + let alert = NSAlert() + alert.messageText = "Home not changed — a piece needs you first" + alert.informativeText = gate.posts.lastError + ?? "An open piece could not be saved. Tend to it, then choose the folder again." + alert.addButton(withTitle: "Back to Museion") + alert.runModal() + } + /// #151: the pill/card state — the gate's phase machine plus the /// provisioning failure verdict. private var statusVisibility: EngineStatusSurface.Visibility { @@ -259,7 +291,6 @@ struct WorkspaceView: View { @ViewBuilder private func paneContent(_ geo: GeometryProxy) -> some View { - @Bindable var gate = gate switch selection { case .posts: // #14: mentor column hands in the app-scoped model + gate's winner. @@ -303,8 +334,9 @@ struct WorkspaceView: View { // #137 (S4): a committed Chat model change restarts the resident // chat engine in place (slice A's engine-side API; deferred to // turn end while streaming). + // brief-28: the Home control binds through the repoint gate. SettingsPaneView( - home: $gate.museionHome, + home: homeRepointBinding, binaryPath: gate.gateModel.currentBinaryPath, onChatSurfaceWrite: { gate.mentor.requestRestart() }, ) diff --git a/MuseionTests/PostsModelRepointTests.swift b/MuseionTests/PostsModelRepointTests.swift index 346fb11..b561819 100644 --- a/MuseionTests/PostsModelRepointTests.swift +++ b/MuseionTests/PostsModelRepointTests.swift @@ -17,18 +17,35 @@ // (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), and a pass started after the repoint runs against the new -// library. +// 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. +// 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 { @@ -65,7 +82,17 @@ struct PostsModelRepointTests { #expect(model.session?.text == "# Shared\n\nA body\n") model.session?.edit("# Shared\n\nA body, typed in A\n") - model.bind(home: homeB) // the Settings repoint + // 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 @@ -91,7 +118,8 @@ struct PostsModelRepointTests { try denyWrites(to: pieceDir) defer { try? allowWrites(to: pieceDir) } - model.bind(home: homeB) // the Settings repoint + // 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. @@ -104,11 +132,13 @@ struct PostsModelRepointTests { #expect(model.lastError != nil) #expect(PostStore.readBody(id: "shared", home: homeB) == "# Shared\n\nB body\n") - // Writability restored → the edits land on A first, then the - // repoint goes through and departs the session. + // Writability restored → the edits land on A first (watchedHome + // still A until the binding commits), then the repoint departs. try allowWrites(to: pieceDir) - model.bind(home: homeB) + #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) @@ -121,7 +151,8 @@ struct PostsModelRepointTests { // #67: a foreign disk body arrived — the alert is up, unanswered. model.session?.diskDidChange(diskText: "foreign body from disk") - model.bind(home: homeB) // the Settings repoint + // The Settings repoint — refused. + #expect(model.repoint(to: homeB) == false) #expect(model.watchedHome == homeA) #expect(model.selectedPostID == "shared") @@ -147,7 +178,8 @@ struct PostsModelRepointTests { #expect(model.session?.loadFailed == true) model.session?.edit("# Retyped words over a file that never loaded") - model.bind(home: homeB) // the Settings repoint + // The Settings repoint — refused: the retype is the only copy. + #expect(model.repoint(to: homeB) == false) #expect(model.watchedHome == homeA) #expect(model.selectedPostID == "shared") @@ -161,13 +193,14 @@ struct PostsModelRepointTests { model.select("unique") model.session?.edit("# Unique\n\nA body, typed in A\n") - model.bind(home: homeB) // the Settings repoint - - // The old session's edits landed on A BEFORE anything moved — the - // vanish path used to tear it down without a flush. + // 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) @@ -175,6 +208,44 @@ struct PostsModelRepointTests { #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() } @@ -187,7 +258,9 @@ struct PostsModelRepointTests { model.select("shared") #expect(model.session?.text == "# Shared\n\nA body\n") - model.bind(home: homeB) // the Settings repoint + // 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") diff --git a/MuseionTests/PostsModelTests.swift b/MuseionTests/PostsModelTests.swift index 0d7542f..c6f322b 100644 --- a/MuseionTests/PostsModelTests.swift +++ b/MuseionTests/PostsModelTests.swift @@ -579,7 +579,10 @@ struct PostsModelWriteRailTests { let homeB = FileManager.default.temporaryDirectory .appendingPathComponent("repoint-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: homeB, withIntermediateDirectories: true) - rig.model.bind(home: homeB) // the Settings repoint, mid-pass + // the Settings repoint, mid-pass — brief-28: gate first (the open + // piece departs cleanly), then the binding commits. + #expect(rig.model.repoint(to: homeB)) + rig.model.bind(home: homeB) // Release the held turn as a NORMALLY ended one — .ended + no refusal. // Poll for the PARK first: runningPass flips before the one-shot // engine spawns, so ending the hold in that window false-fails