Files
lucioandClaude Fable 5 bf9170a850
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 20s
A scope widen indexes the folders it added, not everything again
Every F12 jump into a new folder didOpen-widened the scope and re-ran
a full rescan of all folders accumulated so far, growing with browsing
(opentitan, warm: 120-169 ms per jump, ~90 ms of it re-opening and
decoding the whole persistent store). widen_of chooses: pure folder
adds take a widen scan over only the new files (absorbed into the live
index/candidates/includes, open buffers refreshed from held analyses,
store handle kept, no compaction); anything else still takes the whole
rescan; mid-scan defers to one whole follow-up. Jumps now cost the new
folder alone (12-44 ms flat), first definition of a session 99.7 ->
0.9 ms. IncludeGraph stores edges as the filesystem answered them and
re-spells on relearn so a newly scoped file lends its spelling to
earlier edges. Watcher-coverage narrowing documented: watcher-less
clients lose the widen's incidental disk re-read, same staleness class
as the save path since 2026-08-27. QA was stopped by the owner
mid-gates after its adversarial phases; lead gates run twice, green.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 21:36:55 -07:00

433 lines
26 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# file-watching
## Goal
Teach the server about changes it never saw an editor make. Until M9 the
workspace index was rebuilt on `didSave` and — with no workspace root — on
`didOpen`, so a `git pull`, a branch checkout, a file written by a generator,
or an edit to the `.f` filelist itself stayed invisible until the user
happened to save something. Cross-file answers (`definition`, `workspace/symbol`,
hover's define fallback, completion candidates) were then quietly answering
about a tree that no longer existed. LSP already has the mechanism: the client
watches the disk for its own reasons, and `workspace/didChangeWatchedFiles`
lets a server ask to be told. M9 registers for it and rebuilds the index once
per notification.
## Assumptions
- **Amended (incremental-index, 2026-08-27): one notification is still one
rescan, but a notification naming exactly one held source file takes the
incremental path** — that file's contribution replaced, no progress bar, no
log lines. A checkout filling the list, and a notification naming the
filelist, are whole rebuilds exactly as before. `watch::one_scope_file` is
the test. See `docs/features/incremental-index/README.md`.
- **Amended (index-scope, 2026-08-28): this feature now carries a little more
weight than it did, and the difference is named here rather than left to be
found.** A scope-widening `didOpen` used to run a whole rescan, which re-read
every in-scope file and so *incidentally* caught anything that had changed on
disk behind the server's back. Since that round it indexes only the folders it
added. For a client that advertised
`workspace.didChangeWatchedFiles.dynamicRegistration` — VS Code and Neovim
both do — nothing is lost: the registered glob covers create, change and
delete of every source file in the workspace, which is the mechanism, and the
widen never was. For a client that did not, the **save-only model this README
already documents is slightly narrower**: an external change in a folder
already in scope now waits for the next whole rescan (a save of a file the
index does not hold, a settings change, a folder change, a rename/delete
notification) instead of possibly being caught by the next jump. That is the
same class of window, not a new one — a save has taken the one-file
incremental path since 2026-08-27, so such a session already had no reliable
whole-tree re-read. Written up in full in
`docs/features/index-scope/README.md`.
- **Registration is the only way in.** The protocol has no static
`didChangeWatchedFiles` server capability — a server that wants file events
must ask for them with `client/registerCapability`, and only a client that
advertised `workspace.didChangeWatchedFiles.dynamicRegistration` can be
asked. A client that did not (VS Code's `vscode-languageclient` and
Neovim's built-in client both do; `editors/vscode/smoke.js` deliberately
sends `capabilities: {}`) keeps exactly the save-only model it had before.
That is the honest remaining staleness window, and it is stated in
`docs/features/lucisv-server/README.md` as well as here.
- **The registration is sent from `Server::new`, not from an `initialized`
handler.** `lsp-server`'s `initialize_finish` *consumes* the client's
`initialized` notification before returning, so the request loop never sees
one. `main` builds the `Server` immediately after `initialize_finish`, which
is precisely the first moment the protocol allows a `client/registerCapability`
— so that is where it goes. A handler on `Initialized::METHOD` would be dead
code that looks alive, which is worse than no handler at all.
- **The answer to the registration is ignored.** A client that refuses (or
answers with an error) simply keeps the save-only model; there is nothing
useful to do with the response and nothing to tell the user that their own
editor's log does not already say.
- **One rebuild per notification, never one per file.** `DidChangeWatchedFilesParams`
carries a *list*, and a branch checkout fills it. The handler asks one
question of the whole list and rebuilds at most once. There is **no
time-based debouncing**: that needs a timer, the server is single-threaded
and synchronous by design (`docs/features/lucisv-server/README.md`), and
adding a thread to save part of a 0.7 s corpus rebuild is not a trade worth
making. A burst of several notifications therefore costs several rebuilds;
in practice VS Code and Neovim both coalesce a checkout into very few.
- **Events are filtered by extension, cheaply.** The registered globs already
filter client-side, but a client is free to forward more than it was asked
for, so `touches_scope` drops a notification whose every path is neither a
source extension (`lucisv_core::walk::EXTENSIONS`) nor the configured
filelist. It does **not** try to decide whether a source file is *in* the
current scope: the scope ladder re-applies during the rebuild anyway, and
one rebuild for a stray in-tree `.sv` is much cheaper than duplicating the
ladder's logic per event and getting it subtly wrong.
- **A workspace-folder change does not need a new registration for the source
glob** (added 2026-08-27 by folders-and-config). `SOURCE_GLOB` is a
base-less *string* pattern, which the client matches against the workspace
it currently holds, so a folder added mid-session is covered by the
registration already in force; the `RelativePattern` form, which anchors a
glob to one folder's URI and would have to be re-sent per folder, is
deliberately not used. The **filelist** watcher is the exception: it is an
absolute path, and a relative `lucisv.filelist` is resolved against the
*first* root — so `server.rs` re-registers on a folder change whose
`filelist_path()` differs, exactly as it already did for a changed setting.
See `docs/features/folders-and-config/README.md`.
- **Only the root filelist is watched, not its nested `-f` targets.**
`lucisv_core::filelist::Filelist` reports the files a filelist names but not
the filelists it *read*, and adding that field is a change to another
module for one caller. So editing a nested `.f` outside the editor is still
invisible until the next save or root-filelist touch. Saving a nested
filelist from inside the editor works today (`didSave` rebuilds), which is
the overwhelmingly common case.
- **The filelist is watched by its absolute path, not by a `*.f` glob.** A
filelist can be called anything (`files.list`, `srcs.txt`), so a glob wide
enough for every name would also fire on every unrelated `.f` in the tree.
A path that is not valid UTF-8 cannot be written as a glob and is simply not
watched — the same restriction `uri.rs` already lives under.
- **`lucisv.toml` itself is not watched.** Its `exclude` and `filelist` keys do
change the index's scope, so editing one outside the editor is still
invisible until the next save — but it is read afresh on every rebuild, so
the very next rebuild from any cause picks it up, and saving it from inside
the editor already rebuilds. Watching it would mean a third watcher and a
second re-registration trigger for a file people edit once a quarter.
- **A changed `lucisv.filelist` re-registers.** The watched path is *inside* the
registration, so a new path needs a new registration: the old one is
unregistered by id and a fresh one sent. The alternative — a static watcher
wide enough that no re-registration is ever needed — would mean watching
every file in the tree, which is exactly the noise the tight globs exist to
avoid.
- **`kind` is left unset on both watchers**, which the protocol defines as
create|change|delete. All three matter: a file appearing and a file
vanishing move the index exactly as much as one being rewritten.
- **A watched-file rebuild cannot clobber an open buffer.** `collect_sources`
overlays every open document's text over the disk copy, and the watched-file
path goes through the same `rebuild_index`. Pinned by a test that rewrites
the open file on disk behind the editor's back.
## Handshakes
### `lucisv_server::watch` (new module)
```rust
pub const SOURCE_GLOB: &str = "**/*.{v,vh,sv,svh}";
pub fn dynamic_registration(params: &InitializeParams) -> bool;
pub fn registration(serial: u32, filelist: Option<&Path>) -> Registration;
pub fn unregistration(id: String) -> Unregistration;
pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool;
```
`SOURCE_GLOB` is pinned to `lucisv_core::walk::EXTENSIONS` by a test: a file the
walk indexes but the glob does not name is a file whose external changes are
invisible, and the reverse is wasted rebuilds.
### `lucisv_server::server`
- `Server::new` now takes a `ClientAbilities { snippets, file_watching }`
instead of a bare `snippets: bool` — two adjacent bools at a call site is a
bug waiting to happen. `main.rs` fills both from `InitializeParams`.
- `Server::new` sends the `client/registerCapability` request when
`file_watching` is set (see Assumptions for why it is not an `initialized`
handler).
- `workspace/didChangeWatchedFiles` joins `didSave` and the
`exclude`/`filelist` settings change as a caller of the existing `reindex()`
— same rebuild, same "first warning shown, all of them logged" scope
reporting.
- `workspace/didChangeConfiguration` re-registers the watchers when the
resolved filelist path changed.
- Outgoing request ids are `lucisv-<n>`; registration ids are
`lucisv-watched-files-<n>`. Responses to them are ignored in `run`.
### `lucisv_server::state`
`Workspace::filelist_path()` is now **public** (it was private). It is what
the watcher registration names and what `touches_scope` compares against; the
two must be the same path or filelist edits silently stop rebuilding
anything. No behaviour change.
### `editors/*`
**No editor change is needed.** `vscode-languageclient` advertises
`didChangeWatchedFiles.dynamicRegistration` on its own and creates the
`FileSystemWatcher`s from the registration, and Neovim's built-in client does
the same — so both existing setups gain this with no configuration. There is
no new setting.
## Status / TODO
- [x] `crates/lucisv_server/src/watch.rs`: capability probe, registration and
unregistration builders, per-notification event filter
- [x] `client/registerCapability` sent after the handshake, guarded on the
client capability
- [x] `workspace/didChangeWatchedFiles` handled: one `reindex()` per
notification, warnings surfaced exactly as on save
- [x] Filelist watched by path when one is configured; re-registered when
`lucisv.filelist` resolves somewhere else
- [x] `Workspace::filelist_path` made public for the two callers above
- [x] Unit tests (11 in `watch.rs`, 13 in `server.rs` driving a real `Server`
over `Connection::memory()`), 2 new e2e stdio sessions
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`,
`node editors/vscode/smoke.js` — all clean
- [ ] Not done, deliberately: no time-based debouncing (needs a timer and a
thread; per-notification coalescing only — see Assumptions).
- [ ] Not done, deliberately: nested `-f` filelists are not watched (needs a
new field on `lucisv_core::filelist::Filelist` — see Assumptions).
- [ ] Not done, deliberately: no `workspace/didChangeWorkspaceFolders`. Adding
or removing a folder mid-session still needs a restart; that is its own
change, with its own question about re-registering the watchers.
## Work log
### 2026-08-24 — dev agent, M9
Built in the order the brief lists: the pure `watch` module first, then the
wiring, then the tests, then the docs. Decisions worth recording:
- **Registration moved out of an `initialized` handler.** The first version
hung the registration off `Initialized::METHOD` in `server.rs`'s
notification match, which is what the protocol suggests. The e2e session
then blocked forever waiting for a registration request that never came:
`lsp-server`'s `initialize_finish` receives and swallows the `initialized`
notification itself, so the request loop never sees one. Moved into
`Server::new`, which `main` calls immediately after `initialize_finish` —
the same instant, and provably reached. Recorded in Assumptions because it
is exactly the kind of dead-but-plausible handler a reader would re-add.
- **`ClientAbilities` instead of a second `bool` parameter.**
`Server::new(conn, roots, true, false)` is a call site nobody can read.
- **Two counters, not one.** Registration ids and outgoing request ids are
different namespaces; sharing one counter made the ids jump (`-0`, then
`-3`) for no reason a reader could reconstruct.
- **`touches_scope` filters by extension only, not by scope membership.**
Deciding per event whether the filelist names a file would duplicate the
scope ladder outside `state.rs`, where it would drift. The ladder re-applies
during the rebuild, so an out-of-scope source file costs one rebuild and
changes nothing — pinned by
`an_event_for_a_file_outside_the_scope_still_rebuilds_but_indexes_nothing`.
- **The e2e test needed a new harness.** `talk()` writes the whole session up
front and reads afterwards, so anything a test does to the *filesystem*
mid-script races the server. Added `Live` next to it: one message at a time,
answers read as they arrive, so the test can create a file on disk knowing
the server has not looked yet. `wait_for` is capped at 500 messages and
panics with the transcript rather than hanging a CI job forever. `unframe`
was split into a reusable `read_message` for it; no behaviour change to the
existing tests.
**Files touched outside this feature's module**, all minimal:
- `crates/lucisv_server/src/state.rs` — `filelist_path` private → public, with
a doc comment saying why. No logic change.
- `crates/lucisv_server/src/main.rs` — `mod watch;`, and `ClientAbilities` at
the `Server::new` call site.
- `crates/lucisv_server/tests/e2e.rs` — the `Live` harness and the
`unframe`/`read_message` split, plus the two new sessions.
**Not touched, per the brief**: `TODO.md` §8's M9 checkbox and the umbrella
plan's checklist are left for the lead. `editors/vscode/smoke.js` is
untouched and still passes unchanged — it sends `capabilities: {}`, so it is
never asked to register anything, which
`a_client_that_cannot_watch_files_is_never_asked_to` pins as a test rather
than as a hope. No version bump, no CHANGELOG entry, no new dependency, no
threads.
**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy
--all-targets` silent; `cargo test --workspace` green. `lucisv_server` went
from 372 to 396 unit tests (+24: 11 in `watch.rs`, 13 in `server.rs`) and
from 19 to 21 e2e sessions (+2). `node editors/vscode/smoke.js
target/debug/lucisv-server` → OK, 8 messages, unchanged.
## QA log
### 2026-08-24 — QA agent, M9
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets`
silent. `cargo test -p lucisv_server`: **394 passed + 2 ignored (= 396 unit) +
21 e2e + 3 grammar**, matching the Work log's counts exactly. `cargo test
--workspace`: green, no failures anywhere. `node editors/vscode/smoke.js
target/debug/lucisv-server` → OK, 8 messages, unchanged (capabilities `{}` →
never registered, confirmed both by the new
`a_client_that_cannot_watch_files_is_never_asked_to` e2e test and by running
smoke.js itself). No `unwrap`/`expect`/`panic!` outside `#[cfg(test)]` in
`watch.rs` or the `server.rs` diff; no `unsafe` added. `TODO.md` and the
umbrella `README.md` confirmed untouched (`git status`/`git diff --stat`),
per the QA brief's own scope restriction.
**The `initialize_finish` claim, independently verified against the vendored
source**, not taken on the dev's word: `~/.cargo/registry/.../lsp-server-0.10.0/src/lib.rs:194-208`.
`initialize_finish` sends the `InitializeResult` response and then calls
`self.receiver.recv()` directly (not through the `Connection`'s public
message loop) — if that message is the `initialized` notification it returns
`Ok(())` and the message is gone; it is never pushed anywhere `run()`'s
`self.connection.receiver.recv()` loop could see it. A handler on
`Initialized::METHOD` inside that loop is therefore provably unreachable in
the normal handshake, confirming the Assumptions section's claim and the
non-obvious choice to register from `Server::new`. (A client that sends
something *other* than `initialized` as its very next message makes
`initialize_finish` return `Err`, which `main`'s `?` propagates before
`Server::new` is ever called — pre-existing behavior, not a new race this
feature introduces.)
**Adversarial testing, real `target/release/lucisv-server` binary over stdio**
(hand-rolled Python framing client, one message at a time — the same
write-then-wait-for-reply shape `tests/e2e.rs`'s `Live` harness uses, not a
threaded reader, per the prior QA note about that class of harness hang).
Scripts are in the scratchpad, not the repo. All of the following **PASS**:
- **Percent-encoded spaces, end to end.** A workspace root
`/tmp/Clock Divider .../`, plus a *file* also named with a space
(`clock divider top.sv`), created after the session starts. The
`client/registerCapability` round-trips over a space-containing root, a
`workspace/didChangeWatchedFiles` `Created` event for the space-containing
path indexes it, and `workspace/symbol` finds it on the very next query
with the location URI round-tripping back to the same path. This is
`uri_to_path`'s existing percent-decoding
(`crates/lucisv_server/src/uri.rs:36-53`) doing exactly what it already did
for `didOpen`/`hover`/etc — `watch::touches_scope` and the reindex path
route every event through the same helper, so there was no new surface for
this to go wrong on, and none did.
- **Burst behavior, measured on the real 860-file corpus** (`corpus/`,
read-only, untouched). `client/registerCapability` on that root completes
in 0.34 s. One relevant `didChangeWatchedFiles` notification to the next
answered request: **0.32 s**. Three back-to-back notifications (the `git
checkout` shape) to the next answered request: **0.98 s** — almost exactly
3×, confirming the "no debounce, one rebuild per notification" model costs
what the README says it costs, not more. The server answered a *correct*
follow-up query (`workspace/symbol("clk")`, non-empty, right after the
burst) every time — never wedged, never stale past the burst. This is
faster than the lucisv-server README's own 0.68 s/rebuild debug-build
baseline (release build, as expected) — the honest-gaps assessment below
updates the number for a release binary.
- **Delete the open file.** Deleted the file backing an open buffer on disk,
then sent the matching `Deleted` watched-files event: the symbol it
defines stayed in `workspace/symbol` (buffer overlay wins, per
`an_open_buffer_still_beats_disk_after_a_watched_file_rebuild` and
`collect_sources`'s "contribute themselves when they are not on disk"
rule). Closed the buffer and re-sent the same `Deleted` event: the symbol
disappeared cleanly, no stale location, no crash on the follow-up query.
- **Delete a file that another file references.** Same shape: definer
removed, referencer's `workspace/symbol` query still answers (empty for
the deleted symbol), no crash.
- **`didChangeWatchedFiles` before any `didOpen`.** Sent straight after the
registration handshake, zero open buffers: no panic, and the created file
is indexed on the next `workspace/symbol` query. The "no shared mutable
state, no locks" design (`docs/features/lucisv-server/README.md`) leaves
nothing that startup ordering could race here, and the run confirms it.
- **Filelist emptied.** Rewrote the configured filelist to zero bytes, sent
the matching `Changed` event: the index shrinks to what the now-empty
filelist names (nothing), no crash — this **is** the "filelist names
exactly the set of files" contract working correctly, not a fallback case
(an empty filelist is a valid, if odd, filelist).
- **Filelist deleted.** Removed the filelist file itself, sent the matching
`Deleted` event on the filelist's own watched path: falls back to the
workspace walk (the previously-filelist-scoped symbol reappears) with a
`window/showMessage` warning surfaced — confirms `source_files`'s
`Err(problem)` branch (`state.rs`) is reached correctly from the
watched-files path, not just from `didSave`.
- **Warning volume on a multi-warning filelist, through the watched-files
path specifically** (not just `didSave`, which the filelist feature's own
QA already covered): a filelist with an unsupported flag and three missing
files, touched via a watched-files event, produced **exactly one**
`window/showMessage` ("... and 4 more — see the lucisv log") and **five**
`window/logMessage`s — the "first warning shown, all of them logged" rule
holds on this new trigger, not just the old ones.
- **Re-registration.** Changed `lucisv.filelist` three times in a row: to a
path containing a space (watched verbatim, not escaped or broken — the
glob pattern is a literal path string, not a real glob, so a raw space is
correct), to a nonexistent path (still unregisters/re-registers cleanly,
still answers requests afterward via the workspace-walk fallback), and
back to the same value as immediately before (no re-registration at all —
`set_client_settings`'s equality check holds). Registration ids across all
three changes were `lucisv-watched-files-0/1/2/3` in strict sequence, never
repeated, and each `client/unregisterCapability` named exactly the id the
registration immediately before it carried — confirmed against the wire
messages, not just the unit tests already pinning this in `server.rs`.
- **A client that answers `client/registerCapability` with a JSON-RPC
error** (not just an ignored `result: null`): no crash, no retry loop (no
second registration request arrived in a 1.5 s window), and the server
answered a normal request correctly afterward. `Message::Response(_) => {}`
in `run()` (`server.rs`) matches on the `Message::Response` variant alone,
before ever looking at whether the JSON carries `result` or `error`, so an
error response is exactly as inert as a success — confirmed both by
reading the match arm and by driving a real error response at the binary.
- **Malformed / non-file URIs.** A notification whose `changes` mixed a
string that isn't a URI at all, an empty string, a scheme-less relative
path (`rtl/a.sv`), and an `http://` URI: zero `publishDiagnostics`
republishes followed (i.e., zero rebuilds), and the server stayed correct
and responsive afterward. `uri_to_path`'s `strip_prefix("file://")` on a
non-`file:` or malformed string returns `None`, and `touches_scope`'s
`filter_map` drops it before the `.any(...)` ever runs — verified on the
real binary, not just `an_a_non_file_uri_is_ignored_rather_than_guessed_at`'s
unit-level check with one well-formed `untitled:` URI.
**No blocking findings.** Every claim in the feature README and the dev's
Work log checks out against the real binary, not only its own test suite.
**Honest-gaps assessment (item 4 of the brief).** All three disclosed gaps
are stated where a user/maintainer would actually look — the feature
README's own Assumptions *and* Status/TODO, and restated in
`docs/features/lucisv-server/README.md`'s "State and staleness" section (the
file most likely to be read for "why is my index stale"):
- **No debounce.** Measured above: 3×~0.32 s ≈ 0.98 s for a burst on the full
860-file corpus in a release build. That is well inside "the user won't
notice a beat" territory for the realistic case (a checkout that touches a
fraction of the tree coalesces into very few notifications per the
README's own claim about VS Code/Neovim); the pathological case — every
file in a checkout arriving as its own separate notification — was not
reproduced (both editors' watcher implementations coalesce, and simulating
a non-coalescing client would be testing a hypothetical client, not this
one), but the linear cost model documented ("a burst … costs several
rebuilds") is exactly what was measured, no worse. Acceptable as shipped.
- **Nested `-f` filelists unwatched, and `lucisv.toml` unwatched.** Read-only
confirmed against the Assumptions section's own reasoning (the missing
`Filelist`-reads-filelists field, and "re-read every rebuild" respectively)
— both are stated, reasoned, and cheap to work around (save inside the
editor). Not independently re-tested beyond reading the code path, since
the dev's reasoning is sound and nothing about the watched-files feature
changes it.
- **Static-watcher / non-dynamic-registration clients.** Confirmed via
`a_client_that_cannot_watch_files_is_never_asked_to` (repo test) and
independently via the malformed-URI/error-response probes above using
`capabilities: {}` implicitly (no registration ever requested in any
session that didn't advertise the capability) — such a client keeps
exactly the pre-M9 save-only model, stated in both feature READMEs.
**Verdict: ship.** All dev claims verified, including the two claims a QA
pass exists specifically to not take on faith (the `initialize_finish`
source-level justification, and the burst-cost number). The percent-encoded
space path — this session's specific concern about the user's own directory
shape — round-trips correctly end to end with no special-casing needed,
because it rides the same `uri_to_path` helper every other capability
already depends on. No fixes were needed; none applied.
## Review
**2026-08-24 — lead.** Reviewed after QA's clean ship verdict; gates run
independently. The find of the round is the `initialize_finish` trap —
lsp-server consumes the `initialized` notification, so the
protocol-suggested registration point is provably dead code; QA verified
that against the vendored source rather than taking the claim on faith,
and the README records it where the next reader will look. Registration
payloads, per-notification coalescing, and the id discipline are all
boring in the right way. QA's percent-encoded-space end-to-end run (the
owner's actual "Clock Divider" path shape) is exactly the reality-check
this feature needed. The three honest gaps (no debounce — measured at
~0.3s per notification on the full corpus, nested `-f` unwatched,
static-watcher clients unchanged) are disclosed in both places a user
would look. Accepted; M9 checked off in the umbrella plan and TODO §8.