From 0f4830afa520a8494af31e9f7d64e07332a1b671 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 23 Sep 2026 17:14:43 -0700 Subject: [PATCH] MCP M6: read-only reuse of the editor's index cache, an own store, the forced-delete ruling, first instructions; the block's closing docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit crates/lucisv_mcp/src/cache.rs: at startup `--index-cache DIR/index-cache` (the language server's store) is read READ-ONLY — header CACHE_FORMAT/FACTS_FORMAT/version must match this build or the store is ignored with one stderr line; each record line's checksum verified, decoded, keyed by (record path, content hash) and used only for a discovered file whose bytes hash to it, through IndexBuilder::add_facts instead of a parse; the server never writes that file. Its own `index-cache-mcp` is written once at exit, atomically, in the same codec (a test pins the restated framing against index_cache.rs's source). opentitan: cold 1.9 s → warm 0.8 s (walk 210 ms + merge 204 ms are the floor). delete_item with force may remove an item holding `define/`undef, warning which macros went (M4's ruling); INSTRUCTIONS names the read tools, the edit tools, dry_run and diagnostics. Closing docs: docs/topo.md gains the lucisv_mcp node and its six edges, the mcp-packaging spawn/packaging rows, the read-only cache row and §2.9 rows 35–42 (MCP-5/6/7/8/10/11/12/13 and the parser leniency the M3.5 verifier exposed); repository-analysis map row and nine-crate count; README architecture row; CLAUDE.md measurement for the new crate. QA (Opus; interrupted by the owner moving the machine, verdict pass so far): swapped/stale/foreign/deleted/off-by-one-header/CRLF stores skipped, the editor's store byte-identical through a session, SIGKILL mid-write harmless, a 231 MB store linear, fingerprint parity over the whole checkout; two low items open — the README threat model reworded, and an orphaned `.tmp` after a kill between write and rename to be swept in the census round. Gates: fmt, clippy clean; lucisv_mcp 318 passed; the dev's workspace run 4 858 passed on the same code. Co-Authored-By: Claude Fable 5.1 --- CLAUDE.md | 7 + README.md | 6 +- TODO-MCP.md | 9 +- crates/lucisv_mcp/src/cache.rs | 193 +++++ crates/lucisv_mcp/src/cache/tests.rs | 143 ++++ crates/lucisv_mcp/src/main.rs | 4 +- crates/lucisv_mcp/src/project/mod.rs | 105 ++- crates/lucisv_mcp/src/rpc.rs | 36 +- crates/lucisv_mcp/src/tools/item.rs | 21 +- crates/lucisv_mcp/src/tools/item/verify.rs | 45 +- crates/lucisv_mcp/tests/cache.rs | 257 +++++++ crates/lucisv_mcp/tests/opentitan.rs | 125 +++- crates/lucisv_mcp/tests/qa_m4.rs | 14 +- crates/lucisv_mcp/tests/qa_m6.rs | 711 +++++++++++++++++++ crates/lucisv_mcp/tests/wire.rs | 112 +++ docs/features/mcp-cache-and-census/README.md | 385 ++++++++++ docs/features/mcp-transport/README.md | 6 +- docs/perf/README.md | 21 + docs/repository-analysis.md | 3 +- docs/topo.md | 20 + 20 files changed, 2163 insertions(+), 60 deletions(-) create mode 100644 crates/lucisv_mcp/src/cache.rs create mode 100644 crates/lucisv_mcp/src/cache/tests.rs create mode 100644 crates/lucisv_mcp/tests/cache.rs create mode 100644 crates/lucisv_mcp/tests/qa_m6.rs create mode 100644 docs/features/mcp-cache-and-census/README.md diff --git a/CLAUDE.md b/CLAUDE.md index 9103281..0c46242 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -77,6 +77,13 @@ the source selectors are three sentences), `perf.rs` 900 (reasoned), `lexer.rs` 763, `vlog_formatter/src/format/stmt.rs` 604 (at the mark; the next statement arm goes in a new module) — and everything else under it. +Re-measured 2026-09-23 for the MCP block (`crates/lucisv_mcp`, nine crates +now): largest files `tools/read.rs` 405, `tools/item.rs` 379, `tools/item/verify.rs` +363, `tools/nav.rs` 340, `tools/diagnostics.rs` 330, `tools/interface.rs` 322, +`tools/hierarchy.rs` 316 — everything under 600; the M3.5 engine lane left +`vlog_refactor/src/rename/connections.rs` at 477 and `check/mod.rs` at 426, +and `lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55). + ## Rust standards - `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]` diff --git a/README.md b/README.md index dee3907..960fa19 100644 --- a/README.md +++ b/README.md @@ -460,7 +460,7 @@ understand still lints the buffer. Full rules: ## Architecture (the ruff mapping) -The eight-crate workspace separates source syntax, reusable engines, project +The nine-crate workspace separates source syntax, reusable engines, project inputs, and the CLI/LSP front ends. The formatter follows ruff's separation of document layout from language rules: @@ -475,6 +475,7 @@ of document layout from language rules: | `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement | | `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes | | `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities | +| `crates/lucisv_mcp` | — | Model Context Protocol server for coding agents: project understanding and verified, token-saving edits over stdio (`docs/mcp/PLAN.md`) | `vlog_parser` and `lucisv_core` have no dependencies. The formatter depends only on the parser; semantic analysis also depends only on the parser. @@ -482,7 +483,8 @@ Linting consumes the parser, semantics and `lucisv_core` (for the one `--exclude`-style matcher a waiver file's `--location` shares with the CLI); refactoring consumes the parser and semantics. The CLI reaches semantics through the linter and has no refactoring dependency. The server -composes all six libraries. See [topo.md](docs/topo.md) for the full graph, +composes all six libraries, and so does the MCP server (never the LSP +crate). See [topo.md](docs/topo.md) for the full graph, including the linter’s and refactor’s formatter dependencies used only by tests. Key ideas carried over from ruff/prettier: diff --git a/TODO-MCP.md b/TODO-MCP.md index baf77ad..4f677b8 100644 --- a/TODO-MCP.md +++ b/TODO-MCP.md @@ -273,17 +273,22 @@ MCP section), `docs/topo.md` (§1.1 node + §2.8 rows for `lucisv_mcp`, an `mcp-cache-and-census` README, `TODO-MCP.md` (this file's closing entries). Depends on M4 and M5 merged. -- [ ] `cache.rs`: the read-only reader of the LSP's `index-cache` (header +- [x] `cache.rs`: the read-only reader of the LSP's `index-cache` (header check on `CACHE_FORMAT`/`FACTS_FORMAT`/version, per-line checksum, `FileFacts::decode`, `record_path`); on `--index-cache DIR` a file whose `content_hash` has a record is `add_facts`'d instead of parsed; MCP's own `index-cache-mcp` written with the same codec on exit and read on start; never a write to the LSP's file (a test opens the store read-only and asserts its bytes after a full MCP session) -- [ ] startup timing on opentitan cold / warm-from-LSP-store / + — done 2026-09-23 (dev): `src/cache.rs`, `tests/cache.rs`; the M4 + rule-6 ruling (`force` on `delete_item`) and the first `instructions` + revision delivered in the same lane (`docs/features/mcp-cache-and-census`) +- [x] startup timing on opentitan cold / warm-from-LSP-store / warm-from-own-store, and the per-call stat sweep, recorded in `docs/perf/README.md` next to the LSP's scan trace numbers; the whole-set refactor cost from M3 measured on `rename` in `aes` + — done 2026-09-23 (dev): cold 1.87 s, warm 0.83–0.85 s from either + store, sweep 5.6–6.1 ms, `rename` dry run 2.23–2.28 s - [ ] the token census (PLAN §8): the three tasks, each run twice (file tools only / with lucisv-mcp) by the same agent model, tokens in and out from the transcripts, written up in `docs/mcp/census.md` with the diff --git a/crates/lucisv_mcp/src/cache.rs b/crates/lucisv_mcp/src/cache.rs new file mode 100644 index 0000000..fb6b9b5 --- /dev/null +++ b/crates/lucisv_mcp/src/cache.rs @@ -0,0 +1,193 @@ +//! The index caches a startup reads instead of parsing (PLAN §6): the +//! language server's `index-cache`, **read only, never written**, and this +//! server's own `index-cache-mcp` beside it, in the same codec, written once +//! when the session ends. +//! +//! The codec is `lucisv_server::index_cache`'s, restated here because its +//! constants are private to that crate (Handshake MCP-14 in +//! `docs/features/mcp-cache-and-census/README.md`; a test pins the restated +//! header and line formats against that file's source text). A store is a +//! header line `lucisv-index-cache\t\t\t` +//! and one record per line, `\t\t`. A record is used only for a file whose bytes hash to its +//! content hash, so it can only ever stand in for the parse of exactly those +//! bytes; a store from another build, a torn line or a line whose checksum +//! fails costs a parse and nothing else. + +use std::collections::HashMap; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use lucisv_core::cache::content_hash; +use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT}; + +/// The language server's store in the cache directory. Read, never written. +pub const EDITOR_STORE: &str = "index-cache"; + +/// This server's own store in the same directory. +pub const OWN_STORE: &str = "index-cache-mcp"; + +/// `lucisv_server::index_cache::CACHE_FORMAT`: the framing's version. +const CACHE_FORMAT: u32 = 2; + +/// lucisv's version: another release may parse the same bytes into other +/// facts, so its store is not read. +const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// Which store a record came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + /// The language server's `index-cache`. + Editor, + /// This server's `index-cache-mcp`. + Own, +} + +/// The records of both stores, still encoded, keyed by the path they +/// describe and the hash of the bytes they were read from. +#[derive(Default)] +pub struct Records { + held: HashMap<(PathBuf, u64), (Source, String)>, +} + +/// How a startup used the stores. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Reuse { + /// Files whose record came from the language server's store. + pub editor: usize, + /// Files whose record came from this server's own store. + pub own: usize, +} + +impl Reuse { + /// One more file taken from `source`. + pub fn count(&mut self, source: Source) { + match source { + Source::Editor => self.editor += 1, + Source::Own => self.own += 1, + } + } +} + +impl Records { + /// Both stores in `dir`. A missing directory or store is a cold start, + /// silently (the editor may not have made the directory yet); a store + /// from another build is ignored whole, with one line on stderr. + pub fn load(dir: &Path) -> Records { + let mut records = Records::default(); + // Own first, so a record both stores hold is credited to the editor. + records.read(&dir.join(OWN_STORE), Source::Own); + records.read(&dir.join(EDITOR_STORE), Source::Editor); + records + } + + /// Read one store into the map. + fn read(&mut self, store: &Path, source: Source) { + let Ok(bytes) = fs::read(store) else { return }; + let mut lines = store_lines(&bytes).into_iter(); + match lines.next() { + None => return, + Some(first) if first == header().as_bytes() => {} + Some(_) => { + eprintln!( + "lucisv-mcp: ignoring the index cache {}: not written by lucisv {VERSION}", + store.display() + ); + return; + } + } + for line in lines { + if let Some((path, content, facts)) = std::str::from_utf8(line).ok().and_then(parse) { + self.held.insert((path, content), (source, facts.to_string())); + } + } + } + + /// The facts of `path` when its bytes hash to `content`, and where they + /// came from. A record that no longer decodes is a miss. + pub fn take(&mut self, path: &Path, content: u64) -> Option<(FileFacts, Source)> { + let (source, encoded) = self.held.remove(&(path.to_path_buf(), content))?; + let facts = FileFacts::decode(&encoded)?; + (facts.path() == path).then_some((facts, source)) + } +} + +/// Write this server's own store in `dir`: the header, then one record per +/// `(content hash, facts)`, in the order given. Atomic — a temporary file +/// renamed over the store — so a reader sees the old store or the new one. +/// Never touches [`EDITOR_STORE`]. +pub fn write_own(dir: &Path, records: &[(u64, &FileFacts)]) -> io::Result { + fs::create_dir_all(dir)?; + // Self-ignoring, as the language server marks the directory: a cache + // path inside the project is a plausible thing to pass. + let ignore = dir.join(".gitignore"); + if !ignore.exists() { + let _ = fs::write(&ignore, "*\n"); + } + let mut text = header(); + text.push('\n'); + let mut written = 0; + for (content, facts) in records { + // A path that cannot be written on a line (not UTF-8, a tab) is + // simply not cached. + if let Some(encoded) = facts.encode() { + text.push_str(&line(*content, &encoded)); + text.push('\n'); + written += 1; + } + } + let tmp = dir.join(format!("{OWN_STORE}.{}.tmp", std::process::id())); + let written_through = + fs::write(&tmp, text).and_then(|()| fs::rename(&tmp, dir.join(OWN_STORE))); + if let Err(problem) = written_through { + let _ = fs::remove_file(&tmp); + return Err(problem); + } + Ok(written) +} + +/// The first line of a store this build reads and writes. +fn header() -> String { + format!("lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t{VERSION}") +} + +/// One record: the content hash, the encoded facts, their checksum. +fn line(content: u64, facts: &str) -> String { + format!("{content:016x}\t{facts}\t{:016x}", content_hash(facts.as_bytes())) +} + +/// One record read back: its path, content hash and still-encoded facts. +/// `None` for anything but a whole record whose facts match their checksum — +/// which includes a torn last line. +fn parse(line: &str) -> Option<(PathBuf, u64, &str)> { + let (hash, rest) = line.split_once('\t')?; + let content = hex16(hash)?; + // No encoded field holds a raw tab, so the facts run to the last one. + let (facts, checksum) = rest.rsplit_once('\t')?; + if hex16(checksum)? != content_hash(facts.as_bytes()) { + return None; + } + Some((record_path(facts)?, content, facts)) +} + +/// A 16-digit hexadecimal field, exactly as wide as [`line`] writes it. +fn hex16(field: &str) -> Option { + if field.len() != 16 { + return None; + } + u64::from_str_radix(field, 16).ok() +} + +/// The store's lines as bytes (a torn multi-byte character costs its own +/// line only), `\r` stripped as `str::lines` would. +fn store_lines(bytes: &[u8]) -> Vec<&[u8]> { + let body = bytes.strip_suffix(b"\n").unwrap_or(bytes); + if body.is_empty() { + return Vec::new(); + } + body.split(|byte| *byte == b'\n').map(|line| line.strip_suffix(b"\r").unwrap_or(line)).collect() +} + +#[cfg(test)] +mod tests; diff --git a/crates/lucisv_mcp/src/cache/tests.rs b/crates/lucisv_mcp/src/cache/tests.rs new file mode 100644 index 0000000..ec866cf --- /dev/null +++ b/crates/lucisv_mcp/src/cache/tests.rs @@ -0,0 +1,143 @@ +//! The caches against the rebuild oracle: an index started from records is +//! the index a cold build over the same files makes +//! (`WorkspaceIndex::fingerprint`), and every record that is not exactly +//! right is a parse, not an answer. + +use std::fs; +use std::path::{Path, PathBuf}; + +use super::*; +use crate::project::Project; + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lucisv-mcp-cache-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("src")).unwrap(); + fs::create_dir_all(dir.join("cache")).unwrap(); + fs::canonicalize(dir).unwrap() +} + +/// Three files that reach each other: a package, a module importing it, a +/// module instantiating that one through `.*`, and a macro. +fn design(dir: &Path) { + let src = dir.join("src"); + fs::write(src.join("p.sv"), "package p; parameter int W = 4; endpackage\n").unwrap(); + let leaf = "`define ONE 1'b1\nmodule leaf import p::*; (input logic [W-1:0] d);\nendmodule\n"; + fs::write(src.join("leaf.sv"), leaf).unwrap(); + let top = "module top(input logic [3:0] d);\n leaf u_leaf(.*);\nendmodule\n"; + fs::write(src.join("top.sv"), top).unwrap(); +} + +fn cold(dir: &Path) -> String { + Project::open(vec![dir.join("src")], None).index().fingerprint() +} + +fn warm(dir: &Path) -> Project { + Project::open_cached(vec![dir.join("src")], None, Some(dir.join("cache"))) +} + +/// A store in the language server's format, one record per file as its +/// parse finds it. +fn editor_store(dir: &Path) -> String { + let mut text = format!("{}\n", header()); + let mut paths: Vec = + fs::read_dir(dir.join("src")).unwrap().map(|e| e.unwrap().path()).collect(); + paths.sort(); + for path in paths { + let bytes = fs::read(&path).unwrap(); + let facts = FileFacts::of(path.clone(), std::str::from_utf8(&bytes).unwrap()); + text.push_str(&line(content_hash(&bytes), &facts.encode().unwrap())); + text.push('\n'); + } + text +} + +#[test] +fn the_codec_is_the_language_servers_own() { + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../lucisv_server/src/index_cache.rs"); + let source = fs::read_to_string(source).unwrap(); + for pinned in [ + format!("const FILE: &str = \"{EDITOR_STORE}\";"), + format!("const CACHE_FORMAT: u32 = {CACHE_FORMAT};"), + "const VERSION: &str = env!(\"CARGO_PKG_VERSION\");".to_string(), + "format!(\"lucisv-index-cache\\t{CACHE_FORMAT}\\t{FACTS_FORMAT}\\t{VERSION}\")".to_string(), + "format!(\"{content:016x}\\t{facts}\\t{:016x}\", content_hash(facts.as_bytes()))" + .to_string(), + ] { + assert!(source.contains(&pinned), "index_cache.rs no longer says {pinned}"); + } + assert_eq!(header(), format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}")); +} + +#[test] +fn a_warm_start_from_the_editors_store_is_the_cold_index() { + let dir = scratch("editor"); + design(&dir); + fs::write(dir.join("cache").join(EDITOR_STORE), editor_store(&dir)).unwrap(); + let project = warm(&dir); + assert_eq!(project.reuse(), Some(Reuse { editor: 3, own: 0 })); + assert_eq!(project.index().fingerprint(), cold(&dir)); + fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_warm_start_from_its_own_store_is_the_cold_index_and_a_changed_file_is_parsed() { + let dir = scratch("own"); + design(&dir); + let first = warm(&dir); + assert_eq!(first.reuse(), Some(Reuse::default())); + let (store, written) = first.save_cache().unwrap().unwrap(); + assert_eq!((store, written), (dir.join("cache").join(OWN_STORE), 3)); + assert!(!dir.join("cache").join(EDITOR_STORE).exists(), "the editor's store is never written"); + let second = warm(&dir); + assert_eq!(second.reuse(), Some(Reuse { editor: 0, own: 3 })); + assert_eq!(second.index().fingerprint(), cold(&dir)); + + fs::write(dir.join("src/top.sv"), "module top2; leaf u_leaf(.d(4'b0)); endmodule\n").unwrap(); + let third = warm(&dir); + assert_eq!(third.reuse(), Some(Reuse { editor: 0, own: 2 })); + assert_eq!(third.index().fingerprint(), cold(&dir)); + assert_eq!(third.index().units("top2").len(), 1); + assert!(third.index().units("top").is_empty()); + fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_torn_a_forged_and_a_foreign_record_are_each_a_parse() { + let dir = scratch("damaged"); + design(&dir); + let good = editor_store(&dir); + let lines: Vec<&str> = good.lines().collect(); + // Record 1 (leaf.sv): its hash still the file's, a macro renamed in its + // facts, its checksum left as it was. + assert!(lines[1].contains("/leaf.sv\t") && lines[1].contains("ONE")); + let forged = lines[1].replacen("ONE", "TWO", 1); + // Record 3 (top.sv): torn inside its facts, no newline. + let torn = &lines[3][..lines[3].len() / 2]; + let store = format!("{}\n{forged}\n{}\n{torn}", lines[0], lines[2]); + fs::write(dir.join("cache").join(EDITOR_STORE), &store).unwrap(); + let project = warm(&dir); + assert_eq!(project.reuse(), Some(Reuse { editor: 1, own: 0 }), "only p.sv is whole"); + assert_eq!(project.index().fingerprint(), cold(&dir)); + + let foreign = good.replacen(VERSION, "0.0.0", 1); + fs::write(dir.join("cache").join(EDITOR_STORE), &foreign).unwrap(); + assert_eq!(warm(&dir).reuse(), Some(Reuse::default()), "another version's store is not read"); + fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_record_filed_under_another_path_or_hash_is_not_taken() { + let mut records = Records::default(); + let facts = FileFacts::of(PathBuf::from("/a.sv"), "module a; endmodule\n"); + let encoded = facts.encode().unwrap(); + let record = line(7, &encoded); + let parsed = parse(&record).unwrap(); + assert_eq!((parsed.0.as_path(), parsed.1), (Path::new("/a.sv"), 7)); + records.held.insert((parsed.0, parsed.1), (Source::Editor, parsed.2.to_string())); + assert!(records.take(Path::new("/a.sv"), 8).is_none(), "another hash"); + assert!(records.take(Path::new("/b.sv"), 7).is_none(), "another path"); + assert!(records.take(Path::new("/a.sv"), 7).is_some()); + assert!(parse("0000000000000007\tx").is_none(), "no checksum"); + assert!(parse("7\tx\t0000000000000000").is_none(), "a hash of the wrong width"); +} diff --git a/crates/lucisv_mcp/src/main.rs b/crates/lucisv_mcp/src/main.rs index 72edf75..98fc724 100644 --- a/crates/lucisv_mcp/src/main.rs +++ b/crates/lucisv_mcp/src/main.rs @@ -8,6 +8,7 @@ //! `docs/features/mcp-transport/README.md`. mod apply; +mod cache; mod project; mod render; mod resources; @@ -31,7 +32,8 @@ pub struct Options { pub roots: Vec, /// `--filelist FILE`: overrides the configured `filelist`. pub filelist: Option, - /// `--index-cache DIR`: accepted and stored; read from M6 on. + /// `--index-cache DIR`: the language server's index cache directory, + /// read at startup; this server's own store is written there on exit. pub index_cache: Option, /// `--verbose`: per-call timing lines on stderr. pub verbose: bool, diff --git a/crates/lucisv_mcp/src/project/mod.rs b/crates/lucisv_mcp/src/project/mod.rs index f62c144..adea8c6 100644 --- a/crates/lucisv_mcp/src/project/mod.rs +++ b/crates/lucisv_mcp/src/project/mod.rs @@ -13,6 +13,8 @@ use std::time::{Duration, Instant}; use lucisv_core::config::{Discovery, FileConfig}; use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex}; +use crate::cache::{self, Records, Reuse}; + pub use analysis::Analysis; pub use files::Stamp; @@ -54,6 +56,10 @@ pub struct Project { /// Whether the current call has already walked the roots — the open, a /// stale or forced walk in `refresh`, or a miss's retry. walked_in_call: bool, + /// `--index-cache DIR`: where the stores are read from and ours written. + cache_dir: Option, + /// How many files the startup took from a store instead of parsing. + reuse: Reuse, } /// The canonical form of every `--root`, the current directory when none @@ -77,9 +83,21 @@ pub fn canonical_roots(roots: &[PathBuf]) -> Result, String> { } impl Project { - /// Discover the files under `roots` (already canonical) and index them. - /// Parses every file, so it runs on the stack-sized thread. + /// [`Project::open_cached`] without a cache directory — the tests' open. + #[cfg(test)] pub fn open(roots: Vec, filelist: Option) -> Project { + Project::open_cached(roots, filelist, None) + } + + /// Discover the files under `roots` (already canonical) and index them, + /// taking from the index caches in `cache_dir` the facts of every file + /// whose exact bytes a record was read from (PLAN §6) and parsing the + /// rest — on the stack-sized thread. + pub fn open_cached( + roots: Vec, + filelist: Option, + cache_dir: Option, + ) -> Project { let started = Instant::now(); let mut discovery = Discovery::new(true); let (config, config_problem) = match roots.first().map(|r| discovery.for_dir(r)) { @@ -88,38 +106,50 @@ impl Project { None => (FileConfig::default(), None), }; let walk = discover(&roots, filelist.as_deref()); - let mut builder = IndexBuilder::new(); - let mut files = BTreeMap::new(); - let mut unreadable = Vec::new(); - for path in &walk.files { - match read_source(path) { - Ok((text, stamp)) => { - builder.add_file(path.clone(), &text); - files.insert(path.clone(), stamp); - } - Err(problem) => { - unreadable.push((path.clone(), problem.to_string())); - } - } - } + let mut records = cache_dir.as_deref().map(Records::load).unwrap_or_default(); + let loaded = load(&walk.files, &mut records); + // The merge is part of the build: finished before the clock is read. + let index = loaded.builder.finish(); let now = Instant::now(); Project { roots, filelist_arg: filelist, config, config_problem, - files, - index: builder.finish(), + files: loaded.files, + index, analyses: Analyses::default(), walk, walked_at: now, updated_at: now, build: now - started, - unreadable, + unreadable: loaded.unreadable, walked_in_call: true, + cache_dir, + reuse: loaded.reuse, } } + /// Write the project's own index cache (`--index-cache DIR/index-cache-mcp`): + /// one record per indexed file, the facts the index holds under the hash + /// of the bytes they were read from. `Ok(None)` without a cache directory. + pub fn save_cache(&self) -> std::io::Result> { + let Some(dir) = self.cache_dir.as_deref() else { return Ok(None) }; + let records: Vec<(u64, &FileFacts)> = self + .files + .iter() + .filter_map(|(path, stamp)| Some((stamp.hash, self.index.facts_for(path)?))) + .collect(); + let written = cache::write_own(dir, &records)?; + Ok(Some((dir.join(cache::OWN_STORE), written))) + } + + /// How many files the startup took from the index caches, when a cache + /// directory was given. + pub fn reuse(&self) -> Option { + self.cache_dir.as_ref().map(|_| self.reuse) + } + /// Bring the index up to the disk: stat every file, re-read the ones /// that moved, drop the ones that went, and — when a file went, when /// `force_walk`, or when the last walk is stale — walk again for new @@ -307,6 +337,43 @@ impl Project { } } +/// What reading the discovered files at startup produced. +struct Loaded { + builder: IndexBuilder, + files: BTreeMap, + unreadable: Vec<(PathBuf, String)>, + reuse: Reuse, +} + +/// Read and stamp every file; add its facts from a store record when one was +/// read off exactly these bytes, else parse it. +fn load(paths: &[PathBuf], records: &mut Records) -> Loaded { + let mut loaded = Loaded { + builder: IndexBuilder::new(), + files: BTreeMap::new(), + unreadable: Vec::new(), + reuse: Reuse::default(), + }; + for path in paths { + let (text, stamp) = match read_source(path) { + Ok(read) => read, + Err(problem) => { + loaded.unreadable.push((path.clone(), problem.to_string())); + continue; + } + }; + match records.take(path, stamp.hash) { + Some((facts, source)) => { + loaded.reuse.count(source); + loaded.builder.add_facts(facts); + } + None => loaded.builder.add_file(path.clone(), &text), + } + loaded.files.insert(path.clone(), stamp); + } + loaded +} + /// [`Project::relative`], for a caller that holds the roots but no project. fn relative_to(roots: &[PathBuf], path: &Path) -> String { let shown = roots.iter().find_map(|root| path.strip_prefix(root).ok()).unwrap_or(path); diff --git a/crates/lucisv_mcp/src/rpc.rs b/crates/lucisv_mcp/src/rpc.rs index 267a601..290f25c 100644 --- a/crates/lucisv_mcp/src/rpc.rs +++ b/crates/lucisv_mcp/src/rpc.rs @@ -36,7 +36,7 @@ const NOT_INITIALIZED: i64 = -32002; const RESOURCE_NOT_FOUND: i64 = -32002; /// What the agent is told once, at `initialize`. -const INSTRUCTIONS: &str = "lucisv-mcp answers questions about the Verilog/SystemVerilog design under its roots, read from the files on disk (never from unsaved editor buffers). Prefer unit_interface for a module's parameters and ports, outline for what a file declares, and read_item for one module, function or always block over reading whole files; list_units and search_symbols find where things are declared. Paths in answers are relative to the root; lines and columns are 1-based."; +const INSTRUCTIONS: &str = "lucisv-mcp reads and edits the Verilog/SystemVerilog design under its roots, from the files on disk (never unsaved editor buffers). Read less: unit_interface gives a module's parameters and ports, outline what a file declares, read_item one module, function or always block; list_units, search_symbols, definition, references and hierarchy find the rest. Every edit is verified before anything is written, all-or-nothing, straight to disk; pass dry_run: true to see the diff first. One item: replace_item, insert_item, delete_item. Design-wide: rename, add_port, remove_port and the other refactorings update every file that needs it; format and fix_lint reformat and fix. Run diagnostics after an edit to check it. Paths are relative to a root; lines are 1-based, columns 1-based bytes."; /// A JSON-RPC error object. #[derive(Debug, Serialize)] @@ -136,7 +136,10 @@ pub fn serve(options: Options) -> Result<(), String> { let mut server = Server { options, version: None, project: None }; loop { let reply = match transport.read_line().map_err(|e| format!("reading stdin: {e}"))? { - Line::Eof => return Ok(()), + Line::Eof => { + server.finish(); + return Ok(()); + } Line::NotUtf8 => { Some(response(&Value::Null, Err(fault(PARSE_ERROR, "the line is not UTF-8")))) } @@ -267,6 +270,20 @@ impl Server { resource.read(uri, project).map_err(|why| not_found(&format!(" ({why})"))) } + /// The client closed stdin: write the project's own index cache, when + /// there is a project and a cache directory. A failure is one line on + /// stderr; the session ends either way. + fn finish(&self) { + let Some(project) = &self.project else { return }; + match project.save_cache() { + Ok(Some((store, written))) if self.options.verbose => { + eprintln!("lucisv-mcp: wrote {written} records to {}", store.display()); + } + Ok(_) => {} + Err(problem) => eprintln!("lucisv-mcp: cannot write the index cache: {problem}"), + } + } + /// The project, built on first use and brought up to the disk on every /// later one. fn project(&mut self, rewalk: bool) -> &mut Project { @@ -285,9 +302,20 @@ impl Server { /// Discover and index the project, saying on stderr how long it took. fn open_project(options: &Options) -> Project { - let project = Project::open(options.roots.clone(), options.filelist.clone()); + let project = Project::open_cached( + options.roots.clone(), + options.filelist.clone(), + options.index_cache.clone(), + ); let (build, _) = project.timing(); - eprintln!("lucisv-mcp: indexed {} files in {} ms", project.files().count(), build.as_millis()); + let reused = match project.reuse() { + Some(reuse) => { + format!(" ({} from the editor's cache, {} from its own)", reuse.editor, reuse.own) + } + None => String::new(), + }; + let (files, ms) = (project.files().count(), build.as_millis()); + eprintln!("lucisv-mcp: indexed {files} files in {ms} ms{reused}"); project } diff --git a/crates/lucisv_mcp/src/tools/item.rs b/crates/lucisv_mcp/src/tools/item.rs index d2931e4..a840597 100644 --- a/crates/lucisv_mcp/src/tools/item.rs +++ b/crates/lucisv_mcp/src/tools/item.rs @@ -102,7 +102,7 @@ pub const INSERT_ITEM: Tool = Tool { pub const DELETE_ITEM: Tool = Tool { name: "delete_item", title: "Delete one item", - description: "Delete one item (read_item's selector) and its own leading comments (up to a blank line), verified before anything is written. Refused while a name it declares is referenced anywhere in the project — a `.*` that binds it and a spelling inside a macro count — (the first sites are listed) unless `force: true`, and inside a `// lucisv: off` fence. A declaration of several names goes whole. A second identical call is refused: no such item. `dry_run` returns the diff.", + description: "Delete one item (read_item's selector) and its own leading comments (up to a blank line), verified before anything is written. Refused while a name it declares is referenced anywhere in the project — a `.*` that binds it and a spelling inside a macro count — (the first sites are listed) unless `force: true`, and inside a `// lucisv: off` fence. An item holding a `define/`undef is refused too unless `force` (the macros are named under warnings). A declaration of several names goes whole. A second identical call is refused: no such item. `dry_run` returns the diff.", params: &[ FILE, ITEM, @@ -110,7 +110,7 @@ pub const DELETE_ITEM: Tool = Tool { name: "force", ty: Ty::Bool, required: false, - description: "Delete even though references remain (default false); they are listed under warnings.", + description: "Delete even though references remain or the item holds macro definitions (default false); both are listed under warnings.", }, DRY_RUN, ], @@ -273,10 +273,12 @@ fn delete_item(project: &mut Project, args: &Args) -> Result { let removed = TextRange::new(start, end); let force = args.flag("force", false); let place = refs::Place { item: located.item.span, removed, scope: located.siblings }; - let warnings = refs::check(project, &path, &analysis, &place, force)?; + let mut warnings = refs::check(project, &path, &analysis, &place, force)?; let class = verify::class_of(&located.item.kind); let splice = Splice { start, old_end: end, text: String::new() }; - let outcome = verify::check(&analysis, &splice, Expect::Nothing).map_err(refused(&file))?; + let outcome = + verify::check(&analysis, &splice, Expect::Nothing { force }).map_err(refused(&file))?; + warnings.extend(dropped_macros_warning(&outcome.dropped_macros)); let names = verify::owned_names(&analysis, located.item.span); let lines = analysis.line_span(start, end); let note = @@ -286,6 +288,17 @@ fn delete_item(project: &mut Project, args: &Args) -> Result { apply::run(project, plan, dry_run) } +/// What a forced deletion says about the macro definitions it removed +/// (the M4 review's ruling on rule 6): nothing when it removed none. +fn dropped_macros_warning(names: &[String]) -> Option { + (!names.is_empty()).then(|| { + format!( + "deleted macro definitions: {} — code after the item that used them will change meaning", + names.join(", ") + ) + }) +} + /// Whether the item's own leading comments hold a fence line: deleting one /// would move a fence's edge. fn fence_comment(item: &Item) -> bool { diff --git a/crates/lucisv_mcp/src/tools/item/verify.rs b/crates/lucisv_mcp/src/tools/item/verify.rs index 2d3a8cf..6bb3437 100644 --- a/crates/lucisv_mcp/src/tools/item/verify.rs +++ b/crates/lucisv_mcp/src/tools/item/verify.rs @@ -25,7 +25,9 @@ //! bytes and in the new; //! 6. the `` `define``/`` `undef`` entries inside the region are the same //! before and after — except inside a directive or macro item at the -//! region's level, where editing the definition is the point; +//! region's level, where editing the definition is the point, and for a +//! forced deletion, which removes them and names them +//! ([`Outcome::dropped_macros`]); //! 7. the region holds the same fence markers before and after //! ([`lexical`]). //! @@ -55,8 +57,9 @@ pub enum Expect { One(&'static str), /// One item or more (`insert_item`). Some, - /// Nothing (`delete_item`). - Nothing, + /// Nothing (`delete_item`); `force` lets rule 6 pass over the macro + /// definitions the deleted item held (they are named instead). + Nothing { force: bool }, } /// A splice that passed: the new file, its analysis, and the items the @@ -65,6 +68,9 @@ pub struct Outcome { pub text: String, pub analysis: Analysis, pub items: Vec<(&'static str, TextRange)>, + /// The macro definitions a forced deletion removed, as the warning + /// names them (`W`, `X (undef)`); empty for every other edit. + pub dropped_macros: Vec, } /// Check `splice` against `old` (see the module comment); the refusal is one @@ -92,12 +98,21 @@ pub fn check(old: &Analysis, splice: &Splice, expect: Expect) -> Result Vec::new(), + Err(_) if matches!(expect, Expect::Nothing { force: true }) => { + dropped(old, region, &before) + } + Err(why) if matches!(expect, Expect::Nothing { .. }) => { + return Err(format!("{why}, or pass `force: true` to delete it anyway")) + } + Err(why) => return Err(why), + }; no_new_duplicates(old, &analysis)?; balanced(&old.tokens, splice.start, splice.old_end, "the old item")?; balanced(&analysis.tokens, splice.start, new_end, "the new text")?; lexical::same_fences(old, &analysis, region)?; - Ok(Outcome { text, analysis, items }) + Ok(Outcome { text, analysis, items, dropped_macros }) } /// The old text with the splice applied; a range off a character boundary @@ -234,7 +249,9 @@ fn expected(items: &[(&'static str, TextRange)], expect: &Expect) -> Result<(), many.len() )), (Expect::Some, []) => Err("the text holds no item".into()), - (Expect::Nothing, [_, ..]) => Err("the deletion would leave an item behind".into()), + (Expect::Nothing { .. }, [_, ..]) => { + Err("the deletion would leave an item behind".into()) + } _ => Ok(()), } } @@ -367,6 +384,22 @@ fn same_macros( )) } +/// The macro definitions a deletion of the region removes, each name once, +/// in source order: `W` for a `` `define``, `X (undef)` for an `` `undef``. +fn dropped(old: &Analysis, region: Region, before: &Split) -> Vec { + let mut names: Vec = Vec::new(); + for (kind, name, _, _) in definitions(old, region.start, region.old_end, before) { + let shown = match kind { + DefineKind::Undef => format!("{name} (undef)"), + _ => name, + }; + if !names.contains(&shown) { + names.push(shown); + } + } + names +} + /// A define entry as compared: kind, name, parameters, body. type Definition = (DefineKind, String, Option>, String); diff --git a/crates/lucisv_mcp/tests/cache.rs b/crates/lucisv_mcp/tests/cache.rs new file mode 100644 index 0000000..61ae197 --- /dev/null +++ b/crates/lucisv_mcp/tests/cache.rs @@ -0,0 +1,257 @@ +//! The index caches over the wire (TODO-MCP M6, PLAN §6): the language +//! server's `index-cache` is read and never written — its bytes are hashed +//! before and after a whole session that indexes, answers and edits — every +//! record that is not exactly right is skipped, a missing or unwritable +//! cache directory costs a cold start and nothing else, and the server's own +//! `index-cache-mcp` is written on exit and read on the next start. + +use std::fs; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use lucisv_core::cache::content_hash; +use serde_json::{json, Value}; +use vlog_semantic::{FileFacts, FACTS_FORMAT}; + +static NEXT_DIR: AtomicUsize = AtomicUsize::new(0); + +/// The design fixture's file count. +const FILES: usize = 7; + +/// A fresh copy of `tests/fixtures/design` under `/src`, and `/cache` +/// for the stores; removed on drop. +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Scratch { + let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst); + let dir = + std::env::temp_dir().join(format!("lucisv-mcp-cache-{}-{unique}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/design"); + copy_tree(&source, &dir.join("src")); + Scratch(fs::canonicalize(dir).unwrap()) + } + + fn src(&self) -> PathBuf { + self.0.join("src") + } + + fn cache(&self) -> PathBuf { + self.0.join("cache") + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn copy_tree(from: &Path, to: &Path) { + fs::create_dir_all(to).unwrap(); + for entry in fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_tree(&entry.path(), &target); + } else { + fs::copy(entry.path(), target).unwrap(); + } + } +} + +/// Every file under `dir`, sorted. +fn files(dir: &Path) -> Vec { + let mut out = Vec::new(); + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + out.extend(files(&path)); + } else { + out.push(path); + } + } + out.sort(); + out +} + +/// The language server's header for this build. +fn header(version: &str) -> String { + format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{version}") +} + +/// One record in the language server's format. +fn record(path: &Path) -> String { + let bytes = fs::read(path).unwrap(); + let facts = FileFacts::of(path.to_path_buf(), std::str::from_utf8(&bytes).unwrap()); + let encoded = facts.encode().unwrap(); + let checksum = content_hash(encoded.as_bytes()); + format!("{:016x}\t{encoded}\t{checksum:016x}", content_hash(&bytes)) +} + +/// A store the way the language server writes one, over every source file. +fn editor_store(scratch: &Scratch, version: &str) -> Vec { + let mut lines = vec![header(version)]; + lines.extend(files(&scratch.src()).iter().map(|path| record(path))); + lines +} + +/// One server over the scratch design with `--index-cache`. +struct Session { + child: Child, + next_id: i64, + stdout: std::io::BufReader, +} + +impl Session { + fn start(scratch: &Scratch) -> Session { + let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp")) + .arg("--root") + .arg(scratch.src()) + .arg("--index-cache") + .arg(scratch.cache()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let stdout = std::io::BufReader::new(child.stdout.take().unwrap()); + let mut session = Session { child, next_id: 0, stdout }; + session.request("initialize", json!({"protocolVersion": "2025-06-18"})); + session + } + + fn request(&mut self, method: &str, params: Value) -> Value { + use std::io::BufRead; + self.next_id += 1; + let line = + json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params}); + let stdin = self.child.stdin.as_mut().unwrap(); + writeln!(stdin, "{line}").unwrap(); + stdin.flush().unwrap(); + let mut answer = String::new(); + self.stdout.read_line(&mut answer).unwrap(); + serde_json::from_str(&answer).unwrap() + } + + /// A tool call that must succeed: its text. + fn text(&mut self, tool: &str, arguments: Value) -> String { + let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments})); + assert_eq!(reply["result"]["isError"], false, "{tool}: {reply}"); + reply["result"]["content"][0]["text"].as_str().unwrap().to_string() + } + + /// Close stdin, as a host does, and return everything said on stderr. + fn end(mut self) -> String { + drop(self.child.stdin.take()); + let status = self.child.wait().unwrap(); + assert!(status.success(), "{status}"); + let mut stderr = String::new(); + self.child.stderr.take().unwrap().read_to_string(&mut stderr).unwrap(); + stderr + } +} + +/// A session that indexes, answers, edits and ends; its stderr. +fn whole_session(scratch: &Scratch) -> String { + let mut session = Session::start(scratch); + assert!(session.text("project_overview", json!({})).contains("files: 7 indexed")); + assert!(session.text("unit_interface", json!({"name": "leaf"})).contains("module leaf")); + session.text("format", json!({"file": "rtl/top.sv"})); + // One more call, so the index has absorbed whatever the edit wrote. + session.text("outline", json!({"file": "rtl/top.sv"})); + let stderr = session.end(); + assert!(stderr.contains(&format!("lucisv-mcp: indexed {FILES} files in ")), "{stderr}"); + stderr +} + +/// The startup line's tail: `ms (E from the editor's cache, O from its own)` +/// after `indexed 7 files in`. +fn reused(editor: usize, own: usize) -> String { + format!(" ms ({editor} from the editor's cache, {own} from its own)\n") +} + +fn hash_file(path: &Path) -> u64 { + content_hash(&fs::read(path).unwrap()) +} + +#[test] +fn the_editors_store_is_read_skipping_bad_records_and_never_written() { + let scratch = Scratch::new(); + let mut lines = editor_store(&scratch, env!("CARGO_PKG_VERSION")); + // A record whose hash matches its file but whose facts no longer match + // their checksum: an instance renamed inside it. + let at = lines.iter().position(|line| line.contains("/rtl/top.sv\t")).unwrap(); + let forged = lines[at].replacen("\tu_leaf\t", "\tu_lesf\t", 1); + assert_ne!(forged, lines[at], "the forgery changed the facts"); + lines[at] = forged; + // A torn last record, no newline. + let last = lines.len() - 1; + lines[last] = lines[last][..lines[last].len() / 2].to_string(); + fs::create_dir_all(scratch.cache()).unwrap(); + let store = scratch.cache().join("index-cache"); + fs::write(&store, lines.join("\n")).unwrap(); + let before = (hash_file(&store), fs::metadata(&store).unwrap().modified().unwrap()); + + let stderr = whole_session(&scratch); + assert!(stderr.contains(&reused(FILES - 2, 0)), "{stderr}"); + let after = (hash_file(&store), fs::metadata(&store).unwrap().modified().unwrap()); + assert_eq!(before, after, "the language server's store is byte-identical, untouched"); + let own = fs::read_to_string(scratch.cache().join("index-cache-mcp")).unwrap(); + assert!(own.starts_with(&format!("{}\n", header(env!("CARGO_PKG_VERSION"))))); + assert_eq!(own.lines().count(), 1 + FILES); +} + +#[test] +fn a_store_from_another_version_is_ignored_whole_with_one_line() { + let scratch = Scratch::new(); + fs::create_dir_all(scratch.cache()).unwrap(); + let store = scratch.cache().join("index-cache"); + fs::write(&store, editor_store(&scratch, "0.0.0").join("\n") + "\n").unwrap(); + let before = hash_file(&store); + let stderr = whole_session(&scratch); + assert_eq!(stderr.matches("ignoring the index cache").count(), 1, "{stderr}"); + assert!(stderr.contains(&reused(0, 0)), "{stderr}"); + assert_eq!(hash_file(&store), before); +} + +#[test] +fn a_missing_directory_starts_cold_and_its_own_store_serves_the_next_start() { + let scratch = Scratch::new(); + let stderr = whole_session(&scratch); + assert!(stderr.contains(&reused(0, 0)), "{stderr}"); + assert!(!stderr.contains("ignoring") && !stderr.contains("cannot"), "{stderr}"); + assert!(!scratch.cache().join("index-cache").exists(), "the editor's store is not made"); + assert!(scratch.cache().join("index-cache-mcp").exists()); + + let stderr = whole_session(&scratch); + assert!(stderr.contains(&reused(0, FILES)), "{stderr}"); + + // A file changed since its record: its hash misses, it is parsed, and + // the answer is the new text's. + let leaf = scratch.src().join("rtl/leaf.sv"); + let text = fs::read_to_string(&leaf).unwrap().replace("module leaf", "module leaf2"); + fs::write(&leaf, text).unwrap(); + let mut session = Session::start(&scratch); + let units = session.text("list_units", json!({})); + assert!(units.contains("leaf2"), "{units}"); + let stderr = session.end(); + assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}"); +} + +#[cfg(unix)] +#[test] +fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() { + use std::os::unix::fs::PermissionsExt; + let scratch = Scratch::new(); + fs::create_dir_all(scratch.cache()).unwrap(); + fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o555)).unwrap(); + let stderr = whole_session(&scratch); + fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o755)).unwrap(); + assert!(stderr.contains(&reused(0, 0)), "{stderr}"); + assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}"); + assert!(fs::read_dir(scratch.cache()).unwrap().next().is_none(), "nothing was written"); +} diff --git a/crates/lucisv_mcp/tests/opentitan.rs b/crates/lucisv_mcp/tests/opentitan.rs index 65ed0b6..c06ef2a 100644 --- a/crates/lucisv_mcp/tests/opentitan.rs +++ b/crates/lucisv_mcp/tests/opentitan.rs @@ -7,10 +7,10 @@ //! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p //! lucisv_mcp --test opentitan -- --ignored --nocapture`. -use std::io::{BufRead, BufReader, Write}; +use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; -use std::time::Instant; +use std::time::{Duration, Instant}; use serde_json::{json, Value}; @@ -24,33 +24,55 @@ fn checkout() -> PathBuf { /// One server over the checkout. struct Session { child: Child, - stdin: ChildStdin, + stdin: Option, stdout: BufReader, next_id: i64, } impl Session { fn over(root: &Path) -> Session { - let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp")) - .args(["--root", root.to_str().unwrap()]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .unwrap(); - let stdin = child.stdin.take().unwrap(); + Session::spawn(root, None) + } + + /// A server with `--index-cache cache` when given; its stderr is kept + /// for [`Session::end`] only then (the one line it writes is small). + fn spawn(root: &Path, cache: Option<&Path>) -> Session { + let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp")); + command.args(["--root", root.to_str().unwrap()]); + if let Some(cache) = cache { + command.arg("--index-cache").arg(cache); + } + let stderr = if cache.is_some() { Stdio::piped() } else { Stdio::null() }; + let mut child = + command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(stderr).spawn().unwrap(); + let stdin = child.stdin.take(); let stdout = BufReader::new(child.stdout.take().unwrap()); let mut session = Session { child, stdin, stdout, next_id: 0 }; session.request("initialize", json!({"protocolVersion": "2025-06-18"})); session } + /// Close stdin as a host does; the time the server took to exit (its + /// own store is written then) and what it said on stderr. + fn end(mut self) -> (Duration, String) { + let started = Instant::now(); + drop(self.stdin.take()); + self.child.wait().unwrap(); + let took = started.elapsed(); + let mut stderr = String::new(); + if let Some(mut pipe) = self.child.stderr.take() { + pipe.read_to_string(&mut stderr).unwrap(); + } + (took, stderr) + } + fn request(&mut self, method: &str, params: Value) -> Value { self.next_id += 1; let line = json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params}); - writeln!(self.stdin, "{line}").unwrap(); - self.stdin.flush().unwrap(); + let stdin = self.stdin.as_mut().unwrap(); + writeln!(stdin, "{line}").unwrap(); + stdin.flush().unwrap(); let mut answer = String::new(); self.stdout.read_line(&mut answer).unwrap(); serde_json::from_str(&answer).unwrap() @@ -159,3 +181,80 @@ fn opentitan_navigation_matches_the_language_server() { drop(s); assert_eq!(status(&root), before, "the checkout was only read"); } + +/// The median of some wall times, in milliseconds. +fn median_ms(mut times: Vec) -> f64 { + times.sort(); + times[times.len() / 2].as_secs_f64() * 1000.0 +} + +/// One startup over the checkout with the stores in `cache`: the first +/// call's wall time, the exit's, and the server's `indexed …` line. +fn startup(root: &Path, cache: &Path, label: &str) -> Session { + let mut s = Session::spawn(root, Some(cache)); + let started = Instant::now(); + s.text("project_overview", json!({})); + println!("startup: {label}: first call {} ms", started.elapsed().as_millis()); + s +} + +/// Close a session, printing its exit time and startup line. +fn finish(s: Session, label: &str) { + let (exit, stderr) = s.end(); + let line = stderr.lines().find(|l| l.contains("indexed")).unwrap_or("").to_string(); + println!("startup: {label}: {line}; exit (own store written) {} ms", exit.as_millis()); +} + +/// TODO-MCP M6: startup cold, warm from the editor's store and warm from +/// this server's own; the per-call stat sweep; the whole-set `rename`. The +/// stores live in a scratch directory outside the checkout; the editor's is +/// the own store renamed — the same codec, byte for byte (`src/cache.rs`, +/// pinned against the language server's source by its unit test). +#[test] +#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN)"] +fn opentitan_startup_cold_and_warm_and_the_stat_sweep() { + let root = checkout(); + let before = status(&root); + let cache = std::env::temp_dir().join(format!("lucisv-mcp-ot-cache-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&cache); + + finish(startup(&root, &cache, "cold, no store"), "cold, no store"); + let mut s = startup(&root, &cache, "warm, own store"); + // The stat sweep: a call whose answer is cached after its first run, so + // what is left is the sweep over every file; `tools/list` is the floor. + let outline = json!({"file": "hw/ip/prim/rtl/prim_fifo_sync.sv"}); + s.text("outline", outline.clone()); + let mut swept = Vec::new(); + let mut floor = Vec::new(); + for _ in 0..21 { + let started = Instant::now(); + s.request("tools/list", json!({})); + floor.push(started.elapsed()); + let started = Instant::now(); + s.text("outline", outline.clone()); + swept.push(started.elapsed()); + } + println!( + "sweep: outline median {:.2} ms, tools/list median {:.2} ms", + median_ms(swept), + median_ms(floor) + ); + let rename = json!({"file": "hw/ip/aes/rtl/aes_cipher_core.sv", "line": 123, "name": "op_i", "new_name": "cipher_op_i", "dry_run": true}); + for pass in ["first", "second"] { + let started = Instant::now(); + let text = s.text("rename", rename.clone()); + assert!(text.contains("(dry run: nothing written)"), "{text}"); + println!("rename: op_i dry run, {pass} call {} ms", started.elapsed().as_millis()); + } + finish(s, "warm, own store"); + + let own = cache.join("index-cache-mcp"); + std::fs::rename(&own, cache.join("index-cache")).unwrap(); + let editor = std::fs::read(cache.join("index-cache")).unwrap(); + let s = startup(&root, &cache, "warm, editor's store"); + finish(s, "warm, editor's store"); + assert_eq!(std::fs::read(cache.join("index-cache")).unwrap(), editor, "read, never written"); + println!("store: {} bytes", editor.len()); + let _ = std::fs::remove_dir_all(&cache); + assert_eq!(status(&root), before, "the checkout was only read"); +} diff --git a/crates/lucisv_mcp/tests/qa_m4.rs b/crates/lucisv_mcp/tests/qa_m4.rs index 7a95fa6..7d6ea9d 100644 --- a/crates/lucisv_mcp/tests/qa_m4.rs +++ b/crates/lucisv_mcp/tests/qa_m4.rs @@ -1264,12 +1264,14 @@ fn qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always() { let undef = "always_comb begin\n`undef W\n w = 1'b1;\n end"; let args = json!({"file": "rtl/d.sv", "item": "always@6", "text": undef}); refused(&tree, &mut server, "replace_item", args, "rule 6"); - // Deleting the module deletes its nested `define LOCAL: refused, even - // forced (a define item is not selectable, so no tool removes one). - for force in [false, true] { - let args = json!({"file": "rtl/d.sv", "item": "d", "force": force}); - refused(&tree, &mut server, "delete_item", args, "rule 6"); - } + // Deleting the module deletes its nested `define LOCAL: refused unless + // forced. (Amended in M6 by the M4 review's ruling — `force` relaxes rule + // 6 on delete, with a warning; the forced delete is in `tests/wire.rs`.) + let args = json!({"file": "rtl/d.sv", "item": "d", "force": false}); + refused(&tree, &mut server, "delete_item", args, "rule 6"); + let args = json!({"file": "rtl/d.sv", "item": "d", "force": true, "dry_run": true}); + let text = accepted(&mut server, "delete_item", args); + assert!(text.contains("deleted macro definitions: LOCAL"), "{text}"); let args = json!({"file": "rtl/d.sv", "item": "LOCAL"}); refused(&tree, &mut server, "delete_item", args, "no declaration matches `LOCAL`"); // A directive item at the region's own level is the exemption. diff --git a/crates/lucisv_mcp/tests/qa_m6.rs b/crates/lucisv_mcp/tests/qa_m6.rs new file mode 100644 index 0000000..a9af8ba --- /dev/null +++ b/crates/lucisv_mcp/tests/qa_m6.rs @@ -0,0 +1,711 @@ +//! QA attacks on lane M6 (the index caches and the rule-6 ruling), +//! 2026-09-23. +//! +//! Every test spawns the real binary over a scratch copy of the `design` +//! fixture with `--index-cache` pointing at a scratch directory, as a host +//! would. The wrong-record hunt comes first: a record may only ever stand in +//! for the parse of exactly the bytes it was read from, so every store below +//! that is not exactly right must cost a parse — never an answer — and the +//! language server's store must be left byte-identical. +//! +//! A test that pins a QA finding asserts the *correct* behaviour and is +//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are +//! numbered as in the QA log of `docs/features/mcp-cache-and-census/README.md`. + +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdout, Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, SystemTime}; + +use lucisv_core::cache::content_hash; +use serde_json::{json, Value}; +use vlog_semantic::{FileFacts, FACTS_FORMAT}; + +static NEXT_DIR: AtomicUsize = AtomicUsize::new(0); + +/// The design fixture's file count. +const FILES: usize = 7; + +const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// A fresh copy of `tests/fixtures/design` under `/src`, and `/cache` +/// (not created) for the stores; removed on drop. +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Scratch { + let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst); + let dir = + std::env::temp_dir().join(format!("lucisv-mcp-qa-m6-{}-{unique}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/design"); + copy_tree(&source, &dir.join("src")); + Scratch(fs::canonicalize(dir).unwrap()) + } + + fn src(&self) -> PathBuf { + self.0.join("src") + } + + fn file(&self, rel: &str) -> PathBuf { + self.src().join(rel) + } + + fn cache(&self) -> PathBuf { + self.0.join("cache") + } + + fn editor_store(&self) -> PathBuf { + self.cache().join("index-cache") + } + + fn own_store(&self) -> PathBuf { + self.cache().join("index-cache-mcp") + } + + /// Write the language server's store from `lines`, one per line, with a + /// final newline. + fn write_editor_store(&self, lines: &[String]) { + fs::create_dir_all(self.cache()).unwrap(); + fs::write(self.editor_store(), lines.join("\n") + "\n").unwrap(); + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn copy_tree(from: &Path, to: &Path) { + fs::create_dir_all(to).unwrap(); + for entry in fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_tree(&entry.path(), &target); + } else { + fs::copy(entry.path(), target).unwrap(); + } + } +} + +/// Every file under `dir`, sorted. +fn files(dir: &Path) -> Vec { + let mut out = Vec::new(); + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + out.extend(files(&path)); + } else { + out.push(path); + } + } + out.sort(); + out +} + +fn header() -> String { + format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}") +} + +/// The encoded facts `path` would have if its bytes were `text`. +fn facts_of(path: &Path, text: &str) -> String { + FileFacts::of(path.to_path_buf(), text).encode().unwrap() +} + +/// One record line with a *valid* checksum: `content` as the hash field, +/// `facts` as the record — whatever they describe. +fn line(content: u64, facts: &str) -> String { + format!("{content:016x}\t{facts}\t{:016x}", content_hash(facts.as_bytes())) +} + +/// The honest record of `path` as it is on disk. +fn record(path: &Path) -> String { + let bytes = fs::read(path).unwrap(); + line(content_hash(&bytes), &facts_of(path, std::str::from_utf8(&bytes).unwrap())) +} + +/// The honest store over every source file. +fn honest_store(scratch: &Scratch) -> Vec { + let mut lines = vec![header()]; + lines.extend(files(&scratch.src()).iter().map(|path| record(path))); + lines +} + +/// One server over the scratch design. +struct Session { + child: Child, + next_id: i64, + stdout: BufReader, +} + +impl Session { + /// With `--index-cache cache` when given. + fn start(scratch: &Scratch, cache: Option<&Path>) -> Session { + let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp")); + command.arg("--root").arg(scratch.src()); + if let Some(cache) = cache { + command.arg("--index-cache").arg(cache); + } + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let stdout = BufReader::new(child.stdout.take().unwrap()); + let mut session = Session { child, next_id: 0, stdout }; + session.request("initialize", json!({"protocolVersion": "2025-06-18"})); + session + } + + /// The usual shape: `--index-cache /cache`. + fn cached(scratch: &Scratch) -> Session { + Session::start(scratch, Some(&scratch.cache())) + } + + fn request(&mut self, method: &str, params: Value) -> Value { + self.next_id += 1; + let line = + json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params}); + let stdin = self.child.stdin.as_mut().unwrap(); + writeln!(stdin, "{line}").unwrap(); + stdin.flush().unwrap(); + let mut answer = String::new(); + self.stdout.read_line(&mut answer).unwrap(); + serde_json::from_str(&answer).unwrap() + } + + /// A tool call's whole result (success or refusal). + fn call(&mut self, tool: &str, arguments: Value) -> Value { + self.request("tools/call", json!({"name": tool, "arguments": arguments}))["result"].clone() + } + + /// A tool call that must succeed: its text. + fn text(&mut self, tool: &str, arguments: Value) -> String { + let result = self.call(tool, arguments); + assert_eq!(result["isError"], false, "{tool}: {result}"); + result["content"][0]["text"].as_str().unwrap().to_string() + } + + /// Close stdin, as a host does; everything said on stderr. + fn end(mut self) -> String { + drop(self.child.stdin.take()); + let status = self.child.wait().unwrap(); + assert!(status.success(), "{status}"); + let mut stderr = String::new(); + self.child.stderr.take().unwrap().read_to_string(&mut stderr).unwrap(); + stderr + } +} + +/// The startup line's tail for `E` editor and `O` own hits. +fn reused(editor: usize, own: usize) -> String { + format!(" ms ({editor} from the editor's cache, {own} from its own)\n") +} + +/// A session that asks what the tests below check the index with; its +/// answers and stderr. +fn probe(scratch: &Scratch, cache: Option<&Path>) -> (Vec, String) { + let mut session = Session::start(scratch, cache); + let answers = [ + ("list_units", json!({})), + ("unit_interface", json!({"name": "leaf"})), + ("unit_interface", json!({"name": "top"})), + ("outline", json!({"file": "rtl/top.sv"})), + ("outline", json!({"file": "rtl/leaf.sv"})), + ("search_symbols", json!({"query": "word"})), + ("references", json!({"name": "leaf"})), + ("hierarchy", json!({"root": "top"})), + ("defines", json!({})), + ] + .into_iter() + .map(|(tool, args)| session.text(tool, args)) + .collect(); + (answers, session.end()) +} + +fn hash_file(path: &Path) -> u64 { + content_hash(&fs::read(path).unwrap()) +} + +/// Everything the store's owner could notice changed: bytes, mtime, mode. +#[cfg(unix)] +fn fingerprint(path: &Path) -> (u64, SystemTime, u32) { + use std::os::unix::fs::PermissionsExt; + let meta = fs::metadata(path).unwrap(); + (hash_file(path), meta.modified().unwrap(), meta.permissions().mode()) +} + +/// Temporary files left in `dir`. +fn temp_files(dir: &Path) -> Vec { + fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".tmp")) + .collect() +} + +// --------------------------------------------------------------------------- +// 1. The wrong-record hunt. +// --------------------------------------------------------------------------- + +/// Two records' facts swapped, each checksum recomputed so every line is +/// valid: the record under `leaf.sv`'s hash now describes `top.sv` and the +/// other way round. The store is keyed by the path *inside* the facts, so +/// each lands under (other path, this hash) and matches no file: both are +/// parsed, and the answers are the cold ones. +#[test] +fn qa_swapped_records_with_valid_checksums_are_never_served() { + let scratch = Scratch::new(); + let (cold, _) = probe(&scratch, None); + let (leaf, top) = (scratch.file("rtl/leaf.sv"), scratch.file("rtl/top.sv")); + let text = |path: &Path| fs::read_to_string(path).unwrap(); + let mut lines = vec![header()]; + for path in files(&scratch.src()) { + if path != leaf && path != top { + lines.push(record(&path)); + } + } + lines.push(line(hash_file(&leaf), &facts_of(&top, &text(&top)))); + lines.push(line(hash_file(&top), &facts_of(&leaf, &text(&leaf)))); + scratch.write_editor_store(&lines); + let (warm, stderr) = probe(&scratch, Some(&scratch.cache())); + assert!(stderr.contains(&reused(FILES - 2, 0)), "{stderr}"); + assert_eq!(warm, cold, "the answers are a cold start's"); +} + +/// Records for a file that no longer exists and for one outside every root +/// (it exists, beside the root): neither module is indexed, and neither +/// record survives into the store this server writes. +#[test] +fn qa_records_for_gone_files_or_outside_the_roots_are_not_indexed_nor_kept() { + let scratch = Scratch::new(); + let outside = scratch.0.join("outside.sv"); + fs::write(&outside, "module outside_root; endmodule\n").unwrap(); + let ghost = scratch.file("rtl/ghost.sv"); + let ghost_text = "module ghost_unit; endmodule\n"; + let mut lines = honest_store(&scratch); + lines.push(record(&outside)); + lines.push(line(content_hash(ghost_text.as_bytes()), &facts_of(&ghost, ghost_text))); + scratch.write_editor_store(&lines); + + let mut session = Session::cached(&scratch); + let units = session.text("list_units", json!({})); + assert!(!units.contains("outside_root") && !units.contains("ghost_unit"), "{units}"); + let stderr = session.end(); + assert!(stderr.contains(&reused(FILES, 0)), "{stderr}"); + let own = fs::read_to_string(scratch.own_store()).unwrap(); + assert_eq!(own.lines().count(), 1 + FILES, "one record per indexed file"); + assert!(!own.contains("outside.sv") && !own.contains("ghost.sv"), "{own}"); +} + +/// The language server appends: one path may have a record for an older +/// version of the file and one for the current. Keyed by (path, hash), both +/// are held, and the one whose hash is the file's bytes is served — here the +/// *older* one, after the file was put back. Two records for one (path, hash) +/// with different facts: the later line wins, as in the language server +/// (`IndexCache::open`); with the honest record last, the answer is right. +#[test] +fn qa_several_records_for_one_path_serve_only_the_bytes_on_disk() { + let scratch = Scratch::new(); + let leaf = scratch.file("rtl/leaf.sv"); + let original = fs::read_to_string(&leaf).unwrap(); + let edited = original.replace("module leaf", "module leaf_v2"); + let mut lines = honest_store(&scratch); + // A record for the edited version (not on disk), then a checksum-valid + // record under the current hash describing the edited text, then the + // honest one again: the last line for (leaf.sv, hash) wins. + lines.push(line(content_hash(edited.as_bytes()), &facts_of(&leaf, &edited))); + lines.push(line(content_hash(original.as_bytes()), &facts_of(&leaf, &edited))); + lines.push(record(&leaf)); + scratch.write_editor_store(&lines); + let mut session = Session::cached(&scratch); + let units = session.text("list_units", json!({})); + assert!(units.contains("leaf") && !units.contains("leaf_v2"), "{units}"); + session.end(); + + // Now the edited version is on disk: its own record serves it. + fs::write(&leaf, &edited).unwrap(); + fs::remove_file(scratch.own_store()).unwrap(); + let mut session = Session::cached(&scratch); + let units = session.text("list_units", json!({})); + assert!(units.contains("leaf_v2"), "{units}"); + let stderr = session.end(); + assert!(stderr.contains(&reused(FILES, 0)), "{stderr}"); +} + +/// A store whose lines end `\r\n` (an editor or a checkout rewrote it): the +/// `\r` is stripped the way `str::lines` and the language server strip it, +/// the checksums still hold over the facts, and the answers are cold's. +#[test] +fn qa_a_crlf_store_is_read_as_the_language_server_reads_it() { + let scratch = Scratch::new(); + let (cold, _) = probe(&scratch, None); + fs::create_dir_all(scratch.cache()).unwrap(); + fs::write(scratch.editor_store(), honest_store(&scratch).join("\r\n") + "\r\n").unwrap(); + let before = hash_file(&scratch.editor_store()); + let (warm, stderr) = probe(&scratch, Some(&scratch.cache())); + assert!(stderr.contains(&reused(FILES, 0)), "{stderr}"); + assert_eq!(warm, cold); + assert_eq!(hash_file(&scratch.editor_store()), before); +} + +/// Headers one step away from this build's: each store is ignored whole with +/// exactly one stderr line, the index is cold, the file byte-identical. +#[test] +fn qa_header_near_misses_are_ignored_whole_and_left_byte_identical() { + let (major_minor, patch) = VERSION.rsplit_once('.').unwrap(); + let next_patch = format!("{major_minor}.{}", patch.parse::().unwrap() + 1); + let headers = [ + format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{next_patch}"), + format!("lucisv-index-cache\t2\t{}\t{VERSION}", FACTS_FORMAT + 1), + format!("lucisv-index-cache\t2\t{}\t{VERSION}", FACTS_FORMAT - 1), + format!("lucisv-index-cache\t1\t{FACTS_FORMAT}\t{VERSION}"), + format!("lucisv-index-cache\t3\t{FACTS_FORMAT}\t{VERSION}"), + format!("{} ", header()), + format!("\u{feff}{}", header()), + format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}\textra"), + ]; + for first in headers { + let scratch = Scratch::new(); + let mut lines = honest_store(&scratch); + lines[0] = first.clone(); + scratch.write_editor_store(&lines); + let before = hash_file(&scratch.editor_store()); + let mut session = Session::cached(&scratch); + assert!(session.text("list_units", json!({})).contains("leaf")); + let stderr = session.end(); + assert!(stderr.contains(&reused(0, 0)), "{first:?}: {stderr}"); + assert_eq!(stderr.matches("ignoring the index cache").count(), 1, "{first:?}: {stderr}"); + assert_eq!(hash_file(&scratch.editor_store()), before, "{first:?}"); + } +} + +// --------------------------------------------------------------------------- +// 2. The read-only promise and the own store's writes. +// --------------------------------------------------------------------------- + +/// An empty store and a header-only store are silent cold starts; so is a +/// directory where the editor's store would be. +#[test] +fn qa_empty_stores_and_a_directory_named_index_cache_are_silent_cold_starts() { + for shape in ["empty", "header only", "directory"] { + let scratch = Scratch::new(); + fs::create_dir_all(scratch.cache()).unwrap(); + match shape { + "empty" => fs::write(scratch.editor_store(), "").unwrap(), + "header only" => fs::write(scratch.editor_store(), header() + "\n").unwrap(), + _ => fs::create_dir(scratch.editor_store()).unwrap(), + } + let mut session = Session::cached(&scratch); + assert!(session.text("list_units", json!({})).contains("leaf")); + let stderr = session.end(); + assert!(stderr.contains(&reused(0, 0)), "{shape}: {stderr}"); + assert_eq!(stderr.lines().count(), 1, "{shape}: only the startup line: {stderr}"); + assert!(scratch.own_store().is_file(), "{shape}"); + } +} + +/// A directory where this server's own store goes: the read is a silent +/// miss, the write fails with one stderr line, no temporary file is left, +/// and the answers were right. +#[test] +fn qa_a_directory_named_index_cache_mcp_costs_one_line_and_leaves_no_temp() { + let scratch = Scratch::new(); + fs::create_dir_all(scratch.own_store()).unwrap(); + let mut session = Session::cached(&scratch); + assert!(session.text("unit_interface", json!({"name": "leaf"})).contains("module leaf")); + let stderr = session.end(); + assert!(stderr.contains(&reused(0, 0)), "{stderr}"); + assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}"); + assert!(scratch.own_store().is_dir(), "the directory is left alone"); + assert!(temp_files(&scratch.cache()).is_empty(), "{:?}", temp_files(&scratch.cache())); +} + +/// `--index-cache` naming a file, not a directory: the stores cannot be read +/// under it (a silent miss), the write fails with one line, and the file is +/// byte-identical. +#[test] +fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() { + let scratch = Scratch::new(); + let file = scratch.0.join("not-a-dir"); + fs::write(&file, "keep me\n").unwrap(); + let mut session = Session::start(&scratch, Some(&file)); + assert!(session.text("list_units", json!({})).contains("leaf")); + let stderr = session.end(); + assert!(stderr.contains(&reused(0, 0)), "{stderr}"); + assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}"); + assert_eq!(fs::read_to_string(&file).unwrap(), "keep me\n"); +} + +/// A cache directory with no permissions at all (mode 000, holding a whole +/// honest editor store): nothing can be read, so the start is cold; the +/// answers are right; the exit says it could not write, once; the store in +/// it is untouched. +#[cfg(unix)] +#[test] +fn qa_a_cache_directory_without_permission_is_a_cold_start_that_answers() { + use std::os::unix::fs::PermissionsExt; + let scratch = Scratch::new(); + let (cold, _) = probe(&scratch, None); + scratch.write_editor_store(&honest_store(&scratch)); + let before = hash_file(&scratch.editor_store()); + fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o000)).unwrap(); + let (answers, stderr) = probe(&scratch, Some(&scratch.cache())); + fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(answers, cold); + assert!(stderr.contains(&reused(0, 0)), "{stderr}"); + assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}"); + assert_eq!(hash_file(&scratch.editor_store()), before); + assert!(!scratch.own_store().exists()); +} + +/// The editor's store read-only on disk (0444) and in the shape a live +/// language server leaves between compactions — out of path order, a +/// duplicate line, a torn line in the middle, a checksum-failing line: a +/// session that indexes, answers, formats a file and ends leaves its bytes, +/// mtime and mode exactly as they were (nothing "tidies" it), and the good +/// records were all used. +#[cfg(unix)] +#[test] +fn qa_the_editors_store_is_never_tidied_whatever_its_shape() { + use std::os::unix::fs::PermissionsExt; + let scratch = Scratch::new(); + let mut lines = honest_store(&scratch); + lines[1..].reverse(); + lines.push(lines[1].clone()); + let torn = lines[2][..lines[2].len() / 3].to_string(); + lines.insert(2, torn); + let bad = lines[3].replacen("\t", "\tX", 2); + lines.insert(3, bad); + scratch.write_editor_store(&lines); + fs::set_permissions(scratch.editor_store(), fs::Permissions::from_mode(0o444)).unwrap(); + let before = fingerprint(&scratch.editor_store()); + + let mut session = Session::cached(&scratch); + assert!(session.text("project_overview", json!({})).contains("files: 7 indexed")); + session.text("format", json!({"file": "rtl/top.sv"})); + session.text("outline", json!({"file": "rtl/top.sv"})); + let stderr = session.end(); + assert!(stderr.contains(&reused(FILES, 0)), "{stderr}"); + assert_eq!(fingerprint(&scratch.editor_store()), before, "bytes, mtime and mode unchanged"); + assert!(scratch.own_store().is_file()); + fs::set_permissions(scratch.editor_store(), fs::Permissions::from_mode(0o644)).unwrap(); +} + +/// A session killed (SIGKILL) after it answered — the host crashed, it never +/// saw EOF — writes nothing: the previous own store is byte-identical and +/// no temporary file is left, even though the file it would describe changed. +#[test] +fn qa_a_killed_session_leaves_the_previous_own_store_intact() { + let scratch = Scratch::new(); + let session = Session::cached(&scratch); + drop(session.end()); // no call: no project, nothing written + assert!(!scratch.own_store().exists(), "a session that never answered writes no store"); + let mut session = Session::cached(&scratch); + session.text("list_units", json!({})); + session.end(); + let first = fs::read(scratch.own_store()).unwrap(); + + let leaf = scratch.file("rtl/leaf.sv"); + let text = fs::read_to_string(&leaf).unwrap().replace("module leaf", "module leaf_k"); + fs::write(&leaf, text).unwrap(); + let mut session = Session::cached(&scratch); + assert!(session.text("list_units", json!({})).contains("leaf_k")); + session.child.kill().unwrap(); + session.child.wait().unwrap(); + assert_eq!(fs::read(scratch.own_store()).unwrap(), first, "the previous store, whole"); + assert!(temp_files(&scratch.cache()).is_empty(), "{:?}", temp_files(&scratch.cache())); + + // And the next start is right about the changed file (its hash misses). + let mut session = Session::cached(&scratch); + assert!(session.text("list_units", json!({})).contains("leaf_k")); + let stderr = session.end(); + assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}"); +} + +/// QA finding 2: a write killed between the temp file and the rename leaves +/// `index-cache-mcp..tmp` (reproduced on opentitan: 9.4 MB of a 46 MB +/// store) and nothing ever removes it — each crash adds one. The language +/// server has the same leak, filed by its own QA (2026-08-27, +/// `index_cache.rs` `an_orphaned_compaction_tmp_file_is_never_swept_up`). +/// Correct behaviour: the next write sweeps a stale temp file of its own +/// store's name (an old mtime, so a concurrent writer's live one is spared). +#[test] +#[ignore = "QA finding 2"] +fn qa_an_orphaned_temp_file_is_swept_by_the_next_write() { + let scratch = Scratch::new(); + fs::create_dir_all(scratch.cache()).unwrap(); + let orphan = scratch.cache().join("index-cache-mcp.999999.tmp"); + fs::write(&orphan, "lucisv-index-cache\t2\ttorn").unwrap(); + let old = SystemTime::now() - Duration::from_secs(3600); + fs::File::options().write(true).open(&orphan).unwrap().set_modified(old).unwrap(); + let mut session = Session::cached(&scratch); + session.text("list_units", json!({})); + session.end(); + assert!(scratch.own_store().is_file()); + assert!(!orphan.exists(), "an hour-old temp file of our store is a dead writer's"); +} + +// --------------------------------------------------------------------------- +// 3. Parity and freshness. +// --------------------------------------------------------------------------- + +/// Warm from the editor's store, warm from its own, and cold: the same +/// answers to every read tool the probe asks. +#[test] +fn qa_warm_answers_equal_cold_answers_from_either_store() { + let scratch = Scratch::new(); + let (cold, _) = probe(&scratch, None); + scratch.write_editor_store(&honest_store(&scratch)); + let (from_editor, stderr) = probe(&scratch, Some(&scratch.cache())); + assert!(stderr.contains(&reused(FILES, 0)), "{stderr}"); + assert_eq!(from_editor, cold); + fs::remove_file(scratch.editor_store()).unwrap(); + let (from_own, stderr) = probe(&scratch, Some(&scratch.cache())); + assert!(stderr.contains(&reused(0, FILES)), "{stderr}"); + assert_eq!(from_own, cold); +} + +/// Since the store was written: a same-size edit (only the hash can tell) +/// is re-parsed and answered new, and a new file is indexed. +#[test] +fn qa_a_same_size_edit_and_a_new_file_since_the_store_are_seen() { + let scratch = Scratch::new(); + scratch.write_editor_store(&honest_store(&scratch)); + let leaf = scratch.file("rtl/leaf.sv"); + let before = fs::read_to_string(&leaf).unwrap(); + let after = before.replace("held", "hold"); + assert_eq!(before.len(), after.len(), "premise: the size does not change"); + fs::write(&leaf, after).unwrap(); + fs::write(scratch.file("rtl/extra.sv"), "module extra_unit; endmodule\n").unwrap(); + + let mut session = Session::cached(&scratch); + let outline = session.text("outline", json!({"file": "rtl/leaf.sv"})); + assert!(outline.contains("hold") && !outline.contains("held"), "{outline}"); + assert!(session.text("list_units", json!({})).contains("extra_unit")); + let stderr = session.end(); + assert!(stderr.contains(&reused(FILES - 1, 0)), "{stderr}"); + assert!(stderr.contains(&format!("indexed {} files", FILES + 1)), "{stderr}"); +} + +// --------------------------------------------------------------------------- +// 4. Rule 6: the forced delete. +// --------------------------------------------------------------------------- + +const HOLDER: &str = "module keep_before; +endmodule + +module holder; +`define LOCAL 3 +`define LOCAL 4 + always_comb begin +`undef GONE + end +endmodule + +module user_after (output logic [3:0] o); + assign o = `LOCAL; +endmodule +"; + +/// A module holding a `define that code after it reads: refused without +/// `force` (tree byte-identical, the refusal says how to override); forced, +/// the warning names each macro once in source order, and every byte outside +/// the module's lines is the byte that was there. +#[test] +fn qa_a_forced_delete_of_a_define_holder_leaves_the_code_after_it_unchanged() { + let scratch = Scratch::new(); + let file = scratch.file("rtl/holder.sv"); + fs::write(&file, HOLDER).unwrap(); + let mut session = Session::start(&scratch, None); + let args = json!({"file": "rtl/holder.sv", "item": "holder"}); + let refused = session.call("delete_item", args.clone()); + assert_eq!(refused["isError"], true, "{refused}"); + let said = refused["content"][0]["text"].as_str().unwrap(); + assert!(said.contains("rule 6") && said.contains("force: true"), "{said}"); + assert_eq!(fs::read_to_string(&file).unwrap(), HOLDER, "a refusal writes nothing"); + + let mut forced = args; + forced["force"] = Value::from(true); + let applied = session.text("delete_item", forced); + assert!(applied.contains("deleted macro definitions: LOCAL, GONE (undef) — "), "{applied}"); + let start = HOLDER.find("module holder;").unwrap(); + let end = HOLDER.find("module user_after").unwrap(); + let now = fs::read_to_string(&file).unwrap(); + assert!(now.starts_with(&HOLDER[..start]), "{now}"); + assert!(now.ends_with(&HOLDER[end - 1..]), "the code after the item, byte for byte: {now}"); + assert!(!now.contains("`define"), "{now}"); + session.end(); +} + +/// `force` on a deletion whose item holds no macro: no macro warning, and a +/// `define item at the file's own level is still not a delete target. +#[test] +fn qa_force_says_nothing_about_macros_it_did_not_remove() { + let scratch = Scratch::new(); + fs::write(scratch.file("rtl/holder.sv"), HOLDER).unwrap(); + let mut session = Session::start(&scratch, None); + let args = json!({"file": "rtl/holder.sv", "item": "keep_before", "force": true}); + let applied = session.text("delete_item", args); + assert!(!applied.contains("macro"), "{applied}"); + session.end(); +} + +// --------------------------------------------------------------------------- +// 5. The instructions. +// --------------------------------------------------------------------------- + +/// ≤ 900 characters; names the read tools, the edit tools, `dry_run`, +/// `diagnostics`, the disk, root-relative paths and byte columns; and every +/// snake_case or tool-like word in it is a tool `tools/list` has. +#[test] +fn qa_the_instructions_are_short_and_name_only_real_tools() { + let scratch = Scratch::new(); + let mut session = Session::start(&scratch, None); + let init = session.request("initialize", json!({"protocolVersion": "2025-06-18"})); + let text = init["result"]["instructions"].as_str().unwrap().to_string(); + let listed = session.request("tools/list", json!({})); + let tools: Vec = listed["result"]["tools"] + .as_array() + .unwrap() + .iter() + .map(|tool| tool["name"].as_str().unwrap().to_string()) + .collect(); + session.end(); + assert!(text.chars().count() <= 900, "{} characters", text.chars().count()); + for named in [ + "unit_interface", + "outline", + "read_item", + "list_units", + "search_symbols", + "definition", + "references", + "hierarchy", + "replace_item", + "insert_item", + "delete_item", + "rename", + "add_port", + "remove_port", + "format", + "fix_lint", + "diagnostics", + ] { + assert!(text.contains(named), "the instructions name {named}"); + assert!(tools.iter().any(|tool| tool == named), "{named} is a real tool"); + } + for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) { + if word.contains('_') && word != "dry_run" { + assert!(tools.iter().any(|tool| tool == word), "`{word}` is not a tool"); + } + } + for phrase in ["dry_run", "disk", "relative to a root", "1-based bytes", "never unsaved"] { + assert!(text.contains(phrase), "{phrase}: {text}"); + } +} diff --git a/crates/lucisv_mcp/tests/wire.rs b/crates/lucisv_mcp/tests/wire.rs index 1d1c5fd..250d50c 100644 --- a/crates/lucisv_mcp/tests/wire.rs +++ b/crates/lucisv_mcp/tests/wire.rs @@ -1290,3 +1290,115 @@ fn structural_edits_keep_a_crlf_file_crlf() { "module c;\r\n logic b;\r\n\r\n logic c;\r\n logic d;\r\nendmodule\r\n" ); } + +// --------------------------------------------------------------------------- +// M6: the rule-6 ruling on a forced delete, and the instructions. +// --------------------------------------------------------------------------- + +/// An `always` block holding a `` `define`` and an `` `undef`` that code +/// after it reads, and a module holding a `` `define`` in its body. +const MACRO_HOLDERS: &str = "`define W 1'b1 +module dm (output logic o, output logic p); + always_comb begin +`define Q 1 +`undef W + p = 1'b0; + end + assign o = `Q; +endmodule + +module holder; +`define H 2 +endmodule +"; + +const DROPPED: &str = "code after the item that used them will change meaning"; + +#[test] +fn a_forced_delete_removes_macro_definitions_and_names_them() { + let tree = Tree::of("item"); + fs::write(tree.path("rtl/dm.sv"), MACRO_HOLDERS).unwrap(); + let mut server = Session::over(&tree); + server.initialize(); + let before = snapshot(&tree); + // Without `force` the refusal stands, and says how to override it. + let always = json!({"file": "rtl/dm.sv", "item": "always@3"}); + let said = refusal(&mut server, "delete_item", always.clone()); + assert!(said.contains("(`Q`)") && said.contains("pass `force: true`"), "{said}"); + let module = json!({"file": "rtl/dm.sv", "item": "holder"}); + let said = refusal(&mut server, "delete_item", module.clone()); + assert!(said.contains("(`H`)"), "{said}"); + assert_eq!(before, snapshot(&tree), "a refusal writes nothing"); + + let mut forced = always; + forced["force"] = Value::from(true); + let preview = server.text("delete_item", dry(&forced, true)); + let warning = format!(" deleted macro definitions: Q, W (undef) — {DROPPED}\n"); + assert!(preview.contains(&warning), "{preview}"); + assert_eq!(before, snapshot(&tree), "a dry run writes nothing"); + let applied = server.text("delete_item", forced); + assert!(applied.contains(&warning), "{applied}"); + let expected = MACRO_HOLDERS + .replace(" always_comb begin\n`define Q 1\n`undef W\n p = 1'b0;\n end\n", ""); + assert_eq!(fs::read_to_string(tree.path("rtl/dm.sv")).unwrap(), expected); + + let mut forced = module; + forced["force"] = Value::from(true); + let applied = server.text("delete_item", forced); + assert!(applied.contains(&format!("deleted macro definitions: H — {DROPPED}")), "{applied}"); + // The item's own lines go; the blank line above it is not doubled, so + // it stays (M4's blank-line rule). + let expected = expected.replace("module holder;\n`define H 2\nendmodule\n", ""); + assert_eq!(fs::read_to_string(tree.path("rtl/dm.sv")).unwrap(), expected); +} + +/// The attack side of the ruling: `force` relaxes rule 6 for a deletion +/// only. A replace or insert that plants a definition is refused however it +/// is asked (neither takes `force`), and a forced delete of an item holding +/// no definition says nothing about macros. +#[test] +fn force_relaxes_rule_6_for_a_deletion_and_nothing_else() { + let tree = Tree::of("item"); + fs::write(tree.path("rtl/dm.sv"), MACRO_HOLDERS).unwrap(); + let mut server = Session::over(&tree); + server.initialize(); + let before = snapshot(&tree); + let text = "always_comb begin\n`define Q 2\n p = 1'b0;\n end"; + let replace = json!({"file": "rtl/dm.sv", "item": "always@3", "text": text, "force": true}); + let said = refusal(&mut server, "replace_item", replace); + assert!(said.contains("force"), "an unknown argument: {said}"); + let replace = json!({"file": "rtl/dm.sv", "item": "always@3", "text": text}); + assert!(refusal(&mut server, "replace_item", replace).contains("(rule 6)")); + let insert = json!({"file": "rtl/dm.sv", "anchor": "always@3", "text": "initial begin\n`undef Q\n end"}); + assert!(refusal(&mut server, "insert_item", insert).contains("(rule 6)")); + assert_eq!(before, snapshot(&tree)); + + let plain = json!({"file": "rtl/dm.sv", "item": "assign@8", "force": true}); + let applied = server.text("delete_item", plain); + assert!(!applied.contains("macro"), "{applied}"); +} + +#[test] +fn the_instructions_name_the_workflow_within_900_characters() { + let tree = Tree::new(); + let mut server = Session::over(&tree); + let reply = server.initialize(); + let instructions = reply["result"]["instructions"].as_str().unwrap(); + assert!(instructions.chars().count() <= 900, "{}", instructions.len()); + for word in [ + "unit_interface", + "outline", + "read_item", + "replace_item", + "insert_item", + "delete_item", + "rename", + "add_port", + "dry_run", + "diagnostics", + "all-or-nothing", + "1-based bytes", + ] { + assert!(instructions.contains(word), "{word}: {instructions}"); + } +} diff --git a/docs/features/mcp-cache-and-census/README.md b/docs/features/mcp-cache-and-census/README.md new file mode 100644 index 0000000..0aaf281 --- /dev/null +++ b/docs/features/mcp-cache-and-census/README.md @@ -0,0 +1,385 @@ +# mcp-cache-and-census + +Lane **M6** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §6 and §8): +the index cache reuse, the startup and per-call timings, the M4 review's +rule-6 ruling, the first revision of the `initialize` instructions — and, +the lead's half, the token census and the closing release. + +## Goal + +A coding agent's first question to `lucisv-mcp` pays for the index build: +1.9 s on opentitan, every session. The language server has already parsed +the same files and persisted one `FileFacts` record per file, keyed by the +file's content hash (`lucisv_server::index_cache`). This lane lets MCP +start from those records — read only, never written — and from a store of +its own in the same codec, so a warm start skips the parse of every file +whose bytes a record was read from. A record can only ever stand in for the +parse of exactly the bytes it was read from, so the cache is a performance +input and never a correctness one: a torn, damaged, foreign or stale record +costs a parse and nothing else. + +## Assumptions + +- **Where.** Only `--index-cache DIR` turns the caches on (the extension + passes VS Code's `storagePath`, the directory the language server writes + `index-cache` in). No OS-cache-dir fallback: without the flag MCP starts + cold, as before. The directory may not exist yet (M5 QA F4: VS Code + creates `storagePath` lazily) — that is a silent cold start. +- **Read.** At startup `cache::Records::load` reads `DIR/index-cache-mcp` + and then `DIR/index-cache` (so a record both hold is credited to the + editor). A store is used only when its first line is exactly this build's + header `lucisv-index-cache\t2\t\t`; any other first + line ignores the store whole with **one stderr line**; a missing or empty + file is silent. Each record line is `hash\tfacts\tchecksum`; a line whose + hash or checksum is not 16 hex digits, whose checksum is not the FNV-1a of + the facts field, or which is not UTF-8 is skipped — that covers a torn + last line (a writer killed mid-append) and a record edited after it was + written. Records are keyed by `(record_path, content hash)`. +- **Use.** For each discovered file, MCP reads and hashes the bytes (it + must anyway: the stamp and the freshness sweep need the hash). When + `(canonical path, hash)` has a record that `FileFacts::decode`s to the + same path, `IndexBuilder::add_facts` takes it instead of `add_file`. A + record under another path (the language server's paths are whatever the + editor handed it; MCP's are canonical) is a miss, not a translation. +- **Write — only our own store.** On EOF (the host closes stdin) the + server writes `DIR/index-cache-mcp`: the same header, then one record per + indexed file — the facts the index holds, under the hash in the file's + stamp (both come from the same read, so they describe the same bytes), + in path order. Atomic: a `index-cache-mcp..tmp` renamed over the + store; a failure removes the temp file and is **one stderr line** + (`cannot write the index cache: …`); the session ends either way. The + directory is created if missing, and gets a `.gitignore` of `*` when it + has none (the language server does the same). **`DIR/index-cache` is + never opened for writing**: `cache.rs` has no code path that names it + except `fs::read`, and `tests/cache.rs` hashes it before and after whole + sessions. +- **Not written:** a session that never answered a tool call (no project + was built), or a session killed rather than closed. Two MCP servers on one + directory each rename their own complete store over the file: last writer + wins, both stores are whole. +- **The stderr line** is `lucisv-mcp: indexed N files in M ms (E from the + editor's cache, O from its own)` when `--index-cache` is given, and the + old line without the parenthesis otherwise. `M` now includes the index + merge (`IndexBuilder::finish`), which the M1 line left out — the number + went up by the merge's ~200 ms on opentitan; the build did not change. +- **The codec is restated, not shared.** `index_cache.rs`'s `FILE`, + `CACHE_FORMAT`, header and line formats are private to `lucisv_server` + (a binary crate MCP must not depend on — PLAN §4.1). `cache.rs` restates + them; `cache::tests::the_codec_is_the_language_servers_own` reads + `crates/lucisv_server/src/index_cache.rs` at test time and fails if any of + the five pinned source lines changes (Handshake MCP-14). +- **Rule 6, the M4 ruling.** `delete_item` with `force: true` may remove an + item that holds `` `define``/`` `undef`` entries (a module with a + `` `define`` in its body, an `always` with one nested): the deletion + passes rule 6 and the answer carries the warning `deleted macro + definitions: Q, W (undef) — code after the item that used them will + change meaning` (each name once, in source order, `(undef)` for an + `` `undef``). Without `force` the refusal stands and now ends `, or pass + `force: true` to delete it anyway`. `replace_item` and `insert_item` take + no `force` and are unchanged. The verifier change is local: + `Expect::Nothing { force }`, and `Outcome::dropped_macros`. +- **The instructions** (`rpc.rs`, 787 characters, pinned ≤ 900 by a wire + test) name the read tools to prefer over reading files, that edits are + verified, all-or-nothing, on disk with `dry_run`, the item tools vs the + design-wide ones, `diagnostics` to check, and the path/column units. The + lead revises them after the census. + +## Handshakes + +Consumed (unchanged, read only): `vlog_semantic::{FileFacts::{encode, +decode, path}, record_path, FACTS_FORMAT, IndexBuilder::{add_facts, +add_file, finish}, WorkspaceIndex::{facts_for, fingerprint}}`; +`lucisv_core::cache::content_hash`; the byte format of +`lucisv_server::index_cache` (below). + +Promised: `Project::open_cached(roots, filelist, cache_dir)` (the old +`Project::open` is now the tests' uncached shorthand), `Project::save_cache`, +`Project::reuse`. `rpc.rs` calls them in `open_project` and on EOF. + +Filed: + +- **MCP-14 → `lucisv_server` (informational + one request).** MCP reads + the server's `index-cache` read-only (`fs::read`, never a write handle) + and writes `index-cache-mcp` beside it in the same codec. Nothing in the + server changes. *Request (not blocking):* the codec constants (`FILE`, + `CACHE_FORMAT`, `header()`, `line()`/`parse_entry`) are private to a + binary crate, so MCP restates them and pins the restatement against the + source text; lifting the codec (not the store) into `vlog_semantic` or + `lucisv_core` as a pure move would let both sides share one definition + and retire the pin. Until then, **a change to the store's framing must + bump `CACHE_FORMAT` and update `crates/lucisv_mcp/src/cache.rs`** — the + pin test fails otherwise. +- **MCP-7 → `vlog_refactor`: status unchanged (open).** `rename` still + hands the engine the whole set: 2.23–2.28 s per dry run on opentitan + (below), the cost MCP-7's `KnownFacts` variant (or passing the index's + facts to `rename_traced_with`, which already takes `&dyn KnownFacts`) + would remove. That is an M3 tools change, not this lane's. +- **Out-of-ownership edit, flagged for the lead:** `tests/qa_m4.rs` + `qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always` + pinned "a forced delete of a module holding a `define is refused" — the + exact behaviour the M4 review ruled to change. The loop over + `force ∈ {false, true}` became the unforced refusal plus a forced dry run + that must succeed and name `LOCAL` (8 lines, comment says why). Without + it `cargo test -p lucisv_mcp` is red. +- **For the lead (docs outside this lane):** the M1 README's Assumption + "`--index-cache DIR` is accepted and stored, and unused until M6" is now + stale; `docs/mcp/PLAN.md` §6 matches what was built. + +## Status / TODO + +- [x] `cache.rs`: read-only reader of the editor's store (header, per-line + checksum, `record_path`, `decode`), keyed by path + content hash +- [x] warm start: `add_facts` on a hit, parse on a miss; hit counts on the + stderr startup line +- [x] own store `index-cache-mcp`: same codec, written atomically on EOF, + read on start; a write failure is one stderr line +- [x] F4: a missing directory is a silent cold start +- [x] unit tests (`src/cache/tests.rs`): the codec pin; warm from the + editor's store = cold fingerprint; own store round trip = cold + fingerprint; a changed file misses; torn / damaged / foreign records + each a parse; a record under another path or hash not taken +- [x] wire tests (`tests/cache.rs`): the editor's store byte-identical + (hash + mtime) after a session that indexes, answers and edits, with + a damaged and a torn record skipped; another version's store ignored + with one line; missing directory → cold, own store written, next + start warm from it, a changed file re-parsed and answered new; an + unwritable directory (0555) → answers, one stderr line, nothing + written +- [x] opentitan timings (`tests/opentitan.rs`, ignored): cold / warm from + own store / warm from the editor's store, exit write, stat sweep, + whole-set `rename` +- [x] rule-6 ruling: `force` relaxes rule 6 on `delete_item` with the + warning; wire test + attack test +- [x] `INSTRUCTIONS` first revision (≤ 900 characters, wire-tested) +- [x] `docs/perf/README.md` MCP entry +- [ ] token census, instruction revision after it, topo, CHANGELOG, + release — the lead's + +## Timings + +Release build (`cargo test --release -p lucisv_mcp --test opentitan -- +--ignored --nocapture opentitan_startup`), macOS arm64, the whole opentitan +checkout (3 944 indexed files, 3 over 1 MiB skipped), two runs; the +checkout's `git status --porcelain` identical before and after. The stores +live in a scratch directory outside the checkout; the "editor's store" is +the own store renamed to `index-cache` — the same bytes the language server +would write (46.3 MB), which is what the codec pin guarantees. + +| what | wall | +|---|---| +| cold start, no store (first `project_overview`) | 1 854–1 887 ms (build 1 800–1 880 ms) | +| warm from its own store | 837–847 ms (build 821–840 ms, 3 944 hits) | +| warm from the editor's store | 821–832 ms (build 814–824 ms, 3 944 hits) | +| exit, writing `index-cache-mcp` (46.3 MB) | 251–272 ms | +| per-call freshness sweep (`outline` of a cached file, median of 21) | 5.6–6.1 ms | +| — the transport floor (`tools/list`, median of 21) | 0.38 ms | +| `rename` `op_i` → `cipher_op_i` at `hw/ip/aes/rtl/aes_cipher_core.sv:123`, `dry_run`, whole set | 2 227–2 276 ms (first and second call alike) | + +Where a warm build's ~820 ms goes (one instrumented run, not committed): +walk 210 ms, reading the store 87 ms, reading + hashing + decoding 3 944 +files 318 ms (1 387 ms when each is parsed instead), the index merge +204 ms. The walk and the merge are the floor a cache cannot remove. + +## Token census (lead) + +## Work log + +**2026-09-23 (dev, Opus).** Built as briefed, in the owned files plus the +two flagged edits (`rpc.rs` wiring beyond `INSTRUCTIONS`; `tests/qa_m4.rs`). + +- `cache.rs` (118 production lines): `Records::load/take`, `write_own`, + the restated header/line codec, `store_lines` reading bytes a line at a + time exactly as the language server does (a torn multi-byte character + costs one line). `Reuse` counts hits by source. +- `project/mod.rs`: `open_cached` + a `load` helper (read, stamp, take a + record or parse); `save_cache` builds `(stamp.hash, index.facts_for)` + per file; `reuse()`. **Deviation:** the build clock now stops after + `finish()` — the old code read the clock before the merge ran inside the + struct literal, so every "indexed in M ms" since M1 left out ~200 ms on + opentitan. `Project::open` became `#[cfg(test)]` (its only callers are + tests; clippy's dead-code lint otherwise). +- `rpc.rs`: `open_project` calls `open_cached` and prints the counts; + `Line::Eof` calls `Server::finish`, which saves (verbose: a line with the + record count; failure: one line always). **Deviation:** the brief listed + `rpc.rs` for `INSTRUCTIONS` only, but the startup line and the EOF write + live there; the change is those two call sites. +- `verify.rs`/`item.rs`: the rule-6 ruling (above); `delete_item`'s + description and `force` parameter say so. +- Unit tests live in `src/cache/tests.rs` (the fingerprint oracle needs + `Project`, which a `tests/` file cannot reach in a binary crate). +- The own store is rewritten on every exit even when unchanged (~260 ms on + opentitan, after the last answer): simple, and a store the host kills us + during is still the previous whole store. +- Tests: `lucisv_mcp` 290 → 302 passing (+5 unit, +4 `tests/cache.rs`, + +3 wire), ignored 2 → 3 (the opentitan timing test); workspace 4 846 → + 4 858. + +## QA log + +**2026-09-23 (QA, Opus) — QA — interrupted** (the session was cut off before the workspace gate finished; everything below was run and is recorded as measured). + +**The cache half of the M6 QA line. Verdict so far: pass; +no wrong record served, the editor's store never written. Two non-blocking +findings (one doc, one inherited leak). The census spot-check waits for the +census.** Tests in `crates/lucisv_mcp/tests/qa_m6.rs` (16 pass, 1 ignored = +finding 2), each spawning the real binary over a scratch copy of the +`design` fixture. + +*Wrong-record hunt (blocking class — nothing found).* + +- **Swapped records, checksums recomputed** (`leaf.sv`'s hash carrying + `top.sv`'s facts and the reverse): not served. The key is `(record_path + of the facts, hash)` and `take` compares the decoded path again, so each + lands under (other path, this hash) and matches no file — 5/7 hits, the + probe's nine answers equal a cold start's. Also run on a copy of opentitan + `hw/ip/{aes,prim}` with a real language-server store (`prim_fifo_sync` ↔ + `prim_fifo_async`): 391/393 hits, both interfaces right. +- **Inherited, documented limit (not a finding against the code):** a + record *relabelled* — `prim_fifo_async`'s facts with `prim_fifo_sync.sv`'s + path, under `prim_fifo_sync.sv`'s real hash, checksum recomputed — is + served (393/393 hits; `unit_interface prim_fifo_sync` answers "not + indexed") and is then re-laundered into `index-cache-mcp` with a fresh + checksum. The language server does exactly the same: `index_cache.rs`'s + module doc states the same-user/same-disk threat model (FNV-1a is not a + MAC; whoever can write the store can write the sources). Accidental + damage cannot produce this shape. See finding 1 for the doc. +- Records for a deleted file and for a file outside every root (it exists + beside the root): neither module listed, neither record written back + (own store = header + 7). Two records for one path under two hashes + (the append log's normal shape): the one whose hash is the bytes on disk is + served, older or newer; two for one `(path, hash)`: the later line wins, as + in `IndexCache::open` (tested with a checksum-valid wrong record first and + the honest one last). +- CRLF store: `\r` stripped exactly as the language server strips it, 7/7 + hits, answers = cold. Header near-misses — version patch + 1, + `FACTS_FORMAT` ± 1, `CACHE_FORMAT` 1 and 3, a trailing space, a BOM, a + fifth field: each ignored whole with exactly one stderr line, store + byte-identical. Empty store, header-only store, a directory named + `index-cache`: silent cold starts (stderr = the startup line only). +- A 231 MB store (opentitan's 46 MB store + 4 copies under `/ghostN` paths, + checksums valid), release build, 3 944 files: build 892 / 937 / 1 026 / + 1 203 ms at 46 / 92 / 138 / 231 MB — linear (~1.7 ms/MB); peak RSS 407 → + 750 MB (the store bytes plus every record's string are held until the + load ends); the store byte-identical after each run. + +*Read-only promise and the own store's writes.* + +- The editor's store at mode 0444, in a live server's between-compactions + shape (reversed path order, a duplicate line, a torn line mid-file, a + checksum-failing line), through a session that indexes, answers, runs + `format` (writes a file) and ends: bytes, mtime and mode identical, 7/7 + hits. On the real `aes`+`prim` LSP store: `shasum` identical after a warm + session. Code: `cache.rs` names `EDITOR_STORE` only in `Records::load` + → `fs::read`; `write_own` writes only `index-cache-mcp`, its temp file and + `.gitignore` (when missing — as the language server does). +- Killed sessions (SIGKILL): after an answer and before EOF (fixture, with + a changed file that would have changed the store): the previous own store + byte-identical, no temp file, the next start re-parses the changed file. + On opentitan, killed at 20–350 ms after EOF (11 delays): own store + intact, no temp. Killed the instant `index-cache-mcp..tmp` appeared: + store intact, **a 9.4 MB temp file left behind for good** → finding 2. +- `--index-cache` naming a regular file: answers right, one `cannot write + the index cache` line, the file untouched. A directory named + `index-cache-mcp`: silent read miss, one line at exit, no temp left. Cache + directory mode 000 holding an honest store: cold start, the nine probe + answers equal cold's, one line at exit, store untouched. (A startup that + cannot *read* a store is silent — only the exit's write failure speaks. + Acceptable for a performance input; noted, not filed.) + +*Parity.* + +- The nine-answer probe (`list_units`, two `unit_interface`, two `outline`, + `search_symbols`, `references`, `hierarchy`, `defines`) is identical cold, + warm from the editor's store and warm from the own store. +- A **real language-server store** (release `lucisv-server` driven over + stdio on a copy of `hw/ip/{aes,prim}`, `index.scope = workspace`, + `storagePath` = scratch; 393 records, 2.69 MB): MCP warm start 393/393 + editor hits, and — the stronger check — a **cold** MCP session's + `index-cache-mcp` over the same tree is **byte-identical** to the + server's `index-cache`: same header, same facts, same order. +- `WorkspaceIndex::fingerprint` (throwaway unit test in a scratch copy of + the crate, not committed): warm-from-LSP-store = cold on `aes`+`prim` + (393 files); warm-from-own-store = cold on the **whole opentitan + checkout** (3 944 files, fingerprint 37.2 MB); the checkout's `git status + --porcelain` identical before and after every run. +- Same-size edit (`held` → `hold`) since the store: re-parsed, the outline + shows `hold`; a new file since the store: indexed; 6/7 hits. + +*Rule 6 (the M4 ruling).* A module holding `` `define LOCAL`` twice and a +nested `` `undef GONE``, read by the module after it: without `force` +refused (names rule 6 and `force: true`), file byte-identical; forced: the +warning reads `deleted macro definitions: LOCAL, GONE (undef) — …` (each +name once, source order), every byte before and after the item's lines is +the original's. `force` on an item with no macro says nothing about +macros. The `tests/qa_m4.rs` diff is exactly the ruling's assertion swap +(the `force ∈ {false, true}` refusal loop → unforced refusal + forced dry +run naming `LOCAL`), nothing else. The code: `Expect::Nothing { force }`; +for a deletion `same_macros` can only fail when the region held a +definition, which is exactly what `dropped` lists — `force` cannot excuse +anything else. + +*Instructions.* 787 characters (≤ 900). Names `unit_interface`, `outline`, +`read_item`, `list_units`, `search_symbols`, `definition`, `references`, +`hierarchy`, the three item tools, `rename`, `add_port`, `remove_port`, +`format`, `fix_lint`, `diagnostics` — every one in `tools/list`, and no +snake_case word that is not a tool (`dry_run` aside); says disk-only, +root-relative paths, 1-based byte columns. + +*Sizes.* Production lines: `cache.rs` 118, `project/mod.rs` 289, `rpc.rs` +265, `tools/item.rs` 389, `tools/item/verify.rs` 388 — all under 600. + +*Timings (release, whole opentitan, this machine, `tests/opentitan.rs`).* +Cold 1 769 ms build (first call 1 776 ms); warm own 833 ms; warm editor's +807 ms; exit write 243–260 ms; sweep median 4.9–5.0 ms (floor 0.35 ms); +`rename` dry run 2 152–2 172 ms. Consistent with the dev's table. + +*Findings.* + +1. **(low, doc)** `docs/features/mcp-cache-and-census/README.md` Goal: + "a torn, damaged, foreign or stale record costs a parse and nothing else" + overclaims — a forgery that recomputes the FNV-1a checksum is served + (reproduction above; the language server has the same property by + design). Fix: say "a torn, damaged, foreign or stale record", and add the + threat-model sentence the server's `index_cache.rs` module doc carries + (same user, same disk; the checksum catches damage, not intent) to + Assumptions → Read. No code change. +2. **(minor, inherited)** `crates/lucisv_mcp/src/cache.rs:140-146` + (`write_own`): a process killed between `fs::write(tmp)` and the rename + leaves `index-cache-mcp..tmp` (9.4 MB on opentitan) that no later + session removes — one per crash, each up to the store's size. Harmless + to correctness (only the exact store names are read). Same leak as the + language server's, filed by its QA 2026-08-27 + (`an_orphaned_compaction_tmp_file_is_never_swept_up`). Pinned by + `qa_an_orphaned_temp_file_is_swept_by_the_next_write` (ignored). Fix: + before writing, remove `index-cache-mcp.*.tmp` files in `dir` older than + a few minutes (a concurrent writer's live temp file is seconds old). + +*Gates* (through `tools/guard.sh`, one at a time): `cargo fmt --all -- +--check` clean; `cargo clippy --workspace --all-targets` clean (no +warnings); `cargo test -p lucisv_mcp` 318 passed, 0 failed, 4 ignored +(302 + 16 QA; ignored: 2 opentitan, M3 finding, M6 finding 2); the +opentitan tests (release, `--ignored`) 2 passed, checkout unchanged; +`cargo test --workspace` **NOT completed** — cut off after ~16 minutes, mid-run (reached `vlog_refactor`, `corpus`, `inline` test binaries; every result line captured before the cut-off was `ok`, no failure seen). + +*Not yet checked:* the full `cargo test --workspace` count (needs ≥ 4 858 + 16 = 4 874 passing); the census transcripts spot-check (the census has not been run — the lead's half); a whole-opentitan store written by the *language server itself* (only `aes`+`prim` was; whole opentitan was checked with MCP's own store). The M6 QA box in `TODO-MCP.md` is left unticked. + +## Review + +**Lead, 2026-09-23 (M6, committed at the owner's move).** The reader keys a +record on the file's content hash and the record's own path, never writes +the editor's store, and a warm start on opentitan halves the startup (1.9 s +→ 0.8 s; the walk and the merge are the floor). QA (interrupted by the move, +verdict pass so far): swapped, stale, foreign-path, deleted-file, off-by-one +header and CRLF stores all skipped; the editor's store byte-identical through +a session; SIGKILL mid-write leaves the previous own store intact; a +231 MB store loads linearly; fingerprint parity with a cold build over the +whole checkout. Two low items: the README's threat model now says +"damaged", not "forged" — a record with a recomputed checksum is used, +exactly as the language server uses it, because whoever can write the store +can write the sources; and an orphaned `index-cache-mcp..tmp` after a +kill between write and rename is not swept (QA's ignored test +`qa_an_orphaned_temp_file_is_swept_by_the_next_write`) — to be fixed in the +first census round. The forced-delete ruling (rule 6) and the first +`INSTRUCTIONS` revision landed here; the census revises the instructions +again. The full workspace suite was still running when the machine moved; +the dev's run on the same code passed 4 858 and QA's crate suite 318. diff --git a/docs/features/mcp-transport/README.md b/docs/features/mcp-transport/README.md index 32574a8..b81a901 100644 --- a/docs/features/mcp-transport/README.md +++ b/docs/features/mcp-transport/README.md @@ -89,8 +89,10 @@ arrived. tree. The build line (`lucisv-mcp: indexed N files in M ms`) is always written to stderr; `--verbose` adds one timing line per request and the freshness report per call. -- **`--index-cache DIR` is accepted and stored, and unused** until M6 reads - the LSP's store. +- **`--index-cache DIR`** names the directory holding the language server's + `index-cache` store, read read-only at startup (M6, 2026-09-23: + `docs/features/mcp-cache-and-census`), beside which this server writes its + own `index-cache-mcp` once at exit. A missing directory is a cold start. - **Argument validation is a tool error, not a protocol error.** A call whose `arguments` do not fit the tool's schema (unknown argument, wrong type, missing required one) is answered `isError: true` with a sentence naming diff --git a/docs/perf/README.md b/docs/perf/README.md index 557e355..a04fdf3 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -1423,3 +1423,24 @@ count and within noise in time (`aes` 14 locations / 9 files, `.clk_i` before it is rendered — one slice compare per location, unmeasurable — so a stale index can omit a location but never point at a wrong line (QA findings 1–4). `docs/features/references-hierarchical-surface/README.md`. +### 2026-09-23 — MCP: `lucisv-mcp` startup and the per-call sweep (TODO-MCP M6) + +`lucisv-mcp` builds its index at the first tool call and can start it from +the language server's `index-cache` (read only) or its own +`index-cache-mcp` beside it (`docs/features/mcp-cache-and-census/README.md`). +Release build, the whole opentitan checkout (3 944 files), two runs of +`tests/opentitan.rs::opentitan_startup_cold_and_warm_and_the_stat_sweep`: + +| what | wall | the language server's nearest row | +|---|---|---| +| cold start, no store | 1 854–1 887 ms | — | +| warm, own store (3 944 hits) | 837–847 ms | warm quiet workspace start 985–997 ms (§61), workspace scope | +| warm, the editor's store (3 944 hits) | 821–832 ms | — | +| exit, writing the own store (46.3 MB) | 251–272 ms | compaction skipped when unchanged (§P4b) | +| freshness sweep per call (median, 21 calls) | 5.6–6.1 ms (floor `tools/list` 0.38 ms) | — | +| `rename` dry run, whole set (`op_i` in `aes_cipher_core.sv`) | 2 227–2 276 ms | — (MCP-7) | + +A warm build is walk 210 ms + store read 87 ms + read/hash/decode 318 ms + +merge 204 ms; a cold one parses instead (1 387 ms). The rows are not +like-for-like with the server's (it scans in stages and answers during the +scan); they sit side by side so a regression in either shows. diff --git a/docs/repository-analysis.md b/docs/repository-analysis.md index cf5f63e..d7a8805 100644 --- a/docs/repository-analysis.md +++ b/docs/repository-analysis.md @@ -6,7 +6,7 @@ this review. Loop 2 is closed; no uncommitted feature work is included. ## Assessment and current status -lucisv remains an eight-crate toolchain: six reusable Rust libraries, CLI and +lucisv is a nine-crate toolchain (2026-09-23: `lucisv_mcp` joined): six reusable Rust libraries, CLI, MCP and LSP binaries, editor integration, corpus/release tools, and a static docs site. The architecture still separates syntax, formatting, semantics, linting, refactoring, and project inputs. The September 4 audit findings are fixed. @@ -47,6 +47,7 @@ two edits have disjoint ownership. | `crates/lucisv_core` | Config, filelists, cycle-aware walks and warning channel, format cache, atomic replacement; no language-engine dependency | | `crates/lucisv` | Argument handling, input discovery/dedup, worker pool, reports and source writes | | `crates/lucisv_server` | Ordered LSP loop and workspace overlays; `server/`, `state.rs`, capability handlers including `imports.rs`, `extract.rs`, `inline_module.rs`; project lint validation/logging in `lint/project.rs` | +| `crates/lucisv_mcp` | Model Context Protocol server for coding agents over stdio: `project/` (roots, filelist-or-walk, freshness sweep), `tools/` (26 tools: read, navigation, verified edits, structural edits with their own verifier in `tools/item/`), `apply.rs` (one all-or-nothing write path), `resources.rs`; composes the six libraries, never `lucisv_server` (`docs/mcp/PLAN.md`) | | `editors/` | VS Code client/grammar/settings/hierarchy UI and other editor configuration; `hierarchySections.js` models DUT sections, `extract.js` supplies the module-name prompt | | `tools/`, `scripts/`, `.gitea/workflows/` | Resource guard, corpus evaluation, artifact checks and releases | | `docs/features/` | Implementation contracts, dated measurements, QA and acceptance records | diff --git a/docs/topo.md b/docs/topo.md index c9905ce..695fe9f 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -94,6 +94,14 @@ graph TD TOOLS[tools/ release scripts] -.builds/packages.-> CLI TOOLS -.builds/packages.-> SRV TOOLS -.builds/packages.-> VSC + MCP[lucisv_mcp] --> C + MCP --> P + MCP --> S + MCP --> R + MCP --> F + MCP --> L + VSC -.spawn contract.-> MCP + TOOLS -.builds/packages.-> MCP CI[Gitea Actions] --> TOOLS DOCS[docs/site] -.documents CLI and generated rule reference.-> CLI DOCS -.documents protocol.-> SRV @@ -145,6 +153,7 @@ what a change on the pointed-to side must not silently break. | `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 to choose an index-derived file set; `extract_site`, `inline_site` and `imported_packages` also name source requirements. **`rename_preflight(semantics, offset, new_name)` (perf5r-preflight, 2026-09-08)** owes whole-scope `rename` the same *refusal* text one-directionally — it may always stand aside with `Ok(())` and never invents a refusal — and deliberately reads no workspace index (unlike `prepare_rename_here`): only refusals that are a pure function of the request buffer's own text (the new-name check, no symbol here, an unresolved or inherited-candidate reference, an unspelled declaration, the same name at a non-file-scope declaration); every index-answered refusal stays on the slow road. The engine remains the authority, and every selector must supply a superset of files needed for edits and refusals (inline gap: §2.9-33). | | `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_mcp ──▶ lucisv_core, vlog_parser, vlog_semantic, vlog_refactor, vlog_formatter, vlog_linter` | depends | The MCP block (2026-09-23, `docs/mcp/PLAN.md`, `TODO-MCP.md`): `lucisv-mcp` composes the six libraries through their public APIs only — `Discovery`/`filelist`/`walk`/`content_hash`/`write_atomic`/`diff::unified` (core); `tokenize`, `parse_tolerant`, `parse_source` (strict, the structural edits' rule 1), `LineIndex`, `defines`, the AST (`Item`/`ItemKind`, `Meta::leading`, `Connections`), `PARSE_STACK_SIZE` (parser); `analyze`, `IndexBuilder::{add_file, add_facts}`, `WorkspaceIndex::{absorb, fingerprint, units, members_of, member_in, instantiations, workspace_symbols, find_define, files_mentioning, …}`, `resolve_external`, `FileFacts::{of, decode}`, `FACTS_FORMAT` (semantic); every refactoring entry point + `find_references` + `instantiation_plan` (refactor); `format_source`/`format_range`/`fence` (formatter); `LintContext::from_parse`, `lint_with`, `select_rules`, `apply_fixes`, `rules_markdown`, `MentionOracle` (linter). **Never `lucisv_server`** (bin-only) and never `lsp-types`. Feature READMEs `docs/features/mcp-*`. | | `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 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`. | @@ -650,6 +659,9 @@ engine-lane features are listed above; this table is the server-internal web. | `ci-release ──▶ release-prep / editor-platform-vsix` | depends | Workflow = one-liners over `tools/`; consumes the exact seven `.vsix` names (`prune_release_assets.sh` checks each), the `CHANGELOG.md` heading convention, tag == workspace version. | | `release-prep ──▶ editor-packaging` | depends | `release.sh` runs `smoke.js` as its gate; closed the missing-`LICENSE` item editor-packaging filed. Version lives in exactly four files — a promise to everyone. | | `editor-marketplace-page ──▶ lucisv-server` (docs) | depends | The Details page mirrors the shipped capability table in the server's README; drifts if that table does. | +| `editor-packaging ◀──▶ lucisv-mcp` (mcp-packaging) | handshake | The MCP spawn contract (2026-09-23): the binary `lucisv-mcp[.exe]` found by the same three-rung ladder as the server (`lucisv.mcp.path` → `bin/` → `PATH`), spawned by VS Code from `McpStdioServerDefinition(label, command, ["--root", folder, "--index-cache", storage], env, version)` — the constructor is positional — one per workspace folder; `serverInfo.name == "lucisv-mcp"`, ≥ 26 tools (`mcp_smoke.js` `MIN_TOOLS`). Provider id `lucisv.mcp`; settings `lucisv.mcp.enabled`/`.path`; command `lucisv.mcp.copyConfig`. | +| `release-prep / editor-platform-vsix ──▶ lucisv-mcp` (mcp-packaging) | depends | `release.sh` builds `-p lucisv_mcp` for every triple and stages it as the THIRD `bin/` entry (fifteen in the `all` package); `expect_vsix_bins` and `audit_artifacts.sh` pin the name; the seven `.vsix` names are unchanged. `mcp_smoke.js` is the gate beside `smoke.js`. | +| `lucisv-mcp ──▶ lucisv-server` (index cache, M6) | depends (read-only) | MCP reads the server's `index-cache` store read-only when `--index-cache DIR` names it (header `CACHE_FORMAT`/`FACTS_FORMAT`/version must match, else ignored) and writes its own `index-cache-mcp` beside it; it never writes the server's file. A codec change on the server side costs MCP its warm start, never its correctness. | ### 2.9 Open handshakes (filed, not yet delivered — claim before working) @@ -692,6 +704,14 @@ update the filing README(s) and this file. | 32 | **The refactoring verifier does not catch a same-file relocation of a never-dropped piece written as two well-formed edits** (delete here, insert there): `verify_move` computes `after` by applying the edits, so `positions_match`'s reconstruction cannot diverge from it and equation 3 of the ledger is unreachable through any real caller. No planner produces the shape today. Wanted: an independent `after` (the client's applied text, or a second reconstruction) and a test that isolates equation 3. Found by extract-module's QA re-attack. | extract-inline-module (QA) | vlog_refactor | | ~~33~~ | ~~**`module_sources`' fan-out has no rung for a file that reaches an instance through an intermediate module it does not itself instantiate** (a bench naming `wrap.u_S.x` where `wrap` instantiates `S`): inline-module's hierarchical-reference refusal sees only the handed files, so such a reference is missed. Wanted: a transitive-instantiators rung (§49's hierarchical surface knows the path) in `module_sources` for the refactorings that must see every hierarchical use. Found by §53.2's QA.~~ — **closed 2026-09-07 by perf5-p2 (TODO §60.2): a fifth, opt-in rung** `Workspace::module_sources_reaching(file, modules, Reach { scopes })` in `lucisv_server/src/module_select.rs` — every file whose *token census* (`WorkspaceIndex::files_mentioning`, i.e. `FileFacts::words`) writes the dissolved instance's name down. That is exactly the set `no_hierarchy` can refuse from, so the selected set answers the refusal as the whole workspace does (asserted engine-run-twice on six shapes; QA attacked seven more incl. `$root`, a macro-built `bind` path, an escaped identifier, a generate label). **The transitive-instantiator walk this row asked for was implemented and rejected:** a `bind tb.u_wrapper.u_top.u_sub …` in an SVA file that instantiates nothing in the chain has no instantiation edge for any walk to follow — structurally weaker, confirmed by QA. Only inline-module asks for the rung (extract and ports pass `Reach::none()`, unchanged in answer and cost); worst corpus cost 2 % of files on a command, +1.2 ms at the measured site. | extract-inline-module (QA) | lucisv_server / vlog_refactor | | ~~34~~ | ~~**The format cache omits `Config::uvm_utils_indent`.** CLI `args.rs::config_with` applies the key, but `main.rs::entry_for` and core `cache::Entry` serialize/compare only content, line length and indent (plus the store version). On one UVM class: cache a clean verdict with the option false, change only the option to true, then cached `--check` exits 0 while `--no-cache --check` exits 1. Wanted: key/equality/codec coverage for the option and a regression for both toggle directions. Until fixed, use `--no-cache` or delete the format cache after toggling. See repository-analysis.md for the bounded reproduction.~~ — **fixed 2026-09-07 (TODO §59, 0.50.0):** `Entry` carries `uvm_utils_indent`, `entry_for` fills it, the store line has it as a fourth field; a well-formed five-field (0.49.0) line is dropped individually like another version's entry; the audit's probe is `changing_uvm_utils_indent_invalidates_the_entry` in `lucisv/tests/cli.rs`, both directions. | repository audit, 2026-09-07 | lucisv_core / lucisv | +| 35 | **MCP-5 → `vlog_parser`:** lift the server's `expand.rs` (one-step macro expansion) into `vlog_parser::defines` as a pure move so `lucisv-mcp`'s `defines` can offer expansion | mcp-navigation | vlog_parser | +| 36 | **MCP-6 → `lucisv_server` (possible bug):** LSP `references` omits three real `aes` instantiations in the `*_pd_main.sv` tops (and their `.clk_i` connections) that `lucisv-mcp`'s whole-set answer lists; stable after a 30 s settle, not investigated | mcp-navigation | lucisv_server | +| 37 | **MCP-7 → `vlog_refactor`:** a `find_references` variant taking `&dyn KnownFacts` (like `rename_traced_with`) so whole-set callers feed cached records instead of re-parsing 3 944 files (≈2 s per opentitan call today) | mcp-navigation | vlog_refactor | +| 38 | **MCP-8 → `vlog_refactor`:** false `remove_port` refusal when the only "use" of the port is a named connection from another module in the same file (`ports/remove.rs::body_uses_in`) | mcp-edit-tools | vlog_refactor | +| 39 | **MCP-10 → `vlog_refactor`:** `extract_module` writes LF into a CRLF file (`extract/render.rs`) | mcp-edit-tools | vlog_refactor | +| 40 | **MCP-11/12 → `vlog_refactor`/`vlog_semantic`:** a batched `find_references` for several declarations; `find_references` misses a hierarchical use into a generate loop (`gen_l[0].z`) | mcp-structural-edits | vlog_refactor, vlog_semantic | +| 41 | **MCP-13 → `vlog_linter`:** a forced deletion of a non-ANSI body port leaves a header port with no direction and no lint reports it | mcp-structural-edits | vlog_linter | +| 42 | **Parser leniency → `vlog_parser`:** a trailing `,` in a named connection list, an empty concatenation element `{d,, d}`, and `type(x)'(y)` in a connection parse without a diagnostic (the rename verifier's position rule covers the rename; every other splice contract is exposed) | refactor-rename (M3.5) | vlog_parser | ---