Skip to content

feat(ai-vault-search): session search indexer library owning backfill, reconcile and retention - #19751

Merged
Jinwoo-H merged 38 commits into
mainfrom
session-search-pr3-lifecycle
Sep 11, 2026
Merged

Jinwoo-H merged 38 commits into
mainfrom
session-search-pr3-lifecycle

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3018 $\color{#cf222e}{\Huge{\mathbf{−}}}$​72 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2946
Prod 18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1923 $\color{#cf222e}{\Huge{\mathbf{−}}}$​94 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1829

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 to main when that merges. Rebased onto PR 2's final head abeccc5905. 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 files table: 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; cyclesSinceSweep and sweepNext, which are about the timer and mean nothing to a second process; degradedRoots, lastReconcileAt and lastSweepCompletedAt, which are what the last pass observed, held so status() can answer between passes; and lastCounts, the one cached query result, read only after close() 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 WHERE clause.

Three additive columns on PR 2's files table

state           TEXT NOT NULL DEFAULT 'current'  -- 'current' | 'due' | 'failed'
fail_count      INTEGER NOT NULL DEFAULT 0
failed_mtime_ms REAL                             -- the stat the failures happened at

Schema version 5; PR 2's final pass took 4 when it dropped conversation_fts.

  • A read that commits → state='current', fail_count=0.
  • A declined append → state='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 → 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 path the table does not name needs no record at all: the next pass reads it because the index holds nothing for it.

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" through requiresWholeRead, 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.

  1. Discover. The only filesystem walk: every root on a sweep, the newest N per agent on a cycle. Everything below is decided from what it returns, plus one readdir per directory shared by the whole pass.
  2. Decide and read. sessionSearchReadDecision is 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.
  3. Retire. Candidates are the rows discovery did not return, inside the scope it covered: everything on a sweep, and on a cycle the newest 512 rows under the roots this pass listed. The stateless walk (I1–I8, unchanged) proves each one gone, present or unverifiable; only gone deletes.
  4. Report. status() is SELECT state, count(*) FROM files GROUP BY state plus 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

new SessionSearchIndexer({
  databasePath, roots, historyDays,
  clock?, reconcileIntervalMs? = 20 s, recentPerAgent? = 12,
  passDeadlineMs? = reconcileIntervalMs / 4, fullSweepEveryCycles? = 15, onError?
})

start(): Promise<void>                    // full sweep, then the timer
reconcile({ full? }): Promise<void>       // one pass now; throws before start() and after close()
status(): SessionSearchIndexStatus
close(): void                             // stops everything; nothing queued may run afterwards
settled(): Promise<void>                  // tests only

Immutable after construction. There is no pause, resume, clear, setHistoryDays or invalidate. A configuration change is close-and-construct; throwing the index away is close(), 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 the GROUP BY. current takes all three: no row owed a read, no row whose last read failed, and a sweep that finished. degraded covers 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 append vs replace from the session list's parse-cache resume point; the index has no input. Two distinct cases needed handling:

  1. A declined read (index behind): PR 2's requestWholeTranscriptRead(path) drops the resume point; the whole lane asks for it.
  2. No read at all (first enablement in a running app): the list's cursor already sits at each file's current stat, so the parse reuses its fold and never opens the file. The any lane detects this with sessionParseCacheCoversTranscript (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.ts and tested one invariant at a time.

  • I1. A row is retired only when its file is proven gone: some directory between the file and its configured root lists successfully, and the next path component toward the file is absent from that listing.
  • I2. If no directory from the file's parent up to the configured root can be listed, nothing is proven and no row is dropped. ENOENT and ENOTDIR are walked up; EACCES, EIO and a WSL gate refusal are unverifiable at once.
  • I3. The rule is identical on the first pass after a process start and on every later pass. It needs no memory, because the walk stops at the configured root.
  • I4. A file, or a project directory, the user really deleted retires on the first pass that proves it, sweep or cycle.
  • I5. close() stops all work: nothing queued before it may run afterwards, and the timer goes with it.
  • I6. Every pass that reads transcript bytes stops at one wall-clock deadline, the sweep included.
  • I7. A row naming an entry inside a container is proven one level up: the container must be present, and this pass must have enumerated it in full and successfully.

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.

degradedRoots is 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.ts constructs 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 through messages.

Deviations from the plan

  • Drives discovery and parseAgentSessionFileCached directly rather than scanAiVaultSessions, which parses everything it discovers in one call and makes a per-pass bound unreachable.
  • No filesystem events (decided; the stat-based pass is the authority).

Downstream changes (PR 3 round 11)

PR 2's files table gains state, fail_count and failed_mtime_ms, and the schema version is 4. The store's surface moves with them:

removed replaced by
markStale, takeStale state='due' on the row
pendingFileCount, droppedPendingFileCount, forgetDroppedPending, STALE_PATH_LIMIT stateCounts(); the in-memory set and its bound are gone, so nothing can be dropped
setAcceptingWrites, acceptsCandidate the retention gate moves inside beginWrite, and PR 3's decide step reads retentionCutoff
indexedSources() files(), returning the whole row

Added: files(), setFileState(path, state, atMtimeMs?), stateCounts(), retentionCutoff. Kept: indexedFile, removeFile, beginWrite, writeCommitted, reportWriteFailure, setRetentionCutoffMs, purgeOlderThan, connection, close. indexedFileCount and STALE_PATH_LIMIT are 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), the visible_* views (tests read sessions and messages) and the tombstone table recoveredRows counted. PR 2's round-8 fixes then made indexedFile report 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.ts and its test, session-search-backfill-remainder.ts, session-search-reconcile-budget.ts and its test, session-search-backfill-pacing.ts and its test, session-search-root-recovery.ts, session-search-registered-store.ts, session-search-discovered-counts.ts and 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, SessionSearchRegisteredStore and its removal debt, SessionSearchRetentionWindow with narrowsSessionSearchHistory / widensSessionSearchHistory / SessionSearchRetentionChange, sessionSearchAgentForPath, queuedCandidates and restatCandidate (which existed to resolve a path invalidate() named and the index had never held), SessionSearchWorkLoop.disarm / abort / afterTask, and store.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. disarm and abort had exactly one caller each once pause and clear were gone, and both were close().

files insertions
production, before (round 8, rebased) 25 2,906
production, after 19 2,234
including tests, before 41 5,579
including tests, after 32 4,883

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 both invalidate cells). Four came in: the periodic sweep comes round, every pass out of time at its first file, reconstructed for a narrower history window and the index thrown away and rebuilt — the last two being what replaced setHistoryDays and clear, run through the documented recipe rather than described.

Mutations, each against the whole src/main/ai-vault-search suite (227 tests):

mutation tests failed
the retirement walk always retires 75
the pass deadline is never consulted 7
the deadline applies from the first file rather than the second 14
work the pass did not read is not put back on the queue 5
the periodic sweep is never armed 2
reconcile() before start() is allowed 1
the sweep flag is cleared after the sweep instead of before 1
close() does not close the work loop 1
the queue's bound never drops anything 1
a half-written file is current if its stat matches 1
the pass appends to a half-written file instead of reading it whole 1
a half-written file is charged nothing to read 1

close() 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; current ignoring 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.droppedPendingFileCount to status().droppedPending is 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 6a1bcfdf49 before it was fixed and each repro kept as a test.

  • A transcript deleted between a sweep and the cycle after it survived until the next sweep — five minutes at the default cadence, and the round-9 change is what introduced it. A cycle proves a deletion by comparing what the previous pass watched against what it discovers, and round 9 made a sweep watch only what it could not settle, which is nothing on a healthy machine. So the cycle after a sweep had no candidates at all, and by the cycle after that the path was no longer in the watch set to miss. The sweep now seeds the watch set with its own recency window, taken from its own discoveries through 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.
  • A transcript the reader cannot open occupied the queue for ever. The consumer records a file stale on any read that does not commit, so an unreadable transcript was re-read every cycle: pending stuck at one, a failure count climbing without bound, and a phase that never left 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, and status() 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. indexedSources throws 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.
  • Two indexers on one database both registered with the reader and wrote every transcript twice, with the second write fenced by the first at random and no error anywhere. The second construction now throws. The recipe for every configuration change is close-then-construct, so the ordering that caused this is the one the recipe already rules out.

Mutations, each against the whole src/main/ai-vault-search suite (247 tests):

mutation tests failed
the sweep does not seed the watch set with its recency window 1
the hold-out is never consulted 1
the pass does not stop at a cancellation 1
status() reads the store after a close 1
a completed sweep does not clear the drop count 1
a second indexer on one database is allowed 1
a sweep that threw does not put its flag back 1
a failed held-file read is folded into an empty list 1

Three 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, and store.indexedSources / indexedFileCount losing 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.

gone why it existed what answers it now
previousRecent / the watch set, redefined three times deletion candidates store.files() minus discovery, scoped
the hold-out map, 1,000 entries, oldest dropped unreadable files state='failed' + fail_count + failed_mtime_ms
the store's 20,000-entry stale set, droppedPending, forgetDroppedPending pause, declined reads state='due'; there is nothing to drop
bytesIndexed, unreadableFiles, and their reset rules status count(*) … GROUP BY state
the sweptClean latch "is the index current" lastSweepCompletedAt
SessionNewestFiles seeding of the watch set the round-10 HIGH not needed: candidates come from the store
session-search-backfill.ts, session-search-reconciler.ts sweep and cycle one session-search-pass.ts; they differed only in discovery scope
session-search-indexing-status.ts, session-search-unreadable-files.ts counters, hold-out deleted outright
PR 3's isSessionSearchFileCurrent in session-search-file-cursor.ts the freshness check the decide step, which now owns the one spelling

normalizeSessionSearchHistoryDays is 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':

files insertions
round 10 (patched) 19 2,234
round 11 18 1,850

Mutations, each against the whole src/main/ai-vault-search suite (247 tests):

mutation tests failed
the walk always retires (I1) 77
retirement candidates come from memory instead of the rows (S2) 53
the consumer never records a failure (S3) 8
status is a counter instead of a query over the rows (S1) 6
the decide step ignores failed_mtime_ms, so a changed stat never releases (S3) 3
a pass that ran out of time does not ask for a sweep 2
a cycle's retirement scope is unordered, so the newest rows are not preferred 1

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 the GROUP 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.ts covers the decide step directly, which is where the whole policy now lives.

Round 12

Three HIGHs from the final review, each reproduced on d256580dba before it was fixed and each repro kept as a test. One commit per finding.

  • A block of unreadable rows starved retirement for ever. The walk's cap counted rows, and a directory that cannot be listed answers unverifiable for 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.
  • A failed open poisoned the database path. The claim on a path was staked before the store opened it, and a construction that throws has no 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.
  • Every OpenCode session was re-decoded on every pass. 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 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. The sidebar's cached fold — the STA-1278 and STA-1417 fix — was thrown away with it. 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. Three passes over one unchanged database are one decode. Nothing in the decide step knows what OpenCode is.

Mutations, each against the whole src/main/ai-vault-search suite (251 tests):

mutation tests failed
the retirement cap counts rows again 3
the database path is claimed before the store opens 1
a declined source writes no row 1

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.setAcceptingWrites now 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).

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 1 → bce6204, 7d2cda9

