# index-scope ## Goal Open-file-first indexing for a project too big to scan. Until this round the server had two answers to "which files exist": a filelist, or **every file under every workspace folder** — and on a large codebase the second one costs minutes on every save, to answer questions about the handful of folders the user is actually in. This round makes the walk follow the *open buffers* instead: `lucisv.index.scope` (`"folder"` by default) scopes the index to the folders the open files live in, `lucisv.index.scopeDepth` says how far above each one to start looking for relative files, and opening a file in a folder the scope does not cover widens it and reindexes. A filelist still outranks everything — it is the project file — and `"workspace"` restores the old walk for anyone who wants it. The same round closes the ordering footgun the previous round's QA found in `vlog_semantic::IndexBuilder`, which is what makes the second half of the change safe: **the open buffers' files are fed to the builder first**, so the progress bar completes the user's own files first, and that is provably a reporting decision with no effect on the index. ## Assumptions - **The scope ladder is one ladder with a new rung 3.** Highest first: (1) a filelist — `lucisv.filelist`, else a `filelist` key in a root's config — defines the scope exactly, unchanged and whole-project; (2) `lucisv.index.scope: "workspace"` walks every workspace folder, which is what every session did before this round; (3) the default: the folders the open buffers live in, each raised `lucisv.index.scopeDepth` levels, walked. Rung 2 needs a root to mean anything, so a rootless session is folder-scoped whatever it says. - **This is a behaviour change for every workspace user, and the honest statement of it is that cross-file answers are scope-relative.** A symbol in a folder the scope has not reached does not exist as far as this server is concerned: `textDocument/definition`, `workspace/symbol`, the call and type hierarchies, `find_references` and a workspace rename all answer within the active scope, exactly as they already did within a filelist's. **The migration line is `"lucisv.index.scope": "workspace"`**, which restores the old behaviour exactly (pinned by `the_workspace_scope_setting_restores_the_walk_of_every_root`). - **The scope only ever grows within a session.** It is derived from every directory a buffer has been opened *from* (`Workspace::opened_dirs`), not from the buffers currently open, so `didClose` narrows nothing and costs no rescan. The alternative — recomputing from the open set — would take a working answer away at the next unrelated save, which is a worse surprise than an index that is slightly larger than the editor's tab bar. It is also the cheap choice: no reindex on close, and no reindex-on-close churn while a user cycles through files. - **`didOpen` rebuilds exactly when it widened the scope.** The rule is one comparison of the scope directories across `set_document`, and it replaces the old `has_roots()` branch (rootless reindexed, rooted published) with the question that branch was really asking. Consequences, both deliberate: a rootless session opening a *second* file in an already-scanned directory no longer rebuilds (it used to, always), and a session on the filelist or workspace rung never rebuilds on `didOpen`, because no open buffer can widen those scopes. - **The `didOpen` check costs two `scope_dirs()` calls, and each one asks `filelist_path()` whether rung 1 is in force.** That is a `Discovery` walk up from each root looking for a config — a handful of `exists()` calls, on an event that is already about to reanalyze a whole buffer, and orders of magnitude cheaper than the rebuild it decides against. Named here because it is the one new per-notification cost this round adds. - **A workspace folder is a clamp on the folder rung, not a work list.** Adding one mid-session changes which files exist only once a buffer in it makes it a scope directory; what it does change immediately is how far the climb may go (see below). Removing one likewise only loosens the clamp. The rescan `didChangeWorkspaceFolders` already triggers is unchanged. - **The climb is clamped at the deepest workspace root containing the directory** — that is what keeps `scopeDepth: 5` in a two-deep project from indexing a home directory. **With no root there is nothing to clamp against and the only floor is `/`**: the loop terminates there rather than spinning, and the setting means exactly what it says. The rootless default is 0, so nobody reaches this without asking for it; it is called out in the setting's own description. - **The rootless case is unchanged at the default.** A file opened on its own, at depth 0, still gets a flat one-level read of its directory — no walk, no `.gitignore` — (`with_no_workspace_root_the_open_files_own_directory_is_indexed`, untouched this round). The moment a rootless session raises `scopeDepth` it has named a tree, so the raised directory is walked instead; that is the one place the rung's behaviour depends on the depth being non-zero, and it is what stops a raise from *losing* the file's own siblings. - **One honest filter gap: a root's `.gitignore` does not reach a walk that starts below it.** `lucisv_core::walk` reads ignore files from the walk's own starting directory downwards, so a rule written at the workspace root is not applied when the folder scope starts at `rtl/`. Every `exclude` pattern — the config's and the pushed one — is matched against whole paths and is unaffected. Pinned both ways in `the_folder_scope_honours_every_exclude_and_the_gitignores_below_it`, rather than left to be discovered. The fix belongs in `lucisv_core`'s walk (parent ignore files, as the `ignore` crate does it) and is filed, not done: it is a change to the CLI's walk semantics too, which is not this round's scope. - **The startup index is empty, and that is the point.** No buffer is open at `initialize`, so the folder scope has no folder yet; the first `didOpen` widens it and rebuilds. On a huge project this is the whole saving. It also means a client whose settings say `"workspace"` still gets one empty startup scan and then a rescan when its settings land — the same one extra rescan `lucisv.exclude` and `lucisv.filelist` have always cost, for the same reason (neither settings door can deliver before `initialized`). - **Open buffers still overlay every rung.** A buffer's text beats disk and a buffer outside the scope still contributes itself, exactly as with a filelist. Nothing about diagnostics, formatting or any single-file feature depends on the scope: the per-buffer analysis is bottom-up and instant, and this round does not touch it. - **Wrong-typed settings fall back to the *narrow* default**, the same direction `maxFileSize` falls back to the cap: a misparse must not silently buy a whole-workspace scan. `"scope"` is matched exactly — `"Workspace"` is junk — because the enum in `package.json` is what a settings UI offers and forgiving it here would make a typo mean different things on different clients. - **The progress denominator, the cap counts and the output log follow the active scope for free.** They all read the same work list (`index_order`'s length, known before the first parse), so nothing was re-plumbed; verified by `the_bar_names_the_open_file_before_the_rest_of_the_scope` and by the e2e transcript, whose startup bar honestly ends `0 files indexed`. ## Handshakes ### `vlog_semantic` — `IndexBuilder` is order-insensitive The previous round shipped `IndexBuilder` as a dumb accumulator whose ordering contract was a doc comment ("feed it `index_order`'s list"), and its QA proved that a caller who did not got different `FileId`s and a different winner for a name two files declare (indexing-ux README, QA log 2026-08-27, MEDIUM). That is closed by construction: ```rust pub fn add_file(&mut self, path: PathBuf, src: &str); // parses, keeps FileFacts pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups, merges ``` - `add_file` parses its file and reads off what it declares into a private per-file record (`FileFacts`: the path, the `` `define`` table, the file-scope declarations in declaration order, the members in traversal order). **The parse still happens in `add_file`**, so a caller reporting progress between calls is reporting work that has really been done. - `finish` sorts those records by path — `sort_by` is stable, `dedup_by` keeps the first of a run, which is exactly `index_order`'s rule — and only then hands out `FileId`s and merges the declarations into the `units`/`members` tables. No insertion order can reach the result. - **`WorkspaceIndex::build` is byte-identical for every existing caller**, and the proof is that all 31 pre-existing `vlog_semantic` tests are unchanged and green, including `file_ids_follow_the_sorted_paths_whatever_order_they_arrive_in`, `a_module_declared_in_two_files_is_ambiguous_in_path_order` and `the_incremental_builder_is_what_build_is_made_of`. `build` still calls `index_order` first — not for correctness now, but so a duplicate path is not parsed twice. - **Why this shape and not a type-enforced two-phase API.** The alternative the brief allowed was a builder that cannot be misused because the types forbid it — an `UnsortedBuilder` that only a `SortedFiles` value can be fed. That is a second type, a second constructor and a conversion, to protect an invariant that a five-line `sort_by`/`dedup_by` in `finish` removes outright. Making the wrong call impossible beats making it a compile error when it costs less. The cost is memory: the per-file records for the whole workspace are held until `finish`, which is the same data the finished index holds (names, spans, kinds), partitioned rather than merged — no `Semantics` and no source text is retained. - Permanent re-attack: `no_insertion_order_can_change_what_the_builder_produces` (the QA pair plus a nested-class/defines fixture, in three orders, compared by a full fingerprint of files, ids, disambiguation order, member tables and define counts) and `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at`. - `index_order` stays public and unchanged: the server needs the work list's *length* before the first parse for the progress denominator. ### `vlog_semantic` — facts from an analysis the caller already has (2026-08-28) Two additions, both "the same thing with the parse already done", in the shape `IndexBuilder::add_facts` already had: ```rust impl FileFacts { pub fn from_analysis(path: PathBuf, tree: &SourceFile, defines: &DefineTable, sem: &Semantics) -> FileFacts; } impl WorkspaceIndex { pub fn update_facts(&mut self, facts: FileFacts); // update_file, no parse } ``` - **`FileFacts::of` is now literally `parse_and_collect` + `analyze` + `from_analysis`.** The fact walk moved into the new function and `of` calls it, so there is one implementation and not two: the equivalence the reuse needs holds by construction, not by care. What a caller promises is only that `tree`, `defines` and `sem` really are the analysis of the text at `path`. - **`update_facts` is `update_file`'s body**, with the same contract: what is left is the index a whole build over the same file set would have produced. `update_file` is now `self.update_facts(facts_of(path, src))`. - No `FACTS_FORMAT` change, no new field, no new dependency: this round adds a second *door* to the record, never a second *shape* of it. ### `lucisv_server::state` — a `Document` can hand over its own facts - `Document::facts(path) -> FileFacts` and `Document::words() -> Vec` are **new and public**: what an open buffer contributes to the index and to the completion word table, read off the `tree`/`defines`/`semantics` and the `tokens` it already holds. Never called for a fast-path buffer, whose analysis is the analysis of the empty file and which contributes nothing anyway. - **`IndexEvent::Analyzed { done, total, path }` is a new variant** — one file went into the index from an open buffer's own analysis. Its own variant rather than `Cached` so that "from cache" keeps meaning the persistent store and nothing else; `server.rs` logs `analyzed: ` and, deliberately, adds no clause to the progress bar's end message (see the work log). - `collect_sources` takes a `HeldAnalyses` argument, because it has two callers with different needs: an index rebuild wants the buffers' records, a refactoring reads the texts and nothing else and would be paying for records nothing looks at. - `collect_sources` no longer reads a file from disk when an open buffer speaks for it. The text was read and then thrown away; the size cap is still consulted first, so an oversized file still reports itself `Skipped` exactly as before. ### `lucisv_server::candidates` — words from a token stream - `Candidates::build(index, sources, known: HashMap>)` takes a third argument: the words of the files whose token stream the caller already has. A file listed there is not lexed again; a file absent from it is lexed exactly as every file used to be. - `Candidates::update_words(index, path, words)` is `update_file` with the lex already done, and `update_file` delegates to it. - `words_of_tokens(tokens)` is `pub(crate)`: the whole of `words_in` after the lex, so the two roads to a file's words are one function over one token stream. ### `lucisv_server::settings` - Two new fields, `index_scope: IndexScope` (`Folder` | `Workspace`, default `Folder`) and `index_scope_depth: u64` (default 0), parsed from `lucisv.index.scope` / `lucisv.index.scopeDepth`. Nested under `index` like the other two, so both settings doors — push and pull — carry them with no new code (`the_index_settings_come_through_the_pull_door_too`). - `IndexScope` is public; `state.rs` matches on it. ### `lucisv_server::state` - `Workspace::scope_dirs() -> Vec` is **new and public**: the directories the folder scope walks, or empty when the folder rung is not in force. `server.rs` compares it across a `didOpen`. - `Workspace::set_document` now also records the buffer's directory. It is the one place a directory enters the scope. - `walked_files` takes the directories to walk instead of reading `self.roots`; `sibling_files` is a free function taking the same list. - `has_roots()` is `#[cfg(test)]` now — `didOpen` was its only production caller. - Test-only `open_whole_workspace` / `open_whole_workspace_with` are the one-line spelling of "this test wants the pre-round scope", used by the dozens of tests across the crate whose subject is a hover or a rename rather than the scope. ### `lucisv_server::server` - `didOpen` reindexes when `scope_dirs()` moved, else publishes. One rule for rootless and rooted; the rebuild rides the existing bar, generation bump, code-lens refresh and republish. - `Server::started(connection, roots, abilities, ClientSettings)` is the real constructor and `Server::new` delegates to it with the defaults. The parameter exists for the tests, which is stated where it is written: a test whose subject is not the scope starts from the wide scope rather than driving a `didChangeConfiguration` and then reasoning about the extra rescan. ### `editors/vscode` - Two new `contributes.configuration` properties, both carrying the honesty notes: what stops being answered, that the scope grows and never shrinks, the migration line, and that a filelist overrides both. No `extension.js` change — the whole `lucisv` section including the nested `index` object is already synchronized. ## Status / TODO - [x] `lucisv.index.scope` (`"folder"` default, `"workspace"` opt-in), both settings doors, junk → the narrow default - [x] `lucisv.index.scopeDepth` (default 0), clamped at the deepest containing workspace root, and at `/` with no root - [x] Filelist still outranks both; `scope`/`scopeDepth` ignored on rungs 1–2 - [x] `didOpen` widens the scope and reindexes; the rootless branch unified into the same rule - [x] Scope only grows within a session; `didClose` costs no rescan - [x] Both settings join the rescan condition; `logFiles` still does not - [x] Open buffers' files fed to the builder first; progress reports name them first - [x] `IndexBuilder` order-insensitive, with the QA attack as a permanent test - [x] `package.json` descriptions carry the scope-relative-answers warning and the migration line - [x] 19 new tests (12 state, 2 server, 1 e2e, 2 vlog_semantic, 2 settings), 3 existing ones extended, 1 superseded test rewritten; every other test in the crate that wanted the whole workspace now says so ### Round 19 — a rescan stops re-parsing what is already analyzed (2026-08-28) - [x] Traced where a scope-widening `didOpen`'s 213 ms actually goes, per stage, and wrote it down (work log) - [x] An open buffer's **index facts** come from the analysis it already holds (`FileFacts::from_analysis`), on the whole-rebuild path and on `update_one`'s incremental one - [x] An open buffer's **completion words** come from the tokens it was analyzed from (`words_of_tokens`), on both paths - [x] The disk copy of a file an open buffer speaks for is no longer read - [x] `IndexEvent::Analyzed`, logged as `analyzed: `, so "from cache" still means the persistent store - [x] Equivalence pinned six ways: encoded-record equality across 860 corpus files and 13 crafted shapes, index fingerprint equality at workspace scale, `update_facts` == `update_file`, and the server-level "same index and same completion tables as the same bytes on disk" - [x] **~228 ms → ~23 ms** on the same probe, with the closed-buffer floor unmoved at ~12 ms - [ ] **Not done, deliberately:** no incremental *widen* (index only the newly in-scope files and keep the rest). See the work log — it cannot hold the brief's own fingerprint-equivalence test while other buffers carry unsaved edits, and it would not have touched the 68 ms re-lex or any rescan that a `didOpen` did not trigger. - [ ] **Not done, deliberately:** the remaining ~11 ms an open 1.4 MB buffer adds to a rescan is the fact walk (1.7 ms), the word set (3.1 ms) and the workspace-wide word table taking 40 000 identifiers back in. It is real work over real content, not a repeat of work already done. - [ ] **Not done, deliberately:** no `lucisv.toml` key for either setting. They are editor-session resource settings — how much of *this machine's* time to spend — not project style, the same reason `maxFileSize` has none. - [ ] **Not done, deliberately:** no shrink-on-close, no LRU on the scope, no time-based eviction. All three are guesses at a problem nobody has reported; the escape hatch for a session that grew too wide is to restart it or set a filelist. - [ ] **Filed, not done:** `lucisv_core::walk` does not read `.gitignore` files above its starting directory, so a root-level ignore rule does not apply to a folder-scoped walk. Fixing it changes the CLI's walk too. - [ ] **Filed, not done:** the folder scope makes the write-path honesty gap the previous round's QA found sharper — a workspace rename now rewrites only what is in scope, and says nothing about what is not. The follow-up task the lead filed for the size cap covers exactly this and should name the scope too. ## Work log ### 2026-08-27 — dev agent (open-file-first indexing, folder-scoped walk) - **The builder was hardened first, because the ordering change depends on it.** Feeding the open files first is only free if insertion order provably cannot reach the index, so `IndexBuilder` was rewritten to accumulate `FileFacts` and sort in `finish` *before* anything in the server was reordered. The five-line sort beat the type-enforced two-phase alternative on every axis that matters here (one type instead of three, no conversion, and the misuse becomes impossible rather than merely uncompilable); the price is that the per-file records live until `finish`, which is the index's own data partitioned rather than merged. `WorkspaceIndex::add_file`/`add_members` became the free `facts_of`/`collect_members` with the same traversal, so the merged tables come out in the same order they always did — which is why all 31 existing tests are byte-identical and green. - **The scope ladder went in `source_files`'s rung 3, not beside it.** The filelist rung and the walk are untouched; `default_files` now chooses between `walked_files(&self.roots)` and `folder_files()`, and `folder_files` is `walked_files(&scope_dirs())` with the one rootless exception. That kept the exclude/gitignore/cap plumbing literally the same function, which is what makes "every filter still applies" a fact rather than a claim. - **`opened_dirs`, not `docs`, is what the scope is derived from.** This is the close-shrink decision: the scope grows within a session and never narrows. Deriving from the open documents would have been one less field, but it makes `didClose` silently change what the *next* save indexes, which is a worse surprise than a scope that is a few folders wider than the tab bar. It also keeps `didClose` free of any rebuild. - **`didOpen`'s branch is now one comparison, and it subsumes the rootless rule.** `has_roots()` was answering "can an open buffer widen the scope?" by proxy; `scope_dirs()` answers it directly and correctly on all three rungs. Two deliberate deltas fell out and are documented: a rootless session opening a second file in a directory it already read no longer rebuilds, and a rootless session with a filelist no longer rebuilds on open either (the filelist defines the scope; the buffer is overlaid at the next rebuild regardless). - **The clamp is the deepest containing root, not the first.** With nested workspace folders the tighter floor is the honest one — the user opened both, and the inner one is the more specific statement about that file. - **The rootless flat read is kept at depth 0 and only at depth 0.** Turning it into a walk would have changed the "a file opened on its own" case that has its own documented reason to be shallow; leaving it flat at *every* depth would have made `scopeDepth: 1` index the parent directory while losing the file's own siblings, which is worse than either. So: unchanged at the default, walked the moment the user raises the depth, and both halves pinned. - **The startup scan indexes nothing now**, because no buffer is open yet. That reads as alarming and is exactly the feature: the e2e transcript's first bar ends `0 files indexed`, the `didOpen` bar reports the real file, and that sequence is asserted on the wire. - **The blast radius was 151 tests, and the honest fix was to make each of them say what scope it wants.** Every test across the crate whose subject is not the scope now calls `Workspace::open_whole_workspace` or `Session::wide` instead of the plain form — a mechanical, reviewable change that leaves each test exercising exactly what it exercised before, with the scope no longer a hidden variable. Four settings pushes inside those tests gained `"scope": "workspace"` for the same reason a push replaces every field. The new default's own behaviour is covered by the 22 new tests rather than by accident. - **One test was superseded rather than repaired.** `a_rootless_session_gaining_its_first_folder_flips_didopen_from_reindex_to_publish` pinned the branch this round deletes; it is replaced by `a_didopen_rebuilds_exactly_when_it_widens_the_scope`, same case list, under the rule that replaced it, with an explicit `Superseded this round:` note in the house style. - **Two e2e expectations moved, both of them the model becoming visible on the wire:** `indexing_reports_its_progress_over_the_wire` now shows three bars (empty startup, the widening `didOpen`, the save) with the honest end messages, and `a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire` counts two refreshes because there are now two rescans in its script. - **The `.gitignore` gap was found by a failing test I had written to assert the opposite**, and is documented and pinned as a delta rather than papered over or "fixed" by reaching into `lucisv_core`'s walk, which is the CLI's too. - Files touched: `crates/vlog_semantic/src/workspace.rs`, `crates/vlog_semantic/tests/workspace.rs`, `crates/lucisv_server/src/settings.rs`, `crates/lucisv_server/src/state.rs`, `crates/lucisv_server/src/server.rs`, `crates/lucisv_server/tests/e2e.rs`, the test modules of `completion/hierarchy/file_ops/includes/inlay/hover/lens/ nav/ports/rename/type_def/type_hierarchy/signature/symbols` (constructor swap only), `editors/vscode/package.json`, `docs/features/lucisv-server/README.md`, `docs/features/indexing-ux/README.md`, this README. No new dependency, no version bump, no `CHANGELOG` edit, no `docs/site/`, no commits. **Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace`: zero warnings. `cargo test --workspace`: **2217 passed, 0 failed** (2198 on `HEAD`, measured — 19 new). `cargo test -p vlog_formatter`: green, untouched. `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. `node -e JSON.parse(package.json)`: parses. The 19 new tests, the 3 extended and the 1 rewritten, and what each is for: | test | pins | |---|---| | `no_insertion_order_can_change_what_the_builder_produces` (vlog_semantic) | QA's attack, three orders, full fingerprint — ids, disambiguation winner, member tables, defines | | `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at` (vlog_semantic) | `index_order`'s dedup rule surviving the move into `finish`, non-adjacent duplicate included | | `the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace` (settings) | the default, both words, six junk values → the narrow default | | `the_scope_depth_is_zero_until_a_client_raises_it` (settings) | the default, no upper bound, six wrong types | | `the_index_settings_come_through_the_pull_door_too` (settings) | both new keys through `from_section` as well | | `the_default_scope_is_the_open_files_own_folder_and_everything_under_it` (state) | the headline: own folder and subtree, no sibling folder, nothing before a buffer opens | | `a_scope_depth_of_one_reaches_the_folder_beside_it` (state) | the `rtl/` + `../include` layout the setting exists for | | `the_climb_stops_at_the_workspace_root` (state) | the clamp at depth 99, and the deepest of two nested roots winning | | `a_rootless_climb_stops_at_the_filesystem_root` (state) | termination at `/` with no root — on the directories, never walking one | | `a_rootless_session_that_raises_the_depth_walks_instead_of_reading_one_level` (state) | the one exception, from the other side | | `the_workspace_scope_setting_restores_the_walk_of_every_root` (state) | the migration line, and that the depth is ignored on that rung | | `a_filelist_still_defines_the_scope_exactly_whatever_the_folder_rung_would_say` (state) | rung 1 over rung 3, and that no `didOpen` can widen a filelist | | `closing_a_file_never_narrows_the_scope` (state) | the close decision | | `the_folder_scope_honours_every_exclude_and_the_gitignores_below_it` (state) | both excludes, the in-scope `.gitignore`, **and** the root-`.gitignore` gap, both scopes | | `a_folder_added_mid_session_widens_nothing_until_a_file_in_it_is_opened` (state) | folder events × the folder rung | | `a_scope_or_a_depth_change_asks_for_a_rescan` (state) | both directions, both settings | | `the_open_files_are_indexed_first_and_the_index_cannot_tell` (state) | the event order **and** that the index equals the plain-order one | | `a_didopen_rebuilds_exactly_when_it_widens_the_scope` (server) | the unified rule: widens → rebuild, covered → publish only, rootless and rooted | | `a_new_index_scope_or_depth_rescans_through_the_real_dispatch` (server) | parser + change test + rescan, end to end through `didChangeConfiguration` | | `the_bar_names_the_open_file_before_the_rest_of_the_scope` (server) | `1/3 m_open.sv` first on the wire | | `the_folder_scope_widens_when_a_file_in_another_folder_is_opened` (e2e) | the real binary: definition into a sibling folder empty, opening it resolves, and a `"workspace"` client resolves immediately | | `indexing_reports_its_progress_over_the_wire` (e2e, updated) | the model on the wire: three bars, `0 files indexed` then `1 file indexed` twice | ### 2026-08-28 — dev agent (a rescan stops re-parsing what is already analyzed) **The symptom, reproduced first.** `nav.rs`'s `qa_didopen_latency_when_a_new_folder_widens_the_scope`, `--release`, three runs on `HEAD`: the widening `didOpen` **227.2 / 229.3 / 229.4 ms**, the rescan alone **224.5 / 224.7 / 225.4 ms**, and **12.5 / 13.1 / 12.6 ms** for the same rescan with the 1.4 MB `top.sv` closed. (The closed number is the floor for a reason worth naming: `top.sv` is 1.4 MB, over the 1 MiB default `lucisv.index.maxFileSize`, so with no buffer open it is not walked at all. The "13 ms" is the other 400 files, not 401.) **Where the 210 ms actually goes.** `rebuild_index_with` timed stage by stage, with the buffer open, per rescan: | stage | with the buffer open | with it closed | |---|---|---| | `collect_sources` (401 reads) | 9.5 ms | 8.4 ms | | the facts loop | **133.5 ms** | 1.5 ms | | `IndexBuilder::finish` | 0.4 ms | 0.12 ms | | `Candidates::build` | **68.5 ms** | 0.85 ms | | `IncludeGraph::build` | 0.84 ms | 0.14 ms | | overlay refresh | 0.12 ms | ~0 | So the brief's "210 ms of re-lexing and re-parsing the open buffer" is right in total and **understates the shape**: the buffer was lexed *twice* per rescan. Once inside `FileFacts::of` (tokenize 62 ms, parse 66 ms, `analyze` 18 ms, the fact walk under 2 ms — 133 ms in all), and again inside `Candidates::build`, whose `words_in` re-lexes every file's text to harvest identifiers (62 ms of the 68 ms). A third, smaller waste sat in `collect_sources`, which read the 1.4 MB disk copy of `top.sv` and then threw it away because the buffer overrides it. Every one of those three is work this server had already done: the `Document` for that buffer holds the tokens, the tree, the define table and the `Semantics`, all built from the same text by the same functions, at the last keystroke. **Shape taken: (b), extended to the completion words. (a) was investigated and rejected, on two grounds.** - **(a) cannot hold its own mandatory test.** The brief's hard requirement for an incremental widen is that the widened index fingerprint byte-identically to a fresh full build. It does not, in a case that is easy to reach: the index is rebuilt on save, not on change, so between two rebuilds any open buffer may carry unsaved edits. A *full* rebuild at the widening `didOpen` indexes those edits (`collect_sources` overlays live buffer text); an incremental widen that indexed only the newly in-scope files would not. That is an answer change — type `package p;` into an open buffer, jump into a new folder, and the two shapes disagree about whether `p` exists — and the fingerprint test would catch it as a failure, correctly. Making (a) safe means re-indexing the changed buffers anyway, which is (b) with a diff bolted on in front. - **(a) would have fixed a third of it.** It touches only the facts loop, and only on the rescans a widen triggers. The 68 ms word re-lex is in `Candidates::build`, which a widen rebuilds whatever the file list did; and every *other* rescan with a big buffer open — a save that falls back to a whole rebuild, a settings change, a folder event, a watched file — keeps paying the full 200 ms. (b) is one rule that covers all of them: **an open buffer's finished analysis is what the buffer contributes, wherever it is asked.** **The equivalence is by construction, then pinned anyway.** `facts_of` was split: everything after `tokenize`/`parse_tolerant`/`analyze` moved into `facts_from_analysis`, and `FileFacts::of` now calls it. So `FileFacts::from_analysis` is not a second way of computing a record — it is the same code entered one step later, which is the difference between an equivalence that has to be tested for and one that has to be *broken* to fail. The same split gives `words_of_tokens` (the whole of `words_in` after the lex) and `WorkspaceIndex::update_facts` (the whole of `update_file` after the parse). What is left to prove is the narrow claim that `Document::new`'s analysis is `facts_of`'s analysis — two separate call sites of the same three functions, including the all-or-nothing lex-failure branch — and that is what the corpus sweeps are for. **The reuse is wired where the override already lives.** `collect_sources` is the one place that decides "this buffer's text beats the disk copy"; the facts and the words are now taken from the same `Document` in the same loop iteration, so a record and the text beside it can never describe different bytes. `rebuild_index_with` consults that map *before* the persistent cache, deliberately: an open buffer's own analysis is right even when the buffer has unsaved edits, which is exactly when a content-keyed store has nothing to offer. It still writes the record through to the store, so the next session starts from it. **One argument rather than one wasted walk.** `collect_sources` has a second caller — `sources()`, which every refactoring reads the workspace through — and it wants the texts alone. Building a record and a word set off every open buffer for it would be ~5 ms of dead work per `prepareRename` with a 1.4 MB buffer open, so the function takes a `HeldAnalyses` argument saying which caller it is. A boolean would have read as `collect_sources(watch, true)` at the call site; the two-variant enum says what the `true` means. **`update_one` takes the same shortcut**, through the new `analysis_of`, which finds the buffer the same way `current_text` does — so a `didSave` on a big buffer stops re-parsing it too. That is not the brief's headline case but it is the same waste on the path a user hits most often. **A third event word rather than a fourth meaning for `cached`.** `IndexEvent::Analyzed` is its own variant so "N from cache" in the progress bar's end message keeps meaning the persistent store and nothing else — that sentence is `index-persistence`'s, and e2e transcripts assert it. The per-file log gains `analyzed: `; the end message gains **nothing**, because one file out of a workspace is not why a scan finished fast, and a bar that grew a clause in every session with a file open would say less rather than more. `Analyzed` still ticks the bar, like the other two: it is a file of the work list. **Two existing tests moved, both for the same honest reason.** `the_open_files_are_indexed_first_and_the_index_cannot_tell` counted `Parsing` events to check the *order* of the work list; it now counts all three routes, because the open buffer it is watching no longer parses. `the_cache_never_puts_back_a_file_the_scan_no_longer_visits` asserted its open buffer came from the store; it now asserts it came from its own analysis, and also that it appears on neither of the other two lists — the test's real point (`tb/b.sv` has a record and is still not an indexed file) is untouched. **After, same probe, three runs:** the widening `didOpen` **22.7 / 23.2 / 24.0 ms**, the rescan alone **22.6 / 23.1 / 24.7 ms**, the closed-buffer floor **11.5 / 12.8 / 12.4 ms** — unmoved, as it must be. **~228 ms → ~23 ms, 10×**, and the open 1.4 MB buffer's own share of a rescan went from ~212 ms to ~11 ms. The probe now prints that share directly and permanently, so the claim is re-measurable rather than remembered: ``` That buffer's own share: facts 140.3ms parsed vs 1.67ms reused, words 62.9ms re-lexed vs 3.09ms reused ``` `references-nav`'s own probe is unchanged and green on the same run (110 µs cross-file references either direction, 1.18 ms for the in-file fallback on a name used 10 001 times), which is what says this round did not pay for its rescan out of the request path. **What is left, and why it is not waste.** The ~12 ms the open buffer still adds is the fact walk over its tree (1.7 ms), the identifier set over its tokens (3.1 ms), and `Candidates::build` taking 40 000 identifiers into the workspace-wide word table. All three are work over content that really is in the index; none of them repeats work already done. **Tests added (6).** `vlog_semantic`: `facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text` (13 crafted shapes — empty, unlexable, tolerant-parse-with-errors, packages, classes, nested classes, `` `define``/`` `undef``, imports and `::` paths, a file-scope instantiation that is deliberately not an edge, a generate body), `the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus` (860 files, encoded records byte-identical), `an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text` (workspace scale, files added in reverse path order so the reuse cannot smuggle an ordering in, plus `update_facts` == `update_file`). `lucisv_server`: `an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would` (an **edited** buffer — bytes nowhere on disk — against the same bytes written to disk and parsed: same fingerprint, same words, same unit candidates, and the event lists prove the two really took different routes), `an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus` (the narrow claim, over real `Document::new`s — this is the one that catches `Document::new` drifting from `facts_of`), `a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse`. **Attacked before believing.** Three deliberate mutations, each run and each caught: giving `Document::facts` an empty `DefineTable` fails both the crafted fingerprint test and the corpus record sweep; dropping every 97th token in `Document::new` fails the corpus words sweep. (A mutation to `words_of_tokens` itself is *not* caught, and correctly so — both roads go through that one function, which is the point of the split.) **Files touched:** `crates/vlog_semantic/src/workspace.rs`, `crates/vlog_semantic/tests/workspace.rs`, `crates/lucisv_server/src/state.rs`, `crates/lucisv_server/src/candidates.rs`, `crates/lucisv_server/src/server.rs`, `crates/lucisv_server/src/nav.rs` (the probe's own numbers), this README, `docs/features/references-nav/README.md` (the Handshake, delivered), `docs/features/indexing-ux/README.md` (the new log word), `TODO.md`. No new dependency, no `FACTS_FORMAT` change, no scope-semantics change, no version bump, no commits. **Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace`: zero warnings. `cargo test --workspace`: **2413 passed, 0 failed** (2407 on `HEAD`, measured — 6 new). `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. ## QA log ### 2026-08-27 — QA agent (gates, attack surfaces, mechanical-sweep audit) **Gates, re-run clean on the untouched working tree.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace`: zero warnings. `cargo test --workspace`: **2217 passed, 0 failed, 5 ignored** (matches the dev's count exactly). `cargo test -p vlog_formatter`: 114 passed, untouched. `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. Every temporary probe test below was inserted, run alone, and reverted before the final re-run; the final `git diff` of `state.rs`/`server.rs` hashes identically to the pre-QA diff, confirming no probe was left behind. **The 151-test mechanical sweep.** Sampled all 14 non-scope test modules (`completion`, `file_ops`, `hierarchy`, `hover`, `includes`, `inlay`, `lens`, `nav`, `ports`, `rename`, `signature`, `symbols`, `type_def`, `type_hierarchy` — every `.open_roots(` call in them, ~40 sites) plus the `server.rs`/`state.rs` `Session::wide`/`Workspace::open_whole_workspace` call sites: **every one is a pure constructor swap** (`open_roots` → `open_whole_workspace`, or `Session::with`/`Session::new` → `Session::wide`/`Session::wide_with`, or a `"scope": "workspace"` key added to a settings push). No sampled assertion changed beyond that. Verdict: **mechanical sweep is genuinely mechanical**, as claimed. **The inverse hunt (tests that should have been swapped but weren't) found one real bug and two weakened premises**, all in `state.rs`'s own test module, which is the one file that still has bare `.open_roots(` calls mixed in with the new scope tests: - **MEDIUM — `a_folder_added_twice_across_two_events_is_absent_after_one_removal` (`crates/lucisv_server/src/state.rs:851-876`) no longer tests what it says it does.** It calls `ws.open_roots(...)` but never opens any buffer, so under the new default (folder scope) `scope_dirs()` is empty for the entire test and `"x"` is never indexed — not because of the root add/remove/dedup logic under test, but because nothing is ever in scope. The final `assert_eq!(indexed(&ws, &["x"]), [])` passes vacuously. Confirmed by temporarily inserting a premise check (`assert_eq!(indexed(&ws, &["x"]), ["x"])`) right after the first `change_roots` add and running the test alone: **it failed** (`left: [] right: ["x"]`), proving the premise never held. The `change_roots` return-value assertions (`true`/`false`/`true`) are unaffected and still test the set-not-multiset behavior correctly — only the closing `rebuild_index`/`indexed` pair is vacuous. Fix: either open a buffer in `extra`'s directory before checking, or switch to `open_whole_workspace` and keep the indexed-content assertion meaningful. Not fixed directly — it is a one-line-comment-vs-actual-behavior mismatch that the dev should decide the intended fix for (open a buffer, since the test's own comment is about indexing, not about scope). - **LOW — `an_open_buffer_is_indexed_however_big_the_file_is` (`state.rs:1151-1168`)'s "premise: capped on disk" assertion is now true regardless of the cap**, because no buffer is open at that point either, so folder scope is empty and nothing is indexed for that reason first. The test's actual point (the open buffer overrides the cap after `set_document`) still holds and is still meaningfully exercised, since `set_document` adds the directory to scope before the second `rebuild_index`. Not a false pass on the assertion that matters, but the premise no longer demonstrates what its comment claims. - **LOW — stale rung numbers in comments**, not behavior: `without_a_filelist_there_are_no_incdirs_at_all` (`state.rs:1454-1462`) says "Rung 2 of the ladder names no include path," and `a_broken_filelist_leaves_the_include_graph_without_incdirs` (`state.rs:1464-1475`) implies the same fallback. Both are now rung 3 (folder scope) by default, not rung 2 — the assertions (`None` either way, since no filelist means no incdirs regardless of which walk rung ran) are unaffected, but the comments should say "rung 2 or 3" or just "the fallback." All other `.open_roots(` calls left bare in `state.rs` were individually checked and are correct as left: the filelist tests (rung 1 always wins, scope-independent), the rootless tests (rung 3 is the only rung with no root, unaffected), and `a_folder_change_that_changes_nothing_asks_for_no_rescan` / `a_trailing_slash_in_the_removed_folder_still_matches_the_held_root` (test `change_roots`'s bookkeeping only, no indexed-content assertion to weaken). **Scope correctness at the boundaries — all traced and probed, all correct, none pinned by a permanent test beyond what's listed below:** - Depth clamping when the open file *is* at the root: `raised()`'s first loop iteration compares `out == floor` before descending, so a root-level buffer returns immediately at any depth. Covered by `the_climb_stops_at_the_workspace_root`. - Nested roots, deeper clamps tighter: `max_by_key(|root| root.components().count())` — confirmed by the same test's second half. - `scopeDepth` past the path depth: terminates at `/` (rootless) or the containing root (rooted), confirmed by `a_rootless_climb_stops_at_the_filesystem_root` and the depth-99 case in `the_climb_stops_at_the_workspace_root`. - **A file opened from outside every workspace root, with roots present (folder scope still the active rung): no permanent test covers this.** Probed with a temporary test (root A open, a buffer opened from an unrelated tree B): `scope_dirs()` at depth 0 is just B's own directory, and raising `scopeDepth` to 99 climbs all the way to `/` — exactly the rootless behavior, because `raised()`'s `floor` is `None` when no root contains the directory. **Correct, but untested and not called out in the README's Assumptions** as a distinct case from "rootless session." Recommend a pinned test plus a sentence in the README. - Symlinked folders / case differences on macOS: `opened_dirs` dedups by literal `PathBuf` equality (`seen == dir`), not canonicalized — a symlink and its target, or `/RTL` vs `/rtl`, are two separate scope directories that both get walked. **Not a regression**: the pre-round `sibling_files` deduped the same way. Informational only. **The grows-only model's costs.** Opening three folders then closing all three: union sticks, verified with a temporary test (three folders opened, all three closed, `rebuild_index`, same five packages still indexed) — not just the dev's one-of-two-closed case. The pathological end (opening files across many folders converges the walk cost back toward the whole-workspace walk this round exists to avoid) is **acknowledged only indirectly** — the README's "Not done, deliberately" section says there's no shrink/LRU/TTL and names "restart or set a filelist" as the escape hatch, but never states the asymptotic point plainly. Recommend one sentence owning it, e.g. "a session that has opened files in most of the project's folders pays close to the whole-workspace walk on every rescan; that is the trade, not a bug." **Builder hardening.** `no_insertion_order_can_change_what_the_builder_produces` and `a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at` both pass. Independently re-derived the "first wins" claim from first principles rather than trusting the doc comment: wrote a 6-line scratch program exercising `Vec::sort_by` + `Vec::dedup_by` with the exact closure shape used in `finish` (`sort_by(|a,b| a.path.cmp(&b.path))` then `dedup_by(|a,b| a.path == b.path)`) on `[("a",1),("a",2),("b",3)]`; it produces `[("a",1),("b",3)]`, confirming `dedup_by` really does keep the first of a run in this position (the docs' phrasing invites an off-by-one misreading given the reversed-argument-order caveat). `add_file` after `finish`: prevented at compile time — `finish(mut self)` consumes the builder, so this is Rust's ownership system doing exactly what a type-state `SortedFiles` wrapper would do, for free, matching the README's stated rationale for not building one. Empty builder `finish()`: sorts/dedups an empty `Vec`, loop body never runs, returns `WorkspaceIndex::default()` — no panic, consistent with `an_empty_workspace_answers_nothing_and_panics_nowhere` already covering `WorkspaceIndex::build([])` through the same path. **Cross-feature interaction sweep — verified clean, and structurally so rather than by accident.** `symbols.rs`, `lens.rs`, `type_hierarchy.rs` all read from `ws.index()` directly; `rename.rs` reads from `ws.sources()`, which is `collect_sources(...).texts`, the exact same `source_files()` ladder `rebuild_index` uses. There is one scope-aware code path, not one per feature, so "workspace/symbol, codeLens, typeHierarchy and rename all answer in-scope only" is a structural fact, not a per-feature promise that could drift. `workspace/diagnostic` (`server.rs:988` `workspace_report`) iterates `self.workspace.open_uris()` only — confirmed independent of the index scope entirely, exactly the "unaffected" claim. The cap composes with scope by construction too: `collect_sources` applies `max_file_size` to `scope.files`, which is already the scope-filtered list — no special-casing needed, none found. **Migration path.** Rather than diff against a `git stash` baseline binary, verified the stronger claim algebraically: `default_files()`'s `walks_the_workspace()` branch calls `self.walked_files(&self.roots)`, and `walked_files(dirs: &[PathBuf])`'s body is byte-identical to the pre-round `walked_files(&self)`'s body with `&self.roots` substituted for `dirs` at every use — confirmed by re-reading the diff hunk line by line. So `scope: "workspace"` is not merely equal in practice to the pre-round default, it is the same function called with the same argument, which is a stronger guarantee than a fixture comparison could give. `from_section` delegates to `from_payload` with zero new code (`settings.rs:208-210`), so both settings doors carrying the two new keys is confirmed structurally. **Own-shapes probes (C), all via temporary tests, all reverted:** - Rapid `didOpen` across 10 distinct folders: generation increases by exactly 20 (2 per widening open), completes in ~0.02s — no quadratic blowup at this scale. `opened_dirs.sort()` runs on every `set_document` and `scope_dirs()` sorts+dedups again on every call (twice per `didOpen`), which is O(n log n) per open and O(n² log n) over a session — fine at realistic folder counts, worth knowing if a future report cites hundreds of folders in one session. - Lowering `scopeDepth` mid-session (1 → 0) via `set_client_settings`: **does narrow the index on the next rebuild**, unlike closing a buffer. This is correct and is the right answer (a settings change is a deliberate user action, not the same "never take away an answer" case `didClose` is), but **no permanent test pins it** and the README's Assumptions section states "the scope only ever grows" without distinguishing the open/close axis (grows-only) from the settings axis (moves either way). Recommend a test plus a clarifying sentence. - A filelist appearing mid-session (settings push) while folder scope was active: flips the ladder to rung 1 immediately on the next rebuild (`folder_scoped()` re-checks `filelist_path()` fresh every call, and `set_client_settings`'s rescan condition already includes `filelist` changes). Correct, and covered indirectly by the existing rescan test, but there is no test that also checks the *index content* actually changes to the filelist's files rather than just triggering a rescan — probed with a temporary test, passed. **CLAUDE.md compliance.** `verify.rs` untouched (no diff, confirmed by `git diff --name-only`). No new `unwrap()`/`expect()`/`panic!` outside `#[cfg(test)]` modules in the round's diff (grepped the four core files' diffs for all three patterns; every hit is inside `mod tests`). Doc comments present on every new public item (`IndexScope`, `ClientSettings::index_scope` /`index_scope_depth`, `Workspace::scope_dirs`). `has_roots()` confirmed genuinely `#[cfg(test)]`-only — grepped every call site in the crate, all seven are inside `#[test]` functions. README sections present exactly once. `TODO.md`'s M1 annotation accurately describes the new default and points at this feature's README. Corpus tests still skip-guarded (`if !corpus.exists() { return; }` pattern unchanged, only their `open_roots` calls swapped). **One item beyond the brief, informational only:** `editors/vscode/package.json`'s `lucisv.index.scope` description says the pre-round behavior is "as lucisv did before 0.11" — a forward guess at the next release number. This round makes no version bump (confirmed: `Cargo.toml` and `package.json` both still say `0.10.2`). Not wrong today, but it is a claim about a future version number sitting in a shipped-looking description; worth a quick check by whoever cuts the next release that it lands on 0.11 and not, say, 0.10.3 or 0.12. **Not touched:** `docs/site/` (per instructions), no commit, no push attempted (remote noted as flaky). **Verdict: committable as-is**, modulo the dev's call on the one MEDIUM finding (the vacuous `a_folder_added_twice_across_two_events_is_absent_after_one_removal` assertion — a real but narrow test-coverage gap, not a product bug: nothing about `change_roots`'s actual dedup/removal behavior is broken, only that one test no longer demonstrates it). The two LOW-MEDIUM missing-permanent-test items (out-of-root buffer under folder scope; depth-narrows-on-settings-change) and the stale-comment LOW items are follow-up hygiene, not blockers — every behavior they probe was independently verified correct by hand in this session. ### 2026-08-28 — QA agent (round 19: drift, staleness, threshold and log-semantics attacks) **Charter.** The round under review (dev work log "a rescan stops re-parsing what is already analyzed", same date) claims an open buffer's index facts and completion words can be read off its already-held analysis instead of re-parsed, and that this is safe because `FileFacts::of` and `Document::new`/`FileFacts::from_analysis` are now one code path entered at different points. The charter was to attack exactly the seam where the two routes could still disagree — a masked-corruption seed in CLAUDE.md's terms — plus staleness, the large-file threshold boundary, the cap interaction, and the new log word. **No drift, no staleness bug, and no cap regression were found.** One real, pre-existing (round-independent) robustness gap was found and is filed separately, not against this round. **1. Drift attack — crafted non-corpus shapes, both facts and words.** Traced `Document::new` (`crates/lucisv_server/src/state.rs:64-92`) against `parse_and_collect`/`facts_of` (`crates/vlog_semantic/src/workspace.rs:773-793, 1023-1034`) line by line: same `tokenize` → `collect_defines`/`parse_tolerant` on the `Ok` branch (same token vector, so `collect_defines` reads the same bytes in both places), same `parse_source_tolerant` on the `Err` branch. The one asymmetry — `Document::new` computes `collect_defines(&tokens)` unconditionally, including when `tokens` is the empty `Vec` from a lex failure, while `facts_of`'s `Err` arm substitutes `DefineTable::default()` directly — cannot drift: `DefineTable` derives `Default` as `entries: Vec::new()`, and `collect_defines(&[])` produces exactly that (confirmed by reading `collect_defines`, `crates/vlog_parser/src/defines.rs:91-104`: the loop never runs on an empty slice). Also confirmed `analyze(tree, text)` (`crates/vlog_semantic/src/lib.rs:65`) takes only the tree and the text — no workspace-index dependency — so nothing about the *workspace* state at the moment a buffer was analyzed can make its `semantics` differ from a fresh parse's. Verified by construction is not verified by attack, so 16 crafted non-corpus shapes were run through the real `Document`+`FileFacts::of` pair (encoded facts equality and sorted-word equality), added as a permanent test: `qa_attack_crafted_non_corpus_shapes_drift_check` (`crates/lucisv_server/src/state.rs:3361-3441`) — a UTF-8 BOM, CRLF, BOM+CRLF, an unterminated block comment, an unterminated attribute, an unterminated macro call, an unterminated string, an embedded control character, deep `begin`/`end` nesting, deep paren nesting, 500 `` `define``s, `` `include`` directives, a tree with parse-error recovery, mixed line endings, an embedded NUL, and tabs/form-feeds. **All 16 passed — no drift.** (The BOM cases lex clean, confirmed separately: `tokenize` silently absorbs a leading BOM rather than erroring, so they exercise the `Ok` branch like ordinary source, not the lex-failure one — noted so the case list isn't mistaken for dead weight.) **One robustness finding, filed as out-of-scope, not blocking this round — LOW/INFORMATIONAL, pre-existing.** Deep `begin`/`end` nesting (500 levels) overflows the stack under `cargo test`'s default per-test-thread stack (2 MiB) — and it does so calling **`FileFacts::of` alone**, no `Document`, no reuse, nothing this round touched. Reproduced identically on `git stash`-ed pristine `master` with the same crafted input run through a temporary `vlog_semantic` test (`cargo test -p vlog_semantic` on unmodified `HEAD`: same abort). Because both routes being compared fail *identically*, this is the opposite of the drift this charter hunts for, and it is not a regression — the recursive-descent parser/analyzer has always had this ceiling; a real server thread's default OS stack is larger (8 MiB main-thread default on macOS, confirmed by running the same input outside the test harness) so this is unlikely to bite in the shipped binary at 500 levels, but the underlying unbounded-recursion-depth issue is real and worth a filed follow-up (a recursion-depth guard in the parser/analyzer, or running the LSP request-handling thread with an explicit larger stack). The permanent test above works around it by running on a dedicated 64 MiB-stack thread, which is what let the drift comparison actually exercise 500-level nesting without tripping the unrelated ceiling. Spun off as a background task rather than fixed here — it is not in this round's files or in `verify.rs`, and touching the parser's recursion handling is a bigger, separate change. **2. Staleness attacks.** `qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan` (`crates/lucisv_server/src/state.rs:3482-3517`, new): an open buffer edited away from disk content (never saved) rescans from the live edit — confirmed via the `Analyzed` route and the indexed member changing from `ON_DISK` to `IN_BUFFER` — and, after `close_document` with no save in between, the very next rescan reparses from disk (`Parsing` route) and the index reverts to `ON_DISK`, with no trace of the closed buffer's analysis anywhere. Also traced structurally: the persistent `IndexCache` is keyed by a content hash of the exact bytes (`crates/lucisv_server/src/index_cache.rs:135-157`, `content_hash(text.as_bytes())`), so even though `rebuild_index_with` writes an open buffer's unsaved-edit facts through to the cache (`state.rs`'s facts-loop, `self.cache.record(&facts, text)`), a later lookup against disk's differently-hashed bytes cannot accidentally hit that record — the two are different cache keys by construction, not by care. The "`didSave` where disk write happens after the rescan reads" race cannot occur either, traced rather than merely tested: `server.rs`'s `DidSaveTextDocument` handler (`crates/lucisv_server/src/server.rs:1319-1334`) calls `self.set_document` (updating the in-memory `Document` from the notification's own text, when present) *before* `reindex_one`/`reindex`, and the reused facts come from that in-memory `Document`, never from a disk read — so there is no window in which the index can read disk before the save's bytes land there. **3. Large-file threshold crossing via unsaved edits, both directions** — the charter's explicit "break it differently" ask, since the dev's own test only checks `doc.large` flips, not that a rescan's *event routing* follows it mid-session. Two new tests: `qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session` and `qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse` (`state.rs:3520-3596`). Small-on-disk/huge-live: a real analysis is reused (`Analyzed`) until the buffer is edited past the threshold, at which point the very next rescan drops it from every list (`analyzed` empty, `parsed` empty — contributes nothing at all, matching the fast-path contract), and shrinking it back reinstates reuse on the next rescan. Huge-on-disk/small-live: `doc.large` is decided from the buffer's own live text length (`is_large`, `state.rs:1298-1301`) and never from what is on disk, so the on-disk size is provably irrelevant to the routing — the buffer is on the fast path the instant it is opened with huge text, whatever the disk copy says, and reuse resumes the instant it is edited back down. **No boundary bug in either direction.** **4. Cap interaction, unchanged in both directions.** New test `qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before` (`state.rs:1780-1817`): an open buffer whose file exceeds `maxFileSize` is still reported `Skipped` once, from `collect_sources`'s disk-phase walk (the `spoken_for` short-circuit this round added only skips the wasted *read*, not the cap check that runs ahead of it — traced in `collect_sources`, `state.rs:930-937`) — and it is still indexed in full afterward, now via `Analyzed` rather than `Parsing`. Confirmed the file is never re-parsed (`parsed` empty) and the content is indexed exactly as before this round. The cap boundary moved in neither direction. **5. Event/log semantics — a real gap found and closed.** No test anywhere in the repository — not `state.rs`'s unit tests (which only check the `IndexEvent::Analyzed` *variant*, via the `scan()` helper), not any e2e test — exercised the actual `"analyzed: "` string a real client would receive over `window/logMessage`, despite `docs/features/indexing-ux/README.md` documenting the exact wording. Added `qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan` (`crates/lucisv_server/tests/e2e.rs`, after `the_size_cap_and_the_file_log_work_over_the_wire`): against the real binary, a scope-widening `didOpen` with one open buffer and one disk-only file logs `analyzed: .../m.sv` and `indexing: .../disk_only.sv` — never the other word for the other file — and the follow-up `didSave` (the incremental `reindex_one` path) emits **no** log line at all, confirmed by counting exactly two `analyzed:`/`indexing:` lines in the whole transcript. This also incidentally re-confirms the work log's claim that `reindex_one` sends no per-file log line, which was previously asserted only by a code comment. **6. Reproducing the numbers, `--release`, three fresh runs of `qa_didopen_latency_when_a_new_folder_widens_the_scope`:** widening `didOpen` **23.95 / 24.20 / 24.31 ms** (claimed ~23 ms), rescan alone **23.91 / 24.09 / 23.88 ms**, closed-buffer floor **12.96 / 12.83 / 12.70 ms** (claimed ~12 ms, unmoved — confirmed unmoved). The buffer's own share, printed by the probe: facts **144.3 ms parsed vs 1.7 ms reused**, words **65.8 ms re-lexed vs 3.1 ms reused** — matches the work log's 140.3 ms/1.67 ms and 62.9 ms/3.09 ms within noise. `qa_references_latency_with_a_big_open_top` (references-nav's own probe): **113 µs**/**128 µs** cross-file either direction (claimed ~110 µs), **1.19 ms** for the in-file fallback on a name used 10 001× (claimed 1.18 ms) — unmoved, confirming this round did not move cost onto the request path. **7. Gates.** `cargo fmt --all -- --check`: clean (after formatting the new tests). `cargo clippy --all-targets --workspace`: zero warnings (two clippy hits in QA's own new tests — `cloned_ref_to_slice_refs`, `useless_format` — fixed before the final run). `cargo test --workspace`: all green, 0 failed, across every crate (lucisv_server's own suite: 1204 passed, 23 ignored — the ignored set is the manual latency probes, run separately above). `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. `verify.rs`: no diff (confirmed via `git diff --name-only`). No new `unwrap()`/`expect()`/`panic!` outside `#[cfg(test)]` in the round's diff or in QA's additions (grepped both). **One documentation nit, LOW, informational.** This README's Handshakes section (`docs/features/index-scope/README.md:219`) says `words_of_tokens(tokens)` "is `pub(crate)`"; the actual declaration (`crates/lucisv_server/src/candidates.rs:246`) is `pub fn`. Harmless in practice — `lucisv_server` is a `bin`-only crate with no `lib` target (confirmed: `cargo test -p lucisv_server --lib` errors "no library targets found"), and `candidates` is a private `mod` (`main.rs:9`), so there is no larger scope for `pub` to leak into within this crate — but the README's wording doesn't match the code. Worth a one-word fix (`pub` → `pub(crate)`, or the sentence corrected) whenever this file is next touched. **Tests added (8), all permanent, all passing.** `crates/lucisv_server/src/state.rs`: `qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before`, `qa_attack_crafted_non_corpus_shapes_drift_check` (+ its `_body` helper, run on a dedicated large-stack thread), `qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan`, `qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session`, `qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse`. `crates/lucisv_server/tests/e2e.rs`: `qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan`. **Verdict: SHIP.** The round's central claim — an open buffer's held analysis is byte-identical to a fresh parse's, so reusing it cannot corrupt the index — held against every attack this session could construct, including shapes the dev's own corpus sweep and crafted-shape list did not cover. Staleness, the large-file threshold's two crossing directions, the cap interaction, and the new log word all check out. The one real finding (stack depth) predates this round, affects both compared routes identically, and is filed as a follow-up rather than a blocker. ## Review ### 2026-08-28 — lead, rescan-reuse round Reviewed the diff and both logs after QA's clean SHIP; gates re-run independently (fmt clean, clippy silent, 2419 workspace tests green). The dev's deviation from the brief's preferred incremental-widen shape is correct and well-argued: a widen that skipped already-indexed files would also skip unsaved buffer edits the full rebuild indexes, an answer change the mandatory fingerprint test would have caught — so shape (b) with the split constructors is the honest one, and the split is genuinely by construction (`facts_of` = parse + `facts_from_analysis`, `words_in` = lex + `words_of_tokens`; one implementation each). The drift attacks QA ran — 16 crafted non-corpus shapes plus both corpus sweeps — are the right coverage for the one risk this design carries, and the staleness/threshold/cap boundary tests close the state-machine edges. `IndexEvent::Analyzed` kept separate from `Cached` so the persistence transcripts keep their meaning: good instinct. ~228 ms → ~23 ms reproduced by dev, QA and the probe's own printout. Lead fixed QA's doc nit directly (`words_of_tokens` tightened to `pub(crate)` to match the Handshakes prose; all callers in-crate). The pre-existing deep-nesting overflow QA found on pristine master is correctly out of scope and spun off. Accepted; committed by the lead. ### 2026-08-27 — lead Reviewed the diff, the work log and the QA log; re-ran all gates myself (2217 workspace tests, 0 failed), clean. The round delivers the owner's model exactly and the two structural decisions are right: scope grows only along the open axis (recomputing from the open set would take working answers away on unrelated saves), and the builder hardening makes the open-files-first ordering provably a reporting nicety — QA independently re-derived the dedup-keeps-first-copy claim and confirmed misuse-after-finish is prevented by ownership, which is the cheapest kind of enforcement there is. The migration path being the same function rather than an equal-output one is the strongest form of the "workspace restores today" promise. Lead actions on QA's findings before commit: the vacuous folder-add/remove test now runs whole-workspace scope with a present-while-added assertion restored (the MEDIUM); the big-buffer cap test's premise is the cap's doing again; the stale rung comments and the forward-guessed version string in the setting description are corrected. The behaviors QA verified by hand but left unpinned (depth-narrowing on a settings change, a mid-session filelist flipping the ladder, an outside-root buffer on the folder rung) are accepted on that verification and assigned to round 19's brief as permanent-test obligations — its dev works in these exact files next. The gitignore-below-root delta stays filed against lucisv_core. Accepted as shipped.