Files
museion/MuseionTests/LibrarySearchTests.swift
T
AlexKucera d7fd11cf0d
CI / ci (push) Canceled after 0s
chore(lint): repo-wide green becomes the contract
Close the lint arc #194-#197: deliberate-style rule disables with
rationales (#194), filter-safe test renames + --test-case-name-format
preserve (#195), every surviving warning fixed through the sanctioned
lint-stable shapes (#196), and the docs now state the true contract
(#197): bare swiftlint . reports zero violations and swiftformat .
reformats nothing, while push gates stay scoped to the push's own
files (settled #190 design) — the pre-push hook's stale 'pre-existing
violations' rationale blocks refreshed, gate logic untouched.

Also in the sweep: quiesce the FSEvent-burst watcher race in
LibrarySearchTests (two rescans double-count one shared PostScanCache
miss; benign revision over-bump), pin the learnings scan's symlink-skip
contract (flip-verified — defended in depth by the lstat guard AND
contentsOfDirectory's own symlink refusal), reorder that scan's guard
so cheap rejections precede the directory listing, and park the roster
chmod window with a ceiling comment.

Finish-audit: 3 reviewers, 0 blocking; the one code finding was
disproved by probe (&& out-binds ?? — the guard was correct). Suite
693/693 via scripts/full-test.sh; swiftlint 0 violations; swiftformat
0/141; hook rig 23/23.

Closes #197
2026-11-17 16:29:46 +01:00

216 lines
9.6 KiB
Swift

//
// 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"])
}
}
/// #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, and an unchanged rescan over a quiesced FSEvent burst
/// keeps it — 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 } }
// The FSEvent burst can still hold a sibling rescan that snapshotted
// its miss count BEFORE the landing scan stamped the shared
// PostScanCache — both count the same first read, each bumps the
// revision (#144's counter; an extra bump only over-invalidates a
// search snapshot). This pin is the SETTLED contract: wait out the
// burst (FSEvents latency is 0.5 s) before snapshotting.
var quiet = false
for _ in 0 ..< 20 where !quiet {
let seen = model.contentRevision
try await Task.sleep(nanoseconds: 500_000_000)
quiet = model.contentRevision == seen
}
#expect(quiet) // endless revision churn would never settle
let settled = model.contentRevision
await model.rescan() // nothing changed since the burst — all cache hits
#expect(model.contentRevision == settled)
}
}