An Opus adversarial review of 9667e6c found two HIGH, three MEDIUM, and two follow-ups on the bound commit. All fixed.

  • HIGH: pause during a backfill abandoned the sweep permanently (reproduced). The "sweep due" flag cleared before the await; the abort was swallowed; resume only re-armed after a long pause. 20 transcripts, pause at the first pace, resume, 5 cycles → 12 of 20 indexed and status current. Now a sweep is due until it completes, and drained-but-unread queue entries go back.
  • HIGH: the retention cutoff was frozen at construction (reproduced). Purge used a fresh clock but the store's accept predicate held the start-time cutoff, so every sweep purged and rewrote the same rows; a 30-day window never expired anything while the process lived. Refreshed before any accept decision in a pass.
  • MEDIUM: an invalidate()d path the index had never held was silently dropped; now resolved through the same root table discovery reads, and anything unresolvable stays queued and counted.
  • MEDIUM: status honesty, four ways: attempt count → held count; current now requires no pending work, no degraded roots, and a completed sweep; closed phase added; a declined read is no longer counted as indexed.
  • MEDIUM: the whole-read check-then-drop ran outside the per-path parse lane and could be overtaken by a sidebar parse. The lane is not re-entrant, so it became a requireRead argument evaluated inside the lane.
  • Backfill retirement now consults root health: a root that stops listing is degraded, not retired.
  • Bound commit follow-ups: filesPending double-counted a path in both queues (now a union by path); the queue cap had silently risen 10x (back to 2,000 with the reason written down; worst case 22,000 retained candidates, stated).
  • The indexer crossed the line limit; the task queue, timer and abort moved to session-search-work-loop.ts. No lint disable.

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; current ignoring pending work fails 1; summing the queues instead of the union fails 1.

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 2 → ee4e52d

