# mcp-cache-and-census Lane **M6** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §6 and §8): the index cache reuse, the startup and per-call timings, the M4 review's rule-6 ruling, the first revision of the `initialize` instructions — and, the lead's half, the token census and the closing release. ## Goal A coding agent's first question to `lucisv-mcp` pays for the index build: 1.9 s on opentitan, every session. The language server has already parsed the same files and persisted one `FileFacts` record per file, keyed by the file's content hash (`lucisv_server::index_cache`). This lane lets MCP start from those records — read only, never written — and from a store of its own in the same codec, so a warm start skips the parse of every file whose bytes a record was read from. A record can only ever stand in for the parse of exactly the bytes it was read from, so the cache is a performance input and never a correctness one: a torn, damaged, foreign or stale record costs a parse and nothing else. ## Assumptions - **Where.** Only `--index-cache DIR` turns the caches on (the extension passes VS Code's `storagePath`, the directory the language server writes `index-cache` in). No OS-cache-dir fallback: without the flag MCP starts cold, as before. The directory may not exist yet (M5 QA F4: VS Code creates `storagePath` lazily) — that is a silent cold start. - **Read.** At startup `cache::Records::load` reads `DIR/index-cache-mcp` and then `DIR/index-cache` (so a record both hold is credited to the editor). A store is used only when its first line is exactly this build's header `lucisv-index-cache\t2\t\t`; any other first line ignores the store whole with **one stderr line**; a missing or empty file is silent. Each record line is `hash\tfacts\tchecksum`; a line whose hash or checksum is not 16 hex digits, whose checksum is not the FNV-1a of the facts field, or which is not UTF-8 is skipped — that covers a torn last line (a writer killed mid-append) and a record edited after it was written. Records are keyed by `(record_path, content hash)`. - **Use.** For each discovered file, MCP reads and hashes the bytes (it must anyway: the stamp and the freshness sweep need the hash). When `(canonical path, hash)` has a record that `FileFacts::decode`s to the same path, `IndexBuilder::add_facts` takes it instead of `add_file`. A record under another path (the language server's paths are whatever the editor handed it; MCP's are canonical) is a miss, not a translation. - **Write — only our own store.** On EOF (the host closes stdin) the server writes `DIR/index-cache-mcp`: the same header, then one record per indexed file — the facts the index holds, under the hash in the file's stamp (both come from the same read, so they describe the same bytes), in path order. Atomic: a `index-cache-mcp..tmp` renamed over the store; a failure removes the temp file and is **one stderr line** (`cannot write the index cache: …`); the session ends either way. The directory is created if missing, and gets a `.gitignore` of `*` when it has none (the language server does the same). **`DIR/index-cache` is never opened for writing**: `cache.rs` has no code path that names it except `fs::read`, and `tests/cache.rs` hashes it before and after whole sessions. - **Not written:** a session that never answered a tool call (no project was built), or a session killed rather than closed. Two MCP servers on one directory each rename their own complete store over the file: last writer wins, both stores are whole. - **The stderr line** is `lucisv-mcp: indexed N files in M ms (E from the editor's cache, O from its own)` when `--index-cache` is given, and the old line without the parenthesis otherwise. `M` now includes the index merge (`IndexBuilder::finish`), which the M1 line left out — the number went up by the merge's ~200 ms on opentitan; the build did not change. - **The codec is restated, not shared.** `index_cache.rs`'s `FILE`, `CACHE_FORMAT`, header and line formats are private to `lucisv_server` (a binary crate MCP must not depend on — PLAN §4.1). `cache.rs` restates them; `cache::tests::the_codec_is_the_language_servers_own` reads `crates/lucisv_server/src/index_cache.rs` at test time and fails if any of the five pinned source lines changes (Handshake MCP-14). - **Rule 6, the M4 ruling.** `delete_item` with `force: true` may remove an item that holds `` `define``/`` `undef`` entries (a module with a `` `define`` in its body, an `always` with one nested): the deletion passes rule 6 and the answer carries the warning `deleted macro definitions: Q, W (undef) — code after the item that used them will change meaning` (each name once, in source order, `(undef)` for an `` `undef``). Without `force` the refusal stands and now ends `, or pass `force: true` to delete it anyway`. `replace_item` and `insert_item` take no `force` and are unchanged. The verifier change is local: `Expect::Nothing { force }`, and `Outcome::dropped_macros`. - **The instructions** (`rpc.rs`, 787 characters, pinned ≤ 900 by a wire test) name the read tools to prefer over reading files, that edits are verified, all-or-nothing, on disk with `dry_run`, the item tools vs the design-wide ones, `diagnostics` to check, and the path/column units. The lead revises them after the census. ## Handshakes Consumed (unchanged, read only): `vlog_semantic::{FileFacts::{encode, decode, path}, record_path, FACTS_FORMAT, IndexBuilder::{add_facts, add_file, finish}, WorkspaceIndex::{facts_for, fingerprint}}`; `lucisv_core::cache::content_hash`; the byte format of `lucisv_server::index_cache` (below). Promised: `Project::open_cached(roots, filelist, cache_dir)` (the old `Project::open` is now the tests' uncached shorthand), `Project::save_cache`, `Project::reuse`. `rpc.rs` calls them in `open_project` and on EOF. Filed: - **MCP-14 → `lucisv_server` (informational + one request).** MCP reads the server's `index-cache` read-only (`fs::read`, never a write handle) and writes `index-cache-mcp` beside it in the same codec. Nothing in the server changes. *Request (not blocking):* the codec constants (`FILE`, `CACHE_FORMAT`, `header()`, `line()`/`parse_entry`) are private to a binary crate, so MCP restates them and pins the restatement against the source text; lifting the codec (not the store) into `vlog_semantic` or `lucisv_core` as a pure move would let both sides share one definition and retire the pin. Until then, **a change to the store's framing must bump `CACHE_FORMAT` and update `crates/lucisv_mcp/src/cache.rs`** — the pin test fails otherwise. - **MCP-7 → `vlog_refactor`: status unchanged (open).** `rename` still hands the engine the whole set: 2.23–2.28 s per dry run on opentitan (below), the cost MCP-7's `KnownFacts` variant (or passing the index's facts to `rename_traced_with`, which already takes `&dyn KnownFacts`) would remove. That is an M3 tools change, not this lane's. - **Out-of-ownership edit, flagged for the lead:** `tests/qa_m4.rs` `qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always` pinned "a forced delete of a module holding a `define is refused" — the exact behaviour the M4 review ruled to change. The loop over `force ∈ {false, true}` became the unforced refusal plus a forced dry run that must succeed and name `LOCAL` (8 lines, comment says why). Without it `cargo test -p lucisv_mcp` is red. - **For the lead (docs outside this lane):** the M1 README's Assumption "`--index-cache DIR` is accepted and stored, and unused until M6" is now stale; `docs/mcp/PLAN.md` §6 matches what was built. ## Status / TODO - [x] `cache.rs`: read-only reader of the editor's store (header, per-line checksum, `record_path`, `decode`), keyed by path + content hash - [x] warm start: `add_facts` on a hit, parse on a miss; hit counts on the stderr startup line - [x] own store `index-cache-mcp`: same codec, written atomically on EOF, read on start; a write failure is one stderr line - [x] F4: a missing directory is a silent cold start - [x] unit tests (`src/cache/tests.rs`): the codec pin; warm from the editor's store = cold fingerprint; own store round trip = cold fingerprint; a changed file misses; torn / damaged / foreign records each a parse; a record under another path or hash not taken - [x] wire tests (`tests/cache.rs`): the editor's store byte-identical (hash + mtime) after a session that indexes, answers and edits, with a damaged and a torn record skipped; another version's store ignored with one line; missing directory → cold, own store written, next start warm from it, a changed file re-parsed and answered new; an unwritable directory (0555) → answers, one stderr line, nothing written - [x] opentitan timings (`tests/opentitan.rs`, ignored): cold / warm from own store / warm from the editor's store, exit write, stat sweep, whole-set `rename` - [x] rule-6 ruling: `force` relaxes rule 6 on `delete_item` with the warning; wire test + attack test - [x] `INSTRUCTIONS` first revision (≤ 900 characters, wire-tested) - [x] `docs/perf/README.md` MCP entry - [ ] token census, instruction revision after it, topo, CHANGELOG, release — the lead's ## Timings Release build (`cargo test --release -p lucisv_mcp --test opentitan -- --ignored --nocapture opentitan_startup`), macOS arm64, the whole opentitan checkout (3 944 indexed files, 3 over 1 MiB skipped), two runs; the checkout's `git status --porcelain` identical before and after. The stores live in a scratch directory outside the checkout; the "editor's store" is the own store renamed to `index-cache` — the same bytes the language server would write (46.3 MB), which is what the codec pin guarantees. | what | wall | |---|---| | cold start, no store (first `project_overview`) | 1 854–1 887 ms (build 1 800–1 880 ms) | | warm from its own store | 837–847 ms (build 821–840 ms, 3 944 hits) | | warm from the editor's store | 821–832 ms (build 814–824 ms, 3 944 hits) | | exit, writing `index-cache-mcp` (46.3 MB) | 251–272 ms | | per-call freshness sweep (`outline` of a cached file, median of 21) | 5.6–6.1 ms | | — the transport floor (`tools/list`, median of 21) | 0.38 ms | | `rename` `op_i` → `cipher_op_i` at `hw/ip/aes/rtl/aes_cipher_core.sv:123`, `dry_run`, whole set | 2 227–2 276 ms (first and second call alike) | Where a warm build's ~820 ms goes (one instrumented run, not committed): walk 210 ms, reading the store 87 ms, reading + hashing + decoding 3 944 files 318 ms (1 387 ms when each is parsed instead), the index merge 204 ms. The walk and the merge are the floor a cache cannot remove. ## Token census (lead) ## Work log **2026-09-23 (dev, Opus).** Built as briefed, in the owned files plus the two flagged edits (`rpc.rs` wiring beyond `INSTRUCTIONS`; `tests/qa_m4.rs`). - `cache.rs` (118 production lines): `Records::load/take`, `write_own`, the restated header/line codec, `store_lines` reading bytes a line at a time exactly as the language server does (a torn multi-byte character costs one line). `Reuse` counts hits by source. - `project/mod.rs`: `open_cached` + a `load` helper (read, stamp, take a record or parse); `save_cache` builds `(stamp.hash, index.facts_for)` per file; `reuse()`. **Deviation:** the build clock now stops after `finish()` — the old code read the clock before the merge ran inside the struct literal, so every "indexed in M ms" since M1 left out ~200 ms on opentitan. `Project::open` became `#[cfg(test)]` (its only callers are tests; clippy's dead-code lint otherwise). - `rpc.rs`: `open_project` calls `open_cached` and prints the counts; `Line::Eof` calls `Server::finish`, which saves (verbose: a line with the record count; failure: one line always). **Deviation:** the brief listed `rpc.rs` for `INSTRUCTIONS` only, but the startup line and the EOF write live there; the change is those two call sites. - `verify.rs`/`item.rs`: the rule-6 ruling (above); `delete_item`'s description and `force` parameter say so. - Unit tests live in `src/cache/tests.rs` (the fingerprint oracle needs `Project`, which a `tests/` file cannot reach in a binary crate). - The own store is rewritten on every exit even when unchanged (~260 ms on opentitan, after the last answer): simple, and a store the host kills us during is still the previous whole store. - Tests: `lucisv_mcp` 290 → 302 passing (+5 unit, +4 `tests/cache.rs`, +3 wire), ignored 2 → 3 (the opentitan timing test); workspace 4 846 → 4 858. **2026-09-23 (dev, feedback-1).** QA finding 2 fixed: `write_own` first removes `index-cache-mcp..tmp` files older than 10 minutes (a younger one may be a live writer's); `qa_an_orphaned_temp_file_is_swept_by_the_next_write` un-ignored. `INSTRUCTIONS` revised (896 characters) — `docs/features/mcp-feedback-1`. ## QA log **2026-09-23 (QA, Opus) — QA — interrupted** (the session was cut off before the workspace gate finished; everything below was run and is recorded as measured). **The cache half of the M6 QA line. Verdict so far: pass; no wrong record served, the editor's store never written. Two non-blocking findings (one doc, one inherited leak). The census spot-check waits for the census.** Tests in `crates/lucisv_mcp/tests/qa_m6.rs` (16 pass, 1 ignored = finding 2), each spawning the real binary over a scratch copy of the `design` fixture. *Wrong-record hunt (blocking class — nothing found).* - **Swapped records, checksums recomputed** (`leaf.sv`'s hash carrying `top.sv`'s facts and the reverse): not served. The key is `(record_path of the facts, hash)` and `take` compares the decoded path again, so each lands under (other path, this hash) and matches no file — 5/7 hits, the probe's nine answers equal a cold start's. Also run on a copy of opentitan `hw/ip/{aes,prim}` with a real language-server store (`prim_fifo_sync` ↔ `prim_fifo_async`): 391/393 hits, both interfaces right. - **Inherited, documented limit (not a finding against the code):** a record *relabelled* — `prim_fifo_async`'s facts with `prim_fifo_sync.sv`'s path, under `prim_fifo_sync.sv`'s real hash, checksum recomputed — is served (393/393 hits; `unit_interface prim_fifo_sync` answers "not indexed") and is then re-laundered into `index-cache-mcp` with a fresh checksum. The language server does exactly the same: `index_cache.rs`'s module doc states the same-user/same-disk threat model (FNV-1a is not a MAC; whoever can write the store can write the sources). Accidental damage cannot produce this shape. See finding 1 for the doc. - Records for a deleted file and for a file outside every root (it exists beside the root): neither module listed, neither record written back (own store = header + 7). Two records for one path under two hashes (the append log's normal shape): the one whose hash is the bytes on disk is served, older or newer; two for one `(path, hash)`: the later line wins, as in `IndexCache::open` (tested with a checksum-valid wrong record first and the honest one last). - CRLF store: `\r` stripped exactly as the language server strips it, 7/7 hits, answers = cold. Header near-misses — version patch + 1, `FACTS_FORMAT` ± 1, `CACHE_FORMAT` 1 and 3, a trailing space, a BOM, a fifth field: each ignored whole with exactly one stderr line, store byte-identical. Empty store, header-only store, a directory named `index-cache`: silent cold starts (stderr = the startup line only). - A 231 MB store (opentitan's 46 MB store + 4 copies under `/ghostN` paths, checksums valid), release build, 3 944 files: build 892 / 937 / 1 026 / 1 203 ms at 46 / 92 / 138 / 231 MB — linear (~1.7 ms/MB); peak RSS 407 → 750 MB (the store bytes plus every record's string are held until the load ends); the store byte-identical after each run. *Read-only promise and the own store's writes.* - The editor's store at mode 0444, in a live server's between-compactions shape (reversed path order, a duplicate line, a torn line mid-file, a checksum-failing line), through a session that indexes, answers, runs `format` (writes a file) and ends: bytes, mtime and mode identical, 7/7 hits. On the real `aes`+`prim` LSP store: `shasum` identical after a warm session. Code: `cache.rs` names `EDITOR_STORE` only in `Records::load` → `fs::read`; `write_own` writes only `index-cache-mcp`, its temp file and `.gitignore` (when missing — as the language server does). - Killed sessions (SIGKILL): after an answer and before EOF (fixture, with a changed file that would have changed the store): the previous own store byte-identical, no temp file, the next start re-parses the changed file. On opentitan, killed at 20–350 ms after EOF (11 delays): own store intact, no temp. Killed the instant `index-cache-mcp..tmp` appeared: store intact, **a 9.4 MB temp file left behind for good** → finding 2. - `--index-cache` naming a regular file: answers right, one `cannot write the index cache` line, the file untouched. A directory named `index-cache-mcp`: silent read miss, one line at exit, no temp left. Cache directory mode 000 holding an honest store: cold start, the nine probe answers equal cold's, one line at exit, store untouched. (A startup that cannot *read* a store is silent — only the exit's write failure speaks. Acceptable for a performance input; noted, not filed.) *Parity.* - The nine-answer probe (`list_units`, two `unit_interface`, two `outline`, `search_symbols`, `references`, `hierarchy`, `defines`) is identical cold, warm from the editor's store and warm from the own store. - A **real language-server store** (release `lucisv-server` driven over stdio on a copy of `hw/ip/{aes,prim}`, `index.scope = workspace`, `storagePath` = scratch; 393 records, 2.69 MB): MCP warm start 393/393 editor hits, and — the stronger check — a **cold** MCP session's `index-cache-mcp` over the same tree is **byte-identical** to the server's `index-cache`: same header, same facts, same order. - `WorkspaceIndex::fingerprint` (throwaway unit test in a scratch copy of the crate, not committed): warm-from-LSP-store = cold on `aes`+`prim` (393 files); warm-from-own-store = cold on the **whole opentitan checkout** (3 944 files, fingerprint 37.2 MB); the checkout's `git status --porcelain` identical before and after every run. - Same-size edit (`held` → `hold`) since the store: re-parsed, the outline shows `hold`; a new file since the store: indexed; 6/7 hits. *Rule 6 (the M4 ruling).* A module holding `` `define LOCAL`` twice and a nested `` `undef GONE``, read by the module after it: without `force` refused (names rule 6 and `force: true`), file byte-identical; forced: the warning reads `deleted macro definitions: LOCAL, GONE (undef) — …` (each name once, source order), every byte before and after the item's lines is the original's. `force` on an item with no macro says nothing about macros. The `tests/qa_m4.rs` diff is exactly the ruling's assertion swap (the `force ∈ {false, true}` refusal loop → unforced refusal + forced dry run naming `LOCAL`), nothing else. The code: `Expect::Nothing { force }`; for a deletion `same_macros` can only fail when the region held a definition, which is exactly what `dropped` lists — `force` cannot excuse anything else. *Instructions.* 787 characters (≤ 900). Names `unit_interface`, `outline`, `read_item`, `list_units`, `search_symbols`, `definition`, `references`, `hierarchy`, the three item tools, `rename`, `add_port`, `remove_port`, `format`, `fix_lint`, `diagnostics` — every one in `tools/list`, and no snake_case word that is not a tool (`dry_run` aside); says disk-only, root-relative paths, 1-based byte columns. *Sizes.* Production lines: `cache.rs` 118, `project/mod.rs` 289, `rpc.rs` 265, `tools/item.rs` 389, `tools/item/verify.rs` 388 — all under 600. *Timings (release, whole opentitan, this machine, `tests/opentitan.rs`).* Cold 1 769 ms build (first call 1 776 ms); warm own 833 ms; warm editor's 807 ms; exit write 243–260 ms; sweep median 4.9–5.0 ms (floor 0.35 ms); `rename` dry run 2 152–2 172 ms. Consistent with the dev's table. *Findings.* 1. **(low, doc)** `docs/features/mcp-cache-and-census/README.md` Goal: "a torn, damaged, foreign or stale record costs a parse and nothing else" overclaims — a forgery that recomputes the FNV-1a checksum is served (reproduction above; the language server has the same property by design). Fix: say "a torn, damaged, foreign or stale record", and add the threat-model sentence the server's `index_cache.rs` module doc carries (same user, same disk; the checksum catches damage, not intent) to Assumptions → Read. No code change. 2. **(minor, inherited)** `crates/lucisv_mcp/src/cache.rs:140-146` (`write_own`): a process killed between `fs::write(tmp)` and the rename leaves `index-cache-mcp..tmp` (9.4 MB on opentitan) that no later session removes — one per crash, each up to the store's size. Harmless to correctness (only the exact store names are read). Same leak as the language server's, filed by its QA 2026-08-27 (`an_orphaned_compaction_tmp_file_is_never_swept_up`). Pinned by `qa_an_orphaned_temp_file_is_swept_by_the_next_write` (ignored). Fix: before writing, remove `index-cache-mcp.*.tmp` files in `dir` older than a few minutes (a concurrent writer's live temp file is seconds old). *Gates* (through `tools/guard.sh`, one at a time): `cargo fmt --all -- --check` clean; `cargo clippy --workspace --all-targets` clean (no warnings); `cargo test -p lucisv_mcp` 318 passed, 0 failed, 4 ignored (302 + 16 QA; ignored: 2 opentitan, M3 finding, M6 finding 2); the opentitan tests (release, `--ignored`) 2 passed, checkout unchanged; `cargo test --workspace` **NOT completed** — cut off after ~16 minutes, mid-run (reached `vlog_refactor`, `corpus`, `inline` test binaries; every result line captured before the cut-off was `ok`, no failure seen). *Not yet checked:* the full `cargo test --workspace` count (needs ≥ 4 858 + 16 = 4 874 passing); the census transcripts spot-check (the census has not been run — the lead's half); a whole-opentitan store written by the *language server itself* (only `aes`+`prim` was; whole opentitan was checked with MCP's own store). The M6 QA box in `TODO-MCP.md` is left unticked. ## Review **Lead, 2026-09-23 (M6, committed at the owner's move).** The reader keys a record on the file's content hash and the record's own path, never writes the editor's store, and a warm start on opentitan halves the startup (1.9 s → 0.8 s; the walk and the merge are the floor). QA (interrupted by the move, verdict pass so far): swapped, stale, foreign-path, deleted-file, off-by-one header and CRLF stores all skipped; the editor's store byte-identical through a session; SIGKILL mid-write leaves the previous own store intact; a 231 MB store loads linearly; fingerprint parity with a cold build over the whole checkout. Two low items: the README's threat model now says "damaged", not "forged" — a record with a recomputed checksum is used, exactly as the language server uses it, because whoever can write the store can write the sources; and an orphaned `index-cache-mcp..tmp` after a kill between write and rename is not swept (QA's ignored test `qa_an_orphaned_temp_file_is_swept_by_the_next_write`) — to be fixed in the first census round. The forced-delete ruling (rule 6) and the first `INSTRUCTIONS` revision landed here; the census revises the instructions again. The full workspace suite was still running when the machine moved; the dev's run on the same code passed 4 858 and QA's crate suite 318.