From c0cd60b79809dc6641fa49cd7968c807d4a9c39b Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 11 Nov 2026 22:19:01 +0100 Subject: [PATCH 1/3] test(search): red pin for snapshot invalidation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The mounted search snapshot is keyed only to the trimmed query, so library mutations never restart the sweep: archived/trashed rows linger in the results and edited bodies never enter them until the query changes or the view remounts. Pin the invalidation contract at controller level, the way the pure seam is pinned: LibrarySearch.SearchKey (query + Home + the model's content revision) and the LibrarySearch.Snapshot isFresh gate decide whether a landed sweep may render. The rail pins drive the real rescan path and prove archive, trash, and a same-query body edit each move PostsModel.contentRevision. The property is a stub here — never bumped — so those three pins fail red on this commit. --- Museion/LibrarySearch.swift | 27 +++++++ Museion/PostsModel.swift | 9 +++ MuseionTests/LibrarySearchTests.swift | 110 ++++++++++++++++++++++++++ 3 files changed, 146 insertions(+) diff --git a/Museion/LibrarySearch.swift b/Museion/LibrarySearch.swift index 4ab1e3a..6db7338 100644 --- a/Museion/LibrarySearch.swift +++ b/Museion/LibrarySearch.swift @@ -32,4 +32,31 @@ nonisolated enum LibrarySearch { } return titleHits + bodyHits } + + /// #144 (mounted half): the identity of one search sweep — the + /// trimmed query, the Home it ran under, and the library content + /// revision it saw (`PostsModel.contentRevision`). The column's + /// `.task(id:)` re-keys on ANY difference, so a keystroke, a Home + /// repoint, or a library write that landed after the last sweep + /// restarts it instead of serving the stale snapshot. + nonisolated struct SearchKey: Equatable { + var query: String + var homePath: String + var revision: Int + } + + /// #144 (mounted half): one landed sweep — the results plus the key + /// that produced them. `isFresh` is the column's stale gate: results + /// render only under the key that computed them, so an archived, + /// trashed, renamed, or since-edited library drops to the recompute + /// state, never stale rows. + nonisolated struct Snapshot: Equatable { + var key: SearchKey + var results: [Post] + + /// A snapshot renders only under its own key. + func isFresh(for key: SearchKey) -> Bool { + self.key == key + } + } } diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 562ba8b..142dd15 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -96,6 +96,15 @@ final class PostsModel { /// all times (#107). private(set) var posts: [Post] = [] + /// #144 (mounted half): the library content revision — the search + /// snapshot's invalidation signal. The rescan rail bumps it whenever + /// a scan sees the library change: a Post-list change OR any re-read + /// post.md (a body-only edit compares equal as a Post — #143's skip + /// keeps the list still — yet the search must re-sweep). The `posts` + /// assignment skip stays untouched: panes never regroup on bumps, + /// only the mounted search re-keys. + private(set) var contentRevision = 0 + /// The selected Post's id; nil = nothing selected (empty editor). /// #146: setter internal — the split-out domain extensions set it. var selectedPostID: String? diff --git a/MuseionTests/LibrarySearchTests.swift b/MuseionTests/LibrarySearchTests.swift index 2368676..5130730 100644 --- a/MuseionTests/LibrarySearchTests.swift +++ b/MuseionTests/LibrarySearchTests.swift @@ -89,3 +89,113 @@ struct LibrarySearchTests { #expect(byBody.map(\.id) == ["b-morning-pages"]) } } + +/// #144 (mounted half): the snapshot invalidation the pure seam can't +/// see — PostsLibraryColumn keys its `.task(id:)` to query + Home + +/// `PostsModel.contentRevision` and renders a landed snapshot only +/// while it `isFresh` for the CURRENT key. The controller pins drive +/// the real rescan rail (write verbs + the rail's own rescan Task) and +/// prove archive, trash, and a same-query body edit each move the +/// revision — without that signal a standing snapshot outlives the +/// library it searched (archived rows linger in the results; edited +/// bodies never enter or leave them until the query changes). +@Suite("library search snapshot invalidation") +struct LibrarySearchSnapshotTests { + @Test func `a snapshot renders only under the key that computed it`() { + let swept = LibrarySearch.Snapshot( + key: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 4), + results: [piece("a", title: "Quartz Harbor")], + ) + #expect(swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 4))) + #expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "harbor", homePath: "/users/a/museion", revision: 4))) + #expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/b/museion", revision: 4))) + #expect(!swept.isFresh(for: LibrarySearch.SearchKey(query: "quartz", homePath: "/users/a/museion", revision: 5))) + } + + /// The sweep a mounted column would have landed before the archive: + /// key = (query, home, revision at sweep time), results from the + /// real seam + readBody rail. + @MainActor + private func standingSweep(_ model: PostsModel, home: URL, query: String) -> LibrarySearch.Snapshot { + LibrarySearch.Snapshot( + key: LibrarySearch.SearchKey(query: query, homePath: home.path, revision: model.contentRevision), + results: LibrarySearch.results(for: query, in: model.posts.filter { !$0.isArchived }) { + PostStore.readBody(id: $0.id, home: home) + }, + ) + } + + @Test @MainActor func `archiving a result invalidates the standing snapshot`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Quartz Harbor\n\nthe quartz lamp", home: home) + try await pollUntil { model.posts.contains { $0.id == post.id } } + let standing = standingSweep(model, home: home, query: "quartz") + #expect(standing.results.map(\.id) == [post.id]) // the sweep found it + + model.archivePost(post) + try await pollUntil { model.posts.contains { $0.id == post.id && $0.isArchived } } + + // Same query, same Home — the library moved under the sweep. + #expect(!standing.isFresh(for: LibrarySearch.SearchKey( + query: "quartz", + homePath: home.path, + revision: model.contentRevision, + ))) + } + + @Test @MainActor func `trashing a result invalidates the standing snapshot`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Quartz Harbor\n\nthe quartz lamp", home: home) + try await pollUntil { model.posts.contains { $0.id == post.id } } + let standing = standingSweep(model, home: home, query: "quartz") + #expect(standing.results.map(\.id) == [post.id]) + + model.trash(post) + try await pollUntil { !model.posts.contains { $0.id == post.id } } + + #expect(!standing.isFresh(for: LibrarySearch.SearchKey( + query: "quartz", + homePath: home.path, + revision: model.contentRevision, + ))) + } + + @Test @MainActor func `a same-query body edit invalidates the standing snapshot`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Quiet Study\n\nplain body", home: home) + try await pollUntil { model.posts.contains { $0.id == post.id } } + let standing = standingSweep(model, home: home, query: "quartz") + #expect(standing.results.isEmpty) // nothing matches yet + + // The body gains the needle with NO Post metadata change — the + // #143 equality skip's blind spot: the list itself never moves. + let file = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false) + try PostFrontmatter.stamped( + body: "# Quiet Study\n\nthe quartz lamp", passState: .firstDraft, origin: .writer, type: .post, + ).write(to: file, atomically: true, encoding: .utf8) + let before = model.posts + await model.rescan() + + #expect(model.posts == before) // metadata equal — the scan's skip held + let reswept = LibrarySearch.results(for: "quartz", in: model.posts.filter { !$0.isArchived }) { + PostStore.readBody(id: $0.id, home: home) + } + #expect(reswept.map(\.id) == [post.id]) // a fresh sweep WOULD find it now + #expect(!standing.isFresh(for: LibrarySearch.SearchKey( + query: "quartz", + homePath: home.path, + revision: model.contentRevision, + ))) + } + + @Test @MainActor func `an unchanged rescan keeps the revision`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Settled\n", home: home) + try await pollUntil { model.posts.contains { $0.id == post.id } } + let settled = model.contentRevision + + await model.rescan() // nothing changed since the last scan — all cache hits + + #expect(model.contentRevision == settled) + } +} From becad458838c7e8bf1daf723b4980283bdfebf3a Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 11 Nov 2026 22:20:14 +0100 Subject: [PATCH 2/3] fix(search): re-key sweep on Home and content revision MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The snapshot's only task identity was the trimmed query, so library mutations never restarted the sweep: archived and trashed rows kept rendering in the results, and renamed, new, or since-edited pieces never entered them until the query changed or the view remounted. Extend the #179 write rail's rescan with the missing signal: every scan that changes the Post list OR re-reads any post.md (a body-only edit compares equal as a Post — #143's skip) bumps PostsModel.contentRevision. Key the mounted sweep to the full LibrarySearch.SearchKey (query + Home + revision) and gate rendering on Snapshot.isFresh, so a landed sweep drops to the recompute state the moment the library moves under it. The posts-assignment skip stays: panes never regroup on the bumps, only the search re-keys. --- Museion/PostsModel.swift | 16 +++++++++++++- Museion/PostsPaneView.swift | 43 ++++++++++++++++++++++++++++--------- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 142dd15..c49ca93 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -721,6 +721,11 @@ extension PostsModel { // spurious #67 conflict. let openSession = session 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 + // the counter before the scan so the delta after it says "this + // scan saw disk change" (#144's mounted half). + let missesBefore = scanMemo.misses let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { let posts = Post.scan(home: home, cache: scanMemo) let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } @@ -729,9 +734,18 @@ extension PostsModel { guard !Task.isCancelled else { return } // #143: @Observable invalidates on assignment regardless of equality — // skip the no-op so panes don't regroup on our own autosave echoes. - if scanned != posts { + let listChanged = scanned != posts + if listChanged { posts = scanned } + // #144's mounted half: any list change OR any re-read file bumps the + // content revision — the search snapshot's invalidation signal. + // Archive/trash/rename arrive as list changes; a body-only edit as + // a cache miss (metadata-equal — the skip above keeps the panes + // still, the bump alone re-keys the mounted search). + 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 diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift index 84700e6..5825b6b 100644 --- a/Museion/PostsPaneView.swift +++ b/Museion/PostsPaneView.swift @@ -197,7 +197,11 @@ struct PostsLibraryColumn: View { /// #144: the library search — live title+body filter over the /// non-archived pieces. nil = not searching (sections render). @State private var query = "" - @State private var matches: [Post]? + /// #144 (mounted half): the landed sweep — results plus the key that + /// computed them. nil = not searching or recomputing (the sections / + /// spinner states); a snapshot that isn't `isFresh` for the current + /// key never renders. + @State private var snapshot: LibrarySearch.Snapshot? /// r5 (argon#44, mercury#52, sol#37): focus state for the field's /// accent ring. r8 (argon#6, mercury#12 — root cause found): the r6/r7 /// onAppear-unfocus could never work — the launch focus is AppKit @@ -211,6 +215,16 @@ struct PostsLibraryColumn: View { query.trimmingCharacters(in: .whitespacesAndNewlines) } + /// #144 (mounted half): the sweep's identity — trimmed query, the + /// Home, and the library content revision (`PostsModel.contentRevision`, + /// bumped by the rescan rail on any list change or re-read body). The + /// `.task(id:)` below re-keys on ANY difference, so library writes and + /// Home repoints restart the sweep instead of leaving stale rows; the + /// landed snapshot renders only while `isFresh` for the current key. + private var searchKey: LibrarySearch.SearchKey { + LibrarySearch.SearchKey(query: trimmedQuery, homePath: home.path, revision: model.contentRevision) + } + private var isSearching: Bool { !trimmedQuery.isEmpty } @@ -236,11 +250,15 @@ struct PostsLibraryColumn: View { } searchField if isSearching { - if let matches { - if matches.isEmpty { + // #144 (mounted half): a landed sweep renders only while + // fresh for the CURRENT key — a library write that bumped + // the revision (archive, trash, rename, body edit) or a + // moved query drops to the recompute state, never stale rows. + if let snapshot, snapshot.isFresh(for: searchKey) { + if snapshot.results.isEmpty { searchEmptyState } else { - searchResults(matches) + searchResults(snapshot.results) } } else { ProgressView() @@ -329,21 +347,26 @@ struct PostsLibraryColumn: View { // nonisolated search() runs the disk reads off MainActor while // staying inside this task, so a superseding keystroke or clear // cancels the sweep between pieces (the in-flight file read - // always finishes — readBody is synchronous). - .task(id: trimmedQuery) { - guard !trimmedQuery.isEmpty else { - matches = nil + // always finishes — readBody is synchronous). Keyed to the full + // search key: a library write (revision bump) or a Home repoint + // restarts the sweep too. The snapshot lands under the key + // captured at start; a mid-sweep key change cancels here, and + // even a raced assignment can't render — body gates on isFresh. + .task(id: searchKey) { + let key = searchKey + guard !key.query.isEmpty else { + snapshot = nil return } try? await Task.sleep(for: .milliseconds(250)) guard !Task.isCancelled else { return } let found = await librarySearch( candidates: model.posts.filter { !$0.isArchived }, - matching: trimmedQuery, + matching: key.query, home: home, ) guard !Task.isCancelled else { return } - matches = found + snapshot = LibrarySearch.Snapshot(key: key, results: found) } } From 93d97f2e35cde1b25204d142be5b42b3e924c087 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 11 Nov 2026 22:21:46 +0100 Subject: [PATCH 3/3] docs(devlog): library search stale-after-mutation fix Session log + INDEX row + CHANGELOG entry for the snapshot invalidation fix: the rescan-rail content revision and the mounted key/gate, with the red-first verification trail. --- CHANGELOG.md | 2 ++ ...library-search-stale-after-mutation_log.md | 27 +++++++++++++++++++ docs/devlog/INDEX.md | 1 + 3 files changed, 30 insertions(+) create mode 100644 docs/devlog/20261111-fix-library-search-stale-after-mutation_log.md diff --git a/CHANGELOG.md b/CHANGELOG.md index fceb4e6..3e8aad9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Fixed +- **search:** Library search results no longer go stale after library writes (finding `museion/library-search-stale-after-mutation`, the #144/#157 mounted gap) — the search snapshot's only task identity was the trimmed query, so nothing re-ran the sweep when the library moved underneath it: archiving or trashing a piece from a result row's own context menu left it sitting in the non-archived results after the rescan, and new, renamed, or externally edited pieces never entered or left the results until the query changed or the pane remounted. The #179 write rail's rescan now bumps a content revision whenever a scan sees the library change — a Post-list change OR any re-read post.md, so a body-only edit (which parses to an equal Post and is invisible to #143's equality-gated assignment) counts — and the mounted sweep keys on query + Home + that revision, rendering a landed snapshot only while it stays fresh for the current key (stale rows drop to the recompute spinner; panes never regroup — the assignment skip is untouched). +5 tests (pure key/gate pin; controller-level archive, trash, and same-query body-edit pins over the real rescan rail, red-first; an unchanged-rescan guard). Suite 686 + - **session:** a deferred nil scope drains as an explicit clear (PR #184, finding class #176) — `pendingScopePieceTitle: String?` let "a scope request is pending" and "which piece it targets" ride the same optionality, so a nil-target request (the writer leaves the piece mid-stream or mid-replay: New Post, unsaved draft, external guest, nothing open) deferred correctly but at drain time read as "no pending request" and returned without touching `activeEntry` — the old piece's conversation stayed live under a nothing-open context, at all four drain sites. Pending-ness now rides `PendingScope` (`.none` | `.scope(String?)`): a nil target is an explicit clear everywhere it drains. Finish-audit fanout (3 reviewers): dead `Equatable` cut, the same-turn `pendingRestart` ceiling documented at the drain (the scope is lost in respawn's `.starting` window — consume-at-apply is the upgrade path), and the titled-apply half pinned for the first time over a new `hangOnPromptLoad` rig mode (prompt parks, load answers; flip-verified). Suite 654 (PR #184) ### Changed diff --git a/docs/devlog/20261111-fix-library-search-stale-after-mutation_log.md b/docs/devlog/20261111-fix-library-search-stale-after-mutation_log.md new file mode 100644 index 0000000..18b7702 --- /dev/null +++ b/docs/devlog/20261111-fix-library-search-stale-after-mutation_log.md @@ -0,0 +1,27 @@ +# Library search snapshots invalidated by library writes — the #144/#157 mounted gap + +> **Date:** 2026-11-11 +> **Type:** fix (finding `museion/library-search-stale-after-mutation`; no Gitea ticket) +> **Reference:** #144 (library search), #157 (LibrarySearch seam + pure suite — mounted invalidation explicitly unpinned), #179 (the write rail this extends), #143 (the equality-gated `posts` assignment whose blind spot this closes) + +## Goal + +PostsPaneView's search stored a snapshot in `matches` but its only task identity was `trimmedQuery` (`.task(id: trimmedQuery)` at PostsPaneView.swift:333 on 5915178). Library mutations never re-keyed the task, so the sweep never re-ran: after Archive/Trash from a result row's own context menu, the archived post REMAINED in the non-archived search results even after `model.posts` rescanned; new, renamed, and externally edited matching pieces never entered or left the results until the query changed or the view remounted. Body-only changes had no signal at all — #143's equality-gated assignment keeps `posts` still when a rewritten post.md parses to an equal Post. + +## What Was Done + +- **The rail extension** (PostsModel.swift): `rescan()` now bumps `contentRevision` whenever a scan sees the library change — a Post-list change OR any re-read post.md (the scan cache's miss counter deltas across the detached scan; a miss is one disk read + parse). Archive/trash/rename arrive as list changes; a body-only edit arrives as a cache miss (metadata-equal — the #143 skip keeps the panes still; the bump alone re-keys the search). The `posts`-assignment skip is untouched: panes never regroup on autosave echoes, and an unchanged rescan (all cache hits) does not bump — pinned. +- **The mounted key + gate** (LibrarySearch.swift, pure seam): `LibrarySearch.SearchKey` (query, homePath, revision) and `LibrarySearch.Snapshot` (key + results) with `isFresh(for:)` — a landed sweep renders only under the key that computed it. +- **The view rewiring** (PostsPaneView.swift): the column's `.task(id:)` keys on the full `searchKey` (trimmed query + Home + `model.contentRevision`), so library writes and Home repoints restart the sweep; the task captures its key at start and lands the snapshot under it; body renders a snapshot only while `isFresh(for: searchKey)` — stale rows drop to the recompute spinner instead of lingering. A mid-sweep key change cancels at the existing `Task.isCancelled` guards, and even a raced assignment cannot render — the body-side gate refuses it. +- **Tests** (MuseionTests/LibrarySearchTests.swift, new `LibrarySearchSnapshotTests` suite): the pure key/gate pin, plus controller-level pins over the real rescan rail (`makeModelHome` + `pollUntil` convention) proving archive, trash, and a same-query body edit each move the revision through the standing-snapshot `isFresh` gate; a guard pin that an unchanged rescan keeps the revision. The three rail pins were committed red first (c0cd60b: 3 failed / 2 passed) and turned green with the fix (becad45: 5/5). + +Not done (out of scope): a render harness for the SwiftUI column itself — no UI automation per house style; the invalidation is observable at controller level, which is what the view consumes. + +## Verification + +- Baseline on pristine 5915178 (before any edit, after a stash): `xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' -derivedDataPath /dd-base -resultBundlePath /base.xcresult -only-testing:MuseionTests test` → ** TEST SUCCEEDED **, exit 0; xcresult summary: totalTestCount 681, result Passed. +- RED @ c0cd60b: same invocation with `-only-testing:MuseionTests/LibrarySearchSnapshotTests` → ** TEST FAILED **, exit 65; failedTests 3 (archive, trash, body-edit — exactly the briefed failure set), passedTests 2. +- GREEN focused @ becad45: same focused invocation → ** TEST SUCCEEDED **, exit 0; 5/5 passed, 0 failed. +- GREEN full @ becad45 (code head; the later docs commit adds no compiled code): full `-only-testing:MuseionTests` → ** TEST SUCCEEDED **, exit 0; xcresult summary: totalTestCount 686, passedTests 686, failedTests 0, skippedTests 0 (baseline 681 + the 5 new pins, zero confounds). +- swiftlint: 279 violations / 60 serious in 141 files at base; identical counts at the fix head (the two PostsModel warnings and one PostsPaneView file-length warning pre-exist, only their line counts grew). swiftformat: 0 files require formatting, touched and whole-tree. +- Known flake EditorSessionTests/debounce not encountered in either full run on this base. diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index cb448ad..076209e 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-11 | fix | [20261111-fix-library-search-stale-after-mutation_log.md](20261111-fix-library-search-stale-after-mutation_log.md) | Search snapshots re-key on Home + a rescan-rail content revision (list change OR re-read post.md — body-only edits included); stale rows drop to the recompute spinner (#144/#157 mounted gap) | | 2026-11-10 | follow-up | [20261110-issue179-followup-bind-root-task_log.md](20261110-issue179-followup-bind-root-task_log.md) | Bind hoisted to the WorkspaceView root task (stale watchedHome after repoint); PR #185 closed as superseded by 5bf0955 | | 2026-11-10 | issue | [20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md](20261110-pr184-deferred-empty-piece-scope-lost-audit_log.md) | PR #184 finish-audit: dead Equatable cut, restart-race ceiling named, titled-apply pin + hangOnPromptLoad rig mode | | 2026-11-10 | issue | [20261110-issue182-profilelayout-config-set-rail_log.md](20261110-issue182-profilelayout-config-set-rail_log.md) | ProfileLayout owns every profile path; HermesConfigRail owns the config-set CLI contract; audited, 684 green (#182) |