lucisv-server --verbose: per-operation timing as a shipped toggle
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s

The hand-patched diagnostic build becomes a feature: --verbose gates
the timing lines (request answered / notification handled / HELD
behind a rescan / scan and widen lifecycle / flush / reindex_one, the
exact wordings of the two diagnostic builds) as LOG messages into the
client's output channel; without the flag not one line is sent and
the cost is one branch, measured unmeasurable against HEAD. Unknown
args exit 2 with usage before the transport opens. The extension
gains lucisv.verbose (default off) and its first restart-on-settings
machinery: restart.js, one serialized chain reconciling to the last
toggle, no client transition outside it — activation and deactivate
included — after QA twice caught the alternatives (a mid-start toggle
silently rejoining the stale start; deactivate's out-of-chain stop
orphaning a spawn). Headless node harness restart_test.js, 44 checks,
five mutations caught. Spawn contract amended everywhere it is
written: no args required, --verbose optional.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-29 01:44:56 -07:00
1 parent 829302d0bf
commit 40094c4c4e
17 files changed
+2232 -56

No files matched your search

+5 -1
View File
@@ -678,7 +678,11 @@ to the folder walk, so the index is never silently empty.
<path-to-binary>` spawns it exactly as the extension does and drives a whole
`initialize`/`didOpen`/`shutdown`/`exit` session over stdio, exiting 0 only if
the handshake and the advertised capabilities are intact — which tells you
whether a failure is the server or your editor config.
whether a failure is the server or your editor config. Its neighbour
`node editors/vscode/restart_test.js` needs no binary at all: it drives the
extension's server-restart chain (the one `lucisv.verbose` uses) against a
scripted fake client, so a toggle can never be lost to a restart that was
already in flight.
**Formatting through an editor reads `lucisv.toml` too**, discovered from the
buffer's own path by the CLI's rule, so format-on-save agrees with what
+88 -1
View File
@@ -69,7 +69,27 @@ use vlog_parser::PARSE_STACK_SIZE;
use crate::server::{ClientAbilities, Server};
use crate::uri::uri_to_path;
/// The one flag this binary takes: per-operation timing lines in the client's
/// log channel. One spelling, no `-v` — see
/// `docs/features/verbose-timing/README.md`.
const VERBOSE: &str = "--verbose";
/// What someone who spelled an argument wrong is told, on stderr. One line:
/// this binary is spawned by an editor, not typed at a prompt.
const USAGE: &str = "usage: lucisv-server [--verbose]";
fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// Before the transport: an argument we do not understand means the client
// asked for something we are not doing, and answering LSP anyway would
// hide that for the whole session.
let verbose = match verbose_flag(std::env::args().skip(1)) {
Ok(verbose) => verbose,
Err(unknown) => {
eprintln!("error: unknown option: {unknown}");
eprintln!("{USAGE}");
std::process::exit(2);
}
};
let (connection, io_threads) = Connection::stdio();
let (id, params) = connection.initialize_start()?;
@@ -108,13 +128,32 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
std::thread::Builder::new()
.name("lucisv-main".to_string())
.stack_size(PARSE_STACK_SIZE)
.spawn(move || Server::new(connection, roots, abilities, storage).run())?
.spawn(move || Server::new(connection, roots, abilities, storage, verbose).run())?
.join()
.map_err(|_| "the server thread panicked")??;
io_threads.join()?;
Ok(())
}
/// Whether the arguments ask for verbose timing, or the first argument this
/// binary does not take.
///
/// Refused rather than ignored: a client that spawns `lucisv-server --verbos`
/// would otherwise get a whole session of silence and no way to tell it from a
/// flag that does not work. Repeating the flag is not an error — it says the
/// same thing twice — and no argument at all is the spawn every editor has
/// always used.
fn verbose_flag(args: impl Iterator<Item = String>) -> Result<bool, String> {
let mut verbose = false;
for arg in args {
if arg != VERBOSE {
return Err(arg);
}
verbose = true;
}
Ok(verbose)
}
/// What the server tells the client it can do. Nothing is advertised that is
/// not implemented: a capability an editor discovers to be a lie is worse than
/// one it never had.
@@ -553,6 +592,54 @@ fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
mod tests {
use super::*;
/// [`verbose_flag`] over what a spawn would really hand it.
fn args(args: &[&str]) -> Result<bool, String> {
verbose_flag(args.iter().map(|arg| (*arg).to_string()))
}
#[test]
fn no_arguments_is_the_spawn_every_editor_has_always_used() {
assert_eq!(args(&[]), Ok(false), "and it must never become verbose by accident");
}
#[test]
fn the_one_flag_is_the_one_spelling() {
assert_eq!(args(&["--verbose"]), Ok(true));
// Twice says the same thing twice.
assert_eq!(args(&["--verbose", "--verbose"]), Ok(true));
// Every near miss is refused, `-v` included: one spelling, so a client
// that guessed is told rather than silently given nothing.
for wrong in ["-v", "--Verbose", "--verbos", "verbose", "--verbose=true", "--help"] {
assert_eq!(args(&[wrong]), Err(wrong.to_string()), "{wrong} is not the flag");
}
}
#[test]
fn the_first_argument_we_do_not_take_is_the_one_reported() {
// Named, so the message can say which word was wrong — the whole
// reason this refuses instead of ignoring.
assert_eq!(args(&["--verbose", "--colour"]), Err("--colour".to_string()));
assert_eq!(args(&["--colour", "--verbose"]), Err("--colour".to_string()));
assert_eq!(args(&["/some/file.sv"]), Err("/some/file.sv".to_string()));
}
#[test]
fn the_extension_ships_the_flag_off_which_is_what_no_argument_means() {
// The two halves of the contract live in different languages: the
// manifest's default decides whether `extension.js` puts `--verbose`
// in the spawn arguments, and `verbose_flag` decides what the server
// does with the arguments it gets. They must agree that the shipped
// state is off.
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: serde_json::Value = serde_json::from_str(&text).expect("valid json");
let verbose = &manifest["contributes"]["configuration"]["properties"]["lucisv.verbose"];
assert_eq!(verbose["type"], serde_json::json!("boolean"), "{verbose:#?}");
assert_eq!(verbose["default"], serde_json::json!(false), "{verbose:#?}");
assert_eq!(args(&[]), Ok(false), "which is what the server does with no argument");
}
#[test]
fn every_advertised_capability_is_implemented() {
let caps = capabilities();
+161 -2
View File
@@ -188,6 +188,11 @@ pub struct Server {
/// [`Server::must_wait`] — this is the order contract, not a queue of its
/// own.
held: Vec<Message>,
/// `--verbose`: whether every operation says how long it took, in the
/// client's log channel. Off is the shipped state and the whole of what it
/// costs is the branch that reads this field — see
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
verbose: bool,
}
/// How long a burst of `didChange` notifications may sit unanalyzed once the
@@ -255,6 +260,7 @@ impl Server {
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
storage: Option<std::path::PathBuf>,
verbose: bool,
) -> Server {
Server::started(
connection,
@@ -262,6 +268,7 @@ impl Server {
abilities,
ClientSettings::default(),
storage,
verbose,
Vec::new(),
)
}
@@ -283,6 +290,7 @@ impl Server {
abilities: ClientAbilities,
client: ClientSettings,
storage: Option<std::path::PathBuf>,
verbose: bool,
queued: Vec<Message>,
) -> Server {
// Started before the first scan, not in `run`: the scan below answers
@@ -312,6 +320,7 @@ impl Server {
answering_a_rescan: false,
stopped: false,
held: Vec::new(),
verbose,
};
// Nothing has been built yet, so there is no rebuild to owe: the
// `true` this returns for a non-default `client` is the rebuild that
@@ -447,6 +456,7 @@ impl Server {
// `shutdown` included, because a request sent before a shutdown
// is a request the client is still owed an answer to.
if self.must_wait() && matches!(message, Message::Request(_)) {
self.say_held(&message);
// The cancels this burst carried were consumed on the way
// here, and `cancelled_in` runs again over the held batch — so
// they go back in front of what they cancel rather than being
@@ -521,7 +531,23 @@ impl Server {
// requests
// ------------------------------------------------------------------
/// Answer one request, timing it when `--verbose` asked.
///
/// **The line goes out before the response it describes.** The dispatch is
/// here and the response is sent by the caller, so a wrapper can only
/// speak first — which is also what keeps the measurement to exactly the
/// handler, with none of the transport in it. Nothing keys off the order:
/// a `window/logMessage` carries no id, and a client pairs the response
/// with its request by id whatever arrived in between.
fn request(&mut self, request: Request) -> Response {
let Some(started) = self.timer() else { return self.answer_request(request) };
let method = request.method.clone();
let response = self.answer_request(request);
self.timing(format!("{method} answered in {}", ms(started)));
response
}
fn answer_request(&mut self, request: Request) -> Response {
// A request answers from a buffer's analysis, so any change the client
// has already sent is in effect before it is answered — the order
// contract the loop has always promised. Here is also where a typing
@@ -1378,7 +1404,17 @@ impl Server {
// notifications
// ------------------------------------------------------------------
/// Handle one notification, timing it when `--verbose` asked. A
/// notification has no response, so there is no ordering question here:
/// the line follows the work.
fn notification(&mut self, notification: Notification) {
let Some(started) = self.timer() else { return self.handle_notification(notification) };
let method = notification.method.clone();
self.handle_notification(notification);
self.timing(format!("{method} handled in {}", ms(started)));
}
fn handle_notification(&mut self, notification: Notification) {
let method = notification.method.clone();
// A closing buffer's pending text is dropped *before* the flush, not
// in the `didClose` arm below it: the flush would otherwise analyze
@@ -1765,7 +1801,10 @@ impl Server {
self.rescan_wanted = true;
return true;
}
let started = self.timer();
if !self.workspace.update_one(path) {
// No line: nothing was reindexed, and the caller is about to
// rebuild the whole index — which times itself.
return false;
}
self.refresh_code_lenses();
@@ -1773,6 +1812,7 @@ impl Server {
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
true
}
@@ -1797,9 +1837,22 @@ impl Server {
self.rescan_wanted = true;
return;
}
let started = self.timer();
if started.is_some() {
// The folders by name: which folder a jump widened into is the one
// thing the file log below it does not say in one line.
let paths: Vec<String> = added.iter().map(|p| p.display().to_string()).collect();
let folders = added.len();
self.timing(format!(
"widen started: {folders} folder{} added: {}",
plural(folders),
paths.join(", ")
));
}
let bar = self.begin_indexing();
let mut scan =
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
let total = scan.total();
// No drain between the files: a widen is a rescan a message asked for,
// and `must_wait` would hold every request queued behind it anyway. It
// is also the point of the round that there is no longer a wait worth
@@ -1815,6 +1868,12 @@ impl Server {
let (skipped, cached) = (scan.skipped(), scan.cached());
let warnings = self.workspace.finish_scan(scan);
self.end_indexing(bar, skipped, cached);
self.timed(started, |took| {
format!(
"widen finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
plural(total)
)
});
self.refresh_code_lenses();
self.generation += 1;
self.report_scope(warnings);
@@ -1892,18 +1951,38 @@ impl Server {
/// they are written through per file — so the next session resumes from
/// them, exactly as it does after any other half-done scan.
fn scan_once(&mut self) -> Vec<String> {
// Before the bar and before the work list is built: resolving the
// scope and walking it is part of what a scan costs, and a number that
// left it out would be the wrong answer to "why was that slow?".
let started = self.timer();
let bar = self.begin_indexing();
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
let interleave = scan.total() > INTERLEAVE_ABOVE;
let total = scan.total();
if started.is_some() {
// Whether it interleaves is said here because it is decided here,
// and because it is the answer to "why did my hover wait?" — a
// scan that does not interleave answers nothing until it is done.
let interleaving = if interleave { ", interleaved" } else { "" };
self.timing(format!("scan started: {total} file{}{interleaving}", plural(total)));
}
while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch))
{
if interleave && self.answer_what_is_waiting(&mut scan) {
// Nothing after this may speak to a client that has gone, the
// timing line included.
return Vec::new();
}
}
let (skipped, cached) = (scan.skipped(), scan.cached());
let warnings = self.workspace.finish_scan(scan);
self.end_indexing(bar, skipped, cached);
self.timed(started, |took| {
format!(
"scan finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
plural(total)
)
});
warnings
}
@@ -2108,10 +2187,15 @@ impl Server {
if self.dirty.is_empty() {
return;
}
let started = self.timer();
let buffers = self.dirty.len();
for (uri, text) in std::mem::take(&mut self.dirty) {
self.set_document(uri.clone(), text);
self.publish(&uri);
}
self.timed(started, |took| {
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
});
}
/// Say once, in the output channel, that a buffer is on the large-file
@@ -2180,12 +2264,82 @@ impl Server {
notify_on(&self.connection, method, params);
}
// ------------------------------------------------------------------
// timing (`--verbose`)
// ------------------------------------------------------------------
/// The clock a timing line reads, started **only** when `--verbose` asked
/// for one.
///
/// `None` is the whole of what verbose-off costs: one branch here, and
/// then no clock read, no `format!` and no notification anywhere below.
/// Every timing site starts with this.
fn timer(&self) -> Option<std::time::Instant> {
self.verbose.then(std::time::Instant::now)
}
/// One timing line for work that was being timed — and nothing at all,
/// closure included, for work that was not.
fn timed(&self, started: Option<std::time::Instant>, line: impl FnOnce(&str) -> String) {
let Some(started) = started else { return };
self.timing(line(&ms(started)));
}
/// One `timing:` line in the client's output channel.
///
/// `MessageType::LOG` and the same `window/logMessage` the per-file index
/// log uses — the channel is already this server's, and the one-word
/// prefix is what lets a reader (or a `grep`) pick these out of it. Sent
/// straight down the writer thread like every other notification, so it
/// cannot block on anything the loop is holding.
fn timing(&self, line: String) {
self.notify(
LogMessage::METHOD,
LogMessageParams { typ: MessageType::LOG, message: format!("timing: {line}") },
);
}
/// One line for a request the order contract makes wait, naming which of
/// [`Server::must_wait`]'s three clauses held it.
///
/// The question this answers is the one a slow-looking editor raises:
/// "was that request slow, or was it never started?". Silent for anything
/// that is not a request — nothing else waits.
fn say_held(&self, message: &Message) {
if !self.verbose {
return;
}
let Message::Request(request) = message else { return };
self.timing(format!(
"{} HELD behind a rescan (answering={}, wanted={}, already held={})",
request.method,
self.answering_a_rescan,
self.rescan_wanted,
self.held.len()
));
}
/// The byte offset an LSP position names in an open document.
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
}
}
/// How long ago, in milliseconds — the one unit every timing line is written
/// in, to two decimals so that a sub-millisecond answer is still a number.
fn ms(started: std::time::Instant) -> String {
format!("{:.2} ms", started.elapsed().as_secs_f64() * 1_000.0)
}
/// The `s` a count needs, or nothing. One file is not "1 files".
fn plural(count: usize) -> &'static str {
if count == 1 {
""
} else {
"s"
}
}
// ----------------------------------------------------------------------
// watching an index rebuild
// ----------------------------------------------------------------------
@@ -2727,8 +2881,12 @@ mod tests {
storage: Option<PathBuf>,
) -> Session {
let (server_end, client) = Connection::memory();
// Verbose off, which is how the server ships: every assertion in
// this module counts the messages a session produces, and the
// timing lines are tested where they are observable as protocol
// traffic — `tests/e2e.rs`, against the real binary and its flag.
let server =
Server::started(server_end, roots, abilities, settings, storage, Vec::new());
Server::started(server_end, roots, abilities, settings, storage, false, Vec::new());
Session { server, client }
}
@@ -2755,7 +2913,8 @@ mod tests {
for message in on_the_wire {
client.sender.send(message).expect("the client's wire traffic");
}
let server = Server::started(server_end, roots, abilities, settings, None, queued);
let server =
Server::started(server_end, roots, abilities, settings, None, false, queued);
Session { server, client }
}
+349
View File
@@ -95,7 +95,17 @@ fn temp_dir(name: &str) -> PathBuf {
/// processes the messages in order and exits on `exit`, so stdout closes and
/// the read terminates on its own.
fn talk(session: &str) -> Vec<serde_json::Value> {
talk_with(&[], session)
}
/// [`talk`] with arguments on the spawn.
///
/// The no-argument spawn above is the contract every editor uses and
/// `smoke.js` drives; this is for the one argument the server takes,
/// `--verbose` (`docs/features/verbose-timing/README.md`).
fn talk_with(args: &[&str], session: &str) -> Vec<serde_json::Value> {
let mut child = server_command()
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -3655,6 +3665,86 @@ fn a_flood_of_requests_and_cancels_is_answered_exactly_once_each() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The same flood, `--verbose` this time: the timing notify shares the
/// writer channel with every response, so this is where a reordering or an
/// interleaving in the byte stream would show up first.
///
/// **What a cancelled request's timing line looks like: none.** `request`
/// (the timing wrapper) is never reached for an id `process_batch` already
/// answered from the cancelled set — cancellation is resolved before
/// `self.request(request)` is called — so a cancelled id contributes no
/// `answered in` line at all. That is deliberate (there is nothing to time:
/// the handler never ran) and this test is what pins it, since neither the
/// feature README nor `tests/e2e.rs` said so before this round's QA pass
/// (`docs/features/verbose-timing/README.md`, QA log 2026-08-29).
#[test]
fn a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing() {
let dir = temp_dir("cancelflood_verbose");
let file = dir.join("m.sv");
let source: String = std::iter::once("module flooded;\n".to_string())
.chain((0..300).map(|i| format!("wire w{i};\n")))
.chain(std::iter::once("endmodule\n".to_string()))
.collect();
std::fs::write(&file, &source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let mut session = vec![
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&source).expect("json")
)),
];
for id in 10..30u32 {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)));
if is_cancelled(id) {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","method":"$/cancelRequest","params":{{"id":{id}}}}}"#
)));
}
}
session.push(frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#));
session.push(frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#));
let messages = talk_with(&["--verbose"], &session.concat());
// Every id still answered exactly once — a corrupted or reordered byte
// stream would show up here first, as a missing or duplicated answer.
let mut honoured = 0;
for id in 10..30u32 {
let answers: Vec<&serde_json::Value> = messages.iter().filter(|m| m["id"] == id).collect();
assert_eq!(answers.len(), 1, "id {id} was answered exactly once: {messages:#?}");
if answers[0].get("error").is_some() {
honoured += 1;
}
}
let shutdown = messages.iter().find(|m| m["id"] == 9).expect("a shutdown response");
assert!(shutdown.get("error").is_none(), "shutdown succeeded: {messages:#?}");
// And the timing lines agree with what actually ran: one
// `textDocument/formatting answered in` line per request that was NOT
// served from the cancelled set — never one for a cancelled id, which
// never reaches the timed wrapper at all.
let lines = timing_lines(&messages);
let answered_formatting = lines
.iter()
.filter(|l| l.starts_with("timing: textDocument/formatting answered in"))
.count();
let not_cancelled = 20 - honoured;
assert_eq!(
answered_formatting, not_cancelled,
"one timing line per request the handler actually ran, none for a cancelled one: {lines:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
const TYPEDEF_PKG: &str = "\
package e2e_tdp;
typedef enum logic [1:0] { IDLE, RUN } state_t;
@@ -5203,3 +5293,262 @@ fn a_jump_into_a_new_folder_indexes_that_folder_and_not_the_ones_before_it() {
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// `--verbose` — per-operation timing, over the wire
// ----------------------------------------------------------------------
/// Every `timing:` line the server said, in the order it said them.
///
/// They arrive as `window/logMessage` at `MessageType::LOG` (5), which is the
/// channel the per-file index log already uses — a client that shows one shows
/// both. The prefix is the whole of what tells them apart.
fn timing_lines(messages: &[serde_json::Value]) -> Vec<String> {
messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.filter(|line| line.starts_with("timing: "))
.map(str::to_string)
.collect()
}
/// A whole session over one small buffer: open it, type in it, ask two
/// questions about it, save it, shut down. Every kind of timing line but the
/// held one comes out of this, and nothing in it takes long enough to make an
/// assertion timing-dependent.
fn timed_session(dir: &Path) -> String {
let file = dir.join("top.sv");
let source = "module top;\n wire a;\n initial a = 1;\nendmodule\n// c\n";
std::fs::write(&file, source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
[
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(source).expect("json")
)),
// One keystroke inside the trailing comment: the buffer goes dirty,
// and the request behind it is what flushes it.
frame(&keystroke(&uri, 2, 4, 4)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentSymbol","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
// A save of a file the index already holds: the incremental path, not
// a whole rebuild.
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":10}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat()
}
#[test]
fn the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel() {
let dir = temp_dir("verbose_on");
let messages = talk_with(&["--verbose"], &timed_session(&dir));
let lines = timing_lines(&messages);
assert!(!lines.is_empty(), "`--verbose` must say something: {messages:#?}");
// A line per request, and the wording is the contract: the owner has read
// these for two diagnostic builds, and a `grep timing:` over an output
// channel is how this feature is used.
let answered = |method: &str| {
lines.iter().any(|line| {
line.starts_with(&format!("timing: {method} answered in ")) && line.ends_with(" ms")
})
};
assert!(answered("textDocument/documentSymbol"), "{lines:#?}");
assert!(answered("textDocument/hover"), "{lines:#?}");
// `shutdown` is deliberately absent: `handle_shutdown` answers it in the
// loop, ahead of the dispatch, so it never reaches the timed wrapper.
// Nothing measurable happens there, and a line for it would mean moving
// the handshake through code that has no business timing it.
assert!(!answered("shutdown"), "{lines:#?}");
// A line per notification, in the same shape with the other verb.
assert!(
lines.iter().any(|line| {
line.starts_with("timing: textDocument/didOpen handled in ") && line.ends_with(" ms")
}),
"{lines:#?}"
);
// And the scan lifecycle, both ends of it. This session's workspace is one
// file, so the counts are the small ones — what is pinned is the wording
// and that both ends arrive.
assert!(lines.iter().any(|line| line.starts_with("timing: scan started: ")), "{lines:#?}");
assert!(
lines.iter().any(|line| {
line.starts_with("timing: scan finished: ")
&& line.contains(" skipped, ")
&& line.contains(" from cache) in ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// And the widen lifecycle, which this session reaches by opening a file:
// the folder it added is named, because "which folder did that jump cost
// me?" is the question the line exists to answer
// (`docs/features/index-scope/README.md`).
assert!(
lines.iter().any(|line| {
line.starts_with("timing: widen started: 1 folder added: ")
&& line.ends_with(&dir.display().to_string())
}),
"{lines:#?}"
);
assert!(
lines.iter().any(|line| {
line.starts_with("timing: widen finished: ")
&& line.contains(" from cache) in ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// The two lines that name work nobody asked for by message: the flush of
// what was typed, and the one-file reindex a save costs.
assert!(
lines.iter().any(|line| {
line.starts_with("timing: flush of 1 dirty buffer took ") && line.ends_with(" ms")
}),
"{lines:#?}"
);
assert!(
lines.iter().any(|line| {
line.starts_with(&format!("timing: reindex_one({}", dir.join("top.sv").display()))
&& line.contains(") took ")
&& line.ends_with(" ms")
}),
"{lines:#?}"
);
// The stated ordering: a request's timing line goes out **before** the
// response it describes. Nothing keys off that — a `window/logMessage`
// carries no id — but it is the contract this round wrote down, and the
// only way to notice it change is to pin it.
let line_at = messages
.iter()
.position(|m| {
m["params"]["message"]
.as_str()
.is_some_and(|line| line.starts_with("timing: textDocument/hover answered in "))
})
.expect("the hover's timing line");
let response_at = messages.iter().position(|m| m["id"] == 3).expect("the hover's response");
assert!(
line_at < response_at,
"the line describes the response that follows it: {messages:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn without_the_flag_not_one_timing_line_is_ever_sent() {
// The other half, and the one that matters: the shipped spawn — no
// arguments, which is what `smoke.js` and every editor use — must be
// byte-for-byte as quiet as it was before this feature existed.
let dir = temp_dir("verbose_off");
let messages = talk(&timed_session(&dir));
assert_eq!(timing_lines(&messages), Vec::<String>::new(), "{messages:#?}");
// And it is the same session, really answered: a server that failed to
// start would also say nothing.
assert!(messages.iter().any(|m| m["id"] == 2), "the symbols were answered: {messages:#?}");
assert!(messages.iter().any(|m| m["id"] == 9), "and the shutdown: {messages:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_request_queued_behind_a_rescan_says_it_was_held() {
// The line the owner asked for by name, and the one a "why is my editor
// slow?" session is about: the request was not slow, it had not started.
//
// Driven through the real mid-scan machinery: a filelist of 100 files is
// the startup scan's work list — over `INTERLEAVE_ABOVE`, so the scan
// answers messages between its files — and the whole session is already on
// the wire when it begins. The settings push it drains asks for a rescan,
// which mid-scan is the `rescan_wanted` flag; every request behind it is
// owed that rescan's effect, so it waits. See
// `docs/features/scan-interleave/README.md`.
let dir = temp_dir("verbose_held");
let files = 100usize;
let mut list = String::new();
for n in 0..files {
let name = format!("m{n}.sv");
std::fs::write(dir.join(&name), generated_module(&format!("m{n}"), 200)).expect("write");
list.push_str(&format!("{name}\n"));
}
std::fs::write(dir.join("files.f"), &list).expect("write");
std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write");
let root = format!("file://{}", dir.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
// Changes which files exist, so it asks for a rebuild — the one thing
// a request behind it must not be answered ahead of.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"exclude":["no-such-directory"]}}}}"#,
),
frame(r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"m7"}}"#),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk_with(&["--verbose"], &session);
let lines = timing_lines(&messages);
let held: Vec<&String> = lines.iter().filter(|line| line.contains(" HELD ")).collect();
assert!(
held.iter().any(|line| {
line.starts_with("timing: workspace/symbol HELD behind a rescan (answering=")
&& line.contains(", wanted=")
&& line.contains(", already held=")
}),
"the symbol request must say it waited: {lines:#?}"
);
// Held is not dropped: the order contract answers it once the rescan it
// was queued behind has run.
let answered = messages.iter().find(|m| m["id"] == 2).expect("the symbol response");
assert!(answered["error"].is_null(), "{answered:#?}");
assert!(
lines.iter().any(|line| line.starts_with("timing: workspace/symbol answered in ")),
"and it is timed like any other request: {lines:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_argument_the_server_does_not_take_is_refused_rather_than_ignored() {
// The spawn contract's new edge: no arguments and `--verbose` start a
// server, anything else exits 2 with one line on stderr. A client that
// misspelled the flag learns it here rather than wondering for a whole
// session why nothing is logged.
let refused = server_command()
.args(["--verbos"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("the server binary starts");
assert_eq!(refused.status.code(), Some(2), "{refused:?}");
let said = String::from_utf8_lossy(&refused.stderr);
assert!(said.contains("unknown option: --verbos"), "{said}");
assert!(said.contains("usage: lucisv-server [--verbose]"), "{said}");
assert!(refused.stdout.is_empty(), "nothing LSP-shaped on stdout: {refused:?}");
}
+15 -1
View File
@@ -104,7 +104,21 @@ change. No `initializationOptions` fallback is needed, and none was added.
`extractSettingsInformation(['lucisv'])` calls
`workspace.getConfiguration(undefined).get('lucisv')`, which returns the whole
section with every key at its effective value — so the server sees
`serverPath` and `rainbowBeginEnd` in the payload too, and ignores them.
`serverPath`, `rainbowBeginEnd` and `verbose` in the payload too, and ignores
all three.
**Two settings in the section are deliberately not wire settings**, and the
list is worth keeping short:
- `lucisv.serverPath` decides *which binary* the extension spawns, so it can
only be read before there is a server to tell.
- `lucisv.verbose` (2026-08-29) decides *how* it is spawned — it becomes the
`--verbose` argument, and a process argument cannot be changed by a
notification. Hence the one thing no other setting here does: changing it
restarts the language server. It is a startup decision, not an opinion the
server can adopt mid-session, and giving it a second spelling as a wire
setting would mean two ways to say one thing that could disagree. See
`docs/features/verbose-timing/README.md`.
Other editors: anything that can send `workspace/didChangeConfiguration` with
that `settings` shape works. Neovim's `vim.lsp.config` sends its `settings`
+25 -3
View File
@@ -12,6 +12,25 @@ loop, document state, position arithmetic, and one small handler per
capability. It deliberately contains no analysis of its own; anything that
looks like language knowledge in here is a bug or a `Handshake` request.
## Starting it: the argument contract
`lucisv-server` needs **no arguments** — that is the spawn every editor uses,
the one `editors/vscode/smoke.js` drives, and it is unchanged. Since
2026-08-29 it also *accepts* exactly one:
| argument | effect |
|---|---|
| *(none)* | The shipped server. Silent unless something is worth saying. |
| `--verbose` | Every operation says how long it took, as `timing:` lines in the client's log channel (`window/logMessage`, `MessageType::LOG`). Repeats are idempotent. See `docs/features/verbose-timing/README.md` |
| anything else | `error: unknown option: <arg>` and `usage: lucisv-server [--verbose]` on **stderr**, exit **2** — the CLI's own wording and its "an error occurred" code. Nothing is started |
There is no `-v`, no `--help` and no `--version`: one spelling for the one
flag, and the version number lives on the `lucisv` CLI, which is where
`tools/release.sh` reads it. Anything that is not a startup decision is an
`lucisv.*` setting instead, pushed or pulled over the protocol — a flag can
only be changed by spawning again, which is why `lucisv.verbose` is the one
VS Code setting that restarts the server.
## Capabilities as shipped
| LSP request | Engine it consumes | Notes |
@@ -491,9 +510,12 @@ called by the request handler.
**Consumed from `vlog_formatter`:** `format_source(&str, &Config) ->
Result<String, FormatError>` and `Config { max_width, indent_width }`.
**Promised to nobody yet.** This crate is a leaf: it has no library target and
nothing depends on it. The editor packaging round (TODO.md §6) will consume
the binary's name and its stdio contract, nothing else.
**Promised to the editors:** the binary's name, its stdio contract, and — since
2026-08-29 — its *argument* contract: no arguments required, `--verbose` the
only one accepted, every other one refused with exit 2 (the table under
"Starting it" above; TOPO.md §1.2's `editors/vscode ◀──▶ lucisv_server` row;
`docs/features/verbose-timing/README.md`). Beyond that this crate is a leaf: it
has no library target and nothing in the workspace depends on it.
**Requested of other modules** — none of these block this round, and none was
done here:
+888
View File
@@ -0,0 +1,888 @@
# verbose-timing
## Goal
`lucisv-server --verbose` makes the server say how long every operation took,
as `timing:` lines in the client's own log channel. It is the diagnostic build
the lead produced twice by hand-patching, made permanent and opt-in: the same
lines, the same wording, now shipped behind one flag instead of a rebuild. The
question it answers is the one a user asks when the editor feels slow — *was
that request slow, or was it never started?* — and the two lines that answer it
are `<method> answered in X ms` and `<method> HELD behind a rescan`. Off is the
shipped state and costs one branch per timed site: no clock read, no
`format!`, no notification. VS Code turns it on with `lucisv.verbose`, which
restarts the server because the flag is a spawn argument.
## What it prints
Every line is one `window/logMessage` at `MessageType::LOG`, prefixed
`timing: ` — the same channel and the same message type the per-file index log
(`lucisv.index.logFiles`) already uses, so a client that shows one shows both
and `grep timing:` separates them. Durations are milliseconds to two decimals,
from one helper (`ms`), so a 60 µs hover reads as `0.06 ms` rather than `0 ms`.
| line | where | says |
|---|---|---|
| `timing: <method> answered in X ms` | `Server::request` | One request, handler only — the flush it triggers, the analysis, the answer |
| `timing: <method> handled in X ms` | `Server::notification` | One notification, including any rescan it caused |
| `timing: <method> HELD behind a rescan (answering=…, wanted=…, already held=N)` | `Server::process_batch` | The request did not start: the order contract made it wait. The three fields are `must_wait`'s three clauses, so the line names *which* one held it |
| `timing: scan started: N file(s)[, interleaved]` | `Server::scan_once` | The work list's size, and whether the scan will answer messages between its files (`total > INTERLEAVE_ABOVE`) |
| `timing: scan finished: N file(s) (S skipped, C from cache) in X ms` | `Server::scan_once` | The same counts the progress bar's closing message carries, with the time |
| `timing: widen started: N folder(s) added: <paths>` | `Server::reindex_widened` | Which folders a `didOpen` added to the scope, by name |
| `timing: widen finished: N file(s) (S skipped, C from cache) in X ms` | `Server::reindex_widened` | What that cost |
| `timing: flush of N dirty buffer(s) took X ms` | `Server::flush_dirty` | The debounced reparse a typing burst was coalesced into |
| `timing: reindex_one(<path>) took X ms` | `Server::reindex_one` | The one-file incremental index update a save takes |
Three absences are deliberate:
* **`shutdown` is never timed.** `Connection::handle_shutdown` answers it in
the loop, ahead of the dispatch, so it never reaches the timed wrapper.
Nothing measurable happens there and routing the handshake through the
wrapper to get a line would be worse than not having one.
* **A scan a `shutdown` interrupted prints no `finished` line**, and a
`reindex_one` that declined (the file was not in the index) prints nothing
either: the first must not speak to a client that has gone, and the second
did no work — its caller is about to rebuild the whole index, and *that*
times itself.
* **A cancelled request prints no `answered in` line.** `process_batch`
resolves `$/cancelRequest` before `Server::request` (the timing wrapper) is
ever called — a cancelled id is answered from the cancelled set directly —
so the handler never ran and there is nothing to have timed. Pinned by
`a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing`
in `tests/e2e.rs` (QA, 2026-08-29).
## Ordering: the line comes **before** the response
A request's timing line is sent before the response it describes. The dispatch
is `Server::request`, and the response is sent by its caller
(`process_batch`), so a wrapper around the dispatch can only speak first. That
was chosen over threading the start time out to the caller because it keeps the
measurement to exactly the handler, with none of the transport in it, and it
keeps the shape the two diagnostic builds already had.
Nothing keys off the order. A `window/logMessage` carries no id; a client pairs
a response with its request by id, whatever arrived in between. The one real
consequence — that in verbose mode a response is preceded by one extra small
write — is the cost of the flag and is why it is off by default. The e2e test
`the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel`
pins the order, so a future change to it is a deliberate one.
## The restart: one chain, reconciled to the last toggle
`--verbose` is a spawn argument, so `lucisv.verbose` can only take effect by
starting a new process. That makes the extension's restart the one piece of
this feature with a concurrency problem, and `editors/vscode/restart.js` is
the whole of the answer to it.
**The rule: there is exactly one chain of transitions, no transition exists
outside it, and it always reconciles to the last arguments anybody asked
for.**
- Every toggle writes what it wants into `desiredArgs` **synchronously** and
queues a reconcile onto the same promise (`chain = chain.then(reconcile)`).
Nothing else starts or stops the client — the **activation spawn is the
first link of that chain too**, which is the part that matters: a start is
in flight for as long as the first workspace scan takes, and that is exactly
when a user reaches for the setting.
- A reconcile that finds the running arguments already equal to the desired
ones does nothing. That is what collapses a burst of toggles — `on`, `off`,
`on` — into at most one restart, landing on the last one.
- Otherwise: `stop()` (awaited, and a rejection is tolerated — a client that
is not running cannot be stopped, and because this is on the chain, nobody
else is stopping it), write the arguments into `serverOptions.args` (the
client re-reads that object at every `start()`), `start()` (awaited), then
repaint.
- A `start()` that rejects records "nothing is running", so the next toggle
retries whatever it asks for, and is reported through the same handler
activation failures use rather than swallowed by an anonymous `catch {}`.
The chain survives it.
- **Teardown is a link of the chain too.** `deactivate()` calls
`restarter.dispose()` and awaits it; it never touches `client.stop()`
itself. `dispose()` shuts the door — `want()` becomes a silent no-op, and
any reconcile *already queued* returns without doing anything — and then
puts one final stop on the same chain, which is what the returned promise
resolves after. Idempotent, and a dispose before anything was spawned stops
nothing.
That last bullet is the second half of the same invariant, and it was learned
the same way. `deactivate()` used to await a **snapshot** of the chain and then
stop the client itself. A `lucisv.verbose` event landing in the same tick
mutated the live chain and queued a whole reconcile — stop, then **spawn** —
as a sibling of that stop, with nothing left to await the new process: QA
reproduced `stop, stop, start(--verbose)` against the shipped module (finding
3, 2026-08-29). When the whole window closes that server dies with its parent's
stdin, but an extension *disable* or an extension-host-only restart leaves the
host alive and the process orphaned. Two guards close it, and both are wanted:
the one in `want()` keeps the chain from growing after teardown, and the one
inside `reconcile()` catches the toggle that got into the queue *first* — the
chain only promises that a queued reconcile runs after `dispose()` was called,
not that it was never queued.
Why it has to be a chain rather than a guard: `vscode-languageclient` 9's
`start()` returns the *in-flight* start whenever one exists (`client.js:642`),
and its `stop()` rejects while the client is still `Starting`
(`client.js:960`). A restart that just calls `stop()` then `start()` therefore
stops nothing, rejoins the start that was already running **with the old
arguments**, and reports success — the user believes the toggle worked while
the server has never heard of it. That was QA finding 1 (2026-08-29), and the
chain removes the precondition for it: no transition ever begins while another
is in flight, so there is no in-flight start to rejoin.
`restart.js` knows nothing about VS Code — it takes a client-like object with
`start()`/`stop()`. That is what lets `editors/vscode/restart_test.js`
(`node restart_test.js`, plain node, no dependencies, run like `smoke.js`
beside it) drive **this** logic against a scripted fake, rather than
re-implementing the language client's state machine and testing the copy.
## Why the in-loop send cannot deadlock
Every timing line goes out through `Server::notify`, the same fire-and-forget
path the diagnostics push, the scope warnings and the per-file index log have
always used, on the same thread, holding no lock (this server has none — it is
one thread and `lsp-server`'s two I/O threads).
`lsp-server` 0.10.0's stdio transport makes the writer channel `bounded(0)`, so
a send waits for the writer thread to take the message. That thread does
exactly one thing — write the message to stdout and hand it to a dropper thread
— and never sends anything back into the loop, so there is no cycle to close.
If it has exited, the receiver is dropped and the send returns `Err`, which
`notify_on` discards: a client that has gone is nobody to report to. The only
way a send can wait is a client that has stopped reading its own stdout, and
that already blocks every diagnostic and every one of the hundreds of per-file
log lines a scan sends — verbose adds volume there, not a new hazard.
Ordering is likewise unchanged: one channel, one writer thread, FIFO. A timing
line sent before a response is written before it, and the two can never
interleave.
## Assumptions
- **The client shows `MessageType::LOG`.** `vscode-languageclient` 9 appends
it verbatim to the extension's output channel (its `LogMessageNotification`
handler falls through to `outputChannel.appendLine`), which is where the
index log already lands. A client that drops LOG messages sees nothing —
the same deal `lucisv.index.logFiles` has always had.
- **A user who turns this on accepts the volume.** A busy session logs a line
per keystroke (the flush) and per request. That is stated in the setting's
description rather than rate-limited: a sampled diagnostic is a lying one.
- **Two decimals of a millisecond is enough resolution.** The fastest thing
timed here is a cursor answer at ~0.05 ms; nanoseconds would be noise from
the clock read itself.
- **Nobody parses these lines.** They are for a person reading a channel.
Nothing in the repo greps them except this feature's own tests.
## Handshakes
**Amends `editors/vscode ◀──▶ lucisv_server` (TOPO.md §1.2).** The spawn
contract said "binary named `lucisv-server`, no args, no env, LSP over stdio,
…". It now reads, in that row:
> The extension passes exactly `[]` by default or `['--verbose']` when
> `lucisv.verbose` is true; the server accepts only that spelling (repeats are
> idempotent) and refuses any other argument with exit 2. Changing that
> setting restarts the server because it is a process argument, not an LSP
> setting. […] `smoke.js` still drives the default no-argument contract
> headlessly; `tests/e2e.rs` pins both spawns.
Both halves of that are load-bearing and both are pinned:
- **The no-argument spawn is unchanged**, which is what `smoke.js` drives (its
spawn untouched this round, still passing) and what
`without_the_flag_not_one_timing_line_is_ever_sent` proves stays silent.
- **An argument the server does not take is refused, not ignored.** Today's
server ignores `std::env::args` entirely, so `lucisv-server --verbos` would
have started a perfectly normal server that logged nothing, and the user
would have had no way to tell that from a broken feature. Exit 2 matches the
CLI's own "an error occurred" code and its `error: unknown option: …`
wording. There is deliberately **no** `-v`, `--help` or `--version`: one
spelling, and the version lives on the `lucisv` CLI, which is where
`tools/release.sh` reads it (TOPO.md §1.2, `tools/` handshake).
**Consumed from `editors/vscode`:** the `lucisv.verbose` setting, whose
`false` default and the server's "no argument means off" are pinned against
each other by `the_extension_ships_the_flag_off_which_is_what_no_argument_means`
in `main.rs`, reading `package.json` — the same manifest-vs-shipped-defaults
check `settings.rs` makes for `scopeDepth` and `maxFileSize`.
**Promised to nobody else.** The lines are not a wire format: no client parses
them, and `lucisv.verbose` is not a *server* setting — the server never reads
it out of the `lucisv` section it is pushed (it is spawn-time or nothing), so
`settings.rs` is untouched by this round.
## Status / TODO
- [x] `--verbose` parsed in `main.rs`; unknown arguments exit 2 with a usage
line on stderr; the flag threaded to `Server` as one `bool`.
- [x] `Server::request` / `Server::notification` are timing wrappers around
`answer_request` / `handle_notification`.
- [x] The `HELD` line, naming which `must_wait` clause held the request.
- [x] Scan, widen, flush and `reindex_one` lifecycle lines.
- [x] `timer` / `timed` / `timing` / `ms`, so verbose-off is one branch per
site and nothing else.
- [x] Verbose-off cost measured against HEAD (see the work log).
- [x] `lucisv.verbose` in `package.json`, passed in the spawn args, and a
restart when it changes.
- [x] That restart is **one serialized chain reconciling to the last toggle**
(`editors/vscode/restart.js`), with the activation spawn as its first
link — QA finding 1, reworked 2026-08-29.
- [x] And **teardown is a link of the same chain**: `deactivate()` awaits
`restarter.dispose()`, which shuts the door (in `want` and in a queued
`reconcile`) before its final stop, so no toggle can spawn an orphan on
the way out — QA finding 3, reworked 2026-08-29.
- [x] `node editors/vscode/restart_test.js`: eleven cases over that chain
against a scripted fake client, mutation-checked five ways.
- [x] e2e: the flag times things, the absence of it times nothing, a held
request says so, an unknown argument exits 2.
- [x] e2e: a cancelled request is timed for exactly what ran, and nothing is
reordered under a flood (QA, 2026-08-29).
- [x] `smoke.js` unchanged in behaviour and still passing.
- [x] Contract amended in TOPO.md, `lucisv-server`, `editor-settings`, both
editor READMEs.
- [ ] Not done, deliberately: no `--verbose` on the `lucisv` CLI (it formats
files; there is no session to time), no log file, no rate limit, no
per-category filter. If the volume turns out to be the problem, the next
round is a *filter*, not a sampler.
- [ ] Known, not this round's to fix: after a start that *failed*,
`vscode-languageclient` 9 never clears its `_onStart`, so a later
`start()` re-joins the rejected promise — the chain's retry asks
correctly and the library declines, and a window reload is still needed
to recover from a bad `lucisv.serverPath`. Pre-existing (QA, 2026-08-29);
the retry is the right shape either way and costs nothing.
## Work log
### 2026-08-29 — dev agent (rework 2, after QA finding 3, MEDIUM)
QA's re-verification closed finding 1 (their two mutations were caught by the
shipped test) and found one more transition outside the chain: `deactivate()`
itself. It awaited `restarter.settled()` — a *snapshot* of the chain — and then
called `client.stop()` beside it, so a `want()` landing in the same tick queued
a full reconcile, spawn included, that nothing was left to await. Their trace
against the shipped module: `stop, stop, start(["--verbose"])`. Self-healing
when the window closes (the child's stdin dies with the parent), an orphan when
the extension host outlives the module — a disable, or a host-only restart.
Fixed to the lead's ruling, ten lines:
- `restart.js` gains `disposed` and `dispose()`. The flag is set synchronously
and checked in **two** places: the top of `want()` (nothing new is accepted,
and the chain does not even grow — `want` hands back the teardown promise)
and the top of `reconcile()` (whatever was already queued does nothing). The
second is the load-bearing one: a toggle can beat `dispose` into the queue by
a tick, and the chain only guarantees it *runs* afterwards.
- `dispose()` then chains one `stopForGood` onto the same `chain` and returns
that link, so awaiting it means "the server is stopped", not "the stop was
queued". It stops nothing when nothing was spawned (the real client rejects
a stop of a client that never ran), tolerates a rejected stop (teardown —
nobody can act on it), and is idempotent, with every caller's promise
resolving after the one real stop.
- `extension.js`'s `deactivate()` is now `return restarter ?
restarter.dispose() : undefined` and no longer names `client.stop()` at all.
With that, `grep '\.start(\|\.stop('` over `extension.js` finds no client
transition outside the restarter, which is the invariant the module header
claims — QA checked that grep last pass and it is now true.
`restart_test.js` grows four cases (11 total, 44 checks): QA's exact repro (a
`want()` in the same tick as `dispose()` spawns nothing, and a later toggle
adds no link at all); a reconcile queued *before* `dispose()` becoming a no-op;
`dispose()` resolving only after the final stop, twice-in-one-tick included;
and a dispose before anything was spawned stopping nothing. Mutation-checked to
five now, each caught and each file restored byte-identical: dropping the
`disposed` check in `reconcile` (the half the ruling named), dropping it in
`want`, returning from `dispose` before its stop finishes, hanging that stop
beside the chain instead of on it, and stopping a client that was never
started.
Also took QA's LOW comment nit in
`aFailedStartIsReportedAndTheChainStaysUsable`: the comment said the retry is
"what a user who fixed their `serverPath` does", which reads as though the
retry works against the real client. It does not — `_onStart` is never cleared
after a failed start — so the comment now says what the test actually pins:
`restart.js` keeps *asking*, and whether the ask can succeed is the known
library limitation recorded in Status / TODO.
No `crates/` change in this iteration; the server side is untouched by both
reworks.
### 2026-08-29 — dev agent (rework after QA finding 1, HIGH)
QA found the restart could **silently lose a toggle**: with a `start()` in
flight, `stop()` rejects (swallowed), `start()` rejoins the in-flight start
with the old arguments, the extension repaints, and nothing anywhere says the
setting did not take. Their trace of the vendored client
(`client.js:642-653`, `960-965`, `988-992`) is in the QA log; their repro
harness re-implemented that state machine and was rightly not committed.
Fixed to the lead's ruling — serialize, and reconcile to the last desired
state. New module `editors/vscode/restart.js` (~90 lines, no VS Code
dependency, shipped) holding `createRestarter({ client, serverOptions,
onStarted, onStartFailed })`:
- `desiredArgs` is written synchronously by every `want(args)`; `runningArgs`
is what the live process was actually spawned with (`null` when none is).
- One `chain`; `want()` and `start()` both do
`chain = chain.then(reconcile).catch(onStartFailed)`. **`activate` now
spawns through `restarter.start()` instead of calling `client.start()`
directly** — that is what closes the finding, since the activation start was
the in-flight start being rejoined.
- `reconcile()` returns immediately when `sameArgs(runningArgs, desiredArgs)`
(so a burst collapses to one restart), else stops (tolerating a rejection),
writes `serverOptions.args`, starts, repaints. A rejected `start()` sets
`runningArgs = null` and rethrows, so the failure is reported *and* the next
toggle retries. `sameArgs(null, anything)` is false, `null` included, which
is what makes that retry possible.
- `onStartFailed` is `reportStartFailure` in `extension.js`, now shared with
activation: one line into the client's own output channel (no popup — the
client already reports the spawn failure itself, and activation never opened
one), wrapped in case there is no channel to write to.
- `deactivate()` now waits for the chain before stopping, for the same reason
the toggles do.
**The test seam and the test.** `restart.js` takes a client-like object, so
`editors/vscode/restart_test.js` drives *our* rule against a fake whose
`start()`/`stop()` the test settles by hand — no re-implementation of the
library's state machine, which is what made QA's harness uncommittable. Plain
node, no dependencies, `node editors/vscode/restart_test.js`, exit 0/1, the
same invocation style as `smoke.js` beside it; documented in `README.md`
("Checking the server without an editor") and in `tools/RELEASING.md`'s
`.vscodeignore` bullet. Seven cases, 28 checks:
1. activation spawns once with the settings' arguments;
2. **the finding**: a toggle during the in-flight activation start spawns
nothing while that start is running, then restarts onto `--verbose` once it
finishes (and `serverOptions.args` is what the second start reads);
3. `on`→`off`→`on` during an in-flight start costs **one** restart, landing on
the last toggle;
4. asking for what is already running restarts nothing;
5. a rejected `start()` is reported once, records nothing as running, and the
chain still retries the next toggle;
6. a rejected `stop()` does not cost the start that was asked for;
7. `sameArgs` compares by value and treats `null` as "nothing running".
Deliberately mutation-checked, because a green test proves nothing on its own:
removing the chaining fails case 2 ("nothing else may spawn while it is"),
keeping `runningArgs` after a failed start fails case 5, and reconciling to
the old arguments instead of the desired ones fails case 2's landing
assertion. A watchdog timer fails the run rather than letting node exit 0 in
silence if a promise never settles — which it did during development, and is
a trap worth keeping shut. `.vscodeignore` excludes `restart_test.js` (and
still `smoke.js`); `restart.js` itself must ship, which `RELEASING.md` now
says out loud with the `unzip` check.
QA's own LOW (a cancelled request gets no timing line, documented as the third
deliberate absence and pinned by
`a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing`)
is kept as they left it. The server side is unchanged by this rework.
### 2026-08-29 — dev agent
**Server.** `verbose_flag` in `main.rs` walks `std::env::args().skip(1)`:
every argument must be `--verbose` (repeats are fine — they say the same thing
twice), and the first one that is not is returned and reported. `main` refuses
before `Connection::stdio()` is built: answering LSP anyway would hide the
mistake for a whole session. The flag becomes `Server { verbose: bool }`
(`Server::new` and the test seam `Server::started` each take one more
argument).
`request` and `notification` became timing wrappers; the old bodies are
`answer_request` and `handle_notification`, unchanged. Each wrapper's first
statement is `let Some(started) = self.timer() else { return … }`, so
verbose-off is a field read and a branch — no `Instant::now`, no method clone,
no `format!`. The other five sites use the same `timer()` plus `timed(started,
|took| …)`, whose closure is never called when the timer is `None`; the two
"started" lines (scan, widen) are under `if started.is_some()`.
Decisions worth naming:
- **The line precedes the response** — argued in full above, and pinned by a
test rather than left to a reader.
- **`scan started: N file(s) …`** — the brief's ellipsis is resolved to
`, interleaved` when the scan is over `INTERLEAVE_ABOVE` and to nothing
otherwise. It is one word, it is decided at exactly that point, and it is
the second half of the `HELD` answer: a scan that does not interleave
answers nothing at all until it is done.
- **One duration format for every line.** The brief wrote `X.XX ms` for
requests and `X ms` for the lifecycle lines; both go through `ms()` and read
as `X.XX ms`. Two formats would have been a difference with no meaning.
- **Counts are pluralized** (`1 file`, `0 files`) rather than printing a
literal `file(s)`, which is what `end_indexing` next door already does.
- **`shutdown` is not timed**, because it never reaches the dispatch — found
by an assertion that expected it to be there, now inverted and commented.
**Extension.** `serverArgs()` reads `lucisv.verbose` (`=== true`, so nothing
but a real boolean turns it on) and is called once at activation for
`serverOptions.args`, and again by every toggle. This extension had **no**
restart-on-settings path before; `lucisv.serverPath` still needs a window
reload, which this round deliberately did not change.
*(The first cut of the restart — a straight-line
`stop()`/write-args/`start()` guarded by comparing the new arguments with
`serverOptions.args` — lost a toggle that arrived while a `start()` was in
flight. It was rewritten as the reconcile chain below after QA finding 1;
see the rework entry.)*
The decorations are repainted after each successful start, because they went
with the old connection.
**Tests.** Four e2e cases, and `talk_with(args, session)` so a test can spawn
with arguments (`talk` is now its no-argument case, which is the contract
`smoke.js` drives):
- `the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel`
— one session that opens a buffer, types in it, asks two questions, saves,
and shuts down: it produces every kind of line but `HELD`, and each is
asserted by its exact prefix. It also pins the line-before-response order.
- `without_the_flag_not_one_timing_line_is_ever_sent` — the same session over
the shipped spawn: zero `timing:` lines, and the answers still arrive (a
server that failed to start would also be quiet).
- `a_request_queued_behind_a_rescan_says_it_was_held` — 100 generated files in
a filelist make the startup scan interleave; the session's settings push is
drained mid-scan and asks for a rebuild, so the `workspace/symbol` behind it
is held, says so, and is answered afterwards.
- `an_argument_the_server_does_not_take_is_refused_rather_than_ignored` —
`--verbos` exits 2, names the option, prints the usage line, and puts
nothing on stdout.
Plus `the_extension_ships_the_flag_off_which_is_what_no_argument_means` and
three `verbose_flag` unit tests in `main.rs`.
**Docs.** The contract is amended in five places, because five documents state
it: TOPO.md §1.2's spawn-contract row (see the note at the end of this entry),
`lucisv-server`'s README (a new "Starting it: the argument contract" table, and
its Handshakes section, which said the binary promised nobody anything and now
names the argument contract), `editor-settings`' README (the two settings in
the `lucisv` section that are *not* wire settings, and why one of them
restarts the server), `editors/vscode/README.md`'s settings table, and
`editors/nvim/README.md` (a worked example, including the fact that Neovim
writes `window/logMessage` at info level and drops it at the default `WARN`
log level). `TODO.md` has no item this completes — the backlog never asked for
instrumentation — so it is untouched.
`smoke.js` is unchanged in behaviour: the only edit is the comment above the
spawn, which claimed the extension passes no arguments and now says it passes
none *by default*. It still spawns with `[]` and still passes.
**The verbose-off cost, measured against HEAD.** The claim is that a server
built with this round and started *without* the flag is indistinguishable from
the one at HEAD. Both are release builds of the same tree — HEAD's binary was
built and copied aside before the first edit — and each was driven through the
same scripted session: one 400-line buffer, 2,000 `textDocument/hover`
requests, client-observed round trips on a monotonic clock
(`time.perf_counter`), five runs of each binary, strictly alternating, on an
M1 Max.
| binary | each run's median, sorted | median of those |
|---|---|---:|
| HEAD `46e7b31…`, no args | 0.0265 0.0268 0.0268 0.0274 0.0283 | **0.0268 ms** |
| this round `21da327…`, no args | 0.0261 0.0262 0.0271 0.0280 *0.0510* | **0.0271 ms** |
| this round, `--verbose` (3 runs) | 0.0413 0.0451 0.0454 | **0.0451 ms** |
The off path is **unmeasurable**: the two no-argument binaries are 0.3 µs
apart — about 1 %, against a 1.8 µs spread *between runs of the same binary* —
and the new one is the faster of the pair in three of the five pairings, which
is the shape of noise rather than of a cost. That is what one predictable
branch on a `bool` field buys you: nothing this instrument can see. (The
italicized 0.0510 is the very first run after the binary was copied into place,
with the file cache cold and the machine still busy from the build; it is left
in the table rather than dropped, and the median is why it does not matter.)
Turning the flag **on** costs 14–18 µs per request, which is the extra
`window/logMessage` written before the response. That is half again as long as
a null hover like this probe's, and about 1 % of the 1.35 ms a real cold hover
over opentitan takes (`performance.md` §2). It is a real cost, which is why the
shipped state is off — but it is nowhere near large enough to change what the
lines it buys are measuring.
The probe is
`…/scratchpad/verbose_cost.py <binary> [--verbose]`; it needs no fixture but
its own temp buffer, so it can be re-run against any two builds.
**Note on TOPO.md.** The spawn-contract row this round amends was rewritten in
`topo.md` from outside this work while it was in progress (the file is
`TOPO.md`/`topo.md`, one file on a case-insensitive filesystem; its mtime moved
mid-round, and the whole document was re-dated to 2026-08-29 for several
rounds at once). The amendment already there states exactly what was built —
`[]` or `['--verbose']`, every other argument refused with exit 2, the restart
on the setting, `smoke.js` still driving the default spawn — so it was left
alone rather than written twice. Nothing else in the tree was touched from
outside; `git diff --stat` at the end of this round is this round's files plus
that one document.
## QA log
### 2026-08-29 — QA agent
Adversarial pass over the round described in the work log above. Verified by
**reading**: `crates/lucisv_server/src/main.rs`, `server.rs` (the whole diff,
line by line), `editors/vscode/extension.js` (the whole diff, and its
existing code around `client`), `editors/vscode/node_modules/vscode-languageclient`
9.0.1's `lib/common/client.js` (the real `start()`/`stop()`/`shutdown()` state
machine this round's restart relies on), `topo.md`, and every touched doc.
Verified by **test**: gates below, plus one new permanent regression test and
a standalone headless harness (not committed — see finding 1).
**Finding 1 — HIGH — `restartForVerbose` silently drops the toggle if it is
called while a `start()` is already in flight.** `editors/vscode/extension.js:284-304`.
`vscode-languageclient` 9.0.1's `BaseLanguageClient.start()` (`client.js:642-653`)
returns the *existing* `_onStart` promise whenever one is set, regardless of
whether the client is `Starting` or `Running` — it only throws when the state
is `Stopping`. `_onStart` is set the moment the first `start()` call begins
and is cleared **only** by a stop that actually reaches `cleanUp()`
(`client.js:988-992`). Consequently, a `client.stop()` issued while the state
is `Starting` hits `shutdown()`'s `"Client is not running and can't be
stopped"` branch (`client.js:960-965`) and rejects — which
`restartForVerbose`'s `try/catch` swallows exactly as it swallows "nothing to
stop" — and the subsequent `await client.start()` then just **joins the
original, already-in-flight start**, which captured the *old* `args` before
the toggle ever wrote the new ones into `serverOptions.args`. The function
then reaches `repaintVisible()` with no exception, no rejected promise, no
message anywhere — from the user's point of view the toggle "worked."
This is exactly the scenario the brief names ("toggle while the server is
mid-scan"): a large workspace's startup scan keeps `initialize()` — and
therefore `start()` — in flight for a while, and any `lucisv.verbose` toggle
during that window is lost. It also fires on a second toggle arriving before
a *previous* restart's own `start()` has resolved, i.e. it is not limited to
the very first activation.
Repro (headless, no real VS Code — see "what could not be tested" below):
mock `vscode` and replace `vscode-languageclient/node`'s `LanguageClient`
with a fake whose `stop()`/`start()` reproduce the state transitions read
above (join-if-in-flight, throw-if-not-Running/Stopping); `activate()` a
context, flip the fake `lucisv.verbose` setting and fire
`onDidChangeConfiguration` once, 5ms into a 30ms fake startup `start()`
(modeling a slow initial scan), then let everything settle. Observed:
```
spawn attempt #1 args=[]
running with args=[]
setting at end: verbose=true
```
Only one spawn ever happens, its args are the stale `[]`, and the setting
is left reading `true` while the running server has no `--verbose` — with
no error surfaced anywhere. The harness (`harness.js`, plus three other
scenarios that confirm rapid on→off→on *does* converge correctly once the
client is already `Running`, and that toggling after a genuine
`StartFailed` is at least non-throwing) lives at
`…/scratchpad/restart-harness/harness.js` in this QA session and was not
copied into the repo: it reimplements the vendored library's state machine
from the source cited above rather than driving the real one, so it is
strong enough to pin *this* extension's own guard/ordering logic but not a
substitute for an in-VS-Code integration test. Formalizing it (or a
real-`vscode-languageclient`, fake-`vscode` version of it) as a permanent
check is a design decision for the dev/lead, not something QA should decide
unilaterally.
Not filed as a fix because the right shape (retry-after-settle? track a
"desired args" and reconcile once any in-flight transition finishes? a
queue?) is itself a design call — flagging for dev/lead per "you verify, you
don't redesign."
**Finding 2 — LOW, fixed directly — cancel/timing interaction was
unspecified.** The brief's adversarial charter asked explicitly: "cancel a
request and check the timing line story... check the dev documented it." It
was not documented anywhere, and no test exercised `--verbose` together with
the cancel path. By reading `server.rs:479` (cancelled requests are
answered from the `cancelled` set inside `process_batch`, before
`self.request(request)` is ever called): a cancelled request gets **no**
`answered in` timing line, since the timed wrapper never runs. This is a
reasonable, already-consistent-with-the-rest-of-the-feature choice (matching
the `reindex_one`-declined and shutdown-during-scan absences the dev already
listed), so I documented it in the feature README's "Two absences are
deliberate" section (now three) and added a permanent regression test,
`a_flood_of_requests_and_cancels_under_verbose_times_only_what_ran_and_corrupts_nothing`
in `crates/lucisv_server/tests/e2e.rs`, which re-runs the existing
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each` flood **with
`--verbose`** and additionally asserts: every id still answered exactly once
(protocol-integrity check under load with the timing notify sharing the
writer channel — no reordering or corruption observed), and the count of
`timing: textDocument/formatting answered in` lines equals exactly the
number of requests that were *not* served from the cancelled set (never one
more, for a cancelled id; never one fewer, for a real one).
**Everything else checked and found sound:**
- **Silence when off**: `without_the_flag_not_one_timing_line_is_ever_sent`
covers every instrumented path in one session (request, notification,
scan, widen, flush, reindex_one); confirmed passing. `verbose_flag`'s exit-2
path and the flag's idempotency under repeats are unit-tested in `main.rs`
and pass.
- **HELD line correctness**: `server.rs:459` calls `say_held` before the
request is spliced into `self.held`, so `self.held.len()` at that point is
exactly "already held" as documented — confirmed by reading the ordering
in `process_batch`.
- **Ordering**: the request's `timing:` line precedes its response by
construction (`request` sends the notify, then returns to the caller which
sends the response) — confirmed by reading and pinned by the dev's own
`line_at < response_at` assertion in
`the_flag_times_every_request_and_notification_and_says_so_in_the_log_channel`.
Confirmed no deadlock risk: `notify`/`timing` go through the same
fire-and-forget `bounded(0)` writer-thread channel every other
notification already uses; nothing in the loop holds a lock across it.
- **`didOpen` buffer survives a restart** (brief: "verify, don't assume"):
read `vscode-languageclient`'s `textSynchronization.js:38-53`
(`DidOpenTextDocumentFeature.register` walks `vscode.workspace.textDocuments`
and resends `didOpen` for every one matching the selector) and
`client.js:1005-1007` (`cleanUp()`, run by every successful `stop()`,
clears `_syncedDocuments`) — so a fresh `start()`'s `initialize()` always
re-syncs every currently-open buffer to the new server process. Verified by
reading the real vendored library; not exercised in a live VS Code window
(not available in this environment).
- **Decorations repaint after restart**: `restartForVerbose` calls
`repaintVisible()` after a successful `start()` — confirmed by reading;
not exercised in a live window.
- **`StartFailed` toggle does not throw**: `shutdown()`'s "not running"
branch and `start()`'s Stopping-only throw mean a toggle issued after a
failed start is caught by the existing `try/catch`s and returns quietly.
It also does not *retry* the spawn in that state (`_onStart` is never
cleared by a failed start, so a later `start()` just re-joins the same
rejected promise) — this looks like a pre-existing limitation of
`vscode-languageclient` itself rather than something this round
introduced, but it means "fix the bad `serverPath` and toggle verbose to
recover" will not work; a window reload is still required, same as it was
for `lucisv.serverPath` before this round. Not filing as a new finding
since the brief only asked whether `restartForVerbose` explodes (it does
not) — noting it here so it isn't lost.
- **Off-path cost**: re-ran `…/scratchpad/verbose_cost.py` — built a fresh
release binary of this round's tree and, separately, one from a clean
`git worktree` at `HEAD` (pre-round). Off-path medians over 3×2000 hovers:
HEAD ≈0.0292–0.0341 ms, this round (no args) ≈0.0262–0.0316 ms — well
inside the run-to-run spread of a single binary, confirming "unmeasurable."
`--verbose` medians ≈0.0440–0.0449 ms, a ~12 µs delta consistent with the
dev's reported 14–18 µs. Independently reproduced, not just re-read.
- **Contract coherence**: `topo.md`'s §1.2 spawn-contract row, its new
verbose-timing handshake row (§2.7), the `lucisv-server` README's new
argument table, `editor-settings`' README, `editors/vscode/README.md`'s
settings table, and `package.json`'s `markdownDescription` all state the
same contract (`[]`/`['--verbose']`, exit 2 on anything else, restart on
change). No mismatch found; `topo.md`'s pre-existing edit (noted in the
work log as done outside this round) matches what was actually built.
- **`smoke.js`**: diff is comment-only; still spawns `[]`; ran it directly
(`node smoke.js <built-binary-path>`) — passes.
- **nvim doc's `WARN`-level gotcha**: plausible and consistent with
Neovim's documented default log level (`WARN`) and its historical mapping
of LSP `MessageType.Log` to `INFO` in `window/logMessage`, but I do not
have a Neovim binary in this sandbox to execute against, so this is
recorded as read-only-verified-from-memory, not executed — worth a real
Neovim smoke check before anyone treats it as pinned.
**Gates, all green:**
- `cargo fmt --check` — clean (after formatting the test I added).
- `cargo clippy --all-targets --all-features` — clean, no warnings.
- `cargo test --workspace --release` — every crate green, including the
4 new e2e cases, the 4 new `main.rs` unit tests, and my added e2e case
(63 passed in `lucisv_server`, up from 62; 2 pre-existing perf tests
remain `#[ignore]`d as designed).
- `node editors/vscode/smoke.js <release binary>` — OK (needed an explicit
path; there is no `lucisv-server` on this sandbox's `PATH`, unrelated to
this round).
**Verdict: REWORK (one finding, severity HIGH; everything else SHIP-clean).**
Finding 1 is a genuine silent-failure in brand-new restart machinery, exactly
in the adversarial charter's target zone ("a restart that loses state") —
recommend the dev address it (likely: track the last-desired args and
reconcile once whatever transition is in flight settles, retrying rather
than assuming one attempt suffices) and add a regression check for it before
shipping the extension-side half of this round. The server-side half (the
actual timing instrumentation, the flag parsing, the protocol-safety
properties) is solid: every adversarial angle in the charter came back clean
or was closed with a new permanent test this pass.
### 2026-08-29 — QA agent (re-verification of the rework)
Focused pass over `editors/vscode/restart.js` (new), `restart_test.js` (new),
the rewritten `extension.js`, `.vscodeignore` and `tools/RELEASING.md`. Not a
full re-run of the earlier charter — the server side is untouched by this
rework (confirmed: `crates/` diff stat unchanged since the first pass) and was
not re-audited.
**1. Every entry point into `client.start()`/`client.stop()`, and whether
`desiredArgs` is ever read non-synchronously.** `grep -n "\.start(\|\.stop("
extension.js` finds exactly two live call sites outside comments:
`restarter.start()` (`extension.js:260`, the activation spawn, now the first
link of the chain) and a direct `client.stop()` in `deactivate()`
(`extension.js:270`). Inside `restart.js`, `client.start()`/`client.stop()`
are called from exactly one place, `reconcile()`, which only ever runs
serialized on `chain` — so within `restart.js` there is no second entry point,
confirming the module's own claim. `serverArgs()` (`extension.js:289`) is a
plain synchronous read of `vscode.workspace.getConfiguration`, called at
exactly two sites (`extension.js:157`, `241`), both of which pass its result
straight into `want()`/the initial `serverOptions.args` with no `await`
between the read and the write — no non-synchronous read of desired arguments
anywhere. **However** — see finding 3 below — `deactivate()`'s `client.stop()`
is a transition that happens **outside** the chain, which is exactly the kind
of second entry point the module's own header comment (`restart.js:18-20`)
says must not exist ("Nothing else starts or stops the client"). It is
guarded by waiting for `settled()` first, but that guard has a gap.
**2. My own mutation pass (two mutations, not the dev's three), against
`restart_test.js`, restored after each:**
- Dropped the `.catch(onStartFailed)` in `queue()` (`restart.js:97`,
`chain = chain.then(reconcile).catch(onStartFailed)` →
`chain = chain.then(reconcile)`), so a failed start poisons the chain
instead of leaving it usable. Caught immediately:
`restart: FAIL — Error: spawn ENOENT` (the unhandled rejection propagates
out of `main()`), at the very next test that hits a failure. Restored,
confirmed byte-identical to the pre-mutation file (`diff` clean) and
`restart_test.js` green again (28/28).
- Made `sameArgs` treat `null`/`null` as equal (`restart.js:29-32`, added
`if (a === null && b === null) return true;` before the existing checks).
Caught immediately by the direct unit case:
`restart: FAIL — not even against another nothing — a failed start must
retry`. Restored and re-verified green.
Both mutations were caught by the shipped test without needing a third or
fourth attempt — the suite has good discrimination on the two properties the
brief specifically flagged as easy to get wrong.
**3. Fake-client honesty, against my earlier reading of the real
`BaseLanguageClient`:**
- The fake's `start()`/`stop()` are simpler than the real state machine (no
"return the in-flight promise" join behavior, no `Starting`/`Stopping`
state at all) — but this is not dishonesty, it's the point: `restart.js`'s
whole fix is that it never calls `client.start()`/`client.stop()`
concurrently with itself, so the real library's join/reject-while-Starting
behavior (`client.js:642-653`, `960-965`) is now dead code from
`restart.js`'s point of view, and a fake that doesn't model it is testing
the right surface. `aStopThatRejectsDoesNotStopTheRestart` explicitly
covers the one real behavior that still matters (a `stop()` can reject),
which is the only piece of the real state machine `restart.js` still has to
tolerate.
- **One real gap, LOW:** `aFailedStartIsReportedAndTheChainStaysUsable`'s
fake lets a *second* `start()` call succeed once `failNextStart` is
consumed, and its comment reads "...which is what a user who fixed their
`serverPath` does" — read on its own, that suggests fixing the path and
toggling again brings the server up. Against the real library it does not:
per `client.js:651-653`, `_onStart` is never cleared by a failed start, so
a real second `client.start()` call returns the *same* rejected promise
without attempting a new spawn at all, regardless of whether the
underlying problem was fixed — which is exactly the "known, not this
round's to fix" item the README already states two sections above
(lines 219-224). The test's own assertions are still accurate (they check
that `restart.js` *asks* again, not that the ask succeeds), so this is a
comment-clarity nit, not a wrong assertion — worth a one-line tweak
("...which is what `restart.js` retries regardless of whether the real
client can act on it — see the known limitation above") but not a
regression or a blocker.
- The known-not-ours limitation itself: confirmed the README states it
plainly (lines 219-224) and that the code degrades to *exactly* that,
not worse — `reconcile()`'s catch sets `runningArgs = null` and rethrows
unconditionally on any `start()` rejection, real or fake, so a real
`StartFailed` rejoin is reported once per toggle (never silently dropped)
and every subsequent toggle keeps asking, forever, which is the documented
"asks correctly, library declines" shape.
**4. Toggle-while-deactivating — read, then confirmed by executing the real
`restart.js`: yes, a `want()` landing after `deactivate()` has read
`settled()` can spawn a process nothing will subsequently stop.**
`deactivate()` is:
```js
return restarter ? restarter.settled().then(() => client.stop()) : client.stop();
```
`settled()` returns whatever `chain` currently *is* — a snapshot, not a live
reference — and `deactivate`'s own `client.stop()` is attached as a `.then`
sibling on that snapshot, **not** enqueued through `want()`/`reconcile`. So
`deactivate` never marks the restarter as done, and nothing stops a `want()`
call (a stray `didChangeConfiguration` for `lucisv.verbose`, arriving from a
settings-sync apply or a user toggling right as the window closes) from
calling `queue()`, which mutates the *live* `chain` variable and queues a
perfectly normal `reconcile()` — stop, then **start a new process** — as a
second sibling off the same snapshot.
Reproduced directly against the shipped `editors/vscode/restart.js` (fake
client, no reimplementation of the library — script available on request,
not committed):
```
start([])
onStarted
--- activation settled, deactivate begins ---
stop()
stop()
start(["--verbose"])
onStarted
```
`deactivate()`'s own `client.stop()` resolves first (it was attached first),
but the `want()` fired in the same tick still runs its full `reconcile()`
afterward — including a fresh `client.start()` — with nothing left to await
it: `deactivate()` already returned a promise that resolved after the first
`stop()`, so whatever waits on `deactivate()` (VS Code's extension host) has
no way to know a second spawn is happening. In the common case (whole window
closing) the new child's stdin pipe dies with the parent process and
`lucisv-server`'s own loop exits on that EOF, so this self-heals; the bad
case is an extension disable, or an extension-host-only restart, where the
host process outlives the module unload — there the new process has no
remaining handle anywhere in the extension and is a genuine orphan. This is
the round's own target sin ("a restart that loses... servers"), reachable
only through this specific race, in code the rework just wrote.
**Verdict on item 4: confirmed real, not ruled out.** Filed as a new finding
rather than fixed directly, since the right shape is a design call (a
`disposed` flag that makes `want()` a no-op after `deactivate` starts; or
routing `deactivate`'s stop through the same chain, e.g.
`chain = chain.then(() => client.stop())` before returning it, so a `want()`
racing it queues *after* the stop instead of beside it) — QA verifies, it
doesn't redesign.
**Finding 3 — MEDIUM — `deactivate()` is a transition outside the chain and
can race a concurrent `want()` into spawning an orphaned server process.**
`editors/vscode/extension.js:264-271`. See reproduction above. Requires a
`lucisv.verbose` configuration-change event to land in the same microtask
turn as (or after) `deactivate()` reading `restarter.settled()` — a narrow
window, and self-healing in the ordinary whole-window-close path — but
confirmed reachable by direct execution against the shipped module, and it
is exactly the failure class ("loses servers") the brief's top-level charter
named. Recommend closing before shipping, given how cheap the fix looks
(routing `deactivate`'s stop through the chain, or a disposed-flag guard on
`want`), but it does not block on its own the way finding 1 did — the
common-case teardown path is not at risk.
**Gates, all green (re-run in full since a prior pass, given the file
changes span both sides):** `cargo fmt --check`, `cargo clippy --all-targets
--all-features`, `cargo test --workspace --release` (unchanged pass counts
from the first QA pass — the rework did not touch `crates/`), `node
editors/vscode/smoke.js <release binary>`, `node
editors/vscode/restart_test.js` (28/28).
**Verdict: SHIP with one open item (MEDIUM).** Finding 1 (HIGH, the silent
lost-toggle) is closed: the chain construction is sound, the fix targets the
actual root cause (the activation spawn now being the chain's first link),
and both my own mutations plus the dev's own three were caught by
`restart_test.js`. Finding 2 (LOW, cancel/timing) remains closed from the
first pass. The new finding 3 (MEDIUM, the deactivate race) is real but
narrow, self-healing in the common teardown path, and does not reopen finding
1 — it is a defensible ship-with-a-followup rather than a hold, but the lead
should decide whether a same-round fix (small, per the two options above) is
warranted before release given how directly it falls under this round's own
charter.
## Review
**2026-08-29 — lead.** Reviewed across the full loop: dev, QA REWORK
(HIGH: a toggle mid-start silently rejoined the stale start), rework 1,
QA re-verify (SHIP plus a new MEDIUM: deactivate's stop outside the
chain could orphan a server), rework 2, and the lead's own gate run
(fmt clean, clippy silent, 2540 workspace tests, smoke OK, restart
harness 44/44). The server half was clean from the first pass: exact
diagnostic-build wordings kept, off-path cost measured unmeasurable
against HEAD by dev and QA independently, ordering and no-deadlock
arguments written rather than assumed, and the cancelled-request
absence made deliberate. The extension half is where the loop earned
its keep twice — both findings came from reading the pinned library's
real state machine, and the final shape is the right invariant stated
the right way: one chain, no transition outside it, reconciled to the
last toggle, with dispose() closing the door on both entry points.
The committed headless harness with five mutation checks is exactly
how extension-side machinery should be tested in a repo whose CI has
no VS Code; QA's fake-client honesty check and the plainly-documented
library limitation (_onStart never clears after StartFailed — reload
still required) keep it honest. The spawn-contract amendment is
consistent across topo.md, both server docs, both editor READMEs and
the manifest. Accepted; committed by the lead.
*(reserved for the lead)*
+46
View File
@@ -153,6 +153,52 @@ then the built-in 2 — your `shiftwidth` is not consulted on this path even
though `vim.lsp.buf.format()` sends it. Set `lucisv.indent` if the two need to
agree.
## When it feels slow: `--verbose`
The server takes one argument, and it is the only one it takes. Start it with
`--verbose` and every operation says how long it took, as ordinary
`window/logMessage` lines in your client's LSP log:
```lua
vim.lsp.config('lucisv', {
cmd = { 'lucisv-server', '--verbose' }, -- the one argument the server takes
filetypes = { 'verilog', 'systemverilog' },
root_markers = { 'lucisv.toml', '.lucisv.toml', '.git' },
})
```
```
timing: textDocument/hover answered in 0.42 ms
timing: textDocument/didChange handled in 0.03 ms
timing: flush of 1 dirty buffer took 1.87 ms
timing: scan started: 862 files, interleaved
timing: scan finished: 862 files (2 skipped, 858 from cache) in 141.20 ms
timing: workspace/symbol HELD behind a rescan (answering=true, wanted=false, already held=0)
```
That last line is the one worth knowing: the request was not slow, it had not
*started* — the loop was rebuilding the index and the order contract makes a
request queued behind a rebuild wait for it.
Neovim's built-in handler writes `window/logMessage` to the LSP log file at
*info* level, and the default log level is `WARN` — so raise it once, or the
lines are dropped before they are written:
```lua
vim.lsp.set_log_level('info')
-- then: :lua vim.cmd('edit ' .. vim.lsp.get_log_path())
```
coc.nvim puts them in its own output channel instead
(`:CocCommand workspace.showOutput`); these are the same lines the VS Code
extension shows when you turn on `lucisv.verbose`.
Anything other than `--verbose` is refused: the server prints one usage line on
stderr and exits 2, so a misspelled flag shows up as a server that will not
start rather than as a session that quietly logs nothing. Without the flag not
one `timing:` line is ever sent — this is a diagnostic, not a default, and a
busy session logs a line per keystroke.
## Checking it works
```
+3 -1
View File
@@ -1,4 +1,6 @@
# The smoke test is a pre-publish check, not part of the shipped extension.
# The two checks are pre-publish/developer checks, not part of the shipped
# extension. `restart.js` itself IS shipped — `extension.js` requires it.
smoke.js
restart_test.js
.vscode/**
.gitignore
+1
View File
@@ -276,6 +276,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
| `lucisv.largeFile.threshold` | `4 MiB` | Size in bytes above which an opened file gets viewport-only highlighting and nothing else — no parsing, diagnostics, formatting, or indexing; `0` analyzes everything |
| `lucisv.formatOnSave` | `false` | Protocol save hook for editors without native format-on-save; keep off in VS Code. Its indent comes from `lucisv.toml` or `lucisv.indent`, never from the editor tab size, which the protocol does not send on this path |
| `lucisv.serverPath` | bundled | Explicit server override for advanced use; an unchanged setting uses the bundled server |
| `lucisv.verbose` | `false` | Print how long every operation took in the lucisv output channel — one `timing:` line per request, notification, scan, widen, buffer flush, and per request that had to wait behind a rescan. **Restarts the language server when changed**, because it is an argument the server is started with |
The six `lucisv.index.*` settings and `lucisv.largeFile.threshold` arrive with
the [large workspaces](#large-workspaces) work; everything else ships in
+77 -11
View File
@@ -12,10 +12,17 @@ const fs = require('fs');
const path = require('path');
const vscode = require('vscode');
const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node');
const { createRestarter } = require('./restart');
/** The single client, kept only so `deactivate` can stop it. */
let client;
/**
* The one thing that starts or restarts the server, so that no two transitions
* ever overlap. Created in `activate`; see `restart.js`.
*/
let restarter;
/** The languages this extension attaches to. */
const LANGUAGES = ['verilog', 'systemverilog'];
@@ -139,11 +146,15 @@ function activate(context) {
// install have always used.
const serverPath = userServerPath() || bundledServer || 'lucisv-server';
// No arguments: `lucisv-server` takes none and speaks LSP on stdin/stdout.
// `editors/vscode/smoke.js` spawns it exactly this way.
// `lucisv-server` needs no arguments and speaks LSP on stdin/stdout —
// `editors/vscode/smoke.js` spawns it exactly that way. The one argument it
// takes is `--verbose`, and only when the user asked for it
// (docs/features/verbose-timing/README.md). The object is kept so the
// restart below can put new arguments in it: every `start()` reads it
// afresh.
const serverOptions = {
command: serverPath,
args: [],
args: serverArgs(),
transport: TransportKind.stdio,
};
@@ -182,6 +193,15 @@ function activate(context) {
client.registerFeatures(ProposedFeatures.createAll(client));
context.subscriptions.push(client);
// Built before anything can ask it for a restart — the settings listener
// below calls it, and nothing may reach that listener with this unset.
restarter = createRestarter({
client,
serverOptions,
onStarted: repaintVisible,
onStartFailed: reportStartFailure,
});
// Every colour is one this extension contributes, so every one of them has
// an opaque default in every theme kind: a theme that says nothing about
// `lucisv.rainbowN` gets our default, and a theme or user that overrides it
@@ -214,6 +234,11 @@ function activate(context) {
if (isVerilog(event.document)) scheduleRepaint();
}),
vscode.workspace.onDidChangeConfiguration((event) => {
// A spawn argument can only change by spawning again, so this one
// setting restarts the server. Nothing else here does. What the toggle
// wants is recorded *now*, synchronously; the restarter decides when it
// can act, and reconciles to whatever was asked for last.
if (event.affectsConfiguration('lucisv.verbose')) restarter.want(serverArgs());
if (!event.affectsConfiguration('lucisv.rainbowBeginEnd')) return;
rainbowEnabled = readRainbowSetting();
// Honoured immediately, both ways: turning it off has to take the
@@ -226,19 +251,26 @@ function activate(context) {
// clear on close; the only explicit clearing is turning the setting off,
// which `repaintVisible` does by painting empty ranges.
client.start().then(
() => repaintVisible(),
// The client reports a server that will not start, in its own output
// channel and its own words. Decorations are cosmetic; there is nothing
// useful to add here, and a second error popup would only be noise.
() => {},
);
// The first spawn goes through the restarter rather than around it, and that
// is the whole of the fix for QA finding 1: a `lucisv.verbose` toggle that
// lands while this start is still in flight — a large workspace's first scan
// can hold it for a while — queues behind it instead of racing it, and is
// then reconciled by a real restart. Calling `client.start()` here directly
// would put one transition outside the chain again.
restarter.start();
}
/** Stop the server; VS Code waits on the returned promise. */
function deactivate() {
clearTimeout(repaintTimer);
return client ? client.stop() : undefined;
// Through the restarter, never around it. A `client.stop()` here would be a
// transition outside the chain — and a `lucisv.verbose` toggle landing in the
// same tick would queue a whole reconcile *beside* it, spawning a server with
// nothing left to await or stop it (QA finding 3). `dispose()` shuts the door
// first, so any such toggle is a no-op, and puts the final stop on the same
// chain as everything else. No client means no restarter and nothing spawned:
// every start this extension makes goes through one of them.
return restarter ? restarter.dispose() : undefined;
}
/** True for the documents this extension knows about. */
@@ -250,6 +282,40 @@ function readRainbowSetting() {
return vscode.workspace.getConfiguration('lucisv').get('rainbowBeginEnd') !== false;
}
/**
* The arguments to spawn the server with: `--verbose` when `lucisv.verbose` is
* on, and none otherwise — which is the spawn every version before this used.
*
* `=== true` rather than a truthy test: the setting is a boolean, and anything
* else in it is somebody's mistake, not a request for a noisy log.
*/
function serverArgs() {
return vscode.workspace.getConfiguration('lucisv').get('verbose') === true ? ['--verbose'] : [];
}
/**
* A server that would not start — at activation or at a `lucisv.verbose`
* restart, which is why both go through here rather than through an anonymous
* `catch {}` that drops it.
*
* The language client says plenty about a server that will not spawn, in its
* own output channel and its own words, so there is no popup here: at
* activation there never was one, and a restart is not more alarming. What it
* does *not* say is that a toggle asked for this, so one line goes into the
* same channel the user is already reading. The restart chain survives, so the
* next toggle tries again.
*/
function reportStartFailure(error) {
const reason = (error && error.message) || error;
try {
client.outputChannel.appendLine(`lucisv: the server did not start: ${reason}`);
} catch {
// No channel to write to — no client yet, or one already disposed. The
// client's own report is then all there is, which is exactly what
// activation has always given.
}
}
/** Coalesce a burst of edits into one repaint. */
function scheduleRepaint() {
clearTimeout(repaintTimer);
+5
View File
@@ -187,6 +187,11 @@
"default": "lucisv-server",
"description": "Path to the lucisv-server executable. Overrides the server bundled with the extension. A bare name is looked up on PATH."
},
"lucisv.verbose": {
"type": "boolean",
"default": false,
"markdownDescription": "Print how long every operation took in the lucisv output channel: one `timing:` line per request answered and per notification handled, plus the workspace scans, the index widens, the buffer flushes and any request that had to wait behind a rescan. Off by default and worth turning on only to answer \"why did that feel slow?\" — a busy session logs a line per keystroke. **Changing this restarts the language server**, because it is an argument the server is started with (`lucisv-server --verbose`), not something it can be told mid-session."
},
"lucisv.rainbowBeginEnd": {
"type": "boolean",
"default": true,
+170
View File
@@ -0,0 +1,170 @@
// One serialized restart chain for the language server, and nothing else.
//
// The server's arguments are decided at spawn time (`--verbose`, from
// `lucisv.verbose`), so the only way to change them is to start a new process.
// Doing that naively loses toggles: `vscode-languageclient` 9's `start()`
// returns the *in-flight* start whenever one exists, and its `stop()` rejects
// while the client is still `Starting` — so a toggle that lands during a slow
// first scan can stop nothing, rejoin the start that is already running with
// the old arguments, and report success. The user then believes the setting
// took effect while the server has no idea about it (QA finding 1, 2026-08-29).
//
// The fix is one rule: **there is exactly one chain of transitions, and it
// always reconciles to the last arguments anybody asked for.** Every toggle
// records what it wants and queues onto the same promise, so two transitions
// can never overlap, and a burst of toggles collapses into at most one restart
// that lands on the final answer.
//
// The rule has a second half, and it is the same rule: **no transition exists
// outside the chain either** — teardown included. `deactivate()` used to stop
// the client itself, attached to a *snapshot* of the chain, so a toggle landing
// in the same tick queued a whole reconcile — stop and then **spawn** — beside
// it, with nothing left to await the new process. On an extension disable or an
// extension-host restart, where the host outlives the module, that server is an
// orphan (QA finding 3, 2026-08-29). `dispose()` is the answer: it closes the
// door (`want()` and any already-queued reconcile become no-ops) and puts the
// final stop on the same chain as everything else.
//
// This file knows nothing about VS Code — it takes a client-like object with
// `start()`/`stop()` — which is what lets `restart_test.js` drive it headlessly
// without re-implementing the language client's own state machine.
// See docs/features/verbose-timing/README.md.
/**
* Whether two argument lists are the same list.
*
* `null` is "nothing is running", and it is equal to nothing — not even to
* another `null` — so a reconcile after a failed start always tries again.
*/
function sameArgs(a, b) {
if (a === null || b === null) return false;
return a.length === b.length && a.every((arg, index) => arg === b[index]);
}
/**
* A restarter for one language client.
*
* - `client` — anything with `start()` and `stop()` returning promises.
* - `serverOptions` — the object the client reads its spawn arguments from at
* every `start()`; the desired arguments are written into `.args` here.
* - `onStarted` — called after each successful start (the decorations went
* with the old connection and have to be repainted).
* - `onStartFailed` — called with the error when a start rejects. Not
* optional, and not a place to swallow: the chain survives, so the next
* toggle retries.
*
* `start()` is the first link of the chain — the activation spawn — so a
* toggle arriving while it is still running queues behind it instead of
* racing it. `dispose()` is the last one. That ordering *is* the fix: calling
* `client.start()` or `client.stop()` anywhere else puts a transition outside
* the chain again, which is how both of this feature's restart bugs happened.
*/
function createRestarter({ client, serverOptions, onStarted, onStartFailed }) {
/** What the process that is running (or starting) was given. */
let runningArgs = null;
/** What the settings ask for now. Written synchronously by every toggle, so
* a change that lands mid-restart is recorded even though it cannot act
* yet. */
let desiredArgs = serverOptions.args.slice();
/** The tail of the chain. Everything queues onto this and nothing else. */
let chain = Promise.resolve();
/** How many spawns have actually been attempted — for the tests, and for
* anyone wondering whether a burst of toggles cost one restart or four. */
let spawns = 0;
/** Whether the door is shut. Set synchronously by `dispose`, and checked
* both by `want` (nothing new is accepted) and by `reconcile` (whatever was
* already queued does nothing) — the second check is the one that matters,
* because a toggle can beat `dispose` into the queue by a tick. */
let disposed = false;
/** Make what is running match what is wanted, or do nothing if it already
* does. Never called concurrently with itself: it only runs on the chain. */
async function reconcile() {
// Queued before the door shut. Whatever it wanted, the answer is now
// "nothing" — this is what stops a teardown from spawning a server.
if (disposed) return;
if (sameArgs(runningArgs, desiredArgs)) return;
const wanted = desiredArgs.slice();
if (runningArgs !== null) {
try {
await client.stop();
} catch {
// A client that is not running cannot be stopped, and one already
// stopping is being stopped by somebody else. Neither is a reason not
// to start the process we actually want — and because this runs on the
// chain, "somebody else" is never another reconcile.
}
}
// Written before the start, because that is when the client reads them.
serverOptions.args = wanted;
runningArgs = wanted;
spawns += 1;
try {
await client.start();
} catch (error) {
// Nothing is running, so the next toggle must try again whatever it
// asks for — including the arguments that just failed.
runningArgs = null;
throw error;
}
onStarted();
}
/** The last transition there will ever be: stop whatever is running, and
* leave nothing to start. Never rejects — a client that will not stop while
* the host is going away is not something anyone can act on, and the client
* says so itself if it has anything to say. */
async function stopForGood() {
if (runningArgs === null) return;
runningArgs = null;
try {
await client.stop();
} catch {
// See above: teardown, and nothing to be done about it.
}
}
/** Queue one reconcile, and report a failed start rather than swallowing it.
* The `catch` is what keeps the chain usable for every later toggle — and
* what makes `chain` a promise that always resolves. */
function queue() {
chain = chain.then(reconcile).catch(onStartFailed);
return chain;
}
return {
/** Spawn the server for the first time. The first link of the chain. */
start: queue,
/** Ask for these arguments. Returns when the chain has reconciled.
* A no-op, silently, once `dispose` has been called: nothing may spawn a
* server after teardown has begun. */
want(args) {
if (disposed) return chain;
desiredArgs = args.slice();
return queue();
},
/**
* Shut the door and stop the server, as the last link of the same chain.
*
* Two halves, and both are needed: the flag makes `want` and any reconcile
* already queued do nothing, and the final stop goes *through the chain*
* rather than beside it, so nothing can interleave with it. Await what it
* returns — that is teardown finished. Idempotent.
*/
dispose() {
if (disposed) return chain;
disposed = true;
chain = chain.then(stopForGood);
return chain;
},
/** Everything queued so far, for a test or a `deactivate`. */
settled: () => chain,
/** The arguments the running process was spawned with, or `null` if none
* is running. */
spawnedWith: () => (runningArgs === null ? null : runningArgs.slice()),
/** How many spawns have been attempted. */
spawns: () => spawns,
};
}
module.exports = { createRestarter, sameArgs };
+322
View File
@@ -0,0 +1,322 @@
// Checks for `restart.js`: the serialized restart chain that makes a
// `lucisv.verbose` toggle land on the server, whenever it arrives.
//
// node restart_test.js
//
// Exits 0 on success, 1 on any failure. Plain node, no dependencies and no
// test runner — the same style as `smoke.js` next to it, and run the same way
// (`tools/release.sh` runs `smoke.js`; this one is a developer check).
//
// The fake client below scripts only what `restart.js` is allowed to depend
// on: `start()` and `stop()` return promises, and this file decides when they
// settle. It deliberately does **not** re-implement `vscode-languageclient`'s
// state machine — QA's throwaway harness did, and a copy of somebody else's
// state machine is a test of the copy. What is pinned here is *our* rule: one
// chain, no overlapping transitions, and the last toggle always wins.
// See docs/features/verbose-timing/README.md.
const { createRestarter, sameArgs } = require('./restart');
let checks = 0;
function ok(condition, what) {
checks += 1;
if (!condition) fail(what);
}
function equal(got, want, what) {
checks += 1;
const a = JSON.stringify(got);
const b = JSON.stringify(want);
if (a !== b) fail(`${what}: got ${a}, want ${b}`);
}
function fail(message) {
console.error(`restart: FAIL — ${message}`);
process.exit(1);
}
/** Let every already-resolved promise run. */
const settle = () => new Promise((resolve) => setImmediate(resolve));
/**
* A client whose `start()`/`stop()` this test settles by hand, and a
* `serverOptions` for it to read arguments from.
*
* `spawns` records the arguments of every start *as the client would have read
* them* — which is the whole question a lost toggle turns on.
*/
function fake({ pendingStarts = 0 } = {}) {
const serverOptions = { command: 'lucisv-server', args: [], transport: 'stdio' };
const state = {
serverOptions,
spawns: [],
stops: 0,
started: 0,
failures: [],
/** Resolves the start that is waiting, while there are pending ones left. */
release: null,
pendingStarts,
failNextStart: false,
};
const client = {
start() {
state.spawns.push(serverOptions.args.slice());
if (state.failNextStart) {
state.failNextStart = false;
return Promise.reject(new Error('spawn ENOENT'));
}
// Only the first `pendingStarts` spawns hang — the ones a test is about.
// A restart that follows resolves at once, like a spawn that works.
if (state.pendingStarts <= 0) return Promise.resolve();
state.pendingStarts -= 1;
return new Promise((resolve, reject) => {
state.release = { resolve, reject };
});
},
stop() {
state.stops += 1;
return Promise.resolve();
},
};
state.restarter = createRestarter({
client,
serverOptions,
onStarted: () => {
state.started += 1;
},
onStartFailed: (error) => state.failures.push(error.message),
});
state.client = client;
return state;
}
async function activationSpawnsOnceWithTheSettingsArguments() {
const it = fake();
it.serverOptions.args = ['--verbose'];
const restarter = createRestarter({
client: it.client,
serverOptions: it.serverOptions,
onStarted: () => {},
onStartFailed: fail,
});
await restarter.start();
equal(it.spawns, [['--verbose']], 'activation spawns once, with what the settings said');
equal(restarter.spawnedWith(), ['--verbose'], 'and remembers what it spawned with');
}
async function aToggleDuringTheActivationStartIsNotLost() {
// QA finding 1, 2026-08-29, and the reason this file exists. The activation
// start is still in flight — a large workspace's first scan holds it open —
// when the user turns `lucisv.verbose` on. Before the chain, `stop()` failed,
// `start()` rejoined the in-flight start with the OLD arguments, and the
// extension repainted as if the toggle had worked.
const it = fake({ pendingStarts: 1 });
it.restarter.start();
await settle();
equal(it.spawns, [[]], 'the activation spawn is in flight, with no arguments');
const toggled = it.restarter.want(['--verbose']);
await settle();
equal(it.spawns, [[]], 'and nothing else may spawn while it is: no overlapping transitions');
equal(it.stops, 0, 'and nothing is stopped mid-start');
it.release.resolve();
await toggled;
equal(it.spawns, [[], ['--verbose']], 'the toggle is honoured once the start it queued behind is done');
equal(it.stops, 1, 'by stopping the server that had the old arguments');
equal(it.serverOptions.args, ['--verbose'], 'the client reads the new arguments at that start');
equal(it.restarter.spawnedWith(), ['--verbose'], 'and the running server is the one the user asked for');
equal(it.started, 2, 'both starts repaint');
}
async function aBurstOfTogglesCollapsesToOneRestartOnTheLastOne() {
// on -> off -> on while a start is in flight: three toggles, one restart,
// and it lands on the last thing anybody asked for.
const it = fake({ pendingStarts: 1 });
it.restarter.start();
await settle();
it.restarter.want(['--verbose']);
it.restarter.want([]);
const last = it.restarter.want(['--verbose']);
await settle();
equal(it.spawns, [[]], 'still nothing extra while the first start is in flight');
it.release.resolve();
await last;
equal(it.spawns, [[], ['--verbose']], 'three toggles cost one restart');
equal(it.restarter.spawns(), 2, 'and the restarter says so');
equal(it.restarter.spawnedWith(), ['--verbose'], 'landing on the last toggle');
}
async function aToggleBackToWhatIsRunningRestartsNothing() {
const it = fake();
await it.restarter.start();
await it.restarter.want(['--verbose']);
equal(it.spawns.length, 2, 'the real change restarts');
await it.restarter.want(['--verbose']);
equal(it.spawns.length, 2, 'asking for what is already running does nothing');
equal(it.stops, 1, 'and stops nothing');
}
async function aFailedStartIsReportedAndTheChainStaysUsable() {
const it = fake();
await it.restarter.start();
it.failNextStart = true;
await it.restarter.want(['--verbose']);
equal(it.failures, ['spawn ENOENT'], 'the failure is reported, not swallowed');
equal(it.restarter.spawnedWith(), null, 'and nothing is recorded as running');
// The next toggle must *ask* again, including for the arguments that just
// failed. Whether the ask can succeed is not this module's call: the real
// `vscode-languageclient` never clears `_onStart` after a failed start, so it
// hands back the same rejection without spawning anything (the known
// limitation in the feature README). What is pinned here is that `restart.js`
// keeps asking rather than going quiet — the fake below is free to succeed.
await it.restarter.want(['--verbose']);
equal(it.spawns, [[], ['--verbose'], ['--verbose']], 'the chain is still usable and retries');
equal(it.failures.length, 1, 'and the retry that worked reports nothing');
}
async function aStopThatRejectsDoesNotStopTheRestart() {
// A client that will not stop — not running, or already stopping — must not
// cost the user the start they actually asked for.
const it = fake();
await it.restarter.start();
it.client.stop = () => Promise.reject(new Error('Client is not running'));
await it.restarter.want(['--verbose']);
equal(it.spawns, [[], ['--verbose']], 'the start happens anyway');
equal(it.failures, [], 'and a refused stop is not a start failure');
}
async function aToggleInTheSameTickAsDisposeSpawnsNothing() {
// QA finding 3, 2026-08-29, as they reproduced it: with `deactivate()`
// stopping the client itself — attached to a *snapshot* of the chain — a
// `lucisv.verbose` event arriving in the same tick queued a full reconcile
// beside it and the trace read `stop, stop, start(--verbose)`. That last
// spawn had nothing left to await or stop it: an orphan, whenever the
// extension host outlives the module (a disable, or a host-only restart).
const it = fake();
await it.restarter.start();
equal(it.spawns, [[]], 'the server is up');
const gone = it.restarter.dispose();
it.restarter.want(['--verbose']); // the racing toggle, same tick
await gone;
await settle();
equal(it.spawns, [[]], 'nothing is ever spawned after teardown begins');
equal(it.stops, 1, 'and the one stop is the teardown one');
equal(it.restarter.spawnedWith(), null, 'nothing is left running');
// And the door stays shut: a later toggle is a silent no-op, not a spawn.
const after = it.restarter.want([]);
await after;
equal(it.spawns, [[]], 'a toggle after teardown does nothing at all');
// Nothing is even *queued* after teardown — `want` hands back the teardown
// promise itself rather than adding a reconcile for the flag inside
// `reconcile` to no-op. Both guards are wanted: this one keeps the chain
// from growing, and the one in `reconcile` catches what got in first.
ok(after === gone, 'a toggle after teardown adds no link to the chain');
}
async function aReconcileQueuedBeforeDisposeBecomesANoOp() {
// The other order, and the reason the flag is checked inside `reconcile` and
// not only in `want`: the toggle got into the queue first, and `dispose`
// shut the door behind it. What was queued must do nothing rather than
// spawn — the chain guarantees it runs *after* dispose was called, not that
// it was never queued.
const it = fake({ pendingStarts: 1 });
it.restarter.start();
await settle();
equal(it.spawns, [[]], 'the activation start is in flight');
it.restarter.want(['--verbose']); // queued behind the in-flight start
const gone = it.restarter.dispose(); // ...and then the window closes
it.release.resolve();
await gone;
equal(it.spawns, [[]], 'the queued toggle spawns nothing once the door is shut');
equal(it.stops, 1, 'only the teardown stop happens');
equal(it.restarter.spawnedWith(), null, 'and nothing is left running');
}
async function disposeResolvesAfterTheFinalStop() {
// What `deactivate()` returns is what VS Code waits on, so it has to mean
// "the server is stopped", not "the stop was queued".
const it = fake();
await it.restarter.start();
let stopped = false;
it.client.stop = () =>
new Promise((resolve) =>
setTimeout(() => {
stopped = true;
it.stops += 1;
resolve();
}, 10),
);
await it.restarter.dispose();
ok(stopped, 'dispose() resolves only once the final stop has finished');
equal(it.stops, 1, 'and it really stopped the client');
// Idempotent: disposing twice is one stop, and still resolves.
await it.restarter.dispose();
equal(it.stops, 1, 'a second dispose stops nothing again');
// And two disposes in the *same tick* both mean "teardown is finished" —
// which is only true if the final stop went onto the chain rather than
// beside it, since the second caller gets the chain as it stands.
const again = fake();
await again.restarter.start();
let down = false;
again.client.stop = () =>
new Promise((resolve) =>
setTimeout(() => {
down = true;
resolve();
}, 10),
);
await Promise.all([again.restarter.dispose(), again.restarter.dispose()]);
ok(down, 'both callers wait for the one stop that actually happens');
}
async function disposingBeforeAnythingSpawnedStopsNothing() {
// An activation that failed before a server existed must not stop a client
// that was never started — the real one rejects that, loudly.
const it = fake();
await it.restarter.dispose();
equal(it.stops, 0, 'nothing was running, so nothing is stopped');
equal(it.spawns, [], 'and nothing was ever spawned');
}
function argumentListsCompareByValueAndNullIsNothing() {
ok(sameArgs([], []), 'no arguments is no arguments');
ok(sameArgs(['--verbose'], ['--verbose']), 'the same flag is the same flag');
ok(!sameArgs([], ['--verbose']), 'and a different one is not');
ok(!sameArgs(null, []), 'nothing running is never what is wanted');
ok(!sameArgs(null, null), 'not even against another nothing — a failed start must retry');
}
async function main() {
// A test that awaits a promise nothing will settle would otherwise let node
// run out of work and exit 0 in silence — a hang that reads as a pass. This
// timer both fails it and keeps the event loop alive to say so.
const watchdog = setTimeout(
() => fail('timed out after 5s — a promise this test waits on never settled'),
5000,
);
argumentListsCompareByValueAndNullIsNothing();
await activationSpawnsOnceWithTheSettingsArguments();
await aToggleDuringTheActivationStartIsNotLost();
await aBurstOfTogglesCollapsesToOneRestartOnTheLastOne();
await aToggleBackToWhatIsRunningRestartsNothing();
await aFailedStartIsReportedAndTheChainStaysUsable();
await aStopThatRejectsDoesNotStopTheRestart();
await aToggleInTheSameTickAsDisposeSpawnsNothing();
await aReconcileQueuedBeforeDisposeBecomesANoOp();
await disposeResolvesAfterTheFinalStop();
await disposingBeforeAnythingSpawnedStopsNothing();
clearTimeout(watchdog);
console.log(`restart: OK — ${checks} checks over the restart chain`);
}
main().catch((error) => fail(error.stack || String(error)));
+6 -2
View File
@@ -41,8 +41,12 @@ function fail(message) {
process.exit(1);
}
// The same spawn contract extension.js uses: no arguments, inherited env, the
// workspace directory as cwd, LSP on stdin/stdout.
// The same spawn contract extension.js uses by default: no arguments,
// inherited env, the workspace directory as cwd, LSP on stdin/stdout. The one
// argument the extension can add — `--verbose`, when the user turns on
// `lucisv.verbose` — only adds log lines, and is driven by
// crates/lucisv_server/tests/e2e.rs; this check stays on the spawn everybody
// gets (docs/features/verbose-timing/README.md).
const server = spawn(serverPath, [], { cwd: process.cwd(), env: process.env, stdio: 'pipe' });
server.on('error', (error) => fail(`could not spawn "${serverPath}": ${error.message}`));
+8 -4
View File
@@ -180,10 +180,14 @@ npx @vscode/vsce package --target darwin-arm64 \
a packaging regression — it reproduces with a two-file toy extension. The fix
is to package from a plain path, which is why `release.sh` packages inside the
repo and only writes its *output* to `-o`.
- `.vscodeignore` keeps `smoke.js`, `.vscode/**` and `.gitignore` out of the
package. It must **not** exclude `bin/`, which is where the platform packages'
binaries are staged. Check that after any change to it:
`unzip -l dist/lucisv-<version>.vsix | grep smoke` must print nothing, and
- `.vscodeignore` keeps `smoke.js`, `restart_test.js`, `.vscode/**` and
`.gitignore` out of the package. It must **not** exclude `bin/`, which is
where the platform packages' binaries are staged — nor `restart.js`, which
`extension.js` requires at runtime (an extension that ships without it fails
to activate). Check that after any change to it:
`unzip -l dist/lucisv-<version>.vsix | grep -E 'smoke|restart_test'` must
print nothing, `unzip -l dist/lucisv-<version>.vsix | grep restart.js` must
print `extension/restart.js`, and
`unzip -l dist/lucisv-<version>.vsix | grep syntaxes` must print the grammar —
without it, hover cards ship unhighlighted.
- **`editors/vscode/bin/` is transient.** `release.sh` stages one platform's
+63 -30
View File
@@ -11,7 +11,10 @@ each crate's `Cargo.toml`, each feature's `docs/features/<name>/README.md`
(the **Handshakes** section in particular), `README.md` and `CLAUDE.md`.
Drafted 2026-08-27 from the workspace at v0.10.2 (93 feature READMEs);
updated 2026-08-28 for hover-declarations, change-debounce,
port-detail-spans and interactive-latency (97 feature READMEs).
port-detail-spans and interactive-latency (97 feature READMEs); updated
2026-08-29 from v0.14.0 for hover-line-index, scan-interleave, incremental
scope widening, the request-fan-out performance wave and verbose-timing
(100 feature READMEs).
**Edge notation, used in all three sections:**
@@ -97,17 +100,19 @@ what a change on the pointed-to side must not silently break.
| `lucisv ──▶ lucisv_core` | depends | `config::{FileConfig, Discovery}` (lucisv.toml discovery — `config::parse` is reached through `Discovery`, not called directly), `walk::{collect_files, EXTENSIONS}` (the `.gitignore`/`--exclude` walk), `filelist::read` (`-f`), `cache` (the format cache). (`walk::is_excluded` is `pub` but currently has no consumer outside the crate.) |
| `lucisv ──▶ vlog_formatter` | depends | `format_source` / `format_range` / `LineRanges` / `Config` / `FormatError`, and `fence::{protected_regions, is_protected}` (the `--fix` fence filter — the linter crate deliberately has no fence notion). |
| `lucisv ──▶ vlog_linter` | depends | The public linter API for `lucisv check` — `lint` + `LintContext`/`ParsedSource`, `apply_fixes`, `select_rules` (the CLI does not call `run` itself). Relies on: rule names stable, linting never panics/writes, findings sorted by `(span.start, span.end, rule)`. |
| `lucisv ──▶ vlog_parser` | depends | Thin: `LineIndex` / `TextRange` for lint report coordinates. (The CLI otherwise reaches the parser through the formatter and linter.) |
| `lucisv ──▶ rayon` | depends | The worker pool. Pinned exactly; pool must keep `stack_size(8 MiB)` (recursion-limit handshake) or the parser's depth guarantee regresses to a stack overflow. |
| `lucisv ──▶ vlog_parser` | depends | `LineIndex` / `TextRange` for lint report coordinates, plus `PARSE_STACK_SIZE` for both the named `lucisv` thread and rayon workers. (The CLI otherwise reaches the parser through the formatter and linter.) |
| `lucisv ──▶ rayon` | depends | The worker pool. Pinned exactly; pool must keep `stack_size(vlog_parser::PARSE_STACK_SIZE)` (currently 16 MiB; recursion-limit handshake) or the parser's depth guarantee regresses to a stack overflow. |
| `lucisv_server ──▶ lucisv_core` | depends | Same config discovery and walk as the CLI (that sameness is the point — format-on-save must agree with `lucisv --check`), `filelist::read` (index scope rung 1, `+incdir+` for the include graph), `cache::content_hash` (re-used by the persistent index cache — one FNV-1a, not two). |
| `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the VS Code grammar is generated from). |
| `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the VS Code grammar is generated from), and `PARSE_STACK_SIZE` for the named `lucisv-main` thread. |
| `lucisv_server ──▶ vlog_semantic` | depends | `analyze`/`Semantics` (every navigation answer), `WorkspaceIndex` (build/incremental update, units/members/defines, `instantiations_of`/`subclasses_of` edge tables, `FileFacts` codec for the persistent cache), `resolve_external` overlay, `index_order`/`IndexBuilder` (watched builds). |
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Two negotiated additions, both 2026-08-28 and both additive: **`Symbol::detail_span` / `Def::detail_span`** (where a non-ANSI port's body declaration completes the header that names it — the server's hover card and `nav::definition` both read it, and they show/jump to it in the same order), and **`Semantics::symbols_named`** (name → declarations, built in `analyze`, in declaration order — the server replaced two scan-every-symbol loops with it and the *first-match tie-break must stay declaration order* or hover's choice between two live declarations of one name changes). `docs/features/port-detail-spans/README.md`. |
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Three later additive performance surfaces: **`DeclLines` / `Def::lines`** record declaration and detail lines at index time (`FACTS_FORMAT` 3 → 4); **`WorkspaceIndex::absorb`** folds a scan batch with one merge rather than one merge per file; and **`WorkspaceIndex::files_spelling`** finds external uses by spelling, resolved or not, for rename's dangling-use refusal. The first feeds hover-line-index, the second scan-interleave, and the third refactor-rename's six-rung fan-out. Changing the facts codec, reference-fact census or merge semantics breaks those consumers. |
| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `instantiation_plan`/`render_with`/`module_definition` (completion skeletons, signature help, inlay hints). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. |
| `lucisv_server ◀──▶ vlog_refactor` | handshake | Request-scope selectors added for the performance wave: `prepare_rename_here` must produce the same answer/refusal text as whole-scope `prepare_rename`; `rename_name_at` must name the target that the rename engine acts on; `port_action_modules` and `enclosing_module` must name every module the corresponding port action/command can edit. The server uses those names only to choose an index-derived superset of files; the engine remains the authority. |
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. |
| `editors/vscode ◀──▶ lucisv_server` | handshake | The **spawn contract**: binary named `lucisv-server`, no args, no env, LSP over stdio, `initialize` works with no roots (single-file mode). Wire shapes pinned on both sides: the custom `lucisv/scopePairs` result, the `lucisv.*` settings section (push and pull), `initializationOptions.storagePath`, the markdown fence tag `systemverilog` (server emits it, extension's grammar registers it), the `bin/` layouts of the platform `.vsix` packages. `smoke.js` drives the contract headlessly; `tests/e2e.rs` and `tests/grammar.rs` pin it server-side. |
| `editors/vscode ◀──▶ lucisv_server` | handshake | The **spawn contract**: binary named `lucisv-server`, no env, LSP over stdio, `initialize` works with no roots (single-file mode). The extension passes exactly `[]` by default or `['--verbose']` when `lucisv.verbose` is true; the server accepts only that spelling (repeats are idempotent) and refuses any other argument with exit 2. Changing that setting restarts the server because it is a process argument, not an LSP setting. Wire shapes pinned on both sides: the custom `lucisv/scopePairs` result, the other `lucisv.*` settings section (push and pull), `initializationOptions.storagePath`, the markdown fence tag `systemverilog` (server emits it, extension's grammar registers it), the `bin/` layouts of the platform `.vsix` packages. `smoke.js` still drives the default no-argument contract headlessly; `tests/e2e.rs` pins both spawns and `tests/grammar.rs` pins the grammar. |
| `editors/vscode ◀──▶ vlog_parser` | handshake | The TextMate grammar's keyword alternation is **hand-maintained and test-locked to `vlog_parser::KEYWORDS`**: `crates/lucisv_server/tests/grammar.rs` fails, naming the missing/extra words, when they diverge (there is no generator script). Adding a keyword to `token.rs`'s `keywords!` macro is therefore also a hand edit to `editors/vscode/syntaxes/systemverilog.tmLanguage.json`. |
| `editors/nvim ──▶ lucisv_server` | depends | Documentation-only module: config snippets consuming the same spawn contract and settings shape. No code. |
| `tools/ ◀──▶ crates + editors/vscode` | handshake | `release.sh` parses `lucisv --version` (field 2), runs `smoke.js` against the built server, stages `dist/lucisv[-server]-<version>-<triple>` names, packages seven `.vsix` files and asserts their `bin/` layouts. `audit_artifacts.sh` and `prune_release_assets.sh` key on those exact names. The version number lives in exactly four files (two `Cargo` files, two `package*.json`) and nowhere in Rust source. |
@@ -147,7 +152,10 @@ grammar, depth/chain budgets from recursion-limit) → `ast.rs`; `span.rs`
(`TextRange`), `line_index.rs` (offset↔line:col), `defines.rs` (the
`` `define`` table, reads the token stream, expands nothing). `tests/spans.rs`
is an exhaustive AST walker: **every new node needs an arm there** and must
keep the span-nesting invariant.
keep the span-nesting invariant. `PARSE_STACK_SIZE` is part of the public
parser contract: every production thread that can reach parse or analysis must
use it; the CLI main thread, rayon pool and server main thread do so, while the
server queue and `lsp-server` I/O threads are proven not to parse.
**`vlog_formatter`** — the pipeline is `format.rs` (per-node rules) →
`doc.rs` (the Wadler IR) → `printer.rs` (width-aware printing);
@@ -164,7 +172,9 @@ an error means emit nothing.
`DataType`; shrinks to zero when open handshake §2.9-2 lands);
`workspace.rs` (`WorkspaceIndex`: units, members, defines, instantiation and
inheritance edge tables, incremental `update_file`/`remove_file`,
`fingerprint`); `facts.rs` (`FileFacts` codec for the persistent cache);
reference postings, `files_spelling`, batch `absorb`, declaration `DeclLines`,
`fingerprint`); `facts.rs` (`FileFacts` codec for the persistent cache;
`FACTS_FORMAT` is 4);
`instantiations.rs`, `classes.rs` (the shared walks, lifted from the server
so the index census and the request handlers cannot drift).
@@ -185,10 +195,13 @@ table for the three semantic rules), `naming.rs`, `rule_docs.rs`
(`rules_markdown()` — docs generated from the registry).
**`vlog_refactor`** — `rename.rs` (the `Scope` cache + occurrence walk —
also the engine of `references.rs::find_references`), `ports.rs`
(add/remove/propagate), `instantiate.rs` (plans + rendering; the one layout
both plain and snippet spellings go through), `check.rs` (whole-edit
verification: re-tokenize + re-resolve, refuse everything on any drift).
also the engine of `references.rs::find_references`; publishes the cheap
`prepare_rename_here`/`rename_name_at` selectors whose parity with the full
engine is test-pinned), `ports.rs` (add/remove/propagate plus
`port_action_modules`/`enclosing_module`, the names the server uses to bound
the input set), `instantiate.rs` (plans + rendering; the one layout both plain
and snippet spellings go through), `check.rs` (whole-edit verification:
re-tokenize + re-resolve, refuse everything on any drift).
**`lucisv` (CLI)** — `main.rs` (args → walk → per-file worker pool;
`process_file` is the cache-aware unit of work; panic hook installed once at
@@ -203,25 +216,28 @@ spans two layers — the include graph *and* the `documentLink` handler;
| layer | files | role |
|---|---|---|
| entry | `main.rs` | capabilities advertisement, `InitializeParams` reading, wiring |
| loop | `server.rs` | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, reindex orchestration, progress/log senders |
| state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay) and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) |
| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word tables, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync |
| entry | `main.rs` | the no-argument / `--verbose`-only argument contract, capabilities advertisement, `InitializeParams` reading, wiring |
| loop | `server.rs` | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, stepped startup scans with mid-scan request drains, held-request ordering for rescans, reindex/widen orchestration, progress/log senders, optional `timing:` instrumentation |
| state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay, bounded closed-file `FileView` cache), `Scan` (whole or additive widen), fan-out source selectors (`module_sources`, `rename_sources`, `include_sources`), and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) |
| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word/module tables and their scan-batch forms, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync |
| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs`, `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion.rs`, `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) |
**`editors/vscode`** — `extension.js` (spawn + rainbow decorations + storage
path; ~everything else is `vscode-languageclient` driven off advertised
capabilities), `package.json` (languages, grammar, snippets, settings,
colour ids), `syntaxes/` (hand-maintained grammar, test-locked to
`KEYWORDS`), `snippets/` (static, server-independent), `smoke.js` (headless
handshake check), `README.md` (the Marketplace Details page, owned by
editor-marketplace-page).
`KEYWORDS`), `snippets/` (static, server-independent), `restart.js` (the one
serialized start/restart chain, so a `lucisv.verbose` toggle cannot be lost to
an in-flight start — shipped, and the only module `extension.js` requires),
`smoke.js` (headless handshake check) and `restart_test.js` (headless check of
that chain, against a scripted fake client), `README.md` (the Marketplace
Details page, owned by editor-marketplace-page).
---
## 2. Feature dependency graph
96 features. They cluster into eight lanes; edges inside a lane are listed in
100 features. They cluster into eight lanes; edges inside a lane are listed in
that lane's table, cross-lane edges are repeated where they matter. The
mermaid graph shows the lanes and the load-bearing cross-lane edges only.
@@ -292,7 +308,7 @@ graph LR
| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. |
| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. |
| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. |
| `recursion-limit ◀──▶ parallel-files` | handshake | recursion-limit requires ≥8 MiB worker stacks; parallel-files built the pool with `stack_size(8 MiB)` and a test that fails if it is removed. |
| `recursion-limit ◀──▶ parallel-files` | handshake | recursion-limit requires every parsing thread to use `vlog_parser::PARSE_STACK_SIZE` (currently 16 MiB); parallel-files points the rayon pool at the constant, and the later stack audit put the CLI/server main work on named threads using the same value. Tests fail if a spawn site drifts. |
| `recursion-limit ◀──▶ error-recovery` | handshake | Recovery must not reset `depth`/`links` while unwinding; error-recovery proves it with white-box + mutation tests. |
| `one-parse ◀──▶ linter-core / server-lint` | handshake | Both filed the "one parse, two tools" request; one-parse delivered `LintContext::from_parse` + `ParsedSource`, `Document` gained its `tree` field, and both front ends lint from one parse. Behavior byte-identical was the gate. |
@@ -397,6 +413,11 @@ promise:
| `index-persistence ──▶ format-cache` (lucisv_core) | depends | Reuses `lucisv_core::cache::content_hash` — one FNV-1a shared with the format cache, not a second copy. Also one additive `vlog_parser` touch: `DefineTable::from_entries` + `PartialEq`/`Eq` derives, so a record restores a table without re-reading a file. |
| `index-persistence ◀──▶ indexing-ux` | handshake | `IndexEvent::Cached` — a new variant, so every consumer is forced to say what it does with an unparsed file; the end message names the cached count. |
| `port-detail-spans ◀──▶ index-persistence` | handshake | A declaration record grew two numbers (the detail span, written unconditionally as `0 0` for the `None` every ordinary declaration has), so **`FACTS_FORMAT` went 2 → 3** and every store written by an earlier build is discarded whole rather than read field-shifted. The bump *is* the contract: `index_cache.rs`'s header line carries the number, and the reader's `done()` check is a backstop, not a version scheme. |
| `hover-line-index ──▶ port-detail-spans / index-persistence` | depends + handshake | `DeclLines { name, detail }` rides each indexed `Decl`, so ordinary and split-port hover headings do not reread a file just to compute a line. The record grew again and **`FACTS_FORMAT` went 3 → 4**; the server's bounded `FileView` cache supplies the text/`LineIndex` only when a snippet or a non-indexed position still needs it. Its four invalidation points are `set_document`, `close_document`, `update_one`, and a whole rebuild. |
| `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and `IncludeGraph::absorb` publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. |
| `scan-interleave ──▶ hover-line-index` | depends | Delivers hover-line-index's measured startup-wait request: a startup scan above 64 files drains queued messages between files. A rescan deliberately still holds requests; what an answer sees never depends on elapsed wall time. |
| `index-scope ──▶ scan-interleave` | depends | A scope widen is the second `Scan` shape (`begin_widen`) and shares `scan_step`/`finish_scan`; it folds only newly reached folders plus open-buffer analyses, never masquerades as a whole scan, and never interleaves. Folder scope now ships at depth 2; rootless sessions do not climb an unnamed tree. |
| `index-scope ──▶ one-parse / completion-core` | depends | Whole scans and widens reuse each open `Document`'s existing `FileFacts` and completion words rather than reparse its text. `IndexEvent::Analyzed` keeps this distinct from a persistent-cache hit. |
| `define-table ◀──▶ macro-expansion` | handshake | What began as free-to-change became contract at M14: params stored **as written**, `NAME()` = `Some(vec![])` — `expand.rs` counts arguments against them and declines on mismatch. |
### 2.6 Refactor lane (the M-plan)
@@ -409,9 +430,12 @@ promise:
| `refactor-rename (M2) ──▶ vlog-semantic / workspace-index` | depends | Every edit from a resolved span; whole-edit verification; refusals from `Resolution` variants. |
| `refactor-rename ◀──▶ vlog_semantic` | handshake | The one authorized cross-module change of M2: `Target::Declaration` + `use_end_label` (end labels must rename or the output doesn't compile). Strictly additive; logged in vlog-semantic's work log. |
| `refactor-ports (M3) ──▶ refactor-rename` | depends | Reuses M2's `check`/`Scope`; the two preprocessor scans were factored to return *sites* so M3 words its own warnings without inheriting M2's text (M2's wording pinned by its 48 tests). |
| `refactor-ports ◀──▶ incremental-index / lucisv_server` | handshake | `port_action_modules` and `enclosing_module` name the engine's possible module targets; `Workspace::module_sources` expands them through module declarations, `instantiations_of`, reference postings and open buffers. Code actions and all three commands use the same builder, and parity tests assert the narrowed result equals the old whole-scope result. The instantiation census in `vlog_semantic::instantiations` and `ports::collect_instantiations` must grow together. |
| `refactor-instantiate (M4) ──▶ workspace-index, editor-scopes` | depends | Plans from the index's real definitions; the item-position gate is built on `pairs::analyze`'s published output only. |
| `apply-edit ──▶ refactor-ports` | depends | The port commands now *push* `workspace/applyEdit` (the protocol's actual mechanism) instead of answering the edit as a result no client applies. `ports::execute`'s signature and behavior unchanged — the only `ports.rs` edit was correcting a now-false doc comment, so this is consumption, not a handshake. |
| `references-nav ──▶ refactor-rename` | depends | `find_references` is `Scope::collect_occurrences` lifted out of `collect_edits` — the references list and a rename's touch-set **cannot disagree**, by construction (deliberately not moved to `vlog_semantic`; the walk needs refactor-crate concerns). |
| `refactor-rename ◀──▶ workspace-index / lucisv_server` | handshake | `prepareRename` answers from the open `Document` plus index through `prepare_rename_here`; `rename` asks `rename_name_at` for the engine's target and feeds only `Workspace::rename_sources`'s six-rung superset. The rungs cover declarations/members, resolved postings, instantiation edges, macro definitions, every open buffer, and `files_spelling` for unresolved new-name uses; if a rung cannot bound a case it falls back to all sources. Refusal sentences and whole-scope parity are pinned. Open residue: macro-invocation-argument warnings need §2.9-18. |
| `file-operations ◀──▶ include-nav / lucisv_server` | handshake | `IncludeGraph::includers` exposes the files that can contain a resolving include; `Workspace::include_sources` overlays open buffers and reads only that set for `willRenameFiles`, instead of the workspace. It is sound only while the graph's held-edge census and `resolve` agree. |
### 2.7 LSP server lane
@@ -422,7 +446,7 @@ engine-lane features are listed above; this table is the server-internal web.
|---|---|---|
| `editor-scopes ─▶ (many)` | depends (consumed by) | `pairs.rs` — one stack matcher, eight consumers today: documentHighlight, missing-closer diagnostics, `lucisv/scopePairs` rainbow, folding (references-nav), the item-position gates (completion-core / refactor-instantiate), on-type-formatting's keyword tables, inline-templates' unmatched-`begin` check, expand-selection (`selection.rs`). The `RULES` table + guard list is the shared truth; a keyword change means re-checking it. |
| `editor-scopes ◀──▶ editors/vscode` | handshake | The `lucisv/scopePairs` wire shape (pinned as literal JSON in a test) and the `lucisv.rainbow*` colour ids that must match between `package.json` and `extension.js`. |
| `completion-core ──▶ define-table, vlog-semantic, workspace-index, refactor-instantiate` | depends | Five tiers over existing facts; the parser widening (`KEYWORDS` export) is its one engine touch. Deliberate duplication recorded: `visible_symbols` vs `ports::visible_in` share an idea, not code. |
| `completion-core ──▶ define-table, vlog-semantic, workspace-index, refactor-instantiate` | depends | Five tiers over existing facts; the parser widening (`KEYWORDS` export) is its one engine touch. Deliberate duplication recorded: `visible_symbols` vs `ports::visible_in` share an idea, not code. Since the performance wave, tier 0 reads module names from `Candidates::modules` (built once with the index) and parses only a definition's guarded header slice; equality with `vlog_refactor::module_names` and full-file planning is test-pinned. |
| `completion-templates ──▶ completion-core, editor-scopes` | depends | Tier 3; `templates.rs` is data + one renderer; tier digits moved (only e2e's word-tier assertion cared). Also consumes `vlog_refactor::Layout` (M4's `{ base, step }`), reused rather than re-declared, so a skeleton and a template indent by one type. |
| `completion-templates ◀──▶ editor-snippets` | handshake | Nine overlapping statement/block snippets were **removed** from `editors/vscode/snippets/*.json` when the server started offering them as tier 3; both READMEs' prefix tables are the shared truth. A template added server-side must check the static set, and vice versa. |
| `inlay-hints ──▶ refactor-instantiate` | depends | Reads exactly the `module_definition` + `instantiation_plan` facts M4 published (the `PlanPort`/`PlanParam` name lists signature help reads); every plan refusal is swallowed silently — a hint has no place for a sentence. |
@@ -437,13 +461,17 @@ engine-lane features are listed above; this table is the server-internal web.
| `change-debounce ◀──▶ incremental-sync, pull-diagnostics` | handshake | The amendment above. A `didChange` composes its ranges against the *pending* text when there is one (`sync::apply_changes` unchanged) and defers only the analysis; the flush happens at the next request, the next non-`didChange` notification, or a 150 ms quiet period on the `cancel-request` queue (`recv_timeout` — no thread, no timer object). Observable: intermediate diagnostics states are no longer published, pinned in `tests/e2e.rs`. |
| `port-detail-spans ──▶ hover-declarations` | depends | The second fenced section, and the comment attached to each, are built on hover-declarations' snippet machinery and its `spells_exactly` guard, both unchanged. `nav::definition` returns the detail location first so a jump and the card cannot disagree. |
| `hover-declarations ◀──▶ vlog_semantic` | handshake | `Semantics::symbols_named` (§1.2) replaced `hover::live_symbol`'s and `nav::indexed_references`' scan-every-symbol loops. Behavior-identical **because the lookup preserves declaration order** — the tie-break between two live declarations of one name is pinned on both sides. |
| `hover-line-index ──▶ hover-declarations / port-detail-spans` | depends | `Def::lines` supplies indexed hover headings (including split-port detail lines); `Workspace::file_view` supplies the guarded snippet and the few non-indexed line lookups. `locate::location` shares that view, so a references list reads a closed file once rather than once per site. |
| `cancel-request ──▶ lsp-server pin` | depends | See §1.2; queue/burst exists because the pinned transport is a rendezvous channel. |
| `scan-interleave ──▶ cancel-request / work-done-progress` | depends | The same queue is polled between startup-scan files. `publish_scan` lands the index, completion and include batches before dispatch; `must_wait` holds requests queued behind any rescan-triggering message and preserves their order/cancels. Progress still counts the whole scan even when requests are answered before the bar comes down. |
| `verbose-timing ◀──▶ editor-packaging / scan-interleave / change-debounce` | handshake | `lucisv.verbose` is an extension-owned spawn setting: false means no arguments and no timing traffic; true means `lucisv-server --verbose`, and changing it restarts the client process. The server writes `MessageType::LOG` lines prefixed `timing:` for request/notification handlers, scan and widen lifecycles, dirty-buffer flushes, one-file reindexes, and requests held behind rescans. The request line precedes its response; notification lines follow their work. Instrumentation is silent by construction when off (one branch, no clock read or formatting), and it observes rather than changes scan/queue ordering. |
| `work-done-progress ──▶ indexing-ux` | depends (then) | w-d-p put up the bar; indexing-ux made it count (`IndexEvent` stream); index-persistence added `Cached`. |
| `large-file-mode ◀──▶ semantic-tokens-delta` | handshake | The windowed lexing serves `semanticTokens/range`; on a large buffer `full`/`full/delta` must answer an ERROR (`ServerCancelled`/`ContentModified`) or the client stops asking the range provider — two sides pinning one wire behavior. `Document::large` is structurally a full `Document` (all fields valid, empty) so no handler changes — the obligation lands on **future** handlers that read `doc.text` (dispatch-table test enforces). |
| `lsp-318-extras ──▶ range-formatting` | depends | `rangesFormatting` is a thin adapter over the same n-range `LineRanges` engine `--lines` uses; hand-rolled params because `lsp-types` 0.97 lacks 3.18. |
| `on-type-formatting ──▶ range-formatting, editor-scopes` | depends | `;` goes through `format::range_formatting` unchanged; `\n` answers indent only, computed from `pairs.rs`'s own keyword tables (three items widened to `pub(crate)`) — one reader's answer for "what opens a scope". |
| `interactive-latency ──▶ change-debounce, editor-scopes, selection-range, on-type-formatting, completion-core, inline-templates` | depends | Round 2 of the perf work (`docs/perf/README.md`). It measures the flush change-debounce coalesces and the round trip it defers, and it replaces one token *sweep* with one token *binary search* in `selection.rs`, `on_type.rs`, `completion.rs` and `inline.rs`. No answer moved — each swap is pinned against the sweep it replaced at every byte — so none of those five features' contracts changed; what they now share is `state.rs`'s two search primitives and the ordering property of `tokenize`'s output they rest on. |
| `interactive-latency ◀──▶ lucisv-server` | handshake | Two free functions, `first_token_reaching` and `first_token_from`, are published from `state.rs` beside `Document::token_at`; that is where the monotonicity argument every caller depends on is written down, and `state::tests::the_token_stream_rises_and_never_overlaps` is the test that fails first if `vlog_parser` ever breaks it. `tests/e2e.rs`'s `Live::finish` now returns its publish count (existing callers ignore it), and `perf::generated_module` has a copy in `tests/e2e.rs` — a binary crate's modules are unreachable from an integration test — which must stay the same shape as the original. |
| `references-nav ──▶ workspace-index / hover-line-index` | depends | Cross-file references resolve an indexed target first and consume declaration postings directly; same-file local references stay on `Semantics`. Locations use the shared `FileView`. `documentHighlight` now also follows the document's external overlay for names declared elsewhere, fixing the old “references works, highlight is empty” split without widening highlights beyond the current file. |
| `selection-range / linked-editing ──▶ spans, name-spans` | depends | Pure arrangements of existing ranges; linked-editing's table documents exactly which constructs carry both spans (and which verbatim ones can't — `program`, property/sequence, covergroup). |
| `type-definition ──▶ nav / overlay-promotion / ansi-first-port` | depends + 2 delivered handshakes | Now literally `nav::definition` at the type name's offset; both of its filed requests landed (§2.2, §2.5). |
| `hierarchy ◀──▶ inlay-hints` | handshake (shared walk) | The instantiation walk was lifted out of `inlay.rs` into a shared module (now `vlog_semantic::instantiations`) rather than copied — the two answers cannot drift; inlay's 34 tests are the regression net. |
@@ -454,7 +482,7 @@ engine-lane features are listed above; this table is the server-internal web.
| edge | kind | contract |
|---|---|---|
| `editor-packaging ◀──▶ lucisv-server` | handshake | The spawn contract (§1.2) plus the fence-tag contract: every markdown code block the server emits opens ```` ```systemverilog ```` — three call sites pin the string; the grammar registers the id. |
| `editor-packaging ◀──▶ lucisv-server` | handshake | The spawn contract (§1.2), including verbose-timing's `[]` / `['--verbose']` argument pair and restart-on-setting-change rule, plus the fence-tag contract: every markdown code block the server emits opens ```` ```systemverilog ```` — three call sites pin the string; the grammar registers the id. |
| `editor-packaging ◀──▶ vlog_parser` | handshake | The grammar↔`KEYWORDS` test lock (§1.2). |
| `editor-snippets ──▶ editor-packaging` | depends | Static `contributes.snippets` keyed to the two language ids the manifest declares; consumes nothing from the server *at runtime* (works with the server missing — deliberate). Its **content** is negotiated against the server's template tier — see the `completion-templates ◀──▶ editor-snippets` handshake in §2.7. |
| `editor-platform-vsix ──▶ editor-packaging, release-prep` | depends | Changes *which path* is spawned, never how; consumes `release.sh`'s artifact naming; promises the three `bin/` layout shapes to `extension.js` (asserted with `unzip -Z1` per package). |
@@ -487,8 +515,11 @@ update the filing README(s) and this file.
| 15 | Bind semantics: whether a `bind`'s target scope and connections should resolve through the workspace index (today only the instantiated module name is recorded) | bind | vlog_semantic |
| 16 | DPI/package re-export halves as real references (`export pkg::item` doesn't resolve; `*::*` has `"*"` as its package name, which nothing expects) | dpi-export | vlog_semantic |
| 17 | Inline aggregate as a parameter-override *argument* (`m #(.T(struct packed { logic a; })) u ();`) is rejected in expression position; M4's `instantiation_plan` drops such a `parameter type` default rather than emit unparseable text | refactor-instantiate (gap 1; its gap 2 was delivered by ansi-first-port) | vlog_parser |
| 18 | A macro-invocation census in `FileFacts`: per-file macro names plus identifier-shaped words in their arguments. Rename's index-bounded fan-out currently preserves every edit/refusal but can lose informational macro-argument warnings in files that have no other relationship to the renamed name; the same table would serve the port refactorings' identical scan. This changes the record shape and therefore requires a `FACTS_FORMAT` bump. | refactor-rename (performance-wave residue, accepted and filed) | vlog_semantic |
---## 3. Combined graph — features mapped onto modules
---
## 3. Combined graph — features mapped onto modules
### 3.1 Feature → primary-home matrix
@@ -504,13 +535,13 @@ untouched, reusing existing arms.
|---|---|
| `vlog_parser` | spans, name-spans, recursion-limit, error-recovery, define-table, lexer-cleanup, and the grammar lane: *macro-items*, *classes*, *bind*, *dynamic-types*, *types-decls*, *item-misc*, *directives-in-lists*, *directives-in-instances*, *dpi-export*, *assertions*, *interfaces*, *expressions-2*, *dv-statements*, *mop-up-2*, *directive-split*, *ansi-first-port* (most also add formatter arms — parser+formatter pairs by default; directive-split and ansi-first-port reused existing arms and left `vlog_formatter/src` untouched) |
| `vlog_formatter` | safety-net (`verify.rs`), case-tables, formatter-bug-fixes, corpus-bugs, comments-round, comments-round-2, alignment (`align.rs`), format-fences (`fence.rs`), range-formatting (`range.rs`), shared-fence-filter |
| `vlog_semantic` | vlog-semantic (`bind`/`resolve`/`model`), workspace-index (`workspace.rs`), class-semantics, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` in `bind.rs`/`model.rs`/`workspace.rs`, the `facts.rs` codec + `FACTS_FORMAT` bump, and `Semantics::symbols_named` in `lib.rs`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`), incremental-index (`update_file`, edge tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives) |
| `vlog_semantic` | vlog-semantic (`bind`/`resolve`/`model`), workspace-index (`workspace.rs`), class-semantics, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` and `Semantics::symbols_named`), hover-line-index (`DeclLines`, facts codec + `FACTS_FORMAT` 4), scan-interleave (`WorkspaceIndex::absorb`), refactor-rename's performance amendment (`files_spelling`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`, facts-from-analysis), incremental-index (`update_file`, edge/reference tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives) |
| `vlog_linter` | linter-core, lint-harness, lint-rules-2, semantic-lints (`signals.rs`), one-parse (`context.rs`) |
| `vlog_refactor` | refactor (plan), refactor-rename, refactor-ports, refactor-instantiate, references-nav (engine half) |
| `vlog_refactor` | refactor (plan), refactor-rename (including `prepare_rename_here` / `rename_name_at` selector half), refactor-ports (including module-target selectors), refactor-instantiate, references-nav (whole-scope equivalence oracle) |
| `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`) |
| `lucisv` (CLI) | cli-polish, config-discovery (wiring), parallel-files, cli-filelist, linter-core (CLI half in `lint.rs`), one-parse (`lint.rs` parses once via `ParsedSource`), format-cache (wiring), release-prep (`--version` contract) |
| `lucisv_server` | lucisv-server (trunk), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core→`completion.rs`/`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring→`rename.rs`/`ports.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server.rs`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs`, pull-diagnostics→`diagnostics.rs`+`server.rs`, semantic-tokens-delta→`tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, change-debounce→`server.rs`, perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion.rs`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` |
| `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line) |
| `lucisv_server` | lucisv-server (trunk), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core→`completion.rs`/`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring/performance fan-outs→`rename.rs`/`ports.rs`+`state.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server.rs`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs` (+`include_sources` in `state.rs`), pull-diagnostics→`diagnostics.rs`+`server.rs`, semantic-tokens-delta→`tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, hover-line-index→`hover.rs`+`locate.rs`+`state.rs`, scan-interleave→`server.rs`+`state.rs`+`candidates.rs`+`includes.rs`, change-debounce→`server.rs`, verbose-timing→`main.rs`+`server.rs`+`tests/e2e.rs`, perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion.rs`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` |
| `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line), verbose-timing (`lucisv.verbose`, spawn args and restart in `extension.js`) |
| `tools/` + CI | corpus-check, release-prep, ci-release, editor-platform-vsix (staging), range-formatting (`lucisv-changed.sh`) |
### 3.2 The combined picture
@@ -592,11 +623,13 @@ ownership explicitly.
| `vlog_formatter/src/verify.rs` | safety-net | every formatter feature; the CLI's exit-2 promise | CLAUDE.md invariant #4. Never widen a normalization without masked-corruption attack tests; the standing pattern is "untouched + rejection tests anyway". The single widening in history is macro-items' backtick-`Ident` arm in `normalize` — which produced lucisv's one real corruption; its repair, `trim_lines_outside_strings`, is a *narrowing*, and the pattern to copy: the widening shipped without attack tests, the fix shipped with them. `line_starts_inside_string` is the one definition of "which line breaks are data" — both `format.rs` and `verify.rs` must read it. |
| `vlog_formatter/src/fence.rs` | format-fences | range-formatting, shared-fence-filter, CLI `--fix` (`lucisv/src/lint.rs`), server quick fixes (`lucisv_server/src/lint.rs`) | `protected_regions`/`is_protected` are the **only** supported way to ask "may an automatic edit touch these bytes". One answer, **two** front ends — and `vlog_linter` is deliberately not one of them (it stays fence-blind; the filter lives in each front end). Open gap: no `Class` arm in `scan_nested` (§2.9-3). |
| `lucisv_server/src/pairs.rs` | editor-scopes | documentHighlight, missing-closer diagnostics, scopePairs rainbow, folding, completion gates, on-type indent, inline-templates, expand-selection (`selection.rs`) | The `RULES` table + no-closer guard list is shared truth. Any keyword added to/removed from `token.rs` requires re-checking it (a word that stops being a keyword silently stops being matched). |
| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, indexing-ux, incremental-index, index-persistence, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`) | every handler | `Workspace` is immutable through request handlers (no caches added by handlers — hierarchy/inlay/type-hierarchy all state it). The scope ladder (filelist > `index.scope: "workspace"` > folder-scope, with the rootless flat sibling read as folder-scope's one exception; buffers overlay everything) is the contract; `update_one`'s answer must equal a full rebuild's (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. |
| `lucisv_server/src/server.rs` | lucisv-server; amended by cancel-request, change-debounce, scan-interleave, index-scope, verbose-timing | every request/notification and every rebuild trigger | One ordered loop owns all mutable server state. A startup scan may publish a prefix and answer queued work between files; a request queued behind a rescan trigger is held until that rescan lands, and its cancel travels with it. Never make the distinction time-based: machine load must not change which index a request sees. Verbose timing may observe each wrapper/lifecycle but must be entirely silent when off and must not move protocol ordering. The queue thread only forwards protocol messages and must never parse. |
| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, scan-interleave, indexing-ux, incremental-index, index-persistence, hover-line-index, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`), refactor performance fan-outs | every handler | `Workspace` is immutable through request handlers except the interior-mutable four-entry/8 MiB `FileView` cache. The scope ladder (filelist > `index.scope: "workspace"` > folder-scope at shipped depth 2; a rootless session never climbs and always reads its own directory flat) and open-buffer overlay are contracts. `Scan` has whole/widen shapes but one step/finish path; index/candidate/include prefixes publish together. `module_sources`, `rename_sources`, and `include_sources` must remain supersets of what their engines can edit/refuse over; `rename_sources` falls back to `sources()` when an ambiguous posting prevents a proven bound. `update_one` and a completed scan must equal a fresh build (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. |
| `lucisv_server/src/settings.rs` | editor-settings | folders-and-config, indexing-ux, index-scope, index-persistence, inline-templates, will-save-wait-until, filelist, large-file-mode | One parser for both doors (push and pull, via `from_section` re-wrapping). Every key drops garbage independently; defaults that are not "silence" (1 MiB cap, log on, persist on, 4 MiB large-file threshold) are hand-written in `Default`. `set_client_settings` returns whether a reindex is owed — new keys must decide that question explicitly. |
| `vlog_semantic/src/workspace.rs` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope | server state, hierarchy/lens/type-hierarchy, refactor, completion | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change, edge tables built by the same lifted walks the handlers use. |
| `vlog_semantic/src/workspace.rs` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope, hover-line-index, scan-interleave, refactor-rename performance | server state, hierarchy/lens/type-hierarchy, refactor, completion | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change (currently 4), edge/posting tables built by the same lifted walks the engines use. `DeclLines` must round-trip and participate in `fingerprint`; `absorb` must equal one build over the resulting record set; `files_spelling` must continue to include unresolved non-empty external/inherited paths or rename loses its dangling-use refusal. |
| `vlog_refactor/src/rename.rs` | refactor-rename; shared by references-nav and the performance wave | server rename/prepareRename/references and port refactor verification | `Scope` remains the whole-scope authority and `collect_occurrences` the one rename/references walk. The fast `prepare_rename_here` answer/refusal and `rename_name_at` target are parity contracts, not alternate semantics. Any new refusal must be expressible on the fast path or force a deferral; any new occurrence shape must be reflected in the server fan-out or trigger its all-sources fallback. |
| `vlog_parser/src/token.rs` keyword table | completion-core (`KEYWORDS` export) | lexer, pairs.rs, editor grammar (test-locked), completion | Adding a keyword = lexer change + `pairs.rs` re-check + a hand edit to the grammar (`tests/grammar.rs` names the missing word) + potentially `verify.rs`-adjacent behavior. dv-statements added `randcase`/`let` to `is_keyword` and recorded it as shared with the adjacent lexer-cleanup round — the precedent for treating this file as coordinated even between back-to-back rounds. |
| `editors/vscode/package.json` | editor-packaging | editor-settings, editor-scopes (colour ids), editor-snippets, index-persistence, platform-vsix, marketplace-page | Settings/colour/snippet ids referenced from `extension.js` or the server must move in lockstep; mismatches are *silent* (VS Code ignores unknown ids). Version number is one of the four version files. |
| `editors/vscode/package.json` | editor-packaging | editor-settings, editor-scopes (colour ids), editor-snippets, index-persistence, verbose-timing, platform-vsix, marketplace-page | Settings/colour/snippet ids referenced from `extension.js` or the server must move in lockstep; mismatches are *silent* (VS Code ignores unknown ids). `lucisv.verbose` is special: it changes a spawn argument and therefore restarts the server instead of flowing through the ordinary settings push. Version number is one of the four version files. |
| `tools/release.sh` artifact names | release-prep / editor-platform-vsix | ci-release (`prune_release_assets.sh`), `audit_artifacts.sh`, extension `bin/` layouts | Renaming a `.vsix` is a two-file change (`release.sh` + `prune_release_assets.sh`'s suffix list); renaming a per-triple binary is a two-file change (`release.sh` + `audit_artifacts.sh`, which skips `.vsix` and hard-fails on an unknown binary name). Get the wrong pair and the release fails by name. |
| The frozen CLI contract | cli-polish | corpus scripts, CI users, every new CLI mode | Exit codes 0/1/2 forever; stdout stays machine-readable (JSON mode prints exactly one array; warnings to stderr). |