Second Opus round found that two round-1 fixes landed on the sweep path only; the 20 s reconcile cycle defeated both.

  • HIGH (reproduced): cycle retirement had no root-health guard. The sweep spared an unmounted root's rows; one cycle later retired them. The guard now lives inside retireDeletedSessionSearchSources, which both paths call, so there is one copy. A degraded root keeps its last healthy file count until a sweep lists it non-empty again (the alarm was single-shot before), and the cycle receives the sweep's counts read-only so it can detect an N→0 too.
  • HIGH (reproduced, regression from round 1): invalidate() on an unchanged file never settled. "Indexed" was defined as "cursor moved", and a forced re-read of an unchanged file writes the same cursor, so the path was re-read whole every interval forever with status pinned at indexing. Now "the index took it" means the store's record matches the file's current stat, the same predicate the skip at the top of the pass uses, so "worth reading" and "took it" cannot drift.
  • MEDIUM: an abort could lose stale entries because the store drains up to 20,000 but the indexer queue caps at 2,000. Entries that came from the store now go back to the store.
  • A surviving mutation on the aborted-sweep status latch is pinned.
  • status()'s per-poll COUNT(*) was closed rather than fixed: SyncDatabase.prepare already keeps a statement cache and this SQL is cacheable, so a poll is a cache hit; a maintained counter would be a second source of truth for no gain.

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.

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 3 → e4a509d

