LSP §9c: didChangeWorkspaceFolders + server-pull configuration
ci / checks (push) Failing after 42s
ci / corpus (push) Successful in 21s

Folders: workspace.workspaceFolders advertised with change
notifications; added/removed folders adjust the root set through one
8-line Workspace::change_roots (removals first, dedup, did-it-move
bool) and one reindex per moving notification — progress bar, code-
lens refresh and diagnostics generation all ride along, pinned. Open
buffers in a removed folder keep today's rootless conventions with no
new code. The source watcher's base-less glob needs no re-
registration; the absolute-path filelist watcher re-registers through
the same before/after comparison the settings push already ran.

Configuration: clients advertising workspace.configuration get one
pull at startup and one per empty didChangeConfiguration; the answer
funnels through the same parser and applier as the push, so the two
doors cannot drift, and every malformed answer shape lands on
defaults, silently. The outstanding-request routing refactored to one
Pending enum map — applyEdit's shipped behavior re-proven under
three-way out-of-order interleaving. Push-with-payload stays the
unchanged legacy path.

38 tests added (dev 27 + QA 11, closing every claim that lacked one:
roots.first() reordering, last-root-removed totality, double pulls,
stale answers, the pull-answer-moves-the-filelist chain, rootless-
gains-first-folder). QA's F1 — a subfolder added as its own root is
its own root, outside the parent's exclude — accepted as the per-root
model and documented in Assumptions.

docs/features/folders-and-config/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-26 23:33:17 -07:00
1 parent 8dc8f6489f
commit 17fb2129db
9 files changed
+2097 -52

No files matched your search

