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]>
26 KiB
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_fileis the test. Seedocs/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
didOpenused 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 advertisedworkspace.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 indocs/features/index-scope/README.md. -
Registration is the only way in. The protocol has no static
didChangeWatchedFilesserver capability — a server that wants file events must ask for them withclient/registerCapability, and only a client that advertisedworkspace.didChangeWatchedFiles.dynamicRegistrationcan be asked. A client that did not (VS Code'svscode-languageclientand Neovim's built-in client both do;editors/vscode/smoke.jsdeliberately sendscapabilities: {}) keeps exactly the save-only model it had before. That is the honest remaining staleness window, and it is stated indocs/features/lucisv-server/README.mdas well as here. -
The registration is sent from
Server::new, not from aninitializedhandler.lsp-server'sinitialize_finishconsumes the client'sinitializednotification before returning, so the request loop never sees one.mainbuilds theServerimmediately afterinitialize_finish, which is precisely the first moment the protocol allows aclient/registerCapability— so that is where it goes. A handler onInitialized::METHODwould 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.
DidChangeWatchedFilesParamscarries 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_scopedrops 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.svis 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_GLOBis 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; theRelativePatternform, 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 relativelucisv.filelistis resolved against the first root — soserver.rsre-registers on a folder change whosefilelist_path()differs, exactly as it already did for a changed setting. Seedocs/features/folders-and-config/README.md. -
Only the root filelist is watched, not its nested
-ftargets.lucisv_core::filelist::Filelistreports 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.foutside the editor is still invisible until the next save or root-filelist touch. Saving a nested filelist from inside the editor works today (didSaverebuilds), which is the overwhelmingly common case. -
The filelist is watched by its absolute path, not by a
*.fglob. A filelist can be called anything (files.list,srcs.txt), so a glob wide enough for every name would also fire on every unrelated.fin the tree. A path that is not valid UTF-8 cannot be written as a glob and is simply not watched — the same restrictionuri.rsalready lives under. -
lucisv.tomlitself is not watched. Itsexcludeandfilelistkeys 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.filelistre-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. -
kindis 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_sourcesoverlays every open document's text over the disk copy, and the watched-file path goes through the samerebuild_index. Pinned by a test that rewrites the open file on disk behind the editor's back.
Handshakes
lucisv_server::watch (new module)
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::newnow takes aClientAbilities { snippets, file_watching }instead of a baresnippets: bool— two adjacent bools at a call site is a bug waiting to happen.main.rsfills both fromInitializeParams.Server::newsends theclient/registerCapabilityrequest whenfile_watchingis set (see Assumptions for why it is not aninitializedhandler).workspace/didChangeWatchedFilesjoinsdidSaveand theexclude/filelistsettings change as a caller of the existingreindex()— same rebuild, same "first warning shown, all of them logged" scope reporting.workspace/didChangeConfigurationre-registers the watchers when the resolved filelist path changed.- Outgoing request ids are
lucisv-<n>; registration ids arelucisv-watched-files-<n>. Responses to them are ignored inrun.
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
FileSystemWatchers 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
crates/lucisv_server/src/watch.rs: capability probe, registration and unregistration builders, per-notification event filterclient/registerCapabilitysent after the handshake, guarded on the client capabilityworkspace/didChangeWatchedFileshandled: onereindex()per notification, warnings surfaced exactly as on save- Filelist watched by path when one is configured; re-registered when
lucisv.filelistresolves somewhere else Workspace::filelist_pathmade public for the two callers above- Unit tests (11 in
watch.rs, 13 inserver.rsdriving a realServeroverConnection::memory()), 2 new e2e stdio sessions 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
-ffilelists are not watched (needs a new field onlucisv_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
initializedhandler. The first version hung the registration offInitialized::METHODinserver.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'sinitialize_finishreceives and swallows theinitializednotification itself, so the request loop never sees one. Moved intoServer::new, whichmaincalls immediately afterinitialize_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. ClientAbilitiesinstead of a secondboolparameter.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_scopefilters by extension only, not by scope membership. Deciding per event whether the filelist names a file would duplicate the scope ladder outsidestate.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 byan_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. AddedLivenext 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_foris capped at 500 messages and panics with the transcript rather than hanging a CI job forever.unframewas split into a reusableread_messagefor it; no behaviour change to the existing tests.
Files touched outside this feature's module, all minimal:
crates/lucisv_server/src/state.rs—filelist_pathprivate → public, with a doc comment saying why. No logic change.crates/lucisv_server/src/main.rs—mod watch;, andClientAbilitiesat theServer::newcall site.crates/lucisv_server/tests/e2e.rs— theLiveharness and theunframe/read_messagesplit, 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. Theclient/registerCapabilityround-trips over a space-containing root, aworkspace/didChangeWatchedFilesCreatedevent for the space-containing path indexes it, andworkspace/symbolfinds it on the very next query with the location URI round-tripping back to the same path. This isuri_to_path's existing percent-decoding (crates/lucisv_server/src/uri.rs:36-53) doing exactly what it already did fordidOpen/hover/etc —watch::touches_scopeand 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/registerCapabilityon that root completes in 0.34 s. One relevantdidChangeWatchedFilesnotification to the next answered request: 0.32 s. Three back-to-back notifications (thegit checkoutshape) 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
Deletedwatched-files event: the symbol it defines stayed inworkspace/symbol(buffer overlay wins, peran_open_buffer_still_beats_disk_after_a_watched_file_rebuildandcollect_sources's "contribute themselves when they are not on disk" rule). Closed the buffer and re-sent the sameDeletedevent: 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/symbolquery still answers (empty for the deleted symbol), no crash. didChangeWatchedFilesbefore anydidOpen. Sent straight after the registration handshake, zero open buffers: no panic, and the created file is indexed on the nextworkspace/symbolquery. 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
Changedevent: 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
Deletedevent on the filelist's own watched path: falls back to the workspace walk (the previously-filelist-scoped symbol reappears) with awindow/showMessagewarning surfaced — confirmssource_files'sErr(problem)branch (state.rs) is reached correctly from the watched-files path, not just fromdidSave. - 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 onewindow/showMessage("... and 4 more — see the lucisv log") and fivewindow/logMessages — the "first warning shown, all of them logged" rule holds on this new trigger, not just the old ones. - Re-registration. Changed
lucisv.filelistthree 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 werelucisv-watched-files-0/1/2/3in strict sequence, never repeated, and eachclient/unregisterCapabilitynamed exactly the id the registration immediately before it carried — confirmed against the wire messages, not just the unit tests already pinning this inserver.rs. - A client that answers
client/registerCapabilitywith a JSON-RPC error (not just an ignoredresult: 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(_) => {}inrun()(server.rs) matches on theMessage::Responsevariant alone, before ever looking at whether the JSON carriesresultorerror, 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
changesmixed a string that isn't a URI at all, an empty string, a scheme-less relative path (rtl/a.sv), and anhttp://URI: zeropublishDiagnosticsrepublishes followed (i.e., zero rebuilds), and the server stayed correct and responsive afterward.uri_to_path'sstrip_prefix("file://")on a non-file:or malformed string returnsNone, andtouches_scope'sfilter_mapdrops it before the.any(...)ever runs — verified on the real binary, not justan_a_non_file_uri_is_ignored_rather_than_guessed_at's unit-level check with one well-formeduntitled: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
-ffilelists unwatched, andlucisv.tomlunwatched. Read-only confirmed against the Assumptions section's own reasoning (the missingFilelist-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 usingcapabilities: {}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.