Third 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.

  • HIGH (reproduced): the degraded-root fence was inert for OpenClaw. Its sidebar discovery merges two roots into one delimiter-joined label, and every fence path compared against that label, so an unmounted OpenClaw tree was retired on sweep and cycle. Health now operates on the constituent directories, sourced from the same source table discovery reads (never by splitting the label, since a directory may legally contain the delimiter); files are attributed to the directory they live under. The sidebar's convention is untouched.
  • MEDIUM (reproduced): the N→0 latch never cleared. A root the user legitimately emptied stayed degraded for the process's life with degraded outranking current. Rule, written at the function: a root that readdirs successfully and lists empty on two consecutive full sweeps is believed and retires; a root that cannot be listed stays degraded indefinitely; a cycle never advances the tally.
  • A forced whole read charging the pre-read size to the allowance is left as an intentional under-count, with the reason at the charge site.

Behaviour note for PR 3b: a readable root that lists empty now retires on the second full sweep. Two explicit reconcile({ full: true }) calls in quick succession will retire an emptied root; do not wire a retry loop to it.

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.

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 4 → 506fdb2

Fourth Opus round: round-3 fixes held (segment-bounded root ownership, symlink/WSL spellings cannot diverge, no sidebar-facing file changed). Three findings, all fixed.

  • HIGH (reproduced): the fence was inert on the first sweep of every process. Root health state lived only in memory, so after a restart "held transcripts before" was 0 and a detached volume's ENOENT read as "agent never installed"; one start retired every row. The evidence is now the store: holdsFiles(root) is read from indexedSources, a root that ENOENTs while the index holds files under it is degraded, and only a root the index holds nothing under is absent.
  • MEDIUM (reproduced): "two consecutive" was not consecutive. An unlistable sweep between two empty ones did not reset the tally. It does now.
  • MEDIUM (reproduced): rows under no configured root were immortal and still searchable. Now reported as orphanedFiles in status and retired only when their file is gone (never silently deleted while the file exists). Orphans are judged against the roots this scan actually walked, so OpenCode and Antigravity roots are not mistaken for orphans.
  • Three surviving mutations pinned: segment-bounded ownership, cycles never advancing the emptied tally, aborted sweeps never counting. The third was an equivalent mutant; rather than contrive a test the worker removed the reachability: an incomplete sweep now skips the health pass and carries the previous state, which also fixed an unnamed bug where a pause mid-sweep published an empty degraded list and cleared a live unmount alarm.

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 package job failed on this and the sibling PR from 17:24 UTC with an apt Hash Sum mismatch from the Google Chrome repository on the runner image, before any test ran. External; the mirror is consistent again and the job is being rerun.

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 5 → f51572d

Fifth 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:

  • HIGH (reproduced): round 4 covered one unmount shape, not both. The missing-root branch read "held before" from the store, but the present-but-empty branch still armed from memory, and a Linux/WSL/sshfs unmount leaves the mountpoint present and empty. First sweep of a process → every held row under it retired, status current. Now both branches consult the store.
  • MEDIUM (reproduced): nothing re-armed a full sweep when a root recovered. Root absent at start, remount, and only the recency window was ever indexed; the rest was unreachable for the process's life. A cycle that sees a root return to healthy-with-files now re-arms a full sweep, gated on at least one completed census so early cycles are not turned into sweeps.
  • A surviving mutation on hasIndexedFilesUnder turned out to be a coverage gap, not a bug: the query was already segment-bounded on both separators, verified against real SQLite. Tests added, no behaviour change.

