Merge pull request 'museion/library-search: test coverage + injectable seam for landed #144' (#157) from feat/library-search into main
CI / ci (push) Canceled after 0s

This commit was merged in pull request #157.
This commit is contained in:
AlexKucera committed 2026-11-04 09:04:59 +01:00
commit ef246e3f27
5 files changed
+146 -21

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
//
// LibrarySearch.swift
// Museion
//
// #144 (FEAT-004): the library search's pure core — extracted from the
// landed scan so ranking/partitioning is testable
// (MuseionTests/LibrarySearchTests.swift) while PostsLibraryColumn's
// structured .task stays the runtime path.
//
import Foundation
/// #144: the library search's pure core — title matches first, then body
/// matches, both halves preserving the scan's title order (#108: Finder
/// order, never re-sorted). nonisolated + the injected `@Sendable` reader
/// keep the seam pure: `bodyOf` is `PostStore.readBody` at the call site
/// (frontmatter never searched — stripping is readBody's contract).
nonisolated enum LibrarySearch {
/// The query is trimmed here; empty (or whitespace-only) matches
/// nothing — the caller renders the sectioned library instead.
static func results(
for query: String,
in candidates: [Post],
bodyOf: @Sendable (Post) -> String?,
) -> [Post] {
let needle = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !needle.isEmpty else { return [] }
let titleHits = candidates.filter { $0.title.localizedCaseInsensitiveContains(needle) }
let bodyHits = candidates.filter {
!$0.title.localizedCaseInsensitiveContains(needle)
&& (bodyOf($0) ?? "").localizedCaseInsensitiveContains(needle)
}
return titleHits + bodyHits
}
}
+10 -19
View File
@@ -315,10 +315,13 @@ struct PostsLibraryColumn: View {
}
}
/// #144: the title+body scan — title matches first (stable partition,
/// both halves keep the scan's Finder order), body via readBody
/// (frontmatter never searched); the per-piece cancellation check stops
/// a superseded sweep between files.
/// #144: the title+body scan — a thin mount for the pure
/// `LibrarySearch` seam (title matches first, stable partition, both
/// halves keep the scan's Finder order; body via readBody — frontmatter
/// never searched), pinned by MuseionTests/LibrarySearchTests.swift.
/// The reader's per-piece cancellation check stops a superseded sweep's
/// body reads between files; the in-memory title walk itself completes
/// cheaply and the caller's guard discards its result.
///
/// ponytail: full-body re-read per sweep (folder(of:) re-walked per
/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex
@@ -328,22 +331,10 @@ struct PostsLibraryColumn: View {
matching trimmed: String,
home: URL,
) async -> [Post] {
var byTitle: [Post] = []
var byBody: [Post] = []
for post in candidates {
if Task.isCancelled {
break
}
if post.title.localizedCaseInsensitiveContains(trimmed) {
byTitle.append(post)
continue
}
let body = PostStore.readBody(id: post.id, home: home) ?? ""
if body.localizedCaseInsensitiveContains(trimmed) {
byBody.append(post)
}
LibrarySearch.results(for: trimmed, in: candidates) { post in
guard !Task.isCancelled else { return nil }
return PostStore.readBody(id: post.id, home: home)
}
return byTitle + byBody
}
/// One piece row + its context menu — sections and search results
+91
View File
@@ -0,0 +1,91 @@
//
// LibrarySearchTests.swift
// MuseionTests
//
// #144 (FEAT-004): the library search's pure core — title-first ranking,
// body scan through the injected reader (PostStore.readBody at the call
// site), frontmatter never searched. The field itself is view-local.
//
import Foundation
@testable import Museion
import Testing
private func piece(_ id: String, title: String) -> Post {
Post(id: id, title: title, passState: .firstDraft, origin: .writer, type: .post, project: "posts", isArchived: false)
}
struct LibrarySearchTests {
@Test func `title matches rank ahead of body matches, scan order kept in both halves`() {
let titleHit1 = piece("a", title: "Alpha Quartz")
let bodyHit1 = piece("b", title: "Bravo")
let titleHit2 = piece("c", title: "Charlie Quartz")
let bodyHit2 = piece("d", title: "Delta")
let noHit = piece("e", title: "Echo")
let bodies = ["b": "mentions quartz once", "d": "QUARTZ again", "e": "nothing here"]
let found = LibrarySearch.results(for: "quartz", in: [titleHit1, bodyHit1, titleHit2, bodyHit2, noHit]) { bodies[$0.id] }
#expect(found.map(\.id) == ["a", "c", "b", "d"])
}
@Test func `body-only match reaches pieces whose titles stay silent`() {
let quiet = piece("quiet", title: "A Quiet Study")
let found = LibrarySearch.results(for: "quartz", in: [quiet]) { _ in "the quartz lamp flickered" }
#expect(found.map(\.id) == ["quiet"])
}
@Test func `a piece matching title and body appears once, in the title half`() {
let both = piece("both", title: "Quartz Notes")
let other = piece("other", title: "Other")
let found = LibrarySearch.results(for: "quartz", in: [other, both]) { $0.id == "both" ? "quartz body" : nil }
#expect(found.map(\.id) == ["both"])
}
@Test func `matching is case-insensitive on both fields`() {
let titled = piece("titled", title: "quartz harbor")
let found = LibrarySearch.results(for: "QUARTZ", in: [titled]) { _ in nil }
#expect(found.map(\.id) == ["titled"])
let bodied = piece("bodied", title: "Untitled")
let byBody = LibrarySearch.results(for: "HARBOR", in: [bodied]) { _ in "the harbor at dawn" }
#expect(byBody.map(\.id) == ["bodied"])
}
@Test func `empty or whitespace-only query matches nothing`() {
let anyPiece = piece("a", title: "Anything")
#expect(LibrarySearch.results(for: "", in: [anyPiece]) { _ in "Anything" }.isEmpty)
#expect(LibrarySearch.results(for: " \n\t ", in: [anyPiece]) { _ in "Anything" }.isEmpty)
}
@Test func `unreadable body never matches`() {
let anyPiece = piece("a", title: "Untitled")
#expect(LibrarySearch.results(for: "vanished", in: [anyPiece]) { _ in nil }.isEmpty)
}
@Test func `real readBody rail searches bodies, never frontmatter`() throws {
// Piece A carries "Pass-2 Done" ONLY in frontmatter (every piece's
// pass_state would match a raw-text scan); piece B carries the
// needle only in its body. Stripping is readBody's contract.
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("libsearch-\(UUID().uuidString)", isDirectory: true)
for (id, text) in [
"a-quiet-study": "---\npass_state: Pass-2 Done\n---\n\n# A Quiet Study\n\nProse only.",
"b-morning-pages": "---\n---\n\n# Morning Pages\n\nThe espresso machine hissed.",
] {
let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try text.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
let posts = Post.scan(home: home)
#expect(posts.count == 2)
let frontmatterOnly = LibrarySearch.results(for: "Pass-2 Done", in: posts) {
PostStore.readBody(id: $0.id, home: home)
}
#expect(frontmatterOnly.isEmpty)
let byBody = LibrarySearch.results(for: "espresso", in: posts) {
PostStore.readBody(id: $0.id, home: home)
}
#expect(byBody.map(\.id) == ["b-morning-pages"])
}
}
@@ -15,6 +15,8 @@ Ship FEAT-004 (Argus cycle-1 smallest-win, effort S): search across post titles
- `postRow(_:)` extracted (`LibraryPostRow` + full context menu) — sections and search results render the same row; results carry Rename/Convert/Move/Archive/Trash too.
- DOX closeout: `Museion/AGENTS.md` PostsPaneView entry gains the `**#144:**` line (field, debounce, off-main posture, frontmatter exclusion, ordering, both render surfaces).
- Verification: build SUCCEEDED; suite 574/574 (xcresult executed count); swiftformat idempotent; swiftlint adds zero error-severity violations.
- Rework (same day, 22:00 dispatch — the dispatched branch reduced onto this landing, no behavior change): `Museion/LibrarySearch.swift` extracts the pure core `results(for:in:bodyOf:)` (nonisolated enum, injected `@Sendable` reader) and `search()` mounts it inside the structured scan, shape unchanged — `.task(id: trimmedQuery)` untouched, per-piece cancellation now carried by the reader's `Task.isCancelled` guard (a superseded sweep's body reads stop between files; the in-memory title walk completes and the caller's guard discards its result).
- Rework verification: build SUCCEEDED (platform=macOS); targeted suite 7/7 (xcresult: totalTestCount 7, passed 7, failed 0, skipped 0 — real hosted runner); ranking flip (`bodyHits + titleHits`) fails exactly the ranking pin (6 passed / 1 failed), restored and re-verified 7/7; `swiftformat --lint` 0/3 files; swiftlint adds nothing (PostsPaneView.swift keeps its pre-existing `file_length` warning at 614 lines); full suite 588/589 — the single failure is `MuseionUITests.testAppLaunches` (activation flake: "Failed to activate application … (current state: Running Background)", reproduced twice, untouched target; the hosted unit tests — all 7 new pins included — ran green inside the launched app, so the launch path itself is proven).
## Decisions & Rationale
@@ -25,7 +27,7 @@ Ship FEAT-004 (Argus cycle-1 smallest-win, effort S): search across post titles
| `postRow(_:)` extraction | Search results lacked the context menu (Rename/Move/etc. unreachable from results); one row+menu source for both sites beats duplicating the menu block. |
| Stale-while-revalidate during debounce (`matches` nils only on clear) | Spec's exact code: later keystrokes keep showing prior results through the 250 ms window instead of a spinner flicker; ProgressView is the first-search state. |
| No `readBody` size gate | `Post.scan` already reads every post.md unbounded at startup — search adds no new exposure class; a gate would change shared-function behavior beyond this diff. Ceiling documented as a `ponytail:` note with the `PostScanCache`-style memo upgrade path (LearningsIndex posture). |
| No unit test for the filter | View-local state, no pure logic added — the spec's verification is manual smoke; the repo has no component-render harness (named unpinned delta in the audit report). |
| No unit test for the filter → superseded by the rework's seam + suite | Landing posture: view-local state, no pure logic added, no component-render harness (manual smoke). The rework extracts the pure core with an injected reader — ranking/partition/stripping are now pinned (`MuseionTests/LibrarySearchTests.swift`, 7 pins); the view layer stays untested per house convention. |
| Two `PostsLibraryColumn` instances (unfocused layout + focus reveal) keep separate query state | Matches #108's documented per-view `collapsed` posture; only one is alive at a time; AGENTS.md row promises availability, not shared state. Reviewer confirmed fine. |
## Gotchas & Fixes
@@ -37,6 +39,8 @@ Ship FEAT-004 (Argus cycle-1 smallest-win, effort S): search across post titles
| swiftlint gate exits 2 repo-wide | Pre-existing: 289 violations / 72 serious at HEAD, identical with the diff; earlier chained runs piped through `tail` masked the exit code | Proven pre-existing via stash control (same 289/72); named here and in the commit; my file adds zero errors |
| GitNexus `detect-changes` said "No changes detected" despite a dirty tree | Stale index after an earlier incremental analyze | Re-ran `analyze` (full, 5,820 nodes) → detect-changes then reported the true scope (`PostsLibraryColumn` + docs) |
| Review flag: comment claimed `.task(id:)` cancels the in-flight scan | `Task.detached` never receives parent cancellation — the prose promised an invariant the code didn't have | Structured-concurrency fix above; the comment is now true |
| Test source rejected as "Unprintable ASCII character" (held branch, LibrarySearchTests.swift:56:43) after earlier green runs | A JSON-transported patch rode a decoded TAB byte into the whitespace-query string literal — Swift rejects raw tabs in single-line string literals, and the transport decodes `\t`/`\n` escapes | The literal ships as the two-character `\t` escape (held-branch commit 7e75d53): compose Swift string-escape bytes via chr(92) when patching through JSON transports. The rework carries the fixed file byte-identical (blob 2368676) |
| Held branch's full-suite attempts dispatched ZERO tests ×3 (04:11–04:41: automation-mode timeout, runner hung before connection) | Three concurrent xcodebuild test runners (library-search + helm + vivarium) contending for testmanagerd — the #30 contention family | #134 lesson applied: stopped retrying, captured the seam runs before the wedge (7/7 at 02:13; flip run 1/7 as intended at 02:15). Channel recovered by 20:13 (review re-run 7/7); the rework's full suite ran clean apart from the UI-launch flake above |
## Files Changed
@@ -45,12 +49,16 @@ Ship FEAT-004 (Argus cycle-1 smallest-win, effort S): search across post titles
| `Museion/PostsPaneView.swift` | +164/−23: search state, field, results, empty state, structured scan, `postRow(_:)` extraction |
| `Museion/AGENTS.md` | `**#144:**` line on the PostsPaneView entry (DOX closeout) |
| `AGENTS.md` | write-log window refresh + gitnexus index-stats churn |
| `Museion/LibrarySearch.swift` | rework: the pure seam extracted from the scan (nonisolated enum, injected reader) |
| `Museion/PostsPaneView.swift` | rework: `search()` mounts the seam inside the structured task — no behavior change |
| `MuseionTests/LibrarySearchTests.swift` | rework: 7-pin suite, byte-identical from the held branch |
## Open Items & Next Steps
- [ ] Deferred: re-filter when a watcher rescan lands while a query sits unchanged (any keystroke refreshes; a later slice if it bites)
- [ ] Deferred: `folder(of:)` re-walk per piece per sweep — `PostScanCache`-style body memo if it ever measures hot (named in `search()`'s ponytail note; see the `local-store-caching` skill)
- [ ] Manual smoke: type a known word into Search posts → flat match list; clear → sections return; right-click a result → full menu
- [ ] Held for consent: `Museion/AGENTS.md` + `MuseionTests/AGENTS.md` catalog entries for `LibrarySearch.swift` / `LibrarySearchTests.swift` (text in the branch handoff) — the implementation session's write-protection blocks AGENTS.md writes without a live user; apply or approve
---
+1 -1
View File
@@ -9,7 +9,7 @@ Complete history of session logs in this directory, newest first. One-line summa
| 2026-11-03 | issue | [20261103-issue58-voice-payload-landed_log.md](20261103-issue58-voice-payload-landed_log.md) | #58: Swadia VOICE payload — new owned-insight skill, retelling/next-line cards, interview-first stance, allocation row P1 10 · P2 9 · Chat 11 |
| 2026-11-03 | issue | [20261103-issue147-app-target-lint-clean-five-error-spots_log.md](20261103-issue147-app-target-lint-clean-five-error-spots_log.md) | #147: last five lint error spots — sidecar to extension, renames, guard wraps, PostStoreTests split; two flaky-test root causes fixed |
| 2026-11-03 | issue | [20261103-issue146-postsmodel-split-under-lint-ceilings_log.md](20261103-issue146-postsmodel-split-under-lint-ceilings_log.md) | #146: PostsModel split under lint ceilings — six extensions to three domain files, watcher to file-scope extension; pure move, 574 green |
| 2026-11-03 | issue | [20261103-issue144-library-search-across-titles-and-bodies_log.md](20261103-issue144-library-search-across-titles-and-bodies_log.md) | #144: library search — trimmed-id debounce, structured off-main body scan (audit: detached → nonisolated), postRow menu for results |
| 2026-11-03 | issue | [20261103-issue144-library-search-across-titles-and-bodies_log.md](20261103-issue144-library-search-across-titles-and-bodies_log.md) | #144: library search — trimmed-id debounce, structured off-main body scan (audit: detached → nonisolated), postRow menu for results; rework: LibrarySearch seam + 7-pin suite |
| 2026-11-03 | issue | [20261103-issue143-scan-parse-cache-incremental-rescan_log.md](20261103-issue143-scan-parse-cache-incremental-rescan_log.md) | #143: path+mtime+size parse memo — rescans re-read only changed post.md; pre-read stamp closes the overlap race; equality-gated posts assignment |
| 2026-11-03 | issue | [20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md](20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md) | #142: single-line edits re-key folds in place; chrome becomes per-glyph layers — no more per-keystroke full-document restyle/raster |
| 2026-11-02 | issue | [20261102-issue141-image-drop-illustration-ingest_log.md](20261102-issue141-image-drop-illustration-ingest_log.md) | Image drop → assets/ ingest at drop point; window-destination routing, firstRect viewport-band solve, finish-audit fixes |