Repository navigation
feat(ai-vault-search): session search query engine over the index - #20029
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This re-land of #19750 adds the session-search query engine as a library over PR 2's single-table FTS index. I read the full diff end to end, dispatched two specialist passes (FTS5 scope-isolation and the generation/cursor fence), and re-ran the ai-vault-search (449 tests) and shared-parser (45 tests) suites locally — all green.
- Route ladder & planner — phrase → AND → typo repair → OR, planned against the unicode61 tokenizer contract;
scopedExpressionparenthesizes theconversationcolumn filter so it binds the whole query. - Retrieval & ranking — one-row-per-session bm25 ranking (
max(score)over-bm25), tunable candidate limit with honesttruncated.candidates, and an operator-onlyrecentwalk. - Generation fence — three
filestriggers plus aWHEN-guarded orphan-reclaim trigger onmessages; cursors rejected with a typedSessionSearchCursorErrornaming both generations. - Snippet & typo repair — private-use marks compared per column (marked vs unmarked) so transcript
[[cannot forge a highlight; scoped live-row counts joined tosessionsso orphan/tool-only rows neither propose nor suppress a repair. - Shared operator parser —
splitAiVaultSearchQuerymakesrepo:/path:mean one thing in the panel and the index.
The scope-isolation fence (scopedExpression) is single-sourced and its only behavioral cost is the documented bm25 length-normalization effect on ranking order, which is test-pinned. The generation fence covers every visibility-changing write path and serializes correctly across connections.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughAdds a complete session search engine with FTS5 query planning, scoped retrieval, typo repair, ranking, snippets, filters, pagination, and generation fencing. Adds shared Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Operator-only results can incorrectly claim truncation, invalid candidate-limit configuration can break search bounds, and a documented benchmark setting can hang. Resolve or explicitly accept these limitations before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a detailed and relevant summary, implementation scope, behavior, and validation results. However, it does not follow the required template and omits the required linked issue, visual proof or N/A statement, testing checklist, AI disclosure, review notes, boundary checkbox, and final checklist. Resolution Restructure the description using the repository template. Add the required Linked Issue, Visual Proof, Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections. Include a valid issue reference after “Fixes #” and mark non-applicable items explicitly. Full details: Docstring CoverageExplanation Docstring coverage is 45.98% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 87 functions across 33 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (1)
src/main/ai-vault-search/session-search-sidebar-parity.test.ts (1)
97-100: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winUse the production parser for quoted operators.
This whitespace split truncates
path:"/Users/ada/My Project"topath:"/Users/ada/My. The parity suite therefore cannot validate operator values that contain spaces.Pass the complete query to
filterAiVaultSessions. All current fixtures already contain the commonharborterm.Proposed change
function sidebarIds(query: string): string[] { - const operatorsOnly = query - .split(/\s+/) - .filter((token) => /^(repo|path):/i.test(token)) - .join(' ') return filterAiVaultSessions(SESSIONS.map(asSession), { - query: operatorsOnly, + query,
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: a8006e86-58f1-4c66-becd-82aa7b60a493
📒 Files selected for processing (35)
.gitignoreconfig/scripts/session-search-query-benchmark.tsconfig/scripts/session-search-scope-benchmark.tsconfig/scripts/session-search-tool-heavy-corpus.tsdocs/reference/agent-session-search-query-tuning.mdsrc/main/ai-vault-search/session-search-engine-test-fixture.tssrc/main/ai-vault-search/session-search-engine-types.tssrc/main/ai-vault-search/session-search-engine.test.tssrc/main/ai-vault-search/session-search-engine.tssrc/main/ai-vault-search/session-search-fts5-contract.test.tssrc/main/ai-vault-search/session-search-hit-ranking.test.tssrc/main/ai-vault-search/session-search-hit-ranking.tssrc/main/ai-vault-search/session-search-index-generation.test.tssrc/main/ai-vault-search/session-search-index-generation.tssrc/main/ai-vault-search/session-search-orphan-rows.test.tssrc/main/ai-vault-search/session-search-page-cursor.tssrc/main/ai-vault-search/session-search-paging.test.tssrc/main/ai-vault-search/session-search-query-log.test.tssrc/main/ai-vault-search/session-search-query-log.tssrc/main/ai-vault-search/session-search-query-planner.test.tssrc/main/ai-vault-search/session-search-query-planner.tssrc/main/ai-vault-search/session-search-query-schema.tssrc/main/ai-vault-search/session-search-retrieval.tssrc/main/ai-vault-search/session-search-row-filter.test.tssrc/main/ai-vault-search/session-search-row-filter.tssrc/main/ai-vault-search/session-search-sidebar-parity.test.tssrc/main/ai-vault-search/session-search-snippet-marks.test.tssrc/main/ai-vault-search/session-search-snippet.tssrc/main/ai-vault-search/session-search-source-presence.tssrc/main/ai-vault-search/session-search-typo-policy.test.tssrc/main/ai-vault-search/session-search-typo-repair.tssrc/main/ai-vault-search/session-search-typo-scope.test.tssrc/shared/ai-vault-search-query-operators.test.tssrc/shared/ai-vault-search-query-operators.tssrc/shared/ai-vault-session-filters.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
| ...QUERIES.map((query) => `"${query}"`), | ||
| // Eight terms, quoted: an ordered run that long does not occur in 105 MB of | ||
| // draws from fourteen words, so the phrase rung misses and AND answers. | ||
| ...QUERIES.map((_query, index) => `"${run(index, 4)}"`) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Generate the documented eight-term AND fallback queries.
run(index, 4) creates four-term quoted phrases. The benchmark therefore does not implement the documented eight-term phrase-miss workload. This invalidates the reported AND-route measurement contract. Change the query width to eight terms, rerun the benchmark, and regenerate the table.
config/scripts/session-search-scope-benchmark.ts#L115-L115: callrun(index, 8)for the phrase-miss query group.docs/reference/agent-session-search-query-tuning.md#L113-L117: regenerate the AND-route values after the corrected benchmark run.
📍 Affects 2 files
config/scripts/session-search-scope-benchmark.ts#L115-L115(this comment)docs/reference/agent-session-search-query-tuning.md#L113-L117
|
|
||
| const corpus = await writeToolHeavyCorpus({ | ||
| targetBytes: Number(process.env.CORPUS_MB ?? 100) * 1024 * 1024, | ||
| toolShare: Number(process.env.TOOL_SHARE ?? 0.9) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Reject an invalid TOOL_SHARE value before corpus generation.
TOOL_SHARE=1 reaches writeToolHeavyCorpus() as 1. Its word-count calculation divides by zero and returns Infinity. The words() loop then does not terminate. Validate that the value is finite and in the range [0, 1) before indexing.
Proposed fix
const corpus = await writeToolHeavyCorpus({
targetBytes: Number(process.env.CORPUS_MB ?? 100) * 1024 * 1024,
- toolShare: Number(process.env.TOOL_SHARE ?? 0.9)
+ toolShare: (() => {
+ const value = Number(process.env.TOOL_SHARE ?? 0.9)
+ if (!Number.isFinite(value) || value < 0 || value >= 1) {
+ throw new Error('TOOL_SHARE must be a finite value in [0, 1)')
+ }
+ return value
+ })()
})| private readonly db: SyncDatabase, | ||
| private readonly options: SessionSearchEngineOptions = {} | ||
| ) { | ||
| this.candidateLimit = options.sessionCandidateLimit ?? SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Reject invalid sessionCandidateLimit values.
SessionSearchEngineOptions.sessionCandidateLimit accepts any number and reaches SQLite LIMIT clauses and scan bounds without validation. Negative values can remove the SQLite limit, zero suppresses candidates, and fractional or non-finite values can fail query execution. Require a positive safe integer before constructing SessionSearchRetrieval.
Proposed fix
- this.candidateLimit = options.sessionCandidateLimit ?? SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT
+ const candidateLimit =
+ options.sessionCandidateLimit ?? SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT
+ if (!Number.isSafeInteger(candidateLimit) || candidateLimit <= 0) {
+ throw new RangeError('sessionCandidateLimit must be a positive safe integer')
+ }
+ this.candidateLimit = candidateLimit📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| this.candidateLimit = options.sessionCandidateLimit ?? SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT | |
| const candidateLimit = | |
| options.sessionCandidateLimit ?? SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT | |
| if (!Number.isSafeInteger(candidateLimit) || candidateLimit <= 0) { | |
| throw new RangeError('sessionCandidateLimit must be a positive safe integer') | |
| } | |
| this.candidateLimit = candidateLimit |
| const MARK_OPEN = '\uE000' | ||
| const MARK_CLOSE = '\uE001' |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Preserve private-use characters in the selected transcript column.
The comparison at Lines 93-96 prevents a content character from selecting the wrong column. It does not protect the selected column.
If the selected text contains \uE000 or \uE001, publicMarks converts that content into a public highlight marker. truncateSnippet can also treat a literal \uE000 as an unmatched structural mark and discard valid text.
Track inserted marker positions by comparing the marked and unmarked renderings. Replace and balance only inserted markers. Add a regression case where the matching column contains both the query term and literal \uE000 or \uE001.
Round 6: CodeRabbit findings on the re-landFive fixed, three skipped on purpose, one finding was wrong.
Gates on |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
config/scripts/session-search-scope-benchmark.ts (1)
175-205: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winReject
TOOL_SHARE >= 1before callingwriteToolHeavyCorpus. The environment value reaches the generator without validation. AtTOOL_SHARE=1, its tool-word calculation producesInfinity, sowords()never exits its loop. The benchmark never writes a corpus or reaches indexing and reporting. Validate the value as finite and below1, or clamp it, before invoking the generator.src/main/ai-vault-search/session-search-engine.ts (2)
110-125: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winValidate
sessionCandidateLimitbefore constructing retrieval scope.
SessionSearchEngineforwards this option directly toSessionSearchRetrieval, which interpolates it intoLIMITand uses it as a loop bound. Zero suppresses results, negative values can remove SQLite’s text candidate bound, and fractional, non-finite, or excessively large values can make SQLite reject the query. Accept only positive safe integers, or fall back to the default before retrieval is created.
122-190: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftKeep
SessionSearchEngine.searchgeneration-consistent
readIndexGenerationruns before retrieval, session loading, source-presence reads, and snippets. These operations use separate SQLite statements without one read transaction. If the indexer commits between them, the response can combine different generations whilegenerationandencodeSessionSearchCursorstill use the earlier value. The next page can then fail withstale-generation. Re-read the generation after all result reads and retry or reject when it changed, or execute the complete read in one snapshot.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b27c24c3-7551-4bb4-b5e9-478da99636bf
📒 Files selected for processing (8)
src/main/ai-vault-search/session-search-index-generation.test.tssrc/main/ai-vault-search/session-search-page-cursor.tssrc/main/ai-vault-search/session-search-paging.test.tssrc/main/ai-vault-search/session-search-row-filter.test.tssrc/main/ai-vault-search/session-search-row-filter.tssrc/main/ai-vault-search/session-search-sidebar-parity.test.tssrc/main/ai-vault-search/session-search-snippet-marks.test.tssrc/main/ai-vault-search/session-search-snippet.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/ai-vault-search/session-search-row-filter.test.ts
- src/main/ai-vault-search/session-search-page-cursor.ts
- src/main/ai-vault-search/session-search-row-filter.ts
- src/main/ai-vault-search/session-search-paging.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Five fix and test commits landed since the prior pullfrog review (b209612), all within src/main/ai-vault-search/:
- Snippet mark attribution —
splitMarks/renderSnippetreplace the globalreplaceAllof private-use marks: the marked and unmarked FTS5 renderings are compared code point by code point, so a transcript's own private-use glyph stays text instead of being rewritten into a highlight, and truncation drops an unclosed mark at the ceiling. - Unkeyable scope narrowing — a non-empty
scopePathswhose scopes all failcwdKeynow emits0 = 1rather than no condition, so an empty-string scope returns nothing instead of widening to the whole index. - Cursor generation validation — a fractional or negative generation is now rejected as
malformed(notstale-generation), since a counter is never fractional. - Parity suite —
sidebarIdspasses the full query instead of an operators-only whitespace split, so quoted operator values containing spaces are actually exercised; new fixtures coverpath:"/Users/ada/My Project"andrepo:"ada/My Project". - Trigger-restore test — bumps
mtime_mswith a bareUPDATE filesso it exercises thesearch_generation_file_updatetrigger it dropped, rather than re-indexing (which fires the INSERT/DELETE triggers regardless).
I re-ran the five touched test files (81 tests) — all green.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…be fenced by A search page is a slice of one ranked list, so a cursor only means anything against the snapshot that produced it. The store now keeps a monotone generation in `meta`, bumped by every mutation that can change which rows a read returns, and starts a new one on open so a write whose bump never landed cannot leave a cursor pointing at content that is already gone. Schema version 2 adds the two tables the query layer needs: `messages_vocab` (fts5vocab over messages_fts, the typo repair's whole dictionary) and `search_log`. Both are pure additions and the index is a cache, so a version-1 file is dropped and rebuilt exactly as any other mismatch is.
The planner unfolds the tokenizer contract instead of asking SQLite: same boundaries as `unicode61 tokenchars '_.-/+'`, pinned against real fts5vocab output so a query can be planned without a round trip. It decides the route ladder's first rung (literal shape), strips stop words from prose but never from a literal, and fans an identifier out into its pieces for the OR fallback. Typo repair uses the index's own vocabulary as its dictionary, so it can never suggest a term the index does not hold. Its exact-match probe now joins `visible_messages`: `messages_vocab` is a view over the FTS b-tree and still lists staged and tombstoned terms, and the PR 2 read ratchet is right to demand the join. `splitAiVaultSearchQuery` is the index's reading of repo: / path:. It keeps operator case, which the panel folds and cwd_key must not; a census test pins the two parsers to the same answer about what is an operator until PR 7 moves the panel onto this one.
Every caller-supplied narrowing in one place, so retrieval, the operator-only page and the session load cannot drift apart: agents, an updated-at floor, the retention cutoff, scope paths, and the repo: / path: operators. Scope keying goes through PR 2's `cwdKey`, which is the sidebar's `folderGroupKey` without its prefix, rather than the original branch's second spelling. That drops the branch's WSL distro qualification, which PR 2 removed on purpose, and it makes the filesystem root a key that already ends in a separator, so the child-prefix range is built from the key rather than by appending one; `//` sorts below every real child and would scope the root to nothing. Engine types land here too, under src/main and not src/shared: nothing in this PR is a wire type, and PR 5 lifts what a caller may receive.
`SessionSearchEngine.search()` over the PR 2 store: route ladder (phrase, AND, typo repair, OR), BM25 weights per corpus, one hit per session, fork folding, and a page. - `scope` picks the corpus and the engine never second-guesses it. `conversation` is user and assistant turns; `all` adds tool output and the identifier shadow column. Switching corpus while typing is PR 7's policy; an engine that widened on a miss would make a result impossible to reproduce from its own request. - Pagination is an offset into one ranked list, fenced by the index generation and by a hash of everything that changes the ranking. A cursor from another generation or another query is refused with a typed error rather than silently re-run. Ranking breaks every tie by session id, because a cursor indexes into that order and retrieval does not promise one. - Snippets and source presence are paid for by the page, not the list. A snippet past the per-hit ceiling is cut on a code point, never between `[[` and its `]]`, and flagged on the hit. - Source presence is read from the `files` table. No stat on the query path, and no `missing`: only a proven deletion may claim one, and this read cannot prove it. - `SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT` is an option, not a constant, and the result says when the limit was what cut the answer. - The engine is the only caller of `store.warm()`, on first search. Library only: no IPC, no settings, no Electron, nothing constructs it in production.
…ate limit buys Two corpora, because they answer different questions. The 10.5 MB / 40-session corpus is what the scope split costs a reader: conversation is about 1.6x faster at p50 and 3.4x at p95 than the full corpus, which is the argument for the second FTS table being the one a keystroke can afford. The candidate limit needs more sessions than the limit before it costs anything, so it is swept over 2,500 one-turn transcripts with every session matching. Limits are interleaved sample by sample: run back to back, the first configuration pays for every page the OS cache had not seen and the ordering alone moved p95 further than the limit did. The doc says plainly what these numbers do not cover. They are cost, not relevance; the MRR figures quoted beside the BM25 weights and the identifier shadow column come from a shoot-out over real transcripts and cannot be reproduced from this repository.
…chable pages honestly The page key was hashed twice per search, once to decode the incoming cursor and once to mint the outgoing one. The benchmark's reachable-page figure was clamped against a constant that could never bind; it is the limit over the page size and nothing else.
The warm wiring and the query-length cap were both written and neither was observable. A spy pins that a search is what warms the store, and the cap is pinned through the one input the planner's own term limit does not already bound: a single enormous token, where the cut is what decides whether the term matches the indexed one at all.
…ss cannot see The generation was cached in memory and moved only on this store's own writes, and the bump itself was a read-then-write outside any transaction. Two handles on one file is the normal case once PR 3 lands: the indexer writes in the scanner child while an engine reads elsewhere. A reader would see that writer's deletions while its own generation stood still, honour a stale cursor, and skip a session; two writers could mint one generation for two snapshots. `generation` now reads `meta` on every call, and the bump is a single `ON CONFLICT DO UPDATE ... + 1` inside the transaction that makes the change. That closes the crash hole the bump-on-open existed for, so opening a store no longer invalidates anyone's cursor. Only a change to what a read returns counts. Retiring a path the index never held hides nothing, and the row deletes that drain a tombstone take away rows that were already invisible: bumping there would refuse a cursor every 256 rows and leave pagination unusable for as long as indexing ran. Also drops redaction from the query log, following PR 2's decision to store transcript content as written; the module it called no longer exists.
…red literal whole Two smaller findings. An engine can be handed a connection to a version-1 file that another handle is still answering from, and this PR is what first makes that reachable. It now probes once for the two tables version 2 added and names what it cannot serve on every result, instead of throwing at the first query that reaches for a vocabulary that is not there. The route ladder simply skips its repair rung. Which process may unlink and rebuild the index is PR 3b's decision and is not solved here. Typo repair re-planned the corrected query from scratch, and a corrected spelling can read as prose even when what was typed was a literal: `parseJsonn(the, data)` has the punctuation, `parsejson the data` does not, so the re-plan dropped `the` as a stop word. The repaired query searched for less than was asked and `repairedTerms` reported a body nobody typed. The re-plan is now told what the original decided, because a repair changes spellings, not the query's character. `repairedTerms` is documented as the whole body the repaired plan ran, with the index's own case-folded spelling for the terms it corrected.
… and the index The engine said `repo:` and `path:` a second time, in SQL, and SQL cannot say them. LIKE folds ASCII and nothing else, so `path:CAFÉ` missed `café`; the engine searched `cwd_key` while the panel searches the working directory and the transcript path, so `path:jsonl` matched every session in the panel and none in the index; and the engine compared one path segment where the panel compares the last two, so `repo:orca/session-search` missed. All four reproduce in both directions. So there is one definition now, not two that resemble each other. `matchesAiVaultQueryOperators` moves into the shared filter module beside the panel that already owned the semantics, the panel calls it, and the engine applies it over the rows it retrieved. SQL keeps only what it can express exactly: the `cwd_key` prefix range for `scopePaths`. `parseVaultQuery` now parses through `splitAiVaultSearchQuery`, so one parser decides what an operator is. Its existing tests pass unchanged; four degenerate shapes do answer differently and are pinned as decisions rather than left to be discovered. Two consequences worth stating. The operators are conjunctive now, because that is what the panel has always done, where the engine had been ORing within a key. And the operator-only page walks newest sessions in bounded pages applying the predicate, rather than taking one cut of the newest N and filtering it, which would have answered `repo:x` with nothing on a busy index.
…tor change repo: and path: moved out of SQL, so the operator-only row measures something different now and the note that it is a range seek was wrong. The rest of the table is re-measured on an idle machine: the previous run's p95 column was mostly contention, which is why conversation looked 3.4x faster at p95 rather than the 1.7x it actually is. Adds what this PR does not settle: which process may unlink and rebuild the index is PR 3b's, and PR 4 is only the first thing that makes reading it reachable.
…h that finished The operator-only walk stops at a scan ceiling as well as at a full candidate set, and only the first of those reached the result. A query whose one match sat past the ceiling came back with no hits and truncated.candidates false, which is the engine claiming there is nothing to find when what happened is that it stopped looking. Retrieval now says why it stopped, because it is the only layer that knows, and the count it used to return could not distinguish the two cases. The cursor fence stays as it is: any published read moves the generation, so an outstanding cursor is refused, and that is what F11 asked for. What was wrong was the claim next to the row-delete skip that pagination stays usable through indexing. It does not, and the engine now says so. The rejection carries the generation the cursor was minted in and the one the index is at, so a caller can tell a moved index from a bad cursor and re-issue page one without showing anyone an error. The capability probe was nearly dead code, since every store opens through a function that rebuilds a stale file. It is not dead, because two handles can be open on one file, so the claim is corrected rather than the probe deleted. It now runs per search: a verdict cached in the constructor is wrong in both directions once another handle rebuilds the index. Also says why the row-delete loop may skip the bump: those messages keep batch_id NULL and stay in visible_messages, so what makes them unreachable is their session's tombstone, and the read ratchet is what keeps every reader joining the view that applies it.
…s not end a word Unifying the two parsers changed panel behaviour on nine of twenty probed shapes, not the three previously pinned. Six of the nine were regressions, all from one rule: the shared parser refused a quoted span whose closing quote was not followed by a space, so `"a b"c` and `repo:"a"b` became single terms carrying their own quote characters, which match nothing. The rule was justified as what stops the apostrophes in `it's a repo:orca thing's` from swallowing the operator between them. It is not: a span only ever opens at a token start, and the quote in `it's` is not at one. Dropping the rule restores all six shapes to what the panel has always done and leaves that protection intact. Three changes remain and are kept because the old answer was worse in each: an operator with an empty quoted value is dropped rather than filtering on `""` and silently emptying the list, and a bare pair of quotes reads as an empty term rather than as the two characters. Each is pinned with a test that says which behaviour it is and why.
…gine had to cut Three lows. `repo:" "` survived as a term and matched no label, silently emptying the list, which is the exact defect the empty-value drop exists to prevent wearing different clothes. Operator values are trimmed, and a whitespace-only one drops like an empty one. The substring matcher's copy of a free-text term is trimmed too, so `" "` reads as the empty term already does; the span kept for FTS is still the query verbatim. Two caps upstream of retrieval fired silently: the planner searches at most 48 terms, and the engine cuts the query at 512 characters. A 56-term query whose only match was the 56th came back with no hits and nothing truncated, which claims there is nothing to find. `truncated.query` now says when either fired, alongside the candidate and snippet flags that already did. Every cursor refusal now carries the generation the index is at, which the engine knows before it looks at the cursor, and the generation the cursor claimed wherever that survived parsing. The doc says exactly when each is present instead of leaving absence unexplained.
…s, and own the fence PR 2 deleted the visibility views, the staging tables and the store's generation, so this reads `sessions` and `messages` directly and carries the three schema objects only a query needs — the vocabulary, the query log, and the triggers that move the generation — as its own extension over the store's schema. The fence is now three triggers on `files`, because every transaction the store opens that can change what a search returns writes that table and nothing else does; retention's orphan drain is the one write path that touches neither, and it is the one that must not bump. The triggers live in the file, so a writer in another process moves the generation without knowing a reader exists. A message row can now outlive its session row until the drain reaches it, so the snippet read joins `sessions` and the typo repair asks for a live posting instead of trusting the vocabulary's document count. The engine takes a connection rather than a store: PR 2's store keeps its connection private, and which process may open or rebuild the index file is PR 3b's decision, not a query engine's.
…hout warmup Open decision 3. A column filter over `messages_fts` returns the identical rowid set as `conversation_fts` — checked here per query rather than assumed — so the table exists for latency alone. On a 105 MB corpus at both ends of the tool-output band, the column-filtered form costs 1.16-1.42x at p95, against a bar of 2x, so the recommendation is to delete it. The shoot-out writes its own corpus because the answer turns on the one property the shared generator fixes: how much of a transcript is tool output. Half the tokens in that output are words the conversation also uses, which is deliberately generous to the table under question. The doc records the number that argues the other way. PR 2 priced the table at about a quarter of the index on a corpus whose tool output is 56% of its message text; on a tool-heavy one it is 6.7-11%, because `messages_fts` grows with the tool text and the second table does not. Page warmup is not re-added. The measurement behind it was on a 4 GB index, removing it moves this corpus by less than the run-to-run spread, and a cancellable background pass needs a lifecycle a query library does not have.
…n filter
PR 2 deleted `conversation_fts` on the strength of this PR's shoot-out, so the
scope is a column filter over the one FTS table now. `ftsTableFor` is gone; a
scope is a pair of `scopedExpression` and `scopedWeights`, and the table name
no longer travels through the engine, the snippet builder or a hit.
The filter is parenthesised, and that is the whole of it: `{cols}: (a AND b)`
binds both terms, while `{cols}: a AND b` binds only the first and searches
tool output for the rest. A test drives an AND whose second term lives only in
tool output through both scopes.
The snippet keeps one guard, not two. Its column list and its expression were
each hiding the other's mistakes — a tool-only row was unreachable through
either — so the list is the same four columns for every scope and the scoped
expression is what makes a conversation snippet impossible to draw out of tool
output. Dropping it now leaks that row, which a test catches.
One behaviour the deleted table did not have, pinned rather than wished away:
bm25 normalises by the whole row's length and has no per-column length, so two
rows with identical prose score differently when one also holds tool output.
The rowid set is unchanged; the order within it can move.
Re-measured on the shipping schema. The conversation scope is 1.2-1.4x faster
than `all` at every rung, and the index is 57 MB rather than about 150 MB at
93% tool output, because a tool row is now capped at 3,072 characters.
…swer it Typo repair read `messages_vocab` and probed `messages_fts` with no column filter, so tool output decided whether a conversation-scoped query was repaired, in both directions. A tool row carrying the misspelling made the query look correctly spelled and suppressed the repair; a tool row carrying a rare word became the suggestion, naming in `repairedTerms` a string from a column the scope will never show. Both reproduced against a control index that differs by exactly that one row. The vocabulary proposes and a scoped count disposes. fts5vocab is per table and cannot be column-filtered, so every decision that reaches the plan — already spelled right, eligible, and which of two equally close candidates wins — now comes from a `messages_fts MATCH` under the same filter retrieval uses, joined to `sessions`. That also takes the vocabulary's `doc` out of the ranking, which is the half of the drain defect that belongs here: `doc` counts rows whose session a purge has already cut loose, so reclaiming them changed which word a query was repaired to. Candidates are ordered by term now, because the ordering decides which of them survive the scan limit, and ties on similarity go to the more common word counted live rather than to the vocabulary's number. The cost is one bounded count per candidate examined, at most eight per prefix, and only for a term the scope has no posting for at all.
… session loose Retention's second half deletes from `messages` alone and touched neither `files` nor `sessions`, so it moved no generation. The argument was that those rows answer nothing, which was true of retrieval and not of the engine: the typo repair's dictionary is a view over the FTS b-tree and listed them, so a drain running between two pages swapped the repair under a cursor that was still honoured, and a search that had answered stopped answering. The commit before this one fixes that at its source by counting live rows. It does not make the drain provably inert — the vocabulary still decides which candidates survive its scan limit, and reclaiming a term's last row moves where that limit cuts — so the fence is what covers the rest. A fourth trigger, on `messages`, with a `WHEN` clause that is the whole reason it is affordable: a replace and a `removeFile` delete a session's rows while its `sessions` row still stands, so neither fires, and both already bump through `files`. Only the drain deletes a row whose session is gone. The price is named rather than avoided: a cursor outstanding while a purge runs is now refused once per batch, which `SessionSearchCursorError` reports as `stale-generation` so a caller re-issues page one. The test that pinned the old contract is replaced by one for the new one, and by one proving a replace still does not fire it.
…s brackets The snippet builder asked each of a row's four columns for a marked snippet and showed the first whose text contained `[[`. Transcripts contain `[[`: a bash `if [[ -f … ]]`, numpy's `[[1, 2], [3, 4]]`. A row matching only in tool output was shown its user turn instead, with nothing highlighted in it, and the any-column fallback an identifier-only match depends on was unreachable behind the same collision. Whether a column matched is now the difference between two renderings of the same text: `snippet(…, MARK, MARK, …)` beside `snippet(…, '', '', …)`. Content cannot forge a difference between those two, because it is the same content either way. The marks FTS5 inserts are private-use code points, rewritten to the public `[[` and `]]` once, at the end. That is for the other decision that has to tell a mark from content: the truncation refuses to cut between an open mark and its close, and a transcript's own bracket used to move that cut.
…ches Two small ones from the review's not-routed list. `query.slice(0, 512)` can land between the halves of a surrogate pair, leaving a lone half that matches nothing and that a caller cannot echo back. The reader already has `sliceAtCodeUnitLimit` for exactly this. `loadSessions` bound one parameter per candidate id in a single statement. The list is as long as the candidate limit, the tuning doc invites a host to raise that limit, and SQLite's `SQLITE_MAX_VARIABLE_NUMBER` is 999 on builds older than 3.32 — so one settings change away from `too many SQL variables`. Read in batches of 500, leaving room for the filter's own bound values.
… open Typo repair is the one rung whose cost tracks the vocabulary rather than the result, and it only runs for a term the scope has no posting for. Measured over 1.6 M distinct terms: 10 ms for one unknown term, 387 ms for a 480-character query of thirty-nine of them. The scoped-count fix made that cheaper rather than dearer, from 737 ms, because ordering the vocabulary scan by term drops the sort `doc DESC` needed and the counts it adds are at most eight bounded probes per prefix. A cap on unknown terms per query is a follow-up in the split plan, with the five other items the final review raised and did not route.
…self Two mechanisms landed together and hid each other: choosing a column by comparing a marked rendering against an unmarked one, and marking with private-use code points instead of `[[`. Either alone fixed the bracket repro, so neither had a mutation against it — the same masking the snippet's two column guards had a round ago. They do different jobs, so both stay and each gets the test that needs it. A transcript holding a private-use code point of its own is what the comparison is for; agent output carries Nerd Font glyphs from that block. A snippet past the character ceiling with a bracket after its last real mark is what the private-use marks are for, because the truncation has to find that mark by searching the text. The two one-line fixes get honest framing rather than a mutation neither can have. A lone surrogate is not a token character, so the planner drops it either way and the safe cut is hygiene. And no SQLite this stack runs refuses 1,100 bound ids — 32,766 has been the floor since 3.32 — so the batch is about owning the ceiling here rather than rescuing a reachable failure.
… expressions Making the typo repair ask its questions in the search's own scope put an import from retrieval into it, and retrieval already owns the repair — a cycle the native audit catches. `scopedExpression` belongs beside `phraseExpression`, `andExpression` and `orExpression` anyway: it builds a MATCH expression, and two callers now need it. The bm25 weights stay in retrieval, where the SQL that uses them is.
… trigger after a replace cuts loose
0db838d to
2d36a09
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/main/ai-vault-search/session-search-snippet.ts (1)
19-20: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse collision-free FTS5 markers. If a matched term is immediately followed by literal
MARK_CLOSE,splitMarksconsumes the generated marker as text and classifies the literal character as markup.renderSnippetthen places the literal character inside the public[[...]]highlight. Select marker strings absent from the plain snippet, or use an equivalent escaping scheme before splitting.config/scripts/session-search-scope-benchmark.ts (1)
177-177: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winValidate
TOOL_SHAREbefore corpus generation.TOOL_SHARE=1reacheswriteToolHeavyCorpus, where the tool-word count becomesInfinityand its generation loop never terminates. Reject values unlessNumber.isFinite(toolShare) && toolShare >= 0 && toolShare < 1.src/main/ai-vault-search/session-search-engine.ts (1)
114-114: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winValidate
sessionCandidateLimitin theSessionSearchEngineconstructor.search()passes this unchecked value to retrieval, where text searches interpolate it into SQLLIMITand operator-only searches use it for scan bounds. Zero can suppress all results, a negative value can make text retrieval unbounded while operator retrieval skips its scan, andNaNorInfinitycan produce invalid SQL. Reject supplied values unless they are finite positive integers before assigningthis.candidateLimit.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b1e4c7bf-7ee3-438b-80aa-91d49bbc732e
📒 Files selected for processing (1)
.gitignore
🚧 Files skipped from review as they are similar to previous changes (1)
- .gitignore
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (1)
src/main/ai-vault-search/session-search-retrieval.ts (1)
146-146: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winLimit each page to the remaining scan allowance.
recentsetsceilingtocandidateLimit * 20, but line 146 always requests 512 rows. WithcandidateLimit = 1, a 100-row table can return all 100 rows, exceed the ceiling, and then reportincomplete = trueafter exhausting the table. Limit the query to the remaining allowance and stop when SQLite returns a partial page.Proposed fix
- const rows = page.all(...values, RECENT_PAGE_ROWS, scanned) as SessionRow[] + const pageRows = Math.min(RECENT_PAGE_ROWS, ceiling - scanned) + const rows = page.all(...values, pageRows, scanned) as SessionRow[] if (rows.length === 0) { break } scanned += rows.length for (const row of rows) { if (sessions.length < scope.candidateLimit && scope.matchesOperators(row)) { sessions.push(row) } } + if (rows.length < pageRows) { + break + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 31f3b41c-f15f-413f-91c4-b77299584155
📒 Files selected for processing (9)
docs/reference/agent-session-search-query-tuning.mdsrc/main/ai-vault-search/session-search-engine-types.tssrc/main/ai-vault-search/session-search-engine.test.tssrc/main/ai-vault-search/session-search-engine.tssrc/main/ai-vault-search/session-search-index-generation.tssrc/main/ai-vault-search/session-search-page-cursor.tssrc/main/ai-vault-search/session-search-paging.test.tssrc/main/ai-vault-search/session-search-query-schema.tssrc/main/ai-vault-search/session-search-retrieval.ts
💤 Files with no reviewable changes (1)
- src/main/ai-vault-search/session-search-engine-types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/ai-vault-search/session-search-page-cursor.ts
- src/main/ai-vault-search/session-search-index-generation.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Two commits landed since the prior pullfrog review (0db838d), all in src/main/ai-vault-search/ plus the tuning doc. This delta simplifies and hardens the engine; I read it end to end and re-ran the ai-vault-search suite (456 tests, green).
- Added generation-consistent page reads —
searchnow reads the index generation before retrieval and again after all content reads (hits), throwing a typedSessionSearchCursorError('stale-generation', actual, expected)when it moved, including first-page requests without a cursor. This closes the cross-statement window coderabbit flagged: no page can mix generations and still mint a cursor from the earlier value. - Applied operators before route selection —
SessionSearchRetrieval.runnow filters each attempted route's rows to operator-eligible sessions and OR-sincompleteacross attempts, so an out-of-scope phrase match can no longer suppress a valid AND/OR fallback. New engine test pinsrepo:/path:route selection. - Made a missing source index fail explicitly — removed
SessionSearchUnavailableFeature,response.unavailable,probeCapabilities,withCapabilityRetry, andisMissingTableError;ensureSessionSearchQuerySchemanow returnsvoidand throwsmissing messages_ftsfrom both the constructor and each search instead of degrading. - Removed query logging — deleted
session-search-query-log.ts/.test.ts, dropped thesearch_logtable from the engine schema, and removed thelogQueriesoption. Deferred until a consumer exists. - Narrowed the retrieval API —
Retrievedgainssessionsandincomplete,loadSessionsis now private, and the cursor rejection message readsSearch page rejected: .... - Updated the tuning doc to match the removed degradation/logging paths and the new generation/operator behavior.
No dangling references remain to the deleted symbols (search_log, logSessionSearchQuery, unavailable, canRepairTypos), and the two deleted files leave no callers.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Summary
Adds a query-engine library over the session-search SQLite index:
new SessionSearchEngine(db, options).search({ query, scope, limit, cursor, filters }). The writer stores transcripts and the indexer maintains freshness; this engine returns ranked session hits with highlighted snippets. Nothing constructs it in production. No timers, settings, IPC, or UI integration are added.Re-land of #19750, which merged before prerequisite #19751 and was reverted in #20023. This branch includes subsequent correctness fixes and simplifications.
Behavior
conversationandallscopes over the same FTS5 table; the deliberate 3,072-character indexed tool-output cap remains.repo:/path:parsing and predicates keep the sidebar and search consistent. Operators filter candidates before a retrieval route is accepted, so an unrelated repository's phrase match cannot suppress a valid fallback match.SessionSearchCursorError('stale-generation'), including first-page requests; callers may retry from page one. Reads do not hold a transaction across the search.Implementation and scope
The engine installs an FTS vocabulary and transactional generation triggers. It restores missing derived objects before searching; a missing source FTS table fails explicitly and requires the lifecycle owner to rebuild it. There is no degraded-capability state machine or retry loop. Query logging is deferred until a caller has a consumer for it.
The engine reuses filtered session rows for ranking. Planning, retrieval, ranking, snippets, and cursor handling remain separate modules. The connection owner and future API integration decide index rebuild ownership, error presentation, and which planner details cross the wire.
Validation
src/main/ai-vault-searchand shared query-operator tests.ef7369bfdeawith no further findings.See
docs/reference/agent-session-search-query-tuning.mdfor query-policy measurements and remaining integration concerns.