Cost measured by the reviewer: holdsFiles is one indexed range scan per root per sweep, 0.003 ms per call; the whole health pass is 2.1 ms at 3,000 files / 20 roots.

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: package continues to fail on the runner's apt-get update with a Hash Sum mismatch from Google's Chrome apt repository (their Packages.gz does not match their own Release file; verified from outside GitHub). External; reruns are queued until the mirror is consistent.

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 6: converged.

Sixth Opus round was a pure lifecycle matrix on f51572debc: 11 operations (start; pause/resume; close/restart; clear/start; historyDays narrow then widen; invalidate indexed; invalidate unindexed; reconcile full ×2; delete 2 of 3; delete all 3; remount then 2 cycles) × 3 unmount shapes (ENOENT, EMPTY, EACCES) × 2 agent shapes (plain 2-root, and OpenClaw's merged-root label). 66 of 66 cells pass on four invariants: no row for a file that still exists is deleted; an unmounted root is named in degradedRoots with a real path; after remount plus a sweep every file under it is indexed; the phase is never current while a root is degraded. The close/restart cells start the second process after the unmount, so the restart's first sweep is the judging one.

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: session-transcript-reader.ts:68 accepts a resume when sizeBytes >= byteOffset and a newline sits at the offset, so an in-place rewrite of a transcript to exactly its previous byte length resumes at EOF and both the sidebar and the index keep the old text until something invalidates the file. One byte shorter or longer is caught. Pre-existing on main, shared with the sidebar; noted in the plan doc for a follow-up.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Round 7 (simplicity + correctness adversary → rewrite) → 66f5c22, 63efba1, 57b7218

Rounds 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 session-search-deleted-sources.ts, each one a test:

  • I1 a row is retired only when its file is proven gone: some directory between the file and its configured root lists successfully and the next path component toward the file is absent. I2 if nothing from the file's parent up to the root can be listed (ENOENT/ENOTDIR walked up; anything else unverifiable), nothing is proven and nothing is dropped. I3 identical on the first pass after a restart; no memory. I4 a deleted file or project directory retires on the first proving pass; no census, no waiting period.
  • Deleted: session-search-root-health.ts and its test, store.hasIndexedFilesUnder, lastHealthyCount, emptySweeps, EMPTY_SWEEPS_BEFORE_TRUSTED, holdsFiles, census, afterSweep, rootStates, sweptOnce, pausedAt. degradedRoots is now a per-pass readdir signal with no memory. One bit per root remains: a root that listed transcripts on the previous pass and none on this one is unverifiable for that pass.
  • Stated cost of I3: a volume mounted at exactly a configured root, unmounted so the mountpoint stays present and empty, is indistinguishable from an emptied root and retires (one pass of grace within a process; none on cold start). Realistic unmounts sit above the root and are safe structurally. Two named tests pin it.
  • HIGH (reproduced): close() never closed the work loop, so a queued clear() reopened the store and re-registered the consumer after quit. Store and registration are now one object with one lifetime; close() closes the loop.
  • Backfill was unbudgeted. The sweep now spends its own allowance (512 files / 128 MB per pass vs the cycle's 64 / 8 MB) and hands the rest back; later passes drain it without re-discovering. A 20 GB backlog drains in ~53 min instead of running unbounded.
  • Pause now means it. Narrowing while paused defers the purge and compaction; resume() no longer runs a sweep; start() while paused arms on resume and does not resolve as if a pass ran.
  • Flapping root re-arms a full sweep once per recovery; the root must list healthy on the following pass before it can buy another. Three flap rounds cost one sweep.
  • filesTotal clamped and cleared on cycles; the post-sweep watch set is unverifiable ∪ unchecked only.
  • Plan doc corrected: two concurrent reconcile({full:true}) calls produce one sweep and one cycle.

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; loop.close() removed fails 1; backfill allowance removed fails 2; purge not deferred while paused fails 1; re-arm unbounded fails 1.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Review round 8 (fresh adversary on the round-7 walk) → b7b2540, 1275dbe

The 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:

  • HIGH (reproduced): a full-sweep request during a running sweep was erased. The flag was cleared after the sweep returned, so widening retention or reconcile({full:true}) mid-sweep was lost and status read current. The pass now takes the flag on entry; an unfinished sweep sets it back. Two tests (widening mid-sweep; full reconcile mid-sweep). The first repro was dated against wall time while retention reads the test clock and passed with the fix reverted; the mutation run caught it, not the test run, and it is corrected in 1275dbe.
  • MEDIUM (reproduced): clear() then close() left the database on disk. The queued removal became a no-op once the loop closed while clear()'s promise resolved. Store, consumer registration and file now have one owner; close() performs a removal still owed.
  • MEDIUM: a row inside a container (OpenCode SQLite) was proven by the container file's existence. Now proven one level up (invariant I8): the container must be present and the pass must have enumerated it in full and successfully; an empty enumeration is not proof. Correction to the finding: not user-visible on this branch, since the index pass refuses every OpenCode SQLite candidate (parserPublishesMessages is false), so no such row can be held; a test pins that precondition. The guard is for when that gate opens.
  • MEDIUM: the backfill drain bounded bytes, not time. Pacing every 8 files × a 15 s load backoff × 512 files was up to 16 min inside one cycle. Every read pass now stops at one reconcile interval and hands the rest back.
  • status() before start() reports idle; reconcile() before start() is refused.
  • Follow-up recorded in the plan doc: a case-only path variant passed to invalidate() on a case-insensitive volume writes a duplicate row that the next sweep retires.

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.

@Jinwoo-H
Jinwoo-H force-pushed the session-search-pr3-lifecycle branch from 1275dbe to 6a1bcfd Compare September 10, 2026 19:08
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Round 9: immutable indexer (design change, user decision 2026-09-10) → rebased onto PR 2 b0c07f0e8e, head 6a1bcfdf49

Every prior round's lifecycle finding (pause not covering purges, resume sweeping, start-while-paused, clear-then-close, widening mid-sweep) was an interaction between live mutations. The indexer is now immutable after construction: a configuration change is close it, construct a new one. That is what PR 3b will do for settings and for the clear action.

  • Public surface: constructor, start(), reconcile({ full? }), status(), close() (+ settled() for tests). pause, resume, clear, setHistoryDays, invalidate and every state variable and branch they needed are deleted. reconcile() throws before start() and after close(). Store, consumer registration and indexer share one lifetime.
  • One queue (the store's re-read set; the consumer still marks a file stale on decline). The indexer pending queue, the backfill remainder and the union-by-path count are deleted.
  • One pacer: a wall-clock passDeadlineMs (default a quarter of the interval) checked between files; what does not fit goes back on the queue. The file+byte allowance and the load-average backoff are deleted. Duty cycle measured at a fifth of wall clock; a 20 GB first run drains in ~51–64 min.
  • Sweep cadence replaces root recovery: a full sweep on start() and every fullSweepEveryCycles (default 15, ~5 min). A warm sweep on a synthetic 3,645-transcript corpus is 71–78 ms; a cycle 44–53 ms. Root recovery, the flap bound and the re-arm path are deleted.
  • Status trimmed to phase (idle | indexing | current | degraded | closed), filesIndexed, bytesIndexed, filesPending, droppedPending, failures, degradedRoots, lastReconcileAt.
  • Kept unchanged: the stateless retirement walk (I1–I8), directory listings, per-pass degraded roots, scan-roots (OpenClaw constituent directories), the F4 native-chat test. Lifecycle matrix repruned to 60 cells (five operations left with their methods; four came in: the periodic sweep, a pass out of time at its first file, and the settings-change and clear recipes run rather than described).
  • PR 2 obligation honoured: a chunk-partial file (byteOffset: null) is never current, is read whole (not appended), and is charged its full size. Three tests, one per call site; the first attempt's mutation survived because mustReadWhole short-circuits the skip check, which is why the took-it check has its own test.

Size: source 2,906 → 1,999 lines (25 → 18 modules); with tests 5,579 → 4,462. git diff b0c07f0e8e HEAD over PR 2's core files is only the two store additions (indexedFileCount, indexedSources) and the isSessionSearchFileCurrent re-add.

Verification (rerun by the lead): tc; ai-vault + ai-vault-search (816 tests); both changed-code gates; native audit. Mutations rerun by the lead: walk always retires fails 75; deadline never consulted fails 5; close() skipping the loop fails 97; a half-written file current on stat match fails 1.

@Jinwoo-H
Jinwoo-H force-pushed the session-search-pr3-lifecycle branch from 6a1bcfd to d3ff27c Compare September 10, 2026 20:15
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Round 11: the store is the only memory (design v3, user decision 2026-09-10) → rebased onto PR 2 abeccc5905, head d3ff27c

Round 10's five findings were two design gaps, not five bugs: deletion candidates came from a diff of two in-memory snapshots, and a file had no state of its own. Every piece of cross-pass memory that grew to cover those (watch set, hold-out map, tallied counters, latches) is gone. What the indexer knows between passes is now a row in the store.

  • Three additive columns on files (schema version 5): state (current | due | failed), fail_count, failed_mtime_ms. The consumer writes them on commit / decline / throw. The hold-out policy is a WHERE clause: a file failed 3 times at an unchanged stat is not read until its stat changes.
  • One loop, four steps per pass: discover (recent window on a cycle, all roots on a sweep) → decide (sessionSearchReadDecision, a pure function of stat, row and cutoff, with requiresWholeRead consulted before the stat compare) → retire (store.files() minus what discovery returned, scoped, newest first on a cycle; the unchanged walk proves each one) → report (SELECT state, count(*) FROM files GROUP BY state). Backfill and reconciler collapsed into one session-search-pass.ts; they differed only in discovery scope.
  • Deleted: the watch set (previousRecent, SessionNewestFiles seeding), the hold-out map, the store's in-memory stale set and STALE_PATH_LIMIT, markStale/takeStale/pendingFileCount/droppedPendingFileCount/forgetDroppedPending/setAcceptingWrites/acceptsCandidate/indexedFileCount, bytesIndexed/unreadableFiles/droppedPending, the sweptClean latch (now lastSweepCompletedAt). Cross-pass fields left on the indexer: the root-grace bit, the cycle counter, the next-sweep flag, started, closed.
  • Two gaps the design did not state, caught by its own tests: a cycle only sees the newest window, so a pass that runs out of time asks for a sweep (self-limiting); and cycle retirement is ordered newest-first so a deletion inside the window is proven on the next cycle whenever it happened.
  • Invariants S1–S5 (status equals a hand-written SQL query over a second connection; a deletion at any phase boundary is retired on the next covering pass; three failures at one stat hold a file out until it changes; idempotent passes; close mid-pass leaves the store consistent) join I1–I8; each is a test. The 60-cell lifecycle matrix and the round-8 tests are green.

Size: source over PR 2: 2,234 lines at round 10 → 1,851. PR 3's footprint on PR 2's files is the three columns, the consumer's state writes, and the store surface swap.

Verification (rerun by the lead): tc; ai-vault + ai-vault-search (836 tests); both changed-code gates; native audit. Mutations rerun by the lead: decide ignoring failed_mtime_ms fails 3; consumer never recording a failure fails 8; retirement candidates from nothing instead of store.files() fails 63; status a constant instead of a query fails 9; walk always retires fails 77.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Round 12: final review, three HIGHs fixed → 084f568b89 (stop rule: HIGH-only, reproduced; the rest is in the plan doc's follow-ups)

  • Retirement starvation (reproduced). The walk's 512 cap counted rows in a stable order and discarded the rest, so 520 rows under an unreadable directory kept a genuinely deleted file under a healthy sibling searchable across six full sweeps. The cap now counts directories the walk reads; rows sharing a directory are one read then map lookups, so an unreadable block cannot crowd anything out. The deleted sibling retires on sweep 1.
  • A failed open poisoned the path (reproduced). The one-indexer-per-path claim was staked before the store opened and never released on throw, so one transient open failure refused every later construction for the process's life. The claim is now taken after the store opens.
  • OpenCode re-parsed every sweep (reproduced). The consumer declines OpenCode SQLite candidates, so they never got a files row; with no row the decide step read them whole every pass, which also invalidated the sidebar's parse-cache entry (the STA-1278/STA-1417 fix). A decline now writes the "read through, nothing to index" row the store already had a shape for. Three passes over one unchanged database are one decode; nothing in the decide step knows what OpenCode is.

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 fail_count; a persistently throwing beginWrite loops with the count at 0; post-deadline point queries per remaining candidate; filesIndexed counts unverifiable rows; discovery is not deadline-bounded.

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.

@Jinwoo-H
Jinwoo-H marked this pull request as ready for review September 10, 2026 20:45

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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() is GROUP BY state plus the pass's degraded roots.
  • Declined/unreachable sources — noteUnreachableParser writes a "read-through, no session" row so OpenCode sessions aren't re-decoded every pass (round 12 F3).
  • Lifecycle — immutable indexer, one work loop, liveIndexerPaths claimed after the store opens, close() disarms the timer and queued work.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Jinwoo-H
Jinwoo-H force-pushed the session-search-pr3-lifecycle branch from 084f568 to 202de2f Compare September 10, 2026 21:12
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.
@Jinwoo-H
Jinwoo-H force-pushed the session-search-pr3-lifecycle branch from 202de2f to 3cdb1af Compare September 11, 2026 03:31
@Jinwoo-H
Jinwoo-H changed the base branch from session-search-pr2-index to main September 11, 2026 03:31
@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: cf4a5618-c387-4372-8eef-4492dead886d

📥 Commits

Reviewing files that changed from the base of the PR and between 3cdb1af and 338f957.

📒 Files selected for processing (1)
  • src/main/ai-vault-search/session-search-indexer.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

Adds 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 338f9

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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,… 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, includin…
Docstring Coverage ⚠️ Warning Docstring coverage is 54.79% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 73 functions across 34 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: a session search indexer library that owns backfill, reconciliation, and retention.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 value

Avoid a secondary teardown error when setup fails.

Both tests assign indexer only after awaited transcript setup. If that setup fails, afterEach adds 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c984bc and 3cdb1af.

📒 Files selected for processing (34)
  • src/main/ai-vault-search/session-search-clock.ts
  • src/main/ai-vault-search/session-search-degraded-roots.ts
  • src/main/ai-vault-search/session-search-deleted-sources.test.ts
  • src/main/ai-vault-search/session-search-deleted-sources.ts
  • src/main/ai-vault-search/session-search-directory-listings.test.ts
  • src/main/ai-vault-search/session-search-directory-listings.ts
  • src/main/ai-vault-search/session-search-file-write.test.ts
  • src/main/ai-vault-search/session-search-index-consumer.test.ts
  • src/main/ai-vault-search/session-search-index-consumer.ts
  • src/main/ai-vault-search/session-search-index-pass.test.ts
  • src/main/ai-vault-search/session-search-index-pass.ts
  • src/main/ai-vault-search/session-search-index-writer.test.ts
  • src/main/ai-vault-search/session-search-indexer-options.ts
  • src/main/ai-vault-search/session-search-indexer-test-fixture.ts
  • src/main/ai-vault-search/session-search-indexer.test.ts
  • src/main/ai-vault-search/session-search-indexer.ts
  • src/main/ai-vault-search/session-search-lifecycle-matrix.test.ts
  • src/main/ai-vault-search/session-search-live-transcript.test.ts
  • src/main/ai-vault-search/session-search-merged-roots.test.ts
  • src/main/ai-vault-search/session-search-native-chat-indexing.test.ts
  • src/main/ai-vault-search/session-search-opencode-decline.test.ts
  • src/main/ai-vault-search/session-search-pass.ts
  • src/main/ai-vault-search/session-search-read-decision.test.ts
  • src/main/ai-vault-search/session-search-read-decision.ts
  • src/main/ai-vault-search/session-search-retention-policy.test.ts
  • src/main/ai-vault-search/session-search-retention-policy.ts
  • src/main/ai-vault-search/session-search-scan-roots.test.ts
  • src/main/ai-vault-search/session-search-scan-roots.ts
  • src/main/ai-vault-search/session-search-schema.ts
  • src/main/ai-vault-search/session-search-store-is-memory.test.ts
  • src/main/ai-vault-search/session-search-store.ts
  • src/main/ai-vault-search/session-search-synthetic-sources.ts
  • src/main/ai-vault-search/session-search-work-loop.ts
  • src/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.

Comment on lines +111 to +115
const listings: SessionSearchDirectoryReader = {
namesIn: (directory, signal) => {
asked.add(directory)
return args.listings.namesIn(directory, signal)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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').

Comment on lines +82 to +87
const committed =
write?.commit({
session: null,
byteOffset: candidate.file.sizeBytes ?? 0,
incomplete: false
}) === true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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)

Comment on lines +141 to +158
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: [] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +58 to +60
export function isUnderScanRoot(path: string, root: string): boolean {
return root.length > 0 && (path.startsWith(`${root}/`) || path.startsWith(`${root}\\`))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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-search

Repository: 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.ts

Repository: 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.
+        }
       }

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No blocking issues — one misplaced import and one optional test gap, noted below.

Reviewed changes

  • Normalized the one-writer guard's key — liveIndexerPaths now keys on resolve(options.databasePath) (the resolved absolute path) instead of the raw databasePath, 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 owns test passes the same absolute path twice, so it would stay green even without the resolve normalization. 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

return sessionSearchHistoryCutoffMs(this.options.historyDays, this.clock.now())
}
}
import { resolve } from 'node:path'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant