Repository navigation
feat(ai-vault-search): session search indexer library owning backfill, reconcile and retention - #19751
Conversation
Review round 1 → bce6204, 7d2cda9An Opus adversarial review of 9667e6c found two HIGH, three MEDIUM, and two follow-ups on the bound commit. All fixed.
Verification (rerun by the lead): tc; ai-vault + ai-vault-search (725 tests); both changed-code gates; native audit. Mutations rerun by the lead: clearing the sweep flag before completion fails 1; removing the per-pass cutoff refresh fails 1; |
Review round 2 → ee4e52dSecond Opus round found that two round-1 fixes landed on the sweep path only; the 20 s reconcile cycle defeated both.
Verification (rerun by the lead): tc; ai-vault + ai-vault-search (730 tests); both changed-code gates; native audit. Mutations rerun by the lead: removing the root fence from the retirement function fails 3; settling by cursor movement instead of current stat fails 1. Held: the work loop under double start, throwing tasks, pause and close; the in-lane whole-read request; the title and first-prompt readers unchanged. |
Review round 3 → e4a509dThird Opus round: the round-2 fixes held (live-append settles and charges the tail; 50→5 is not a false alarm; return-to-store keeps the freshest stat and counts drops; a recent-window cycle cannot fake an empty root; no sidebar-facing file changed). Seven mutations, zero survivors. Two new findings, both fixed.
Behaviour note for PR 3b: a readable root that lists empty now retires on the second full sweep. Two explicit Verification (rerun by the lead): tc; ai-vault + ai-vault-search (736 tests); both changed-code gates; native audit. Mutations rerun by the lead: treating an unlistable root as empty fails 3; believing after one sweep fails 4; health on the joined label fails 1. |
Review round 4 → 506fdb2Fourth Opus round: round-3 fixes held (segment-bounded root ownership, symlink/WSL spellings cannot diverge, no sidebar-facing file changed). Three findings, all fixed.
Verification (rerun by the lead): tc; ai-vault + ai-vault-search (745 tests); both changed-code gates; native audit. Mutations rerun by the lead: seeding held-files from memory only fails 2; no tally reset on an unreadable sweep fails 1; string-prefix ownership fails 1. CI note: the |
Review round 5 → f51572dFifth Opus round ran a 22-cell lifecycle matrix (11 operations × ENOENT/EMPTY unmount, 2 roots × 3 files, sweep + cycle): 21 cells passed. The one failure and its fix:
Cost measured by the reviewer: Verification (rerun by the lead): tc; ai-vault + ai-vault-search (749 tests); both changed-code gates; native audit. Mutations rerun by the lead: arming the empty branch from memory only fails 1; no re-arm on recovery fails 1. CI note: |
Review round 6: converged.Sixth Opus round was a pure lifecycle matrix on Teeth check: stubbing the store's held-files query back to the memory-only form fails 24 cells (all 22 ENOENT cells = round 4's HIGH; both close/restart EMPTY cells = round 5's HIGH). The green is not vacuous. No new findings. Ready for a human read. Stays a draft until PR 2 merges and this rebases onto main. One observation outside this PR's diff, not routed here: |
Round 7 (simplicity + correctness adversary → rewrite) → 66f5c22, 63efba1, 57b7218Rounds 2 through 5 were one bug in four shapes: retiring rows because a root looked empty or missing. The root-health state machine that grew around it is deleted and replaced by a stateless rule, written as invariants at the top of
Net source delta for the rewrite: +909 / −469 across 16 files (the walk, per-pass listing cache, degraded-roots derivation, root recovery, backfill remainder, and registered-store are new small modules; the state machine is gone). The round-6 lifecycle matrix is now in the repo, 66 cells. Verification (rerun by the lead): tc; ai-vault + ai-vault-search (826 tests); both changed-code gates; native audit. Mutations rerun by the lead: walk always retires fails 80; |
Review round 8 (fresh adversary on the round-7 walk) → b7b2540, 1275dbeThe stateless walk held every attack: symlinked roots and transcripts, trailing-separator roots, prefix-sibling roots, a root or mid-tree component replaced by a file, a 60-deep path on one readdir, the 512 cap against the listing cache, OpenClaw's merged label, WSL UNC routing; the remainder loop converges with a plan six times its bound. Four findings landed in round-7 code around it:
Verification (rerun by the lead): tc; ai-vault + ai-vault-search (834 tests); both changed-code gates; native audit. Mutations rerun by the lead: flag cleared after the sweep fails 3; close ignoring an owed removal fails 7; synthetic rows proven as their container fails 1; deadline removed fails 1. |
1275dbe to
6a1bcfd
Compare
Round 9: immutable indexer (design change, user decision 2026-09-10) → rebased onto PR 2
|
6a1bcfd to
d3ff27c
Compare
Round 11: the store is the only memory (design v3, user decision 2026-09-10) → rebased onto PR 2
|
Round 12: final review, three HIGHs fixed → 084f568b89 (stop rule: HIGH-only, reproduced; the rest is in the plan doc's follow-ups)
Held under attack: close mid-pass then a new instance on the same path in the same tick; deletion under a root with an unverifiable sibling; deletion outside the recent window; deadline starvation; partial candidate sets; chunk-partial rows. Not routed (plan doc follow-ups): a decline resets Verification (rerun by the lead): tc; ai-vault + ai-vault-search (840 tests); both changed-code gates; native audit. Mutations rerun by the lead: cap counting rows again fails 3; claim before open fails 1; decline writing no row fails 1. |
There was a problem hiding this comment.
ℹ️ No blocking issues — one edge worth closing, noted inline.
Reviewed changes
SessionSearchIndexer, a library in src/main/ai-vault-search/ that owns freshness for PR 2's index: a full sweep plus a per-agent recency cycle on a timer, retention purge, stateless deletion-retirement and status reporting, built around "the store is the only memory" — three new files columns (state, fail_count, failed_mtime_ms; schema v5) replace the in-memory stale set, watch set and hold-out map, with a four-step pass, a pure sessionSearchReadDecision, a directory-capped retirement walk, and a work loop. It also touches one shared file: parseAgentSessionFileCached gains an optional requireRead lane (any/whole) so the index can force a whole read without a second spelling of the parse-cache check.
- Freshness as fake-clock tests — grown / rename-replaced / deleted transcripts are reflected within one reconcile interval; the periodic sweep reaches everything the recency window misses.
- Retirement as a stateless walk — the I1–I8 invariants (provably-gone only, loss-of-contact is never absence), capped by directories read rather than rows (round 12 F1).
- Store as memory —
files()/stateCounts()/setFileState()replace the stale set;status()isGROUP BY stateplus the pass's degraded roots. - Declined/unreachable sources —
noteUnreachableParserwrites a "read-through, no session" row so OpenCode sessions aren't re-decoded every pass (round 12 F3). - Lifecycle — immutable indexer, one work loop,
liveIndexerPathsclaimed after the store opens,close()disarms the timer and queued work.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| const candidates = [...this.stale.values()] | ||
| this.stale.clear() | ||
| return candidates | ||
| setFileState(path: string, state: SessionSearchFileState, atMtimeMs?: number): void { |
There was a problem hiding this comment.
setFileState drops the this.closed guard that markStale had, and a pass's read has no cancellation — parseAgentSessionFileCached takes no AbortSignal, so close() does not interrupt a read in flight. A read that finishes after close() still reaches finish() and writes through the closed handle (setFileState('failed') here, and write.commit in the consumer), which reaches onError with a database is not open — the round-10 M2 symptom. The close tests only close between files (clock seam), so this race isn't covered.
Technical details
# Close mid-read still reports a DB error to the owner
## Affected sites
- src/main/ai-vault-search/session-search-store.ts:188 — `setFileState` has no `this.closed` guard (the removed `markStale` did: `if (this.closed || …) return`).
- src/main/ai-vault-search/session-search-index-consumer.ts:119 — `finish()` calls `write.commit` / `writeCommitted` / `setFileState` with no awareness of `close()`.
- src/main/ai-vault/session-scanner-parse-cache.ts:105 — `parseAgentSessionFileCached` takes no signal, so the pass's read is not aborted by `loop.close()`; `close()` completes synchronously and shuts the store while the read is still awaiting.
## Required outcome
- Closing the indexer reports nothing to the owner (invariant I5 / round-10 M2), including when the in-flight read is the one still finishing against the now-shut handle.
## Suggested approach (optional)
- Guard `setFileState` / `writeCommitted` with `if (this.closed) return`, and have the consumer's `finish()` no-op (including `reportWriteFailure`) once the store is closed.
## Open questions for the human (optional)
- Is a read finishing after `close()` in-scope for I5? Today only *queued* work is stopped; in-flight reads run to completion — against a shut handle — before settling.084f568 to
202de2f
Compare
Three questions a lifecycle owner has to be able to ask, none of which had an answer: how many unfinished writes this open tombstoned, what the index believes it holds, and whether the session list's cursor already covers a file. The last one is not a nicety. The reader only opens a transcript the list still needs, so any file the list scanned before the index existed would be reused from cache and never reach the index at all. Naming the rule where it lives keeps one spelling of it instead of two.
…respect An injected clock, a retention window, a per-cycle allowance in files and bytes, a bounded re-read queue, and the load-aware pacing from the original branch. The allowance deliberately does not carry unspent room forward: accumulating it would let a long idle stretch buy one unbounded cycle, which is the stall the budget exists to prevent. Work that does not fit is queued, not dropped, and a transcript larger than a whole cycle's bytes is admitted alone rather than being refused forever.
…hat happened One pass over a candidate list, plus the four things a caller has to be told about afterwards: what was discovered, which roots could not be read, which sources are provably gone, and where the whole run stands. Two absence rules are load-bearing. The file walker swallows a readdir failure and returns, so an unreadable root and an uninstalled agent both arrive as "no files"; only a root that yielded nothing is re-probed, and only ENOENT counts as absent. A source is retired on the same evidence and no weaker: an EACCES, an EIO or a stalled distro keeps its rows. Progress lives in the index's own files table, so a pass skips what it already covers and an interrupted run resumes instead of starting over.
The sweep enumerates every root without a limit and is the only pass that can retire a source deleted while nothing was running. The cycle re-stats the newest N per agent, which is the sidebar's own rule rather than a second one, folds in the store's stale set and anything a caller invalidated, and reads what changed inside the cycle's allowance. A replaced file gets a whole re-read in the cycle that notices it. Waiting for the index to decline an append and mark itself stale would cost a second cycle and, because the reader resumes from the session list's cursor, would decline again every cycle after that.
… tested The object that owns freshness for the index: a full sweep on start, a timer that reconciles the recent window, retention that purges when it narrows and re-sweeps when it widens, and a pause that stops the writers rather than only the timer. A library, not a service. No Electron, no app lifecycle, no settings read, no IPC, and nothing constructs it. The clock is injected because a guarantee stated in wall time is a claim until a test can advance the clock and watch it hold: a transcript in the recent window that grows, is rename-replaced, or is deleted is reflected within one interval, each with its own test.
Reviewer F4 and the plan's fourth open decision. A conversation held in the panel writes the same file in the same place as one held in the terminal, so it must be searchable through the same path with nothing else running. The test constructs the indexer over an isolated root, writes and then appends native-chat-shaped rows, advances the clock one interval, and reads the rows back through the published views.
The pass read the index's own file row to decide how to read a candidate, and only then asked whether the store would accept it. A store that is paused or already closed answers no to everything, so those cursor reads were against a handle it had given up.
…ause rules `requestWholeTranscriptRead` replaces the local invalidation: the reader owns the resume point, so asking it is the honest way to say the index needs a span the session list has already moved past. Two callers, and the second is the one no decline can reach. A forced path is one the store handed back from `takeStale` or a caller invalidated, and it has to arrive as a `replace` or the consumer declines the same append forever. But when the list's cursor already sits at a file's current stat the parse opens nothing at all, so no consumer is asked and there is nothing to record. That is every transcript on the machine the first time the index is switched on inside a running app, so it gets a test on both the sweep and the cycle path. Pausing now keeps the store's re-read set, so `filesPending` and `droppedPending` add both bounded queues together: a caller cannot act on one of them alone. The schema creates the index directory, so the indexer no longer does.
The indexer's scheduled-work queue carried a bound of its own beside the store's STALE_PATH_LIMIT, so `droppedPending` summed two numbers that meant two different things. It now shares the store's ceiling, set by the indexer, which is the only thing holding both queues. They stay separate queues. The store records that the index has a hole in a file; this records work scheduled and not yet done. Merging them by pushing budget leftovers through `markStale` would turn every deferred append into a whole re-read.
…t current Seven review findings, all in the seam between "stopped working" and "finished". One commit because they meet in the same three files. A pause part way through a backfill abandoned it. The flag was cleared on entry, the abort was swallowed as a normal stop, and resume only re-swept when the pause outlasted an interval. A sweep is now due until one completes, and work drained out of a queue and then not read goes back: a stale or invalidated path is a hole in the index, not finished work. The retention cutoff was set once at construction while purges took a fresh one, so with a one-day window a sweep three days later deleted a row the very next accept check re-indexed. It is refreshed from the clock before any accept decision in a pass. An invalidated path the index had never held was dropped unread, because it was resolved only through rows the index already had. It now resolves the agent from the same root table discovery reads, and what still cannot be resolved stays queued and counted rather than vanishing. Status told four small lies: a file count that tallied attempts and grew past the total, `current` while work was queued or before any sweep had finished, `current` after close, and a declined read counted as indexed because the parse returned without throwing. It now counts what the store holds, requires all three conditions for `current`, has a `closed` phase, and counts a file only when the index's own cursor moved. The cursor drop ran outside the per-path parse lane, so an overlapping sidebar parse could store its entry in between and turn a forced whole read back into a cache reuse. The decision moves inside the lane as a read requirement, which is the only place that is atomic against it. A sweep retired every indexed file it did not discover. An unmounted volume ENOENTs its whole tree at once, so that deleted a user's searchable history for a detached drive. A root that cannot be read, or that lists nothing where it listed transcripts before, is degraded, and a degraded root's files are never retired however loudly the filesystem says they are gone. The pass loop moves to `session-search-work-loop.ts`: one task at a time, one pending tick, one abort. It is the part with no opinion about transcripts, and the indexer was over the line limit with it inline.
…ing on purpose `filesPending` summed the store's re-read set and the indexer's queue, and a path sits in both the moment a read is declined during a pause and a caller then invalidates the same file. One transcript read as two, with nothing to distinguish that from two transcripts. It is a union by path now. The drop counts stay a sum, because a drop is an event rather than a membership and nothing retains the paths to deduplicate afterwards. The previous commit raised this queue's cap from 2,000 to the store's 20,000 as a side effect of trying to make one number out of two, which the double-count shows it never was. Both queues retain a candidate per entry, so that quietly doubled the worst-case memory of a background feature. Back to 2,000, with the reason written down: the store's set is filled by the reader at machine speed during a pause and needs headroom proportional to the transcripts on the disk, while this one is filled by a cycle's budget rollover, bounded by one recent window at a few hundred, and by `invalidate()`, where 2,000 outstanding requests is already a malfunctioning caller.
Two of the round-1 fixes were written on the sweep and the cycle walked around them twenty seconds later. The degraded-root fence now lives inside the retirement function itself rather than at one call site, so both passes get it from one place and the cycle cannot delete what the sweep just protected. The cycle also reads the sweep's root counts, so it can see a tree that went to zero at all; it does not write them back, because a recent-window discovery is not a census. The N-to-zero alarm was single-shot: the degraded sweep's own zero became the baseline, so the next sweep compared zero with zero and retired the tree it had just spared. A root keeps its last healthy count until one lists it non-empty again. Taking a file no longer means the cursor moved. A forced whole re-read of an unchanged file writes an identical cursor, so an invalidated file that turned out not to have changed was never settled: owed forever, re-read whole every interval, status pinned. It means the index now covers the file at this stat, which is the same question the skip at the top of the pass asks, and it is the same function. An aborted cycle handed the store's re-read set to a queue a tenth its size, which silently discarded the difference. What came from the store goes back to the store, under its own bound and its own retention rule. Whether a sweep finished is now an argument rather than a call site's position, so an aborted one cannot latch `current` by being reported a line too early.
The degraded-root fence did nothing at all for OpenClaw, the one agent whose roots are alternates for a single install. Discovery reports those as one discovery whose rootDir is every path joined by the platform's path delimiter, and that string is not a directory: the probe readdir'd it and got ENOENT, the containment check never matched a file under it, and a scan issue recorded against a real root never compared equal to it. So the agent most likely to live on a mounted volume was the one an unmount deleted, and the degraded root it reported was not a path anyone could act on. Health now runs on the constituent directories, taken from the same source table discovery reads rather than by splitting the joined string back apart, which would be its own bug: a directory may legally contain the delimiter. Files are attributed to the root they actually live under, so one alternate can be unreadable while the other keeps indexing and retiring normally. The N-to-zero alarm also never released. Carrying only counts above zero meant a root the user legitimately emptied stayed degraded for the life of the process, its rows never retired and the phase pinned. The rule is now explicit: a root that cannot be listed keeps its last healthy count and stays degraded indefinitely, while one that lists successfully and empty on two consecutive full sweeps is believed. One sweep is not enough, because that is also what a freshly unmounted volume looks like, and only a sweep counts: a recent-window cycle can see a root at zero but is not a census. The allowance still charges a forced read at the size discovery saw. That is an under-count when a file grows mid-cycle, and it is deliberate: the budget paces a cycle rather than accounting for it, and the error is bounded by what one cycle's writers appended.
…ex, not memory The fence was inert on the first sweep of every process. The evidence that a root had ever held anything lived only in memory, so after a restart it was empty, and a missing directory is what a detached volume and an agent that was never installed both look like. Index a transcript, close, detach the volume, open the same database: every row retired on that one sweep, with no degraded root reported. The evidence now comes from the store, which is the thing that actually outlives the process, through a range scan on the path key. A root that is missing while the index holds files under it is degraded; only one the index holds nothing under is absent. Consecutive also has to mean consecutive. An unreadable sweep left the tally alone rather than breaking it, so empty, unreadable, empty added up to a deletion nobody performed. Anything that is not a successful empty listing now resets the run. Rows under no configured root were immortal: nothing refreshed them, nothing retired them, nothing reported them, and searches still returned them. That happens when a profile moves or a root is reconfigured. One rule, written at the function: such a file is retired exactly like any other if its path answers ENOENT, because that is proof, and otherwise the rows stay and `orphanedFiles` reports them. An index holding content the current configuration cannot reach is a configuration problem to surface, not a licence to delete history. An aborted sweep no longer publishes findings it never gathered. It stops probing on abort, so its empty degraded list would have cleared a live alarm, and its partial view must not count toward emptying a root either. It now skips the health pass entirely and carries the previous state forward.
…tention reads The transcript meant to sit outside a 30-day window was dated against wall time while the window is measured against the test clock, which runs a year behind it, so the file was inside the window and the test proved nothing: it passed with the fix reverted.
The rebase onto the one-transaction-per-file store: re-add the cursor predicate PR 2 dropped, read `sessions`/`messages` now the visibility views are gone, and delete `recoveredRows` -- there is no tombstone table left for a crashed writer to leave rows in, so the counter could only ever read zero.
… and one bound A configuration change is now "close it, construct a new one", so the object has one store, one registration and one lifetime. `pause`, `resume`, `clear`, `setHistoryDays` and `invalidate` are gone, and with them every flag that only existed to keep a second lifetime in step: `paused`, `pausedAt`, `purgeDue`, the deferred-purge path, the resume-sweep rules and the start-while-paused case. Throwing the index away is close, `removeSessionSearchDatabase`, and a new instance; widening retention is a new instance whose opening sweep admits the older files, and narrowing is the purge that opens every full sweep. One queue, not three. The indexer's pending queue and the sweep remainder are deleted; the store's re-read set is the one bounded queue, already the place a declined read lands, and `filesPending` is its size rather than a union across queues that could count one transcript twice. One pacer, not three. The files-and-bytes allowance and the load-average back-off are deleted; a pass reads until its wall-clock deadline and hands the rest back. A pass that runs out of time defers only files it would actually have read, so a truncated pass cannot buy a whole re-read for a file the index already covers. The sweep cadence subsumes root recovery: a full sweep runs on start and every `fullSweepEveryCycles` after it, so a root that comes back is picked up by the next one instead of by a flap-bounded re-arm rule.
Removing `loop.close()` from `close()` failed no test: the unregister already stopped a later scan reaching the index, so the surviving timer and the task queued behind it were invisible. The close test now asserts the timer is gone and that advancing the clock past it reports nothing, which is what a pass running against a shut store would have done.
`retirementChecksPerCycle` had no caller in the stack, so the reconciler keeps its own constant; the error reporter is only needed while the store and the loop are being built, so it stops being a field.
…ked for The per-path arm existed for `invalidate()`, which had to resolve a path the index might never have held. Only the sweep reads this now, and it reads all of it.
PR 2 now reports a file a chunked read left half written with a null cursor under the whole file's mtime and size, so the freshness check has to start at `requiresWholeRead`: comparing only the stat calls a prefix current and leaves it in the index for good. Two consequences, one test each. The skip check no longer skips such a file, and the took-it check no longer reports it indexed, so it stays owed until a read finishes it. The pass reads it whole rather than appending, which repairs it in one pass instead of waiting for the consumer to decline an append it was never going to take.
Round 10, each reproduced on 6a1bcfdf49 first and each repro kept as a test. A sweep watched only what it could not settle, which is nothing on a healthy machine, so the cycle after a sweep had no deletion candidates and the cycle after that no longer remembered the file. A transcript deleted in that interval survived until the next periodic sweep, five minutes later. The sweep now seeds the watch set with its own recency window, taken from its own discoveries through the same class discovery selects with, so there is no second spelling of the rule and no second walk of the trees. A transcript the reader cannot open was recorded stale by the consumer on every attempt and re-read every cycle for ever. Three failures at one unchanged stat now hold a file out until that stat moves, which is the only thing that can mean it changed. `failures`, a tally of attempts that climbed without bound, becomes `unreadableFiles`, a gauge of files being held; a non-zero value is degradation, because waiting will not close that gap. `close()` part way through a pass left the pass reading a shut handle and reported three database errors to the owner who asked for the close, and `status()` afterwards opened it again to answer zero files. The pass stops at the cancellation the close raises, and a closed indexer reports what it last knew. `indexedSources` throws rather than answering with an empty list: its caller is a sweep deciding what nothing rediscovered, and an empty answer is the one conclusion an unreadable handle must not reach. A sweep that threw puts its own flag back, so something is still armed to try again. `droppedPending` was a lifetime tally under a doc that promised it meant the queue was incomplete until the next sweep. A completed sweep now clears it, and `bytesIndexed` resets per pass rather than per sweep, so it stops sawtoothing every fifteen cycles. Two indexers on one database both registered with the reader and wrote every transcript twice. The second construction throws.
… not reach Three round-10 mutations survived the first pass of tests, all of them the same shape: a pass that failed still reached a verdict, and nothing checked. The drop reset moves into the sweep itself, where a test holding the store can overflow the queue and watch a completed sweep clear it; from the indexer the call was unreachable without twenty thousand files. A sweep whose held-file read throws now has a test that the failure travels rather than being folded into an empty list, and a sweep that threw part way has one that the flag saying a sweep is owed comes back.
Three additive columns on `files`, and the consumer writes them. `state` is 'current', 'due' or 'failed'; `fail_count` and `failed_mtime_ms` are what stop an unreadable transcript being retried on every pass for ever. Schema version 4, so a stale index rebuilds. Every refusal now leaves its record on the row rather than in a map beside it. A declined append is 'due': the index is behind on a span no append reaches, so the next pass reads the file whole. A read that started and did not commit is 'failed', counted, and stamped with the stat it failed at, because a transcript the reader cannot open fails identically every time and only a change to that stat can mean the file itself changed. A path the file table does not name needs no record at all: the next pass reads it because the index holds nothing for it. Deleted with the in-memory set they served: `markStale`, `takeStale`, `pendingFileCount`, `droppedPendingFileCount`, `forgetDroppedPending`, `setAcceptingWrites`, `acceptsCandidate`, `STALE_PATH_LIMIT`. Added: `files()`, `setFileState()`, `stateCounts()`, `retentionCutoff`. The retention gate moves into `beginWrite`, because the consumer observes every read the session list makes and not only the ones the index asked for. The indexer rewrite that consumes this surface is the commit after; this one is kept to the store, the schema and the consumer so PR 2's own final commits can rebase over it.
The common unreadable transcript is one no read ever got through: a file behind the wrong mode bits fails on its first attempt, so there is no row to count the failure on and it would be read again on every pass for the life of the process. The failure now inserts its own row, holding a zero cursor and no session, which is what "the index holds nothing for this file" already looked like.
Design v3. Every question a pass asks between passes is a row in `files`: what is owed a read, what has failed and how often, what the index holds and therefore what may have been deleted, what to report. Two things outlive a pass and are not rows -- the timer, and one bit per root for the retirement walk's grace -- and both are named in the class doc. One loop, four steps. Discover: the only filesystem walk, every root on a sweep and the newest N per agent on a cycle. Decide: the candidate's stat against its row, as one pure function with its own test. Retire: the rows discovery did not return, inside the scope it covered, through the unchanged walk. Report: a `GROUP BY state` over the same rows. `session-search-backfill.ts` and `session-search-reconciler.ts` become one `session-search-pass.ts`, because the two differed only in discovery scope. Deleted with them: the watch set redefined three times, the hold-out map, the `sweptClean` latch, `session-search-indexing-status.ts` and every counter with a rule about when to reset, `session-search-unreadable-files.ts`, and PR 3's addition to `session-search-file-cursor.ts`, which the decide step replaced. Two things the design did not anticipate, both found by its own tests. A cycle lists the newest N per agent, so a backlog outside that window is invisible to it and a first run would have crawled: a pass that runs out of time now asks for a sweep, which is self-limiting because the first pass that finishes its reads hands the interval back. And a cycle's retirement candidates are the newest rows under the roots it listed, capped, so a deletion inside the recency window is proven on the next cycle whenever it happened rather than waiting for a sweep.
Removing the newest-first sort from a cycle's retirement scope failed nothing: the fixture wrote its transcripts oldest first and the sweep indexed them newest first, so the table's own row order already put the oldest last and an unsorted slice happened to reach the same answer. The oldest file is now indexed on its own first, which makes it the earliest row as well as the oldest file, and the two orders disagree.
PR 2's final pass took version 4 when it dropped conversation_fts, and the rebase merged both bumps into one number. The columns take 5. Two smaller things the same rebase left behind: the stub store in the identity test still declared the two methods the consumer no longer calls, and STALE_PATH_LIMIT outlived the set it bounded. This sits one commit above the columns rather than inside them, because the rebase onto abeccc5 was the one history rewrite that was authorised. Whoever cherry-picks the store commit needs both.
… what memory is left `store.indexedFileCount` has no caller: the status reports the state counts and PR 4 reads sessions. The class doc claimed two things outlive a pass. Six do, and each is now named with the reason it cannot be a row: the grace bit, the two timer fields, the three the last pass observed for `status()` to answer between passes, and one cached query result read only after a close. A slogan that undercounts is worse than a list, because the next round has to rediscover what it left out.
The claim on a database path was staked before the store opened it, and a construction that throws has no close() to release it. One failed open -- a directory where the file should be, a corrupt header, a permission -- left the path owned by an object that does not exist, and every later construction was refused for the life of the process, including the one that would have fixed whatever broke the open.
An OpenCode SQLite session decodes where the message channel cannot reach it, so no read of one will ever commit a row, and the consumer declined it without writing anything. That left the file table silent about a source discovery returns on every pass: the decide step saw a path the index held nothing for and asked for a read, and asking for one over a warm cache drops the session list's own resume point. Every OpenCode session was fully decoded on every pass, and the sidebar's cached fold was thrown away with it -- the cache STA-1278 and STA-1417 added. The decline now writes the row the store already has a shape for: a read that went through and decoded no session, cursor at the file's size, no session row. The decide step skips it until its stat moves, and the retirement walk retires it like any other row. Nothing in the decide step knows what OpenCode is.
…y rows A directory that cannot be listed answers `unverifiable` for every row under it, on every pass, for as long as the permission stays wrong. Counting rows against the cap let five hundred such rows spend the whole budget on one readdir's worth of verdicts: a row for a file the user really deleted, sorted behind them, was never reached on any pass. Six full sweeps and it was still held; at a hundred rows the same file retires on the first. The cap now counts the directories a walk asks for, which is what actually costs a read, and it is spent only by a row that starts somewhere the walk has not been. Rows sharing a directory are one read and then map lookups, so a block of them can no longer crowd out anything. The comment claiming the leftovers "keep being watched" went with it. There is no watch set: a row the walk did not reach is simply still undiscovered on the next pass, which is what makes finishing over several passes safe.
202de2f to
3cdb1af
Compare
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review. 📝 WalkthroughWalkthroughAdds a database-backed session-search indexer with persistent file states, incremental and whole-file reads, retention handling, root degradation reporting, deletion proofs, synthetic-source support, timer scheduling, and lifecycle management. Adds extensive tests for indexing, retries, deadlines, restarts, root failures, deletion handling, merged roots, native-chat transcripts, and OpenCode sessions. Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Several indexing and lifecycle paths can still stop future work, leave changed sessions unindexed, exceed configured work bounds, or publish incomplete state. These issues should be resolved before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives extensive technical context, rationale, scope, testing, and verification details. However, it does not follow several required template sections: the Linked Issue field is blank, Visual Proof does not contain the required N/A statement, and the Review, Agent skill upstream boundary, Notes, and Checklist sections are missing. Resolution Add a valid issue reference after "Fixes #". Add the exact Visual Proof statement "N/A" with a brief reason if there is no UI or interaction change. Complete the Review, Agent skill upstream boundary, Notes, and Checklist sections, including the required test and compatibility confirmations.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (1)
src/main/ai-vault-search/session-search-merged-roots.test.ts (1)
29-29: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAvoid a secondary teardown error when setup fails.
Both tests assign
indexeronly after awaited transcript setup. If that setup fails,afterEachadds a hook error. Vitest 4.1.11 appends hook errors to the existing test result, so the original failure remains visible. Use nullable state to remove the secondary error.💚 Proposed fix
-let indexer: SessionSearchIndexer +let indexer: SessionSearchIndexer | null = null beforeEach(async () => { + indexer = null resetSessionParseCacheForTests() resetTranscriptConsumersForTests() clock = new FakeSessionSearchClock() harness = await openSessionSearchIndexerHarness('ss-merged-roots') }) afterEach(async () => { - indexer.close() + indexer?.close()
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 2d2132ae-7b23-404c-bc1c-3fec40e476f0
📒 Files selected for processing (34)
src/main/ai-vault-search/session-search-clock.tssrc/main/ai-vault-search/session-search-degraded-roots.tssrc/main/ai-vault-search/session-search-deleted-sources.test.tssrc/main/ai-vault-search/session-search-deleted-sources.tssrc/main/ai-vault-search/session-search-directory-listings.test.tssrc/main/ai-vault-search/session-search-directory-listings.tssrc/main/ai-vault-search/session-search-file-write.test.tssrc/main/ai-vault-search/session-search-index-consumer.test.tssrc/main/ai-vault-search/session-search-index-consumer.tssrc/main/ai-vault-search/session-search-index-pass.test.tssrc/main/ai-vault-search/session-search-index-pass.tssrc/main/ai-vault-search/session-search-index-writer.test.tssrc/main/ai-vault-search/session-search-indexer-options.tssrc/main/ai-vault-search/session-search-indexer-test-fixture.tssrc/main/ai-vault-search/session-search-indexer.test.tssrc/main/ai-vault-search/session-search-indexer.tssrc/main/ai-vault-search/session-search-lifecycle-matrix.test.tssrc/main/ai-vault-search/session-search-live-transcript.test.tssrc/main/ai-vault-search/session-search-merged-roots.test.tssrc/main/ai-vault-search/session-search-native-chat-indexing.test.tssrc/main/ai-vault-search/session-search-opencode-decline.test.tssrc/main/ai-vault-search/session-search-pass.tssrc/main/ai-vault-search/session-search-read-decision.test.tssrc/main/ai-vault-search/session-search-read-decision.tssrc/main/ai-vault-search/session-search-retention-policy.test.tssrc/main/ai-vault-search/session-search-retention-policy.tssrc/main/ai-vault-search/session-search-scan-roots.test.tssrc/main/ai-vault-search/session-search-scan-roots.tssrc/main/ai-vault-search/session-search-schema.tssrc/main/ai-vault-search/session-search-store-is-memory.test.tssrc/main/ai-vault-search/session-search-store.tssrc/main/ai-vault-search/session-search-synthetic-sources.tssrc/main/ai-vault-search/session-search-work-loop.tssrc/main/ai-vault/session-scanner-parse-cache.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| const listings: SessionSearchDirectoryReader = { | ||
| namesIn: (directory, signal) => { | ||
| asked.add(directory) | ||
| return args.listings.namesIn(directory, signal) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Enforce directoryLimit for every new directory.
The current check occurs only before proveSource. One source walk can then add and read many new ancestor directories. For example, repeated ENOENT results on a deeply nested path can exceed a limit of one by the full path depth.
Apply the budget when namesIn receives each new directory. If the budget is exhausted, classify the current and remaining paths as unchecked.
Also applies to: 138-140
|
|
||
| expect(indexedMessages()).toBe(2) | ||
| expect(store.takeStale()).toHaveLength(1) | ||
| expect(owed()?.state).not.toBe('current') |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert the exact persisted state.
Each scenario first creates a files row. The row cannot be absent on the subsequent read. Identity or cursor changes record due; incomplete reads and write failures record failed. Assert due at lines 137 and 341, and failed at lines 162 and 254. Otherwise, regressions in these persistent transitions can pass because undefined also satisfies not.toBe('current').
| const committed = | ||
| write?.commit({ | ||
| session: null, | ||
| byteOffset: candidate.file.sizeBytes ?? 0, | ||
| incomplete: false | ||
| }) === true |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Handle an uncommitted unreachable-parser write.
write.commit() can throw or return false. This path does not use the failure handling in SessionSearchReadConsumer.finish().
If the commit throws, the exception escapes from beginRead() into the transcript reader. If the commit returns false, no row records the failure, so a later pass can decode the source again.
Report the error and mark an attempted but uncommitted write as failed.
Proposed fix
- const committed =
- write?.commit({
- session: null,
- byteOffset: candidate.file.sizeBytes ?? 0,
- incomplete: false
- }) === true
+ if (!write) {
+ return
+ }
+ let committed = false
+ try {
+ committed = write.commit({
+ session: null,
+ byteOffset: candidate.file.sizeBytes ?? 0,
+ incomplete: false
+ })
+ } catch (error) {
+ this.store.reportWriteFailure(error)
+ }
if (committed) {
this.store.writeCommitted(candidate)
+ return
}
+ this.store.setFileState(candidate.file.path, 'failed', candidate.file.mtimeMs)| const retirement = completed | ||
| ? await retireDeletedSessionSearchSources({ | ||
| store, | ||
| paths: retirementCandidates(rows, swept, roots, args.full), | ||
| roots, | ||
| // Only a sweep enumerates without a per-agent limit, so only a sweep | ||
| // may prove a synthetic row's container holds it no longer. | ||
| enumeratedContainers: args.full | ||
| ? sessionSearchEnumeratedContainers(swept.candidates, issues) | ||
| : undefined, | ||
| emptiedRoots: previousRootsWithFiles | ||
| ? sessionSearchEmptiedRoots(previousRootsWithFiles, rootsWithFiles) | ||
| : new Set(), | ||
| listings: args.listings, | ||
| directoryLimit: RETIREMENT_DIRECTORIES_PER_PASS, | ||
| signal | ||
| }) | ||
| : { retired: [], unverifiable: [], unchecked: [], degradedRoots: [] } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Return completed: false when cancellation stops retirement or root checks.
Both later phases can stop normally after signal.aborted. Neither phase changes completed. The pass can therefore return partial conclusions with completed: true.
After each phase, detect cancellation and mark the pass incomplete or propagate the cancellation. This prevents the indexer from recording partial root health and reconciliation state as complete.
Also applies to: 170-176
| return ( | ||
| row.state === 'failed' && | ||
| row.failCount >= SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT && | ||
| row.failedMtimeMs === mtimeMs |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Release held-out rows when the complete file stat changes.
Line 90 compares only failedMtimeMs. The normal decision path recognizes size changes with an unchanged mtime. After three failed reads, an append that preserves mtimeMs remains held out, so new transcript content stays unindexed until another mtime change occurs. Persist and compare the failed size and identity, or otherwise reset the holdout when either value changes.
| export function isUnderScanRoot(path: string, root: string): boolean { | ||
| return root.length > 0 && (path.startsWith(`${root}/`) || path.startsWith(`${root}\\`)) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline src/main/ai-vault/session-scanner-agent-sources.ts --view expanded
ast-grep outline src/main/ai-vault/session-scanner-roots.ts --view expanded
rg -n -C4 \
'rootDirs|normalizedWslHomeDirs|normalize|resolve|trailing|isUnderScanRoot' \
src/main/ai-vault/session-scanner-agent-sources.ts \
src/main/ai-vault/session-scanner-roots.ts \
src/main/ai-vault-searchRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- session-scanner-roots.ts ---'
cat -n src/main/ai-vault/session-scanner-roots.ts | sed -n '1,95p'
printf '%s\n' '--- session-scanner-values.ts ---'
rg -n -C8 'export function normalizeAgentSessionsDir|function normalizeAgentSessionsDir' src/main/ai-vault/session-scanner-values.ts
printf '%s\n' '--- root construction and tests ---'
rg -n -C3 'function sessionRootDirs|export function sessionRootDirs|normalizedWslHomeDirs|isUnderScanRoot|trailing slash|trailing separator|sessionsDir' \
src/main/ai-vault/session-scanner-roots.ts \
src/main/ai-vault/session-scanner-values.ts \
src/main/ai-vault-search/session-search-scan-roots.test.ts \
src/main/ai-vault-search/session-search-scan-roots.tsRepository: stablyai/orca
Length of output: 7998
Normalize configured scan roots before containment checks.
sessionRootDirs and claudeProjectsRootDirs return configured roots unchanged. A trailing separator therefore makes isUnderScanRoot search for a doubled separator, so descendants can be treated as outside the configured root. Normalize these roots before containment checks.
| } catch (error) { | ||
| // An aborted task is a close, never a failure. | ||
| if (!controller.signal.aborted) { | ||
| this.options.onFailure(error) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Keep settled non-rejecting when onFailure throws.
onFailure is caller-provided. If it throws, run() rejects and the following arm() call does not run. This breaks the documented settled contract and stops interval scheduling.
Isolate exceptions from the failure callback.
Proposed fix
if (!controller.signal.aborted) {
- this.options.onFailure(error)
+ try {
+ this.options.onFailure(error)
+ } catch {
+ // Failure reporting must not reject the work loop.
+ }
}There was a problem hiding this comment.
ℹ️ No blocking issues — one misplaced import and one optional test gap, noted below.
Reviewed changes
- Normalized the one-writer guard's key —
liveIndexerPathsnow keys onresolve(options.databasePath)(the resolved absolute path) instead of the rawdatabasePath, so a relative and an absolute spelling of the same database collide under the round-10 two-indexers guard instead of slipping past it.
ℹ️ Nitpicks
- The fix adds no test: the existing
refuses a second indexer on a database one already ownstest passes the same absolute path twice, so it would stay green even without theresolvenormalization. A one-line assertion that a relative spelling of the harness path also throws would pin the behavior the commit is actually adding, matching the repro-test-per-fix discipline the rest of the stack follows.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| return sessionSearchHistoryCutoffMs(this.options.historyDays, this.clock.now()) | ||
| } | ||
| } | ||
| import { resolve } from 'node:path' |
There was a problem hiding this comment.
resolve is imported at the bottom of the file, after the class, instead of grouped with the imports at the top. Move it up so the file reads consistently and a future import/first rule won't trip on it.

Summary
PR 3 of the agent-session-search stack (plan:
docs/reference/agent-session-search-pr-split.md). Stacked on #19687 (PR 2); the base moves tomainwhen that merges. Rebased onto PR 2's final headabeccc5905. Diff against #19687 is 33 files, roughly +4.6k/-160.SessionSearchIndexer: the library that owns freshness for the PR 2 index. It answers the design review's F2, F3, F6 and F12 at the library layer, where each guarantee is a fake-clock test. It knows nothing about Electron, the app lifecycle, settings, IPC or the panel, and nothing constructs it in production: that is PR 3b, deliberately after PR 5.The store is the only memory
Every question the indexer answers between passes is answered by a row in the
filestable: what is owed a read, what has failed and how often, what the index holds and therefore what may have been deleted, and what to report. There is no queue, no watch set, no hold-out map, and no counter with a rule about when to reset.Six fields outlive a pass and are not rows. The class doc names each with the reason it cannot be one: the grace bit per root that the retirement walk needs and deliberately does not persist;
cyclesSinceSweepandsweepNext, which are about the timer and mean nothing to a second process;degradedRoots,lastReconcileAtandlastSweepCompletedAt, which are what the last pass observed, held sostatus()can answer between passes; andlastCounts, the one cached query result, read only afterclose()so that describing what happened does not reopen a handle the owner has finished with.This is a rewrite of rounds 9 and 10, not a patch on them. Rounds 7 through 10 produced eleven findings, and nine were the same shape: a structure beside the store that had to be kept in step with it, and was not. The watch set was redefined three times and still let a file deleted between a sweep and the next cycle survive five minutes. The queue needed a bound, a drop policy, a drop counter, and a rule for when to clear the counter. The hold-out map needed a capacity and an eviction order. Each of those is now a column or a
WHEREclause.Three additive columns on PR 2's
filestableSchema version 5; PR 2's final pass took 4 when it dropped
conversation_fts.state='current', fail_count=0.state='due': the index is behind on a span no append reaches, so the next pass reads the file whole.state='failed', counted, stamped with the stat it failed at. The row is inserted if there was none, because the common unreadable transcript is one no read ever got through.A stale index rebuilds on the bump. The chunk-partial sentinel PR 2 already writes (
byte_offset = -1) is left alone; it reads as "owed a whole read" throughrequiresWholeRead, and a fourth state would have been a second spelling of it.One loop, four steps
Every pass does the same four things. A sweep and a cycle differ only in what step 1 lists.
sessionSearchReadDecisionis a pure function of the candidate's stat and its row, with its own test: retention first, then no row, held out,due, a cursor that continues nothing, a file shorter than the index read to, a failed read still within its retries, and finally a stat comparison. Reads stop at the wall-clock deadline and nothing is recorded about what was left, because being owed is a fact about the row.gonedeletes.status()isSELECT state, count(*) FROM files GROUP BY stateplus this pass's degraded roots. Nothing is tallied, so nothing can drift and nothing needs a reset rule.Two things the design did not anticipate, both found by its own tests. A cycle lists the newest N per agent, so a backlog outside that window is invisible to it and a first run would have crawled: a pass that runs out of time asks for a sweep, which is self-limiting because the first pass that finishes its reads hands the interval back. And a cycle's retirement scope is ordered newest first, so a deletion inside the recency window is proven on the next cycle whenever it happened rather than waiting for a sweep.
Surface
Immutable after construction. There is no
pause,resume,clear,setHistoryDaysorinvalidate. A configuration change is close-and-construct; throwing the index away isclose(),removeSessionSearchDatabase(databasePath), construct. Widening retention is a new instance whose opening sweep admits the older files; narrowing is the purge that opens every full sweep. A second indexer on one database path throws, because that ordering is the one the recipe rules out.Status
phase(idle | indexing | current | degraded | closed),filesIndexed,filesDue,filesFailed,degradedRoots,lastReconcileAt,lastSweepCompletedAt. The three counts are theGROUP BY.currenttakes all three: no row owed a read, no row whose last read failed, and a sweep that finished.degradedcovers both gaps the index knows about and cannot close alone — a root it could not read, and a file it could not read. A closed indexer reports what it last knew and opens nothing.Two seams with the reader, both load-bearing
The reader chooses
appendvsreplacefrom the session list's parse-cache resume point; the index has no input. Two distinct cases needed handling:requestWholeTranscriptRead(path)drops the resume point; thewholelane asks for it.anylane detects this withsessionParseCacheCoversTranscript(extracted from the parse cache's own unchanged check, one spelling) and asks for a whole read. Dropping this condition fails both "fills an empty index over a warm session-list cache" tests.Retirement: one rule, and the invariants around it
Unchanged since round 7. Stated at the top of
session-search-deleted-sources.tsand tested one invariant at a time.close()stops all work: nothing queued before it may run afterwards, and the timer goes with it.One bit per root survives: a root that held transcripts on the previous pass and holds none on this one is unverifiable for that pass, so a directory swapped out for a moment cannot retire a tree. What that does not cover, stated rather than hidden: a volume mounted at exactly a configured root and unmounted so the mountpoint stays present and lists empty is indistinguishable from a root the user emptied. Inside one process the transition buys a pass of grace; across a restart there is no transition to see and the rows retire. The unmount shapes that actually occur are above the root, and the walk's boundary at the configured root is what makes those safe with no memory at all.
degradedRootsis a per-pass signal with no memory: roots discovery recorded a scan issue against, roots the walk could not read through, and roots that yielded no transcripts and refuse to list at all. Health operates on real directories: for an agent whose discovery merges several roots into one delimiter-joined label (OpenClaw), the constituent directories come from the same source table discovery reads, never from splitting the label. An incomplete pass publishes nothing, so an abort part way through cannot clear a live alarm.F4: native chat indexed with no panel
session-search-native-chat-indexing.test.tsconstructs the indexer over an isolated root, writes then appends a native-chat-shaped Claude transcript with no panel and no service, advances the fake clock one interval, and reads rows back throughmessages.Deviations from the plan
parseAgentSessionFileCacheddirectly rather thanscanAiVaultSessions, which parses everything it discovers in one call and makes a per-pass bound unreachable.Downstream changes (PR 3 round 11)
PR 2's
filestable gainsstate,fail_countandfailed_mtime_ms, and the schema version is 4. The store's surface moves with them:markStale,takeStalestate='due'on the rowpendingFileCount,droppedPendingFileCount,forgetDroppedPending,STALE_PATH_LIMITstateCounts(); the in-memory set and its bound are gone, so nothing can be droppedsetAcceptingWrites,acceptsCandidatebeginWrite, and PR 3's decide step readsretentionCutoffindexedSources()files(), returning the whole rowAdded:
files(),setFileState(path, state, atMtimeMs?),stateCounts(),retentionCutoff. Kept:indexedFile,removeFile,beginWrite,writeCommitted,reportWriteFailure,setRetentionCutoffMs,purgeOlderThan,connection,close.indexedFileCountandSTALE_PATH_LIMITare deleted with the set and the counter they served; nothing in the stack reads either.Round 9: the simplification rewrite
Rebased onto PR 2's round-8 head. PR 2's rewrite removed
isSessionSearchFileCurrent(re-added here, as the plan said it would be), thevisible_*views (tests readsessionsandmessages) and the tombstone tablerecoveredRowscounted. PR 2's round-8 fixes then madeindexedFilereport a half-written file with a null cursor, which is a compile error at both of this PR's cursor-arithmetic sites; that is handled above.Deleted outright:
session-search-pending-files.tsand its test,session-search-backfill-remainder.ts,session-search-reconcile-budget.tsand its test,session-search-backfill-pacing.tsand its test,session-search-root-recovery.ts,session-search-registered-store.ts,session-search-discovered-counts.tsand its test. From the surface:pause,resume,clear,setHistoryDays,invalidate. From the indexer's state:paused,purgeDue,fullSweepDue's pause interactions, the deferred-purge path, the resume-sweep rules, the start-while-paused case,SessionSearchPendingFiles,SessionSearchBackfillRemainder,SessionSearchRootRecovery,SessionSearchRegisteredStoreand its removal debt,SessionSearchRetentionWindowwithnarrowsSessionSearchHistory/widensSessionSearchHistory/SessionSearchRetentionChange,sessionSearchAgentForPath,queuedCandidatesandrestatCandidate(which existed to resolve a pathinvalidate()named and the index had never held),SessionSearchWorkLoop.disarm/abort/afterTask, andstore.hasStale, which PR 3 itself had added to the store for the union count and is the only line of PR 2's store this PR removes again.The work loop is now one timer, one in-flight task and a closed flag.
disarmandaborthad exactly one caller each once pause and clear were gone, and both wereclose().Lifecycle matrix, repruned. 10 operations × 3 unreachable-root shapes × 2 ways discovery reports a root, 60 cells, on the same four invariants. Five operations went with the methods that are gone (
pause and resume,clear and rebuild,history narrowed then widened, and bothinvalidatecells). Four came in:the periodic sweep comes round,every pass out of time at its first file,reconstructed for a narrower history windowandthe index thrown away and rebuilt— the last two being what replacedsetHistoryDaysandclear, run through the documented recipe rather than described.Mutations, each against the whole
src/main/ai-vault-searchsuite (227 tests):reconcile()beforestart()is allowedclose()does not close the work loopclose()not closing the loop failed nothing on the first run: unregistering the consumer already stopped a later scan reaching the index, so the surviving timer and the task queued behind it were invisible. The close test now asserts the timer is gone and that advancing the clock past it reports nothing, and the mutation fails.Earlier rounds' mutations that still apply: the reconciler treating every file as current fails 6; the first-enablement condition dropped fails 2; removing the per-pass cutoff refresh fails 1;
currentignoring pending work fails 1; settling by cursor movement instead of current stat fails 1; attributing a file by string prefix instead of path segment fails 1; treating synthetic rows as present fails 1; removing the emptied-root grace fails 6; removing the unreadable-root probe fails 3.Not covered, stated rather than hidden: nothing in PR 3 drives the queue past its 20,000 bound, so the wire from
store.droppedPendingFileCounttostatus().droppedPendingis untested here. The bound and the oldest-first drop are PR 2's test (session-search-index-consumer.test.ts), and the status field is covered by the status unit test; only the one-line join between them is not.Round 10
One HIGH and three MEDIUMs, each reproduced on
6a1bcfdf49before it was fixed and each repro kept as a test.SessionNewestFiles— the same class discovery selects with, applied per the same unit — so there is no second spelling of the recency rule and no second walk of the trees. The existing "watches what a sweep could not settle" test stays green: a file outside the window is still the next sweep's to find.indexing. One file with the wrong mode bits was indistinguishable from a real backlog. Three failures at one unchanged stat now hold a file out, and the hold is released by the only thing that can mean the file changed — its stat. Held-out files are bounded at 1,000, oldest dropped, and a dropped hold is a file that gets tried again, which is the safe direction.close()part way through a pass reported three database errors to the owner who asked for the close, andstatus()afterwards opened the shut handle again to answer zero files. The pass now stops at the cancellation the close raises, before every store read below it; a closed indexer reports what it last knew.indexedSourcesthrows rather than returning an empty list, because its caller is a sweep deciding which rows nothing rediscovered and an empty answer reads as "nothing is missing" — the one conclusion an unreadable handle must not reach. A sweep that throws puts back the flag saying a sweep is owed, so something is still armed to try again.Mutations, each against the whole
src/main/ai-vault-searchsuite (247 tests):status()reads the store after a closeThree of those survived the first set of tests written for them, all the same shape: a pass that failed still reached a verdict and nothing checked. The drop reset moved into the sweep, where a test holding the store can overflow the queue and watch a completed sweep clear it; from the indexer the call was unreachable without twenty thousand files.
Two additions to PR 2's files this round, both stated because the stack's rule is that PR 3 does not change them:
store.forgetDroppedPending(), which is the reset above and has its assertion appended to PR 2's own bound test, andstore.indexedSources/indexedFileCountlosing their swallowing catches.Round 11: the store is the only memory
A rework rather than a patch, on the design in
/tmp/ss-pr3-design-v3.md.Deleted concepts.
previousRecent/ the watch set, redefined three timesstore.files()minus discovery, scopedstate='failed'+fail_count+failed_mtime_msdroppedPending,forgetDroppedPendingstate='due'; there is nothing to dropbytesIndexed,unreadableFiles, and their reset rulescount(*) … GROUP BY statesweptCleanlatchlastSweepCompletedAtSessionNewestFilesseeding of the watch setsession-search-backfill.ts,session-search-reconciler.tssession-search-pass.ts; they differed only in discovery scopesession-search-indexing-status.ts,session-search-unreadable-files.tsisSessionSearchFileCurrentinsession-search-file-cursor.tsnormalizeSessionSearchHistoryDaysis no longer exported; its only callers were its own test and the cutoff function beside it.Line count,
git diff --shortstat b0c07f0e8e HEAD -- src ':!*.test.ts':Mutations, each against the whole
src/main/ai-vault-searchsuite (247 tests):failed_mtime_ms, so a changed stat never releases (S3)The last one survived the first version of its test: the fixture wrote its transcripts oldest first while the sweep indexed them newest first, so the table's own row order already reached the same answer an mtime sort would. The oldest file is now indexed on its own first, which makes the two orders disagree.
New tests. S1 to S5 from the design, in
session-search-store-is-memory.test.ts, all through a second connection and hand-written SQL: status equals theGROUP BY; a deletion is retired at every phase boundary (after the opening sweep, after a cycle, after a periodic sweep, and while a pass was out of time); a file that fails three times at one stat is not read again and only its stat releases it; two passes over an unchanged filesystem leave the table identical; and a close part way through a pass leaves nothing for the next instance to repair.session-search-read-decision.test.tscovers the decide step directly, which is where the whole policy now lives.Round 12
Three HIGHs from the final review, each reproduced on
d256580dbabefore it was fixed and each repro kept as a test. One commit per finding.unverifiablefor every row under it on every pass, for as long as the permission stays wrong. Five hundred and twenty such rows spent the whole budget on one readdir's worth of verdicts, and a row for a file the user really deleted, sorted behind them, was never reached: six full sweeps and it was still held, where a hundred rows retire the same file on the first. The cap now counts the directories a walk asks for, which is what a read costs, and it is spent only by a row that starts somewhere the walk has not been. Rows sharing a directory are one read and then map lookups, so a block of them cannot crowd anything out. The comment claiming leftovers "keep being watched" went with it: there is no watch set, and a row the walk did not reach is simply still undiscovered next pass.close()to release it. One failed open left the path owned by an object that does not exist, and every later construction was refused for the life of the process — including the one that would have fixed whatever broke the open.Mutations, each against the whole
src/main/ai-vault-searchsuite (251 tests):Round 11's seven still fail: 79, 54, 8, 6, 3, 2, 1.
Verification
pnpm tc;pnpm test src/main/ai-vault src/main/ai-vault-search(840 tests, 251 in ai-vault-search);pnpm run check:code-quality:changed(0 new findings across 60 changed files);pnpm run check:react-doctor:changed;pnpm run audit:code-quality:native. All pass.Follow-up for PR 2
store.setAcceptingWritesnow has no production caller: pause was its only one. It is left in place because removing it means rewriting PR 2's consumer tests, which use it to exercise the decline path, and PR 2's comments about a paused store recording what it declined are stale for the same reason. Worth a line in PR 2's YAGNI table rather than a change from here.Not in this PR
Anything that constructs the indexer; the scanner-service protocol; settings; IPC; the query engine (PR 4, #19750); the wire contract (PR 5).