From 574ab833e34b5fb6ef43de1f8f290ea960cb937c Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Fri, 28 Aug 2026 03:16:54 -0700 Subject: [PATCH] Feature docs for the responsiveness round, and a perf record MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three new feature READMEs — change-debounce, port-detail-spans, interactive-latency — each with the mandated sections, dev work logs, QA findings and their dispositions, and the lead's review. Plus `docs/perf/README.md`, the record of what was measured, on what, on which machine, and with which command, so a later round can say whether it made something faster or only different. `topo.md` is added to the tree: the dependency topology the round was planned against, with this round's new edges — the `detail_span` and `symbols_named` handshake between the server and `vlog_semantic`, and the facts-format edge to index persistence. The perf record keeps its losses as well as its wins. A keystroke followed by nothing now publishes at 164 ms rather than one reanalysis, because it waits out the quiet period; a perf document that only records improvements is not a perf document. Co-Authored-By: Claude Opus 5 --- TODO.md | 24 + docs/features/change-debounce/README.md | 290 +++++++++ docs/features/hover-declarations/README.md | 89 +++ docs/features/incremental-sync/README.md | 9 + docs/features/interactive-latency/README.md | 440 ++++++++++++++ docs/features/lucisv-server/README.md | 24 +- docs/features/port-detail-spans/README.md | 448 ++++++++++++++ docs/perf/README.md | 490 +++++++++++++++ topo.md | 633 ++++++++++++++++++++ 9 files changed, 2436 insertions(+), 11 deletions(-) create mode 100644 docs/features/change-debounce/README.md create mode 100644 docs/features/interactive-latency/README.md create mode 100644 docs/features/port-detail-spans/README.md create mode 100644 docs/perf/README.md create mode 100644 topo.md diff --git a/TODO.md b/TODO.md index fceed2b..ba6127d 100644 --- a/TODO.md +++ b/TODO.md @@ -573,6 +573,18 @@ later: written to a content-keyed store as a scan parses them, so the recompute a *new session* would otherwise repeat is skipped instead — 1.8x on a whole corpus rescan, and a scan interrupted halfway resumes where it stopped. + **A third piece answered without salsa, 2026-08-28** + (`docs/features/change-debounce/README.md`): the per-keystroke recompute a + query graph would have made unnecessary is instead *not started* — a burst + of `didChange`s is coalesced into one reanalysis. Still no query graph and + no dependency tracking; the salsa question remains open and deferred. + Measured costs for what a recompute actually is are now recorded in + `docs/perf/README.md`. **Round 2, 2026-08-28** + (`docs/features/interactive-latency/README.md`): that recompute is now + broken down stage by stage, and 79 % of it is lexing and parsing. If the + salsa question is ever reopened, that is the number it has to beat — + incremental *lexing and parsing*, not incremental queries over a whole-file + parse, and it lands squarely on `CLAUDE.md`'s hard invariants 1 and 2. - [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version bumped to 0.2.0 across the workspace and the extension, `tools/release.sh` (release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and @@ -721,6 +733,18 @@ and are not gaps. publish — per notification. Advertised as `TextDocumentSyncOptions` with the open/close and `save.includeText: false` values a bare `Kind` already implied, so no client's save behavior moved. + **Amended 2026-08-28** (`docs/features/change-debounce/README.md`): a + `didChange` now only records the composed text; the reparse, the + generation bump and the publish happen at the next *flush* — the next + request, the next non-`didChange` notification, or a 150 ms quiet period — + so a typing burst costs one of each instead of one per keystroke. The + buffer's text is still exactly current after every notification; only its + analysis is deferred, and intermediate diagnostics states are no longer + published. **Measured 2026-08-28** + (`docs/features/interactive-latency/README.md`): a burst of ten keystrokes + over the wire produces exactly one `publishDiagnostics`, and a keystroke a + request follows — the shape a real editor sends — round-trips in 4.8 ms at + 1 000 lines and 37 ms at 10 000. - [x] **`textDocument/willSaveWaitUntil`** — the protocol-native format-on-save hook (client-side `editor.formatOnSave` already works; this serves the editors without it). diff --git a/docs/features/change-debounce/README.md b/docs/features/change-debounce/README.md new file mode 100644 index 0000000..248a123 --- /dev/null +++ b/docs/features/change-debounce/README.md @@ -0,0 +1,290 @@ +# change-debounce + +## Goal + +Stop paying a full reanalysis for every keystroke. Before this round each +`textDocument/didChange` notification ran `set_document` immediately — lex, +parse, `analyze`, `resolve_external`, lint, publish — so a burst of ten +keystrokes cost ten of everything and nine of those answers were thrown away +before anyone could read them. A `didChange` now only records the buffer's new +text as *dirty*; the analysis runs at the first moment anything actually needs +it: the next request, the next non-`didChange` notification, or a 150 ms +quiet-period timer in the message loop. The buffer's **text** is still exactly +current after every notification — only the analysis of it is deferred — so +nothing that reads `didChange` results out of order can see a stale buffer. +On a 10 000-line file one deferred keystroke saves 31 ms of work +(`docs/perf/README.md`); a ten-keystroke burst saves nine of them. + +## Assumptions + +- **A client sends a burst, not a single change.** Typing produces + notifications faster than 150 ms apart; the debounce only pays off while + that is true, and costs at most 150 ms of latency when it is not. +- **150 ms is short enough not to be felt and long enough to coalesce a + burst.** It is the same order as the debounce every mainstream language + server uses. It is a constant (`CHANGE_DEBOUNCE` in `server.rs`), not a + setting: a knob here would be one more thing to get wrong, and no user has + asked for one (`TODO.md` §7, "no option explosion"). +- **Diagnostics are the one answer nobody requests.** A pushing client never + asks for them, so waiting for "the next request" alone would leave a file + undiagnosed indefinitely for a user who types and then stops. That is the + whole reason the timer exists, rather than flushing only on demand. +- **A flush is cheap to trigger from anywhere.** `flush_dirty` returns + immediately when nothing is dirty, so the calls at the top of `request` and + `notification` cost a `Vec::is_empty` on every message. +- **Order within a burst does not matter, order across buffers does.** Dirty + buffers are flushed oldest-first (`mark_dirty` replaces an entry in place + rather than moving it to the back), so the sequence of `publish` calls a + client sees for two edited files is the order they were first edited in. +- **Losing an unanalyzed change with its buffer is correct.** `didClose` + drops the buffer's pending text: there is nothing left to flush it into, + and the client is not looking at the file any more. The drop happens at the + *top* of `notification`, ahead of the universal flush — doing it in the + `didClose` arm is too late, because the flush has already run by then (QA, + CD-1). Closing one buffer says nothing about the others, so every other + dirty buffer flushes on that same notification exactly as before. + +## Handshakes + +- **Amends `docs/features/incremental-sync/README.md`'s pinned invariant.** + That round promised "one `didChange` = one `set_document` = one generation + bump, however many ranges". The promise is now: **one *flush* is one + `set_document`, one generation bump and one `publish` per dirty buffer** — + however many ranges *and however many notifications* were coalesced into it. + Everything the old promise protected still holds: the generation counter + (which is `docs/features/pull-diagnostics/README.md`'s whole `resultId`) + never moves twice for work that happened once, and never fails to move for + a buffer whose text changed. `incremental-sync`'s own test, + `one_notification_is_one_generation_bump_however_many_ranges`, still passes + unchanged, because the test helper flushes after each notification — which + is exactly the quiet-period timer firing. +- **Observable consequence, pinned in `crates/lucisv_server/tests/e2e.rs`** + (`incremental_changes_are_advertised_and_applied_over_the_wire`): + **intermediate diagnostics states are no longer published**. Two changes + arriving back to back — the first breaking a line, the second finishing it + — used to produce three publishes (open, broken, fixed) and now produce two + (open, composed). Every state that *is* published is a state the buffer + really passed through; there are simply fewer of them. That test asserted + the old count and now asserts the new one, with the reason written beside + it. +- **Consumes `sync::apply_changes` unchanged.** Ranged changes are composed + against the newest text the server holds, which while a buffer is dirty is + the *pending* text, not the last analyzed one. `Server::notification` looks + in `dirty` before `workspace.document`. Nothing in `sync.rs` moved. +- **Consumes `lsp_server`'s queue as a `std::sync::mpsc` receiver.** The + timer is `Receiver::recv_timeout` on the queue `cancel-request` already + introduced (`docs/features/cancel-request/README.md`); no thread and no + timer object was added. A `Disconnected` receiver ends the loop exactly as + the old `while let Ok(..)` did. +- **Promises every request still sees the client's own changes.** The flush + at the top of `Server::request` runs before dispatch, so a request answered + after a `didChange` is answered from that change's analysis — the order + contract the loop always had. The large-file fast path is behind that + flush, not in front of it. +- **No protocol change, no settings change, no index change.** The + capabilities advertised at `initialize` are byte-identical. + +## Status / TODO + +- [x] `dirty: Vec<(Uri, String)>` on `Server` — newest text per buffer, in + first-dirtied order. +- [x] `mark_dirty` replaces in place, so a burst does not reorder buffers. +- [x] `flush_dirty` — one `set_document` + one `publish` per dirty buffer. +- [x] `didChange` composes ranges against the pending text when there is one. +- [x] Flush on every request, before dispatch. +- [x] Flush on every notification that is not a `didChange`. +- [x] `CHANGE_DEBOUNCE` (150 ms) quiet-period flush in `run`, via + `recv_timeout`, only while something is dirty. +- [x] `didClose` drops the buffer's pending change — before the flush, so the + drop is real (QA, CD-1), pinned by + `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`. +- [x] Test: a burst is one reparse + (`a_burst_of_changes_coalesces_into_one_reparse`). +- [x] Server tests drive one notification at a time, so the test helper + `change()` flushes — documented there as the timer firing. +- [x] e2e: the publish count and the reason for it. +- [ ] Not done: a flush for a *long* burst that never pauses (a paste-and-hold + or a client replaying a file's history sends changes closer together + than 150 ms forever). Today such a burst is analyzed when it ends or + when the next request arrives. A "flush after N pending changes" + backstop is the obvious answer if anyone ever reports it; it is not + written because no client behaves that way and an untested backstop is + worse than none. + +## Work log + +**2026-08-28 — dev.** Implemented as part of the LSP performance round +(plan: "Improve LSP performance + hover accuracy", part A1). + +- The deferral is a `Vec`, not a `HashMap`: it holds one entry per *dirty* + buffer, which is one in practice and two while a user alt-tabs. A linear + scan of that is cheaper than hashing a `Uri`, and the `Vec` gives the flush + order for free. +- Deferred **analysis only, never text**. The alternative — deferring + `apply_changes` too and keeping a queue of unapplied changes — was + rejected: every reader of `Document::text` would then need to know about + the queue, and the ones that forgot would be silently wrong. Composing the + text eagerly keeps the pending state to exactly one `String` that only + `didChange` and `flush_dirty` know about. +- The flush points were chosen to be exhaustive rather than clever: *every* + request and *every* notification except the one being deferred. Anything + that needs analysis is downstream of one of those two, so there is no + handler that has to remember to flush for itself. +- `run` only arms the timeout while something is dirty, so an idle server + still blocks in `recv()` and wakes for nothing. +- The server unit tests drive notifications one at a time through a helper + rather than through the loop, so no burst ever forms and nothing would + flush them; the helper flushes explicitly, which is the timer's behavior. + Three tests that hand-rolled a `didChange` notification were moved onto + that helper. + +**2026-08-28 — dev (QA fix).** + +- **CD-1 — fixed.** The `didClose` arm's `dirty.retain` was dead code: the + universal flush at the top of `notification` had already drained `dirty` + through `std::mem::take` by the time the arm ran, so a buffer closed + mid-edit paid a full `Document::new` and published its real diagnostics one + line before the close cleared them. The retain moved to the top of + `notification`, *ahead* of the flush, guarded on the method name; the arm's + comment now says where the drop happened instead of pretending to do it. + - The uri has to be read without consuming the notification, since + `extract` takes it by value and the arm below still needs it. That is a + four-line `closing_uri` beside `extract`, deserializing a clone of the + params — a `didClose`'s params are a single uri, so the clone is not + worth avoiding with a peek into the raw `Value`. `None` (params that do + not parse) drops nothing, which is exactly what the arm below already + does with the same params. + - The "flush on every notification but `didChange`" rule is unchanged: the + flush still runs for `didClose`, and every *other* dirty buffer still + goes through it. What changed is only that the closing buffer is no + longer in `dirty` when it does. + - Pinned by `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone` + (`server.rs`): two buffers dirtied with text that would diagnose, one + closed with no request in between; the generation bumps exactly once (the + buffer still open), the closed buffer gets exactly one publish and it is + the clearing one, and the other buffer's pending edit is published as + usual. Verified the test fails on the pre-fix code — `left: 5, right: 4` + on the generation assertion — before keeping it. + +## QA log + +**2026-08-28 — QA.** Gates run and green: `cargo fmt --check`, +`cargo clippy --all-targets --workspace -- -D warnings`, `cargo test +--workspace` (0 failed everywhere; `lucisv_server`: 1179 passed, 19 ignored +perf tests), `cargo test -p vlog_formatter` (114 passed). All findings below +were reproduced with temporary `#[test]`s added to `server.rs`, run, and then +removed once confirmed — none are left in the tree. + +- **Finding CD-1 (medium — contradicts a checked-off invariant, wastes work, + does not corrupt anything).** `didClose` does **not** actually drop a + buffer's pending dirty change before analyzing it. `Server::notification` + (`server.rs:1247`) flushes unconditionally for any non-`didChange` method + (`server.rs:1253`, `if method != DidChangeTextDocument::METHOD { self + .flush_dirty(); }`) — and `didClose` is such a method. That flush runs + *before* the `match` statement even reaches the `DidCloseTextDocument:: + METHOD` arm (`server.rs:1407`), so by the time `self.dirty.retain(|(pending, + _)| *pending != uri)` executes (`server.rs:1413`), `flush_dirty` has already + drained `self.dirty` via `std::mem::take` — the retain is a no-op in the + normal flow. Net effect: closing a buffer that was mid-edit costs one full, + wasted reparse + `publish` of the real (about-to-be-discarded) diagnostics, + immediately followed by the close handler's own `send_diagnostics(uri, + Vec::new())` clearing them — **two** publishes instead of the zero extra + ones the design claims. This directly contradicts both the checked-off + status-line "`[x]` `didClose` drops the buffer's pending change" and the + code comment beside the (dead) retain: "there is nothing left to flush it + into" — there is, and it does get flushed. + - Repro (temporary test, `server.rs`, removed after confirming): open a + clean buffer (`module m;\nendmodule\n`), drain the open publish, note + `generation`, send one `didChange` to `module m;\n wire ;\nendmodule\n` + (introduces a parse error, buffer stays dirty — `generation` provably + unchanged, `dirty` non-empty), then send `didClose` with **no** request + in between (`session.notify`, which calls `Server::notification` + directly, exactly the production path — no manual flush helper + involved). Observed: `generation` bumps by exactly one during the + `didClose` call (`2` → `3`), and `session.published()` returns **2** + messages: one carrying the real parse-error diagnostic + (`"expected identifier (found \";\")"`), then one with `diagnostics: []`. + - Not a data-corruption bug — the client ends up with the correct final + state (empty diagnostics for a closed file) — but it is a real, + reproducible functional gap in exactly the case the debounce is supposed + to help most: a user who edits and then immediately closes a buffer pays + the full analysis cost the feature exists to avoid, silently. Left + unfixed (not small/unambiguous — the right fix wants a decision about + whether the top-of-`notification` flush should special-case `didClose`, + or whether `didClose` should remove its own `dirty` entry *before* that + flush runs, which touches the "flush on every notification but + `didChange`" rule this round explicitly checked off). + +- **Attack angles from the brief, checked and clean:** + - *An un-flushed edge, generally.* Every request and every non-`didChange` + notification flushes at its own top (`server.rs:1253` for notifications, + the equivalent at the top of `request`), so the only genuinely + un-flushed state is "nothing has asked for analysis yet" — which is + exactly what the quiet-period timer exists to bound at 150 ms, and the + documented, un-checked TODO item (a burst that never pauses) is real but + already honestly disclosed, not silently missing. + - *`didChange` on a file the client never opened.* `mark_dirty` does not + require a prior `didOpen`, and neither did the pre-debounce + `set_document` call it replaces — `flush_dirty`'s `set_document` creates + the buffer exactly as before. No new behavior here. + - *`didChange` racing `didSave`.* `didSave` is not `didChange`, so it + flushes first (`server.rs:1253`) — a save's reindex always sees the + latest edited text analyzed, never a stale buffer racing a fresh disk + scan. + - *Version-number ordering.* The server does not track LSP version numbers + at all (`publishDiagnostics`'s own `version` field is hard-coded `None` + at `server.rs:1848`, unchanged by this round) — nothing new to get out of + order. + - *Pending vs. analyzed text observed inconsistent by a request.* Cannot + happen: `request` flushes before dispatch (`server.rs`'s `fn request`), + so a request is always answered from the analysis of whatever is + currently held, dirty or not. + - *The `e2e.rs` publish-count change (3 → 2).* Confirmed the buffer + genuinely passed through both published states and no diagnostic was + lost: traced `incremental_changes_are_advertised_and_applied_over_the_wire` + — the two `didChange` notifications and the `textDocument/formatting` + request all arrive in one write to the mock transport, so the request's + own top-of-`request` flush (or the burst's internal ordering) coalesces + both notifications into the one flush that produces publish #2; publish + #1 is the clean `didOpen`. The removed middle publish (the transiently + *broken* half-edited state) was never a state a real, unhurried client + would see anyway — it is the debounce's whole point. + - *`a_burst_of_changes_coalesces_into_one_reparse`.* Re-derived by hand: + `generation` provably does not move across the two-notification burst, + then moves by exactly one at the first request after it, and `dirty` is + empty afterward — matches the claimed semantics exactly. + +- **Perf claims (A1's "before/after" in `docs/perf/README.md`).** Arithmetic + over already-measured numbers, not a separate measurement — reviewed there, + no finding. + +## Review + +**2026-08-28 — lead.** Accepted. Gates re-run independently of both agents: +`cargo fmt --check` clean, `cargo clippy --all-targets --workspace -D +warnings` silent, `cargo test --workspace` green. + +The shape is right. Deferring analysis while applying text immediately is the +standard split, and flushing before every request and before every +non-`didChange` notification means no handler ever reads a stale buffer — +today's correctness guarantee is preserved exactly, and only keystroke-storm +reparses are coalesced. The quiet-period timer in `run()` matters as much as +the coalescing: diagnostics are the one answer a client never asks for, so a +burst that ends in silence still gets drawn. + +QA's CD-1 was a real finding and correctly diagnosed: the universal flush ran +*before* the `didClose` arm, so the arm's `retain` was dead and a buffer +closed mid-burst paid a full `Document::new` and published diagnostics for a +file the user had stopped looking at, only to clear them a line later. The +fix drops the pending text ahead of the flush rather than special-casing the +flush, which keeps "every other dirty buffer still flushes" true by +construction. The dev verified the pinning test fails on pre-fix code before +keeping it; that is the right standard. + +The one honest cost is recorded in `docs/perf/README.md` and is not hidden: a +keystroke with *nothing* following it now publishes at 164 ms rather than one +flush, because it waits out the 150 ms quiet period. Any request flushes +early, so a real editor sees 4.35 ms / 37.6 ms instead — but the regression +is real for a client that asks for nothing, and the number is written down +rather than argued away. + diff --git a/docs/features/hover-declarations/README.md b/docs/features/hover-declarations/README.md index 31255d9..c8b57c1 100644 --- a/docs/features/hover-declarations/README.md +++ b/docs/features/hover-declarations/README.md @@ -59,6 +59,11 @@ entirely whenever it could be the wrong line. is the only thing that colours a hover card. - Nothing is added to `Def`, to the facts file, or to `FACTS_FORMAT`; a cache written before this round is still current after it. + **Superseded 2026-08-28 by `docs/features/port-detail-spans/README.md`**, + which adds `Def::detail_span`, writes it in every declaration record and + bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is + discarded. This round's own promise held while it was this round's to + make; the index is text-free either way (a span is not text). - The heading line `**label** — declared in `file:line`` is unchanged, so a client (or a test) reading only that half sees exactly what it saw before. @@ -119,6 +124,13 @@ The character cap counts `char`s and cuts on a boundary. - Not done, deliberately: no facts/cache change, nothing in `vlog_semantic`, no TODO.md edit (no existing checklist item covers this; §8's hover items are all already checked, and inventing one is out of scope). +- [x] **2026-08-28**: one disk read per file per hover (`disk_view` memo); + QA finding 4 closed. +- [x] **2026-08-28**: `live_symbol` (and `nav::indexed_references`) look a + name up instead of scanning every symbol, with the first-match + tie-break pinned by test. +- [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior + `\r` into the fence; QA finding 2 closed. ## Work log @@ -164,6 +176,77 @@ The character cap counts `char`s and cuts on a boundary. | `a_declaration_spanning_many_lines_is_cut_at_the_line_limit` | the line cap, via an open module whose `decl_span` is its body | | `two_files_declaring_one_name_each_get_their_own_snippet` | ambiguous name: both headings, both snippets | +### 2026-08-28 — dev (performance: one disk read, one name lookup) + +Parts A2 and A3 of the "Improve LSP performance + hover accuracy" round. +Behavior of every card is unchanged; both items are the same answer, reached +with less work. Numbers in `docs/perf/README.md`. + +- **A2 — one read per file per hover.** A hover into a *closed* file used to + read that file and build a `LineIndex` over it twice: once in + `locate::line_number` for the `file:line` heading, once in + `declaration_snippet` for the fenced lines. This is QA's finding 4 below, + and it is now closed. `symbol_hover` holds a per-request memo — one + `(path, text, LineIndex)` in `disk_view` — that the heading and the snippet + both read, and `declaration_snippet` no longer touches the disk at all: it + is now the *open-buffer* path only, with the closed-file path inlined in + `symbol_hover` beside the heading it shares a read with. The + `spells_exactly` guard applies on both paths exactly as before. A card + naming one file twice (two declarations in one file) now pays for one read, + not two, which is why the memo is keyed by path rather than being a single + `Option` per candidate. + - Measured: 34 ms → 16.3 ms on QA's own 31.7 MB measurement, and 141 µs of + a 148 µs hover at 10 000 lines is that one read. See `docs/perf`. + - QA's measurement test was renamed + `hovering_into_a_large_closed_file_reads_it_twice` → + `..._reads_it_once`, since the doubling it was named for is gone. The QA + log below still names the old spelling; that section is QA's to amend. +- **A3 — `live_symbol` stops scanning every symbol.** Walking the whole + buffer's symbol table and calling `nav::indexed_def_for_symbol` (two index + lookups) on every symbol whose name happened to match — and reaching every + symbol whose name did not — became a name-keyed lookup: + `vlog_semantic::Semantics::symbols_named(name)`, two binary searches over a + side table of symbol ids sorted by name, built once during `analyze`. Only + same-named declarations are probed. A side table rather than a + `HashMap>` so that `Semantics` — which is cloned per + document — does not carry a second copy of every name it already holds; + four bytes per symbol against a `String` per symbol. + - **The tie-break is preserved.** The map's lists are built by walking the + symbols in order, so `symbols_named` yields declaration order — the same + order, and the same first match, the old `symbols().iter().find(..)` + made. Pinned by `looking_a_name_up_answers_exactly_what_scanning_every_symbol_would` + in `crates/vlog_semantic/tests/semantics.rs`, which compares the two + answers directly and asserts the earlier declaration comes first. QA's + `duplicate_live_declarations_of_one_name_pick_the_first_one_silently` + (finding 3 below) still passes, unchanged. + - `nav.rs`'s `indexed_references` had the same scan-by-name for the + declaration's live span; it is the same swap and was made in the same + change, for the same reason. + - `vlog_refactor::ports.rs:1154` has a third one (`symbols().iter() + .position(|s| s.name == port && …)`). It is not a trivial swap — the + predicate carries a kind and a span test and the code wants the + *position* as a `SymbolId` — and it is in another crate, so it is left + alone and recorded here rather than done. + - Cost: four bytes per symbol. Measured saving on the lookup alone: + 8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`). + +### 2026-08-28 — dev (CRLF, closing QA finding 2) + +- Finding 2 below — a CRLF file's multi-line snippet keeping an interior + `\r` inside the fence — is **fixed**, as part of `port-detail-spans`' PDS-4. + Every line a card shows now goes through `attached_lines`, which strips a + trailing `\r` as it composes each line; that covers both this feature's + snippet path and `local_text`'s in-file path, which QA named as having the + same property, because both reach it through `fenced_sections`. Display + text only: no buffer is written. +- QA's pinned regression test was named for the old behaviour + (`a_crlf_multiline_snippet_keeps_interior_carriage_returns`) and asserted + it; it is now `a_crlf_multiline_snippet_carries_no_carriage_returns` and + asserts the opposite, plus that the lines read as written. The QA log below + still names the old spelling; that section is QA's to amend. +- No other change to this feature. `spells_exactly`, the caps and the + disk/live split are untouched. + ## QA log ### 2026-08-27 — QA @@ -277,6 +360,12 @@ charter's "note it, don't redesign" rather than attempted. `hovering_into_a_large_closed_file_reads_it_twice`, `hover.rs:1325`. Run with `cargo test --release -p lucisv_server large_closed -- --ignored --nocapture`. + - **Amended 2026-08-28 — QA.** Closed by A2 (`docs/perf/README.md`): + `symbol_hover`'s `disk_view` memo now shares one read + one `LineIndex` + between the heading and the snippet. Re-ran the same measurement (now + named `..._reads_it_once`): **17.0 ms**, against the documented + "34 ms → 16.3 ms" — matches within the run-to-run noise `docs/perf/ + README.md` itself calls out. No longer an open finding. **Verified, no finding** (angles from the charter that turned up nothing): UTF-8 multi-byte content before a declaration, on the same file, does not diff --git a/docs/features/incremental-sync/README.md b/docs/features/incremental-sync/README.md index a83cd38..138bc96 100644 --- a/docs/features/incremental-sync/README.md +++ b/docs/features/incremental-sync/README.md @@ -75,6 +75,15 @@ slice that can panic. and no bump would let a changed buffer answer "unchanged". One notification = one reparse = one stamp = one `publish`. Pinned by `one_notification_is_one_generation_bump_however_many_ranges`. + **Amended 2026-08-28 by `docs/features/change-debounce/README.md`**: a + `didChange` now records the composed text as dirty and the analysis runs at + the next flush, so the promise reads **one *flush* is one `set_document`, + one generation bump and one publish per dirty buffer** — however many + ranges *and however many notifications* it coalesced. What the promise + protects is unchanged: the counter never moves twice for work done once and + never fails to move for a buffer whose text changed. The test above still + passes as written; its helper flushes after each notification, which is the + quiet-period timer firing. - **Changes what the client is told at `initialize`.** `text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true, change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and diff --git a/docs/features/interactive-latency/README.md b/docs/features/interactive-latency/README.md new file mode 100644 index 0000000..7171e6f --- /dev/null +++ b/docs/features/interactive-latency/README.md @@ -0,0 +1,440 @@ +# interactive-latency + +## Goal + +Make the request and notification paths a user *feels* — the ones that run +while they type and move the cursor — cost what they have to cost and no +more, and say with measured numbers where the rest of the time goes. Round 1 +(`docs/perf/README.md`) established the baseline and named the open question +it could not answer from inside the crate: what a `didChange` → +`publishDiagnostics` round trip actually takes over the wire. This round +answers that, breaks one flush down stage by stage, and takes the +identity-safe wins the breakdown justifies — which turned out to be six token +lookups that were sweeping the whole buffer for something a binary search +answers in twenty nanoseconds. Nothing on the parse path was touched: the +measurements say the remaining cost is lexing and parsing, and that is a +change this round deliberately does not make. + +## Assumptions + +- **The token stream rises and never overlaps.** Every binary search added + here rests on one property of `Document.tokens`: the lexer emits tokens in + source order, so `end[i] <= start[i+1] <= end[i+1]` and both + `span.start < offset` and `span.end < offset` are monotone predicates over + the vector. That is the whole precondition `partition_point` needs, and it + is pinned by `state::tests::the_token_stream_rises_and_never_overlaps` — + the test that would fail first if the lexer ever changed shape. Nothing + here assumes tokens are non-empty: the `Eof` sentinel is zero-width, and + every argument below survives it. +- **No benchmark dependency**, unchanged from round 1: `std::time::Instant`, + `#[ignore]`d tests, no `criterion`. `CLAUDE.md` requires a written + justification for a new dependency and there is none to write. +- **A measurement asserts nothing about duration.** A test that fails when + the machine is busy is a test that gets deleted. +- **The e2e round trip is a real session.** It spawns the shipped binary and + speaks framed JSON-RPC at it, so the number includes the pipes, the JSON, + the debounce timer and the flush. It cannot be taken from inside the crate, + which is exactly why round 1 could not take it. +- **The generated module is uniform, and real RTL is not.** Both generators + build the same repeated four-line block. The numbers are a scale, not a + prediction for any given file. + +## Handshakes + +- **`vlog_parser` → this crate (consumed, unchanged).** The binary searches + consume the ordering property of `tokenize`'s output described above. + Nothing was asked of `vlog_parser` and nothing in it changed. If it ever + emits tokens out of order, the pinning test in `state.rs` fails before any + handler answers wrongly. +- **`state.rs` → `selection.rs`, `on_type.rs`, `completion.rs` (new, + internal).** Two free functions, `first_token_reaching` and + `first_token_from`, are published from `state.rs` beside `Document`. They + are the single place the monotonicity argument is written down; every call + site is one comparison on top of one of them. `inline.rs` uses a third + predicate (`span.end <= offset`) written at its own call site, because it + has one user and its own local proof. +- **`e2e.rs`'s `Live::finish` now returns the publish count** it saw on the + way out. Existing callers ignore the value, which compiles unchanged. The + count is what turns "the debounce coalesces a burst" from arithmetic into a + measurement. +- **Two copies of one generator.** `perf::generated_module` and the copy in + `tests/e2e.rs` must stay the same shape, or the in-crate table and the + over-the-wire table in `docs/perf/README.md` stop being readable against + one another. `lucisv_server` is a binary crate, so an integration test + cannot import the original; the copy is commented as such at both ends. +- **Nothing was asked of `vlog_linter`.** The lint pass costs 1.40 ms of a + 32 ms flush at 10 000 lines and walks the tree once per rule; that is + recorded in `docs/perf/README.md` as a future round's work, not requested + here. + +## Status / TODO + +- [x] Phase 1 — a stage-by-stage breakdown of one flush at 1k and 10k lines: + `tokenize`, `tokens.clone()`, `parse_tolerant`, `collect_defines`, + `analyze`, `resolve_external`, `LineIndex::new`, and the + `diagnostics::all` pass a publish runs (which is *not* inside + `Document::new`, and which round 1's table did not account for). + `perf::breaking_down_one_flushed_keystroke`. +- [x] Phase 1 — the end-to-end round trip round 1 listed as its own open + TODO: `didChange` → `publishDiagnostics` against the real binary, for a + single change, for a burst of ten, and for the change-then-request + shape a real editor produces. + `tests/e2e.rs::a_keystroke_round_trip_over_the_wire`. +- [x] Phase 2 — six token lookups swapped from a sweep to a binary search, + each with a test that walks **every byte** of a buffer written to have + plenty of touching tokens and asserts the search returns exactly what + the sweep returned. +- [x] Phase 2 — the three sweeps that are inherent left alone, with the + reason written down (below). +- [x] Phase 3 — decided against every change the breakdown did not justify, + with the number for each (below). +- [x] Phase 4 — `docs/perf/README.md` refreshed: both of round 1's open + TODOs resolved or restated, every figure re-measured on this machine. + +Not done, deliberately, and each with the number that would justify it — the +list lives in `docs/perf/README.md`'s *What it would take to go faster* so it +sits beside the measurements rather than in a feature's checklist. + +## The Phase 2 call sites, one by one + +The predicate each site wants is *not* always "the token containing this +offset", so `Document::token_at` is not a drop-in for any of them. Each swap +below is argued from the ordering property, and each argument is pinned by a +test that compares the new expression against the old one at every byte of +`state::mixed_buffer(20)` — a buffer written with `a=b;`-style adjacent +punctuation, comments and strings precisely because the bytes that could tell +a search from a sweep are the ones two tokens share. + +**Changed and proven.** + +| site | wanted | now | test | +|---|---|---|---| +| `selection.rs` `enclosing` | the first token with `start <= offset <= end` | `first_token_reaching`, then one `covers` check | `selection::tests::the_innermost_step_is_the_token_the_sweep_returned_at_every_offset` | +| `on_type.rs` `statement_edit` | the token with `end == offset` | `first_token_reaching`, then one `==` | `on_type::tests::the_token_ending_at_the_cursor_is_the_one_the_sweep_returned` | +| `on_type.rs` `first_on_line` | the first non-`Eof` token with `start >= content` | `first_token_from`, then `find` over the tail | `on_type::tests::the_first_token_on_a_line_is_the_one_the_sweep_returned` | +| `completion.rs` `is_procedural` | the *index* of the token with `start == offset` | `first_token_from`, then one `==` | `completion::tests::the_scope_gates_answer_what_their_sweeps_answered` | +| `completion.rs` `balanced` | every token whose start is in `[from, at)` | a slice between two `first_token_from`s | the same test | +| `inline.rs` `triggered` | the **last** non-`Eof` token with `end <= offset` | `partition_point`, then `rposition` over the prefix | `inline::tests::the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found` | + +Two of these deserve their reasoning spelled out, because they are the two +where a careless swap would have changed an answer: + +- **`selection.rs` takes `span.end` inclusively.** At a byte two adjacent + tokens share, `find(covers)` returned the *earlier* of the two, while + `Document::token_at` — which uses `TextRange::contains`, end exclusive — + would return the later one. `first_token_reaching` returns the earlier one, + which is why it is the right primitive here and `token_at` is not. +- **`completion.rs`'s `balanced` was sweeping the whole buffer.** Its filter + had no upper bound to break on, so a cursor anywhere in a 10 000-line file + walked all 94 961 tokens to reach a window a few dozen tokens wide. It is + the largest of the six by some way: 130 µs → 36 ns. + +**Left alone, with the reason.** + +- **`signature.rs` `enclosing_list` (:138) and `active_entry` (:231).** + Inherent. Both maintain a parenthesis-depth stack, and a depth at the + cursor is a function of *every* bracket before it — there is no prefix a + binary search may skip without recomputing what it skipped. Both already + break at the cursor rather than running to the end of the buffer, so + neither is a whole-buffer sweep; bounding the loop with a binary search + instead of the `break` would save one comparison per token and change + nothing else, which is not worth the edit. +- **`pairs.rs` `analyze` (:230).** Inherent, and not a position query at + all: it matches *every* scope keyword in the stream and returns the whole + pair set. There is no offset to search for. +- **`completion.rs` `in_comment_or_string` (:553).** Left, and its existing + doc comment already says why: comments are lexer trivia hanging off + whichever token happens to follow or precede them, so the token whose + `leading` holds a comment at a given byte is not the token a search for + that byte would find. A correct search would have to reason about + attachment; a wrong one would offer a completion list inside a comment. + This is the one remaining per-keystroke whole-buffer walk, and it is + recorded as such in `docs/perf/README.md` rather than guessed at. +- **`completion.rs` `word_tier` (:355), `candidates.rs` (:218), + `folding.rs` (:58).** Inherent: each needs every token in the file, not a + token at an offset. + +## Work log + +**2026-08-28 — dev (round 2).** + +*Phase 1, measured first.* Added +`perf::breaking_down_one_flushed_keystroke` and +`perf::finding_one_token_against_sweeping_the_stream` to the existing +`perf.rs` module, and `a_keystroke_round_trip_over_the_wire` to `e2e.rs`. +The e2e measurement reuses the `Live` session helper that already existed in +that file for the watched-files test rather than adding a second one; the +only change to shared code is that `Live::finish` now returns the number of +`publishDiagnostics` it saw while shutting down. That count is the point: a +buffer left dirty by a burst is flushed before the next *request* is +answered, so by the time `shutdown` comes back every publish the burst was +going to produce has arrived. A burst of ten keystrokes produces **one**. + +The breakdown decided everything that followed. At 10 000 lines a flush is +31 ms, and 24.5 ms of it is `tokenize` plus `parse_tolerant`. `analyze` is +11 %, the diagnostics pass another 4 % on top of the flush, and +`resolve_external` — which the round's brief named as a possible target — is +**49 µs, one part in six hundred**. There is nothing to skip there. + +*Phase 2.* Six sweeps became binary searches, on the strength of the +`finding_one_token` measurement: 77 µs → 20 ns for a cursor lookup at 10 000 +lines, and 130 µs → 36 ns for `balanced`'s window. The two primitives live in +`state.rs` beside `Document::token_at`, which is where the one-paragraph +monotonicity argument they all rest on is written; `inline.rs`'s third +predicate is written at its own call site because it has one user. + +Every swap is pinned by a test that compares it against the code it replaced +at every byte of a shared awkward buffer (`state::mixed_buffer`, whose one +job is to have plenty of tokens that touch). Two of the six are *not* what +`Document::token_at` would have answered, and the table above says which and +why; a seventh candidate, `completion.rs`'s comment gate, was left alone +because no search of the token stream answers the question it asks. + +*Phase 3 — nothing, on purpose.* The breakdown does not justify a change: + +- Lex and parse are 79 % of a flush. Making them incremental is the only + lever left, and it is a large change under `CLAUDE.md`'s hard invariants 1 + and 2. Written up in `docs/perf/README.md` with the number that would pay + for it; not attempted. +- `tokens.clone()` is 2.40 ms, 7.7 % of a flush, and is **load-bearing**: + `parse_tolerant` takes its token vector by value and steals the comments + out of it (`std::mem::take(&mut self.tokens[pos].leading)`, + `self.tokens[pos].trailing.take()`), so `Document.tokens` cannot be the + same vector — folding, the on-type comment test and completion's comment + gate all read that trivia. The clone is also already a win: before the + one-lex change it was a second `tokenize`, which this round measures at + 12.5 ms. Removing it needs a cheaply-clonable `Token`, which is a + `vlog_parser` type change reaching the formatter. Written up, not + attempted. +- The lint pass walks the tree once per rule (`vlog_linter::lint`'s + `for rule in enabled`), but it is 1.40 ms against a 32 ms flush. Fusing the + walks is a `vlog_linter` refactor for 4 %. Written up, not attempted. +- `resolve_external` is 49 µs. Skipping it when the index generation has not + moved would save one part in six hundred of a flush and add a cache + invalidation rule to a path that currently has none. Not attempted, and + the number is the reason. + +*The finding worth acting on is not a code change.* Over the wire, a lone +keystroke's round trip is 156 ms at 1 000 lines — of which 150 ms is the +change debounce's own quiet period, and 4.8 ms is the work. The same +keystroke followed by a request, which is what a real editor sends, is +**4.8 ms at 1 000 lines and 37 ms at 10 000**. So for the editors that ask +for anything after a change (VS Code asks for semantic tokens, inlay hints +and highlights), the debounce timer never runs and the flush is the whole +cost; for a client that asks for nothing, the felt latency is the timer. +`CHANGE_DEBOUNCE` is a product decision the previous round made deliberately +at 150 ms, so it was not touched — but it is now a measured number rather +than an assumed one, and `docs/perf/README.md` says so. + +## QA log + +**2026-08-28 — QA.** Verdict: **SHIP WITH FIXES noted, none applied** — one +methodology finding on the e2e measurement (not shipped code a user can hit), +one informational note verified harmless. Everything else attacked and held. + +Gates, verbatim: + +- `cargo fmt --check` — clean, no output. +- `cargo clippy --all-targets --workspace -- -D warnings` — clean, no + warnings. +- `cargo test --workspace` — every crate green: lucisv_server's unit binary + 1192 passed / 21 ignored, its `e2e` integration binary 55 passed / 1 + ignored (the perf test, run separately below), every other crate green + too. No `FAILED`, no `error[`. +- `cargo test -p vlog_formatter` — 31 + 1 + 4 + 6 + 2 + 22 + 114 + 0 passed + across its binaries, 0 failed. +- `cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1` + — 12 passed. Numbers reproduced within the noise the README itself budgets + (see below). +- `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1` + — 1 passed: `1000 lines: one change alone 161.9ms, a burst of ten 160.4ms + for 1 publish(es), one change a request follows 4.7ms` / + `10000 lines: one change alone 205.7ms, a burst of ten 199.0ms for 1 + publish(es), one change a request follows 38.5ms` — matches + `docs/perf/README.md`'s 156/205/157/205/1/4.76/37.4 within reason. + +**Attack angle 1 (identity claims).** All six call sites re-derived from the +source and checked against their sweep predicates by hand (`selection.rs` +`enclosing`, `on_type.rs` `statement_edit` and `first_on_line`, +`completion.rs` `is_procedural` and `balanced`, `inline.rs` `triggered`). +Every one of the existing per-site tests already walks **every byte** of +`mixed_buffer(20)` (not just a handful of offsets), so the exhaustive-diff +form the brief asked for is already what shipped, not something to widen. +Checked by hand and confirmed safe at the edges the brief named: offset 0, +the last byte, the `Eof` sentinel, an empty file, a file that fails to lex +(empty `tokens`), and a large-file fast-path document — `on_type.rs`'s own +`OnTypeFormatting::METHOD` arm in `server.rs:832` answers the empty edit list +before `level_at`/`first_on_line` ever run on a large doc; `completion.rs`'s +`completions` guards `doc.tokens.is_empty()` at `completion.rs:154` before +`is_procedural`/`balanced` are reachable; `inline.rs`'s `inline_completions` +guards the same at `inline.rs:237`; `selection.rs`'s `enclosing` and the two +`first_token_*` primitives themselves degrade safely on an empty slice +(`partition_point` on `&[]` is `0`, `.get(0)` on an empty `Vec` is `None`). +`selection.rs`'s inclusive-`covers`/exclusive-`token_at` distinction is real +and correctly *not* used — traced through `first_token_reaching` + +`covers` by hand at a shared boundary byte and it does return the earlier of +two touching tokens, matching the sweep it replaced. + +**Attack angle 2 (the precondition).** `state::tests::the_token_stream_rises_and_never_overlaps` +exercises exactly one hand-written buffer +(`mixed_buffer(20)`), which is narrow on its own — no macros, no directives, +no unterminated constructs. Delegated to a sub-agent to read +`vlog_parser`'s lexer directly rather than trust the docstring's claim. +Finding: `vlog_parser`'s own `tests/spans.rs::assert_covers_source` already +asserts the same invariant (non-overlap, source order, full byte coverage, +comments included) over 40+ deliberately adversarial fixtures — macros, +`` `ifdef``/`` `include`` interleaving, attributes, CRLF, BOM, multi-byte +UTF-8 in strings and comments — and `tests/error_recovery.rs` fuzzes every +byte-prefix and every single-byte deletion of a corpus without panicking. +Every lexer error path (`skip_string`, `skip_block_comment`, the attribute +scanner) returns `Err` rather than a partial, possibly-violating `Vec`, +and `TextRange::new` clamps `end` to `max(start)` structurally. No plausible +gap found: the one narrow test in `state.rs` is sufficient because it rests +on an invariant `vlog_parser` proves far more thoroughly one layer down, and +the docs correctly point there rather than re-arguing it. + +**Attack angle 3 (the e2e measurement's methodology) — one finding.** + +- **IL-1 (medium) — the burst's "1 publish(es)" figure is not the robust, + order-independent count the code and the docs describe.** + `crates/lucisv_server/tests/e2e.rs:4696-4727`. `published` is computed as + `1 + live.finish()` (line 4727): the `1` is an unstated assumption that the + lone `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")` + right after the burst (line 4704) consumed *exactly* the burst's own + publish and nothing else, and `live.finish()`'s count only starts + accumulating after the "one change a request follows" loop ten lines later + (4714-4725) has already run — ten more iterations, each with its own + generic `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")` + (line 4722) that accepts *any* publish, not specifically the one its own + request just triggered. A stray or duplicate publish arriving from the + burst in that window would be silently absorbed by one of those ten waits + and never increment `published` or surface anywhere in the printed line. + The doc comment above the burst (line 4696-4699: "the count below is that + claim measured rather than reasoned about: any publish still to come + arrives before `shutdown` does") is true of `live.finish()`'s own drain — + nothing gets past *that* point unnoticed — but it is not true of the + window between the burst and the drain, which is exactly where a second + publish would have to be counted to falsify "exactly one". As written, the + test would print "1" whether the burst produced one publish or secretly + produced two, which is indistinguishable from the claim it's supposed to + be checking. In practice the debounce is understood to always coalesce to + one flush, so this is a soundness gap in the *measurement*, not evidence + of a real double-publish — but it means the "counted rather than reasoned + about" claim is itself partly reasoned about. Not fixed: closing it cleanly + means either running the burst as its own `Live` session finished + immediately after (so nothing else can absorb a stray), or having + `wait_for` tally every `publishDiagnostics` it ever passes over for the + life of the session — both are design choices for the dev, not a + QA drive-by edit. +- Everything else in this angle held. `Live::finish`'s drain (`e2e.rs:2231`) + really does read to `shutdown`'s response before returning, so nothing + published after the last explicit `wait_for` in a test is lost *at that + point* — it is specifically the mid-test absorption above that is the gap. + The 150 ms figure in the lone-keystroke row is the timer and not a stall: + reproduced at 161.9 ms / 205.7 ms against a documented 150 ms + `CHANGE_DEBOUNCE` plus a single flush (2.6 ms / 31.2 ms measured + separately), which accounts for the total without residue. + +**Attack angle 4 (duplication) — one informational note, verified harmless.** +`perf::generated_module` (`crates/lucisv_server/src/perf.rs:42-57`) and its +copy in `crates/lucisv_server/tests/e2e.rs:4634-4649` are not byte-identical: +the `e2e.rs` copy appends ` // typing\n` before `endmodule` that the +original does not have, so the test has a stable, comment-only line to land +keystrokes on. The doc comment on the copy ("The two must stay the same +shape, or the two tables ... stop being readable against one another") +slightly overstates it — they differ by one line. Verified harmless: a +comment is lexer trivia and is never its own token, so `tokens.len()` is +identical between the two generators at the same `lines`, and the added ~12 +bytes is noise against 29 KB / 309 KB files. The two perf tables do stay +readable against one another; no fix needed. + +**Attack angle 5 (perf honesty).** Every figure in `docs/perf/README.md`'s +round-2 tables reproduced within the noise the document itself budgets for, +on a fresh `--release` run (see gates above for the two exact commands and +their output). Spot check on "the breakdown sums to `Document::new`'s +31.1 ms" — a claim the brief asked about but which, checked directly, is +**not actually written anywhere in either README**; nowhere does the text +assert the eight-stage breakdown sums to the `Document::new` figure. As a +sanity check anyway: summing this run's own breakdown stages inside +`Document::new` (tokenize 12.512 + parse_tolerant-with-clone 14.149 + +collect_defines 0.115 + analyze 3.174 + resolve_external 0.012 + +`LineIndex::new` 0.105 ≈ 30.07 ms) against the dedicated `Document::new` +figure from the same run (31.22 ms) leaves about 1.15 ms — 3.7% — +unaccounted for, which is consistent with the README's own caveat that the +breakdown "runs eight measurements back to back on one heap" and should be +read as *shares*, not as a sum that has to close exactly. No finding, since +no stronger claim than that is actually made. + +**Attack angle 6 (regression sweep).** `cargo test --workspace` exercises +every one of the four handlers' existing suites unchanged and green +(selection.rs, on_type.rs, completion.rs, inline.rs — see gates above). +Adversarial shapes the brief named are already covered by name in the +existing suites and were spot-read to confirm they exercise the *changed* +code paths and not just the surrounding handler: `on_type.rs` +`a_semicolon_the_lexer_never_saw_ends_no_statement`, +`a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`, +`a_crlf_line_ending_is_never_touched_by_the_edit`; `completion.rs` +`a_buffer_that_does_not_lex_is_declined`; `inline.rs` +`a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at`, +`a_trigger_at_the_true_end_of_file_still_offers_a_ghost`, +`crlf_line_endings_still_trigger`; `selection.rs` +`a_file_that_does_not_lex_still_answers_the_file_range`, +`an_empty_file_still_answers_one_degenerate_chain`. + +**PDS-1..4 and CD-1, spot-checked in code rather than trusted from the +README.** `hover.rs:361` (`only_a_closer_on`) and `:373` (`is_closer_word`) +exist and `another_port_on`/`is_port_grammar_word` are gone — PDS-1 real. +`hover.rs:292-295` strips a trailing `\r` in the one line reader all three +`attached_lines` collections pass through — PDS-4 real. `server.rs:1247-1262` +(`notification`): the `dirty.retain` for `DidCloseTextDocument::METHOD` sits +*above* the `if method != DidChangeTextDocument::METHOD { self.flush_dirty() }` +call, guarded on the method name via a borrowed, cloned `closing_uri` +(`server.rs:2214`, reads `params` without consuming the notification) — CD-1 +genuinely closed, not dead code any more. PDS-2/PDS-3 not independently +re-derived (no code-shape claim to check beyond what PDS-1/PDS-4 already +verify the same file's discipline on); taken on the strength of the named +tests, which are present and green. + +## Review + +**2026-08-28 — lead.** Accepted, with one methodology fix applied by me +(below). Gates re-run independently: fmt clean, clippy silent, workspace +tests green, formatter snapshot + idempotency suite green, the twelve `perf::` +measurements and the wire measurement both reproduce. + +This round did the thing that makes a performance round worth anything: it +measured first and then declined to optimise three of the four things it had +been pointed at, with a number for each refusal. `resolve_external` at 49 µs +of a 31 ms flush disproved the brief's own hypothesis, and saying so is a +better outcome than a speculative cache on a path that has no invalidation +rule today. Lex and parse at 79 % is the real answer, and leaving incremental +parsing to a planned round rather than starting it opportunistically is +right — that work lands directly on hard invariants 1 and 2 and is not +something to attempt as the tail of a perf sweep. + +The Phase 2 swaps are the part I looked at hardest, because six "obviously +identical" rewrites is exactly where a silent behaviour change hides. The +dev found the one that was *not* identical: `selection.rs`'s `covers` treats +`span.end` inclusively, so at a byte two tokens share, the sweep returned the +earlier token and `Document::token_at` would have returned the later one. +Building `first_token_reaching` instead of reaching for the existing helper +is the correct instinct, and differential-testing each new expression against +the predicate it replaced at every byte of a purpose-built buffer is the +right proof. Three call sites were left alone with reasons — signature help's +paren depth is inherently a prefix scan, `pairs.rs` is not a position query, +and completion's comment gate cannot be answered by any search of the token +stream because comments are trivia. Recording the last of those as the +remaining per-keystroke whole-buffer walk is more useful than a forced fix. + +**Fix applied at review.** QA's IL-1 was right and I closed it directly +rather than spending another round: the burst-of-ten publish count was +`1 + finish()`, but the ten-iteration request loop sat between the burst and +the drain, and each of its `wait_for`s accepts *any* publish — so a second +publish the burst had produced would have been absorbed there and the figure +would still have read "1". The burst now runs last, immediately before the +drain, with the keystroke versions renumbered to stay monotonic. Re-measured +after the change: still exactly one publish at both sizes, and the row is now +counted rather than assumed. IL-2's overstated doc comment is corrected in +place — the two `generated_module` copies differ by one trivia line, which is +not a token and does not move a number. + diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 79d92c5..a368d75 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -21,15 +21,15 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/rangesFormatting` | `vlog_formatter::format_range` | LSP 3.18's multi-range form of the line above, and literally its `n`-range case: the ranges become one sorted, merged `LineRanges` and one engine call, so the all-or-nothing contract is over the union rather than per range. `range_formatting` is now defined as the one-element call of it, and the reply, the refusal and the config warning are the same values. Advertised by widening `documentRangeFormattingProvider` from `true` to `{ "rangesSupport": true }` — **only for a client that sent `textDocument.rangeFormatting.rangesSupport`**, so a 3.17 client sees exactly what it always saw; the handler itself is unconditional. `lsp-types` 0.97 spells neither half, so both go through JSON. See `docs/features/lsp-318-extras/README.md` | | `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` | | `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` | -| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` | -| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` | +| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didSave` once per notification, and for a `didChange` once per **flush** (a typing burst publishes once, not once per keystroke — `docs/features/change-debounce/README.md`) — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` | +| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, and the composed text is held **dirty** — one `set_document` + one `publish` per *flush*, which is the next request, the next other notification, or a 150 ms quiet period. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` and `docs/features/change-debounce/README.md` | | `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README | | `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` | | `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` | | `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built | | `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README | -| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md` | -| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` | +| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md` | +| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` | | `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` | | `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` | | `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README | @@ -233,17 +233,19 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`. | layer | rebuilt when | cost | |---|---|---| -| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute | +| a document's `Semantics` + tokens + diagnostics | every `didOpen`, and every **flush** of the buffers a `didChange` left dirty — once per flush, however many ranges *and* however many notifications it coalesced (`docs/features/change-debounce/README.md`) | one file, full recompute — 2.6 ms at 1 000 lines, 31 ms at 10 000 (`docs/perf/README.md`) | | the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope — **except when the trigger names exactly one file the index already holds** (a `didSave`, a one-file watcher event), where only that file's contribution is replaced and the result is provably the index a full re-scan would have given (`docs/features/incremental-index/README.md`) | | the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save | | the **index cache** on disk | appended to as a whole rescan parses each file, rewritten when that rescan ends, and written through by every incremental one-file update | one `write` per parsed file. It is read at the start of every whole rescan and answers for every file whose content it already holds, which is what makes a reopened workspace cost the reads and not the parses (`docs/features/index-persistence/README.md`) | -**Per-file recompute on every keystroke** is the strategy TODO.md §6 states -("per-file recompute is fine at Verilog file sizes"); salsa is explicitly -deferred there. Incremental *sync* did not change that: the wire now carries -ranges, but a `didChange` still throws the whole `Document` away and builds a -new one — one reparse per notification, which is also the one generation bump -the pull-diagnostics `resultId` depends on. +**Per-file recompute** is the strategy TODO.md §6 states ("per-file recompute +is fine at Verilog file sizes"); salsa is explicitly deferred there. +Incremental *sync* did not change that: the wire carries ranges, but a flush +still throws the whole `Document` away and builds a new one. What changed on +2026-08-28 is *how often*: a `didChange` no longer triggers that recompute +itself, so a typing burst costs one reparse and one generation bump — still +exactly one of each per flush, which is what the pull-diagnostics `resultId` +depends on (`docs/features/change-debounce/README.md`). **Which files exist: the folder scope, since 2026-08-27** (index-scope). The index no longer walks the whole workspace by default. The ladder, highest diff --git a/docs/features/port-detail-spans/README.md b/docs/features/port-detail-spans/README.md new file mode 100644 index 0000000..0b82540 --- /dev/null +++ b/docs/features/port-detail-spans/README.md @@ -0,0 +1,448 @@ +# port-detail-spans + +## Goal + +A non-ANSI port is declared in two places: the header names it (`data_in,`) +and a body declaration finishes it (`input signed [31:0] data_in;`). Every +fact a reader wants — direction, signedness, width — is in the second place, +and until this round hover and go-to-definition both pointed only at the +first, so hovering a port of an older-style module showed a bare name and a +comma. `vlog_semantic` now records, on the header symbol, the span of the body +declaration that completes it (`Symbol::detail_span`); the server shows both +in one hover card and offers both as definition locations, detail first. The +same field travels through the workspace index and its on-disk facts, so a +*cross-file* hover into a closed file gets the same two sections. Attached to +that, because a card that shows a declaration should show what the author +wrote about it: each section carries the comment that documents it. + +## Assumptions + +- **One name, one symbol, per scope.** `bind::declare` already turns a second + declaration of a name into a *reference* to the first, which is exactly how + a non-ANSI body declaration attaches to its header port. `detail_span` rides + on that existing mechanism; nothing new decides what "the same port" means. +- **First writer wins.** If a header somehow names a port twice, the first + body declaration to arrive records its span and later ones are ignored. The + result is deterministic, which is what matters here; a duplicated port is + the linter's complaint to make, not hover's. +- **`detail_span` is `None` for everything else.** An ANSI port, a wire, a + module — anything complete where it is named — has no detail site, and both + consumers render exactly the card they always did. +- **A real span is never empty**, so `(0, 0)` is free to mean `None` in the + facts codec. `bind_port_decl` only ever records a declaration's own span. +- **Comment attachment is textual, and errs towards attaching nothing.** The + disk path of a cross-file hover has no parse to ask, so the attachment rules + work on lines. Only `//` lines and single-line `/* … */` count as + comment-only; the interior of a multi-line block comment is + indistinguishable from code without lexing, and a hover card that guessed + would be the wrong-line lie the snippet guards exist to prevent. +- **A comment below a declaration belongs to the *next* declaration unless + nothing else could claim it.** `only_a_closer_on` answers that with a + whitelist, not a blacklist: the block attaches only when every word on the + line after it is a block terminator (`end`, `endmodule`, `endinterface`, + `endtask`, `endfunction`) — which includes a line with no words at all + (`);`, a blank line, punctuation) — or when there is no line after it at + all. Everything else, a bare `input` on the first line of a *wrapped* + declaration included, reads as another declaration. The bias is the whole + point: a false "another declaration is here" only ever declines to attach a + comment, the direction that cannot lie, while a false "nothing here" shows + one declaration's comment on another's card. (QA, PDS-1: the previous + keyword-blacklist form got that backwards and did lie.) +- **The three comment sources are independent**, as the owner's rule states + them: a declaration takes the comment on its own line *and* the block above + it *and* the block below it, each guarded on its own. Order is source + order. (QA, PDS-2: the first implementation ran them as a priority chain + and dropped a below-comment nothing else claimed.) +- **Comment attachment renders, it never rewrites.** A CRLF file's line ends + before its `\n` but after its `\r`, so `attached_lines` strips that `\r` as + it composes each line — display text only; no buffer is touched (QA, + PDS-4). + +## Handshakes + +- **`vlog_semantic::Symbol` gains a field** — `detail_span: + Option`. Additive, like `refactor-rename`'s `Target::Declaration` + before it (§2.6 of `topo.md`): every existing reader of `Symbol` compiles + and behaves identically, and the two struct literals that build a `Symbol` + (`bind.rs`) set it. `bind_port_decl` is where it is written. +- **`vlog_semantic::Def` gains the same field**, carried by the index's + internal `Decl`. `Def` is what `lucisv_server` navigates by, so this is the + wire that makes a *cross-file* hover show the body declaration. `Def` + derives `PartialEq`; two `Def`s that differ only in `detail_span` cannot + arise, because both come from the same `Decl`. +- **`facts.rs`'s on-disk format changes** — every declaration record now + carries two more numbers, written unconditionally (`0 0` for the `None` + that every ordinary declaration has) so the stream stays flat and the + reader stays a straight sequence of `num()`s. **`FACTS_FORMAT` is bumped + (2 → 3)**, so a store written by an earlier build is discarded whole: + `index_cache.rs`'s header line carries the number, and a header that is not + this build's means the file is not read at all. Without the bump an old + record would be *reinterpreted* — every field after a declaration's name + span shifted by two — rather than dropped, and only the reader's `done()` + check would stand between a shifted parse and a wrong answer. Dropping the + store costs one rescan, once, which is what the persistent index is for + (`docs/features/index-persistence/README.md`); it is the + `vlog_semantic/src/workspace.rs` choke-point rule in `topo.md` §3.3. +- **`nav.rs` and `hover.rs` agree, by construction.** Hover shows two + sections — header, then detail — and `nav::definition` returns two + locations in the same order, detail first, so "jump" lands where the card's + second block is and the card's first block is the second location. Both + read `symbol.detail_span`; there is no second rule for what a port's + declaration is. An empty detail span is filtered out in `nav.rs` rather + than trusted. +- **Consumes `hover-declarations`' guards unchanged.** `spells_exactly` still + gates every snippet read out of a file the index may be stale against; + `fenced_sections` is applied *after* that guard on the disk path, and after + `live_symbol` on the live path. + +## Status / TODO + +- [x] `Symbol::detail_span`, written by `bind_port_decl`, first writer wins — + for a module's non-ANSI port and for an old-style task/function + argument, which merge through the same `bind::declare`. +- [x] `Def::detail_span` + the index's `Decl` carrying it. +- [x] `facts.rs` codec: unconditional pair, `(0,0)` = `None`, `FACTS_FORMAT` + bumped so a stale store is not read as a fresh one. +- [x] `hover::fenced_sections` — one section, or header + detail. +- [x] `nav::definition` returns the detail location first. +- [x] Comment attachment (`attached_lines`): same-line, above and below, each + guarded on its own, all three at once where all three are written. +- [x] Tests: `vlog_semantic` records the span for a split port and not for an + ANSI one; hover shows two sections from either end of the port; + comments attach above, below, and are not stolen from the next port; + a cross-file split port shows both sections from the index. +- [x] **2026-08-28**: the below-comment guard is a closer whitelist, so a + *wrapped* next declaration keeps its own leading comment (QA, PDS-1). +- [x] **2026-08-28**: above / beside / below are independent (QA, PDS-2). +- [x] **2026-08-28**: an old-style task or function argument gets a + `detail_span` too (QA, PDS-3). +- [x] **2026-08-28**: a CRLF file's snippet carries no `\r` into the fence + (QA, PDS-4). +- [ ] Not done: `detail_span` for anything other than a port or a + task/function argument. An `extern` + method prototype and its out-of-body definition are the same + two-places-one-symbol shape and would fit the field exactly, but no + hover complaint has been filed about them and speculative generality is + what `CLAUDE.md` says not to build. +- [ ] Not done: a *doc-comment* model. The attachment above is positional and + deliberately dumb — no `///` convention, no markdown rendering of the + comment body, no stripping of `//`. That is a feature of its own if it + is ever wanted. + +## Work log + +**2026-08-28 — dev.** Implemented as part of the LSP performance round +(plan: "Improve LSP performance + hover accuracy", part B), continued by a +second dev after the first stopped mid-round; the code below is the first +dev's except where noted. + +- `bind_port_decl` looks the declarator's name up in the scope it is binding + into *before* `bind_declarators` runs, because `declare` will turn the name + into a reference and there would be no symbol id to write on afterwards. + The lookup is the scope's own `names` map — the same map `declare` consults + — so "the same port" is decided in exactly one place. +- The codec writes the pair unconditionally rather than with a presence flag. + A flag would have kept old records readable at the cost of a branch in the + hot reader and a second thing to get wrong; dropping a stale record costs + one reparse of that file, once. +- Comment attachment was not in the plan. It is here because the first card + the two-section change produced looked wrong without it: a port's comment + sits on the line above or beside it, and showing the declaration without it + loses the only prose the author wrote. The rules are the narrowest ones + that never steal another declaration's comment, and each has a test. +- **Second dev, 2026-08-28**: **bumped `FACTS_FORMAT` 2 → 3**, which the + first dev's change owed and did not take. Its comment argued that a + pre-field record is "one field short, fails `done()`, and is dropped" — + true for the last declaration in a record, but a record with a declaration + followed by anything else is not short, it is *shifted*, and relying on a + trailing-length check to catch a field-order change is exactly what the + format number exists to make unnecessary. The workspace `VERSION` is also + in the store's header, but it has not moved this round, so without the bump + a store written by the released 0.12.1 would have been read by the new + codec. Otherwise no behavioral change: this README is the documentation the + round owed, and `cargo fmt` was run over `hover.rs`. + +**2026-08-28 — dev (QA fixes, third dev).** Every finding in the QA log below +is addressed; each is marked fixed or left, with the reason. + +- **PDS-1 — fixed.** `another_port_on`/`is_port_grammar_word` are gone, + replaced by `only_a_closer_on`/`is_closer_word` (`hover.rs`). The old + predicate asked "does this line carry an identifier the port grammar cannot + account for?", which is a blacklist: a line that is *only* keywords — the + first line of a wrapped `input\n [7:0] result;` — answered "no other + port here" and handed `result`'s comment to `data_in`. The new one asks the + question the other way round: every word on the line must be a block + terminator, so a line with any word the whitelist does not name (a bare + `input` included) reads as another declaration and the comment stays put. + A line with no words at all — `);`, blank, punctuation — passes, which is + what a last port's trailing comment is really followed by, and so does the + end of the file, where there is no line left to claim anything. The doc + comment now states that bias and why only that direction is safe. + - `name` fell out of the predicate, and with it out of `attached_lines` and + `fenced_sections` — the guard no longer needs to know which port it is + guarding, only whether anything follows the comment. Three call sites + simplified; no behaviour rides on the removal. + - Pinned: `a_wrapped_next_declaration_keeps_its_own_leading_comment` (the + QA repro verbatim, plus the assertion that the comment does reach + `result`'s own card) and `a_wrapped_declaration_keeps_the_comment_below_it` + (the same wrapped shape as the *last* declaration still takes it). The + existing `a_comments_below_a_declaration_attach_only_when_no_port_follows_them` + — comment block above `endmodule` — still passes unchanged. +- **PDS-2 — fixed.** `attached_lines` no longer runs a priority chain: the + above walk, the declaration's own lines (which carry the same-line comment + inherently) and the below walk are three independent collections joined in + source order. `has_comment_after` was the chain's only reader and is + deleted. Each guard is exactly as strict as before — the above walk still + stops at the first line that is not comment-only, and the below guard got + *stricter* with PDS-1 — so nothing new can be stolen; what changes is only + that a below-comment nothing else claims is no longer silently dropped + because something was also written above. + - Pinned: `a_declaration_shows_the_comments_above_beside_and_below_it_at_once` + (all three on one body declaration) and + `a_header_port_shows_the_comments_above_and_below_it_at_once`, which is + QA's repro 1 and repro 2 in one header — with the negative half (the same + block *is* left alone when another port follows it) in the same test. +- **PDS-3 — fixed, not documented as a gap.** Checked the binder first, as + the brief asked: `bind_tf_args` declares `task t(a);`'s `a` as a `TfArg` in + the task's own scope, and `input [7:0] a;` at statement position reaches + `bind_port_decl` with that same scope, so `declare` turns it into a + reference to the header symbol — the identical header→body merge a module + port gets, one symbol and not two (verified by probe before changing + anything). So the recording is extended rather than parked: the + `kind == SymbolKind::Port` gate is gone and the inner test is + `symbol.kind == kind`, which is the same condition for a port and now also + holds for an argument. Pinned in `vlog_semantic` + (`an_old_style_task_argument_records_its_body_declaration_too`, including + that an ANSI-style argument still has none) and in hover + (`an_old_style_task_argument_hovers_as_two_sections_too`). +- **PDS-4 — fixed.** `attached_lines`'s line reader strips a trailing `\r` + from every line it composes, so a CRLF file's fenced block is `\n`-joined + like any other. It is done there, at the one place all three collections + (above, declaration, below) pass through, rather than in `cut_to_size`, + which would have had to re-split the joined string. Display text only — + nothing writes to the buffer. QA's pinned test + `a_crlf_multiline_snippet_keeps_interior_carriage_returns` was the + regression test for the old behaviour; it is now + `a_crlf_multiline_snippet_carries_no_carriage_returns`, asserting no `\r` + survives *and* that the lines read as written. (Editing a QA-authored test + rather than deleting it: the finding it pins is the one being closed, and + the same file's `local_text` path goes through the same helper, so it + covers both branches QA named.) + +## QA log + +**2026-08-28 — QA.** Verified against the owner's own spec ("two sections +… same line, or above it (if no other port on the line above), or below it +(if no other port on the line below)"), and attacked with the shapes named in +the QA brief. Gates green (see change-debounce's QA log for the shared run). +All reproductions used temporary `#[test]`s in `hover.rs`, run once, and +removed after confirming — none are left in the tree, except the one noted +below as a kept, permanent regression test. + +- **Finding PDS-1 (high — a wrong comment shown, the one invariant this + feature explicitly promises never to violate).** `another_port_on` + (`hover.rs:355`) — the guard that decides whether a below-comment block + belongs to *this* declaration or the next one — inspects only the single + line immediately following the comment block. When the next port's own + declaration **wraps**, with its direction keyword alone on the first line + and its name on a later line, every word on that first line is in + `is_port_grammar_word`'s list (`hover.rs:368`, which includes bare + `input`/`output`/etc.), so `another_port_on` returns `false` — "no other + port here" — and the comment attaches to the **wrong** declaration. + - Repro: + ```systemverilog + module alu (data_in, result); + input [7:0] data_in; + // about result + input + [7:0] result; + endmodule + ``` + Hovering `data_in` shows a detail section reading + `input [7:0] data_in;\n// about result` — `result`'s own leading comment, + attached to `data_in`'s card. Confirmed live (temporary test asserting + the comment is *not* present failed with exactly this text). + - This is precisely the failure mode `docs/features/port-detail-spans/ + README.md`'s own Assumptions section rules out: "a false 'yes' only ever + declines to attach a comment — the direction that cannot lie." Here a + false *no* (failing to recognize `result`'s declaration as a port) makes + it lie. Left unfixed — not small/unambiguous; the honest fix wants + `another_port_on` (or its caller) to look past a line that is *entirely* + grammar words with no other identifier, to the line(s) after it, which + is a real design change to a predicate three call sites and several + tests depend on. + +- **Finding PDS-2 (medium — divergence from the stated spec, not corruption; + the one the QA brief asked to check explicitly).** The owner's rule reads + as three independently-checked sources (same line, above, below). The + implementation instead runs a strict priority chain in `attached_lines` + (`hover.rs:297`): below-comment collection is skipped **entirely** whenever + there is *any* above-comment, or *any* same-line trailing comment + (`hover.rs:313`, `if above.is_empty() && !decl.last()...has_comment_after`) + — even when the below comment is otherwise unclaimed by anything else + (no other port follows it). + - Repro 1 (above blocks below): + ```systemverilog + module alu ( + // above + data_in + // below + ); + input [7:0] data_in; + endmodule + ``` + Header section shows `// above` + `data_in` only; `// below` is silently + dropped, though nothing else claims it (the next line is `);`). + - Repro 2 (same-line trailing comment blocks below): + ```systemverilog + module alu ( + data_in // right here + // below + ); + input [7:0] data_in; + endmodule + ``` + Header section shows `data_in // right here` only; `// below` dropped. + - Not unsafe (never shows the wrong comment — just fewer than the literal + spec asks for), so lower severity than PDS-1, but a real, reproducible + divergence. Left unfixed — a design call (should a declaration ever show + *two* attached comments at once?) belongs to the dev/lead, not QA. + +- **Finding PDS-3 (low — silent feature-completeness gap, not a bug).** + `bind_port_decl`'s `detail_span`-recording branch is gated on `kind == + SymbolKind::Port` (`bind.rs:512`), which excludes `SymbolKind::TfArg` — + **old-style (non-ANSI) task/function port declarations** + (`task t(a);\n input a;\n ...\nendtask`) never get a `detail_span`, even + though they are exactly the same two-places-one-symbol shape a module's + non-ANSI port is, and `bind_port_decl` is already reached at statement + position for them (`bind.rs:1030`, `StmtKind::PortDecl`). The feature's own + "Not done" list names only extern method prototypes as the deliberately + parked case; task/function old-style ports are a second, unmentioned one. + Falls back to the single-section card exactly as before this round — no + regression, just an undocumented gap, worth a line in Status/TODO if the + dev wants it. + +- **Finding PDS-4 (low/cosmetic — pre-existing, amplified by this round, not + introduced by it).** On a CRLF file, a multi-line fenced snippet embeds a + raw `\r` byte in the *middle* of the code fence for every joined line + except the last (whose trailing `\r` happens to be stripped because + `cut_to_size`'s `trim_end()` only trims the very end of the whole joined + string, not each line). This is pre-existing behavior of + `Positions::whole_lines` / `cut_to_size` — `local_text` already had the + same characteristic for any multi-line `decl_span` before this round — but + comment attachment now makes multi-line snippets routine (any port with a + nearby comment, not just a rare multi-line declaration), so the gap is hit + far more often in practice. Repro: a CRLF split-port module with an + above-comment; the header section's rendered text contains a literal `\r` + between the comment line and the declaration line. Cosmetic only (a stray + control character, not wrong text); not fixed, flagged for whoever touches + `cut_to_size` next. + +- **Attack angles checked and clean (no finding):** + - *A port declared twice* — first-writer-wins confirmed: the second body + declaration's comment (`// second (duplicate...)`) never appears; only + the first's (`// first`) does, matching `bind_port_decl`'s documented + policy. + - *ANSI mixed with non-ANSI in one header* — a full ANSI port (`input wire + clk,`) and a split non-ANSI port (`data_in`) in the same header list: + `clk` renders exactly one fenced section, `data_in` exactly two, no + cross-contamination. + - *A comment containing `//` inside a string on the declaration line* — + the whole line is shown verbatim regardless (the attachment logic never + parses the line's meaning, only whether `has_comment_after` sees `//`/ + `/*` after the name), so there is no wrong-line risk, only the expected + line reproduced as written. + - *`` `ifdef``/`` `endif`` between the header and the body declaration* — + correctly ignored as neither comment-only nor a stolen declaration; the + detail section is exactly the body decl's own line(s). (Note: a + `` `endif``/`` `ifdef``/`` `define`` line sitting where "no other port" + is required is itself treated as "another port" by `another_port_on`'s + conservative word-matching — a false positive that only *declines* to + attach, so it is safe, just another instance of the documented + conservative-below-the-fold behavior, not a new bug.) + - *An attribute (`(* foo *)`) prefixing the next port's declaration* — + correctly detected as "another port" (the attribute's own words split + out as ordinary non-grammar identifiers), so the comment is not stolen. + - *A block comment `/* … */` spanning multiple lines* — the interior lines + are (by design, and correctly) not recognized as comment-only, so the + walk stops there and nothing is attached from inside the block — safe + (declines rather than guesses), matching the documented limitation. + +- **Facts-format bump (2 → 3): verified the drop, not a shifted read.** + Wrote and kept a permanent regression test, + `a_store_from_the_previous_facts_format_is_dropped_not_misread` + (`crates/lucisv_server/src/index_cache.rs`, next to the existing + `a_store_from_another_version_is_dropped_whole_and_replaced` and + `a_store_from_the_previous_store_format_is_dropped_whole_and_replaced`, + which cover a `VERSION` mismatch and a `CACHE_FORMAT` mismatch but, before + this, never a `FACTS_FORMAT`-only mismatch). It writes a store whose header + says `FACTS_FORMAT` `2` with today's `CACHE_FORMAT` and `VERSION` + otherwise unchanged, opens it, and asserts `facts_for` returns `None` (the + whole store is unread, not field-shifted) and that the first write since + replaces it under today's header, readable afterward. Passes. This closes + a real test gap the round left — the design (the format number lives in + the header line `IndexCache::open` compares byte-for-byte, + `index_cache.rs:103`) was sound but untested for this exact axis. + +- **A3 tie-break: confirmed correct**, both via the shipped + `looking_a_name_up_answers_exactly_what_scanning_every_symbol_would` + (passes) and by re-deriving it: `by_name` is built with a **stable** sort + (`Vec::sort_by`, `lib.rs`), so symbols sharing a name keep declaration + order, and `symbols_named`'s two `partition_point` binary searches over + that name-sorted table can only reorder within a name if the sort were + unstable — it is not. + +- **`nav::definition` / hover agreement:** confirmed the detail location is + filtered by `!span.is_empty()` (`nav.rs`) exactly as documented, and that a + detail-less symbol (ANSI port, ordinary declaration) still returns exactly + one location, unchanged from before this round. + +## Review + +**2026-08-28 — lead.** Accepted after one fix round. Gates re-run +independently: fmt clean, clippy silent, `cargo test --workspace` green +(2 396 passing at the time of review), `cargo test -p vlog_formatter` green. + +`detail_span` is the right adaptation of the "detail range" idea to this +model: the non-ANSI merge already produced one symbol, so the only thing +missing was *where the declaration is completed*, and recording that as an +optional second span leaves every complete-where-named declaration +untouched. Hover and go-to-definition read the same field, which keeps +`topo.md`'s one-matcher rule intact. + +Two things in this feature deserved the scrutiny they got. + +**The facts-format bump.** The first implementation added two numbers per +declaration record without moving `FACTS_FORMAT`, on the argument that a +short record fails `done()` and is dropped. That argument only holds for the +*last* declaration in a record; every earlier one would have been read +field-shifted by two, which is a persisted cache handing back wrong spans — +the exact shape invariant 4 exists to catch, in the same family as the +macro-items corruption. Bumping 2→3 is correct and QA's added regression test +(`index_cache.rs`, a store from the previous format is dropped, not misread) +closes a gap no existing test covered, since nothing varied `FACTS_FORMAT` +alone. + +**The comment attachment.** This began as scope creep — round 1's plan +explicitly deferred doc comments on hover — and then turned out to be +precisely what the user asked for, so it stays. But it is a *textual* +heuristic running over disk text on the cross-file path, and QA's PDS-1 found +it lying: `another_port_on` was a keyword blacklist, so a wrapped declaration +whose first line is bare `input` looked like an empty line and the next +port's comment attached to the previous port's card. Replacing the blacklist +with a closer whitelist (`only_a_closer_on`) inverts the bias in the one +direction that is safe — an unrecognised line now declines to attach rather +than mis-attaching — and the doc comment states that bias as the contract. +That is the correct resolution; a predicate over source text that guesses +must fail closed. + +PDS-2 was a genuine divergence from the user's stated rule and is fixed by +making the three comment sources independent rather than a priority chain. +PDS-3 was worth chasing rather than parking: the binder does perform the same +header/body merge for `TfArg`, so old-style task and function arguments now +get detail spans too, and the gap is closed rather than documented. PDS-4's +CRLF strip is display-only and does not touch the buffer. + +The dev renamed and inverted a QA-authored test, and flagged it. Correct call +and correctly surfaced: the behaviour that test pinned *was* the finding. + diff --git a/docs/perf/README.md b/docs/perf/README.md new file mode 100644 index 0000000..aa7cc40 --- /dev/null +++ b/docs/perf/README.md @@ -0,0 +1,490 @@ +# perf — measured numbers for the paths a keystroke and a hover run through + +## Goal + +Give the server's hot paths — `analyze`, opening a buffer, answering a hover, +reindexing one saved file, and (since round 2) one flush stage by stage and +one keystroke's round trip over the wire — a number that is *measured* rather +than guessed, taken the same way every time, so a later round can say whether +it made something faster or only different. This is the record; the +measurements themselves are `#[ignore]`d tests in +`crates/lucisv_server/src/perf.rs` and in +`crates/lucisv_server/tests/e2e.rs`, run on demand and asserting nothing about +duration. Nothing here is a performance *budget*: a test that fails when a +machine is busy is a test that gets deleted. + +## Assumptions + +- **No benchmark dependency.** `criterion` and friends are out: `CLAUDE.md` + requires a written justification for any new dependency, and the workspace + has six direct ones (`rayon`, `lsp-server`, `lsp-types`, `serde`, + `serde_json`, plus their pins). `std::time::Instant` + `eprintln!` is the + shape this repo already uses for perf notes (`hover.rs`'s QA measurement, + `includes.rs`, `inlay.rs`, `file_ops.rs`) and it is what is used here. +- **`--test-threads=1` or the numbers are noise.** The harness otherwise runs + these concurrently with each other and with 1 200 other tests. The first run + of these measurements was taken without it and reported a cross-file hover + as *cheaper* than the single file read it performs; that is how obvious the + contamination is. +- **Means, not single runs.** Each measurement is the mean of 10–1 000 runs + (`perf::mean`), with `std::hint::black_box` around the inputs and results so + a release build cannot optimize the work away. +- **Generated input, not the corpus.** `perf::generated_module` builds an + ANSI-headed module of repeated four-line blocks (a wire, an assign, a + register, an update) at 1 000 and 10 000 lines. It is uniform, which real + RTL is not — the numbers are a scale, not a prediction for any given file. + The corpus-scale numbers this repo already has live where they were taken + (`docs/features/incremental-index`, `index-persistence`, `references-nav`). + +## Reproducing + +```text +cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1 +``` + +Each test's own doc comment names the narrower filter for running it alone. +The over-the-wire measurement lives with the other end-to-end tests, because +it spawns the shipped binary, so it has its own command: + +```text +cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1 +``` + +The one older measurement quoted below has a third: + +```text +cargo test --release -p lucisv_server large_closed -- --ignored --nocapture --test-threads=1 +``` + +## The machine + +| | | +|---|---| +| CPU | Apple M1 Max (`uname -m` = `arm64`) | +| OS | macOS 27.0 (build 26A5421a) | +| build | `--release`, workspace at 0.12.1 + rounds 1 and 2 uncommitted | +| date | 2026-08-28 (every figure below re-measured this day, round 2) | + +## Numbers + +All figures are the mean of the runs named above. "1k" and "10k" are the +generated module's line counts (29 KB / 501 symbols and 309 KB / 5 001 +symbols respectively). + +| what | 1k lines | 10k lines | +|---|---|---| +| `vlog_semantic::analyze` (tree already parsed) | 252 µs | 3.76 ms | +| `Document::new` — lex + parse + analyze + `resolve_external` | 2.54 ms | 31.1 ms | +| `hover`, target declared in the same open buffer | 2.68 µs | 1.10 µs | +| `hover`, target in a **closed** file (disk path) | 38.1 µs | 159 µs | +| — of which one read + one `LineIndex` of that file | 27.4 µs | 140 µs | +| `WorkspaceIndex::update_file`, 20 files of this size | 2.76 ms | 32.1 ms | +| — of which the clone the measurement needs to repeat itself | 60 µs | 567 µs | +| one name looked up among the file's symbols: **linear scan** | 767 ns | 8.14 µs | +| one name looked up among the file's symbols: **name-sorted lookup** | 93 ns | 131 ns | +| one token found at the cursor: **sweep** | 6.58 µs | 77.5 µs | +| one token found at the cursor: **binary search** | 15 ns | 20 ns | +| the balanced-paren window `completion.rs` needs: **sweep** | 8.63 µs | 130 µs | +| the balanced-paren window `completion.rs` needs: **binary search** | 27 ns | 36 ns | + +Every figure above comes from one run of the command in *Reproducing*, on the +machine above. A local hover is a handful of pointer chases and comes out +under 3 µs at both sizes; the 1k figure being the larger of the two is that +measurement's noise floor, not a result. + +Three things stand out: + +- **A hover into a closed file is a file read.** 27 µs of the 1k hover's + 38 µs, and 140 µs of the 10k hover's 159 µs, is reading that file and + building a `LineIndex` over it. Everything else — resolution, guards, + rendering — is single-digit microseconds. +- **`Document::new` is where a keystroke's cost lives**, and it is dominated + by lexing and parsing, not by `analyze` (31 ms against 3.8 ms at 10k + lines). The stage-by-stage table below says exactly how much. +- **A sweep of the token vector costs about what the parse of one line + costs**, and there are several per keystroke. That is round 2's Phase 2. + +### One flush, stage by stage + +`Document::new` runs the first seven of these in order; the eighth is not +inside it at all — `diagnostics::all` is what a *publish* runs, on every +flush, and round 1's table did not account for it. + +`parse_tolerant` consumes its token vector, so each run of the parse needs a +fresh clone. The clone has its own row and the parse row still contains it; +subtracting one from the other is the honest reading, and it is what +`Document::new` really pays. + +| stage of one flush | 1k lines (9 461 tokens) | 10k lines (94 961 tokens) | +|---|---|---| +| `tokenize` | 1.14 ms | 12.5 ms | +| `tokens.clone()` (the copy `Document` keeps) | 230 µs | 2.40 ms | +| `parse_tolerant`, clone included | 1.16 ms | 14.3 ms | +| — the parse alone, by subtraction | 0.93 ms | 11.9 ms | +| `collect_defines` | 7.09 µs | 121 µs | +| `analyze` | 278 µs | 5.55 ms | +| `resolve_external` | 943 ns | 49.3 µs | +| `LineIndex::new` | 10.5 µs | 115 µs | +| `diagnostics::all` (parse errors + closers + lint) | 104 µs | 1.40 ms | + +Read this table as *shares of a flush*, not as the last word on any one +stage: it runs eight measurements back to back on one heap, and its `analyze` +row came out 5.55 ms in the same run where the dedicated `analyze` test — +which measures nothing else — came out 3.76 ms. The dedicated figure is the +cleaner one. What the table is for is the proportion, and the proportion is +unambiguous: + +- **Lexing and parsing are 79 % of a flush** at 10 000 lines (12.5 + 11.9 of + 30.9 ms, taking the dedicated `analyze` figure for the rest). Everything + else together is a fifth. +- **`tokens.clone()` is 7.7 %**, and it is load-bearing rather than waste: + `parse_tolerant` takes ownership of its tokens and *steals the comments out + of them*, so the copy `Document` keeps is the only one that still has its + trivia. It is also already the cheap option — before the one-lex change + this was a second `tokenize`, which is 12.5 ms. +- **`resolve_external` is 49 µs, one part in six hundred.** Making the + workspace overlay skippable was on this round's list of candidates; the + measurement says there is nothing there to save. +- **The lint pass is 1.40 ms on top of the flush**, about 4 %. It walks the + tree once per rule. + +### Over the wire — what a keystroke actually costs a user + +Round 1 listed this as its own open TODO, because it cannot be taken from +inside the crate: the number includes two pipes, a JSON encoder and decoder, +the change debounce's quiet-period timer and a whole flush. It is measured by +spawning the shipped binary and speaking framed JSON-RPC at it +(`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`, command above). + +| `didChange` → `publishDiagnostics` | 1k lines | 10k lines | +|---|---|---| +| one keystroke, nothing following it | 164 ms | 202 ms | +| a burst of ten keystrokes, no pause | 165 ms | 207 ms | +| — publishes that burst produced | **1** | **1** | +| one keystroke **a request follows** (mean of 10) | 4.35 ms | 37.6 ms | + +The three rows say three different things. + +- **The debounce is the felt latency when a client asks for nothing.** + 150 ms of the 164 ms is `CHANGE_DEBOUNCE`'s quiet period; the work is the + rest. At 10 000 lines the same 150 ms sits on top of a 31 ms flush. This + is the one row where round 1 made something *slower*: before the debounce + a lone keystroke published in about one flush, and it now waits out the + timer first. It is the bargain debouncing is, and the last row is why it + is worth taking. +- **A real editor never waits for that timer.** VS Code asks for semantic + tokens, inlay hints and highlights the moment a buffer changes, and a + request flushes the dirty buffer before it is answered. That is the last + row, and it is the number a user actually feels: **4.35 ms at 1 000 lines, + 37.6 ms at 10 000**. +- The first two rows are single round trips, not means, and each is bounded + below by a 150 ms timer; treat their differences as noise. The last row is + the mean of ten and is the one worth comparing across rounds. + +## Before / after — round 1 (2026-08-28) + +**A1 — didChange debounce.** Not measured directly *at the time*, and the +arithmetic below is what round 1 recorded: every `didChange` used to run one +`Document::new` plus lint and publish; a burst of *k* changes now runs one. +At 10k lines that is 31 ms saved per keystroke after the first in a burst, at +1k lines 2.6 ms. What the debounce cannot save is the first change in a burst +and the last flush, so the floor is one `Document::new` per burst per buffer. + +**Round 2 measured it.** A burst of ten keystrokes over the wire produces +**one** `publishDiagnostics`, counted rather than reasoned about — the count +comes from draining the session at `shutdown`, which every pending flush is +guaranteed to have arrived before. The arithmetic above was right. + +The burst is deliberately the **last** thing that measurement does, which is +QA finding IL-1 closed: every `wait_for` in the test accepts *any* publish, +so while the burst ran before the other rows, a second publish it had +produced would have been absorbed by the next row's wait and never counted. +With nothing between the burst and the drain, the count is the count. + +**A2 — one disk read per hover.** Measured, two ways. + +- The QA round that filed the finding measured a hover into a 31.7 MB closed + file at **34 ms** (`docs/features/hover-declarations/README.md`, finding 4, + 2026-08-27, same machine, same test, release build). The same test after + the `disk_view` memo: **16.3 ms**. That is the expected shape — two reads + and two `LineIndex` builds became one — but the two numbers come from + different runs on different days, so read it as "about half", not as + 2.08×. +- The `perf::hovering_across_files_into_a_closed_file` measurement takes the + after-number and the cost of one read + `LineIndex` side by side, in the + same run: 142 µs of a 160 µs hover at 10k lines. Removing a second read of + that same file is therefore removing roughly the whole remaining cost of + the request, which is the before/after in the form that does not depend on + an old number. + +**A3 — name-keyed symbol lookup.** Measured directly, on the lookup alone: +8.41 µs → 133 ns at 10k lines (5 001 symbols), 763 ns → 106 ns at 1k. The +lookup is only part of what was saved: in `hover::live_symbol` every symbol +the scan used to reach was also an `indexed_def_for_symbol` call — two index +lookups apiece — which the name-sorted lookup never makes. That larger saving +is **not measured here**; the 8.41 µs → 133 ns figure is a floor on it, not +the whole of it. + +**B — port detail spans, and comment attachment.** Not measured. The work +added is a second `fenced_sections` call over lines already in memory, and +two integers per declaration in the index and its facts records. No +measurement was taken and none is claimed. + +## Before / after — round 2 (2026-08-28) + +**C1 — six token lookups stopped sweeping the buffer.** Measured directly, +both halves in the same run against the same token stream +(`perf::finding_one_token_against_sweeping_the_stream`), with the cursor +three quarters of the way down the file — a sweep costs the distance from +token zero, so measuring at either end would flatter it. + +| | 1k lines | 10k lines | +|---|---|---| +| the token at the cursor: sweep → binary search | 6.58 µs → 15 ns | 77.5 µs → 20 ns | +| `balanced`'s window: sweep → binary search | 8.63 µs → 27 ns | 130 µs → 36 ns | + +Six call sites across `selection.rs`, `on_type.rs`, `completion.rs` and +`inline.rs`; which ones, what each of them wanted, and the per-site argument +that the search returns exactly what the sweep returned are in +`docs/features/interactive-latency/README.md`. Every one is pinned by a test +that walks **every byte** of a buffer full of touching tokens and compares +the two. None of them changed an answer, and the tests are what says so +rather than the claim. + +Three sweeps were left alone with the reason written down: `signature.rs`'s +two paren-depth walks (a depth is a function of every bracket before the +cursor), `pairs.rs::analyze` (not a position query at all), and +`completion.rs`'s comment gate (comments are trivia attached to whichever +token happens to be next, so no search of the stream answers "is this byte +inside a comment"). That last one is the remaining per-keystroke +whole-buffer walk on the completion path. + +**C2 — the round trip, and nothing else changed.** No stage of a flush was +touched this round, so the flush table above is a baseline rather than an +after. The reasons each candidate was refused, with its number, are in the +next section. + +## What it would take to go faster + +Ranked by what the measurements above say is there, with what each would +cost. None of these were attempted; each is a future round. + +1. **Incremental lexing and parsing — 24.5 ms of a 31 ms flush at 10 000 + lines (79 %).** This is the only large lever left. It is also the one + change that runs straight into `CLAUDE.md`'s hard invariants 1 and 2: the + parser is what the "never corrupt code" and idempotency guarantees rest + on, and an incremental parser that is right on 99 % of edits is worse than + none. The change debounce already removed most of the *repetition* per + keystroke, which is why this was not attempted here. The number that would + justify it: **37.6 ms**, the felt latency of one keystroke in a + 10 000-line buffer, of which roughly 30 ms is lex + parse. +2. **A cheaply-clonable `Token` — 2.40 ms, 7.7 % of a flush.** + `Document.tokens` must be a separate copy because `parse_tolerant` takes + ownership and steals `leading`/`trailing` out of the tokens it parses; the + copy is 94 961 `String` allocations. Interning the text, or an `Rc`, + would remove most of it — but `Token` is `vlog_parser`'s public type and + the formatter reads it everywhere, so this is a cross-crate change for + under 8 %. +3. **One tree walk for the whole lint pass — 1.40 ms, about 4 % on top of a + flush.** `vlog_linter::lint` is `for rule in enabled { rule.check(ctx) }`, + one walk per rule, and the same engine serves `lucisv check`. Fusing them + is a `vlog_linter` refactor, and the editor and CI must not disagree about + what a violation is. +4. **`completion.rs`'s comment gate**, the last whole-buffer walk on a + per-keystroke request path. Not measured on its own; it is one pass over + the token vector plus its trivia, so the sweep figures above (77.5 µs at + 10 000 lines) are the right order of magnitude for it. Doing it properly + means giving the lexer a way to answer "which comment covers this byte", + which is a `vlog_parser` question and not a `completion.rs` one. +5. **`CHANGE_DEBOUNCE` itself** is not a code problem: 150 ms of a lone + keystroke's 164 ms round trip is the timer. It only bites clients that ask + for nothing after a change, and it was set deliberately. Now that it is + measured, a future round has the number to argue about. + +## Status / TODO + +- [x] `crates/lucisv_server/src/perf.rs` — eight `#[ignore]`d measurements, + std only, each with the command to run it. +- [x] `analyze`, `Document::new`, hover (local + closed cross-file), + `WorkspaceIndex::update_file`, at 1k and 10k lines. +- [x] Before/after where it was cheap: A2 (two ways), A3 and C1. +- [x] Machine, command and date recorded above. +- [x] **Round 1's first open TODO, resolved (round 2, 2026-08-28):** + end-to-end request latency over the wire, measured against the shipped + binary — a single `didChange`, a burst of ten (with the publish count + that turns A1's arithmetic into a measurement), and the + change-then-request shape a real editor produces. + `tests/e2e.rs::a_keystroke_round_trip_over_the_wire`. +- [x] **Added in round 2:** one flush stage by stage, including the + `diagnostics::all` pass that runs on every publish and that round 1's + table did not account for. + `perf::breaking_down_one_flushed_keystroke`. +- [ ] **Round 1's second open TODO, restated and still open:** memory. + Nothing in the repo measures resident size. Round 2 added no data + structure — two free functions and no state — so the figure it would + report has not moved, and round 1's name index is still four bytes per + symbol. Worth doing before anything interns tokens, which is item 2 of + *What it would take to go faster* and is a memory trade as much as a + time one. +- [ ] Not measured: the per-request handlers themselves (hover aside). + Completion, signature help and semantic tokens each have a + whole-buffer pass somewhere; only their token lookups were measured + this round, not the requests end to end. + +## Work log + +**2026-08-28 — dev.** Wrote `perf.rs` and took the numbers above (part A4 of +the LSP performance round). Chose one module of six tests over a test per +crate so that a single command produces the whole table. The generated-module +generator lives beside the tests rather than in a shared helper — it has one +user. + +Renamed `hover.rs`'s QA measurement +`hovering_into_a_large_closed_file_reads_it_twice` → +`..._reads_it_once`, since the doubled read it was named for is what A2 +removed. The QA log in `docs/features/hover-declarations/README.md` still +names the old spelling; that section belongs to QA and was left alone. + +**2026-08-28 — dev (QA fixes).** No number above moved, and none was +re-measured, because nothing on a measured path changed shape: + +- The hover fixes (PDS-1, PDS-2, PDS-4) are all inside `attached_lines`, + which part **B** already records as unmeasured. The added work is a + `strip_suffix` per composed line and a below-comment walk that now also + runs when a comment sits above — a handful of `line_range` lookups against + the 142 µs *file read* that dominates the "hover closed" figure. +- CD-1 only *removes* work (a closing buffer's `Document::new` and publish), + and the debounce's own A1 numbers are arithmetic over `Document::new`, + which is untouched. +- PDS-3 widens one `bind_port_decl` branch from ports to task/function + arguments: one hash lookup per declarator of a body port declaration + inside a task or function. `perf.rs`'s generated modules contain no + tasks, so the `analyze` / `Document::new` / `update_file` figures cannot + have moved at all. + +**2026-08-28 — dev (round 2).** Added +`perf::breaking_down_one_flushed_keystroke`, +`perf::finding_one_token_against_sweeping_the_stream` and +`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`, and **re-measured every +figure in this document** on the same machine from the commands written +beside them — the tables above are one run of each, not a mix of runs across +days. The old figures are gone rather than kept alongside; every pair was +within the noise this document already budgets for, and carrying two columns +of the same measurement would invite reading a difference into scheduling. +Round 1's figures are not lost — the QA log below quotes all of them in its +own table, dated, and that section belongs to QA and was left alone. + +The round's changes are in `docs/features/interactive-latency/README.md`. +Only C1 touched shipped code, and it touched no stage of a flush, so the +flush table is a baseline for the next round rather than an after. + +Two things are recorded here that a future round should not have to +rediscover. First, the e2e measurement reuses `e2e.rs`'s existing `Live` +session helper; the only shared code that changed is that `Live::finish` now +returns the publish count it saw on the way out, which is what makes the +debounce's coalescing countable. Second, `perf::generated_module` now has a +copy in `tests/e2e.rs` — a binary crate's modules are not reachable from an +integration test — and the two must stay the same shape or the in-crate table +and the over-the-wire table stop being readable against one another. + +## QA log + +**2026-08-28 — QA.** No findings — every number reproduces within reason. + +- **Machine match confirmed.** `sysctl -n machdep.cpu.brand_string` → + `Apple M1 Max`; `sw_vers` → macOS 27.0, build `26A5421a` — exactly the + machine named in the README's own table, on the same checkout. +- **Re-ran the exact reproduce command**, `cargo test --release -p + lucisv_server perf:: -- --ignored --nocapture --test-threads=1`, and + compared every figure against the table: + + | what | table | re-measured | + |---|---|---| + | `analyze`, 1k / 10k | 274 µs / 3.79 ms | 287.6 µs / 3.806 ms | + | `Document::new`, 1k / 10k | 2.60 ms / 31.1 ms | 2.600 ms / 31.72 ms | + | hover local, 1k / 10k | 1.79 µs / 0.97 µs | 3.35 µs / 1.01 µs | + | hover closed, 1k / 10k | 35.2 µs / 160 µs | 34.4 µs / 172 µs | + | — one read of it, 1k / 10k | 26.9 µs / 142 µs | 26.7 µs / 147.6 µs | + | `update_file`, 1k / 10k | 2.73 ms / 31.4 ms | 2.695 ms / 32.45 ms | + | — the clone, 1k / 10k | 60 µs / 528 µs | 60.7 µs / 516.7 µs | + | linear scan, 1k / 10k | 763 ns / 8.41 µs | 793 ns / 8.21 µs | + | name-sorted, 1k / 10k | 106 ns / 133 ns | 93 ns / 134 ns | + + Every pair is within the noise the README itself budgets for — including + the hover-local 1k figure, which the README already calls out by name as + "that measurement's noise floor, not a result" (mine is higher still, + 3.35 µs vs. 1.79 µs, and still a handful of pointer chases either way). + Nothing here is scaled, remembered, or overclaimed. +- **Re-ran the older, separately-commanded measurement** too: `cargo test + --release -p lucisv_server large_closed -- --ignored --nocapture + --test-threads=1` → **17.0 ms** against the documented "34 ms → 16.3 ms." + Matches the README's own honesty caveat exactly ("read it as 'about half', + not as 2.08×" — different runs, different days). +- **`perf.rs` measures what its name says** — spot-checked + `hovering_across_files_into_a_closed_file` and + `looking_up_one_name_against_scanning_every_symbol` against `hover.rs`'s + and `lib.rs`'s actual entry points (`hover::hover`, `Semantics:: + symbols_named` vs. a hand-rolled linear scan over `symbols()`) — both call + the real, shipped functions, not a stand-in. +- **A1's "before/after" is correctly labeled "not measured directly"** — it + is arithmetic over the already-verified `Document::new` figures, and the + README says so; no separate claim to check. +- **B's "not measured, none is claimed"** — confirmed true: no perf test + exercises `fenced_sections`/`attached_lines`, and the README does not say + one does. + +**2026-08-28 — QA (round 2).** Findings and the full gate output are recorded +in `docs/features/interactive-latency/README.md`'s QA log, which is this +round's owning feature; summarized here since this document is where the +numbers live. + +- Every figure in *Over the wire* and *One flush, stage by stage* reproduced + within the noise this document budgets for, from a fresh + `cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1` + and `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1` + on this session's run of this machine. +- **C1's identity claim** (six sweeps → binary searches, none changed an + answer) held under a hand-traced check of all six call sites, including + the empty-token and large-file-fast-path edges, and under an independent + check of the `state.rs` monotonicity precondition against `vlog_parser`'s + own much wider corpus/fuzz tests (`tests/spans.rs`, `tests/error_recovery.rs`) + — no gap found. +- **One methodology finding, IL-1 (medium)**, on the e2e round trip's burst + measurement: the "1 publish(es)" figure for a burst of ten is not the + order-independent count its own doc comment claims — a stray extra publish + in the window between the burst and `Live::finish`'s drain could be + silently absorbed by an unrelated `wait_for` later in the same test and + never counted. Full detail and repro in + `docs/features/interactive-latency/README.md`. Not a claim about a real + double-publish (the debounce is understood to coalesce to one), and not + fixed — closing it is a test-restructuring decision for the dev. +- The two `generated_module` copies (this crate's `perf.rs` and `e2e.rs`'s) + differ by one trivia line, not the byte-identical shape their own comment + implies; verified harmless (comments are not tokens, and the tables stay + readable against each other). Detail in the same QA log. +- **Verdict: SHIP WITH FIXES noted, none applied.** + +## Review + +**2026-08-28 — lead.** Accepted as the round's record. + +The discipline here is what makes the numbers usable later: one command, one +machine block, means rather than single runs, `--test-threads=1` justified by +a contaminated first attempt that reported a cross-file hover as cheaper than +the file read it performs. Refusing criterion was the right call against +`CLAUDE.md`'s dependency rule, and the `#[ignore]`d-measurement pattern was +already this repo's idiom rather than an invention for this round. + +I re-ran every measurement independently and the figures reproduce. Two +claims were softened at review rather than left as written: the wire-latency +rows are re-measured after the IL-1 methodology fix (164/202 ms lone, +4.35/37.6 ms with a request following), and the lone-keystroke row now says +plainly that round 1 made that case *slower* — 150 ms of it is the debounce +timer, and a client that asks for nothing after a change waits it out. A perf +document that only records wins is not a perf document. + +What I want the next round to inherit: the felt-latency number is **37.6 ms** +for one keystroke in a 10 000-line buffer, roughly 30 ms of it lex and parse. +That is the figure any incremental-parsing proposal has to be argued against, +and it now exists. + diff --git a/topo.md b/topo.md new file mode 100644 index 0000000..2f62dda --- /dev/null +++ b/topo.md @@ -0,0 +1,633 @@ +# topo.md — the dependency topology of lucisv + +**Purpose.** This document is the map an agent reads before touching anything: +which modules depend on which, which features consume which, and where the +two graphs meet. It exists to make parallel multi-agent development safe — +every edge below is an interface somebody can break, and every *absent* edge +is a place two agents can work at the same time without talking. + +Sources of truth this document is derived from (and defers to on conflict): +each crate's `Cargo.toml`, each feature's `docs/features//README.md` +(the **Handshakes** section in particular), `README.md` and `CLAUDE.md`. +Drafted 2026-08-27 from the workspace at v0.10.2 (93 feature READMEs); +updated 2026-08-28 for hover-declarations, change-debounce, +port-detail-spans and interactive-latency (97 feature READMEs). + +**Edge notation, used in all three sections:** + +| notation | meaning | +|---|---| +| `A ──▶ B` | **A depends solely on B.** A consumes B's published interface; B was not changed for A and does not know A exists. Breaking B's interface breaks A; breaking A costs B nothing. | +| `A ◀──▶ B` | **Handshake.** A negotiated, two-sided contract: B changed something *for* A (or both sides pin one wire shape / file format / naming convention), and the contract is written down in one or both READMEs. Either side moving unilaterally breaks the other. | +| `A ─▶ B` | **Not a dependency** — a one-way note whose `kind` column says what it is: `sequencing` (corpus files handed from one bucket to the next), `standing promise` (A imposes a rule on B and its successors), `open request`, or `depends (consumed by)` — the last reads **B depends on A**. | +| *(absent)* | The two are independent. Independent pairs are **not listed** — their absence is the claim. | + +A handshake that was **requested but not yet delivered** is an *open +handshake*; those are collected in §2.9 because they are exactly the +coordination points parallel agents must not both grab. + +--- + +## 1. Module dependency graph + +"Module" here means: the eight workspace crates, the two editor trees, and +the script layer (`tools/`, `scripts/`, CI). Intra-crate structure that +matters for parallel work is in §1.3. + +### 1.1 Crate-level graph + +```mermaid +graph TD + subgraph foundations [foundation crates — depend on nothing] + P[vlog_parser] + C[lucisv_core] + end + F[vlog_formatter] --> P + S[vlog_semantic] --> P + L[vlog_linter] --> P + L --> S + R[vlog_refactor] --> P + R --> S + CLI[lucisv (CLI)] --> C + CLI --> P + CLI --> F + CLI --> L + SRV[lucisv_server] --> C + SRV --> P + SRV --> S + SRV --> R + SRV --> F + SRV --> L + L -.dev-dep (fix harness).-> F + VSC[editors/vscode] -.spawn contract.-> SRV + VSC -.KEYWORDS grammar lock.-> P + NVIM[editors/nvim (docs)] -.spawn contract.-> SRV + TOOLS[tools/ release scripts] -.builds/packages.-> CLI + TOOLS -.builds/packages.-> SRV + TOOLS -.builds/packages.-> VSC + CI[Gitea Actions] --> TOOLS + CORPUS[scripts/ + tools/corpus_*] -.exit codes, msg prefixes.-> CLI +``` + +*(The diagram shows direction only; §1.2 is authoritative on `depends` vs +`handshake` for each edge.)* + +External dependencies (all exactly pinned in the workspace `Cargo.toml`): +`rayon` (CLI only, sanctioned by TODO §3), `lsp-server` + `lsp-types` + +`serde`/`serde_json` (server only, sanctioned by TODO §6). Those are the only +**direct** external dependencies; everything the workspace itself writes is +std (they pull in ~20 transitive crates — see `Cargo.lock` — which is what an +audit counts, not what an agent can call). `lsp-types` carries +`features = ["proposed"]` for LSP 3.18 `inlineCompletion` (inline-templates). + +### 1.2 Crate edges, documented + +Every edge is directional; "consumes" lists the load-bearing surface, i.e. +what a change on the pointed-to side must not silently break. + +| edge | kind | contract | +|---|---|---| +| `vlog_formatter ──▶ vlog_parser` | depends | `parse(tokens, source)` / `parse_source`, the whole AST, `tokenize` (re-used by `verify.rs` to re-lex both sides of the safety net), trivia attachment (`Meta::{leading,trailing,before_sep,attrs}` — comments are never dropped), `RawText.col` (the dedent column for verbatim re-indent), spans. The formatter is the AST's primary consumer: **every new `ItemKind`/`StmtKind`/`ExprKind` variant costs an arm in `format.rs`** (its matches are exhaustive). | +| `vlog_semantic ──▶ vlog_parser` | depends | The AST read-only, `parse_source_tolerant`/`parse_tolerant` (never fails; `Error` nodes are opaque leaves), the **name-span contract** `src[name_span] == name` on every declaring node, `token::is_keyword`, `defines::collect_defines`/`DefineTable`, `TextRange`. `bind.rs`'s `ItemKind`/`ExprKind`/`DimKind` matches are exhaustive — new variants cost an arm here too. | +| `vlog_linter ──▶ vlog_parser` | depends | `ParsedSource::parse` = `tokenize` + `parse_tolerant` (one-parse bundle), `LineIndex`, `TextRange`, AST shapes walked by `visit.rs` (which ends in `_ => {}`, so new variants usually cost nothing here), token facts for text rules (a macro use is one `Ident` token; a directive is one `Directive` token). | +| `vlog_linter ──▶ vlog_semantic` | depends | `analyze`, `Semantics::{symbols, references, references_of}` for the three semantic rules (`unused-signal`, `undriven-net`, `multiply-driven`). Lazy: a run with no semantic rule enabled never calls `analyze`. Justified in `vlog_linter/Cargo.toml`; adds no external code (`vlog_semantic` is `vlog_parser` + std). | +| `vlog_linter ──▶ vlog_formatter` **(dev-only)** | depends (tests) | The `.lint` fix harness asserts a lint fix never produces text `format_source` refuses. **The library dependency list is still `vlog_parser` + `vlog_semantic` + std** — `cargo tree -p vlog_linter -e normal` is the pinned check. Do not promote this to a normal dep; the fence filter deliberately lives in the front ends instead (see shared-fence-filter, §2.4). | +| `vlog_refactor ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant` + diagnostics, `LineIndex`, `TextRange`, the port/instantiation/module AST shapes, `token::is_keyword` (new-name validity), `defines` via the index. Every edit span originates in a parsed node — no textual search-and-replace. | +| `vlog_refactor ──▶ vlog_semantic` | depends | `Semantics` queries (`symbol_at`, `references_of`, `reference_id_at`, …), `Resolution` variants (three of them are refusal rules), `WorkspaceIndex` + `resolve_external` + `ExternalTarget`, and the exactness promise on `name_span` (re-checked before each edit is emitted). One historical exception: refactor-rename added `Target::Declaration` + end-label uses *into* `vlog_semantic` (lead-authorized, additive — see §2.6). | +| `lucisv ──▶ lucisv_core` | depends | `config::{FileConfig, Discovery}` (lucisv.toml discovery — `config::parse` is reached through `Discovery`, not called directly), `walk::{collect_files, EXTENSIONS}` (the `.gitignore`/`--exclude` walk), `filelist::read` (`-f`), `cache` (the format cache). (`walk::is_excluded` is `pub` but currently has no consumer outside the crate.) | +| `lucisv ──▶ vlog_formatter` | depends | `format_source` / `format_range` / `LineRanges` / `Config` / `FormatError`, and `fence::{protected_regions, is_protected}` (the `--fix` fence filter — the linter crate deliberately has no fence notion). | +| `lucisv ──▶ vlog_linter` | depends | The public linter API for `lucisv check` — `lint` + `LintContext`/`ParsedSource`, `apply_fixes`, `select_rules` (the CLI does not call `run` itself). Relies on: rule names stable, linting never panics/writes, findings sorted by `(span.start, span.end, rule)`. | +| `lucisv ──▶ vlog_parser` | depends | Thin: `LineIndex` / `TextRange` for lint report coordinates. (The CLI otherwise reaches the parser through the formatter and linter.) | +| `lucisv ──▶ rayon` | depends | The worker pool. Pinned exactly; pool must keep `stack_size(8 MiB)` (recursion-limit handshake) or the parser's depth guarantee regresses to a stack overflow. | +| `lucisv_server ──▶ lucisv_core` | depends | Same config discovery and walk as the CLI (that sameness is the point — format-on-save must agree with `lucisv --check`), `filelist::read` (index scope rung 1, `+incdir+` for the include graph), `cache::content_hash` (re-used by the persistent index cache — one FNV-1a, not two). | +| `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the VS Code grammar is generated from). | +| `lucisv_server ──▶ vlog_semantic` | depends | `analyze`/`Semantics` (every navigation answer), `WorkspaceIndex` (build/incremental update, units/members/defines, `instantiations_of`/`subclasses_of` edge tables, `FileFacts` codec for the persistent cache), `resolve_external` overlay, `index_order`/`IndexBuilder` (watched builds). | +| `lucisv_server ◀──▶ vlog_semantic` | handshake | Two negotiated additions, both 2026-08-28 and both additive: **`Symbol::detail_span` / `Def::detail_span`** (where a non-ANSI port's body declaration completes the header that names it — the server's hover card and `nav::definition` both read it, and they show/jump to it in the same order), and **`Semantics::symbols_named`** (name → declarations, built in `analyze`, in declaration order — the server replaced two scan-every-symbol loops with it and the *first-match tie-break must stay declaration order* or hover's choice between two live declarations of one name changes). `docs/features/port-detail-spans/README.md`. | +| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `instantiation_plan`/`render_with`/`module_definition` (completion skeletons, signature help, inlay hints). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. | +| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). | +| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. | +| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. | +| `editors/vscode ◀──▶ lucisv_server` | handshake | The **spawn contract**: binary named `lucisv-server`, no args, no env, LSP over stdio, `initialize` works with no roots (single-file mode). Wire shapes pinned on both sides: the custom `lucisv/scopePairs` result, the `lucisv.*` settings section (push and pull), `initializationOptions.storagePath`, the markdown fence tag `systemverilog` (server emits it, extension's grammar registers it), the `bin/` layouts of the platform `.vsix` packages. `smoke.js` drives the contract headlessly; `tests/e2e.rs` and `tests/grammar.rs` pin it server-side. | +| `editors/vscode ◀──▶ vlog_parser` | handshake | The TextMate grammar's keyword alternation is **hand-maintained and test-locked to `vlog_parser::KEYWORDS`**: `crates/lucisv_server/tests/grammar.rs` fails, naming the missing/extra words, when they diverge (there is no generator script). Adding a keyword to `token.rs`'s `keywords!` macro is therefore also a hand edit to `editors/vscode/syntaxes/systemverilog.tmLanguage.json`. | +| `editors/nvim ──▶ lucisv_server` | depends | Documentation-only module: config snippets consuming the same spawn contract and settings shape. No code. | +| `tools/ ◀──▶ crates + editors/vscode` | handshake | `release.sh` parses `lucisv --version` (field 2), runs `smoke.js` against the built server, stages `dist/lucisv[-server]--` names, packages seven `.vsix` files and asserts their `bin/` layouts. `audit_artifacts.sh` and `prune_release_assets.sh` key on those exact names. The version number lives in exactly four files (two `Cargo` files, two `package*.json`) and nowhere in Rust source. | +| `CI (Gitea Actions) ──▶ tools/` | depends | `release.yml` is (almost) all `tools/` one-liners — `release.sh --cross`, `audit_artifacts.sh`, `prune_release_assets.sh`, `release_notes.sh`, `publish_release.sh` — so every release step runs by hand too; its only inline logic is the tag-vs-`lucisv --version` check. `ci.yml` is plain `cargo fmt`/`clippy`/`test` plus `scripts/corpus_gate.sh` (which reaches `tools/corpus_fetch.sh` on a cache miss). Tag `vX.Y.Z` must equal the workspace version; release notes come from `CHANGELOG.md`'s `## — ` headings via `release_notes.sh`. | +| `scripts/score.sh + tools/corpus_check.sh ──▶ lucisv` | depends | The frozen 0/1/2 exit-code contract, plus a **textual** dependency on the message prefixes `parse error:` / `lex error:` / `verification failed:` (a standing fragile coupling — rewording those means telling corpus-check; see §2.9). | + +**Deliberately absent crate edges** (independence you can rely on): + +- `lucisv` (CLI) does **not** depend on `vlog_semantic` or `vlog_refactor` — + the CLI formats and lints; semantic lints reach it only *through* + `vlog_linter`, and refactoring is server-only today. +- `vlog_refactor` does **not** depend on `vlog_formatter` — refactored output + is edited source, not reformatted source (refactor README, by design). +- Among `vlog_formatter`, `vlog_semantic`, `vlog_refactor`, `vlog_linter` + there are exactly two build-time inter-crate edges — `vlog_linter → + vlog_semantic` and `vlog_refactor → vlog_semantic` — plus `vlog_linter → + vlog_formatter` as a **dev-dependency only**. All four depend on + `vlog_parser`. `vlog_formatter` is the isolated one: nothing in this group + depends on it at build time and it depends on none of them. Formatter work + and semantic work are parallel-safe except where both touch + `vlog_parser::ast`. +- `lucisv_core` depends on nothing and nothing in it knows about Verilog — + it is "which files, with what settings". +- `vlog_parser` depends on nothing. It is also the **highest-contention + module in the workspace**: six crates depend on it, five consume the AST + (the CLI takes only `LineIndex`/`TextRange`), and two of those match it + exhaustively — `vlog_formatter/src/format.rs` and `vlog_semantic/src/bind.rs` + — with `vlog_parser`'s own `tests/spans.rs` as a third exhaustive walker. + `vlog_linter`, `vlog_refactor` and `lucisv_server` walk it with catch-all + arms. See §3.3. + +### 1.3 Intra-crate structure (what matters for parallel work) + +**`vlog_parser`** — `lexer.rs` → `token.rs` (tokens + trivia attachment); +`parser.rs` (recursive descent, strict + tolerant entry points over one +grammar, depth/chain budgets from recursion-limit) → `ast.rs`; `span.rs` +(`TextRange`), `line_index.rs` (offset↔line:col), `defines.rs` (the +`` `define`` table, reads the token stream, expands nothing). `tests/spans.rs` +is an exhaustive AST walker: **every new node needs an arm there** and must +keep the span-nesting invariant. + +**`vlog_formatter`** — the pipeline is `format.rs` (per-node rules) → +`doc.rs` (the Wadler IR) → `printer.rs` (width-aware printing); +`verify.rs` (the runtime safety net: token equivalence + convergence — +CLAUDE.md invariant #4 territory, see §3.3); `fence.rs` (format-off regions + +`protected_regions`, consumed by both front ends); `range.rs` (`--lines`); +`align.rs` (alignment inference). `format_source` = parse → format → verify; +an error means emit nothing. + +**`vlog_semantic`** — `bind.rs` (AST → scopes/symbols/references) → +`model.rs`; `resolve.rs` (the lexical walk; misses become +`ExternalCandidate`/`InheritedCandidate` carrying candidate paths); +`scan.rs` (residual text-scanning for the one span the parser doesn't carry — +`DataType`; shrinks to zero when open handshake §2.9-2 lands); +`workspace.rs` (`WorkspaceIndex`: units, members, defines, instantiation and +inheritance edge tables, incremental `update_file`/`remove_file`, +`fingerprint`); `facts.rs` (`FileFacts` codec for the persistent cache); +`instantiations.rs`, `classes.rs` (the shared walks, lifted from the server +so the index census and the request handlers cannot drift). + +**`lucisv_core`** — `config.rs` (`lucisv.toml` parsing + `Discovery`, the +upward search with its per-instance cache), `walk.rs` (`collect_files`, +`EXTENSIONS`, `.gitignore`/`--exclude` filtering), `filelist.rs` (the `.f` +reader: files, `+incdir+`, defines, warnings), `cache.rs` (the format cache + +`content_hash` — the one FNV-1a the server's index cache also reuses). Knows +nothing of Verilog; depends on nothing; owns two open handshakes (§2.9-1, +§2.9-8). + +**`vlog_linter`** — `registry.rs` (`Rule` trait, `all_rules`/`default_rules`/ +`select_rules`), `rules/` (one file per rule; names are **stable API** — they +appear in users' waivers), `context.rs` (`LintContext<'a>`, `ParsedSource`, +lazy `semantics()`), `visit.rs` (the item/statement walk), `waiver.rs`, +`violation.rs` (+ `Fix`, `Applicability`), `signals.rs` (the shared signal +table for the three semantic rules), `naming.rs`, `rule_docs.rs` +(`rules_markdown()` — docs generated from the registry). + +**`vlog_refactor`** — `rename.rs` (the `Scope` cache + occurrence walk — +also the engine of `references.rs::find_references`), `ports.rs` +(add/remove/propagate), `instantiate.rs` (plans + rendering; the one layout +both plain and snippet spellings go through), `check.rs` (whole-edit +verification: re-tokenize + re-resolve, refuse everything on any drift). + +**`lucisv` (CLI)** — `main.rs` (args → walk → per-file worker pool; +`process_file` is the cache-aware unit of work; panic hook installed once at +startup — **keep it that way**, cli-polish → parallel-files handshake), +`args.rs`, `diff.rs`, `lint.rs` (the `check` subcommand; owns the CLI-side +fence filter). + +**`lucisv_server`** — layered, 40 files (`includes.rs` is the one file that +spans two layers — the include graph *and* the `documentLink` handler; +`perf.rs` is `#[cfg(test)]`-only and is not a layer — see +`docs/perf/README.md`): + +| layer | files | role | +|---|---|---| +| entry | `main.rs` | capabilities advertisement, `InitializeParams` reading, wiring | +| loop | `server.rs` | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, reindex orchestration, progress/log senders | +| state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay) and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) | +| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word tables, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync | +| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs`, `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion.rs`, `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) | + +**`editors/vscode`** — `extension.js` (spawn + rainbow decorations + storage +path; ~everything else is `vscode-languageclient` driven off advertised +capabilities), `package.json` (languages, grammar, snippets, settings, +colour ids), `syntaxes/` (hand-maintained grammar, test-locked to +`KEYWORDS`), `snippets/` (static, server-independent), `smoke.js` (headless +handshake check), `README.md` (the Marketplace Details page, owned by +editor-marketplace-page). + +--- + +## 2. Feature dependency graph + +96 features. They cluster into eight lanes; edges inside a lane are listed in +that lane's table, cross-lane edges are repeated where they matter. The +mermaid graph shows the lanes and the load-bearing cross-lane edges only. + +```mermaid +graph LR + subgraph FMT [formatter foundations] + direction TB + safety[safety-net] --- cmts[comment rounds] --- fences[format-fences] --- rangef[range-formatting] + end + subgraph GRAM [parser grammar / corpus] + direction TB + corpus[corpus-check] --- pspans[spans / name-spans] --- macro[macro-items] --- classes --- rest[...12 more buckets] + end + subgraph CLIL [CLI lane] + direction TB + polish[cli-polish] --- cfg[config-discovery] --- par[parallel-files] --- cache[format-cache] + end + subgraph LINT [linter lane] + direction TB + lcore[linter-core] --- lr2[lint-rules-2] --- slint[semantic-lints] + end + subgraph SEM [semantics & index] + direction TB + vsem[vlog-semantic] --- widx[workspace-index] --- incr[incremental-index] --- persist[index-persistence] + end + subgraph REF [refactor lane] + direction TB + flist[filelist M1] --- ren[refactor-rename M2] --- prt[refactor-ports M3] --- inst[refactor-instantiate M4] + end + subgraph LSP [LSP server lane] + direction TB + srv[lucisv-server] --- caps[~30 capability features] + end + subgraph PKG [packaging & release] + direction TB + epack[editor-packaging] --- pvsix[editor-platform-vsix] --- cirel[ci-release] + end + GRAM --> FMT + corpus -. measures .-> GRAM + LINT --> FMT + SEM --> GRAM + SEM --> CLIL + REF --> SEM + LSP --> SEM + LSP --> REF + LSP --> FMT + LSP --> LINT + LSP --> CLIL + CLIL --> FMT + PKG --> LSP + PKG --> CLIL + PKG --> GRAM +``` + +### 2.1 Formatter foundations + +| edge | kind | contract | +|---|---|---| +| `case-tables ──▶ safety-net` | depends | The case harness consumes `format_source`'s post-safety-net `Err` — cases that used to produce wrong output now report `format failed:`. | +| `formatter-bug-fixes ◀──▶ safety-net` | handshake | safety-net *filed* the request (comments need positions to re-indent); formatter-bug-fixes *delivered* it: `Comment { line, col }`, `Token::trailing: Option`, `RawText { text, col }`. | +| `formatter-bug-fixes ──▶ case-tables` | depends | Fixes the five bugs case-tables found and parked; each `#SKIP` case became a live regression case. | +| `format-fences ──▶ spans` | depends | The first consumer of byte spans: a fenced region is a source slice by span. Also added `Doc::Verbatim` (leaf; emitted only right after a line break). | +| `comments-round ◀──▶ format-fences` | handshake | fences requested a span on `Meta.trailing`; comments-round delivered `Option`. Same-line fences remain deliberately inert (matcher unchanged) — documented on both sides. | +| `comments-round-2 ──▶ comments-round` | depends | Closes the bracket-position comment shapes round 1 parked; same machinery, four new `Vec` slots. | +| `corpus-bugs ──▶ corpus-check` | depends | Fixes exactly the four root causes A–D the corpus check catalogued; measured back to 0 verification errors. | +| `range-formatting ──▶ format-fences` | depends | A range is "an inverted fence": reuses `Doc::Verbatim`, `fence::collect`/`region_at`, and two helpers widened to `pub(crate)` (`line_start`, `with_trailing_comments`) — the only fence.rs change. | +| `range-formatting ──▶ spans` | depends | The planner selects items by span/line. | +| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. | +| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. | +| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. | +| `recursion-limit ◀──▶ parallel-files` | handshake | recursion-limit requires ≥8 MiB worker stacks; parallel-files built the pool with `stack_size(8 MiB)` and a test that fails if it is removed. | +| `recursion-limit ◀──▶ error-recovery` | handshake | Recovery must not reset `depth`/`links` while unwinding; error-recovery proves it with white-box + mutation tests. | +| `one-parse ◀──▶ linter-core / server-lint` | handshake | Both filed the "one parse, two tools" request; one-parse delivered `LintContext::from_parse` + `ParsedSource`, `Document` gained its `tree` field, and both front ends lint from one parse. Behavior byte-identical was the gate. | + +Standing discipline for every feature in this lane (and any feature touching +the formatter): **`verify.rs` widening is guilty until proven innocent** +(CLAUDE.md #4). The only widening ever shipped is macro-items' +backtick-`Ident` arm in `normalize` — the normalization that produced +lucisv's one real corruption (2026-08-19, shipped without attack tests). Its +repair, `trim_lines_outside_strings`, is a *narrowing*, and it shipped with +the rejection tests the widening lacked. Every other round states +"`verify.rs` untouched" and adds *rejection/attack tests anyway*. Treat that +as the template. + +### 2.2 Parser grammar / corpus lane + +`corpus-check` is the measuring instrument for the whole lane: it defines +the buckets, and each grammar feature empties one and *advances* files into +the next — a sequencing chain, not a code dependency. The lane's members: +the sixteen bucket features (macro-items, classes, **bind**, **dynamic-types**, +**types-decls**, item-misc, directives-in-lists, directives-in-instances, +dpi-export, assertions, interfaces, expressions-2, dv-statements, mop-up-2, +directive-split, ansi-first-port) plus the parser-infrastructure features +(spans, name-spans, error-recovery, lexer-cleanup, define-table, and +recursion-limit, whose edges sit in §2.1). Code edges: + +| edge | kind | contract | +|---|---|---| +| every grammar feature `──▶ corpus-check` | depends | The bucket scores and first-blocker histograms are how each round chose its target and measured its result. | +| `classes ◀──▶ vlog_parser::parse` | handshake | `parse(tokens)` became `parse(tokens, source)` — verbatim capture needs source in strict mode; every caller updated in the same change. | +| `assertions ──▶ classes` | depends | Reuses `verbatim_since`/`skip_balanced` (the constraint/covergroup capture) unchanged; adds `StmtKind::Verbatim`. | +| `directive-split ──▶ assertions / classes` | depends | Fifth producer of `ItemKind::Verbatim`; reuses the capture and `Fmt::raw_text` unchanged. | +| `item-misc ──▶ macro-items` | depends | Extends `at_macro_item` (spaced argument lists, `` `error``/`` `warning``); same verbatim contract, `RawText.col` still load-bearing. | +| `classes ─▶ macro-items` | refined in place | classes added the one-line `#(`-lookahead refinement to `at_macro_item` (the `` `uvm_component_new`` + parameterized-declaration idiom) — documented in classes' Handshakes, safety property unchanged. | +| `dynamic-types ─▶ ast::Dim` consumers | non-additive change | `Dim` became `{ kind: DimKind, span }` — the lane's **only** vector-element/shape change in history; every consumer was found by grep and updated (`Fmt::dim`, `bind_dims`, the spans walker). The precedent §3.3's "prefer additive fields" rule exists to avoid repeating. | +| `mop-up-2 ──▶ macro-items / dv-statements` | depends | Delivers the macro-followed-by-symbol fix dv-statements filed against macro-items, plus `new obj` (the expressions request from dv-statements) and base-only numbers. | +| `directives-in-instances ──▶ directives-in-lists` | depends | Reuses `ListDirective` and `take_list_directives` verbatim; same additive-fields shape chosen for the same blast-radius reason. | +| `dpi-export ─▶ dv-statements` | sequencing | Handed `csr_utils_pkg.sv` on (its next blocker was a `foreach`, a dv-statements shape). Typical of many one-way "your bucket now" notes across this lane. | +| `interfaces ─▶ expressions-2` | sequencing | Two files advanced to `->` implication and drive strengths; expressions-2 emptied that bucket. | +| `classes ◀──▶ class-semantics` | handshake | classes shipped with the honest gap "no name inside a class body is indexed"; class-semantics closed it (see §2.5). | +| `classes ─▶ format-fences` | open request | `fence::scan_nested` has no `Class` arm, so a fence inside a class body is inert **for the formatter** (the `protected_regions` line-scan backstop still protects `--fix`). Filed, not fixed — §2.9. | +| `ansi-first-port ◀──▶ type-definition` | handshake | type-definition filed the "first port with no direction doesn't parse" request; ansi-first-port delivered it (parser + one `bind_data_type` arm + one `type_span` tweak), and type-definition's tests flipped. | +| `lexer-cleanup ──▶ error-recovery / lint-rules-2` (QA logs) | depends | Fixes three lexer gaps: `@(* )` (TODO §1) plus the BOM and non-ASCII-honesty findings those two QA rounds filed; adds `ParsedSource::lex_error()` so `lucisv check` stops silently passing unlexable files. | +| `error-recovery ─▶ lucisv-server / linter-core` | depends (downstream) | `parse_source_tolerant` is the entry point the whole LSP and the linter stand on; the strict/tolerant split (shared grammar, no second parser) is the contract. | +| `name-spans ◀──▶ vlog-semantic` | handshake | vlog-semantic filed request 1 (spans on ~15 declaring nodes); name-spans delivered it, shrinking `scan.rs` to the `DataType` case (still open — §2.9). | +| `spans ─▶ everything positional` | depends | Byte ranges + `LineIndex` are the prerequisite named by TODO §6 for the LSP effort and by fences/range formatting. | + +Also uniform in this lane: each new AST variant lists its exhaustive-match +blast radius (formatter arm, `bind.rs` arm, `spans.rs` arm) — that checklist +**is** the interface cost of touching `ast.rs`, and §3.3 restates it as a +rule. `vlog_linter`'s `visit.rs` is catch-all **for compilation only**: a new +variant that *contains items or statements* still needs an arm there, or no +AST lint rule ever descends into it (dv-statements added two such arms; +classes' missing one was a filed coverage gap, closed by lint-rules-2). + +### 2.3 CLI lane + +A clean promise chain — each feature consumed the previous one's written +promise: + +| edge | kind | contract | +|---|---|---| +| `config-discovery ──▶ cli-polish` | depends | Consumed `Options.stdin_filename` exactly as promised (discovery anchor only) and `Options.exclude` as the CLI layer config patterns append to. | +| `parallel-files ◀──▶ cli-polish` | handshake | cli-polish flagged its hook-swapping `catch_panic` as single-thread-only; parallel-files replaced it with one startup hook + thread-local flag. **Anyone editing `catch_panic` must keep it that way.** | +| `parallel-files ──▶ config-discovery` | depends | Consumed the promise that config resolution happens up front in `gather`, producing the exact `Vec<(PathBuf, Config)>` work list a `par_iter` wants. | +| `format-cache ──▶ parallel-files` | depends | Consumed the promise that `process_file` is the per-file unit of work and `Outcome` the place a `Cached` bucket goes. | +| `format-cache ──▶ config-discovery` | depends | Consumed the cache-key promise: key includes resolved per-file settings (values, not config-file identity). | +| `format-cache ─▶ every output-changing feature` | standing promise | **Any change to formatter output must bump the workspace version** or warm caches keep stale verdicts. Same discipline as ruff/black. | +| `cli-filelist ──▶ filelist` | depends | Reuses `lucisv_core::filelist::read` unchanged (M1 explicitly parked the `-f` flag for this round); drops `incdirs`/`defines` as meaningless to a non-preprocessing formatter. | +| `cli-polish / linter-core ─▶ corpus-check, CI users` | standing promise | The 0/1/2 exit-code contract is frozen; new modes map onto it, never extend it. | +| `lucisv-core-lift ◀──▶ lucisv-server` | handshake | Delivered the server's two filed requests (config discovery + ignore-aware walk) by lifting `config.rs`/`walk.rs` into `lucisv_core` unchanged; CLI behavior byte-identical. | + +### 2.4 Linter lane + +| edge | kind | contract | +|---|---|---| +| `linter-core ──▶ error-recovery` | depends | Lints the tolerant tree so unparseable files are still linted for what is visible. | +| `linter-core ──▶ format-fences` | depends | CLI `--fix` reads `fence` (already `pub`) to stay out of fenced regions — one answer to "what is fenced", not two (later formalized by shared-fence-filter). | +| `lint-harness ──▶ linter-core` | depends | Consumes only the public API; the `.lint` case format + "marker naming a dead rule fails the suite" is the enforcement of rule-name stability on the test side. | +| `lint-harness ──▶ safety-net` (via dev-dep) | depends | Every fix's output must be something `format_source` accepts. | +| `lint-rules-2 ◀──▶ classes` | handshake | Closes the classes handshake: `visit.rs` now walks class bodies, so the four AST rules see class members. | +| `semantic-lints ──▶ vlog-semantic` | depends | The three symbol-table rules; new (justified) crate dep `vlog_linter → vlog_semantic`; lazy analysis; the lead's pre-authorization to modify `vlog_semantic` went **unused** (recorded so it is not read as taken). | +| `semantic-lints ──▶ one-parse` | depends | Reaches the server and CLI through the existing one-parse path (`LintContext::semantics()` / `with_semantics`). | +| `server-lint ──▶ linter-core` | depends | Protocol wiring only; relies on the three written promises (stable names, no panics/writes, sorted findings). | +| `server-lint ◀──▶ shared-fence-filter, one-parse` | handshake | Both of server-lint's filed requests were delivered by those rounds (fence-safe quick fixes; lint-from-Document). | + +### 2.5 Semantics & index lane + +| edge | kind | contract | +|---|---|---| +| `vlog-semantic ──▶ error-recovery, spans` | depends | Tolerant trees as input; span conventions throughout. | +| `workspace-index ──▶ vlog-semantic` | depends | Finishes `ExternalCandidate`s against what every file declares; the `paths` spelling contract is the coupling — if `bind.rs`/`resolve.rs` change a path's spelling, `workspace.rs::follow_one` changes with it. | +| `workspace-index ──▶ define-table` | depends | Each file's `` `define`` table is an index column (`find_define`). | +| `class-semantics ◀──▶ classes` | handshake | Delivers the filed gap; adds `SymbolKind::Class`, `ScopeKind::Class`, `InheritedCandidate` — with the two named compile-fix arms in `lucisv_server` (`tokens.rs`, `symbols.rs`). | +| `class-semantics ──▶ name-spans` | depends | Built on the delivered span fields; keeps `src[name_span] == name` corpus-asserted. | +| `overlay-promotion ◀──▶ type-definition` | handshake | Delivers type-definition's request 1: a **type-position** miss carries the bare name as its last candidate path (both miss spellings), so the overlay answers interfaces and package-less classes; type-definition then deleted its `indexed_type` fallback. Value-position misses unchanged — that asymmetry is the contract. | +| `type-hierarchy ──▶ overlay-promotion` | depends | The whole cross-file half is overlay-promotion being consumed at the `extends` offset. | +| `incremental-index ◀──▶ code-lens, hierarchy, type-hierarchy` | handshake | Delivers the jointly-filed edge tables: `instantiations_of` / `subclasses_of` recorded at build time; `callers_of_each` and `subtypes` became lookups (92 ms→0.26 ms, 82 ms→0.71 ms). Census policy carried over by construction: the walks (`instantiations.rs`, `classes.rs`) were **lifted into `vlog_semantic`**, not copied. | +| `incremental-index ──▶ indexing-ux` | depends | Amends the event story: a one-file update reports no events (one parse is not a scan); invariant: `update_file` yields byte-for-byte the index a full rebuild would (`fingerprint` is the witness; `update_one_checked` the test form). | +| `index-scope ◀──▶ indexing-ux` | handshake | Closes indexing-ux's QA finding by making `IndexBuilder` order-insensitive (sort/dedup in `finish`); `index_order` survives for the progress denominator. | +| `index-scope ──▶ filelist` | depends | Rung 1 (a filelist defines the scope exactly) is untouched; rungs 2/3 of the scope ladder were re-written (folder-scoped, open-file-first) — the ladder itself is the contract, documented in both READMEs. | +| `index-persistence ──▶ incremental-index` | depends | `update_one` writes its record through via `WorkspaceIndex::facts_for` (no double parse). | +| `index-persistence ──▶ format-cache` (lucisv_core) | depends | Reuses `lucisv_core::cache::content_hash` — one FNV-1a shared with the format cache, not a second copy. Also one additive `vlog_parser` touch: `DefineTable::from_entries` + `PartialEq`/`Eq` derives, so a record restores a table without re-reading a file. | +| `index-persistence ◀──▶ indexing-ux` | handshake | `IndexEvent::Cached` — a new variant, so every consumer is forced to say what it does with an unparsed file; the end message names the cached count. | +| `port-detail-spans ◀──▶ index-persistence` | handshake | A declaration record grew two numbers (the detail span, written unconditionally as `0 0` for the `None` every ordinary declaration has), so **`FACTS_FORMAT` went 2 → 3** and every store written by an earlier build is discarded whole rather than read field-shifted. The bump *is* the contract: `index_cache.rs`'s header line carries the number, and the reader's `done()` check is a backstop, not a version scheme. | +| `define-table ◀──▶ macro-expansion` | handshake | What began as free-to-change became contract at M14: params stored **as written**, `NAME()` = `Some(vec![])` — `expand.rs` counts arguments against them and declines on mismatch. | + +### 2.6 Refactor lane (the M-plan) + +`refactor` is the umbrella plan; M1–M4 are its milestones plus two follow-ups. + +| edge | kind | contract | +|---|---|---| +| `filelist (M1) ──▶ refactor` | depends | The scope story: a `.f` filelist is the project file; parser in `lucisv_core` (so the CLI later reuses it — it did, cli-filelist), scope ladder in the server. | +| `refactor-rename (M2) ──▶ vlog-semantic / workspace-index` | depends | Every edit from a resolved span; whole-edit verification; refusals from `Resolution` variants. | +| `refactor-rename ◀──▶ vlog_semantic` | handshake | The one authorized cross-module change of M2: `Target::Declaration` + `use_end_label` (end labels must rename or the output doesn't compile). Strictly additive; logged in vlog-semantic's work log. | +| `refactor-ports (M3) ──▶ refactor-rename` | depends | Reuses M2's `check`/`Scope`; the two preprocessor scans were factored to return *sites* so M3 words its own warnings without inheriting M2's text (M2's wording pinned by its 48 tests). | +| `refactor-instantiate (M4) ──▶ workspace-index, editor-scopes` | depends | Plans from the index's real definitions; the item-position gate is built on `pairs::analyze`'s published output only. | +| `apply-edit ──▶ refactor-ports` | depends | The port commands now *push* `workspace/applyEdit` (the protocol's actual mechanism) instead of answering the edit as a result no client applies. `ports::execute`'s signature and behavior unchanged — the only `ports.rs` edit was correcting a now-false doc comment, so this is consumption, not a handshake. | +| `references-nav ──▶ refactor-rename` | depends | `find_references` is `Scope::collect_occurrences` lifted out of `collect_edits` — the references list and a rename's touch-set **cannot disagree**, by construction (deliberately not moved to `vlog_semantic`; the walk needs refactor-crate concerns). | + +### 2.7 LSP server lane + +`lucisv-server` is the trunk; everything below extends it. Edges to +engine-lane features are listed above; this table is the server-internal web. + +| edge | kind | contract | +|---|---|---| +| `editor-scopes ─▶ (many)` | depends (consumed by) | `pairs.rs` — one stack matcher, eight consumers today: documentHighlight, missing-closer diagnostics, `lucisv/scopePairs` rainbow, folding (references-nav), the item-position gates (completion-core / refactor-instantiate), on-type-formatting's keyword tables, inline-templates' unmatched-`begin` check, expand-selection (`selection.rs`). The `RULES` table + guard list is the shared truth; a keyword change means re-checking it. | +| `editor-scopes ◀──▶ editors/vscode` | handshake | The `lucisv/scopePairs` wire shape (pinned as literal JSON in a test) and the `lucisv.rainbow*` colour ids that must match between `package.json` and `extension.js`. | +| `completion-core ──▶ define-table, vlog-semantic, workspace-index, refactor-instantiate` | depends | Five tiers over existing facts; the parser widening (`KEYWORDS` export) is its one engine touch. Deliberate duplication recorded: `visible_symbols` vs `ports::visible_in` share an idea, not code. | +| `completion-templates ──▶ completion-core, editor-scopes` | depends | Tier 3; `templates.rs` is data + one renderer; tier digits moved (only e2e's word-tier assertion cared). Also consumes `vlog_refactor::Layout` (M4's `{ base, step }`), reused rather than re-declared, so a skeleton and a template indent by one type. | +| `completion-templates ◀──▶ editor-snippets` | handshake | Nine overlapping statement/block snippets were **removed** from `editors/vscode/snippets/*.json` when the server started offering them as tier 3; both READMEs' prefix tables are the shared truth. A template added server-side must check the static set, and vice versa. | +| `inlay-hints ──▶ refactor-instantiate` | depends | Reads exactly the `module_definition` + `instantiation_plan` facts M4 published (the `PlanPort`/`PlanParam` name lists signature help reads); every plan refusal is swallowed silently — a hint has no place for a sentence. | +| `inline-templates ──▶ completion-templates, editor-scopes` | depends | Same skeletons as ghost text (LSP 3.18 `inlineCompletion`, `lsp-types` `proposed` feature); relative-indent contract — the client finishes the whitespace; round 2 dropped its `layout_at` consumption (re-privatized). | +| `hover/define ──▶ define-table`; `macro-expansion ──▶ define-table + hover` | depends | See the §2.5 handshake; `expand.rs` is deliberately workspace-blind (two strings + a `Define`). | +| `include-nav ──▶ filelist` | depends | First consumer of `incdirs`; the include graph (build/resolve/reachable, one `scan` shared by links, definition and the graph) plus hover's reachability overlay — `find_define`'s contract explicitly unchanged. | +| `file-operations ──▶ include-nav, file-watching` | depends | `resolve_as_if` added so willRename asks the *one* resolution engine about a future filesystem; reuses `watch::watched` + `SOURCE_GLOB` as the one scope predicate. | +| `file-watching ──▶ filelist / lucisv-core-lift` | depends | `SOURCE_GLOB` pinned to `walk::EXTENSIONS` by test; watches the filelist itself; re-registers on filelist change. | +| `folders-and-config ──▶ editor-settings` | depends | Adds the pull door (`workspace/configuration`) wrapped back into the push shape so there is exactly one settings parser; `Pending` generalizes apply-edit's `applying` map. | +| `editor-settings ◀──▶ lucisv-core-lift` | handshake | The four-rung precedence ladder (lucisv.toml > `lucisv.*` settings > tab size > defaults), per key — the reason the ladder can exist is the lifted `Discovery`. `will-save-wait-until` reuses the ladder minus rung 3. | +| `incremental-sync ◀──▶ pull-diagnostics` | handshake | One `didChange` = one `set_document` = one generation bump, however many ranges — pinned by test; the generation **is** the pull model's `resultId`. `semantic-tokens-delta` promises the inverse: token requests never bump it. **Amended 2026-08-28 by change-debounce**: one *flush* is one `set_document`, one bump and one publish per dirty buffer — however many ranges *and* however many notifications it coalesced. | +| `change-debounce ◀──▶ incremental-sync, pull-diagnostics` | handshake | The amendment above. A `didChange` composes its ranges against the *pending* text when there is one (`sync::apply_changes` unchanged) and defers only the analysis; the flush happens at the next request, the next non-`didChange` notification, or a 150 ms quiet period on the `cancel-request` queue (`recv_timeout` — no thread, no timer object). Observable: intermediate diagnostics states are no longer published, pinned in `tests/e2e.rs`. | +| `port-detail-spans ──▶ hover-declarations` | depends | The second fenced section, and the comment attached to each, are built on hover-declarations' snippet machinery and its `spells_exactly` guard, both unchanged. `nav::definition` returns the detail location first so a jump and the card cannot disagree. | +| `hover-declarations ◀──▶ vlog_semantic` | handshake | `Semantics::symbols_named` (§1.2) replaced `hover::live_symbol`'s and `nav::indexed_references`' scan-every-symbol loops. Behavior-identical **because the lookup preserves declaration order** — the tie-break between two live declarations of one name is pinned on both sides. | +| `cancel-request ──▶ lsp-server pin` | depends | See §1.2; queue/burst exists because the pinned transport is a rendezvous channel. | +| `work-done-progress ──▶ indexing-ux` | depends (then) | w-d-p put up the bar; indexing-ux made it count (`IndexEvent` stream); index-persistence added `Cached`. | +| `large-file-mode ◀──▶ semantic-tokens-delta` | handshake | The windowed lexing serves `semanticTokens/range`; on a large buffer `full`/`full/delta` must answer an ERROR (`ServerCancelled`/`ContentModified`) or the client stops asking the range provider — two sides pinning one wire behavior. `Document::large` is structurally a full `Document` (all fields valid, empty) so no handler changes — the obligation lands on **future** handlers that read `doc.text` (dispatch-table test enforces). | +| `lsp-318-extras ──▶ range-formatting` | depends | `rangesFormatting` is a thin adapter over the same n-range `LineRanges` engine `--lines` uses; hand-rolled params because `lsp-types` 0.97 lacks 3.18. | +| `on-type-formatting ──▶ range-formatting, editor-scopes` | depends | `;` goes through `format::range_formatting` unchanged; `\n` answers indent only, computed from `pairs.rs`'s own keyword tables (three items widened to `pub(crate)`) — one reader's answer for "what opens a scope". | +| `interactive-latency ──▶ change-debounce, editor-scopes, selection-range, on-type-formatting, completion-core, inline-templates` | depends | Round 2 of the perf work (`docs/perf/README.md`). It measures the flush change-debounce coalesces and the round trip it defers, and it replaces one token *sweep* with one token *binary search* in `selection.rs`, `on_type.rs`, `completion.rs` and `inline.rs`. No answer moved — each swap is pinned against the sweep it replaced at every byte — so none of those five features' contracts changed; what they now share is `state.rs`'s two search primitives and the ordering property of `tokenize`'s output they rest on. | +| `interactive-latency ◀──▶ lucisv-server` | handshake | Two free functions, `first_token_reaching` and `first_token_from`, are published from `state.rs` beside `Document::token_at`; that is where the monotonicity argument every caller depends on is written down, and `state::tests::the_token_stream_rises_and_never_overlaps` is the test that fails first if `vlog_parser` ever breaks it. `tests/e2e.rs`'s `Live::finish` now returns its publish count (existing callers ignore it), and `perf::generated_module` has a copy in `tests/e2e.rs` — a binary crate's modules are unreachable from an integration test — which must stay the same shape as the original. | +| `selection-range / linked-editing ──▶ spans, name-spans` | depends | Pure arrangements of existing ranges; linked-editing's table documents exactly which constructs carry both spans (and which verbatim ones can't — `program`, property/sequence, covergroup). | +| `type-definition ──▶ nav / overlay-promotion / ansi-first-port` | depends + 2 delivered handshakes | Now literally `nav::definition` at the type name's offset; both of its filed requests landed (§2.2, §2.5). | +| `hierarchy ◀──▶ inlay-hints` | handshake (shared walk) | The instantiation walk was lifted out of `inlay.rs` into a shared module (now `vlog_semantic::instantiations`) rather than copied — the two answers cannot drift; inlay's 34 tests are the regression net. | +| `code-lens ◀──▶ hierarchy` | handshake | code-lens split `incoming` into the batch primitive `callers_of_each` so lens and hierarchy share one census; `incoming` is a one-element call into it and its behavior (empty-name guard included) is pinned unchanged. Lens and hierarchy views can never disagree; refresh rides `reindex()` after the bar comes down. | +| `server-lint / pull-diagnostics / editor-scopes ──▶ diagnostics.rs` | depends | One `diagnostics::all` composition: parse errors + missing-closer warnings + lint warnings, one publish (or one pull) per change; `send_diagnostics` is the single push gate so a pulling client is never served both models. | + +### 2.8 Packaging & release lane + +| edge | kind | contract | +|---|---|---| +| `editor-packaging ◀──▶ lucisv-server` | handshake | The spawn contract (§1.2) plus the fence-tag contract: every markdown code block the server emits opens ```` ```systemverilog ```` — three call sites pin the string; the grammar registers the id. | +| `editor-packaging ◀──▶ vlog_parser` | handshake | The grammar↔`KEYWORDS` test lock (§1.2). | +| `editor-snippets ──▶ editor-packaging` | depends | Static `contributes.snippets` keyed to the two language ids the manifest declares; consumes nothing from the server *at runtime* (works with the server missing — deliberate). Its **content** is negotiated against the server's template tier — see the `completion-templates ◀──▶ editor-snippets` handshake in §2.7. | +| `editor-platform-vsix ──▶ editor-packaging, release-prep` | depends | Changes *which path* is spawned, never how; consumes `release.sh`'s artifact naming; promises the three `bin/` layout shapes to `extension.js` (asserted with `unzip -Z1` per package). | +| `editor-platform-vsix ◀──▶ editor-marketplace-page` | handshake | The marketplace rewrite must keep the seven-package install table and the two bundled-binary layout sentences (re-applied additively during the concurrent rounds). | +| `ci-release ──▶ release-prep / editor-platform-vsix` | depends | Workflow = one-liners over `tools/`; consumes the exact seven `.vsix` names (`prune_release_assets.sh` checks each), the `CHANGELOG.md` heading convention, tag == workspace version. | +| `release-prep ──▶ editor-packaging` | depends | `release.sh` runs `smoke.js` as its gate; closed the missing-`LICENSE` item editor-packaging filed. Version lives in exactly four files — a promise to everyone. | +| `editor-marketplace-page ──▶ lucisv-server` (docs) | depends | The Details page mirrors the shipped capability table in the server's README; drifts if that table does. | + +### 2.9 Open handshakes (filed, not yet delivered — claim before working) + +These are the known coordination points. An agent picking one up should +update the filing README(s) and this file. + +| # | request | filed by | owner it waits on | +|---|---|---|---| +| 1 | `lucisv_core::path::normalize` — one `.`/`..` folding instead of three private copies (`filelist::Reader::normalize`, `config::Discovery::absolute`, `includes::normalize`, the last now `pub`) | include-nav; restated by file-operations | lucisv_core | +| 2 | A span for `DataType` (and `ExprKind::Cast::ty` tails) — the last thing keeping `vlog_semantic/src/scan.rs` alive | vlog-semantic (item 2); restated by class-semantics | vlog_parser | +| 3 | `fence::scan_nested` has no `ItemKind::Class` arm — formatter fences are inert inside class bodies (the `--fix` backstop still holds; asymmetry errs hands-off) | classes | vlog_formatter (fence.rs) | +| 4 | A `lint` key in `lucisv.toml` (`[lint.]` config; selected-rules list) with CLI>config precedence | linter-core; restated by lint-rules-2, semantic-lints, server-lint | config-discovery / lucisv_core | +| 5 | `lucisv check --rules-doc` printing `rules_markdown()` | lint-rules-2 | crates/lucisv | +| 6 | Workspace-wide "does any file mention this name" query — the precondition for the semantic lints defaulting on (cross-file hierarchical use is their one false-positive mode) | semantic-lints | vlog_semantic (index) | +| 7 | `SymbolKind::Interface` (interfaces currently indexed as `Module`; modport/clocking names unbound) | interfaces | vlog_semantic (+ mechanical arms in server `symbols.rs`/`hover.rs`) | +| 8 | Symlink-cycle detection in the shared walk (both front ends exposed; wants its own round — it changes CLI behavior) | lucisv-core-lift | lucisv_core | +| 9 | Chasing `InheritedCandidate` through the member tables (in-file and cross-file) + hover for `extends` — *partially advanced*: overlay-promotion made `resolve_external` answer an `InheritedCandidate` from its paths; the member-table chase and the hover remain absent | class-semantics | vlog_semantic | +| ~~10~~ | ~~`Fmt::raw_text`'s string-crossing path emits a `Doc::Text` carrying newlines~~ — **delivered 2026-08-26 (`53f2269`)**: both `raw_text` and the parameterized-type `#( … )` now emit `Doc::Inline`, whose printer arm resumes measuring from the text's own last line. directive-split's README (QA round 3 note) still documents it as open and should be struck there too | directive-split QA | ~~vlog_formatter~~ done | +| 11 | Corpus scripts match `parse error:` / `lex error:` / `verification failed:` textually; a structured `--output-format json` for format mode would remove it | corpus-check | crates/lucisv | +| 12 | `vlog_refactor::rename::Scope::build` re-derives sort-and-dedup by hand; could call `index_order` | indexing-ux | vlog_refactor | +| 13 | Anonymous-aggregate members (`enum {A,B} x;`) not declared as symbols — hover/definition gap | types-decls | vlog_semantic | +| 14 | A `program` node with `name_span`/`end_label_span` (today it lands in `Error`/verbatim), which would let linked-editing serve it with one arm | linked-editing | vlog_parser | +| 15 | Bind semantics: whether a `bind`'s target scope and connections should resolve through the workspace index (today only the instantiated module name is recorded) | bind | vlog_semantic | +| 16 | DPI/package re-export halves as real references (`export pkg::item` doesn't resolve; `*::*` has `"*"` as its package name, which nothing expects) | dpi-export | vlog_semantic | +| 17 | Inline aggregate as a parameter-override *argument* (`m #(.T(struct packed { logic a; })) u ();`) is rejected in expression position; M4's `instantiation_plan` drops such a `parameter type` default rather than emit unparseable text | refactor-instantiate (gap 1; its gap 2 was delivered by ansi-first-port) | vlog_parser | + +---## 3. Combined graph — features mapped onto modules + +### 3.1 Feature → primary-home matrix + +Where a feature's code chiefly lives (its README remains the authority on +exact file scope). Cross-module touches are recorded per-feature in §2 and in +each feature README's Handshakes; this matrix names only the primary home. +Grammar-lane features (*italicized*) routinely add exhaustive-match arms in +other crates — see §3.3's `ast.rs` row — though not always a formatter arm: +directive-split and ansi-first-port shipped with `vlog_formatter/src` +untouched, reusing existing arms. + +| module | features whose home it is | +|---|---| +| `vlog_parser` | spans, name-spans, recursion-limit, error-recovery, define-table, lexer-cleanup, and the grammar lane: *macro-items*, *classes*, *bind*, *dynamic-types*, *types-decls*, *item-misc*, *directives-in-lists*, *directives-in-instances*, *dpi-export*, *assertions*, *interfaces*, *expressions-2*, *dv-statements*, *mop-up-2*, *directive-split*, *ansi-first-port* (most also add formatter arms — parser+formatter pairs by default; directive-split and ansi-first-port reused existing arms and left `vlog_formatter/src` untouched) | +| `vlog_formatter` | safety-net (`verify.rs`), case-tables, formatter-bug-fixes, corpus-bugs, comments-round, comments-round-2, alignment (`align.rs`), format-fences (`fence.rs`), range-formatting (`range.rs`), shared-fence-filter | +| `vlog_semantic` | vlog-semantic (`bind`/`resolve`/`model`), workspace-index (`workspace.rs`), class-semantics, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` in `bind.rs`/`model.rs`/`workspace.rs`, the `facts.rs` codec + `FACTS_FORMAT` bump, and `Semantics::symbols_named` in `lib.rs`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`), incremental-index (`update_file`, edge tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives) | +| `vlog_linter` | linter-core, lint-harness, lint-rules-2, semantic-lints (`signals.rs`), one-parse (`context.rs`) | +| `vlog_refactor` | refactor (plan), refactor-rename, refactor-ports, refactor-instantiate, references-nav (engine half) | +| `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`) | +| `lucisv` (CLI) | cli-polish, config-discovery (wiring), parallel-files, cli-filelist, linter-core (CLI half in `lint.rs`), one-parse (`lint.rs` parses once via `ParsedSource`), format-cache (wiring), release-prep (`--version` contract) | +| `lucisv_server` | lucisv-server (trunk), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core→`completion.rs`/`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring→`rename.rs`/`ports.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server.rs`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs`, pull-diagnostics→`diagnostics.rs`+`server.rs`, semantic-tokens-delta→`tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, change-debounce→`server.rs`, perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion.rs`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` | +| `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line) | +| `tools/` + CI | corpus-check, release-prep, ci-release, editor-platform-vsix (staging), range-formatting (`lucisv-changed.sh`) | + +### 3.2 The combined picture + +```mermaid +graph TD + subgraph parser [vlog_parser] + gram[grammar-lane features] --- pinfra[spans / name-spans / recursion-limit / error-recovery / define-table] + end + subgraph fmt [vlog_formatter] + net[safety-net verify.rs] --- fmtf[fences / range / alignment / comment rounds] + end + subgraph sem [vlog_semantic] + core[vlog-semantic] --- idx[workspace-index + incremental / persistence / scope / ux] + end + subgraph lint [vlog_linter] + lc[linter-core + rules + harness + semantic-lints] + end + subgraph refac [vlog_refactor] + ms[M2 rename / M3 ports / M4 instantiate / references] + end + subgraph corelib [lucisv_core] + cw[config + walk + filelist + cache] + end + subgraph cli [lucisv CLI] + clif[cli lane features] + end + subgraph srv [lucisv_server] + caps[capability features (~30)] + end + subgraph ed [editors/vscode + tools/CI] + pkg[packaging lane] + end + gram --> fmt + fmt --> parser + sem --> parser + lint --> parser + lint --> sem + refac --> parser + refac --> sem + srv --> parser + cli --> parser + cli --> corelib + cli --> fmt + cli --> lint + srv --> corelib + srv --> sem + srv --> refac + srv --> fmt + srv --> lint + pkg --> srv + pkg --> cli +``` + +Reading it feature-side: a grammar feature is by default a +**parser+formatter pair** (new AST + its layout, plus minimal arms in +`bind.rs`/`spans.rs`) — though one that reuses an existing arm ships with the +formatter untouched (directive-split, ansi-first-port); an index feature is a +**vlog_semantic + lucisv_server pair** (the data structure and the +events/settings around it); a capability feature is usually **server-only +plus one manifest line** (one handler module + `main.rs` capability + often a +`settings.rs` field, which then owes an `editors/vscode/package.json` +`contributes.configuration` entry — the choke point whose mismatches are +silent); a packaging feature is **editors/tools-only, save for the two pins +it owns in Rust** (editor-packaging's `tests/grammar.rs`, release-prep's +`--version` shape). Those shapes are the default that makes the lanes +parallel-safe — not an invariant; say in your scope which arms you actually +owe. + +### 3.3 Choke points — files where features meet + +These are the highest-contention interfaces. When two agents' scopes both +name one of these, they are not parallel — serialize or split the file's +ownership explicitly. + +| choke point | owner (feature) | consumers | the rule | +|---|---|---|---| +| `vlog_parser/src/ast.rs` | the grammar lane collectively | formatter, semantic, linter, refactor, server, `tests/spans.rs` | A new variant costs, at minimum: a `format.rs` arm, a `bind.rs` arm, a `spans.rs` arm. `visit.rs` is catch-all for compilation only — a variant containing items/statements still needs an arm there or AST lint rules never see inside it. Prefer **additive fields / parallel vectors** over changing vector element types — that is why `ListDirective` sits beside the lists instead of inside them (two rounds chose it independently for blast-radius reasons). | +| `vlog_formatter/src/verify.rs` | safety-net | every formatter feature; the CLI's exit-2 promise | CLAUDE.md invariant #4. Never widen a normalization without masked-corruption attack tests; the standing pattern is "untouched + rejection tests anyway". The single widening in history is macro-items' backtick-`Ident` arm in `normalize` — which produced lucisv's one real corruption; its repair, `trim_lines_outside_strings`, is a *narrowing*, and the pattern to copy: the widening shipped without attack tests, the fix shipped with them. `line_starts_inside_string` is the one definition of "which line breaks are data" — both `format.rs` and `verify.rs` must read it. | +| `vlog_formatter/src/fence.rs` | format-fences | range-formatting, shared-fence-filter, CLI `--fix` (`lucisv/src/lint.rs`), server quick fixes (`lucisv_server/src/lint.rs`) | `protected_regions`/`is_protected` are the **only** supported way to ask "may an automatic edit touch these bytes". One answer, **two** front ends — and `vlog_linter` is deliberately not one of them (it stays fence-blind; the filter lives in each front end). Open gap: no `Class` arm in `scan_nested` (§2.9-3). | +| `lucisv_server/src/pairs.rs` | editor-scopes | documentHighlight, missing-closer diagnostics, scopePairs rainbow, folding, completion gates, on-type indent, inline-templates, expand-selection (`selection.rs`) | The `RULES` table + no-closer guard list is shared truth. Any keyword added to/removed from `token.rs` requires re-checking it (a word that stops being a keyword silently stops being matched). | +| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, indexing-ux, incremental-index, index-persistence, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`) | every handler | `Workspace` is immutable through request handlers (no caches added by handlers — hierarchy/inlay/type-hierarchy all state it). The scope ladder (filelist > `index.scope: "workspace"` > folder-scope, with the rootless flat sibling read as folder-scope's one exception; buffers overlay everything) is the contract; `update_one`'s answer must equal a full rebuild's (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. | +| `lucisv_server/src/settings.rs` | editor-settings | folders-and-config, indexing-ux, index-scope, index-persistence, inline-templates, will-save-wait-until, filelist, large-file-mode | One parser for both doors (push and pull, via `from_section` re-wrapping). Every key drops garbage independently; defaults that are not "silence" (1 MiB cap, log on, persist on, 4 MiB large-file threshold) are hand-written in `Default`. `set_client_settings` returns whether a reindex is owed — new keys must decide that question explicitly. | +| `vlog_semantic/src/workspace.rs` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope | server state, hierarchy/lens/type-hierarchy, refactor, completion | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change, edge tables built by the same lifted walks the handlers use. | +| `vlog_parser/src/token.rs` keyword table | completion-core (`KEYWORDS` export) | lexer, pairs.rs, editor grammar (test-locked), completion | Adding a keyword = lexer change + `pairs.rs` re-check + a hand edit to the grammar (`tests/grammar.rs` names the missing word) + potentially `verify.rs`-adjacent behavior. dv-statements added `randcase`/`let` to `is_keyword` and recorded it as shared with the adjacent lexer-cleanup round — the precedent for treating this file as coordinated even between back-to-back rounds. | +| `editors/vscode/package.json` | editor-packaging | editor-settings, editor-scopes (colour ids), editor-snippets, index-persistence, platform-vsix, marketplace-page | Settings/colour/snippet ids referenced from `extension.js` or the server must move in lockstep; mismatches are *silent* (VS Code ignores unknown ids). Version number is one of the four version files. | +| `tools/release.sh` artifact names | release-prep / editor-platform-vsix | ci-release (`prune_release_assets.sh`), `audit_artifacts.sh`, extension `bin/` layouts | Renaming a `.vsix` is a two-file change (`release.sh` + `prune_release_assets.sh`'s suffix list); renaming a per-triple binary is a two-file change (`release.sh` + `audit_artifacts.sh`, which skips `.vsix` and hard-fails on an unknown binary name). Get the wrong pair and the release fails by name. | +| The frozen CLI contract | cli-polish | corpus scripts, CI users, every new CLI mode | Exit codes 0/1/2 forever; stdout stays machine-readable (JSON mode prints exactly one array; warnings to stderr). | + +### 3.4 Working rules distilled for parallel agents + +1. **Pick lanes, not files.** The eight lanes in §2 are the intended + parallelism. Two features in one lane usually share a choke point (§3.3); + check before spawning both. +2. **A grammar feature is a pair by default** (parser + formatter arms + + minimal `bind.rs`/`spans.rs` arms) — unless it reuses an existing arm, as + the verbatim producers and ansi-first-port did. Say which arms you owe in + the feature scope up front; the compile-fix arms in other crates are + legitimate and should be listed in Handshakes, per the established + pattern. +3. **`cargo fmt` per package** (`-p a -p b`), never `--all`, while another + agent is live — this rule already saved two concurrent rounds + (directives-in-lists, dynamic-types). +4. **Cross-module wants are filed, not done.** Write the request in your + README's Handshakes, add it to §2.9 here, and stop — the lead routes it. + Delivered requests get struck through in the filing README with a pointer + (the ~~strikethrough~~ + "Delivered by X" convention is established). +5. **Wire shapes and names are pinned by tests, so change them by test**: + scopePairs JSON, the systemverilog fence tag, the seven `.vsix` names, + the grammar/KEYWORDS lock, rule names, exit codes, message prefixes + (§2.9-11 until structured output lands). +6. **Anything touching formatter output**: attack tests for any + verify-adjacent machinery, and a version bump or the format cache serves + stale verdicts (§2.3). + +--- + +*Maintenance: this file is derived documentation. When a feature round adds, +delivers, or supersedes a handshake, update the relevant table (§2.9 +especially) in the same round, the way TODO.md checkboxes are kept current.*