+37 -2
View File
@@ -925,10 +925,45 @@ and are not gaps.
copy of the EDA search order) and `normalize` became public; the
standing request to extract one `lucisv_core::path::normalize` for
the three private copies is still open.
- [ ] **`workspace/didChangeWorkspaceFolders`** — roots are read once
- [x] **`workspace/didChangeWorkspaceFolders`** — roots are read once
at initialize; adding/removing a folder mid-session is ignored.
- [ ] **`workspace/configuration` (server-pull)** — we rely solely on
→ delivered 2026-08-27 by `docs/features/folders-and-config/README.md`:
`workspace.workspaceFolders { supported, changeNotifications }` +
`Workspace::change_roots`. One rescan per *notification* — the event
carries both lists, and the progress bar, the code-lens refresh and the
diagnostics generation all ride inside the existing `reindex()`. An
event that leaves the root set where it was costs nothing: a folder
already held, one never held, an empty event, params that do not parse,
a non-`file:` folder. A removed folder's files leave the index while
its **open buffers stay open and keep being diagnosed** — no code was
needed for that, since `collect_sources` appends every open document
after the scope ladder has spoken — and removing the *last* folder
simply becomes rung 3 of that ladder, the rootless case. The watcher
determination is recorded there: the source glob is a base-less string
pattern and so is workspace-wide (no re-registration), while the
filelist watcher is an absolute path anchored at the first root and is
re-registered when a folder change moves it. `state.rs` gained exactly
one 8-line method.
- [x] **`workspace/configuration` (server-pull)** — we rely solely on
push `didChangeConfiguration`; clients are moving to the pull model.
→ delivered 2026-08-27 by `docs/features/folders-and-config/README.md`:
one `workspace/configuration` for the `lucisv` section at startup and
again on every *empty* `didChangeConfiguration` (the 3.17 client's
"something changed, ask me"), gated on `workspace.configuration`. A
push with a payload still applies directly, so the legacy path is
untouched; a client without the capability keeps exactly today's
behaviour, empty-payload semantics included. **One parser** — the
answer's entry 0 is wrapped back into the push shape and read by the
same `settings::from_payload` — and **one applier**, so `exclude`/
`filelist` cost the same rescan and the same watcher re-registration
whichever door they came in. An error, a `null`, an empty array or junk
all resolve to the defaults and none of them says anything to the user.
The outstanding-request tracking was refactored from `applying:
HashMap<RequestId, String>` to `pending: HashMap<RequestId, Pending>`,
one map and one `match`, with the three-way interleave
(applyEdit + progress create + configuration) under test. Known and
stated, not fixed: a pulled setting can land after the first index
build, exactly as a pushed one always could.
- [ ] **3.18 additions:** `textDocument/rangesFormatting` (multi-range,
feeds format-modified-lines), snippet edits in `WorkspaceEdit`
(would improve `addPort` cursor placement), and
+78 -5
View File
@@ -58,7 +58,7 @@ use lsp_types::{
SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities,
ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability,
WorkDoneProgressOptions, WorkspaceServerCapabilities,
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
};
use crate::server::{ClientAbilities, Server};
@@ -80,6 +80,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
work_done_progress: work_done_progress_support(&params),
code_lens_refresh: code_lens_refresh_support(&params),
show_document: show_document_support(&params),
configuration: configuration_support(&params),
};
connection.initialize_finish(id, initialize_value()?)?;
@@ -264,10 +265,18 @@ fn capabilities() -> ServerCapabilities {
// never sends them and the capability costs it nothing. See
// `docs/features/file-operations/README.md`.
workspace: Some(WorkspaceServerCapabilities {
// Roots are still read once at `initialize`; adding a folder
// mid-session needs `didChangeWorkspaceFolders`, which is its own
// item in TODO.md §9c.
workspace_folders: None,
// Workspace folders, added and removed mid-session. Both halves
// are needed and neither implies the other: `supported` says the
// server understands a multi-folder workspace at all, and
// `changeNotifications` is what makes the client *send*
// `didChangeWorkspaceFolders`. `Left(true)` rather than an id —
// the string form exists so the registration can later be undone
// by name, and this server never unregisters it. See
// `docs/features/folders-and-config/README.md`.
workspace_folders: Some(WorkspaceFoldersServerCapabilities {
supported: Some(true),
change_notifications: Some(OneOf::Left(true)),
}),
file_operations: Some(file_ops::file_operations()),
}),
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
@@ -419,6 +428,21 @@ fn show_document_support(params: &InitializeParams) -> bool {
.is_some_and(|show_document| show_document.support)
}
/// Whether the client answers `workspace/configuration`.
///
/// The pull half of the settings model: a client that says so is asked for
/// the `lucisv` section at startup and again whenever it sends an empty
/// `didChangeConfiguration`. A client that said nothing is only ever pushed
/// settings, exactly as before.
fn configuration_support(params: &InitializeParams) -> bool {
params
.capabilities
.workspace
.as_ref()
.and_then(|workspace| workspace.configuration)
.unwrap_or(false)
}
/// The directories to index: the client's workspace folders, or the
/// deprecated single root when that is all it sent.
fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
@@ -493,6 +517,55 @@ mod tests {
}
}
#[test]
fn workspace_folders_are_supported_and_their_changes_are_asked_for() {
// Two separate statements, and a client reads them separately:
// without `supported` it may not treat this as a multi-folder server
// at all, and without `changeNotifications` it never sends
// `didChangeWorkspaceFolders` however well that is handled.
let folders = capabilities()
.workspace
.expect("the workspace section")
.workspace_folders
.expect("workspace folders");
assert_eq!(folders.supported, Some(true));
assert_eq!(folders.change_notifications, Some(OneOf::Left(true)));
}
#[test]
fn the_workspace_folder_capability_reaches_the_wire_at_the_key_a_client_reads() {
// Nested one level wrong, or serialized as the string form of
// `changeNotifications`, and the notification simply never arrives.
let value = initialize_value().expect("the initialize result serializes");
assert_eq!(
value["capabilities"]["workspace"]["workspaceFolders"],
serde_json::json!({ "supported": true, "changeNotifications": true }),
"{value:#?}"
);
// And the neighbour under the same key is untouched.
assert!(value["capabilities"]["workspace"]["fileOperations"].is_object(), "{value:#?}");
}
#[test]
fn configuration_support_is_read_from_the_clients_own_capabilities() {
use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities};
assert!(!configuration_support(&InitializeParams::default()), "silence means push-only");
let saying = |configuration: Option<bool>| InitializeParams {
capabilities: ClientCapabilities {
workspace: Some(WorkspaceClientCapabilities {
configuration,
..Default::default()
}),
..Default::default()
},
..Default::default()
};
assert!(configuration_support(&saying(Some(true))));
assert!(!configuration_support(&saying(Some(false))));
assert!(!configuration_support(&saying(None)));
}
#[test]
fn the_type_hierarchy_is_advertised_even_though_lsp_types_cannot_spell_it() {
// `ServerCapabilities` has no `type_hierarchy_provider` field in
File diff suppressed because it is too large. Load diff
+107 -2
View File
@@ -1,4 +1,5 @@
//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`.
//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`
//! — or answers when the server pulls them with `workspace/configuration`.
//!
//! These are the editor's copy of what `lucisv.toml` carries — the same keys, so
//! a user with no config file in the tree can still say "indent 4" from their
@@ -27,6 +28,12 @@ use serde_json::Value;
const LINE_LENGTH_RANGE: RangeInclusive<u64> = 40..=400;
const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
/// The configuration section these settings live in — the key a push nests
/// them under, and the `section` a pull asks for. One constant, because the
/// two must name the same thing or the pull would answer settings the parser
/// then looks for somewhere else.
pub const SECTION: &str = "lucisv";
/// The `lucisv.*` settings in force, after validation. Every field is "no
/// opinion" until a client says otherwise, which is exactly what an unset
/// VS Code setting means.
@@ -70,7 +77,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// `synchronize.configurationSection: 'lucisv'` produces. A payload without
// the section (including the `{"settings": null}` a client sends when it
// syncs no section at all) means "no opinion about anything".
let Some(lucisv) = settings.get("lucisv") else { return ClientSettings::default() };
let Some(lucisv) = settings.get(SECTION) else { return ClientSettings::default() };
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
@@ -84,6 +91,38 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
}
}
/// Read one `workspace/configuration` answer — the *contents* of the `lucisv`
/// section, since that is what the server asked for by name.
///
/// Deliberately the same parser as a push, reached by wrapping the section
/// back into the shape a push arrives in. Two entry points, one set of rules:
/// a range, a type or a default that drifted between the pull and the push
/// paths would be a setting that means one thing in VS Code and another in
/// Neovim. `null` — the answer the spec requires when a client cannot provide
/// the section — parses as "no opinion about anything", which is exactly the
/// defaults.
pub fn from_section(section: &Value) -> ClientSettings {
from_payload(&Value::Object([(SECTION.to_string(), section.clone())].into_iter().collect()))
}
/// Whether a `didChangeConfiguration` payload carries nothing at all.
///
/// The 3.17 model: a client that knows the server pulls sends the
/// notification as a bare "something changed, ask me for what you need" —
/// `{"settings": null}` is what `vscode-languageclient` sends once no legacy
/// `synchronize.configurationSection` is configured, and `{}` is the same
/// statement written differently. Both are a *trigger*, not a settings
/// payload, so the server pulls rather than resetting everything to its
/// default. A payload with any key in it is a real push and is applied as it
/// always was, whether or not our section is among those keys.
pub fn says_nothing(settings: &Value) -> bool {
match settings {
Value::Null => true,
Value::Object(map) => map.is_empty(),
_ => false,
}
}
/// A JSON boolean, or nothing. `as_bool` rejects the string `"false"` and the
/// number `0` along with everything else that is not a boolean: a wrong-typed
/// value is dropped here exactly as it is everywhere else in this module, and
@@ -279,6 +318,72 @@ mod tests {
assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]);
}
#[test]
fn a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one() {
// The whole point of `from_section`: the pull answers the section's
// contents, the push nests them one level deeper, and every rule
// about ranges, types and defaults must be the one set of rules.
let section = json!({
"lineLength": 120, "indent": 4, "exclude": ["vendor"],
"filelist": "rtl/files.f", "inlineTemplates": false, "formatOnSave": true
});
assert_eq!(from_section(&section), settings(json!({ "lucisv": section })));
// ...including the rejections.
let junk = json!({ "indent": "4", "lineLength": 4000, "exclude": "vendor" });
assert_eq!(from_section(&junk), settings(json!({ "lucisv": junk })));
assert_eq!(from_section(&junk), ClientSettings::default(), "and they are rejections");
}
#[test]
fn an_unusable_pull_answer_is_the_defaults_rather_than_an_error() {
// A client that cannot provide the section must answer `null`, per
// spec — and one that answers something absurd instead must cost the
// user no more than one that answered nothing.
for answer in [
json!(null),
json!({}),
json!("lucisv"),
json!(7),
json!([1, 2]),
json!({ "lucisv": { "indent": 4 } }),
] {
assert_eq!(
from_section(&answer),
ClientSettings::default(),
"the answer {answer} must resolve to the defaults"
);
}
}
#[test]
fn an_empty_push_is_a_pull_signal_and_a_populated_one_is_not() {
// `{"settings": null}` is what a modern `vscode-languageclient`
// sends: "something changed, ask me". Applying it as a payload would
// silently reset every setting the user had pulled.
assert!(says_nothing(&json!(null)));
assert!(says_nothing(&json!({})));
assert!(!says_nothing(&json!({ "lucisv": { "indent": 4 } })));
// A legacy push that syncs some *other* server's section is still a
// push: it carries a payload, and this server's answer to it — no
// opinion about anything — is what it has always been.
assert!(!says_nothing(&json!({ "someOtherServer": { "indent": 4 } })));
// Neither an array nor a scalar is the client saying "ask me"; both
// are junk, and junk goes down the push path where `from_payload`
// drops it.
assert!(!says_nothing(&json!([])));
assert!(!says_nothing(&json!("")));
}
#[test]
fn the_section_constant_is_the_key_the_parser_reads() {
// The pull asks for `SECTION` by name and the push nests under it. A
// constant that drifted from the parser would make every pulled
// setting silently invisible.
let found = from_payload(&json!({ SECTION: { "indent": 4 } }));
assert_eq!(found.indent, Some(4));
assert_eq!(SECTION, "lucisv");
}
#[test]
fn the_accepted_ranges_are_the_ones_lucisv_toml_accepts() {
// The bounds above are copied from `lucisv_core::config`, which exports
+216
View File
@@ -125,6 +125,27 @@ impl Workspace {
self.rebuild_index()
}
/// Add and remove workspace roots mid-session, reporting whether the set
/// actually moved — which is whether the caller owes a rebuild.
///
/// Removals are applied before additions, so a folder named in both lists
/// (which the protocol does not forbid, and which is how some clients
/// spell "this folder moved") ends up present. Adding a root that is
/// already held and removing one that was never held are both no-ops, and
/// say so by leaving the set equal: `didChangeWorkspaceFolders` is a
/// notification, so there is nowhere to report a disagreement to and
/// nothing to gain from re-scanning for one.
pub fn change_roots(&mut self, added: Vec<PathBuf>, removed: &[PathBuf]) -> bool {
let before = self.roots.clone();
self.roots.retain(|root| !removed.contains(root));
for root in added {
if !self.roots.contains(&root) {
self.roots.push(root);
}
}
self.roots != before
}
pub fn index(&self) -> &WorkspaceIndex {
&self.index
}
@@ -374,6 +395,7 @@ impl Workspace {
#[cfg(test)]
mod tests {
use super::*;
use std::slice::from_ref;
use std::str::FromStr;
fn uri(s: &str) -> Uri {
@@ -474,6 +496,200 @@ mod tests {
}
}
#[test]
fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() {
let first = Tree::new("rootsfirst");
first.package("a.sv", "a");
let second = Tree::new("rootssecond");
second.package("b.sv", "b");
let mut ws = Workspace::default();
ws.open_roots(vec![first.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: one folder");
assert!(ws.change_roots(vec![second.path.clone()], &[]), "a new folder moves the set");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "both folders are scanned");
assert!(ws.change_roots(Vec::new(), from_ref(&first.path)), "and so does dropping one");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["b"], "the dropped folder's files are gone");
}
#[test]
fn a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed() {
// Overlap does not duplicate a file's registration: `walked_files`
// walks each root independently and `dedup`s the combined, sorted
// list by path, so a file both roots would reach lands in the index
// once, not twice (a second identical registration would show up as
// an *ambiguous* member — `indexed` below only counts a name found
// exactly once).
//
// It is NOT exclude-proof, though, and that half is a genuine
// consequence of "each root is governed by its own config"
// (documented on `walked_files`): a directory the parent root's
// `lucisv.toml` excludes is added *as a root in its own right* here,
// and nothing excludes a root from itself. QA (2026-08-27): flagged
// in the QA log as a finding, not a bug fix — this is consistent
// with the per-root config model, but it was unreachable before this
// round (roots used to be frozen at `initialize`), so it is worth a
// pin and a name.
let tree = Tree::new("subdirroot");
tree.write("lucisv.toml", "exclude = [\"sub\"]\n");
tree.package("kept.sv", "kept");
tree.package("sub/hidden.sv", "hidden_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["kept", "hidden_pkg"]), ["kept"], "excluded, as configured");
assert!(ws.change_roots(vec![tree.path.join("sub")], &[]));
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["kept", "hidden_pkg"]),
["kept", "hidden_pkg"],
"reachable once through the added root, and only once — not ambiguous"
);
}
#[test]
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
// Every no-op shape a client can send. Each must leave the root set
// exactly as it was, and say so — a rescan here is pure cost.
let tree = Tree::new("rootsnoop");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert!(!ws.change_roots(Vec::new(), &[]), "an empty event");
assert!(!ws.change_roots(vec![tree.path.clone()], &[]), "a folder already held");
let never = tree.path.join("never-added");
assert!(!ws.change_roots(Vec::new(), from_ref(&never)), "a folder never held");
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&never)), "and both at once");
assert!(ws.has_roots(), "the root survived every one of them");
}
#[test]
fn a_trailing_slash_in_the_removed_folder_still_matches_the_held_root() {
// `uri_to_path` decodes a URI verbatim, trailing slash and all, and
// `change_roots` compares by `PathBuf` equality — which compares
// components, not raw strings, so `/a/b/` and `/a/b` are already the
// same path as far as `retain`/`contains` are concerned. Pinned
// because the doc README calls this out as a boundary worth
// checking, not because the standard library needed help.
let tree = Tree::new("trailingslash");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let mut with_slash = tree.path.clone().into_os_string();
with_slash.push("/");
assert!(
ws.change_roots(Vec::new(), from_ref(&PathBuf::from(with_slash))),
"the trailing slash must not hide the match"
);
assert!(!ws.has_roots());
}
#[test]
fn a_folder_named_in_both_halves_of_one_event_stays() {
// Removals run first, so "removed and added again" — which is how a
// moved folder reaches some clients — is not a way to lose a root.
let tree = Tree::new("rootsboth");
tree.package("a.sv", "a");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&tree.path)), "no net change");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a"]), ["a"]);
}
#[test]
fn a_folder_added_twice_across_two_events_is_absent_after_one_removal() {
// The root set is a set, not a multiset: `change_roots` dedups on
// push (`if !self.roots.contains(&root)`), so a second add of the
// same path — even from a *later*, separate notification — never
// grows a reference count for it. One removal is therefore always
// enough, however many times a client (redundantly) added it.
// QA (2026-08-27): pinned per the review checklist's multiset-vs-set
// question.
let tree = Tree::new("addedtwice");
let extra = Tree::new("addedtwiceextra");
extra.package("x.sv", "x");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert!(ws.change_roots(vec![extra.path.clone()], &[]), "the first add moves the set");
assert!(
!ws.change_roots(vec![extra.path.clone()], &[]),
"a second, separate add of the same path is a no-op"
);
assert!(
ws.change_roots(Vec::new(), from_ref(&extra.path)),
"one removal is enough to take it out"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["x"]), Vec::<String>::new(), "gone, not merely decremented");
}
#[test]
fn removing_the_last_root_falls_back_to_the_rootless_model() {
// Rung 3 of the ladder is not a startup-only state: a session that
// closes its last folder becomes the single-file case, and an open
// buffer must still resolve against the files beside it.
let tree = Tree::new("rootslast");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/sibling.sv", "sibling");
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["open_pkg", "sibling", "far"]), ["open_pkg", "sibling", "far"]);
let path = tree.path.join("rtl/open.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
assert!(!ws.has_roots(), "the workspace is rootless now");
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["open_pkg", "sibling", "far"]),
["open_pkg", "sibling"],
"the buffer and its neighbours, as if the file had been opened on its own"
);
}
#[test]
fn removing_the_last_root_leaves_a_relative_filelist_unanchored() {
// `filelist_path` anchors a relative setting at `roots.first()`. With
// no roots left there is nothing to anchor it to, and the path comes
// back exactly as the client wrote it — not resolved against the
// folder that is now gone, and not resolved against anything else
// either. Nothing panics: `source_files` still falls back to the
// rootless walk with a warning when that bare path cannot be read
// (`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so`
// covers that fallback). QA (2026-08-27): pinned because this is new
// reachable behaviour this round — losing the last root used to be
// impossible.
let tree = Tree::new("rootslastfilelist");
tree.package("rtl/open.sv", "open_pkg");
tree.write("files.f", "rtl/open.sv\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
ws.filelist_path(),
Some(tree.path.join("files.f")),
"anchored at the root while it exists"
);
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
assert_eq!(
ws.filelist_path(),
Some(PathBuf::from("files.f")),
"with no roots left, the same setting comes back bare — anchored at nothing"
);
}
#[test]
fn the_scan_skips_what_a_gitignore_skips() {
let tree = Tree::new("gitignore");
+165
View File
@@ -3792,3 +3792,168 @@ fn a_moving_includer_s_own_edit_is_addressed_to_its_old_uri_on_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// §9c (folders-and-config): a folder added mid-session, over the real wire.
///
/// What only an e2e test can settle: that the two halves of
/// `workspace.workspaceFolders` reach a real handshake at the key a client
/// reads (without `changeNotifications` no editor ever sends the
/// notification, however well it is handled), and that a cross-file jump into
/// a folder the server did not have at `initialize` resolves afterwards.
#[test]
fn a_folder_added_mid_session_is_indexed_over_the_wire() {
let first = temp_dir("foldersfirst");
let second = temp_dir("folderssecond");
// `top.sv` uses a parameter the *second* folder's package declares, so
// the jump can only resolve once that folder is part of the workspace.
let top = first.join("top.sv");
std::fs::write(&top, "module top;\n localparam W = added_pkg::WIDTH;\nendmodule\n")
.expect("write");
let added = second.join("added_pkg.sv");
std::fs::write(&added, "package added_pkg;\n localparam WIDTH = 8;\nendpackage\n")
.expect("write");
let first_uri = format!("file://{}", first.display());
let second_uri = format!("file://{}", second.display());
let top_uri = format!("file://{}", top.display());
let added_uri = format!("file://{}", added.display());
// The cursor on `WIDTH` in `added_pkg::WIDTH`.
let definition = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":1,"character":30}}}}}}"#
)
};
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"workspaceFolders":[{{"uri":"{first_uri}","name":"first"}}],"capabilities":{{"workspace":{{"workspaceFolders":true}}}}}}}}"#
));
let handshake = live.wait_for(|m| m["id"] == 1);
assert_eq!(
handshake["result"]["capabilities"]["workspace"]["workspaceFolders"],
serde_json::json!({ "supported": true, "changeNotifications": true }),
"{handshake:#?}"
);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string("module top;\n localparam W = added_pkg::WIDTH;\nendmodule\n")
.expect("json")
));
live.send(&definition(2));
let before = live.wait_for(|m| m["id"] == 2);
assert_eq!(
before["result"].as_array().map(Vec::len),
Some(0),
"premise: the second folder is not in the workspace yet: {before:#?}"
);
// "Add Folder to Workspace".
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWorkspaceFolders","params":{{"event":{{"added":[{{"uri":"{second_uri}","name":"second"}}],"removed":[]}}}}}}"#
));
live.send(&definition(3));
let after = live.wait_for(|m| m["id"] == 3);
let targets = after["result"].as_array().expect("a location list");
assert_eq!(targets.len(), 1, "{after:#?}");
assert_eq!(targets[0]["uri"], added_uri.as_str(), "{after:#?}");
// ...and closing it again takes those answers away.
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeWorkspaceFolders","params":{{"event":{{"added":[],"removed":[{{"uri":"{second_uri}","name":"second"}}]}}}}}}"#
));
live.send(&definition(4));
let gone = live.wait_for(|m| m["id"] == 4);
assert_eq!(gone["result"].as_array().map(Vec::len), Some(0), "{gone:#?}");
live.finish();
let _ = std::fs::remove_dir_all(&first);
let _ = std::fs::remove_dir_all(&second);
}
/// §9c (folders-and-config): the server-pull settings round trip.
///
/// The push half is covered by `pushed_settings_reach_the_formatter...`; this
/// is the pull half, and only a live session can drive it — the server asks,
/// the test answers as a client would, and the very next format shows the
/// answer took.
#[test]
fn the_configuration_pull_round_trips_over_the_wire() {
let dir = temp_dir("configpull");
let file = dir.join("pull_me.sv");
std::fs::write(&file, "module pull_me;\nwire a;\nendmodule\n").expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let format = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)
};
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"workspace":{{"configuration":true}}}}}}}}"#
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
// The server asks, unprompted, exactly once and for exactly our section.
let pull = live.wait_for(|m| m["method"] == "workspace/configuration");
assert_eq!(
pull["params"],
serde_json::json!({ "items": [{ "section": "lucisv" }] }),
"{pull:#?}"
);
let pull_id = serde_json::to_string(&pull["id"]).expect("json");
// One entry per requested item, and the entry is the section itself.
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{pull_id},"result":[{{"indent":4}}]}}"#));
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string("module pull_me;\nwire a;\nendmodule\n").expect("json")
));
live.send(&format(2));
let pulled = live.wait_for(|m| m["id"] == 2);
assert_eq!(
pulled["result"][0]["newText"],
serde_json::json!("module pull_me;\n wire a;\nendmodule\n"),
"the pulled indent beats the editor's tabSize=2: {pulled:#?}"
);
// An empty `didChangeConfiguration` is the modern "come and ask again",
// not a settings payload that clears everything.
live.send(r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":null}}"#);
let again = live.wait_for(|m| m["method"] == "workspace/configuration");
let again_id = serde_json::to_string(&again["id"]).expect("json");
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{again_id},"result":[{{"indent":8}}]}}"#));
live.send(&format(3));
let repulled = live.wait_for(|m| m["id"] == 3);
assert_eq!(
repulled["result"][0]["newText"],
serde_json::json!("module pull_me;\n wire a;\nendmodule\n"),
"{repulled:#?}"
);
// And a client with nothing to say answers `null`, which is the defaults.
live.send(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{}}}"#,
);
let empty = live.wait_for(|m| m["method"] == "workspace/configuration");
let empty_id = serde_json::to_string(&empty["id"]).expect("json");
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{empty_id},"result":[null]}}"#));
live.send(&format(4));
let defaulted = live.wait_for(|m| m["id"] == 4);
assert_eq!(
defaulted["result"][0]["newText"],
serde_json::json!("module pull_me;\n wire a;\nendmodule\n"),
"the tab size is back in charge: {defaulted:#?}"
);
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
+11
View File
@@ -51,6 +51,17 @@ per notification.
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
+568
View File
@@ -0,0 +1,568 @@
# folders-and-config
Two small §9c items, one round, because they are the same shape: both are a
piece of the session's *setup* that the server used to read exactly once and
never again.
## Goal
**`workspace/didChangeWorkspaceFolders`.** Until this round the workspace
roots were read at `initialize` and frozen for the life of the process, so
"Add Folder to Workspace" (or closing one) changed nothing until the editor
was restarted — a multi-repo SV project, which is the normal shape for a
design plus its verification IP, could not be assembled without a reload. The
server now advertises `workspace.workspaceFolders` (both halves) and adjusts
its root set from the notification, rebuilding the index once per event.
**`workspace/configuration` (server-pull).** The `lucisv.*` settings only ever
arrived by *push*, and the push is the legacy path: `vscode-languageclient`
sends `didChangeConfiguration` with a real payload only where a
`synchronize.configurationSection` is configured, and the modern arrangement
is for the client to say "something changed" and for the server to fetch what
it needs. The server now asks for the `lucisv` section at startup, and again
on every empty `didChangeConfiguration`, gated on the client's own
`workspace.configuration` capability. The answer goes through **the same
parser** a push does, so the two paths cannot drift.
## Assumptions
- **A subdirectory added as its own workspace folder is its own root.** It
resolves its own `lucisv.toml` from its own tree, so the parent root's
`exclude` does not reach into it — files the parent excluded become
indexable through the child root (QA log F1, 2026-08-27; no
double-indexing, no ambiguity). This is the per-root config model applied
consistently to a shape that could not previously occur; a user who adds a
subfolder as a root is asking for exactly that folder.
- **A workspace folder is a directory on disk.** A folder whose URI is not a
`file:` URI is dropped rather than guessed at — `uri.rs`'s rule everywhere
else, and there is nothing to walk for a `vscode-vfs://` folder anyway.
- **The root set is a list, not a set with an identity.** Roots are compared
by path. A client that re-adds a folder it already sent, or removes one it
never sent, changes nothing and is told nothing: the notification has no
reply, and re-scanning to discover that the answer is the same is pure
cost. Removals are applied before additions, so a folder named in *both*
lists of one event survives (some clients spell a moved folder that way).
- **Removing a folder does not close its buffers.** The client owns buffer
lifecycle; LSP has no "the server dropped your file" message. An open buffer
whose folder was closed keeps exactly the deal every out-of-scope buffer has
always had — it is analyzed, diagnosed, formatted, and it still overrides
disk in the index by contributing itself (`Workspace::collect_sources` adds
every open document with a path, whatever the scope ladder said). Removing
the *last* folder is not a special case either: the session becomes the
rootless one rung 3 of the scope ladder already describes, where the scope
is the open buffers' own directories.
- **One set of settings per session, not one per folder.** The pull sends no
`scopeUri`. `ClientSettings` is a single struct read by `format::settings_for`
and the index scope, with no notion of "these settings, for files under that
folder" — asking per-resource would be asking for answers there is nowhere
to put. A multi-folder workspace where two folders want different indents
should say so in a `lucisv.toml` per folder, which already works and already
beats the editor setting.
- **A pull answer is never an error.** A refusal, a `null` entry, an empty
array, an object where an array belongs — all mean the same thing, "no
settings for you", which is the defaults. The user did not ask for this
request and cannot act on its failure, so nothing here opens a popup.
- **Settings can arrive after the first index build**, and this round does not
change that. The pull is sent at the same moment the watchers are registered
— the earliest legal point for a server-initiated request — and answered
later, in the loop. That is exactly what a pushed `didChangeConfiguration`
has always done too (it cannot arrive before `initialized` either): the
first index is built against the default scope, and a pulled
`lucisv.exclude`/`lucisv.filelist` costs one extra rescan when it lands.
Nothing is *wrong* in between, it is simply the wider scope.
## The settings model, stated once
| what arrives | what the server does |
|---|---|
| `didChangeConfiguration` with a payload (any non-empty object) | applied directly, through `settings::from_payload` — the legacy path, unchanged |
| `didChangeConfiguration` with `settings: null` or `{}`, **and** `workspace.configuration` | pulls `workspace/configuration` for the `lucisv` section; nothing is applied until the answer comes back |
| `didChangeConfiguration` with `settings: null` or `{}`, **no** capability | applied directly, which resolves to "no opinion about anything" — exactly what such a client got before this round |
| startup, with `workspace.configuration` | one pull, unprompted |
| startup, without it | nothing; settings only ever arrive by push |
Whichever door they came in, settings are adopted by one function —
`Server::apply_settings` — so `exclude`/`filelist` cost the same rescan and the
same watcher re-registration on both paths, and no third path can be added
without going through it.
## The watcher determination
**The source-glob registration does not need re-sending when folders change.**
`watch::registration` sends a `FileSystemWatcher` whose `globPattern` is the
plain string `**/*.{v,vh,sv,svh}`. In LSP a *string* glob pattern carries no
base URI, and the client matches it against the workspace it holds — VS Code
re-evaluates such a pattern against its current folder set, so a folder added
after registration is watched by the registration already in force. (The
alternative shape, `RelativePattern`, anchors a glob to one folder's URI and
*would* have to be re-sent per folder; this server has never used it, and
adopting it would mean one watcher per root for no gain.)
**The filelist watcher does.** The second watcher in the same registration is
an absolute path, and `Workspace::filelist_path` resolves a *relative*
`lucisv.filelist` against `roots.first()`. So a folder event that changes which
root is first — or that removes the root the setting was anchored to — moves
the watched path without anyone touching the setting. The handler therefore
compares `filelist_path()` before and after and re-registers when it moved:
literally the same two lines `didChangeConfiguration` already ran, for the
same reason (the watched path is baked into the registration).
## Handshakes
**Consumed from `lsp-types` 0.97:** `WorkspaceFoldersServerCapabilities
{ supported, change_notifications }` — `change_notifications` is
`OneOf<bool, String>` and is sent as `Left(true)`; the string form exists so
the registration can be undone by id, and this server never unregisters it.
`DidChangeWorkspaceFoldersParams { event: { added, removed } }`,
`ConfigurationParams`/`ConfigurationItem`, and `WorkspaceConfiguration`
(`Result = Vec<Value>`).
**Asked of `state.rs` (delivered, minimal):** one new public method,
```rust
pub fn change_roots(&mut self, added: Vec<PathBuf>, removed: &[PathBuf]) -> bool
```
which adjusts the private `roots` list and reports whether it moved, in the
same shape `set_client_settings` already reports "you owe a rebuild". Nothing
else in `state.rs` changed: `rebuild_index` walks `self.roots` and so already
does the right thing for a wider or narrower set, and the rootless fallback
(`default_files` → `sibling_files`) already covers "the last folder went
away". The root list is deliberately *not* exposed — the server has no use for
it beyond changing it, and `has_roots()` already answers the one question it
does ask.
**Promised to `server.rs`'s other handlers:** `Pending` replaces the
`applying: HashMap<RequestId, String>` map. Every server-initiated request
whose answer matters is registered in one `pending: HashMap<RequestId,
Pending>`; everything else (watcher registration, `workDoneProgress/create`,
`codeLens/refresh`, `showDocument`) is still absent from it and still falls
through `response` untouched. A future request kind that needs its answer read
adds a variant, and the compiler names every place that must handle it. Two
maps would have meant two lookups in `response` and two chances to forget one.
**`settings.rs` gained** `SECTION` (the one spelling of `"lucisv"`, used by the
parser and by the pull's `ConfigurationItem`), `from_section` (a pull answer,
wrapped back into the push shape so there is exactly one parser) and
`says_nothing` (whether a push payload is really a pull signal).
**Nothing outside `crates/lucisv_server` was touched**, and no dependency was
added. `editors/vscode` was deliberately left alone, and the interplay is
worth stating: `extension.js` still sets
`synchronize: { configurationSection: 'lucisv' }`, so VS Code keeps *pushing*
a real payload — the legacy path, unchanged — while `vscode-languageclient`
advertises `workspace.configuration` and `workspace.workspaceFolders` on its
own and therefore also answers the startup pull (with the same section, read
by the same parser, to the same result). Dropping the `synchronize` line
would leave the pull in sole charge and is a client-side change for another
round. `smoke.js` sends `capabilities: {}` — the no-capability polarity, and
the one worth keeping under test.
## Status / TODO
- [x] `workspace.workspaceFolders: { supported: true, changeNotifications: true }`
advertised, and pinned as JSON at the key a client reads.
- [x] `workspace/didChangeWorkspaceFolders` handled: added/removed adjust the
root set, one `reindex()` per notification.
- [x] A removed folder's files leave the index; its open buffers stay open and
keep being diagnosed.
- [x] Duplicate adds, removing a never-added folder, an empty event, params
that do not parse, a non-`file:` folder — all no-ops, none of them a
rescan.
- [x] Watcher determination made and implemented: source glob workspace-wide
(no re-registration), filelist path anchored at the first root
(re-registered when it moves).
- [x] `workspace.configuration` read from the client's capabilities.
- [x] One `workspace/configuration` at startup, gated on that capability.
- [x] An empty `didChangeConfiguration` pulls instead of resetting; a
populated one still applies directly.
- [x] The answer applies through `settings::from_section` → the same
`from_payload` a push uses, and through one `apply_settings`.
- [x] `null`/empty/malformed/errored answers are total and leave the defaults.
- [x] `applying` → `pending: HashMap<RequestId, Pending>`; three-way
interleave tested.
- [x] Tests: **27 new** — 4 in `settings.rs`, 4 in `state.rs`, 14
`Session`-level in `server.rs`, 3 capability tests in `main.rs`, 2 e2e
sessions against the real binary.
- [x] `docs/features/lucisv-server/README.md` capability table and the
roots/settings model text updated; `docs/features/file-watching/README.md`
told about the folder interaction; TODO.md §9c boxes checked.
## Work log
### 2026-08-27 — dev agent
**Item 1, `didChangeWorkspaceFolders`.**
- `main.rs::capabilities` now sends `workspace.workspaceFolders` with both
fields. They are separate statements and a client reads them separately:
`supported` says the server understands a multi-folder workspace at all,
`changeNotifications` is what makes the client *send* the notification.
`change_notifications` is `OneOf<bool, String>` in lsp-types 0.97 (checked
against the crate source, not assumed); `Left(true)` is the right form here
because the id-string variant exists only so the registration can later be
unregistered by name, which this server never does.
- `state.rs::change_roots` is the whole of the state change — 8 lines. Roots
were already a private `Vec<PathBuf>` that `rebuild_index` re-walks from
scratch, so widening and narrowing the set is genuinely nothing more than
editing that list. Removals before additions; `bool` out, in the same shape
`set_client_settings` uses, so the server's "did this cost a rescan?"
question is asked the same way for both kinds of change.
- The handler is five lines of body: parse, convert URIs to paths, change the
roots, reindex if they moved, re-register the watchers if the *filelist*
path moved. One `reindex()` per notification — an event carries both lists,
and the progress bar, the code-lens refresh and the diagnostics generation
all ride inside `reindex()` already, which
`one_folder_notification_is_one_rescan_with_one_bar_and_one_generation` pins
rather than assumes.
- **The open-buffer question resolved by reading, not by inventing.** The
brief asked that buffers in a removed folder keep behaving like rootless /
out-of-scope buffers. They already do, and no code was needed:
`collect_sources` appends every open document with a path *after* the scope
ladder has spoken, so such a buffer stays in the index as itself; `reindex`
republishes every open URI whatever the roots say; and `didOpen`'s
root-conditional (`has_roots()` → publish, else reindex) reads the current
root set, so a session that has lost its last folder starts behaving like
the single-file case from the next `didOpen` on. The two tests
(`a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed`,
`removing_the_last_root_falls_back_to_the_rootless_model`) exist to keep
that true, not to describe something new.
- **The watcher determination** is written up in its own section above. Short
version: the source glob is a base-less string pattern and is workspace-wide,
so it needs no re-registration; the filelist watcher is an absolute path
anchored at the first root, so it does — and the handler reuses the exact
before/after comparison `didChangeConfiguration` already made.
**Item 2, `workspace/configuration`.**
- `ClientAbilities::configuration`, read in `main.rs` from
`capabilities.workspace.configuration`, in the same shape as its five
siblings.
- `Server::request_configuration` sends one item, `section: "lucisv"`, no
`scopeUri`, and records the id as `Pending::Configuration`. It is called
from `Server::new` (immediately after `register_watchers`, which is the
earliest legal moment and already proven so by the file-watching round) and
from the `didChangeConfiguration` handler when the payload says nothing.
- **Pending-map decision: one map, an enum, refactored.** The alternative was
a second `HashMap<RequestId, ()>` beside `applying`. One map won: `response`
is then a single lookup and a single `match`, the "which of our requests is
this?" question has exactly one answer rather than one per map, and a third
kind is a variant the compiler makes you handle instead of a map somebody
forgets to consult. The cost is a rename (`applying` → `pending`) and one
extracted function (`applied`, which is the old body verbatim). The
fall-through that makes every *other* server-initiated request's answer
ignorable is unchanged and still the documented rule.
- **One parser, spelled out.** A pull answers the *contents* of the section;
a push nests them under `lucisv`. Rather than a second reader,
`settings::from_section` wraps the answer back into the push shape and calls
`from_payload`. `a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one`
asserts the two agree on a fully-populated section *and* on a fully-junk
one, which is the half that would actually rot.
- **One applier.** The body of the old `didChangeConfiguration` arm became
`Server::apply_settings` (rescan on a scope change, re-register on a moved
filelist path) and both doors now go through it. There is no way to adopt
settings without paying what they cost.
- `settings::says_nothing` decides push-vs-pull: `null` and `{}` are the
client saying "come and ask"; anything with a key in it is a payload, even
when the key is some other server's section (that case has always meant "no
opinion about anything" and still does).
- **Deliberate non-change:** the pull's answer can land after the first index
build. Stated in Assumptions, not fixed — blocking `Server::new` on a client
round trip would be a deadlock waiting to happen (the spec lets a client
answer whenever it likes) and the push path has always had the same shape.
**Tests.** 4 new in `settings.rs` (pull/push parser agreement, unusable
answers, the push-empty predicate, the section constant), 4 new in `state.rs`
(add/remove, every no-op shape, a folder in both lists, the last-folder
fallback), 14 new `Session`-level tests in `server.rs` (folder add reaching
`workspace/symbol`, removal with a still-diagnosed buffer, one-rescan-per-
notification with bar/publish/refresh/generation counts, the six no-op shapes,
the watcher re-registration polarity, the startup pull's params, the no-pull
polarity, a pulled answer reaching the formatter, a pulled `exclude` rebuilding
the index, seven unusable answers plus an error response, empty-push-pulls,
empty-push-without-the-capability, populated-push-applies-directly, and the
three-way interleave), 3 new capability tests in `main.rs`, and 2 new e2e
sessions (a folder added and removed over the wire with a definition resolving
into it, and a full pull round trip including the re-pull and the `null`
answer).
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
clean; `cargo test --workspace` green (982 in the server binary, 48 e2e);
`node editors/vscode/smoke.js` OK. One flake seen and *not* caused here:
`lens::code_lenses_for_a_whole_file_cost_about_one_workspace_walk` is a
wall-clock ratio test and fails under a loaded machine — it passes on its own
and in a normal `--workspace` run.
## QA log
### 2026-08-27 — QA agent
Reviewed the working tree on top of `45db6cd` (`git diff 45db6cd`), against
the dev's claims above and the lead's attack-surface list. Verified by
reading every changed line in `main.rs`/`server.rs`/`settings.rs`/`state.rs`/
`tests/e2e.rs`, then attacking each surface below — mostly by adding a
pinning test that exercises it directly rather than by inspection alone,
since a claim about interleaving or wire order is only as good as a test
that would fail if it were wrong. No redesign; two small additions beyond
tests (both noted below) were within "small and unambiguous."
**Gates.**
- `cargo fmt --all -- --check`: clean (after my own additions were formatted
— one round of `cargo fmt --all` was needed once I'd added tests by hand).
- `cargo clippy --all-targets`: clean, no warnings, before and after my
additions.
- `cargo test --workspace`, run twice end-to-end: green both times, no
failures, no flake. Baseline was 982 `lucisv_server` unit tests as the dev
reported; ended at 993 after the 11 tests I added (see below). 48 e2e tests
green throughout.
- The lens flake (`lens::code_lenses_for_a_whole_file_cost_about_one_workspace_walk`,
`crates/lucisv_server/src/lens.rs:652`): did **not** fire in two full
`cargo test --workspace` runs, nor in 5 back-to-back runs of that test
alone with four `yes > /dev/null` processes competing for CPU
(ratio stayed ~1.4–1.5x against the 2x budget each time). Did not need to
check it at `45db6cd` since it never reproduced here — nothing in this
diff touches `lens.rs`, and the test is a wall-clock ratio exactly as the
dev described, so I take the dev's report at face value. Not a blocker.
- `node editors/vscode/smoke.js target/debug/lucisv-server` (had to pass the
path explicitly — `lucisv-server` is not on `PATH` in this checkout):
`OK`. This is the no-capability (`capabilities: {}`) polarity, so it
exercises the "client can't be asked, keeps today's behaviour" branch of
both features.
**Attack surfaces — verdicts.**
1. **`roots.first()` dependency.** Verified clean, with new pins.
`Workspace::change_roots` (`state.rs:138`) removes before adding and dedups
adds via `contains`, so insertion order is preserved and a folder can only
ever appear once — confirmed by
`a_folder_added_twice_across_two_events_is_absent_after_one_removal`
(new, `state.rs`): two separate add events for the same path plus one
removal leaves it fully absent, not merely "count decremented." The
remove-then-add-reorders-first case is exactly what
`a_folder_change_re_registers_the_watchers_only_when_the_watched_path_moves`
(existing, `server.rs:4908`) already pinned end to end (drop the first
root, watch the second's `files.f`, both the reindex and the
unregister+register fire). The "no roots left" total case was **not**
pinned before this round: added
`removing_the_last_root_leaves_a_relative_filelist_unanchored`
(`state.rs`, near line 549) — `filelist_path()` returns the bare relative
path (`PathBuf::from("files.f")`), anchored at nothing, once the last root
is gone. Nothing panics and `source_files` still degrades to the rootless
walk with a warning when that bare path can't be read
(`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so`
already covers that half) — but it is a real, newly-reachable oddity
(see finding F1 below) rather than an outright bug.
2. **`Pending` refactor / applyEdit routing.** Verified clean. The pre-existing
applyEdit round's tests (`a_command_pushes_its_edit_...`,
`a_response_with_a_jsonrpc_error_is_reported_too`,
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`,
etc.) are untouched by the diff and green. `three_outstanding_requests_are_answered_by_id_in_any_order`
(`server.rs:5127`) does genuinely have all three requests
(`applyEdit`, `workDoneProgress/create`, `workspace/configuration`)
outstanding simultaneously before any answer — confirmed by reading
`Session::sent`: it drains the channel once and the test pulls all three
ids from that single drain — and answers them out of the send order
(pull, then create, then edit) with each answer reaching the right
handler. Two follow-up questions the dev's tests didn't cover, both now
pinned: **two `Configuration` entries pending at once, answered out of
order** — new `two_outstanding_configuration_pulls_are_each_answered_by_their_own_id`
(`server.rs`): each answer is applied independently through its own id;
whichever is *processed* last is what's in force after, no id-based
precedence, which is the only sane semantics for a `HashMap` keyed by id.
**An answer to an id `pending` doesn't hold** — new
`an_answer_to_a_request_the_server_never_tracked_is_silently_ignored`
(`server.rs`): a stale re-answer to an already-consumed id, and an id
never sent at all, are both no-ops (trivially true from
`HashMap::remove`'s `Option`, but worth a test that would catch a future
refactor that made `response` assume the id is always present).
3. **Settings pull correctness.** Verified clean, with one real gap closed.
`configured` (`server.rs:1174`) reads `response_result.unwrap_or(Value::Null)`
then `answered.get(0)` — a client answering with 2 entries silently uses
only entry 0 (correct: exactly one item was asked for), 0 entries or a
non-array (`get(0)` on a string/number returns `None`) both fall through
to `Value::Null` → defaults; `an_unusable_pull_answer_leaves_the_defaults_and_says_nothing`
(`server.rs:5091`, pre-existing) already covers `null`, `[]`, `[null]`, a
bare string, an object, junk-typed fields, and a `lucisv`-nested answer
(the pull/push shape mismatch), plus an actual JSON-RPC error response —
all resolve to defaults with no popup. `a_pulled_answer_that_changes_the_scope_rebuilds_the_index`
(`server.rs:5048`, pre-existing) does assert the **index** actually
changed (`indexed(&session, "scratch_pkg")` flips from 1 to 0), not just
"no crash" — confirmed by reading it, not just trusting the name.
**Gap found and closed:** nothing exercised a pulled *filelist* moving the
watched path — `apply_settings` is shared code so it was very likely
already correct, but "very likely" isn't "pinned." Added
`a_pulled_filelist_re_registers_the_watchers_through_the_same_chain_a_push_uses`
(`server.rs`, next to the exclude test): a pulled `{"filelist": "files.f"}`
does cost an unregister+register with the new absolute path in the
registration, exactly like the pushed case. **Precedence, traced and now
pinned both directions:** the loop is single-threaded and processes
messages in strict receive order; `apply_settings` always replaces the
whole `ClientSettings` struct rather than merging, so whichever message is
*processed* last wins, full stop. `a_push_with_a_payload_is_applied_directly_even_when_the_client_could_be_asked`
(pre-existing) covers pull-then-push; added
`a_late_pull_answer_overrides_a_push_that_landed_while_it_was_outstanding`
for the other direction (push arrives while a pull is still outstanding,
the pull's answer lands after and clobbers it). Both are "last processed
wins," no special-casing either way — worth knowing, not worth fixing.
4. **Folder-change semantics.** Mostly verified clean; one real (low-severity,
arguably by-design) finding.
- Definition into an added folder: `a_folder_added_mid_session_is_indexed_over_the_wire`
(e2e, pre-existing) asserts the returned location's `uri` string equals
the expected `file://` URI exactly, which is as much "decoded correctly"
as a same-process round trip can show without deliberately using a
percent-encoded character in the added folder's path (this round's e2e
test doesn't; existing coverage for URI-decoding a workspace path with
unusual characters lives in `include_nav_round_trips_in_a_workspace_whose_directory_has_a_space`,
unrelated to folder-add specifically). Did not add a new e2e test for
this — the marginal risk is in `uri::uri_to_path`, which is untouched by
this round and already has its own coverage.
- Removed folder's symbols gone from `workspace/symbol`:
`a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed`
confirms via `indexed()` (an index-membership check, equivalent to what
`workspace/symbol` reads from) that the removed folder's non-open file
drops to 0 hits; `a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol`
drives a real `workspace/symbol` request for the added-folder case.
- **F1 — subdirectory added as its own root bypasses the parent's
`exclude`.** New test
`a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed`
(`state.rs`) confirms there is **no** double-indexing/ambiguity when an
already-covered subdirectory is added as a second root — `walked_files`'s
`sort()`+`dedup()` on the combined path list handles that correctly, and
`indexed()`'s "found exactly once" check would have caught an ambiguous
double-registration if there were one. But a directory the parent root's
`lucisv.toml` excludes **is** reachable once it's added as a root in its
own right, because `walked_files` (`state.rs:365`) resolves each root's
`exclude` independently via `Discovery::for_dir(root)`, and nothing
excludes a root from itself. This is consistent with the documented
per-root config model (`walked_files`'s own doc comment says so) and
arguably *correct* — "Add Folder to Workspace" on a specific directory is
an explicit ask to index it — but it was unreachable before this round
(roots were frozen at `initialize`), so it's a genuinely new behavior the
dev's README doesn't mention. Recommend a one-line callout in
Assumptions if the lead agrees it's intentional; not a blocker either way,
and not a corruption risk (formatter output is verified regardless of
what got indexed).
- Folder added twice then removed once: set semantics confirmed (new test,
see item 1 above) — present after two adds, absent after one removal,
not "still there because it was added twice."
- Trailing slash: verified clean, and pinned anyway since the README calls
it out as a boundary worth checking. `uri_to_path` decodes the URI
verbatim (trailing slash included), but `PathBuf`/`Path` equality
compares `Components`, not raw bytes — `Path::new("/a/b/") == Path::new("/a/b")`
is `true` in std, confirmed with a throwaway `rustc` check before writing
the test — so `change_roots`'s `contains`/`retain` already treat them as
the same folder with no code needed. New:
`a_trailing_slash_in_the_removed_folder_still_matches_the_held_root`
(`state.rs`).
5. **Open-buffer convention.** Verified clean, one gap closed.
`a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed`
does assert diagnostics *content* — `!published[0].diagnostics.is_empty()`
after editing the buffer to be broken, not merely "a publish happened."
Closing such a buffer was **not** exercised — added a continuation of the
same test (`server.rs`, same test) that sends `didClose` afterward and
confirms the diagnostics clear (`published[0].diagnostics.is_empty()`).
The code path (`DidCloseTextDocument` handling, `server.rs:1100`) is
pre-existing and untouched by this diff — it doesn't special-case removed
folders at all, which is correct: closing is generic.
6. **Startup pull ordering.** Verified clean, gap closed. `Server::new`
(`server.rs:178`) calls `register_watchers()` then `request_configuration()`
in that order in the source, but nothing checked the *wire*. Added
`the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire`
(`server.rs`): checks both the drained-channel order and, independently,
that the `RegisterCapability` request's `lucisv-N` id number is lower than
the pull's (every outgoing request id comes off one monotonically
increasing counter in `send_request`, `server.rs:1251`, so the numeric
suffix *is* the send order — a second, independent way to catch a future
reordering that a channel-order check alone might not). The full chain —
pull answer → `apply_settings` → filelist moved → re-register — is now
pinned by item 3's `a_pulled_filelist_re_registers_the_watchers_...` test.
"Pulled settings can land after the first index build" is honestly
documented in Assumptions and in the Work log; I didn't find anywhere it's
overstated.
7. **CLAUDE.md compliance.** Clean.
- No `unwrap()`/`expect()`/`panic!` in the non-test portion of
`main.rs`/`server.rs`/`settings.rs`/`state.rs` (checked by slicing each
file at its `#[cfg(test)]` boundary and grepping the part before it —
all four files have exactly one such boundary).
- New public items have doc comments: `Workspace::change_roots`,
`settings::SECTION`, `settings::from_section`, `settings::says_nothing`,
`ClientAbilities::configuration` all do. (Three *pre-existing* undocumented
`pub fn`s in `state.rs` — `index`, `document`, `close_document` — are out
of this round's diff and not this review's problem.)
- `docs/features/folders-and-config/README.md` has every required section
exactly once (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA
log, Review), plus two extra explanatory sections which the template
doesn't forbid.
- Both `TODO.md` §9c items are checked with their original text intact and
a `→ delivered ...` addendum appended, not rewritten.
- `crates/vlog_formatter/src/verify.rs`: zero diff against `45db6cd`
(`git diff 45db6cd -- '**/verify.rs'` is empty) — untouched, as this
round should never need it (nothing here touches formatting or
verification).
- `docs/site/` untouched by both the dev's diff and by me (per this
round's instructions, never opened it).
**C. Beyond the list — "own shapes."**
- `a_rapid_add_remove_add_of_the_same_folder_costs_three_rescans_and_ends_up_added`
(`server.rs`): add, remove, add of the same folder across three separate
notifications costs three separate rescans (no cross-notification
batching — `change_roots` only batches within one event, as designed) and
the net state (two adds, one remove) is "present," matching set semantics.
- `a_rootless_session_gaining_its_first_folder_flips_didopen_from_reindex_to_publish`
(`server.rs`): a session that starts with no roots at all (impossible to
change mid-session before this round) gains its first folder via
`didChangeWorkspaceFolders`, and the very next `didOpen` correctly takes
the `has_roots()` branch — publish only, no second rescan — where it would
have reindexed before the folder arrived. (Caught my own arithmetic error
writing this: `generation` counts *both* a buffer's text and the index, so
a rootless `didOpen` costs two bumps — `set_document` plus `reindex` — not
one; fixed the assertion rather than the code, since the code is correct
and pre-existing.)
**Fixes made directly (small, unambiguous, noted here per the workflow).**
- None to production code. Everything above is test-only: 11 new tests
across `state.rs` (5) and `server.rs` (6), all passing, `cargo fmt`/
`clippy` clean throughout. `cargo test --workspace` ended at 993
`lucisv_server` unit tests (982 dev baseline + 11) plus the unchanged
48 e2e, both green across two full runs.
**Verdict: committable as-is.** No corruption risk, no invariant violated,
no test that should exist and doesn't after this pass. F1 (subdirectory
root bypassing parent's exclude) is worth a documentation line from the lead
or dev — not worth blocking on, since it's arguably correct behavior and
carries no data-loss or formatting-correctness risk.
## Review
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
clean. Both items landed the way small protocol features should: the
folder handler is one 8-line state method plus the existing reindex
machinery (with the bar, the lens refresh and the generation all pinned
as riding along rather than assumed), and the config pull reuses the one
settings parser and the one applier so the two doors cannot drift. The
watcher determination — base-less glob needs nothing, the absolute-path
filelist watcher re-registers through the comparison the push path
already ran — is the kind of read-first engineering this workflow is
for. The Pending-enum refactor is accepted: one map, one match, and a
third request kind is now a compiler-enforced variant; QA re-ran the
apply-edit suite and interleaved all three answer kinds out of order to
prove the shipped routing survived.
QA's roots.first() attack found the design holds (order preserved,
last-root-removal total) and its eleven added tests closed every
claim that lacked one, including the previously-untested
pull-answer-moves-the-filelist chain. F1 is accepted as designed and
now documented in Assumptions: a subdirectory added as its own root is
its own root, per-root config applied consistently. The extension's
redundant push+pull double-answer stays filed for a client-side round.
Accepted as shipped.
+27 -1
View File
@@ -52,6 +52,8 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README |
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
| `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` |
| `workspace/didChangeWorkspaceFolders` | `Workspace::change_roots` + `rebuild_index` | Folders added and removed mid-session, since 2026-08-27. One rescan per *notification* (the event carries both lists), and none at all for an event that leaves the root set where it was — a folder already held, one never held, an empty event, a non-`file:` folder. A removed folder's files leave the index; its open buffers stay open and keep being diagnosed, exactly as an out-of-scope buffer always has. Advertised as `workspace.workspaceFolders: { supported, changeNotifications }` — both halves, because a client reads them separately. See `docs/features/folders-and-config/README.md` |
| `workspace/configuration` | `settings::from_section` → `from_payload` | Server-**initiated**, since 2026-08-27: the `lucisv` section, asked for once at startup and again on every *empty* `didChangeConfiguration` (the 3.17 client's "something changed, ask me"). Only for a client that advertised `workspace.configuration`; a push with a payload still applies directly, so the legacy path is untouched. The answer is entry 0 of an array and goes through the same parser a push does; an error, a `null`, an empty array or junk all mean the defaults, and none of them says anything to the user. Same feature README |
| `workspace/willRenameFiles` | `includes::IncludeGraph` (through `resolve_as_if`) | The client is about to rename files and asks what that costs: every `` `include`` in scope whose **resolved** target moves — never a filename match — is re-spelled so it still resolves, in the form it was written in (bare stays bare where a rung reaches it, angled resolves through `+incdir+`s only, absolute stays absolute), shortest resolving suffix first and a `../`-relative spelling only as a last resort. An include written *in* a file that moves is re-spelled too. An include no spelling can reach is **left exactly as written** and named in a `window/showMessage` warning — nothing is invented. `null` when there is nothing to do. Folders are answered as well as files (LSP sends only the folder's URI; a folder is a path prefix). Every edit covers the path token alone and is verified three ways before it is emitted — see `docs/features/file-operations/README.md` |
| `workspace/didRenameFiles`, `workspace/didDeleteFiles` | `Workspace::rebuild_index` | One `reindex()` per notification whose paths touch the index's scope, filtered by the same predicate a watched-file event is. Deliberately not deduplicated against the watcher: a client may send both, and a second rebuild re-reads the tree rather than changing an answer. Source-file filters only — a folder move reaches the index through the watcher's own events. Same feature README |
| `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` |
@@ -231,7 +233,7 @@ 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 |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, and a changed `lucisv.exclude`/`lucisv.filelist` | full re-scan of the roots |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist` (pushed **or** pulled) | full re-scan of the roots |
| 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 |
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
@@ -282,6 +284,23 @@ model above; nested `-f` filelists are not watched, only the root one;
rebuild from any cause picks it up); and there is no time-based debouncing, so
a burst arriving as several separate notifications costs one rebuild each.
**Settings arrive two ways since 2026-08-27** (folders-and-config): pushed, as
they always were, and *pulled*. A client that advertised
`workspace.configuration` is sent one `workspace/configuration` for the
`lucisv` section at startup, and another whenever it sends a
`didChangeConfiguration` whose payload is empty — which is the 3.17 client's
way of saying "something changed, come and ask", and is what
`vscode-languageclient` sends once no legacy `synchronize.configurationSection`
is configured. A push that carries a real payload still applies directly, so
nothing about the old path moved. Both doors lead to one parser
(`settings::from_payload`) and one applier (`Server::apply_settings`), so a
setting cannot mean two things depending on how it arrived, and
`exclude`/`filelist` cost the same rescan either way. A pulled answer can land
*after* the first index build — as a pushed one always could, since neither
can arrive before `initialized` — so the first index is built against the
default scope and a narrowing setting costs one extra rescan when it lands.
Rules: `docs/features/folders-and-config/README.md`.
**Definition targets in other files need that file's text** to turn a
`TextRange` into a `Range`, and the index deliberately keeps no file contents.
The server resolves a target by taking the **open buffer's text if that path
@@ -313,6 +332,13 @@ not see.
on a POSIX path legitimately named `/C:`.
- **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling
back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`.
~~They are read once and frozen for the session.~~ **Superseded
(folders-and-config, 2026-08-27): `workspace/didChangeWorkspaceFolders`
adjusts the root set mid-session, one rescan per notification. A removed
folder's files leave the index while its open buffers stay open and keep
being diagnosed, and removing the *last* folder simply becomes rung 3 of
the scope ladder — the rootless case — with no special handling. See
`docs/features/folders-and-config/README.md`.**
~~`.gitignore` and `--exclude` are **not** honored~~ **Superseded by
lucisv-core-lift (lead note): the scan now uses the lifted `lucisv_core` walk —
`.gitignore` always on, workspace-root config excludes applied. The old