From 14b72f286226e5f3fdccc9c07d73b94ad4f75cc6 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 23 Sep 2026 07:24:28 -0700 Subject: [PATCH] =?UTF-8?q?MCP=20M3:=20the=20edit=20tools=20=E2=80=94=20fo?= =?UTF-8?q?rmat,=20fix=5Flint,=20rename,=20the=20port/import/module=20refa?= =?UTF-8?q?ctorings,=20instantiate=20=E2=80=94=20through=20one=20all-or-no?= =?UTF-8?q?thing=20write=20path;=20diff=20printer=20lifted=20to=20lucisv?= =?UTF-8?q?=5Fcore=20(MCP-1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit crates/lucisv_mcp/src/apply.rs is the one write path every edit tool uses: every file's new text is computed first (edits applied last-first; overlap, past-the-end and split-character edits refused), every target must lie inside a root (a created file's directory too, symlinked dirs resolved), every file is re-read and compared byte for byte with the text the plan was computed against before the first write — one mismatch refuses the whole edit — then write_atomic in path order, a failure part-way reported as "written N of M". dry_run returns the unified diff. Tools (tools/{format,edit,refactor}.rs): format (per-file lucisv.toml config, lines ranges, the safety net's refusal names the file, a formatter panic is caught), fix_lint (the diagnostics lint pass, safe fixes only, never inside a lucisv: off fence, refuses a result with more parse errors), rename, expand_wildcard, convert_ports, organize_imports, inline_module, propagate_ports, remove_port, add_port, extract_module (new file or same file), instantiate (text only; instance name validated). Every whole-set tool hands the engine every indexed file read at call time and re-walks the roots first (a file written in the last 5 s is in the set); a file the index skips (over 1 MiB, non-UTF-8) that spells a changed name as a whole word refuses the edit, otherwise it is named once under warnings; references carries the same warning. Annotations from an Effect table (read / edit, idempotent where a second call writes nothing). MCP-1 delivered as a pure move: crates/lucisv/src/diff.rs::unified → lucisv_core::diff::unified, the CLI re-exports it; --diff output byte-identical (QA compared the 82bbba0 binary over the aes copy); lucisv_core still dependency-free. QA (Opus, two rounds + two lead fixes): 38 qa_m3 tests; the write path held under a 50 ms writer race (no torn file in 650 calls), chmod 444, symlinked escapes, a concurrent lucisv --check; format/fix_lint byte-identical to the CLI on CRLF, nested configs, fences and all 124 aes files. Open and OUT of this lane: vlog_refactor::rename leaves .* and .name shorthand connections broken when a port or its bound net is renamed — a pre-existing engine corruption the LSP shares, fixed next in lane M3.5 (TODO-MCP.md); the rename tool says so until then. Engine findings filed: MCP-8 (false remove_port refusal on a same-file instantiation), MCP-10 (extract_module writes LF into a CRLF file). Gates through tools/guard.sh: fmt, clippy, workspace 4 664 passed. Co-Authored-By: Claude Fable 5.1 --- TODO-MCP.md | 45 +- crates/lucisv/src/diff.rs | 221 +-- crates/lucisv_core/src/diff.rs | 221 +++ crates/lucisv_core/src/lib.rs | 4 +- crates/lucisv_mcp/src/apply.rs | 415 +++++ crates/lucisv_mcp/src/main.rs | 1 + crates/lucisv_mcp/src/project/files.rs | 26 +- crates/lucisv_mcp/src/project/mod.rs | 23 +- crates/lucisv_mcp/src/tools/diagnostics.rs | 42 +- crates/lucisv_mcp/src/tools/edit.rs | 283 ++++ crates/lucisv_mcp/src/tools/format.rs | 267 ++++ crates/lucisv_mcp/src/tools/mod.rs | 77 +- crates/lucisv_mcp/src/tools/nav.rs | 44 +- crates/lucisv_mcp/src/tools/refactor.rs | 291 ++++ crates/lucisv_mcp/src/tools/source.rs | 82 +- .../tests/fixtures/edit/fmt/messy.sv | 4 + .../tests/fixtures/edit/rtl/cell.sv | 7 + .../tests/fixtures/edit/rtl/edit_pkg.sv | 4 + .../lucisv_mcp/tests/fixtures/edit/rtl/ext.sv | 9 + .../lucisv_mcp/tests/fixtures/edit/rtl/inl.sv | 9 + .../lucisv_mcp/tests/fixtures/edit/rtl/inv.sv | 6 + .../tests/fixtures/edit/rtl/leaf.sv | 7 + .../lucisv_mcp/tests/fixtures/edit/rtl/mid.sv | 11 + .../lucisv_mcp/tests/fixtures/edit/rtl/old.sv | 6 + .../tests/fixtures/edit/rtl/partial.sv | 7 + .../tests/fixtures/edit/rtl/spare.sv | 7 + .../tests/fixtures/edit/rtl/spare_user.sv | 10 + .../lucisv_mcp/tests/fixtures/edit/rtl/top.sv | 15 + .../tests/fixtures/edit/rtl/wild.sv | 7 + crates/lucisv_mcp/tests/qa_m1.rs | 4 +- crates/lucisv_mcp/tests/qa_m3.rs | 1389 +++++++++++++++++ crates/lucisv_mcp/tests/wire.rs | 328 +++- docs/features/mcp-edit-tools/README.md | 703 +++++++++ 33 files changed, 4271 insertions(+), 304 deletions(-) create mode 100644 crates/lucisv_core/src/diff.rs create mode 100644 crates/lucisv_mcp/src/apply.rs create mode 100644 crates/lucisv_mcp/src/tools/edit.rs create mode 100644 crates/lucisv_mcp/src/tools/format.rs create mode 100644 crates/lucisv_mcp/src/tools/refactor.rs create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/fmt/messy.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/cell.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/edit_pkg.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/ext.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/inl.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/inv.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/leaf.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/mid.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/old.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/partial.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/spare.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/spare_user.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/top.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/edit/rtl/wild.sv create mode 100644 crates/lucisv_mcp/tests/qa_m3.rs create mode 100644 docs/features/mcp-edit-tools/README.md diff --git a/TODO-MCP.md b/TODO-MCP.md index 361972a..42ae51f 100644 --- a/TODO-MCP.md +++ b/TODO-MCP.md @@ -118,34 +118,67 @@ Depends on M1 merged. Handshake MCP-1 (the diff lift) — until MCP-1 lands, `apply.rs` carries a private copy of `unified` marked `// TODO(MCP-1)` and the README says so. -- [ ] `apply.rs`: `RefactorEdit` → (`dry_run`) unified diff per file | the +- [x] `apply.rs`: `RefactorEdit` → (`dry_run`) unified diff per file | the all-computed-then-written loop over `write_atomic`, refusing before the first write on any verifier failure; the summary (files, +/- lines, warnings, created); the "written N of M then failed" report -- [ ] `format` (`files[]` or `file` + `lines`, `dry_run`), `fix_lint` +- [x] `format` (`files[]` or `file` + `lines`, `dry_run`), `fix_lint` (`apply_fixes` through `fence::protected_regions`, safe fixes only), `rename`, `expand_wildcard`, `convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`, `remove_port`, `add_port`, `extract_module` (`home`: new file / same file; the created file is written too), `instantiate` (text only; `style`) — every one with `destructiveHint: false`, `idempotentHint` where true -- [ ] the source-set rule: each refactor gets the whole in-scope file set +- [x] the source-set rule: each refactor gets the whole in-scope file set (PLAN §2.1 — the server narrows; MCP does not, so it can never be narrower than the engine needs); the README states the cost on opentitan and M6 measures it -- [ ] tests: every tool `dry_run` then real on the fixtures; run twice → +- [x] tests: every tool `dry_run` then real on the fixtures; run twice → second run is a no-op with an empty diff; a refusal leaves the fixture tree byte-identical (hash the tree before/after); an `extract_module` into a new file; a rename that touches three files; a `fix_lint` whose finding sits in a format fence (must not touch it) -- [ ] README `mcp-edit-tools`; Handshake MCP-1 filed there with the exact +- [x] README `mcp-edit-tools`; Handshake MCP-1 filed there with the exact move; work log; gates; sizes -- [ ] QA: an edit whose target file changed on disk between the stat +- [x] QA: an edit whose target file changed on disk between the stat sweep and the write (the freshness promise vs the write — the write must be refused, not applied over the newer bytes; the dev states the mechanism); a read-only file; a path through a symlink leaving the root; concurrent `lucisv --check` on the same tree; a CRLF file through `format`; verdict + — done 2026-09-23 (Opus, two rounds + lead fixes): pass for the lane; + the write path held under a 50 ms writer race, chmod 444, symlinked + escapes and a concurrent CLI; `format`/`fix_lint` byte-identical to + the CLI. Findings ruled: skipped files refuse a whole-word match; + whole-set tools re-walk first. **Open, out of lane:** the engine's + rename breaks `.*`/`.name` shorthand connections → M3.5 below. + +## M3.5. Rename vs implicit connections (inserted 2026-09-23 after M3 QA) + +**Files:** `crates/vlog_refactor/src/rename/**`, `crates/vlog_refactor/src/check/**` +only if the verifier must learn the shape, `crates/vlog_refactor/tests/` +(or the crate's test modules), `docs/features/refactor-rename/README.md` +(a dated section), `crates/lucisv_mcp/src/tools/edit.rs` (drop the +known-limit sentence) + `tests/qa_m3.rs` (un-ignore finding 1), `TODO.md` +(one line under the §8 rope-port refactorings noting the fix). An engine +lane: the LSP's rename inherits the fix. + +- [ ] `vlog_refactor::rename` rewrites implicit connections: renaming a port + `p` → `q` turns `.p` into `.q(p)` and adds `.q(p)` beside a `.*` that + bound it (explicit connections beside `.*` are legal); renaming a net + `n` → `m` in a module whose instantiations bind it through `.n` or `.*` + turns `.n` into `.n(m)` and adds `.n(m)` beside the `.*`; comments and + layout of the connection list preserved (append after the last + connection, before the closing paren, on its own line when the list is + one-per-line); every such rewrite listed in `warnings` so the user + sees it; refuse (never guess) when the instantiation's port list + cannot be read (`ifdef`-split, error element) +- [ ] the verifier sees the new edits as intended (no false "moved" + refusal); attack tests: `.*` + explicit of the same port; nested + instances; a `.name` whose net and port differ; a bind instance +- [ ] QA: attack the rewrite on opentitan copies (`prim_fifo_sync` ports + under `.*` users); LSP parity via `vlog_refactor::rename` directly + ## M4. Structural edits (the one new verifier in the block) diff --git a/crates/lucisv/src/diff.rs b/crates/lucisv/src/diff.rs index f31d6f4..a9e6ff6 100644 --- a/crates/lucisv/src/diff.rs +++ b/crates/lucisv/src/diff.rs @@ -1,218 +1,5 @@ -//! A small line-oriented unified diff for `--diff`. -//! -//! The hunks are not a minimal edit script: on a divergence the two -//! sides are resynchronized with a bounded forward search. That keeps -//! the code short and the memory linear, at the cost of occasionally -//! reporting a coarser change than GNU `diff` would. +//! `--diff`'s unified diff. The printer lives in `lucisv_core::diff`, shared +//! with the MCP server's `dry_run` (Handshake MCP-1, a pure move); this module +//! keeps the CLI's `diff::unified` path. -/// Unchanged lines printed around each hunk. -const CONTEXT: usize = 3; -/// Unchanged lines that must line up before the sides count as resynced. -const SYNC_RUN: usize = 3; -/// How far ahead a resynchronization point is searched for. -const MAX_SCAN: usize = 200; -/// Pseudo-line standing in for a missing final newline. -const NO_NEWLINE: &str = "\\ No newline at end of file"; - -#[derive(Clone, Copy, PartialEq)] -enum Tag { - Keep, - Del, - Ins, -} - -/// Renders the changes from `old` to `new` as a unified-style diff. -/// Returns an empty string if the two texts are equal. -pub fn unified(path: &str, old: &str, new: &str) -> String { - if old == new { - return String::new(); - } - let old = split_lines(old); - let new = split_lines(new); - let edits = edits(&old, &new); - let mut out = format!("--- {path}\n+++ {path}\n"); - render_hunks(&edits, &mut out); - out -} - -/// Splits into lines *keeping* each terminator, so a final line with no -/// newline compares unequal to its terminated twin and shows up as a -/// change, exactly as GNU diff treats it. -fn split_lines(text: &str) -> Vec<&str> { - let mut lines = Vec::new(); - let mut rest = text; - while !rest.is_empty() { - let end = rest.find('\n').map_or(rest.len(), |p| p + 1); - lines.push(&rest[..end]); - rest = &rest[end..]; - } - lines -} - -fn edits<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(Tag, &'a str)> { - let mut out = Vec::new(); - let (mut i, mut j) = (0, 0); - while i < old.len() && j < new.len() { - if old[i] == new[j] { - out.push((Tag::Keep, old[i])); - i += 1; - j += 1; - continue; - } - let Some((di, dj)) = resync(old, new, i, j) else { break }; - out.extend(old[i..i + di].iter().map(|l| (Tag::Del, *l))); - out.extend(new[j..j + dj].iter().map(|l| (Tag::Ins, *l))); - i += di; - j += dj; - } - out.extend(old[i..].iter().map(|l| (Tag::Del, *l))); - out.extend(new[j..].iter().map(|l| (Tag::Ins, *l))); - out -} - -/// Finds the smallest pair of skip counts that puts the two sides back -/// in step, preferring the shortest total divergence. -fn resync(old: &[&str], new: &[&str], i: usize, j: usize) -> Option<(usize, usize)> { - for d in 1..=MAX_SCAN { - for k in 0..=d { - for (di, dj) in [(d, k), (k, d)] { - if i + di <= old.len() && j + dj <= new.len() && in_step(old, new, i + di, j + dj) { - return Some((di, dj)); - } - } - } - } - None -} - -fn in_step(old: &[&str], new: &[&str], i: usize, j: usize) -> bool { - let available = (old.len() - i).min(new.len() - j); - if available == 0 { - // Both sides running out together is a valid resync point. - return old.len() - i == new.len() - j; - } - (0..SYNC_RUN.min(available)).all(|k| old[i + k] == new[j + k]) -} - -fn render_hunks(edits: &[(Tag, &str)], out: &mut String) { - // Line numbers each edit occupies on the old and the new side. - let mut rows = Vec::with_capacity(edits.len()); - let (mut old_no, mut new_no) = (1usize, 1usize); - for &(tag, text) in edits { - rows.push((tag, text, old_no, new_no)); - match tag { - Tag::Keep => { - old_no += 1; - new_no += 1; - } - Tag::Del => old_no += 1, - Tag::Ins => new_no += 1, - } - } - - let mut start = 0; - while start < rows.len() { - let Some(first) = (start..rows.len()).find(|&r| rows[r].0 != Tag::Keep) else { break }; - let mut last = first; - // Extend while the next change is close enough that its context - // would touch this hunk's. - loop { - let reach = (last + 2 * CONTEXT + 1).min(rows.len()); - match (last + 1..reach).find(|&r| rows[r].0 != Tag::Keep) { - Some(next) => last = next, - None => break, - } - } - let from = first.saturating_sub(CONTEXT); - let to = (last + CONTEXT + 1).min(rows.len()); - render_one_hunk(&rows[from..to], out); - start = to; - } -} - -fn render_one_hunk(rows: &[(Tag, &str, usize, usize)], out: &mut String) { - let old_count = rows.iter().filter(|r| r.0 != Tag::Ins).count(); - let new_count = rows.iter().filter(|r| r.0 != Tag::Del).count(); - let (old_start, new_start) = (rows[0].2, rows[0].3); - out.push_str(&format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n")); - for &(tag, text, _, _) in rows { - let sign = match tag { - Tag::Keep => ' ', - Tag::Del => '-', - Tag::Ins => '+', - }; - out.push(sign); - match text.strip_suffix('\n') { - Some(body) => { - out.push_str(body); - out.push('\n'); - } - None => { - // patch(1) expects the marker bare, on its own line, - // directly after the unterminated line. - out.push_str(text); - out.push('\n'); - out.push_str(NO_NEWLINE); - out.push('\n'); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn equal_texts_produce_nothing() { - assert_eq!(unified("f.sv", "a\nb\n", "a\nb\n"), ""); - } - - #[test] - fn single_line_change_keeps_context() { - let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n"; - let new = "1\n2\n3\n4\nX\n6\n7\n8\n9\n"; - let d = unified("f.sv", old, new); - assert!(d.starts_with("--- f.sv\n+++ f.sv\n@@ -2,7 +2,7 @@\n"), "{d}"); - assert!(d.contains("\n-5\n+X\n"), "{d}"); - // Context is bounded: the first and last lines stay out of it. - assert!(!d.contains("\n 1\n"), "{d}"); - assert!(!d.contains("\n 9\n"), "{d}"); - } - - #[test] - fn distant_changes_become_separate_hunks() { - let old: String = (0..40).map(|i| format!("{i}\n")).collect(); - let new = old.replace("\n1\n", "\nX\n").replace("\n30\n", "\nY\n"); - let d = unified("f.sv", &old, &new); - assert_eq!(d.matches("@@ ").count(), 2, "{d}"); - assert!(d.contains("-1\n+X\n") && d.contains("-30\n+Y\n"), "{d}"); - } - - #[test] - fn insertions_and_deletions_are_reported_separately() { - let d = unified("f.sv", "a\nb\nc\n", "a\nb\nb2\nc\n"); - assert!(d.contains("+b2\n"), "{d}"); - assert!(!d.contains("-b\n"), "{d}"); - - let d = unified("f.sv", "a\nb\nc\nd\n", "a\nc\nd\n"); - assert!(d.contains("-b\n"), "{d}"); - // No insertions in the hunk body (the `+++` header line aside). - assert!(!d.lines().skip(2).any(|l| l.starts_with('+')), "{d}"); - } - - #[test] - fn missing_final_newline_matches_patch_format() { - // The unterminated line is the change; the marker follows it bare. - let d = unified("f.sv", "a\nb", "a\nb\n"); - assert!(d.contains("-b\n\\ No newline at end of file\n+b\n"), "{d}"); - let d = unified("f.sv", "a\nb\n", "a\nb"); - assert!(d.contains("-b\n+b\n\\ No newline at end of file\n"), "{d}"); - } - - #[test] - fn wholly_different_texts_diff_as_replacement() { - let d = unified("f.sv", "a\nb\n", "x\ny\n"); - assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}"); - } -} +pub use lucisv_core::diff::unified; diff --git a/crates/lucisv_core/src/diff.rs b/crates/lucisv_core/src/diff.rs new file mode 100644 index 0000000..0d595b7 --- /dev/null +++ b/crates/lucisv_core/src/diff.rs @@ -0,0 +1,221 @@ +//! A small line-oriented unified diff: the CLI's `--diff` and the MCP +//! server's `dry_run` print the same hunks through this one function. +//! Moved here from `crates/lucisv/src/diff.rs` unchanged (Handshake MCP-1, +//! `docs/features/mcp-edit-tools/README.md`); the CLI re-exports it. +//! +//! The hunks are not a minimal edit script: on a divergence the two +//! sides are resynchronized with a bounded forward search. That keeps +//! the code short and the memory linear, at the cost of occasionally +//! reporting a coarser change than GNU `diff` would. + +/// Unchanged lines printed around each hunk. +const CONTEXT: usize = 3; +/// Unchanged lines that must line up before the sides count as resynced. +const SYNC_RUN: usize = 3; +/// How far ahead a resynchronization point is searched for. +const MAX_SCAN: usize = 200; +/// Pseudo-line standing in for a missing final newline. +const NO_NEWLINE: &str = "\\ No newline at end of file"; + +#[derive(Clone, Copy, PartialEq)] +enum Tag { + Keep, + Del, + Ins, +} + +/// Renders the changes from `old` to `new` as a unified-style diff. +/// Returns an empty string if the two texts are equal. +pub fn unified(path: &str, old: &str, new: &str) -> String { + if old == new { + return String::new(); + } + let old = split_lines(old); + let new = split_lines(new); + let edits = edits(&old, &new); + let mut out = format!("--- {path}\n+++ {path}\n"); + render_hunks(&edits, &mut out); + out +} + +/// Splits into lines *keeping* each terminator, so a final line with no +/// newline compares unequal to its terminated twin and shows up as a +/// change, exactly as GNU diff treats it. +fn split_lines(text: &str) -> Vec<&str> { + let mut lines = Vec::new(); + let mut rest = text; + while !rest.is_empty() { + let end = rest.find('\n').map_or(rest.len(), |p| p + 1); + lines.push(&rest[..end]); + rest = &rest[end..]; + } + lines +} + +fn edits<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(Tag, &'a str)> { + let mut out = Vec::new(); + let (mut i, mut j) = (0, 0); + while i < old.len() && j < new.len() { + if old[i] == new[j] { + out.push((Tag::Keep, old[i])); + i += 1; + j += 1; + continue; + } + let Some((di, dj)) = resync(old, new, i, j) else { break }; + out.extend(old[i..i + di].iter().map(|l| (Tag::Del, *l))); + out.extend(new[j..j + dj].iter().map(|l| (Tag::Ins, *l))); + i += di; + j += dj; + } + out.extend(old[i..].iter().map(|l| (Tag::Del, *l))); + out.extend(new[j..].iter().map(|l| (Tag::Ins, *l))); + out +} + +/// Finds the smallest pair of skip counts that puts the two sides back +/// in step, preferring the shortest total divergence. +fn resync(old: &[&str], new: &[&str], i: usize, j: usize) -> Option<(usize, usize)> { + for d in 1..=MAX_SCAN { + for k in 0..=d { + for (di, dj) in [(d, k), (k, d)] { + if i + di <= old.len() && j + dj <= new.len() && in_step(old, new, i + di, j + dj) { + return Some((di, dj)); + } + } + } + } + None +} + +fn in_step(old: &[&str], new: &[&str], i: usize, j: usize) -> bool { + let available = (old.len() - i).min(new.len() - j); + if available == 0 { + // Both sides running out together is a valid resync point. + return old.len() - i == new.len() - j; + } + (0..SYNC_RUN.min(available)).all(|k| old[i + k] == new[j + k]) +} + +fn render_hunks(edits: &[(Tag, &str)], out: &mut String) { + // Line numbers each edit occupies on the old and the new side. + let mut rows = Vec::with_capacity(edits.len()); + let (mut old_no, mut new_no) = (1usize, 1usize); + for &(tag, text) in edits { + rows.push((tag, text, old_no, new_no)); + match tag { + Tag::Keep => { + old_no += 1; + new_no += 1; + } + Tag::Del => old_no += 1, + Tag::Ins => new_no += 1, + } + } + + let mut start = 0; + while start < rows.len() { + let Some(first) = (start..rows.len()).find(|&r| rows[r].0 != Tag::Keep) else { break }; + let mut last = first; + // Extend while the next change is close enough that its context + // would touch this hunk's. + loop { + let reach = (last + 2 * CONTEXT + 1).min(rows.len()); + match (last + 1..reach).find(|&r| rows[r].0 != Tag::Keep) { + Some(next) => last = next, + None => break, + } + } + let from = first.saturating_sub(CONTEXT); + let to = (last + CONTEXT + 1).min(rows.len()); + render_one_hunk(&rows[from..to], out); + start = to; + } +} + +fn render_one_hunk(rows: &[(Tag, &str, usize, usize)], out: &mut String) { + let old_count = rows.iter().filter(|r| r.0 != Tag::Ins).count(); + let new_count = rows.iter().filter(|r| r.0 != Tag::Del).count(); + let (old_start, new_start) = (rows[0].2, rows[0].3); + out.push_str(&format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n")); + for &(tag, text, _, _) in rows { + let sign = match tag { + Tag::Keep => ' ', + Tag::Del => '-', + Tag::Ins => '+', + }; + out.push(sign); + match text.strip_suffix('\n') { + Some(body) => { + out.push_str(body); + out.push('\n'); + } + None => { + // patch(1) expects the marker bare, on its own line, + // directly after the unterminated line. + out.push_str(text); + out.push('\n'); + out.push_str(NO_NEWLINE); + out.push('\n'); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn equal_texts_produce_nothing() { + assert_eq!(unified("f.sv", "a\nb\n", "a\nb\n"), ""); + } + + #[test] + fn single_line_change_keeps_context() { + let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n"; + let new = "1\n2\n3\n4\nX\n6\n7\n8\n9\n"; + let d = unified("f.sv", old, new); + assert!(d.starts_with("--- f.sv\n+++ f.sv\n@@ -2,7 +2,7 @@\n"), "{d}"); + assert!(d.contains("\n-5\n+X\n"), "{d}"); + // Context is bounded: the first and last lines stay out of it. + assert!(!d.contains("\n 1\n"), "{d}"); + assert!(!d.contains("\n 9\n"), "{d}"); + } + + #[test] + fn distant_changes_become_separate_hunks() { + let old: String = (0..40).map(|i| format!("{i}\n")).collect(); + let new = old.replace("\n1\n", "\nX\n").replace("\n30\n", "\nY\n"); + let d = unified("f.sv", &old, &new); + assert_eq!(d.matches("@@ ").count(), 2, "{d}"); + assert!(d.contains("-1\n+X\n") && d.contains("-30\n+Y\n"), "{d}"); + } + + #[test] + fn insertions_and_deletions_are_reported_separately() { + let d = unified("f.sv", "a\nb\nc\n", "a\nb\nb2\nc\n"); + assert!(d.contains("+b2\n"), "{d}"); + assert!(!d.contains("-b\n"), "{d}"); + + let d = unified("f.sv", "a\nb\nc\nd\n", "a\nc\nd\n"); + assert!(d.contains("-b\n"), "{d}"); + // No insertions in the hunk body (the `+++` header line aside). + assert!(!d.lines().skip(2).any(|l| l.starts_with('+')), "{d}"); + } + + #[test] + fn missing_final_newline_matches_patch_format() { + // The unterminated line is the change; the marker follows it bare. + let d = unified("f.sv", "a\nb", "a\nb\n"); + assert!(d.contains("-b\n\\ No newline at end of file\n+b\n"), "{d}"); + let d = unified("f.sv", "a\nb\n", "a\nb"); + assert!(d.contains("-b\n+b\n\\ No newline at end of file\n"), "{d}"); + } + + #[test] + fn wholly_different_texts_diff_as_replacement() { + let d = unified("f.sv", "a\nb\n", "x\ny\n"); + assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}"); + } +} diff --git a/crates/lucisv_core/src/lib.rs b/crates/lucisv_core/src/lib.rs index 2de0033..cfe5a57 100644 --- a/crates/lucisv_core/src/lib.rs +++ b/crates/lucisv_core/src/lib.rs @@ -8,7 +8,8 @@ //! needs to be processed at all, and `filelist` answers the first one the way //! an EDA project already does, from a `.f` file. `atomic` is the one write //! path all of them share: nothing here ever truncates a file it is -//! replacing. See +//! replacing. `diff` is the unified diff the CLI's `--diff` and the MCP +//! server's `dry_run` both print. See //! `docs/features/lucisv-core-lift/README.md`, and //! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md` //! for the rules themselves. @@ -16,5 +17,6 @@ pub mod atomic; pub mod cache; pub mod config; +pub mod diff; pub mod filelist; pub mod walk; diff --git a/crates/lucisv_mcp/src/apply.rs b/crates/lucisv_mcp/src/apply.rs new file mode 100644 index 0000000..dc0ceab --- /dev/null +++ b/crates/lucisv_mcp/src/apply.rs @@ -0,0 +1,415 @@ +//! The one write path every edit tool goes through. +//! +//! A tool hands over a [`Plan`] — per file, the text it computed against and +//! the text it wants written — and gets back either the unified diff +//! (`dry_run`) or a summary of what was written. The write is all-or-nothing +//! as far as a filesystem allows: every file's new text exists before the +//! first write; every target is checked to lie inside a root; every file is +//! re-read and compared with the text the plan was computed against, and a +//! file that moved since refuses the **whole** edit before anything is +//! written (the write-freshness rule); then each file goes through +//! `write_atomic`, in path order. A write that fails after others landed is +//! reported as such — "written N of M" — which is the CLI's posture. +//! See `docs/features/mcp-edit-tools/README.md`. + +use std::fs; +use std::path::{Path, PathBuf}; + +use lucisv_core::atomic::write_atomic; +use lucisv_core::diff::unified; +use serde_json::{json, Value}; +use vlog_refactor::{RefactorEdit, TextEdit}; + +use crate::project::Project; +use crate::tools::Answer; + +/// One file an edit rewrites or creates. +pub struct Change { + /// The canonical path of the file. + pub path: PathBuf, + /// The text the edit was computed against; empty for a created file. + pub before: String, + /// The text to write. + pub after: String, + /// Whether the file does not exist yet and the edit creates it. + pub created: bool, +} + +/// Everything one edit tool wants written, and what it has to say. +#[derive(Default)] +pub struct Plan { + /// The files to write, in any order. + pub changes: Vec, + /// Files the tool looked at and left as they were (`format`, `fix_lint`). + pub unchanged: Vec, + /// The engine's sentences about what it deliberately left alone. + pub warnings: Vec, + /// One line the tool adds to the summary (`fix_lint`'s rules), if any. + pub note: Option, +} + +impl Plan { + /// A refactoring's edit, over the texts it was computed against. A file + /// the edit names but `texts` does not hold, and an edit that does not + /// fit its file, refuse the whole plan. + pub fn from_refactor(edit: RefactorEdit, texts: &[(PathBuf, String)]) -> Result { + let mut plan = Plan { warnings: edit.warnings, ..Plan::default() }; + for (path, edits) in edit.edits { + let created = edit.created.contains(&path); + let before = match texts.iter().find(|(held, _)| *held == path) { + Some((_, text)) => text.clone(), + None if created => String::new(), + None => { + return Err(format!("the edit names `{}`, which was not read", path.display())) + } + }; + let after = apply_edits(&before, &edits) + .map_err(|why| format!("the edit does not fit `{}`: {why}", path.display()))?; + plan.changes.push(Change { path, before, after, created }); + } + Ok(plan) + } +} + +/// `text` with `edits` applied, last first so every offset still points at +/// the bytes it was computed for. Overlapping edits, an edit past the end +/// and one splitting a UTF-8 character are refused, never guessed at. +fn apply_edits(text: &str, edits: &[TextEdit]) -> Result { + let mut sorted: Vec<&TextEdit> = edits.iter().collect(); + sorted.sort_by_key(|edit| (edit.range.start, edit.range.end)); + for pair in sorted.windows(2) { + if pair[1].range.start < pair[0].range.end { + return Err(format!("two edits overlap at byte {}", pair[1].range.start)); + } + } + let mut out = text.to_string(); + for edit in sorted.iter().rev() { + let (start, end) = (edit.range.start as usize, edit.range.end as usize); + if start > end || end > out.len() { + return Err(format!("an edit ends at byte {end}, past the end ({})", out.len())); + } + if !out.is_char_boundary(start) || !out.is_char_boundary(end) { + return Err(format!("an edit at byte {start} splits a character")); + } + out.replace_range(start..end, &edit.new_text); + } + Ok(out) +} + +/// Check, then diff or write, then summarise. `dry_run` writes nothing. +pub fn run(project: &Project, plan: Plan, dry_run: bool) -> Result { + for change in &plan.changes { + contained(project, change)?; + } + let mut moved: Vec<&Change> = + plan.changes.iter().filter(|c| c.created || c.before != c.after).collect(); + moved.sort_by(|a, b| a.path.cmp(&b.path)); + let mut unchanged: Vec = plan + .changes + .iter() + .filter(|c| !c.created && c.before == c.after) + .map(|c| project.relative(&c.path)) + .chain(plan.unchanged.iter().map(|path| project.relative(path))) + .collect(); + unchanged.sort(); + let files: Vec = moved.iter().map(|change| Written::of(project, change)).collect(); + if !dry_run { + commit(&moved, |path| project.relative(path))?; + } + Ok(summary(&files, &unchanged, &plan, dry_run)) +} + +/// A target must lie inside a root: an existing file resolves into one; a +/// created file's directory does, and nothing is at its path yet. +fn contained(project: &Project, change: &Change) -> Result<(), String> { + let shown = change.path.display(); + let inside = |dir: Option| { + dir.is_some_and(|dir| project.roots().iter().any(|root| dir.starts_with(root))) + }; + if !change.created { + let Ok(real) = fs::canonicalize(&change.path) else { + return Err(format!("`{shown}` no longer exists; nothing written.")); + }; + if !inside(Some(real)) { + return Err(format!( + "`{shown}` is outside every root; lucisv-mcp only writes inside its roots." + )); + } + return Ok(()); + } + if !inside(change.path.parent().and_then(|dir| fs::canonicalize(dir).ok())) { + return Err(format!( + "`{shown}` would be created outside every root; lucisv-mcp only writes inside its roots." + )); + } + if fs::symlink_metadata(&change.path).is_ok() { + return Err(format!( + "`{}` already exists; nothing written.", + project.relative(&change.path) + )); + } + Ok(()) +} + +/// Write every change, or none when any target moved since it was read. +/// +/// First every file is re-read and compared byte for byte with the text the +/// plan was computed against (a created file must still not exist, a +/// read-only one is refused as `write_atomic` would refuse it); one mismatch +/// refuses the whole edit before the first write. Then each file is +/// written with `write_atomic`, in the order given. A failure part-way is +/// reported with what was already written. +pub fn commit(changes: &[&Change], shown: impl Fn(&Path) -> String) -> Result<(), String> { + for change in changes { + let name = shown(&change.path); + if change.created { + if fs::symlink_metadata(&change.path).is_ok() { + return Err(format!("`{name}` already exists; nothing written.")); + } + continue; + } + if fs::metadata(&change.path).is_ok_and(|meta| meta.permissions().readonly()) { + return Err(format!("`{name}` is read-only; nothing written.")); + } + match fs::read(&change.path) { + Ok(bytes) if bytes == change.before.as_bytes() => {} + Ok(_) => { + return Err(format!("`{name}` changed on disk since it was read; nothing written.")) + } + Err(e) => return Err(format!("`{name}` cannot be read again ({e}); nothing written.")), + } + } + let mut done: Vec = Vec::new(); + for change in changes { + let name = shown(&change.path); + if let Err(e) = write_atomic(&change.path, change.after.as_bytes()) { + let list = if done.is_empty() { "nothing".to_string() } else { done.join(", ") }; + return Err(format!( + "written {} of {}: {list}; failed on `{name}`: {e}", + done.len(), + changes.len() + )); + } + done.push(name); + } + Ok(()) +} + +/// One file of the summary: its name, its diff and the lines it moves. +struct Written { + file: String, + created: bool, + diff: String, + added: usize, + removed: usize, +} + +impl Written { + fn of(project: &Project, change: &Change) -> Written { + let file = project.relative(&change.path); + let diff = unified(&file, &change.before, &change.after); + // The two header lines are `---`/`+++`; every later line starting + // with a sign is one line of the change. + let body = diff.lines().skip(2); + let added = body.clone().filter(|line| line.starts_with('+')).count(); + let removed = body.filter(|line| line.starts_with('-')).count(); + Written { file, created: change.created, diff, added, removed } + } +} + +/// The text and JSON an edit answers with. +fn summary(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Answer { + let created = files.iter().filter(|f| f.created).count(); + let mut text = if files.is_empty() { + "unchanged\n".to_string() + } else { + let tail = if dry_run { " (dry run: nothing written)" } else { "" }; + format!("files: {} changed, {created} created{tail}\n", files.len() - created) + }; + for file in files { + let mark = if file.created { " (created)" } else { "" }; + text.push_str(&format!(" {} +{} -{}{mark}\n", file.file, file.added, file.removed)); + } + if !unchanged.is_empty() && !files.is_empty() { + text.push_str(&format!("unchanged: {}\n", unchanged.join(", "))); + } + if let Some(note) = &plan.note { + text.push_str(note); + text.push('\n'); + } + push_warnings(&mut text, &plan.warnings); + if dry_run { + files.iter().for_each(|file| text.push_str(&file.diff)); + } + Answer { text, structured: structured(files, unchanged, plan, dry_run) } +} + +fn push_warnings(text: &mut String, warnings: &[String]) { + if warnings.is_empty() { + return; + } + text.push_str("warnings:\n"); + for warning in warnings { + text.push_str(&format!(" {warning}\n")); + } +} + +fn structured(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Value { + let entry = |file: &Written| { + let mut entry = json!({ "file": file.file, "added": file.added, "removed": file.removed }); + if dry_run { + entry["diff"] = Value::from(file.diff.clone()); + } + entry + }; + let changed: Vec = files.iter().filter(|f| !f.created).map(entry).collect(); + let created: Vec = files.iter().filter(|f| f.created).map(entry).collect(); + json!({ + "changed": changed, + "created": created, + "unchanged": unchanged, + "warnings": plan.warnings, + "note": plan.note, + "dry_run": dry_run, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_parser::span::TextRange; + + fn scratch(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("lucisv-mcp-apply-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + fs::canonicalize(dir).unwrap() + } + + fn edit(start: u32, end: u32, text: &str) -> TextEdit { + TextEdit { range: TextRange::new(start, end), new_text: text.to_string() } + } + + fn change(path: &Path, before: &str, after: &str) -> Change { + Change { + path: path.to_path_buf(), + before: before.into(), + after: after.into(), + created: false, + } + } + + fn name(path: &Path) -> String { + path.file_name().unwrap().to_string_lossy().into_owned() + } + + #[test] + fn edits_apply_last_first_and_a_misfit_is_refused() { + let edits = [edit(8, 11, "xyz!"), edit(0, 3, "q")]; + assert_eq!(apply_edits("abc def abc", &edits).unwrap(), "q def xyz!"); + assert_eq!(apply_edits("abc", &[edit(3, 3, "d")]).unwrap(), "abcd"); + assert!(apply_edits("abcdef", &[edit(0, 3, "x"), edit(2, 4, "y")]).is_err()); + assert!(apply_edits("abc", &[edit(2, 9, "x")]).is_err()); + assert!(apply_edits("é", &[edit(1, 2, "x")]).unwrap_err().contains("splits")); + } + + #[test] + fn a_file_that_moved_since_it_was_read_refuses_every_write() { + let dir = scratch("stale"); + let (a, b) = (dir.join("a.sv"), dir.join("b.sv")); + fs::write(&a, "module a; endmodule\n").unwrap(); + fs::write(&b, "module b; endmodule // edited meanwhile\n").unwrap(); + let first = change(&a, "module a; endmodule\n", "module a2; endmodule\n"); + let second = change(&b, "module b; endmodule\n", "module b2; endmodule\n"); + let refused = commit(&[&first, &second], name).unwrap_err(); + assert_eq!(refused, "`b.sv` changed on disk since it was read; nothing written."); + // The first file, whose bytes still matched, was not written either. + assert_eq!(fs::read_to_string(&a).unwrap(), "module a; endmodule\n"); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_created_file_that_appeared_meanwhile_is_refused_and_a_fresh_edit_lands() { + let dir = scratch("create"); + let a = dir.join("a.sv"); + fs::write(&a, "module a; endmodule\n").unwrap(); + let taken = dir.join("n.sv"); + fs::write(&taken, "// someone else's\n").unwrap(); + let edit = change(&a, "module a; endmodule\n", "module a; n u_n (); endmodule\n"); + let new = + Change { path: taken.clone(), before: String::new(), after: "x".into(), created: true }; + let refused = commit(&[&edit, &new], name).unwrap_err(); + assert_eq!(refused, "`n.sv` already exists; nothing written."); + assert_eq!(fs::read_to_string(&a).unwrap(), "module a; endmodule\n"); + fs::remove_file(&taken).unwrap(); + commit(&[&edit, &new], name).unwrap(); + assert_eq!(fs::read_to_string(&a).unwrap(), "module a; n u_n (); endmodule\n"); + assert_eq!(fs::read_to_string(&taken).unwrap(), "x"); + fs::remove_dir_all(dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn a_write_that_fails_after_another_landed_says_what_was_written() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("partial"); + let shut = dir.join("shut"); + fs::create_dir(&shut).unwrap(); + let (a, b) = (dir.join("a.sv"), shut.join("b.sv")); + fs::write(&a, "a\n").unwrap(); + fs::write(&b, "b\n").unwrap(); + // A read-only file is refused before any write … + fs::set_permissions(&b, fs::Permissions::from_mode(0o444)).unwrap(); + let (first, second) = (change(&a, "a\n", "a2\n"), change(&b, "b\n", "b2\n")); + let refused = commit(&[&first, &second], name).unwrap_err(); + assert_eq!(refused, "`b.sv` is read-only; nothing written."); + assert_eq!(fs::read_to_string(&a).unwrap(), "a\n"); + // … but a directory that will not take the temp file fails only at + // the write, after `a.sv` landed: said, not hidden. + fs::set_permissions(&b, fs::Permissions::from_mode(0o644)).unwrap(); + fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap(); + let refused = commit(&[&first, &second], name).unwrap_err(); + fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(refused.starts_with("written 1 of 2: a.sv; failed on `b.sv`: "), "{refused}"); + assert_eq!(fs::read_to_string(&a).unwrap(), "a2\n"); + assert_eq!(fs::read_to_string(&b).unwrap(), "b\n"); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_target_outside_every_root_is_refused_and_nothing_is_written() { + let dir = scratch("roots"); + let (root, outside) = (dir.join("root"), dir.join("outside")); + fs::create_dir(&root).unwrap(); + fs::create_dir(&outside).unwrap(); + fs::write(root.join("a.sv"), "module a; endmodule\n").unwrap(); + fs::write(outside.join("b.sv"), "module b; endmodule\n").unwrap(); + let project = Project::open(vec![root.clone()], None); + let create = |path: PathBuf| Change { + path, + before: String::new(), + after: "module n; endmodule\n".into(), + created: true, + }; + let refuse = |change: Change| { + let plan = Plan { changes: vec![change], ..Plan::default() }; + run(&project, plan, false).err().unwrap() + }; + let beside = refuse(create(outside.join("n.sv"))); + assert!(beside.contains("would be created outside every root"), "{beside}"); + #[cfg(unix)] + { + // A directory inside the root that is a symlink leading out. + std::os::unix::fs::symlink(&outside, root.join("link")).unwrap(); + let through = refuse(create(root.join("link").join("n.sv"))); + assert!(through.contains("outside every root"), "{through}"); + } + let existing = outside.join("b.sv"); + let rewritten = refuse(change(&existing, "module b; endmodule\n", "module c; endmodule\n")); + assert!(rewritten.contains("outside every root"), "{rewritten}"); + assert!(!outside.join("n.sv").exists()); + assert_eq!(fs::read_to_string(&existing).unwrap(), "module b; endmodule\n"); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/lucisv_mcp/src/main.rs b/crates/lucisv_mcp/src/main.rs index df93c07..72edf75 100644 --- a/crates/lucisv_mcp/src/main.rs +++ b/crates/lucisv_mcp/src/main.rs @@ -7,6 +7,7 @@ //! with `lucisv-server` or the `lucisv` CLI. See `docs/mcp/PLAN.md` and //! `docs/features/mcp-transport/README.md`. +mod apply; mod project; mod render; mod resources; diff --git a/crates/lucisv_mcp/src/project/files.rs b/crates/lucisv_mcp/src/project/files.rs index 96205ac..22563d9 100644 --- a/crates/lucisv_mcp/src/project/files.rs +++ b/crates/lucisv_mcp/src/project/files.rs @@ -33,6 +33,9 @@ pub struct FileSet { pub warnings: Vec, /// Walked files skipped for being over [`MAX_FILE_BYTES`]. pub skipped_large: usize, + /// Those files' canonical paths: an edit tool must know which files it + /// could not read (`docs/features/mcp-edit-tools`, QA finding 2). + pub skipped: Vec, } /// Find the project's files: the filelist (`--filelist`, else the first @@ -97,17 +100,17 @@ fn walk_root(root: &Path, roots: &[PathBuf], set: &mut FileSet) { } set.warnings.extend(warnings); for (path, size) in found { - if size.unwrap_or(0) > MAX_FILE_BYTES { + let Some(path) = canonical(&path) else { continue }; + if !roots.iter().any(|root| path.starts_with(root)) { + set.warnings.push(format!( + "{}: outside every root (reached through a symlink); not indexed", + path.display() + )); + } else if size.unwrap_or(0) > MAX_FILE_BYTES { set.skipped_large += 1; - } else if let Some(path) = canonical(&path) { - if roots.iter().any(|root| path.starts_with(root)) { - set.files.push(path); - } else { - set.warnings.push(format!( - "{}: outside every root (reached through a symlink); not indexed", - path.display() - )); - } + set.skipped.push(path); + } else { + set.files.push(path); } } } @@ -115,6 +118,8 @@ fn walk_root(root: &Path, roots: &[PathBuf], set: &mut FileSet) { fn finish(mut set: FileSet) -> FileSet { set.files.sort(); set.files.dedup(); + set.skipped.sort(); + set.skipped.dedup(); set } @@ -241,6 +246,7 @@ mod tests { let set = discover(std::slice::from_ref(&dir), None); assert_eq!(set.files, vec![dir.join("a.sv")]); assert_eq!(set.skipped_large, 1); + assert_eq!(set.skipped, vec![dir.join("big.sv")]); fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/lucisv_mcp/src/project/mod.rs b/crates/lucisv_mcp/src/project/mod.rs index b79f8a1..f62c144 100644 --- a/crates/lucisv_mcp/src/project/mod.rs +++ b/crates/lucisv_mcp/src/project/mod.rs @@ -48,9 +48,9 @@ pub struct Project { walked_at: Instant, updated_at: Instant, build: Duration, - /// Discovered files that are not UTF-8 text, as `path: why`, recomputed - /// by every walk. - unreadable: Vec, + /// Discovered files that are not UTF-8 text, with why, recomputed by + /// every walk. + unreadable: Vec<(PathBuf, String)>, /// 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, @@ -98,7 +98,7 @@ impl Project { files.insert(path.clone(), stamp); } Err(problem) => { - unreadable.push(format!("{}: {problem}", relative_to(&roots, path))); + unreadable.push((path.clone(), problem.to_string())); } } } @@ -194,7 +194,7 @@ impl Project { self.files.insert(path.clone(), stamp); added += 1; } - Err(problem) => unreadable.push(format!("{}: {problem}", self.relative(path))), + Err(problem) => unreadable.push((path.clone(), problem.to_string())), } } self.unreadable = unreadable; @@ -245,8 +245,17 @@ impl Project { } /// Files discovery found but could not read as UTF-8 text. - pub fn unreadable(&self) -> &[String] { - &self.unreadable + pub fn unreadable(&self) -> Vec { + let shown = |(path, why): &(PathBuf, String)| format!("{}: {why}", self.relative(path)); + self.unreadable.iter().map(shown).collect() + } + + /// Every discovered file the index does not hold, with why: over the + /// size cap, or not UTF-8 text. An edit over the whole set must not + /// pretend these were searched. + pub fn skipped(&self) -> Vec<(PathBuf, String)> { + let large = self.walk.skipped.iter().map(|path| (path.clone(), "over 1 MiB".to_string())); + large.chain(self.unreadable.iter().cloned()).collect() } /// How long the startup build took, and how long ago the index last diff --git a/crates/lucisv_mcp/src/tools/diagnostics.rs b/crates/lucisv_mcp/src/tools/diagnostics.rs index 25adab0..f9e71e6 100644 --- a/crates/lucisv_mcp/src/tools/diagnostics.rs +++ b/crates/lucisv_mcp/src/tools/diagnostics.rs @@ -81,7 +81,7 @@ struct Finding { } /// What one config file makes of a lint run. -struct Run { +pub(super) struct Run { rules: Vec<&'static dyn Rule>, options: RuleOptions, waivers: ExternalWaivers, @@ -95,14 +95,14 @@ fn diagnostics(project: &mut Project, args: &Args) -> Result { let selected: Option> = args.str("rules").map(|rules| { rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect() }); - let mut runs = Runs { discovery: Discovery::new(true), held: BTreeMap::new(), selected }; + let mut runs = Runs::new(selected); let mut findings = Vec::new(); match args.str("file") { Some(file) => { let path = project.resolve(file)?; let analysis = project.analysis(&path)?; let own = project.index().file_id(&path); - let oracle = Mentions { index: project.index(), census: None, own }; + let oracle = Mentions::of_file(project.index(), own); findings = file_findings(project, &mut runs, &path, &analysis, &oracle)?; } None => { @@ -125,18 +125,24 @@ fn diagnostics(project: &mut Project, args: &Args) -> Result { Ok(render_findings(&findings, args)) } -/// The runs met so far in one call, one per governing config file. -struct Runs { +/// The runs met so far in one call, one per governing config file — shared +/// with `fix_lint`, so a fix runs under exactly the rules a finding came from. +pub(super) struct Runs { discovery: Discovery, held: BTreeMap, Rc>, selected: Option>, } impl Runs { + /// No run built yet; `selected` replaces each config's `[lint] select`. + pub(super) fn new(selected: Option>) -> Runs { + Runs { discovery: Discovery::new(true), held: BTreeMap::new(), selected } + } + /// The run for the config governing `path`, built on first use. A config /// that does not read, an unknown rule, a bad option or an unreadable /// waiver file is a refusal naming it — `lucisv check` fails the same way. - fn for_file(&mut self, path: &Path) -> Result, String> { + pub(super) fn for_file(&mut self, path: &Path) -> Result, String> { let config = self.discovery.for_file(path)?; if let Some(run) = self.held.get(&config.source) { return Ok(Rc::clone(run)); @@ -224,6 +230,18 @@ fn file_findings( fix: Value::Null, }) .collect(); + let violations = violations(&run, path, analysis, oracle); + out.extend(violations.iter().map(|violation| lint_finding(&file, &analysis.lines, violation))); + Ok(out) +} + +/// One file's lint findings under `run`, its waivers applied. +pub(super) fn violations( + run: &Run, + path: &Path, + analysis: &Analysis, + oracle: &Mentions, +) -> Vec { let ctx = LintContext::from_parse( &analysis.text, &analysis.tokens, @@ -238,8 +256,7 @@ fn file_findings( .with_oracle(oracle); let (violations, used) = lint_with(&ctx, &run.rules, &run.waivers); run.used.borrow_mut().merge(&used); - out.extend(violations.iter().map(|violation| lint_finding(&file, &analysis.lines, violation))); - Ok(out) + violations } fn lint_finding(file: &str, lines: &LineIndex, violation: &Violation) -> Finding { @@ -326,13 +343,20 @@ impl<'a> Census<'a> { /// The project index answering the linter's cross-file questions — the /// language server's `IndexMentions`, with the census when one was built. -struct Mentions<'a> { +pub(super) struct Mentions<'a> { index: &'a WorkspaceIndex, census: Option<&'a Census<'a>>, /// The linted file itself, subtracted from "elsewhere". own: Option, } +impl<'a> Mentions<'a> { + /// The oracle for one file, asking the index per question. + pub(super) fn of_file(index: &'a WorkspaceIndex, own: Option) -> Mentions<'a> { + Mentions { index, census: None, own } + } +} + impl MentionOracle for Mentions<'_> { fn mentioned_elsewhere(&self, name: &str) -> bool { match self.census { diff --git a/crates/lucisv_mcp/src/tools/edit.rs b/crates/lucisv_mcp/src/tools/edit.rs new file mode 100644 index 0000000..aab16d8 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/edit.rs @@ -0,0 +1,283 @@ +//! The refactorings that act at one position — `rename`, and the six the +//! editor offers as code actions at a cursor (`expand_wildcard`, +//! `convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`, +//! `remove_port`) — plus what every edit tool shares: the `dry_run` +//! argument, the whole-set read the engines are handed, and the step from a +//! verified `RefactorEdit` to `apply::run`. +//! +//! Each engine gets **every indexed file**, read from disk at call time +//! (`source::WholeSet`, M2's ruling for `references`: a use can resolve +//! through a file that never spells its name, so no narrowing is sound). +//! The texts read are the texts the write-freshness rule compares against. +//! A file the index skipped (over 1 MiB, not UTF-8) is never edited around: +//! when its bytes spell a name the edit changes, the edit is refused; +//! otherwise it is named under `warnings:` (QA finding 2). + +use std::path::{Path, PathBuf}; + +use vlog_refactor::RefactorEdit; + +use super::select::{target, Target}; +use super::source::WholeSet; +use super::{nav, Answer, Args, Param, Tool, Ty}; +use crate::apply::{self, Plan}; +use crate::project::{Analysis, Project}; + +/// `dry_run`, which every edit tool takes. +pub(super) const DRY_RUN: Param = Param { + name: "dry_run", + ty: Ty::Bool, + required: false, + description: "Return the unified diff and write nothing (default false).", +}; + +const FILE: Param = Param { + name: "file", + ty: Ty::Str, + required: true, + description: "The file holding the position, relative to a root or absolute inside one.", +}; +const LINE: Param = Param { + name: "line", + ty: Ty::Int { min: 1 }, + required: false, + description: "1-based line in `file`; alone it means the line's first non-blank character.", +}; +const COL: Param = Param { + name: "col", + ty: Ty::Int { min: 1 }, + required: false, + description: "1-based column in bytes on `line`.", +}; +const NAME: Param = Param { + name: "name", + ty: Ty::Str, + required: false, + description: "The name written at the position: with `line`, its occurrence on that line; without, its occurrence in `file`.", +}; + +/// The position arguments of the six cursor refactorings, then `dry_run`. +const AT: &[Param] = &[FILE, LINE, COL, NAME, DRY_RUN]; + +/// One engine that acts at a position. +type Engine = fn(&[(PathBuf, String)], &Path, u32) -> Result; + +/// The names an engine acting at a position changes — what a skipped file +/// must not spell. +type Stake = fn(&Analysis, u32) -> Vec; + +pub const EXPAND_WILDCARD: Tool = Tool { + name: "expand_wildcard", + title: "Expand .* connections", + description: "Replace one instantiation's `.*` with the named connections it binds, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a `bind` instance, a positional list, and a port list whose binding depends on `ifdef`s, with the reason. `dry_run` returns the diff.", + params: AT, + rewalk: true, + handler: expand_wildcard, +}; + +pub const CONVERT_PORTS: Tool = Tool { + name: "convert_ports", + title: "Convert ports to ANSI", + description: "Rewrite a module's non-ANSI header (`module m(a, b); input a; …`) as an ANSI port list, verified before anything is written. Point at the module: `file`+`line` (+`col`, or the module `name`). Refuses a header it cannot convert exactly, with the reason. `dry_run` returns the diff.", + params: AT, + rewalk: true, + handler: convert_ports, +}; + +pub const ORGANIZE_IMPORTS: Tool = Tool { + name: "organize_imports", + title: "Organize imports", + description: "Remove the unused `import` items of the scope at a position and sort the rest, verified before anything is written. Point into the scope with `file`+`line`. Refuses where it cannot judge (a macro or `include` in the scope, an unknown package), with the reason. `dry_run` returns the diff.", + params: AT, + rewalk: true, + handler: organize_imports, +}; + +pub const INLINE_MODULE: Tool = Tool { + name: "inline_module", + title: "Inline a module instance", + description: "Replace one instantiation with the body of the module it instantiates, its connections substituted, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses what it cannot substitute exactly, with the reason. `dry_run` returns the diff.", + params: AT, + rewalk: true, + handler: inline_module, +}; + +pub const PROPAGATE_PORTS: Tool = Tool { + name: "propagate_ports", + title: "Connect missing ports", + description: "Add a named connection for every port one instantiation leaves unconnected, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a positional or `.*` list, and an instance that already connects every port. `dry_run` returns the diff.", + params: AT, + rewalk: true, + handler: propagate_ports, +}; + +pub const REMOVE_PORT: Tool = Tool { + name: "remove_port", + title: "Remove a port", + description: "Delete one module port and its connection from every instantiation in the project, verified before anything is written. Point at the port: `file`+`line` (+`col`, or the port `name`). Refuses a port the body still uses, a positional instantiation, and a deletion that would drop a comment. `dry_run` returns the diff.", + params: AT, + rewalk: true, + handler: remove_port, +}; + +pub const RENAME: Tool = Tool { + name: "rename", + title: "Rename a symbol", + description: "Rename one declaration and every reference to it across the project, verified before anything is written. Select as for `definition`: `file`+`line`+`col`, `file`+`line`+`name`, `file`+`name`, or `name` (+`unit`). Refuses an invalid or clashing name and a use it cannot account for; a name already `new_name` is `unchanged`. A `.*` or `.name` shorthand connection bound to the renamed name is not rewritten yet (known engine limit, M3.5); check `dry_run` on designs using them.", + params: &[ + Param { required: false, ..FILE }, + Param { + description: "1-based line in `file`; give `col` too, or the `name` written on that line.", + ..LINE + }, + COL, + Param { + description: "The name to rename: alone, looked up across the project; with `file`, its occurrence there; with `file` and `line`, its occurrence on that line.", + ..NAME + }, + Param { + name: "unit", + ty: Ty::Str, + required: false, + description: "With a bare `name`: the module, interface, package or class declaring it.", + }, + Param { + name: "new_name", + ty: Ty::Str, + required: true, + description: "The new name.", + }, + DRY_RUN, + ], + rewalk: true, + handler: rename, +}; + +fn expand_wildcard(project: &mut Project, args: &Args) -> Result { + at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated) +} + +fn convert_ports(project: &mut Project, args: &Args) -> Result { + at_cursor(project, args, vlog_refactor::convert_to_ansi, enclosing) +} + +fn organize_imports(project: &mut Project, args: &Args) -> Result { + // Only the file's own `import` items change; nothing another file spells. + at_cursor(project, args, vlog_refactor::organize_imports, |_, _| Vec::new()) +} + +fn inline_module(project: &mut Project, args: &Args) -> Result { + at_cursor(project, args, vlog_refactor::inline_module, instantiated) +} + +fn propagate_ports(project: &mut Project, args: &Args) -> Result { + at_cursor(project, args, vlog_refactor::propagate_ports, instantiated) +} + +fn remove_port(project: &mut Project, args: &Args) -> Result { + let port_and_module = |analysis: &Analysis, offset: u32| { + let mut names = name_at(analysis, offset); + names.extend(instantiated(analysis, offset)); + names + }; + at_cursor(project, args, vlog_refactor::remove_port, port_and_module) +} + +/// The declared name at a position. +fn name_at(analysis: &Analysis, offset: u32) -> Vec { + vlog_refactor::rename_name_at(&analysis.semantics, offset).into_iter().collect() +} + +/// The module an instantiation at a position names, or whose port it is on. +fn instantiated(analysis: &Analysis, offset: u32) -> Vec { + vlog_refactor::port_action_modules_in(&analysis.tree, offset) +} + +/// The module whose declaration covers a position. +pub(super) fn enclosing(analysis: &Analysis, offset: u32) -> Vec { + vlog_refactor::enclosing_module(&analysis.text, offset).into_iter().collect() +} + +/// Run `engine` at the position the arguments name, over the whole set. +fn at_cursor( + project: &mut Project, + args: &Args, + engine: Engine, + stake: Stake, +) -> Result { + let (path, offset) = cursor(project, args)?; + let names = stake(&*project.analysis(&path)?, offset); + let set = whole_set(project, Some(&path), &names)?; + let edit = engine(&set.files, &path, offset)?; + finish(project, edit, &set, args) +} + +/// The position a cursor refactoring acts at: `file` + `line` alone is the +/// line's first non-blank byte; anything else is `definition`'s selector, +/// which must name a file. +fn cursor(project: &mut Project, args: &Args) -> Result<(PathBuf, u32), String> { + if let (Some(file), Some(line), None, None) = + (args.str("file"), args.int("line"), args.int("col"), args.str("name")) + { + let path = project.resolve(file)?; + let analysis = project.analysis(&path)?; + let line = u32::try_from(line).unwrap_or(u32::MAX); + let Some(range) = analysis.lines.line_range(line) else { + let count = analysis.lines.line_count(); + return Err(format!("line {line} is past the end ({count} lines) (in `{file}`)")); + }; + let text = analysis.line_text(line); + let blank = text.len() - text.trim_start().len(); + return Ok((path, range.start + blank as u32)); + } + match target(project, args)? { + Target::At { path, offset, .. } => Ok((path, offset)), + Target::Named { .. } => Err("give the `file` the position is in.".into()), + } +} + +/// The whole set an engine is handed — refused when a file the index +/// skipped spells one of `names`, since the edit could not reach it. +pub(super) fn whole_set( + project: &Project, + extra: Option<&Path>, + names: &[String], +) -> Result { + let set = WholeSet::read(project, extra); + if let Some((path, why, name)) = set.mentioning(names) { + return Err(format!( + "`{}` (skipped: {why}) may reference `{name}`; lucisv-mcp will not edit around a file it cannot index; nothing written.", + project.relative(path) + )); + } + Ok(set) +} + +/// A verified edit over the set's texts, diffed or written; the files the +/// set left out are named under `warnings:`. +pub(super) fn finish( + project: &Project, + edit: RefactorEdit, + set: &WholeSet, + args: &Args, +) -> Result { + let mut plan = Plan::from_refactor(edit, &set.files)?; + plan.warnings.extend(set.warning(project)); + apply::run(project, plan, args.flag("dry_run", false)) +} + +fn rename(project: &mut Project, args: &Args) -> Result { + let new_name = args.str("new_name").unwrap_or_default(); + let (path, offset) = match target(project, args)? { + Target::At { path, offset, .. } => (path, offset), + Target::Named { name, unit } => nav::declaration_position(project, &name, unit.as_deref())?, + }; + let names = name_at(&*project.analysis(&path)?, offset); + // Already renamed: a second identical call is a no-op, not a refusal. + if names.first().map(String::as_str) == Some(new_name) { + return apply::run(project, Plan::default(), args.flag("dry_run", false)); + } + let set = whole_set(project, Some(&path), &names)?; + let edit = vlog_refactor::rename(&set.files, &path, offset, new_name)?; + finish(project, edit, &set, args) +} diff --git a/crates/lucisv_mcp/src/tools/format.rs b/crates/lucisv_mcp/src/tools/format.rs new file mode 100644 index 0000000..0b461b3 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/format.rs @@ -0,0 +1,267 @@ +//! `format` and `fix_lint`: the CLI's `lucisv format` and `lucisv check +//! --fix`, per file, through the one write path (`apply.rs`). +//! +//! `format` is `format_source` (or `format_range` for `lines`) under the +//! `lucisv.toml` governing each file — the formatter's own safety net decides, +//! and a refusal names the file and writes nothing anywhere. `fix_lint` runs +//! the lint pass `diagnostics` runs (the same config ladder, waivers and +//! cross-file oracle), applies the **safe** fixes whose edits stay out of +//! every `// lucisv: off` fence — the CLI's `--fix` filter — until the file +//! stops changing, and refuses a result that parses worse than the input. + +use std::collections::BTreeMap; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::path::{Path, PathBuf}; + +use lucisv_core::config::{Discovery, FileConfig}; +use vlog_formatter::fence::{self, Region}; +use vlog_formatter::{format_range, format_source, Config, LineRanges}; +use vlog_linter::{apply_fixes, Fix, Violation}; + +use super::diagnostics::{violations, Mentions, Runs}; +use super::edit::DRY_RUN; +use super::{Answer, Args, Param, Tool, Ty}; +use crate::apply::{self, Change, Plan}; +use crate::project::{Analysis, Project}; + +/// How many fix-then-relint rounds one file gets — the CLI's cap, for the +/// CLI's reason: two overlapping fixes land in successive rounds. +const MAX_FIX_ROUNDS: usize = 10; + +const FILE: Param = Param { + name: "file", + ty: Ty::Str, + required: false, + description: "One file, relative to a root or absolute inside one.", +}; +const FILES: Param = Param { + name: "files", + ty: Ty::Str, + required: false, + description: "Several files, comma-separated, instead of `file`.", +}; + +pub const FORMAT: Tool = Tool { + name: "format", + title: "Format files", + description: "Format `file` (or the comma-separated `files`) as `lucisv format` does, under each file's lucisv.toml; `lines` (`12-40,55`, one file only) formats just the constructs meeting those lines. The formatter verifies its own output: a file it will not format safely refuses the whole call, naming it. An already formatted file is `unchanged`. `dry_run` returns the diff.", + params: &[ + FILE, + FILES, + Param { + name: "lines", + ty: Ty::Str, + required: false, + description: "1-based line ranges such as `12-40,55`; only with a single file.", + }, + DRY_RUN, + ], + rewalk: false, + handler: format, +}; + +pub const FIX_LINT: Tool = Tool { + name: "fix_lint", + title: "Apply safe lint fixes", + description: "Apply the safe automatic fixes of the lint findings in `file` (or the comma-separated `files`), as `lucisv check --fix` does: the project's [lint] config and waivers, never inside a `// lucisv: off` fence, never an unsafe fix. Reports which rules were fixed and how many findings remain (`diagnostics` lists them). `rules` narrows the run like --select. `dry_run` returns the diff.", + params: &[ + FILE, + FILES, + Param { + name: "rules", + ty: Ty::Str, + required: false, + description: "Comma-separated rule names or severities to fix instead of the configured set.", + }, + DRY_RUN, + ], + rewalk: false, + handler: fix_lint, +}; + +/// The files a call names, resolved, each once, in the order given. +fn named_files(project: &Project, args: &Args) -> Result, String> { + let given: Vec<&str> = match (args.str("file"), args.str("files")) { + (Some(_), Some(_)) => return Err("give `file` or `files`, not both.".into()), + (Some(file), None) => vec![file], + (None, Some(files)) => files.split(',').map(str::trim).filter(|f| !f.is_empty()).collect(), + (None, None) => return Err("give a `file`, or comma-separated `files`.".into()), + }; + if given.is_empty() { + return Err("`files` names no file.".into()); + } + let mut out: Vec = Vec::new(); + for file in given { + let path = project.resolve(file)?; + if !out.contains(&path) { + out.push(path); + } + } + Ok(out) +} + +/// A file's text as it is on disk now. +fn read(project: &Project, path: &Path) -> Result { + std::fs::read_to_string(path) + .map_err(|e| format!("cannot read `{}`: {e}", project.relative(path))) +} + +fn format(project: &mut Project, args: &Args) -> Result { + let paths = named_files(project, args)?; + let lines = match args.str("lines") { + None => None, + Some(_) if paths.len() > 1 => return Err("`lines` needs a single file.".into()), + Some(spec) => Some(LineRanges::parse(spec).map_err(|e| format!("`lines`: {e}"))?), + }; + let mut discovery = Discovery::new(true); + let mut plan = Plan::default(); + for path in paths { + let before = read(project, &path)?; + let config = formatter_config(&discovery.for_file(&path)?); + let after = formatted(&before, &config, lines.as_ref()).map_err(|why| { + format!("`{}` was not formatted: {why}; nothing written.", project.relative(&path)) + })?; + plan.changes.push(Change { path, before, after, created: false }); + } + apply::run(project, plan, args.flag("dry_run", false)) +} + +/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's +/// `Options::config_with` with no command-line flags. +fn formatter_config(file: &FileConfig) -> Config { + let mut config = Config::default(); + if let Some(width) = file.line_length { + config.max_width = width; + } + if let Some(indent) = file.indent { + config.indent_width = indent; + } + if let Some(on) = file.format_uvm_utils_indent { + config.uvm_utils_indent = on; + } + config +} + +/// Format one text; a formatter panic is an error like any other, never the +/// end of the server. +fn formatted(text: &str, config: &Config, lines: Option<&LineRanges>) -> Result { + let run = catch_unwind(AssertUnwindSafe(|| match lines { + Some(lines) => format_range(text, config, lines), + None => format_source(text, config), + })); + match run { + Ok(Ok(out)) => Ok(out), + Ok(Err(e)) => Err(e.to_string()), + Err(_) => Err("the formatter panicked".into()), + } +} + +fn fix_lint(project: &mut Project, args: &Args) -> Result { + let paths = named_files(project, args)?; + let selected: Option> = args.str("rules").map(|rules| { + rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect() + }); + let mut runs = Runs::new(selected); + let mut plan = Plan::default(); + let mut fixed: BTreeMap<&'static str, usize> = BTreeMap::new(); + let mut left = 0; + for path in paths { + let before = read(project, &path)?; + let outcome = fix_file(project, &mut runs, &path, &before)?; + for (rule, count) in outcome.fixed { + *fixed.entry(rule).or_default() += count; + } + left += outcome.left; + plan.changes.push(Change { path, before, after: outcome.text, created: false }); + } + plan.note = Some(fixed_note(&fixed, left)); + apply::run(project, plan, args.flag("dry_run", false)) +} + +/// What fixing one file came to. +struct Fixed { + text: String, + /// Per rule, how many of its findings the fixes removed. + fixed: BTreeMap<&'static str, usize>, + /// Findings still reported after the last round. + left: usize, +} + +/// Fix, re-lint, repeat until nothing more applies; refuse a result whose +/// tolerant parse reports more errors than the input's did. +fn fix_file( + project: &Project, + runs: &mut Runs, + path: &Path, + before: &str, +) -> Result { + let run = runs.for_file(path)?; + let oracle = Mentions::of_file(project.index(), project.index().file_id(path)); + let first = Analysis::of(before.to_string()); + let errors_before = first.diagnostics.len(); + let found = violations(&run, path, &first, &oracle); + let mut remaining = found.clone(); + let mut text = before.to_string(); + let mut errors_after = errors_before; + for _ in 0..MAX_FIX_ROUNDS { + let round = apply_fixes(&text, &outside_fences(&text, &remaining), false); + if round.applied == 0 { + break; + } + text = round.output; + let analysis = Analysis::of(text.clone()); + errors_after = analysis.diagnostics.len(); + remaining = violations(&run, path, &analysis, &oracle); + } + if errors_after > errors_before { + return Err(format!( + "fixing `{}` would leave it with {errors_after} parse errors where it had {errors_before}; nothing written.", + project.relative(path) + )); + } + let fixed = removed_per_rule(&found, &remaining); + Ok(Fixed { text, fixed, left: remaining.len() }) +} + +/// The findings whose fix may be applied: those whose every edit stays out +/// of the fenced regions — the CLI's `fixable_outside_fences`, over +/// `fence::protected_regions`, the one answer to which bytes are fenced. +fn outside_fences(text: &str, found: &[Violation]) -> Vec { + let regions = fence::protected_regions(text); + found + .iter() + .filter(|v| v.fix.as_ref().is_some_and(|fix| !touches_fence(fix, ®ions))) + .cloned() + .collect() +} + +fn touches_fence(fix: &Fix, regions: &[Region]) -> bool { + fix.edits + .iter() + .any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize)) +} + +/// Per rule, how many fewer findings the fixed text has. +fn removed_per_rule(before: &[Violation], after: &[Violation]) -> BTreeMap<&'static str, usize> { + let count = |found: &[Violation]| { + let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new(); + found.iter().for_each(|v| *counts.entry(v.rule).or_default() += 1); + counts + }; + let after = count(after); + count(before) + .into_iter() + .filter_map(|(rule, n)| { + let gone = n.saturating_sub(after.get(rule).copied().unwrap_or(0)); + (gone > 0).then_some((rule, gone)) + }) + .collect() +} + +/// `fixed: rule ×2, rule ×1; 3 findings left`. +fn fixed_note(fixed: &BTreeMap<&'static str, usize>, left: usize) -> String { + let listed: Vec = fixed.iter().map(|(rule, n)| format!("{rule} ×{n}")).collect(); + let fixed = if listed.is_empty() { "nothing".to_string() } else { listed.join(", ") }; + let plural = if left == 1 { "" } else { "s" }; + format!("fixed: {fixed}; {left} finding{plural} left") +} diff --git a/crates/lucisv_mcp/src/tools/mod.rs b/crates/lucisv_mcp/src/tools/mod.rs index b6d1660..17e8d0a 100644 --- a/crates/lucisv_mcp/src/tools/mod.rs +++ b/crates/lucisv_mcp/src/tools/mod.rs @@ -5,11 +5,14 @@ mod defines; mod diagnostics; +mod edit; +mod format; mod hierarchy; mod interface; mod nav; mod read; mod read_item; +mod refactor; mod select; mod source; @@ -61,46 +64,76 @@ pub struct Tool { pub handler: Handler, } +/// What a tool does to the disk — the annotations a host shows before it +/// lets an agent call it. +#[derive(Clone, Copy)] +pub enum Effect { + /// Nothing on disk changes; the same call on the same disk gives the + /// same answer. + Read, + /// Files inside the roots are rewritten (or created). `idempotent` when + /// a second identical call writes nothing more. + Edit { idempotent: bool }, +} + +use Effect::{Edit, Read}; + /// Every tool this server offers, in the order `tools/list` gives them. -const TOOLS: &[Tool] = &[ - read::PROJECT_OVERVIEW, - read::LIST_UNITS, - interface::UNIT_INTERFACE, - read::OUTLINE, - read_item::READ_ITEM, - read::SEARCH_SYMBOLS, - defines::DEFINES, - nav::DEFINITION, - nav::REFERENCES, - hierarchy::HIERARCHY, - diagnostics::DIAGNOSTICS, +const TOOLS: &[(Tool, Effect)] = &[ + (read::PROJECT_OVERVIEW, Read), + (read::LIST_UNITS, Read), + (interface::UNIT_INTERFACE, Read), + (read::OUTLINE, Read), + (read_item::READ_ITEM, Read), + (read::SEARCH_SYMBOLS, Read), + (defines::DEFINES, Read), + (nav::DEFINITION, Read), + (nav::REFERENCES, Read), + (hierarchy::HIERARCHY, Read), + (diagnostics::DIAGNOSTICS, Read), + (format::FORMAT, Edit { idempotent: true }), + (format::FIX_LINT, Edit { idempotent: true }), + (edit::RENAME, Edit { idempotent: false }), + (edit::EXPAND_WILDCARD, Edit { idempotent: true }), + (edit::CONVERT_PORTS, Edit { idempotent: true }), + (edit::ORGANIZE_IMPORTS, Edit { idempotent: true }), + (edit::INLINE_MODULE, Edit { idempotent: false }), + (edit::PROPAGATE_PORTS, Edit { idempotent: false }), + (edit::REMOVE_PORT, Edit { idempotent: false }), + (refactor::ADD_PORT, Edit { idempotent: false }), + (refactor::EXTRACT_MODULE, Edit { idempotent: false }), + (refactor::INSTANTIATE, Read), ]; /// The tool called `name`. pub fn find(name: &str) -> Option<&'static Tool> { - TOOLS.iter().find(|tool| tool.name == name) + TOOLS.iter().map(|(tool, _)| tool).find(|tool| tool.name == name) } /// The `tools/list` result: every tool, no pagination. pub fn list() -> Value { - let tools: Vec = TOOLS.iter().map(describe).collect(); + let tools: Vec = TOOLS.iter().map(|(tool, effect)| describe(tool, *effect)).collect(); json!({ "tools": tools }) } -fn describe(tool: &Tool) -> Value { +fn describe(tool: &Tool, effect: Effect) -> Value { + // No tool consults anything outside the roots (`openWorldHint`), and no + // edit tool destroys: each rewrites files inside the roots through a + // verified engine, and `dry_run` shows the diff first. + let (read_only, idempotent) = match effect { + Read => (true, true), + Edit { idempotent } => (false, idempotent), + }; json!({ "name": tool.name, "title": tool.title, "description": tool.description, "inputSchema": schema(tool.params), - // Every M1 tool only reads: nothing on disk changes, the same call - // gives the same answer on the same disk, and nothing outside the - // roots is consulted. "annotations": { "title": tool.title, - "readOnlyHint": true, + "readOnlyHint": read_only, "destructiveHint": false, - "idempotentHint": true, + "idempotentHint": idempotent, "openWorldHint": false, }, }) @@ -211,13 +244,13 @@ mod tests { #[test] fn every_schema_is_closed_and_names_its_required_arguments() { - for tool in TOOLS { + for (tool, _) in TOOLS { let schema = schema(tool.params); assert_eq!(schema["additionalProperties"], false, "{}", tool.name); assert!(schema["required"].is_array(), "{}", tool.name); assert!(!tool.description.is_empty() && tool.description.len() < 600, "{}", tool.name); } - let names: Vec<&str> = TOOLS.iter().map(|tool| tool.name).collect(); + let names: Vec<&str> = TOOLS.iter().map(|(tool, _)| tool.name).collect(); let mut unique = names.clone(); unique.sort_unstable(); unique.dedup(); diff --git a/crates/lucisv_mcp/src/tools/nav.rs b/crates/lucisv_mcp/src/tools/nav.rs index 1ac9964..d13419b 100644 --- a/crates/lucisv_mcp/src/tools/nav.rs +++ b/crates/lucisv_mcp/src/tools/nav.rs @@ -8,10 +8,10 @@ //! the index. `definition` walks the server's ladder — an `` `include`` line, //! a macro use, the file's own symbol table, the workspace overlay — and //! lists every site, never a guess. `references` hands the declaration to -//! `vlog_refactor::find_references` over every indexed file ([`all_files`]). +//! `vlog_refactor::find_references` over every indexed file +//! (`source::WholeSet`). //! The selector itself is `select.rs`. -use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use serde_json::{json, Value}; @@ -19,7 +19,7 @@ use vlog_parser::token::{Token, TokenKind}; use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex}; use super::select::{macro_name, target, Target}; -use super::source::{self, checked_site, Site, Texts}; +use super::source::{self, checked_site, Site, Texts, WholeSet}; use super::{Answer, Args, Param, Tool, Ty}; use crate::project::{Analysis, Project}; use crate::render::{self, DEFAULT_LIMIT}; @@ -94,7 +94,7 @@ pub const REFERENCES: Tool = Tool { description: "Hits to skip, for paging past `… and N more` (default 0).", }, ], - rewalk: false, + rewalk: true, handler: references, }; @@ -289,12 +289,13 @@ fn references(project: &mut Project, args: &Args) -> Result { if let Some(name) = analysis.token_at(offset).filter(|t| t.is_macro()).and_then(macro_name) { return Err(format!("`{name} is a macro; {MACRO_REFUSAL}")); } - let files = all_files(project, &path); + let set = WholeSet::read(project, Some(&path)); let include = args.flag("include_declaration", true); - let found = - vlog_refactor::find_references(&files, &path, offset, include).map_err(engine_refusal)?; + let found = vlog_refactor::find_references(&set.files, &path, offset, include) + .map_err(engine_refusal)?; + let partial = set.warning(project); let mut texts = Texts::default(); - for (held, text) in files { + for (held, text) in set.files { texts.hold(held, text); } let hits: Vec = found @@ -304,11 +305,17 @@ fn references(project: &mut Project, args: &Args) -> Result { Some(Site::at(project.relative(file), text, lines, *span, "use")) }) .collect(); - Ok(render_hits(&hits, args)) + let mut answer = render_hits(&hits, args); + // A file the index skipped was not searched: the census is partial. + if let Some(partial) = partial { + answer.text.push_str(&format!("warning: {partial}\n")); + answer.structured["warning"] = Value::from(partial); + } + Ok(answer) } -/// The one declaration a bare `name` selects for `references`. -fn declaration_position( +/// The one declaration a bare `name` selects for `references` (and `rename`). +pub(super) fn declaration_position( project: &mut Project, name: &str, unit: Option<&str>, @@ -347,21 +354,6 @@ fn declaration_position( const MACRO_REFUSAL: &str = "references follows declarations, not macros (`defines` lists its definitions)."; -/// Every indexed file (and the selected one), read from disk now — the -/// whole set, always (lead's ruling on QA finding 1): a use can resolve -/// through files that never spell its name (`u_a.u_b.sig` needs the file -/// declaring `u_b`; `e.s.count` needs the class declaring `s`), so no -/// narrowing by name is sound. The cost is a parse of the set per call -/// (README; Handshake MCP-7 lets cached facts replace it). -fn all_files(project: &Project, path: &Path) -> Vec<(PathBuf, String)> { - let mut wanted: BTreeSet = project.index().files().iter().cloned().collect(); - wanted.insert(path.to_path_buf()); - wanted - .into_iter() - .filter_map(|path| std::fs::read_to_string(&path).ok().map(|text| (path, text))) - .collect() -} - /// The engine's refusal, said as ours: prefixed, and its rename wording — /// `find_references` shares the rename's resolution — turned into this /// tool's. diff --git a/crates/lucisv_mcp/src/tools/refactor.rs b/crates/lucisv_mcp/src/tools/refactor.rs new file mode 100644 index 0000000..8f1ce1e --- /dev/null +++ b/crates/lucisv_mcp/src/tools/refactor.rs @@ -0,0 +1,291 @@ +//! The refactorings that are not "act at this cursor": `add_port` (a module +//! and a declaration), `extract_module` (a line range and a new name), and +//! `instantiate`, which writes nothing at all — it answers with the text of +//! an instantiation for the agent to place. + +use std::path::{Path, PathBuf}; + +use vlog_refactor::{instantiation_plan, module_definition, Home, Layout, ModuleRef}; + +use super::edit::{enclosing, finish, whole_set, DRY_RUN}; +use super::{Answer, Args, Param, Tool, Ty}; +use crate::project::Project; + +pub const ADD_PORT: Tool = Tool { + name: "add_port", + title: "Add a port", + description: "Add one ANSI port to a module and a connection for it to every instantiation in the project, verified before anything is written. Name the module by `module`, or by `file`+`line` inside its declaration; `declaration` is the port as written in the header (`input logic [7:0] cfg`). Refuses a port that exists, an ordered instantiation of a different length, and a list split by `ifdef`s. `dry_run` returns the diff.", + params: &[ + Param { + name: "module", + ty: Ty::Str, + required: false, + description: "The module's name (declared once in the project).", + }, + Param { + name: "file", + ty: Ty::Str, + required: false, + description: "Instead of `module`: the file declaring it, with `line`.", + }, + Param { + name: "line", + ty: Ty::Int { min: 1 }, + required: false, + description: "1-based line inside the module's declaration in `file`.", + }, + Param { + name: "declaration", + ty: Ty::Str, + required: true, + description: "One directed ANSI port declaration, e.g. `input logic [7:0] cfg`.", + }, + DRY_RUN, + ], + rewalk: true, + handler: add_port, +}; + +pub const EXTRACT_MODULE: Tool = Tool { + name: "extract_module", + title: "Extract lines into a module", + description: "Move the whole items on lines `start_line`..`end_line` of a module into a new module `new_name`, whose ports come from the dataflow across the selection, and instantiate it in their place; verified before anything is written. `home: new_file` (default) creates `new_name.sv` beside the file (refused if it exists); `same_file` writes it below the module. Refuses a partial item and names it cannot carry. `dry_run` returns the diff.", + params: &[ + Param { + name: "file", + ty: Ty::Str, + required: true, + description: "The file holding the module, relative to a root or absolute inside one.", + }, + Param { + name: "start_line", + ty: Ty::Int { min: 1 }, + required: true, + description: "First line of the selection (1-based).", + }, + Param { + name: "end_line", + ty: Ty::Int { min: 1 }, + required: true, + description: "Last line of the selection (1-based, included).", + }, + Param { + name: "new_name", + ty: Ty::Str, + required: true, + description: "The new module's name; nothing in the project may declare it yet.", + }, + Param { + name: "home", + ty: Ty::Enum(&["new_file", "same_file"]), + required: false, + description: "Where the new module goes: `new_file` (default) or `same_file`.", + }, + DRY_RUN, + ], + rewalk: true, + handler: extract_module, +}; + +pub const INSTANTIATE: Tool = Tool { + name: "instantiate", + title: "Instantiation template", + description: "The text of an instantiation of module `name` for the agent to place — parameters with their defaults, the instance name, and each port connected to a same-named signal (`named`) or as `.*` (`wildcard`). Writes nothing. Refuses a module that is not indexed or is declared twice (pass `file` to pick one).", + params: &[ + Param { + name: "name", + ty: Ty::Str, + required: true, + description: "The module (or interface) to instantiate.", + }, + Param { + name: "style", + ty: Ty::Enum(&["named", "wildcard"]), + required: false, + description: "`named` connections (default) or `.*`.", + }, + Param { + name: "with_params", + ty: Ty::Bool, + required: false, + description: "Write the `#( … )` parameter overrides (default true).", + }, + Param { + name: "instance", + ty: Ty::Str, + required: false, + description: "The instance name (default `u_`).", + }, + Param { + name: "file", + ty: Ty::Str, + required: false, + description: "The file declaring the module, when more than one does.", + }, + ], + rewalk: false, + handler: instantiate, +}; + +fn add_port(project: &mut Project, args: &Args) -> Result { + let declaration = args.str("declaration").unwrap_or_default(); + match (args.str("module"), args.str("file"), args.int("line")) { + (Some(name), None, None) => { + let set = whole_set(project, None, &[name.to_string()])?; + let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(name), declaration)?; + finish(project, edit, &set, args) + } + (None, Some(file), Some(line)) => { + let path = project.resolve(file)?; + let offset = line_start(project, &path, line)?; + let names = enclosing(&*project.analysis(&path)?, offset); + let set = whole_set(project, Some(&path), &names)?; + let module = ModuleRef::At { file: &path, offset }; + let edit = vlog_refactor::add_port(&set.files, module, declaration)?; + finish(project, edit, &set, args) + } + _ => Err("name the module by `module`, or by `file` and `line`, not both.".into()), + } +} + +/// The byte offset where 1-based `line` of `path` starts; `end` asks for +/// where it ends instead (its line ending excluded). +fn line_offset(project: &mut Project, path: &Path, line: i64, end: bool) -> Result { + let analysis = project.analysis(path)?; + let count = analysis.lines.line_count(); + let range = u32::try_from(line).ok().and_then(|line| analysis.lines.line_range(line)); + let Some(range) = range else { + let file = project.relative(path); + return Err(format!("line {line} is past the end of `{file}` ({count} lines).")); + }; + Ok(if end { range.end } else { range.start }) +} + +fn line_start(project: &mut Project, path: &Path, line: i64) -> Result { + line_offset(project, path, line, false) +} + +fn extract_module(project: &mut Project, args: &Args) -> Result { + let file = args.str("file").unwrap_or_default(); + let path = project.resolve(file)?; + let (first, last) = (args.int("start_line").unwrap_or(1), args.int("end_line").unwrap_or(1)); + if last < first { + return Err(format!("`end_line` {last} is before `start_line` {first}.")); + } + let start = line_start(project, &path, first)?; + let end = line_offset(project, &path, last, true)?; + let home = match args.str("home") { + Some("same_file") => Home::SameFile, + _ => Home::NewFile, + }; + let new_name = args.str("new_name").unwrap_or_default(); + let names = enclosing(&*project.analysis(&path)?, start); + let set = whole_set(project, Some(&path), &names)?; + let edit = vlog_refactor::extract_module(&set.files, &path, start, end, new_name, home)?; + finish(project, edit, &set, args) +} + +fn instantiate(project: &mut Project, args: &Args) -> Result { + let name = args.str("name").unwrap_or_default(); + let path = declaring_file(project, name, args.str("file"))?; + let text = std::fs::read_to_string(&path) + .map_err(|e| format!("cannot read `{}`: {e}", project.relative(&path)))?; + let mut plan = instantiation_plan(name, &text, None)?; + if !args.flag("with_params", true) { + plan.params.clear(); + } + let wildcard = args.str("style") == Some("wildcard"); + if wildcard { + plan.ports.clear(); + } + let instance = match args.str("instance") { + Some(instance) => identifier(instance)?.to_string(), + None => plan.instance_name(), + }; + // `render_with` numbers the fill-ins: each parameter, then the instance. + let instance_hole = plan.params.len() + 1; + let mut hole = |n: usize, default: &str| { + if n == instance_hole { + instance.clone() + } else { + default.into() + } + }; + let mut skeleton = plan.render_with(&layout(project), &mut hole); + if wildcard { + // With no ports the skeleton ends `u_x ();`. + skeleton.truncate(skeleton.len() - "();".len()); + skeleton.push_str("(.*);"); + } + skeleton.push('\n'); + let file = project.relative(&path); + let structured = serde_json::json!({ + "module": name, "file": file, "text": skeleton, "warnings": plan.warnings, + }); + let mut text = skeleton; + for warning in &plan.warnings { + text.push_str(&format!("warning: {warning}\n")); + } + Ok(Answer { text, structured }) +} + +/// The one file declaring module `name` — `file` when given (it must be a +/// file the index says declares it), else the index's single answer, after +/// one walk for a module written since the last one. +fn declaring_file( + project: &mut Project, + name: &str, + file: Option<&str>, +) -> Result { + if let Some(file) = file { + let path = project.resolve(file)?; + let declares = project.index().units(name).iter().any(|def| { + def.kind.is_instantiable() && project.index().path(def.file) == Some(path.as_path()) + }); + if !declares { + return Err(format!("`{file}` declares no module named `{name}`.")); + } + return Ok(path); + } + let found = module_definition(project.index(), name).map(Path::to_path_buf); + match found { + Err(_) if project.ensure_walked_for_miss() => { + module_definition(project.index(), name).map(Path::to_path_buf) + } + found => found, + } + .map_err(|why| { + if why.contains("more than one") { + format!("{why} Pass `file` to pick one.") + } else { + why + } + }) +} + +/// `name`, when it is one SystemVerilog identifier: a simple one +/// (`[A-Za-z_][A-Za-z0-9_$]*`, not a keyword) or an escaped one (`\`, then +/// printable non-space characters, then one space). Anything else would +/// render text that does not parse. +fn identifier(name: &str) -> Result<&str, String> { + let simple = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$') + && !vlog_parser::token::is_keyword(name); + let escaped = name + .strip_prefix('\\') + .and_then(|rest| rest.strip_suffix(' ')) + .is_some_and(|body| !body.is_empty() && body.chars().all(|c| c.is_ascii_graphic())); + if simple || escaped { + return Ok(name); + } + Err(format!( + "`instance` must be one identifier — `[A-Za-z_][A-Za-z0-9_$]*` and not a keyword, or an escaped identifier `\\name ` ending in one space; `{name}` is not." + )) +} + +/// Column zero, one indentation step as the project's lucisv.toml spells it. +fn layout(project: &Project) -> Layout { + let indent = + project.config().0.indent.unwrap_or(vlog_formatter::Config::default().indent_width); + Layout { base: String::new(), step: " ".repeat(indent) } +} diff --git a/crates/lucisv_mcp/src/tools/source.rs b/crates/lucisv_mcp/src/tools/source.rs index ade6b12..f69fcef 100644 --- a/crates/lucisv_mcp/src/tools/source.rs +++ b/crates/lucisv_mcp/src/tools/source.rs @@ -4,7 +4,7 @@ //! call ([`Texts`]); the index's spans are checked against the bytes before //! they are printed, so a stale span is omitted, never mislocated. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::path::{Path, PathBuf}; use serde_json::{json, Value}; @@ -148,6 +148,77 @@ pub fn without_comments(text: &str) -> String { out } +/// The whole in-scope set a cross-file engine is handed: every indexed file, +/// and one more when asked, read from disk now — plus every file the set +/// could not include (over the size cap, not UTF-8, no longer readable), +/// so an answer never pretends those were searched (QA finding 2 of M3). +pub struct WholeSet { + /// `(path, text)` for every file read. + pub files: Vec<(PathBuf, String)>, + /// The files left out, with why. + pub skipped: Vec<(PathBuf, String)>, +} + +impl WholeSet { + /// Read every indexed file and `extra` from disk now. The whole set, + /// always (M2's ruling on QA finding 1): a use can resolve through files + /// that never spell its name, so no narrowing by name is sound. + pub fn read(project: &Project, extra: Option<&Path>) -> WholeSet { + let mut wanted: BTreeSet = project.index().files().iter().cloned().collect(); + wanted.extend(extra.map(Path::to_path_buf)); + let mut set = WholeSet { files: Vec::new(), skipped: project.skipped() }; + for path in wanted { + match std::fs::read_to_string(&path) { + Ok(text) => set.files.push((path, text)), + Err(e) => set.skipped.push((path, format!("no longer reads: {e}"))), + } + } + set + } + + /// The first skipped file whose bytes spell one of `names` as a whole + /// word, with why it was skipped and the name it spells. + pub fn mentioning<'n>(&self, names: &'n [String]) -> Option<(&Path, &str, &'n str)> { + self.skipped.iter().find_map(|(path, why)| { + let bytes = std::fs::read(path).ok()?; + let name = names.iter().find(|name| word_in_bytes(&bytes, name.as_bytes()))?; + Some((path.as_path(), why.as_str(), name.as_str())) + }) + } + + /// One line naming the skipped files (ten at most), or `None` when the + /// set is complete. + pub fn warning(&self, project: &Project) -> Option { + if self.skipped.is_empty() { + return None; + } + let named: Vec = self + .skipped + .iter() + .take(10) + .map(|(path, why)| format!("{} ({why})", project.relative(path))) + .collect(); + let more = self.skipped.len().saturating_sub(10); + let tail = if more > 0 { format!(" and {more} more") } else { String::new() }; + Some(format!("not indexed, so not searched or edited: {}{tail}", named.join(", "))) + } +} + +/// Whether `name` occurs in `bytes` not glued to an identifier character on +/// either side — how an identifier, escaped or not, is written. +fn word_in_bytes(bytes: &[u8], name: &[u8]) -> bool { + let glued = + |b: Option<&u8>| b.is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_' || b == b'$'); + if name.is_empty() || name.len() > bytes.len() { + return false; + } + bytes.windows(name.len()).enumerate().any(|(at, window)| { + window == name + && !glued(at.checked_sub(1).and_then(|before| bytes.get(before))) + && !glued(bytes.get(at + name.len())) + }) +} + /// Whether `c` may continue an identifier. fn is_ident_char(c: char) -> bool { c.is_ascii_alphanumeric() || c == '_' || c == '$' @@ -187,6 +258,15 @@ mod tests { assert_eq!(word_in("anything", ""), None); } + #[test] + fn a_skipped_file_is_searched_for_whole_words_only() { + assert!(word_in_bytes(b"leaf u (.d(x));", b"d")); + assert!(word_in_bytes(b"\xa9 d", b"d")); + assert!(!word_in_bytes(b"data d_q $d dd", b"d")); + assert!(word_in_bytes(b"d", b"d")); + assert!(!word_in_bytes(b"", b"d")); + } + #[test] fn comments_are_dropped_and_strings_kept() { let text = "#( // why\n .W(8), /* old: 4 */ .S(\"a//b\"), .D(4 / 2) )"; diff --git a/crates/lucisv_mcp/tests/fixtures/edit/fmt/messy.sv b/crates/lucisv_mcp/tests/fixtures/edit/fmt/messy.sv new file mode 100644 index 0000000..21e36db --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/fmt/messy.sv @@ -0,0 +1,4 @@ +module messy(input logic a,output logic b); +assign b=a; + // keep this comment +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/cell.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/cell.sv new file mode 100644 index 0000000..3f2a6f2 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/cell.sv @@ -0,0 +1,7 @@ +module cell ( + input logic clk, + input logic en, + output logic o +); + assign o = en; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/edit_pkg.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/edit_pkg.sv new file mode 100644 index 0000000..ea09a9f --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/edit_pkg.sv @@ -0,0 +1,4 @@ +package edit_pkg; + parameter int WIDTH = 8; + typedef logic [WIDTH-1:0] word_t; +endpackage diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/ext.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/ext.sv new file mode 100644 index 0000000..f7d7fe5 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/ext.sv @@ -0,0 +1,9 @@ +module ext ( + input logic clk, + input logic [7:0] a, + output logic [7:0] q +); + logic [7:0] s; + assign s = a + 8'd1; + always_ff @(posedge clk) q <= s; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/inl.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/inl.sv new file mode 100644 index 0000000..98384db --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/inl.sv @@ -0,0 +1,9 @@ +module inl ( + input logic x, + output logic z +); + inv u_inv ( + .i(x), + .o(z) + ); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/inv.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/inv.sv new file mode 100644 index 0000000..fa8cc1e --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/inv.sv @@ -0,0 +1,6 @@ +module inv ( + input logic i, + output logic o +); + assign o = ~i; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/leaf.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/leaf.sv new file mode 100644 index 0000000..c2d7f47 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/leaf.sv @@ -0,0 +1,7 @@ +module leaf ( + input logic clk, + input logic [7:0] d, + output logic [7:0] q +); + always_ff @(posedge clk) q <= d; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/mid.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/mid.sv new file mode 100644 index 0000000..3d48d9b --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/mid.sv @@ -0,0 +1,11 @@ +module mid ( + input logic clk, + input logic [7:0] din, + output logic [7:0] dout +); + leaf u_leaf ( + .clk(clk), + .d (din), + .q (dout) + ); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/old.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/old.sv new file mode 100644 index 0000000..9bb250f --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/old.sv @@ -0,0 +1,6 @@ +module old (a, b, y); + input a; + input b; + output y; + assign y = a & b; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/partial.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/partial.sv new file mode 100644 index 0000000..a962d3d --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/partial.sv @@ -0,0 +1,7 @@ +module partial ( + input logic clk, + input logic en, + output logic o +); + cell u_c (.clk(clk)); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/spare.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/spare.sv new file mode 100644 index 0000000..8f63e3a --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/spare.sv @@ -0,0 +1,7 @@ +module spare ( + input logic clk, + input logic unused_i, + output logic o +); + assign o = clk; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/spare_user.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/spare_user.sv new file mode 100644 index 0000000..14125f5 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/spare_user.sv @@ -0,0 +1,10 @@ +module spare_user ( + input logic clk, + output logic o2 +); + spare u_s ( + .clk (clk), + .unused_i(1'b0), + .o (o2) + ); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/top.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/top.sv new file mode 100644 index 0000000..0a4771e --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/top.sv @@ -0,0 +1,15 @@ +module top ( + input logic clk, + input logic [7:0] a, + output logic [7:0] y +); + import edit_pkg::word_t; + import edit_pkg::WIDTH; + word_t w; + assign w = a; + leaf u_leaf2 ( + .clk(clk), + .d (w), + .q (y) + ); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/edit/rtl/wild.sv b/crates/lucisv_mcp/tests/fixtures/edit/rtl/wild.sv new file mode 100644 index 0000000..af4dd1f --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/edit/rtl/wild.sv @@ -0,0 +1,7 @@ +module wild ( + input logic clk, + input logic en, + output logic o +); + cell u_cell (.*); +endmodule diff --git a/crates/lucisv_mcp/tests/qa_m1.rs b/crates/lucisv_mcp/tests/qa_m1.rs index d17dc17..db0b6ec 100644 --- a/crates/lucisv_mcp/tests/qa_m1.rs +++ b/crates/lucisv_mcp/tests/qa_m1.rs @@ -276,8 +276,8 @@ fn qa_everything_but_initialize_and_ping_waits_for_the_handshake() { assert!(s.pings()); s.initialize(); // M2 added five tools (defines, definition, references, hierarchy, - // diagnostics) to M1's six. - assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 11); + // diagnostics) to M1's six; M3 added twelve edit tools. + assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 23); } #[test] diff --git a/crates/lucisv_mcp/tests/qa_m3.rs b/crates/lucisv_mcp/tests/qa_m3.rs new file mode 100644 index 0000000..50659d6 --- /dev/null +++ b/crates/lucisv_mcp/tests/qa_m3.rs @@ -0,0 +1,1389 @@ +//! QA attacks on lane M3 (the edit tools and their one write path), +//! 2026-09-23. +//! +//! Two kinds of test. The first half includes the production write path, +//! `src/apply.rs`, verbatim (`#[path]`) over two small stand-ins for the +//! modules it names (`Project`'s roots and `Answer`), so `commit` — the +//! write-freshness rule — can be attacked directly with stale texts; no +//! black box can hook the gap between a tool's read and its write. The +//! second half spawns the real binary over scratch trees, as a host would. +//! +//! 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-edit-tools/README.md`. + +use std::collections::BTreeMap; +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::sync::Arc; +use std::time::Duration; + +use serde_json::{json, Value}; + +/// Stand-in for `crate::project`: the two questions `apply.rs` asks. +mod project { + use std::path::{Path, PathBuf}; + + pub struct Project { + roots: Vec, + } + + impl Project { + pub fn open(roots: Vec, _filelist: Option) -> Project { + Project { roots } + } + + pub fn roots(&self) -> &[PathBuf] { + &self.roots + } + + pub fn relative(&self, path: &Path) -> String { + let inside = self.roots.iter().find_map(|root| path.strip_prefix(root).ok()); + inside.unwrap_or(path).display().to_string() + } + } +} + +/// Stand-in for `crate::tools`: the answer type `apply.rs` builds. +mod tools { + pub struct Answer { + pub text: String, + pub structured: serde_json::Value, + } +} + +#[path = "../src/apply.rs"] +mod apply; + +const BIN: &str = env!("CARGO_BIN_EXE_lucisv-mcp"); +const ANSWER_TIMEOUT: Duration = Duration::from_secs(60); + +static NEXT_DIR: AtomicUsize = AtomicUsize::new(0); + +/// A scratch directory, removed on drop. +struct Scratch(PathBuf); + +impl Scratch { + fn empty() -> Scratch { + let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst); + let dir = + std::env::temp_dir().join(format!("lucisv-mcp-qa3-{}-{unique}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + Scratch(fs::canonicalize(dir).unwrap()) + } + + /// A scratch tree holding `files` (relative path, contents). + fn with(files: &[(&str, &str)]) -> Scratch { + let scratch = Scratch::empty(); + for (path, text) in files { + scratch.write(path, text); + } + scratch + } + + /// A fresh copy of `tests/fixtures/edit`. + fn edit_fixture() -> Scratch { + let scratch = Scratch::empty(); + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/edit"); + copy_tree(&source, &scratch.0); + scratch + } + + fn path(&self, relative: &str) -> PathBuf { + self.0.join(relative) + } + + fn write(&self, relative: &str, text: &str) { + let path = self.path(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + + fn read(&self, relative: &str) -> String { + fs::read_to_string(self.path(relative)).unwrap() + } + + fn root(&self) -> &str { + self.0.to_str().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 entry under a tree, root-relative: a file's bytes and mode, a +/// symlink's target, a directory's mode. Anything moving shows up. +fn snapshot(root: &Path) -> BTreeMap)> { + use std::os::unix::fs::PermissionsExt; + fn walk(dir: &Path, root: &Path, out: &mut BTreeMap)>) { + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + let relative = path.strip_prefix(root).unwrap().to_string_lossy().into_owned(); + let meta = fs::symlink_metadata(&path).unwrap(); + let mode = meta.permissions().mode(); + if meta.file_type().is_symlink() { + let target = fs::read_link(&path).unwrap(); + out.insert(relative, (mode, target.to_string_lossy().as_bytes().to_vec())); + } else if meta.is_dir() { + out.insert(format!("{relative}/"), (mode, Vec::new())); + walk(&path, root, out); + } else { + out.insert(relative, (mode, fs::read(&path).unwrap())); + } + } + } + let mut out = BTreeMap::new(); + walk(root, root, &mut out); + out +} + +/// The entries whose bytes or mode differ between two snapshots. +fn moved( + before: &BTreeMap)>, + after: &BTreeMap)>, +) -> Vec { + let mut names: Vec<&String> = before.keys().chain(after.keys()).collect(); + names.sort(); + names.dedup(); + names.into_iter().filter(|n| before.get(*n) != after.get(*n)).cloned().collect() +} + +/// One running server, past the handshake. +struct Session { + child: Child, + stdin: Option, + lines: Receiver, + next_id: i64, +} + +impl Session { + fn ready(root: &str) -> Session { + let mut child = Command::new(BIN) + .args(["--root", root]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let stdout = child.stdout.take().unwrap(); + let (send, lines) = mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { break }; + if send.send(line).is_err() { + break; + } + } + }); + let stdin = child.stdin.take(); + let mut session = Session { child, stdin, lines, next_id: 0 }; + session.request("initialize", json!({"protocolVersion": "2025-06-18"})); + session.send(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#); + session + } + + fn over(scratch: &Scratch) -> Session { + Session::ready(scratch.root()) + } + + fn send(&mut self, line: &str) { + let stdin = self.stdin.as_mut().unwrap(); + stdin.write_all(format!("{line}\n").as_bytes()).unwrap(); + stdin.flush().unwrap(); + } + + fn request(&mut self, method: &str, params: Value) -> Value { + self.next_id += 1; + let id = self.next_id; + self.send( + &json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string(), + ); + let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered"); + let reply: Value = serde_json::from_str(&line).expect("every stdout line is JSON"); + assert_eq!(reply["id"], id, "answers come back in order"); + reply + } + + fn call(&mut self, tool: &str, arguments: Value) -> Value { + self.request("tools/call", json!({"name": tool, "arguments": arguments}))["result"].clone() + } + + /// A call that must succeed: its whole result. + fn ok(&mut self, tool: &str, arguments: Value) -> Value { + let result = self.call(tool, arguments.clone()); + assert_eq!(result["isError"], false, "{tool} {arguments}: {result}"); + result + } + + /// A call that must succeed: its text. + fn text(&mut self, tool: &str, arguments: Value) -> String { + text_of(&self.ok(tool, arguments)) + } + + /// A call that must be refused: its sentence. + fn refusal(&mut self, tool: &str, arguments: Value) -> String { + let result = self.call(tool, arguments.clone()); + assert_eq!(result["isError"], true, "{tool} {arguments}: {result}"); + text_of(&result) + } +} + +impl Drop for Session { + fn drop(&mut self) { + drop(self.stdin.take()); + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn text_of(result: &Value) -> String { + result["content"][0]["text"].as_str().unwrap().to_string() +} + +/// `arguments` with `dry_run` set. +fn dry(arguments: &Value, dry_run: bool) -> Value { + let mut arguments = arguments.clone(); + arguments["dry_run"] = Value::from(dry_run); + arguments +} + +/// The `lucisv` CLI built beside `lucisv-mcp`, when the build made it +/// (`cargo test --workspace` does; `-p lucisv_mcp` alone may not). +fn cli() -> Option { + let path = Path::new(BIN).parent()?.join("lucisv"); + path.exists().then_some(path) +} + +/// `+`/`-` body lines of a unified diff (headers skipped). +fn signed_lines(diff: &str) -> (usize, usize) { + let body = diff.lines().filter(|l| !l.starts_with("--- ") && !l.starts_with("+++ ")); + let body: Vec<&str> = body.collect(); + let added = body.iter().filter(|l| l.starts_with('+')).count(); + let removed = body.iter().filter(|l| l.starts_with('-')).count(); + (added, removed) +} + +// ================================================ apply::commit, directly + +fn change(path: &Path, before: &str, after: &str) -> apply::Change { + apply::Change { + path: path.to_path_buf(), + before: before.into(), + after: after.into(), + created: false, + } +} + +fn base(path: &Path) -> String { + path.file_name().unwrap().to_string_lossy().into_owned() +} + +/// Three files in path order, all as the plan read them. +fn three(scratch: &Scratch) -> Vec { + ["a.sv", "b.sv", "c.sv"] + .iter() + .map(|name| { + let before = format!("module {}; endmodule\n", &name[..1]); + scratch.write(name, &before); + change(&scratch.path(name), &before, &before.replace("module ", "module x_")) + }) + .collect() +} + +#[test] +fn qa_commit_refuses_a_stale_file_first_middle_or_last_and_writes_none() { + for stale in 0..3 { + let scratch = Scratch::empty(); + let changes = three(&scratch); + let victim = &changes[stale].path; + // Same length, one byte different: a size or mtime check would miss it. + let moved_text = changes[stale].before.replace("endmodule", "endmodulE"); + fs::write(victim, &moved_text).unwrap(); + let pristine = snapshot(&scratch.0); + let refs: Vec<&apply::Change> = changes.iter().collect(); + let refused = apply::commit(&refs, base).unwrap_err(); + assert_eq!( + refused, + format!("`{}` changed on disk since it was read; nothing written.", base(victim)) + ); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "stale #{stale}"); + } +} + +#[test] +fn qa_commit_refuses_a_deleted_file_and_a_file_turned_directory() { + let scratch = Scratch::empty(); + let changes = three(&scratch); + let refs: Vec<&apply::Change> = changes.iter().collect(); + fs::remove_file(&changes[1].path).unwrap(); + let pristine = snapshot(&scratch.0); + let refused = apply::commit(&refs, base).unwrap_err(); + assert!(refused.starts_with("`b.sv` cannot be read again"), "{refused}"); + assert!(refused.ends_with("; nothing written."), "{refused}"); + fs::create_dir(&changes[1].path).unwrap(); + let refused = apply::commit(&refs, base).unwrap_err(); + assert!(refused.starts_with("`b.sv` cannot be read again"), "{refused}"); + let mut after = snapshot(&scratch.0); + after.remove("b.sv/"); + assert!(moved(&pristine, &after).is_empty()); +} + +#[test] +fn qa_commit_is_byte_based_a_rewrite_with_the_same_bytes_still_lands() { + let scratch = Scratch::empty(); + let changes = three(&scratch); + // Rewritten (new inode, new mtime), bytes identical: fresh by the rule. + let path = &changes[2].path; + let tmp = scratch.path("c.tmp"); + fs::write(&tmp, &changes[2].before).unwrap(); + fs::rename(&tmp, path).unwrap(); + let refs: Vec<&apply::Change> = changes.iter().collect(); + apply::commit(&refs, base).unwrap(); + for change in &changes { + assert_eq!(fs::read_to_string(&change.path).unwrap(), change.after); + } +} + +#[test] +fn qa_commit_refuses_a_created_path_taken_by_a_dangling_symlink_or_a_directory() { + let scratch = Scratch::empty(); + let changes = three(&scratch); + let new = scratch.path("n.sv"); + let created = apply::Change { + path: new.clone(), + before: String::new(), + after: "x\n".into(), + created: true, + }; + let mut refs: Vec<&apply::Change> = changes.iter().collect(); + refs.push(&created); + std::os::unix::fs::symlink(scratch.path("nowhere/at/all.sv"), &new).unwrap(); + let pristine = snapshot(&scratch.0); + assert_eq!(apply::commit(&refs, base).unwrap_err(), "`n.sv` already exists; nothing written."); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty()); + fs::remove_file(&new).unwrap(); + fs::create_dir(&new).unwrap(); + let pristine = snapshot(&scratch.0); + assert_eq!(apply::commit(&refs, base).unwrap_err(), "`n.sv` already exists; nothing written."); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty()); +} + +#[test] +fn qa_commit_refuses_a_read_only_last_file_before_writing_the_first() { + use std::os::unix::fs::PermissionsExt; + let scratch = Scratch::empty(); + let changes = three(&scratch); + fs::set_permissions(&changes[2].path, fs::Permissions::from_mode(0o444)).unwrap(); + let pristine = snapshot(&scratch.0); + let refs: Vec<&apply::Change> = changes.iter().collect(); + assert_eq!(apply::commit(&refs, base).unwrap_err(), "`c.sv` is read-only; nothing written."); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty()); +} + +#[test] +fn qa_plan_refuses_an_unread_file_overlapping_edits_and_a_split_character() { + use vlog_parser::span::TextRange; + use vlog_refactor::{RefactorEdit, TextEdit}; + let scratch = Scratch::empty(); + let read = scratch.path("r.sv"); + let texts = vec![(read.clone(), "module é; endmodule\n".to_string())]; + let edit = |path: &Path, start: u32, end: u32| RefactorEdit { + edits: vec![( + path.to_path_buf(), + vec![TextEdit { range: TextRange::new(start, end), new_text: "z".into() }], + )], + ..RefactorEdit::default() + }; + let unread = apply::Plan::from_refactor(edit(&scratch.path("u.sv"), 0, 1), &texts); + assert!(unread.err().unwrap().contains("which was not read")); + let split = apply::Plan::from_refactor(edit(&read, 8, 9), &texts); + assert!(split.err().unwrap().contains("splits a character")); + let past = apply::Plan::from_refactor(edit(&read, 3, 99), &texts); + assert!(past.err().unwrap().contains("past the end")); + let two = RefactorEdit { + edits: vec![( + read.clone(), + vec![ + TextEdit { range: TextRange::new(0, 6), new_text: "a".into() }, + TextEdit { range: TextRange::new(5, 7), new_text: "b".into() }, + ], + )], + ..RefactorEdit::default() + }; + assert!(apply::Plan::from_refactor(two, &texts).err().unwrap().contains("overlap")); + // A fitting edit plans, and `run` in dry-run mode writes nothing. + fs::write(&read, &texts[0].1).unwrap(); + let plan = apply::Plan::from_refactor(edit(&read, 0, 6), &texts).unwrap(); + let project = project::Project::open(vec![scratch.0.clone()], None); + let pristine = snapshot(&scratch.0); + let answer = apply::run(&project, plan, true).unwrap(); + assert!(answer.text.contains("(dry run: nothing written)"), "{}", answer.text); + assert_eq!(answer.structured["changed"][0]["file"], "r.sv"); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty()); +} + +// ================================================ corruption hunt (attack 1) + +/// Every edit tool, one real call over a fresh fixture copy: exactly the +/// reported files move, each reported count matches the dry run's diff, the +/// dry-run diff is the diff of what was written, and the same call again +/// writes nothing. +#[test] +fn qa_every_edit_writes_only_what_it_reports_and_a_repeat_writes_nothing() { + let calls = [ + ("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"})), + ("rename", json!({"name": "d", "unit": "leaf", "new_name": "din_i"})), + ("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6})), + ("convert_ports", json!({"file": "rtl/old.sv", "line": 1})), + ("organize_imports", json!({"file": "rtl/top.sv", "line": 6})), + ("inline_module", json!({"file": "rtl/inl.sv", "line": 5})), + ("propagate_ports", json!({"file": "rtl/partial.sv", "line": 6})), + ("remove_port", json!({"file": "rtl/spare.sv", "line": 3, "name": "unused_i"})), + ("add_port", json!({"module": "leaf", "declaration": "input logic en"})), + ( + "add_port", + json!({"file": "rtl/cell.sv", "line": 3, "declaration": "input logic rst_ni"}), + ), + ( + "extract_module", + json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}), + ), + ( + "extract_module", + json!({"file": "rtl/ext.sv", "start_line": 8, "end_line": 8, "new_name": "reg8", "home": "same_file"}), + ), + ("format", json!({"files": "fmt/messy.sv,rtl/mid.sv"})), + ("fix_lint", json!({"file": "fmt/messy.sv"})), + ]; + for (tool, arguments) in calls { + let scratch = Scratch::edit_fixture(); + scratch.write("fmt/messy.sv", "module messy(input logic a,output logic b); \nassign b=a;\n // keep this comment\nendmodule"); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + let preview = server.ok(tool, dry(&arguments, true))["structuredContent"].clone(); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{tool}: dry run wrote"); + let result = server.ok(tool, dry(&arguments, false)); + let written = snapshot(&scratch.0); + let reported = &result["structuredContent"]; + let mut listed: Vec = ["changed", "created"] + .iter() + .flat_map(|key| reported[*key].as_array().unwrap().clone()) + .map(|entry| entry["file"].as_str().unwrap().to_string()) + .collect(); + listed.sort(); + assert_eq!(moved(&pristine, &written), listed, "{tool} {arguments}: {result}"); + for key in ["changed", "created"] { + for (real, shown) in + reported[key].as_array().unwrap().iter().zip(preview[key].as_array().unwrap()) + { + let file = real["file"].as_str().unwrap(); + let before = pristine.get(file).map(|(_, b)| b.clone()).unwrap_or_default(); + let after = &written[file].1; + let diff = lucisv_core::diff::unified( + file, + std::str::from_utf8(&before).unwrap(), + std::str::from_utf8(after).unwrap(), + ); + assert_eq!(shown["diff"].as_str().unwrap(), diff, "{tool}: {file}"); + let (added, removed) = signed_lines(&diff); + assert_eq!( + (real["added"].as_u64(), real["removed"].as_u64()), + (Some(added as u64), Some(removed as u64)), + "{tool}: {file}" + ); + } + } + let again = server.call(tool, dry(&arguments, false)); + let said = text_of(&again); + assert!( + said.starts_with("unchanged") || again["isError"] == true, + "{tool}: a repeat must write nothing: {said}" + ); + assert!(moved(&written, &snapshot(&scratch.0)).is_empty(), "{tool}: the repeat wrote"); + } +} + +/// A refusal from every tool — engine refusals, argument refusals, path +/// refusals — and not one byte or mode bit of the tree moves. +#[test] +fn qa_every_refusal_leaves_every_byte_and_mode_identical() { + let scratch = Scratch::edit_fixture(); + scratch.write("fmt/broken.sv", "module broken(input a;\n assign = ;\nendmodule\n"); + scratch.write( + "rtl/pos.sv", + "module pos (input logic clk, input logic en, output logic o);\n cell u_p (clk, en, o);\nendmodule\n", + ); + let outside = Scratch::with(&[("o.sv", "module o; endmodule\n")]); + std::os::unix::fs::symlink(&outside.0, scratch.path("out")).unwrap(); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + let outside_pristine = snapshot(&outside.0); + let refused = [ + ("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "module"})), + ("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "clk"})), + ("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "\\a+b "})), + ("rename", json!({"name": "clk", "new_name": "ck"})), + ("rename", json!({"file": "out/o.sv", "line": 1, "col": 8, "new_name": "p"})), + ("expand_wildcard", json!({"file": "rtl/pos.sv", "line": 2})), + ("convert_ports", json!({"file": "rtl/leaf.sv", "line": 1})), + ("organize_imports", json!({"file": "rtl/leaf.sv", "line": 99})), + ("inline_module", json!({"file": "rtl/pos.sv", "line": 2})), + ("inline_module", json!({"file": "rtl/wild.sv", "line": 6})), + ("propagate_ports", json!({"file": "rtl/mid.sv", "line": 6})), + ("propagate_ports", json!({"file": "rtl/wild.sv", "line": 6})), + ("remove_port", json!({"file": "rtl/cell.sv", "line": 3, "name": "en"})), + ("remove_port", json!({"file": "rtl/pos.sv", "line": 1, "name": "en"})), + ("add_port", json!({"module": "cell", "declaration": "input logic en"})), + ("add_port", json!({"module": "cell", "declaration": "input logic newp"})), + ( + "extract_module", + json!({"file": "rtl/ext.sv", "start_line": 1, "end_line": 2, "new_name": "x2"}), + ), + ( + "extract_module", + json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "leaf"}), + ), + ( + "extract_module", + json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "../x"}), + ), + ( + "extract_module", + json!({"file": "out/o.sv", "start_line": 1, "end_line": 1, "new_name": "x3"}), + ), + ("format", json!({"files": "fmt/messy.sv,fmt/broken.sv"})), + ("format", json!({"file": "out/o.sv"})), + ("format", json!({"file": "fmt/messy.sv", "lines": "3-1"})), + ("fix_lint", json!({"file": "/etc/hosts"})), + ("instantiate", json!({"name": "nothing_here"})), + ]; + for (tool, arguments) in refused { + let said = server.refusal(tool, arguments.clone()); + assert!(!said.is_empty()); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{tool} {arguments}: {said}"); + assert!(moved(&outside_pristine, &snapshot(&outside.0)).is_empty(), "{tool}: {said}"); + } +} + +/// Comments beside every edited span survive: a port with a trailing +/// comment renamed, a `.*` with comments in its list expanded, a block with +/// a leading and a trailing comment extracted. +#[test] +fn qa_comments_around_every_edited_span_survive() { + let scratch = Scratch::with(&[ + ( + "leaf.sv", + "module leaf (\n input logic clk, // the clock\n input logic [7:0] d, // data in /* not nested */\n output logic [7:0] q // data out\n);\n always_ff @(posedge clk) q <= d; // register\nendmodule\n", + ), + ( + "top.sv", + "module top (\n input logic clk,\n input logic [7:0] d,\n output logic [7:0] q\n);\n // the instance\n leaf u_leaf (\n // leading\n .* // trailing star comment\n /* block */\n );\nendmodule\n", + ), + ( + "ext.sv", + "module ext (\n input logic clk,\n input logic [7:0] a,\n output logic [7:0] q\n);\n logic [7:0] s;\n // the adder\n assign s = a + 8'd1; // plus one\n always_ff @(posedge clk) q <= s;\nendmodule\n", + ), + ]); + let comments = [ + "// the clock", + "// data in /* not nested */", + "// data out", + "// register", + "// the instance", + "// leading", + "// trailing star comment", + "/* block */", + "// the adder", + "// plus one", + ]; + let count = |scratch: &Scratch, comment: &str| -> usize { + snapshot(&scratch.0) + .values() + .map(|(_, bytes)| String::from_utf8_lossy(bytes).matches(comment).count()) + .sum() + }; + let before: Vec = comments.iter().map(|c| count(&scratch, c)).collect(); + let mut server = Session::over(&scratch); + server.text("expand_wildcard", json!({"file": "top.sv", "line": 7})); + server.text( + "extract_module", + json!({"file": "ext.sv", "start_line": 7, "end_line": 8, "new_name": "adder"}), + ); + server.text("rename", json!({"file": "leaf.sv", "line": 3, "name": "d", "new_name": "din"})); + let after: Vec = comments.iter().map(|c| count(&scratch, c)).collect(); + assert_eq!(before, after, "{:?}", snapshot(&scratch.0).keys().collect::>()); + assert!(scratch.read("leaf.sv").contains("din, // data in"), "{}", scratch.read("leaf.sv")); + assert!(scratch.read("top.sv").contains(".din(d)"), "{}", scratch.read("top.sv")); +} + +// ================================================ write-freshness race (attack 2) + +/// A real `rename` back and forth in a loop while another thread rewrites +/// one of its target files every 50 ms (atomically, alternating the +/// unrenamed and renamed text plus a marker line). After every call each +/// file is wholly one form or the other — never a half-applied file — and +/// every freshness refusal names the file that moved. +#[test] +fn qa_a_rename_racing_a_writer_never_tears_a_file() { + let scratch = Scratch::edit_fixture(); + let files = ["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"]; + let target = "rtl/mid.sv"; + let mut server = Session::over(&scratch); + let at = |from: &str, to: &str| json!({"file": "rtl/leaf.sv", "line": 3, "name": from, "new_name": to}); + let original: Vec = files.iter().map(|f| scratch.read(f)).collect(); + server.text("rename", at("d", "din_i")); + let renamed: Vec = files.iter().map(|f| scratch.read(f)).collect(); + server.text("rename", at("din_i", "d")); + assert_eq!(original, files.iter().map(|f| scratch.read(f)).collect::>()); + + let stop = Arc::new(AtomicBool::new(false)); + let writer = { + let stop = Arc::clone(&stop); + let path = scratch.path(target); + let forms = [original[1].clone(), renamed[1].clone()]; + std::thread::spawn(move || { + let mut n = 0usize; + while !stop.load(Ordering::SeqCst) { + let body = format!("{}// w{n}\n", forms[n % 2]); + let tmp = path.with_extension("w"); + fs::write(&tmp, body).unwrap(); + fs::rename(&tmp, &path).unwrap(); + n += 1; + std::thread::sleep(Duration::from_millis(50)); + } + }) + }; + let (mut written, mut stale) = (0, 0); + for _ in 0..80 { + let line = scratch.read("rtl/leaf.sv").lines().nth(2).unwrap().to_string(); + let (from, to) = if line.contains("din_i") { ("din_i", "d") } else { ("d", "din_i") }; + let result = server.call("rename", at(from, to)); + let said = text_of(&result); + if result["isError"] == false { + written += 1; + } else if said.contains("changed on disk") { + stale += 1; + assert!(said.contains(target), "a freshness refusal names the file: {said}"); + } + for (i, file) in files.iter().enumerate() { + let text = scratch.read(file); + let text = match text.rfind("// w") { + Some(mark) if *file == target => text[..mark].to_string(), + _ => text, + }; + assert!(text == original[i] || text == renamed[i], "{file} is torn:\n{text}"); + } + std::thread::sleep(Duration::from_millis(7)); + } + stop.store(true, Ordering::SeqCst); + writer.join().unwrap(); + assert!(written > 0, "the loop must exercise real writes (stale refusals: {stale})"); +} + +// ================================================ paths (attack 3) + +#[test] +fn qa_created_and_rewritten_paths_never_leave_the_root() { + let scratch = Scratch::edit_fixture(); + let outside = Scratch::with(&[("ext.sv", &Scratch::edit_fixture().read("rtl/ext.sv"))]); + std::os::unix::fs::symlink(&outside.0, scratch.path("link")).unwrap(); + std::os::unix::fs::symlink(outside.path("adder.sv"), scratch.path("rtl/adder.sv")).unwrap(); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + let outside_pristine = snapshot(&outside.0); + let extract = |file: &str, name: &str| json!({"file": file, "start_line": 7, "end_line": 7, "new_name": name}); + for name in ["../evil", "/tmp/evil", "\\../../evil ", "a/b", ""] { + let said = server.refusal("extract_module", extract("rtl/ext.sv", name)); + assert!(!said.is_empty()); + } + let said = server.refusal("extract_module", extract("link/ext.sv", "adder")); + assert!(said.contains("outside every root"), "{said}"); + let abs = outside.path("ext.sv"); + let said = server.refusal("extract_module", extract(abs.to_str().unwrap(), "adder")); + assert!(said.contains("outside every root"), "{said}"); + // A dangling symlink at the created path, pointing out of the root. + let said = server.refusal("extract_module", extract("rtl/ext.sv", "adder")); + assert!(said.contains("adder.sv"), "{said}"); + fs::remove_file(scratch.path("rtl/adder.sv")).unwrap(); + fs::create_dir(scratch.path("rtl/adder.sv")).unwrap(); + let said = server.refusal("extract_module", extract("rtl/ext.sv", "adder")); + assert!(said.contains("adder.sv"), "{said}"); + fs::remove_dir(scratch.path("rtl/adder.sv")).unwrap(); + std::os::unix::fs::symlink(outside.path("adder.sv"), scratch.path("rtl/adder.sv")).unwrap(); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty()); + assert!(moved(&outside_pristine, &snapshot(&outside.0)).is_empty()); + assert!(!Path::new("/tmp/evil.sv").exists()); +} + +#[test] +fn qa_a_read_only_target_refuses_before_the_first_write() { + use std::os::unix::fs::PermissionsExt; + let scratch = Scratch::edit_fixture(); + // `top.sv` sorts last of the rename's three files. + fs::set_permissions(scratch.path("rtl/top.sv"), fs::Permissions::from_mode(0o444)).unwrap(); + // A trailing blank so `fix_lint` has something to write. + scratch.write("fmt/messy.sv", &scratch.read("fmt/messy.sv").replace("b=a;", "b=a; ")); + fs::set_permissions(scratch.path("fmt/messy.sv"), fs::Permissions::from_mode(0o444)).unwrap(); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + let said = server.refusal( + "rename", + json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"}), + ); + assert_eq!(said, "`rtl/top.sv` is read-only; nothing written."); + let said = server.refusal("format", json!({"files": "fmt/messy.sv"})); + assert_eq!(said, "`fmt/messy.sv` is read-only; nothing written."); + let said = server.refusal("fix_lint", json!({"file": "fmt/messy.sv"})); + assert_eq!(said, "`fmt/messy.sv` is read-only; nothing written."); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty()); +} + +#[test] +fn qa_formatting_through_a_symlink_writes_the_file_and_keeps_the_link() { + let scratch = Scratch::with(&[("real.sv", "module r(input logic a);\nendmodule\n")]); + std::os::unix::fs::symlink("real.sv", scratch.path("alias.sv")).unwrap(); + let mut server = Session::over(&scratch); + let text = server.text("format", json!({"files": "alias.sv,real.sv"})); + assert_eq!(text, "files: 1 changed, 0 created\n real.sv +1 -1\n"); + assert!(fs::symlink_metadata(scratch.path("alias.sv")).unwrap().file_type().is_symlink()); + assert_eq!(scratch.read("real.sv"), "module r (input logic a);\nendmodule\n"); +} + +// ================================================ concurrency with the CLI (attack 4) + +#[test] +fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() { + let Some(cli) = cli() else { + eprintln!("skipped: no `lucisv` beside `lucisv-mcp` (run the workspace suite)"); + return; + }; + let scratch = Scratch::empty(); + let messy: Vec<(String, String)> = (0..60) + .map(|n| { + let text = format!( + "module m{n}(input logic a,output logic b);\nassign b=a; // c{n}\nendmodule\n" + ); + (format!("m{n:02}.sv"), text) + }) + .collect(); + for (name, text) in &messy { + scratch.write(name, text); + } + let names: Vec = messy.iter().map(|(name, _)| name.clone()).collect(); + let reference = Scratch::empty(); + copy_tree(&scratch.0, &reference.0); + let status = Command::new(&cli).arg("--no-cache").arg(&reference.0).output().unwrap(); + assert!(status.status.success(), "{status:?}"); + let stop = Arc::new(AtomicBool::new(false)); + let checker = { + let (stop, cli, root) = (Arc::clone(&stop), cli.clone(), scratch.0.clone()); + std::thread::spawn(move || { + let mut codes = Vec::new(); + while !stop.load(Ordering::SeqCst) { + let out = + Command::new(&cli).args(["--check", "--no-cache"]).arg(&root).output().unwrap(); + codes.push(out.status.code()); + } + codes + }) + }; + let mut server = Session::over(&scratch); + let files = names.join(","); + for _ in 0..5 { + for (name, text) in &messy { + scratch.write(name, text); + } + let result = server.call("format", json!({"files": files})); + let said = text_of(&result); + assert!(result["isError"] == false || said.contains("changed on disk"), "{said}"); + } + server.text("format", json!({"files": files})); + stop.store(true, Ordering::SeqCst); + let codes = checker.join().unwrap(); + assert!(!codes.is_empty()); + assert!(codes.iter().all(|c| matches!(c, Some(0) | Some(1))), "{codes:?}"); + for name in &names { + assert_eq!(scratch.read(name), reference.read(name), "{name}"); + } +} + +// ================================================ format (attack 5) + +/// `format` writes what `lucisv` writes, byte for byte: a CRLF file, a file +/// under a nested lucisv.toml with a different line length, a fenced +/// region, and `lines` ranges that overlap, run backwards in order, or pass +/// the end. +#[test] +fn qa_format_writes_the_clis_bytes() { + let Some(cli) = cli() else { + eprintln!("skipped: no `lucisv` beside `lucisv-mcp` (run the workspace suite)"); + return; + }; + let long = "module w(input logic aaaaaaaaaaaaaaaa,input logic bbbbbbbbbbbbbbbbbbbbbbbb,output logic cccccccccccccccccccc);\nassign cccccccccccccccccccc=aaaaaaaaaaaaaaaa&bbbbbbbbbbbbbbbbbbbbbbbb;\nendmodule\n"; + let files: &[(&str, &str)] = &[ + ("crlf.sv", "module crlf(input logic a,output logic b);\r\n // c\r\nassign b=a;\r\nendmodule\r\n"), + ("sub/lucisv.toml", "line-length = 40\nindent = 4\n"), + ("sub/w.sv", long), + ("w.sv", long), + ( + "fence.sv", + "module f(input logic a,output logic b);\n// lucisv: off\nassign b=a;\n// lucisv: on\nlogic c;\nendmodule\n", + ), + ("r.sv", "module r(input logic a,output logic b);\nlogic x;\nassign b=a;\nlogic y;\nendmodule\n"), + ]; + let mcp = Scratch::with(files); + let mut server = Session::over(&mcp); + for file in ["crlf.sv", "sub/w.sv", "w.sv", "fence.sv"] { + let cli_tree = Scratch::with(files); + let out = Command::new(&cli).arg("--no-cache").arg(cli_tree.path(file)).output().unwrap(); + assert!(out.status.success(), "{out:?}"); + server.text("format", json!({"file": file})); + assert_eq!(mcp.read(file), cli_tree.read(file), "{file}"); + } + for lines in ["2,1-2,99", "4,2", "4-4,2-2", "50-60", "1-999"] { + let cli_tree = Scratch::with(files); + let out = Command::new(&cli) + .args(["--no-cache", "--lines", lines]) + .arg(cli_tree.path("r.sv")) + .output() + .unwrap(); + assert!(out.status.success(), "{lines}: {out:?}"); + mcp.write("r.sv", files[5].1); + server.text("format", json!({"file": "r.sv", "lines": lines})); + assert_eq!(mcp.read("r.sv"), cli_tree.read("r.sv"), "lines {lines}"); + } + // A duplicate in `files` is one file, written once. + mcp.write("w.sv", long); + let text = server.text("format", json!({"files": "w.sv, w.sv,./w.sv", "dry_run": true})); + assert_eq!(text.matches("--- w.sv\n").count(), 1, "{text}"); +} + +// ================================================ fix_lint (attack 1, 5) + +/// `fix_lint` writes what `lucisv check --fix` writes: nothing inside a +/// `// lucisv: off` or `// verilog_format: off` fence, and never the +/// unsafe `always-comb` fix, even when that rule is the only one asked for. +#[test] +fn qa_fix_lint_matches_check_fix_and_never_touches_a_fence_or_an_unsafe_fix() { + let source = "module f (input logic a, output logic b, output logic c);\n\tlogic t; \n // lucisv: off \n assign b = a;; \n\tassign t = a;\n // lucisv: on\n always @* c = a;\n assign t2 = 4'b1;;\n // verilog_format: off\n wire z;; \n // verilog_format: on\nendmodule"; + let scratch = Scratch::with(&[("f.sv", source)]); + let mut server = Session::over(&scratch); + let unsafe_only = server.text("fix_lint", json!({"file": "f.sv", "rules": "always-comb"})); + assert!(unsafe_only.starts_with("unchanged\n"), "{unsafe_only}"); + assert_eq!(scratch.read("f.sv"), source); + server.text("fix_lint", json!({"file": "f.sv"})); + let fixed = scratch.read("f.sv"); + for fenced in [" // lucisv: off \n assign b = a;; \n\tassign t = a;\n", " wire z;; \n"] + { + assert!(fixed.contains(fenced), "a fenced line moved: {fixed:?}"); + } + assert!(fixed.contains("always @* c = a;"), "an unsafe fix was applied: {fixed:?}"); + if let Some(cli) = cli() { + let cli_tree = Scratch::with(&[("f.sv", source)]); + Command::new(&cli).args(["check", "--fix"]).arg(cli_tree.path("f.sv")).output().unwrap(); + assert_eq!(fixed, cli_tree.read("f.sv")); + } +} + +// ================================================ rename (attack 6) + +/// `vlog_refactor::rename` over every source file of the tree, applied — +/// the answer `rename` must write. +fn engine_rename(root: &Path, file: &str, offset: u32, new_name: &str) -> BTreeMap { + let mut files: Vec<(PathBuf, String)> = snapshot(root) + .into_iter() + .filter(|(name, _)| name.ends_with(".sv")) + .map(|(name, (_, bytes))| (root.join(name), String::from_utf8(bytes).unwrap())) + .collect(); + files.sort(); + let edit = vlog_refactor::rename(&files, &root.join(file), offset, new_name).unwrap(); + let mut out = BTreeMap::new(); + for (path, edits) in edit.edits { + let mut text = files.iter().find(|(p, _)| *p == path).unwrap().1.clone(); + for edit in edits.iter().rev() { + text.replace_range(edit.range.start as usize..edit.range.end as usize, &edit.new_text); + } + out.insert(path.strip_prefix(root).unwrap().display().to_string(), text); + } + out +} + +#[test] +fn qa_rename_writes_exactly_what_the_engine_answers_over_all_files() { + let scratch = Scratch::edit_fixture(); + let leaf = scratch.read("rtl/leaf.sv"); + let offset = leaf.find(" d,").unwrap() as u32 + 1; + let expected = engine_rename(&scratch.0, "rtl/leaf.sv", offset, "din_i"); + assert_eq!(expected.len(), 3); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + server.text("rename", json!({"name": "d", "unit": "leaf", "new_name": "din_i"})); + let written: Vec = moved(&pristine, &snapshot(&scratch.0)); + assert_eq!(written, expected.keys().cloned().collect::>()); + for (file, text) in &expected { + assert_eq!(&scratch.read(file), text, "{file}"); + } +} + +#[test] +fn qa_rename_by_bare_name_picks_the_declaration_references_picks() { + let scratch = Scratch::edit_fixture(); + let mut server = Session::over(&scratch); + let refs = server.ok("references", json!({"name": "din"}))["structuredContent"].clone(); + let mut hit_files: Vec = refs["hits"] + .as_array() + .unwrap() + .iter() + .map(|h| h["file"].as_str().unwrap().to_string()) + .collect(); + hit_files.dedup(); + let preview = server.ok("rename", json!({"name": "din", "new_name": "d_in", "dry_run": true})); + let files: Vec = preview["structuredContent"]["changed"] + .as_array() + .unwrap() + .iter() + .map(|c| c["file"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(files, hit_files); + // Ambiguous: refused, listing every site. + let said = server.refusal("rename", json!({"name": "q", "new_name": "qq"})); + for site in ["rtl/ext.sv:4", "rtl/leaf.sv:4"] { + assert!(said.contains(site), "{said}"); + } + assert!(said.contains("pick one"), "{said}"); +} + +#[test] +fn qa_rename_surfaces_the_engines_macro_warning() { + let scratch = Scratch::with(&[ + ("defs.svh", "`define PASS(x) (x)\n"), + ( + "m.sv", + "`include \"defs.svh\"\nmodule m (input logic sig_a, output logic y);\n assign y = `PASS(sig_a);\nendmodule\n", + ), + ]); + let mut server = Session::over(&scratch); + let text = server.text( + "rename", + json!({"file": "m.sv", "line": 2, "name": "sig_a", "new_name": "sig_b", "dry_run": true}), + ); + assert!(text.contains("warnings:\n `sig_a` appears in the arguments of the macro"), "{text}"); +} + +// ================================================ findings + +/// Finding 1 (blocking, engine): renaming a port bound by an implicit +/// connection (`.*` or `.name`), or a net such a connection binds, writes a +/// "verified" edit that silently changes the connectivity. It must refuse +/// (or rewrite the connection explicitly) — never leave the binding broken. +#[test] +#[ignore = "QA finding 1: engine limit, fixed in M3.5"] +fn qa_rename_never_breaks_an_implicit_port_connection() { + let files: &[(&str, &str)] = &[ + ( + "leaf.sv", + "module leaf (input logic clk, input logic [7:0] d, output logic [7:0] q);\n always_ff @(posedge clk) q <= d;\nendmodule\n", + ), + ( + "top.sv", + "module top (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.*);\nendmodule\n", + ), + ( + "top2.sv", + "module top2 (input logic clk, input logic [7:0] d, output logic [7:0] q);\n leaf u_leaf (.clk, .d, .q);\nendmodule\n", + ), + ]; + let cases = [ + // The port: `.*` in top.sv and `.d` in top2.sv stop binding it. + json!({"file": "leaf.sv", "line": 1, "name": "d", "new_name": "din"}), + // The net `.*` binds. + json!({"file": "top.sv", "line": 1, "name": "d", "new_name": "x"}), + // The net `.d` binds. + json!({"file": "top2.sv", "line": 1, "name": "d", "new_name": "x"}), + ]; + for arguments in cases { + let scratch = Scratch::with(files); + let mut server = Session::over(&scratch); + let result = server.call("rename", arguments.clone()); + if result["isError"] == true { + continue; + } + let top = scratch.read("top.sv"); + let top2 = scratch.read("top2.sv"); + let leaf = scratch.read("leaf.sv"); + let port = if leaf.contains("[7:0] din") { "din" } else { "d" }; + let net = |text: &str| if text.contains("[7:0] x") { "x" } else { "d" }; + // `.*` binds by equal names; `.name` connects the same-named net. + let star_ok = !top.contains("(.*)") || port == net(&top); + let dot_ok = top2.contains(&format!(".{port}({})", net(&top2))) + || (top2.contains(&format!(".{port},")) && port == net(&top2)); + assert!(star_ok && dot_ok, "{arguments}: {}\n{top}\n{top2}", text_of(&result)); + } +} + +/// Finding 2 (blocking): a rename leaves unrenamed every use in a file the +/// index skipped (over 1 MiB, or not UTF-8) and reports success without a +/// word. It must refuse, or at least name the file it could not read. +#[test] +fn qa_rename_says_so_when_a_skipped_file_mentions_the_name() { + let filler: String = (0..12_000) + .map(|i| format!(" // filler line {i:07} ...............................................................\n")) + .collect(); + let big = format!( + "module big (input logic clk, input logic [7:0] x, output logic [7:0] y);\n{filler} leaf u_l (.clk(clk), .d(x), .q(y));\nendmodule\n" + ); + let scratch = Scratch::edit_fixture(); + scratch.write("rtl/big.sv", &big); + let mut latin1 = b"// Copyright \xa9 2020\n".to_vec(); + latin1.extend_from_slice( + scratch.read("rtl/mid.sv").replace("module mid", "module mid2").as_bytes(), + ); + fs::write(scratch.path("rtl/mid2.sv"), latin1).unwrap(); + let mut server = Session::over(&scratch); + let result = server + .call("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"})); + let said = text_of(&result); + assert!( + result["isError"] == true || (said.contains("rtl/big.sv") && said.contains("rtl/mid2.sv")), + "a skipped file that spells the name is neither refused nor named: {said}" + ); +} + +/// Finding 3 (non-blocking, engine): `extract_module` into a CRLF file +/// writes its instantiation with LF line endings, leaving the file mixed. +#[test] +#[ignore = "QA finding 3: engine-side, Handshake MCP-10 to vlog_refactor"] +fn qa_extract_module_keeps_a_crlf_file_crlf() { + let scratch = Scratch::edit_fixture(); + let crlf = scratch.read("rtl/ext.sv").replace('\n', "\r\n"); + scratch.write("rtl/ext.sv", &crlf); + let mut server = Session::over(&scratch); + server.text( + "extract_module", + json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}), + ); + let ext = scratch.read("rtl/ext.sv"); + let bare = ext.split_inclusive('\n').filter(|line| !line.ends_with("\r\n")).count(); + assert_eq!(bare, 0, "{ext:?}"); +} + +/// Finding 4 (non-blocking, lead's ruling: no change): `"dry_run": null` +/// means absent — JSON null is "not given" for every argument — so the edit +/// is written; `"true"` and `1` are refused as non-booleans. +#[test] +fn qa_a_null_dry_run_is_absent_and_a_non_boolean_is_refused() { + let scratch = Scratch::edit_fixture(); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + for not_boolean in [json!("true"), json!(1)] { + let arguments = json!({"file": "fmt/messy.sv", "dry_run": not_boolean}); + server.refusal("format", arguments); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty()); + } + let result = server.call("format", json!({"file": "fmt/messy.sv", "dry_run": null})); + assert_eq!(moved(&pristine, &snapshot(&scratch.0)), ["fmt/messy.sv"], "{}", text_of(&result)); +} + +/// Finding 5 (non-blocking): `instantiate` takes any `instance` string, so +/// an empty or non-identifier name renders text that does not parse. +#[test] +fn qa_instantiate_refuses_an_instance_name_that_is_not_an_identifier() { + let scratch = Scratch::edit_fixture(); + let mut server = Session::over(&scratch); + for instance in ["", "a b", "u_x); evil (", "module"] { + server.refusal("instantiate", json!({"name": "leaf", "instance": instance})); + } +} + +// ================================================ re-check, 2026-09-23 (finding 2's rework) + +/// A 1.1 MB file: `module big` with `line` before `endmodule`. +fn oversized(line: &str) -> String { + let filler: String = (0..12_000) + .map(|i| format!(" // filler line {i:07} ...............................................................\n")) + .collect(); + format!("module big (input logic clk);\n{filler}{line}endmodule\n") +} + +/// A file that is not UTF-8 (a Latin-1 `©`) holding `body`. +fn latin1(body: &[u8]) -> Vec { + let mut bytes = b"// Copyright \xa9 2020 vendor\n".to_vec(); + bytes.extend_from_slice(body); + bytes +} + +const RENAME_D: fn(bool) -> Value = |dry_run| json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i", "dry_run": dry_run}); + +#[test] +fn qa_recheck_a_skipped_file_spelling_the_name_refuses_naming_file_and_reason() { + let use_d = " leaf u_l (.clk(clk), .d(x), .q(y));\n"; + let cases: [(&str, Vec, &str); 2] = [ + ("rtl/big.sv", oversized(use_d).into_bytes(), "over 1 MiB"), + ("rtl/lat.sv", latin1(use_d.as_bytes()), "not UTF-8 text"), + ]; + for (file, bytes, why) in cases { + let scratch = Scratch::edit_fixture(); + fs::write(scratch.path(file), &bytes).unwrap(); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + for dry_run in [true, false] { + let said = server.refusal("rename", RENAME_D(dry_run)); + assert_eq!( + said, + format!("`{file}` (skipped: {why}) may reference `d`; lucisv-mcp will not edit around a file it cannot index; nothing written.") + ); + } + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{file}"); + } +} + +/// The name only inside other words (`data`, `d_q`, `dd`, `d$x`, `x$d`, +/// the escaped `\dx `): not a refusal, and the skipped file is named once. +#[test] +fn qa_recheck_a_substring_only_is_written_with_the_skipped_file_named() { + let only_inside = " wire data, d_q, dd, d$x, x$d, \\dx ; // odd, dd\n"; + let cases: [(&str, Vec, &str); 2] = [ + ("rtl/big.sv", oversized(only_inside).into_bytes(), "over 1 MiB"), + ("rtl/lat.sv", latin1(only_inside.as_bytes()), "not UTF-8 text"), + ]; + for (file, bytes, why) in cases { + let scratch = Scratch::edit_fixture(); + fs::write(scratch.path(file), &bytes).unwrap(); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + let text = server.text("rename", RENAME_D(false)); + let line = format!("warnings:\n not indexed, so not searched or edited: {file} ({why})\n"); + assert!(text.contains(&line), "{text}"); + assert_eq!(text.matches("not indexed").count(), 1, "{text}"); + let written = moved(&pristine, &snapshot(&scratch.0)); + assert_eq!(written, ["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"]); + assert_eq!(fs::read(scratch.path(file)).unwrap(), bytes); + } +} + +/// The whole-word rule at its edges: the name at the very first and very +/// last byte of the file, beside `.` and `(`, escaped (`\d ` is `d`), and +/// beside a non-ASCII byte — each a refusal, never a miss. +#[test] +fn qa_recheck_the_whole_word_rule_holds_at_every_edge() { + let latin: [&[u8]; 6] = [ + b"d\xa9 is first", + b"\xa9 last is d", + b"\xa9\n x u (.d(1));\n", + b"\xa9\n assign y = f(d);\n", + b"\xa9\n wire \\d ;\n", + b"\xa9d\xa9", + ]; + for bytes in latin { + let scratch = Scratch::edit_fixture(); + fs::write(scratch.path("rtl/lat.sv"), bytes).unwrap(); + let mut server = Session::over(&scratch); + let said = server.refusal("rename", RENAME_D(true)); + assert!(said.starts_with("`rtl/lat.sv` (skipped: not UTF-8 text)"), "{bytes:?}: {said}"); + } + let mut at_end = oversized("").into_bytes(); + at_end.extend_from_slice(b"d"); + let scratch = Scratch::edit_fixture(); + fs::write(scratch.path("rtl/big.sv"), at_end).unwrap(); + let said = Session::over(&scratch).refusal("rename", RENAME_D(true)); + assert!(said.starts_with("`rtl/big.sv` (skipped: over 1 MiB)"), "{said}"); +} + +/// An escaped declaration: the escaped spelling ended by a tab, a newline +/// or the end of the file refuses; `a+b` as an expression, or a longer +/// escaped name, does not. +#[test] +fn qa_recheck_an_escaped_name_is_guarded_by_its_escaped_spelling() { + let esc = "module esc (input logic \\a+b , output logic y);\n assign y = \\a+b ;\nendmodule\n"; + let rename = + json!({"file": "rtl/esc.sv", "line": 2, "col": 14, "new_name": "ab", "dry_run": true}); + let cases: [(&[u8], bool); 5] = [ + (b"\\a+b\t", true), + (b"x = \\a+b\n;", true), + (b"\\a+b", true), + (b"assign y = a+b;", false), + (b"wire \\a+bc ;", false), + ]; + for (body, refused) in cases { + let scratch = Scratch::edit_fixture(); + scratch.write("rtl/esc.sv", esc); + fs::write(scratch.path("rtl/lat.sv"), latin1(body)).unwrap(); + let mut server = Session::over(&scratch); + let result = server.call("rename", rename.clone()); + let said = text_of(&result); + assert_eq!(result["isError"] == true, refused, "{body:?}: {said}"); + if refused { + assert!(said.contains("may reference `\\a+b`"), "{said}"); + } + } +} + +/// Every whole-set edit tool refuses over its stake (the README's table) +/// when only a skipped file spells it; `organize_imports`, which stakes +/// nothing, writes and names the skipped file. +#[test] +fn qa_recheck_every_edit_tool_refuses_over_its_stake() { + let scratch = Scratch::edit_fixture(); + let spelled = + b"\xa9\n cell u_c (.clk(c)); old u_o (); inv u_i (); ext u_e (); spare u_s ();\n"; + fs::write(scratch.path("rtl/lat.sv"), latin1(spelled)).unwrap(); + let mut server = Session::over(&scratch); + let pristine = snapshot(&scratch.0); + let staked = [ + ("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6}), "cell"), + ("propagate_ports", json!({"file": "rtl/partial.sv", "line": 6}), "cell"), + ("inline_module", json!({"file": "rtl/inl.sv", "line": 5}), "inv"), + ("convert_ports", json!({"file": "rtl/old.sv", "line": 1}), "old"), + ("remove_port", json!({"file": "rtl/spare.sv", "line": 3, "name": "unused_i"}), "spare"), + ("add_port", json!({"module": "cell", "declaration": "input logic x_i"}), "cell"), + ( + "add_port", + json!({"file": "rtl/cell.sv", "line": 2, "declaration": "input logic x_i"}), + "cell", + ), + ( + "extract_module", + json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}), + "ext", + ), + ]; + for (tool, arguments, name) in staked { + let said = server.refusal(tool, arguments.clone()); + let expected = format!("`rtl/lat.sv` (skipped: not UTF-8 text) may reference `{name}`;"); + assert!(said.starts_with(&expected), "{tool} {arguments}: {said}"); + assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{tool}"); + } + let text = server.text("organize_imports", json!({"file": "rtl/top.sv", "line": 6})); + assert!(text.contains("not indexed, so not searched or edited: rtl/lat.sv"), "{text}"); +} + +/// A skipped file that is rewritten small and UTF-8 is searched once the +/// next walk sees it (until then the edit stays refused — the safe side); +/// an indexed file that stops being UTF-8 is refused on the very next call. +#[test] +fn qa_recheck_a_file_leaving_or_entering_the_skipped_set_is_followed() { + let use_d = " leaf u_l (.clk(clk), .d(x), .q(y));\n"; + let scratch = Scratch::edit_fixture(); + scratch.write("rtl/big.sv", &oversized(use_d)); + let mut server = Session::over(&scratch); + assert!(server.refusal("rename", RENAME_D(true)).starts_with("`rtl/big.sv`")); + scratch.write("rtl/big.sv", &format!("module big (input logic clk);\n{use_d}endmodule\n")); + let soon = server.call("rename", RENAME_D(true)); + assert!(soon["isError"] == true || text_of(&soon).contains("--- rtl/big.sv"), "{soon}"); + std::thread::sleep(Duration::from_millis(5_500)); + let later = server.text("rename", RENAME_D(true)); + assert!(later.contains("--- rtl/big.sv\n"), "{later}"); + assert!(!later.contains("not indexed"), "{later}"); + // The other way: `mid.sv` gains a Latin-1 byte. + let mid = scratch.read("rtl/mid.sv"); + fs::write(scratch.path("rtl/mid.sv"), latin1(mid.as_bytes())).unwrap(); + let said = server.refusal("rename", RENAME_D(true)); + assert!(said.starts_with("`rtl/mid.sv` (skipped: not UTF-8 text) may reference `d`"), "{said}"); +} + +/// The merge of `edit.rs::sources` and `nav.rs::all_files` into +/// `WholeSet::read` left `references` alone: at every identifier of the nav +/// fixture, adding a skipped file that spells nothing changes the answer +/// only by the one trailing warning line. +#[test] +fn qa_recheck_references_answers_only_gain_the_warning_line() { + let nav = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/nav"); + let (plain, partial) = (Scratch::empty(), Scratch::empty()); + copy_tree(&nav, &plain.0); + copy_tree(&nav, &partial.0); + fs::write(partial.path("rtl/zz.sv"), latin1(b"\xa9\xa9\n")).unwrap(); + let (mut a, mut b) = (Session::over(&plain), Session::over(&partial)); + let warning = "not indexed, so not searched or edited: rtl/zz.sv (not UTF-8 text)"; + let mut answered = 0; + for (file, (_, bytes)) in snapshot(&plain.0) { + if !file.ends_with(".sv") && !file.ends_with(".svh") { + continue; + } + let text = String::from_utf8(bytes).unwrap(); + for (i, line) in text.lines().enumerate() { + let bytes = line.as_bytes(); + for col in 0..bytes.len() { + let starts = (bytes[col].is_ascii_alphabetic() || bytes[col] == b'_') + && (col == 0 + || !(bytes[col - 1].is_ascii_alphanumeric() || bytes[col - 1] == b'_')); + if !starts { + continue; + } + let args = json!({"file": file, "line": i + 1, "col": col + 1}); + let (x, mut y) = + (a.call("references", args.clone()), b.call("references", args.clone())); + if x["isError"] == true { + assert_eq!(x, y, "{args}"); + continue; + } + answered += 1; + assert_eq!(text_of(&y), format!("{}warning: {warning}\n", text_of(&x)), "{args}"); + assert_eq!(y["structuredContent"]["warning"], warning, "{args}"); + y["structuredContent"].as_object_mut().unwrap().remove("warning"); + assert_eq!(x["structuredContent"], y["structuredContent"], "{args}"); + } + } + } + assert!(answered > 50, "{answered}"); +} + +/// Finding 6 (blocking): the whole set is "every indexed file", and the +/// index sees a file created since the last walk only after `REWALK_AFTER` +/// (5 s) — the edit tools do not walk (`rewalk: false`). A rename right +/// after an agent writes a new instantiation leaves it unrenamed and says +/// nothing; a new over-1 MiB file escapes the skipped-file guard the same way. +#[test] +fn qa_an_edit_sees_a_file_created_just_before_it() { + let scratch = Scratch::edit_fixture(); + let mut server = Session::over(&scratch); + server.text("rename", RENAME_D(true)); + scratch.write( + "rtl/newer.sv", + "module newer (input logic clk, input logic [7:0] x, output logic [7:0] y);\n leaf u_l (.clk(clk), .d(x), .q(y));\nendmodule\n", + ); + let result = server.call("rename", RENAME_D(false)); + let newer = scratch.read("rtl/newer.sv"); + assert!( + result["isError"] == true || newer.contains(".din_i(x)"), + "a file written just before the rename was left behind: {}\n{newer}", + text_of(&result) + ); +} + +/// Finding 7 (non-blocking): an over-1 MiB file reached through a symlink +/// leading out of the root is recorded as skipped (`project/files.rs`, the +/// size-cap branch skips the containment check the indexed branch makes), +/// so it refuses edits inside the root and the refusal prints its absolute +/// path outside the root. A small file behind the same kind of link is +/// dropped, as M1 rules; the large one should be too. +#[test] +fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() { + let scratch = Scratch::edit_fixture(); + let outside = Scratch::empty(); + outside.write("big.sv", &oversized(" leaf u_l (.clk(clk), .d(x), .q(y));\n")); + std::os::unix::fs::symlink(outside.path("big.sv"), scratch.path("rtl/big_link.sv")).unwrap(); + let mut server = Session::over(&scratch); + let text = server.text("rename", RENAME_D(true)); + assert!(!text.contains(outside.root()), "{text}"); +} diff --git a/crates/lucisv_mcp/tests/wire.rs b/crates/lucisv_mcp/tests/wire.rs index 525b8ce..fbaf8cb 100644 --- a/crates/lucisv_mcp/tests/wire.rs +++ b/crates/lucisv_mcp/tests/wire.rs @@ -186,18 +186,40 @@ fn tools_list_describes_every_tool_for_the_agent() { "definition", "references", "hierarchy", - "diagnostics" + "diagnostics", + "format", + "fix_lint", + "rename", + "expand_wildcard", + "convert_ports", + "organize_imports", + "inline_module", + "propagate_ports", + "remove_port", + "add_port", + "extract_module", + "instantiate" ] ); assert!(reply["result"].get("nextCursor").is_none()); + // The edit tools write; those whose second identical call writes nothing + // more say so. `instantiate` only answers with text. + let idempotent_edits = + ["format", "fix_lint", "expand_wildcard", "convert_ports", "organize_imports"]; for tool in tools { + let name = tool["name"].as_str().unwrap(); + let edits = names.iter().position(|n| *n == name).unwrap() >= 11 && name != "instantiate"; assert_eq!(tool["inputSchema"]["type"], "object"); assert_eq!(tool["inputSchema"]["additionalProperties"], false); assert!(tool["inputSchema"]["required"].is_array()); - assert_eq!(tool["annotations"]["readOnlyHint"], true); + assert_eq!(tool["annotations"]["readOnlyHint"], !edits, "{name}"); assert_eq!(tool["annotations"]["destructiveHint"], false); - assert_eq!(tool["annotations"]["idempotentHint"], true); + let idempotent = !edits || idempotent_edits.contains(&name); + assert_eq!(tool["annotations"]["idempotentHint"], idempotent, "{name}"); assert_eq!(tool["annotations"]["openWorldHint"], false); + if edits { + assert_eq!(tool["inputSchema"]["properties"]["dry_run"]["type"], "boolean", "{name}"); + } } } @@ -765,3 +787,303 @@ fn an_escaped_name_is_followed_across_files() { let at = json!({"file": "rtl/esc_user.sv", "line": 3, "col": 4}); assert_eq!(sites(&mut server, at), ["rtl/esc.sv:1:8 module"]); } + +// --------------------------------------------------------------------------- +// M3: the edit tools, over a fresh copy of `tests/fixtures/edit` per test. +// --------------------------------------------------------------------------- + +/// Every file under a tree, root-relative, with its bytes. +fn snapshot(tree: &Tree) -> std::collections::BTreeMap> { + fn walk(dir: &Path, root: &Path, out: &mut std::collections::BTreeMap>) { + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(&path, root, out); + } else { + let relative = + path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"); + out.insert(relative, fs::read(&path).unwrap()); + } + } + } + let mut out = std::collections::BTreeMap::new(); + walk(&tree.0, &tree.0, &mut out); + out +} + +/// The files whose bytes differ between two snapshots (added, removed or +/// changed). +fn moved( + before: &std::collections::BTreeMap>, + after: &std::collections::BTreeMap>, +) -> Vec { + let mut names: Vec<&String> = before.keys().chain(after.keys()).collect(); + names.sort(); + names.dedup(); + names.into_iter().filter(|n| before.get(*n) != after.get(*n)).cloned().collect() +} + +/// `arguments` with `dry_run` set. +fn dry(arguments: &Value, dry_run: bool) -> Value { + let mut arguments = arguments.clone(); + arguments["dry_run"] = Value::from(dry_run); + arguments +} + +/// One edit tool's life: a dry run shows a diff and writes nothing; the real +/// call writes exactly `touched`; the same call again writes nothing more +/// (answering `unchanged`, or the engine's "nothing to do" refusal). Returns +/// the real call's text. +fn exercise(tool: &str, arguments: Value, touched: &[&str]) -> String { + let tree = Tree::of("edit"); + let mut server = Session::over(&tree); + server.initialize(); + let pristine = snapshot(&tree); + let preview = server.text(tool, dry(&arguments, true)); + assert!(preview.contains("(dry run: nothing written)"), "{tool}: {preview}"); + for file in touched { + assert!(preview.contains(&format!("--- {file}\n")), "{tool}: {file} in {preview}"); + } + assert!(moved(&pristine, &snapshot(&tree)).is_empty(), "{tool}: a dry run wrote"); + let applied = server.text(tool, dry(&arguments, false)); + assert!(!applied.contains("--- "), "{tool}: a real run answers a summary: {applied}"); + let written = snapshot(&tree); + assert_eq!(moved(&pristine, &written), touched, "{tool}: {applied}"); + let again = server.call(tool, dry(&arguments, false)); + let said = again["content"][0]["text"].as_str().unwrap(); + assert!( + said.starts_with("unchanged") || again["isError"] == true, + "{tool}: a repeat must write nothing: {said}" + ); + assert!(moved(&written, &snapshot(&tree)).is_empty(), "{tool}: the repeat wrote: {said}"); + applied +} + +#[test] +fn rename_writes_three_files_and_a_repeat_is_unchanged() { + let args = json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"}); + let text = exercise("rename", args, &["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"]); + assert!(text.starts_with("files: 3 changed, 0 created\n"), "{text}"); + assert!(text.contains(" rtl/mid.sv +1 -1\n"), "{text}"); +} + +#[test] +fn rename_by_name_and_unit_reaches_every_file() { + let tree = Tree::of("edit"); + let mut server = Session::over(&tree); + server.initialize(); + let text = server.text("rename", json!({"name": "d", "unit": "leaf", "new_name": "data_i"})); + assert!(text.starts_with("files: 3 changed"), "{text}"); + let mid = fs::read_to_string(tree.path("rtl/mid.sv")).unwrap(); + assert!(mid.contains(".data_i (din)"), "{mid}"); +} + +#[test] +fn every_cursor_refactoring_previews_writes_and_repeats_as_a_no_op() { + exercise("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6}), &["rtl/wild.sv"]); + exercise( + "convert_ports", + json!({"file": "rtl/old.sv", "line": 1, "name": "old"}), + &["rtl/old.sv"], + ); + exercise("organize_imports", json!({"file": "rtl/top.sv", "line": 6}), &["rtl/top.sv"]); + exercise("inline_module", json!({"file": "rtl/inl.sv", "line": 5}), &["rtl/inl.sv"]); + exercise( + "propagate_ports", + json!({"file": "rtl/partial.sv", "line": 6, "name": "u_c"}), + &["rtl/partial.sv"], + ); + let removed = exercise( + "remove_port", + json!({"file": "rtl/spare.sv", "line": 3, "name": "unused_i"}), + &["rtl/spare.sv", "rtl/spare_user.sv"], + ); + assert!(removed.contains("was deleted with the port"), "{removed}"); +} + +#[test] +fn add_port_by_name_or_by_position_connects_every_instantiation() { + let added = exercise( + "add_port", + json!({"module": "spare", "declaration": "input logic en"}), + &["rtl/spare.sv", "rtl/spare_user.sv"], + ); + assert!(added.contains("warnings:\n no signal named `en`"), "{added}"); + let tree = Tree::of("edit"); + let mut server = Session::over(&tree); + server.initialize(); + let at = json!({"file": "rtl/cell.sv", "line": 2, "declaration": "input logic rst_ni"}); + let text = server.text("add_port", at); + assert!(text.contains(" rtl/cell.sv +"), "{text}"); + let both = + json!({"module": "cell", "file": "rtl/cell.sv", "line": 2, "declaration": "input logic x"}); + assert!(refusal(&mut server, "add_port", both).contains("not both")); +} + +#[test] +fn extract_module_creates_its_file_once_and_never_over_an_existing_one() { + let args = json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}); + let text = exercise("extract_module", args.clone(), &["rtl/adder.sv", "rtl/ext.sv"]); + assert!(text.starts_with("files: 1 changed, 1 created\n"), "{text}"); + assert!(text.contains(" rtl/adder.sv +6 -0 (created)\n"), "{text}"); + + let tree = Tree::of("edit"); + fs::write(tree.path("rtl/adder.sv"), "// taken\n").unwrap(); + let mut server = Session::over(&tree); + server.initialize(); + let before = snapshot(&tree); + let taken = refusal(&mut server, "extract_module", args); + assert!(taken.contains("adder.sv"), "{taken}"); + assert_eq!(before, snapshot(&tree)); + + let same = json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder2", "home": "same_file"}); + let text = server.text("extract_module", same); + assert!(text.starts_with("files: 1 changed, 0 created\n"), "{text}"); + assert!(fs::read_to_string(tree.path("rtl/ext.sv")).unwrap().contains("module adder2")); +} + +#[test] +fn a_refusal_leaves_the_tree_byte_identical() { + let tree = Tree::of("edit"); + let mut server = Session::over(&tree); + server.initialize(); + let before = snapshot(&tree); + let refused = [ + ("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "1bad"})), + ("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "q"})), + ("convert_ports", json!({"file": "rtl/leaf.sv", "line": 1})), + ("remove_port", json!({"file": "rtl/cell.sv", "line": 3, "name": "en"})), + ("expand_wildcard", json!({"file": "rtl/mid.sv", "line": 1})), + ("add_port", json!({"module": "spare", "declaration": "logic nodir"})), + ( + "extract_module", + json!({"file": "rtl/ext.sv", "start_line": 8, "end_line": 7, "new_name": "x"}), + ), + ("format", json!({"file": "../outside.sv"})), + ]; + for (tool, arguments) in refused { + let said = refusal(&mut server, tool, arguments.clone()); + assert!(!said.is_empty(), "{tool} {arguments}"); + assert_eq!(before, snapshot(&tree), "{tool} {arguments}: {said}"); + } +} + +#[test] +fn format_writes_every_file_or_none_and_repeats_unchanged() { + let text = exercise("format", json!({"files": "fmt/messy.sv, rtl/old.sv"}), &["fmt/messy.sv"]); + assert!(text.contains("unchanged: rtl/old.sv\n"), "{text}"); + + let tree = Tree::of("edit"); + fs::write(tree.path("fmt/broken.sv"), "module broken(;\nendmodule\n").unwrap(); + let mut server = Session::over(&tree); + server.initialize(); + let before = snapshot(&tree); + let said = refusal(&mut server, "format", json!({"files": "fmt/messy.sv,fmt/broken.sv"})); + assert!(said.starts_with("`fmt/broken.sv` was not formatted: "), "{said}"); + assert!(said.ends_with("; nothing written."), "{said}"); + assert_eq!(before, snapshot(&tree)); + let lines = + refusal(&mut server, "format", json!({"files": "fmt/messy.sv,rtl/leaf.sv", "lines": "1"})); + assert!(lines.contains("single file"), "{lines}"); + let ranged = server.text("format", json!({"file": "fmt/messy.sv", "lines": "2"})); + assert!(ranged.starts_with("files: 1 changed"), "{ranged}"); +} + +#[test] +fn format_on_a_crlf_file_is_the_formatters_own_output() { + let tree = Tree::of("edit"); + let source = + "module c (\r\n input logic a,\r\n output logic b\r\n);\r\nassign b=a;\r\nendmodule\r\n"; + fs::write(tree.path("fmt/crlf.sv"), source).unwrap(); + let mut server = Session::over(&tree); + server.initialize(); + let text = server.text("format", json!({"file": "fmt/crlf.sv"})); + assert!(text.starts_with("files: 1 changed"), "{text}"); + let expected = + vlog_formatter::format_source(source, &vlog_formatter::Config::default()).unwrap(); + assert_eq!(fs::read_to_string(tree.path("fmt/crlf.sv")).unwrap(), expected); + assert_eq!(server.text("format", json!({"file": "fmt/crlf.sv"})), "unchanged\n"); +} + +#[test] +fn fix_lint_fixes_safe_findings_and_never_inside_a_fence() { + let tree = Tree::of("edit"); + let source = "module f (\n input logic a, \n output logic b\n);\n // lucisv: off\n assign b = a; \n // lucisv: on\nendmodule\n"; + fs::write(tree.path("fmt/fix.sv"), source).unwrap(); + let mut server = Session::over(&tree); + server.initialize(); + let preview = server.text("fix_lint", json!({"file": "fmt/fix.sv", "dry_run": true})); + assert!(preview.contains("fixed: no-trailing-whitespace ×1;"), "{preview}"); + assert_eq!(fs::read_to_string(tree.path("fmt/fix.sv")).unwrap(), source); + server.text("fix_lint", json!({"file": "fmt/fix.sv"})); + let fixed = fs::read_to_string(tree.path("fmt/fix.sv")).unwrap(); + assert_eq!(fixed, source.replacen("logic a, \n", "logic a,\n", 1)); + assert!(fixed.contains(" assign b = a; \n"), "the fenced line is untouched: {fixed}"); + let again = server.text("fix_lint", json!({"file": "fmt/fix.sv"})); + assert!(again.starts_with("unchanged\nfixed: nothing;"), "{again}"); + // `rules` narrows the run like --select. + fs::write(tree.path("fmt/fix.sv"), source).unwrap(); + let other = json!({"file": "fmt/fix.sv", "rules": "no-tabs", "dry_run": true}); + assert!(server.text("fix_lint", other).starts_with("unchanged\nfixed: nothing; 0 findings")); +} + +#[test] +fn instantiate_writes_text_and_no_file() { + let tree = Tree::of("edit"); + let mut server = Session::over(&tree); + server.initialize(); + let before = snapshot(&tree); + let named = server.text("instantiate", json!({"name": "leaf"})); + assert_eq!(named, "leaf u_leaf (\n .clk(clk),\n .d(d),\n .q(q)\n);\n"); + let wild = + server.text("instantiate", json!({"name": "cell", "style": "wildcard", "instance": "u_x"})); + assert_eq!(wild, "cell u_x (.*);\n"); + let missing = refusal(&mut server, "instantiate", json!({"name": "nothing_here"})); + assert!(missing.contains("nothing_here"), "{missing}"); + assert_eq!(before, snapshot(&tree)); +} + +#[test] +fn a_file_the_index_skipped_is_never_edited_around() { + let tree = Tree::of("edit"); + let filler = + "// filler .......................................................\n".repeat(17_000); + let big = format!("module big;\n{filler} leaf u_l (.clk(c), .d(x), .q(y));\nendmodule\n"); + fs::write(tree.path("rtl/big.sv"), big).unwrap(); + fs::write(tree.path("rtl/latin1.sv"), b"// \xa9 vendor\nmodule other; endmodule\n").unwrap(); + let mut server = Session::over(&tree); + server.initialize(); + let before = snapshot(&tree); + // `d` is spelled in the skipped big.sv: the rename could not reach it. + let rename = json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"}); + let refused = refusal(&mut server, "rename", rename); + assert_eq!( + refused, + "`rtl/big.sv` (skipped: over 1 MiB) may reference `d`; lucisv-mcp will not edit around a file it cannot index; nothing written." + ); + let port = json!({"module": "leaf", "declaration": "input logic en"}); + assert!(refusal(&mut server, "add_port", port).contains("`leaf`")); + assert_eq!(before, snapshot(&tree)); + // A name no skipped file spells: written, and the skipped files named. + let text = server.text("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6})); + assert!( + text.contains(" not indexed, so not searched or edited: rtl/big.sv (over 1 MiB), rtl/latin1.sv (not UTF-8 text)\n"), + "{text}" + ); + let found = server.text("references", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22})); + assert!(found.ends_with("warning: not indexed, so not searched or edited: rtl/big.sv (over 1 MiB), rtl/latin1.sv (not UTF-8 text)\n"), "{found}"); +} + +#[test] +fn instantiate_takes_only_an_identifier_for_the_instance() { + let tree = Tree::of("edit"); + let mut server = Session::over(&tree); + server.initialize(); + let escaped = server + .text("instantiate", json!({"name": "cell", "style": "wildcard", "instance": "\\u-x "})); + assert_eq!(escaped, "cell \\u-x (.*);\n"); + for bad in ["", "1u", "a b", "module", "\\u-x", "u_x); evil ("] { + let said = refusal(&mut server, "instantiate", json!({"name": "cell", "instance": bad})); + assert!(said.starts_with("`instance` must be one identifier"), "{bad}: {said}"); + } +} diff --git a/docs/features/mcp-edit-tools/README.md b/docs/features/mcp-edit-tools/README.md new file mode 100644 index 0000000..8596759 --- /dev/null +++ b/docs/features/mcp-edit-tools/README.md @@ -0,0 +1,703 @@ +# mcp-edit-tools + +Lane **M3** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §4.3). + +## Goal + +Give an agent lucisv's verified edits as single MCP calls: `format`, +`fix_lint`, `rename`, the six cursor refactorings (`expand_wildcard`, +`convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`, +`remove_port`), `add_port`, `extract_module`, and the text-only +`instantiate`. An agent that renames a port across a design today reads and +edits every file that mentions it; here it makes one call, sees the diff +first if it wants (`dry_run`), and gets either the whole verified edit on +disk or a sentence saying why nothing was written. Every tool is a wrapper +over an engine that already verifies its own output (`vlog_refactor`, +`vlog_formatter`, `vlog_linter`); the one new piece is the write path, +`src/apply.rs`, which every tool shares. + +## Assumptions + +- **All-or-nothing, as far as a filesystem allows.** An engine's + `RefactorEdit` is all-or-nothing by construction; `apply.rs` keeps it so + on disk: every file's new text is computed (edits applied last-first, + refusing on overlap, a range past the end, or a split UTF-8 character) + before anything is written; every target is checked to lie inside a root + (an existing file by its canonical path; a created file by its parent's + canonical path, and nothing — not even a dangling symlink — at its own + path); then the write-freshness check (next point); then `write_atomic` + per file in path order. A write that fails after others landed is an + `isError` result: "written N of M: a.sv, b.sv; failed on `c.sv`: " + — the CLI's posture: said, never hidden, never rolled back. +- **The write-freshness rule** (the lead's ruling for QA's first attack): + immediately before the first write, every file the edit rewrites is + re-read and compared **byte for byte** with the text the plan was + computed against (the ruling says "content hash"; comparing the bytes + themselves costs the same read and cannot collide); a created file must + still not exist; a read-only file is refused here, where `write_atomic` + would only refuse it later, after other files landed. One mismatch + refuses the whole edit: "`f` changed on disk since it was read; nothing + written." **The window** that remains is between that check and each + file's `rename(2)`: the time to write the files already checked, a few + milliseconds for a rename across three files. A writer that lands inside + it is overwritten, which is the same exposure `lucisv format` has between + its read and its write. There is no lock, for the reason + `lucisv_core::atomic` gives: a lock would buy nothing between processes + that do not take it. +- **Where the texts come from.** A refactoring is handed the whole indexed + set plus the selected file, read from disk at call time + (`tools/source.rs::WholeSet::read`, the one whole-set read `references` + shares) — M2's ruling for `references`, for the same + reason: a use can resolve through a file that never spells its name, so no + narrowing by name is sound, and a narrowed set turns an unresolvable use + into a false refusal. Those same texts are what the freshness rule + compares against, so the index is never trusted for bytes. **Cost**: one + read and one parse of every indexed file per call — see the timings in the + work log (a copy of opentitan's `hw/ip/aes`: 124 files) and, for all of + opentitan, M2's `references` numbers (1.6–2.6 s release, 3 944 files). + M6 measures `rename` on the whole checkout; Handshake MCP-7's + `KnownFacts` variant is the way down, as it is for `references`. +- **Files the index skipped are never edited around** (QA finding 2, lead's + ruling). The index leaves out files over 1 MiB and files that are not + UTF-8 (M1's rules); `project/files.rs` now keeps the large ones' paths + (`FileSet::skipped`) and `Project::skipped()` returns both kinds with the + reason. `WholeSet::read` carries that list beside the texts, plus any + indexed file that no longer reads. Before an engine runs, each edit tool + names what it changes — `rename`: the old name; `remove_port`: the port + and its module; `propagate_ports`, `expand_wildcard`, `inline_module`: + the instantiated module; `convert_ports`, `extract_module`, `add_port` by + position: the enclosing module; `add_port` by `module`: that name; + `organize_imports`: nothing (it edits only its own file's `import`s) — + and when a skipped file's bytes spell one of those names as a **whole + word** the edit is refused: "`rtl/big.sv` (skipped: over 1 MiB) may + reference `d`; lucisv-mcp will not edit around a file it cannot index; + nothing written." Whole-word rather than any substring (a refinement of + the ruling's "bytes contain"): an identifier, escaped or not, is always + written with a non-identifier byte on each side, so no reference is + missed, while a one-letter port such as `d` would otherwise refuse every + edit on any tree holding one skipped file. Otherwise the skipped files are + named once under `warnings:` ("not indexed, so not searched or edited: …", + ten at most, then "and N more"); `references` ends its answer with the + same line as `warning:` (and `structuredContent.warning`), since its + census is then partial. The search is conservative: a skipped file that + spells the name only in a comment still refuses. +- **Known limits.** `vlog_refactor::rename` does not rewrite a `.*` or + `.name` shorthand connection bound to the renamed name (QA finding 1: the + design is silently rewired; the LSP's rename has the same limit). It is + the engine's, fixed in lane M3.5; until then the `rename` description + says so and tells the agent to check `dry_run` on designs using them. + `extract_module` into a CRLF file writes its instantiation with LF + (Handshake MCP-10). +- **`dry_run: null` means absent** (lead's ruling on QA finding 4): JSON + null is "not given" for every argument of every tool (M1's validation), + so a null `dry_run` is the default, `false`, and the edit is written; + `"true"` and `1` are refused as non-booleans. +- **What `dry_run` returns**: the summary with `(dry run: nothing written)`, + the warnings, then `lucisv_core::diff::unified` per file, headed by the + root-relative path (a created file diffs from empty). `structuredContent` + carries each file's `diff` too. Nothing is written and nothing is + re-read for freshness. A real run answers the summary only: + `files: N changed, M created`, one `path +added -removed` line per file + (counted from the diff, whose resync is deliberately coarse — a count can + include an unchanged line the resync re-emitted), `unchanged:` for files + looked at and left alone (`format`), the tool's note (`fix_lint`), and + `warnings:`. Nothing to write answers `unchanged`. +- **Idempotency.** `idempotentHint: true` on `format`, `fix_lint`, + `expand_wildcard`, `convert_ports`, `organize_imports` (the lead's list). + A second identical call writes nothing: `format`, `fix_lint` and `rename` + answer `unchanged` (for `rename`, when the name at the position already + is `new_name` — checked with `vlog_refactor::rename_name_at` before the + engine runs); `expand_wildcard`, `convert_ports` and `organize_imports` + answer the engine's own "nothing to do" sentence (`writes no .* to + expand`, `already declares its ports ANSI-style`, `already sorted, and + every one of them is used`) as a tool error. Turning those sentences into + `unchanged` would mean matching engine wording, which drifts; a refusal + that writes nothing is idempotent in effect, which is what the hint + promises. The wire test asserts "`unchanged` or a refusal, and not one + byte moved". +- **The fence rule** (`fix_lint`): a fix is applied only when none of its + edits touches a region `vlog_formatter::fence::protected_regions` reports + (`// lucisv: off` / `// verilog_format: off`) — the CLI's + `fixable_outside_fences`, restated in `tools/format.rs::outside_fences` + over the same library answer (the CLI's copy is in a binary crate and + cannot be called). Only `Applicability::Safe` fixes (`apply_fixes(…, + false)`); up to the CLI's 10 fix-then-relint rounds; the run is + `diagnostics`'s (`Runs`, the per-file `lucisv.toml`, `[lint] + select/ignore`, options, external waivers, the index-backed oracle). The + result is refused when its tolerant parse has more errors than the + input's (the CLI does not check this; the brief asked for it). The note + says `fixed: rule ×n, …; N findings left`, counted as findings that + disappeared per rule. +- **`format`** takes `file` or comma-separated `files` (no `Ty::List`: + a comma string, as the brief allowed) and `lines` with one file only + (`LineRanges::parse`, then `format_range`). The config is the CLI's + `Options::config_with` with no flags: `line-length`, `indent`, + `[format] uvm-utils-indent` from `Discovery::for_file`. One file the + formatter refuses refuses the whole call ("`f` was not formatted: ; nothing written."); a formatter panic is caught and + refused the same way. A CRLF file comes back LF-normalised — the + formatter's own behaviour (`docs/features/alignment`), so `format` and + `lucisv format` write the same bytes (asserted by the CRLF wire test). +- **Selectors.** `rename` takes `definition`'s selector (`tools/select.rs`) + and, for a bare `name` (+`unit`), `nav::declaration_position` — the one + declaration `references` would pick. The six cursor tools take `file` + + `line` with `col` or `name` through the same selector; `file` + `line` + alone means the line's first non-blank byte (`organize_imports` wants a + scope, not a token). `add_port` takes `module` (`ModuleRef::Name`) or + `file` + `line` (`ModuleRef::At` at the line's start), not both. + `extract_module`'s selection is `start_line`'s first byte to `end_line`'s + last (line ending excluded); `home` is `new_file` (default, the file is + `new_name.sv` beside the source, as the engine names it) or `same_file`. +- **`instantiate`** is `instantiation_plan` + `render_with` over the file + `vlog_refactor::module_definition` names (one walk on a miss; `file` + picks among several declarations), with no site — so no auto-connect: + every port is connected to a same-named placeholder. `with_params: false` + drops the `#(…)`; `instance` replaces the instance hole and must be one + identifier — `[A-Za-z_][A-Za-z0-9_$]*` and not a keyword, or an escaped + identifier `\name ` ending in its one space — else the call is refused + naming the rule (QA finding 5); `wildcard` + renders with no ports and writes `(.*)`. The indentation step is the + first root's `indent`. Read-only annotations. +- **Engine refusals are passed through as written.** They are sentences + for a user already (`vlog_refactor`'s convention), and several speak of + the refactoring by name, which is right here (unlike `references`, which + borrows rename's resolution). + +## Handshakes + +Consumed (public APIs only; no library crate's behaviour was changed): + +| crate | items | +|---|---| +| `vlog_refactor` | `RefactorEdit`, `TextEdit`, `rename`, `rename_name_at`, `expand_wildcard`, `convert_to_ansi`, `organize_imports`, `inline_module`, `propagate_ports`, `remove_port`, `add_port`, `ModuleRef`, `extract_module`, `Home`, `instantiation_plan`, `InstantiationPlan::{render_with, instance_name}`, `Layout`, `module_definition` | +| `vlog_formatter` | `format_source`, `format_range`, `LineRanges::parse`, `Config`, `fence::{protected_regions, is_protected, Region}` | +| `vlog_linter` | `apply_fixes`, `Fix`, `Violation` (plus everything `diagnostics` already consumed) | +| `lucisv_core` | `atomic::write_atomic`, `diff::unified` (new, below), `config::{Discovery::for_file, FileConfig}` | + +**Handshake MCP-1 — delivered as a pure move (lead's ruling).** +`crates/lucisv/src/diff.rs` (the CLI's `--diff` printer, 127 production +lines and its six tests) moved unchanged to `crates/lucisv_core/src/diff.rs`, +exposed as `lucisv_core::diff::unified` (`pub mod diff;` in +`lucisv_core/src/lib.rs`, the crate doc updated). The only edit to the moved +text is its module doc comment. `crates/lucisv/src/diff.rs` is now one line, +`pub use lucisv_core::diff::unified;`, so `main.rs`'s two `diff::unified` +calls are untouched and `--diff` output is byte-identical (same function). +The six tests run in `lucisv_core` now; `lucisv_core` is still +dependency-free. `docs/topo.md` is the lead's to update (M6). + +Edits outside this lane's files, each a one-liner forced by the lane: + +- `crates/lucisv_mcp/src/tools/nav.rs`: `declaration_position` is + `pub(super)` (was private) so `rename` picks the same declaration for a + bare `name` that `references` does — a copy would drift. +- `crates/lucisv_mcp/src/tools/diagnostics.rs` (allowed by the brief): + `Runs`, `Runs::new`, `Runs::for_file`, `Run`, `Mentions`, + `Mentions::of_file` are `pub(super)`; the lint call inside + `file_findings` became `pub(super) fn violations` so `fix_lint` lints + exactly as `diagnostics` does. `diagnostics`' answers are unchanged (its + wire and QA tests are green, unedited). +- `crates/lucisv_mcp/tests/qa_m1.rs`: the tool count in + `qa_everything_but_initialize_and_ping_waits_for_the_handshake` goes from + 11 to 23 (M2 made the same one-line edit when it added five tools). +- Rework (lead's rulings on QA findings 2 and 4): `project/files.rs` + (`FileSet::skipped`), `project/mod.rs` (`unreadable` keeps paths; + `Project::skipped()`; `unreadable()` returns the same strings as before), + `tools/source.rs` (`WholeSet`), `tools/nav.rs` (`all_files` replaced by + `WholeSet::read`; `references`' `warning:` line), `tests/qa_m3.rs` + (findings 2 and 5 un-ignored, 1 and 3 re-reasoned, 4's test rewritten to + the ruling). + +Requests: + +- **MCP-8 → `vlog_refactor` (a false refusal, not a corruption):** + `remove_port` refuses a port whose only "use" is a named connection to it + from an instantiation in **another module of the same file**: + `spare` (with `input logic unused_i`) and `spare_user` (instantiating + `spare u_s (.unused_i(1'b0), …)`) in one file → "`unused_i` is still used + inside `spare` at s.sv:15; remove those uses first." — line 15 is + `spare_user`'s connection. With the two modules in two files the removal + succeeds and deletes the connection. `ports/remove.rs::body_uses_in` + seems to count the file's connection text rather than `spare`'s body + alone. The fixtures put `spare_user` in its own file. +- **MCP-9 → `vlog_refactor` (candidate):** the engines' "nothing to do" + refusals (`expand_wildcard` rule 5, `convert_to_ansi`'s "already + ANSI-style", `organize_imports`' "already sorted") are indistinguishable + from real refusals except by wording. A typed `Err` (or an + `Ok(RefactorEdit::default())`) for "already done" would let every front + end answer `unchanged` for an idempotent second call. +- **To M6 (instructions):** `rpc.rs`'s `INSTRUCTIONS` (M1's file) names + only the read tools. A sentence such as "edit tools (rename, format, + fix_lint, the port refactorings) verify before writing and take `dry_run` + to show the diff first" belongs there; M6 revises `instructions` from + the census anyway. +- **MCP-10 → `vlog_refactor` (non-blocking, QA finding 3):** + `extract_module` into a CRLF file writes the instantiation it leaves in + place with bare LF (`extract/render.rs` renders `\n` only), so the file + ends up with mixed line endings; the created file is LF. Valid Verilog, + nothing lost. The engine should render the source file's line ending. + QA's `qa_extract_module_keeps_a_crlf_file_crlf` stays ignored for it. +- **QA finding 1 → lane M3.5 (lead's ruling):** `rename` and `.*`/`.name` + shorthand connections — see Known limits. QA's + `qa_rename_never_breaks_an_implicit_port_connection` stays ignored ("engine + limit, fixed in M3.5"). +- Done in the rework: `nav.rs::all_files` and `edit.rs::sources` merged into + `source::WholeSet::read` (one function; `nav.rs` calls it). + +## Status / TODO + +- [x] MCP-1: `unified` moved to `lucisv_core::diff`, CLI re-exports it, + tests moved, CLI `--diff` byte-identical +- [x] `apply.rs`: plan from a `RefactorEdit` (reverse-order application, + overlap/bounds/char-boundary refusals); containment (existing and + created targets); the write-freshness check before the first write; + `write_atomic` in path order; "written N of M" on a late failure; + dry-run diffs; the summary text and JSON +- [x] registry: `tools::Effect` (read / edit, idempotent) drives the + annotations; twelve tools registered +- [x] `format` (`file`/`files`, `lines`, config ladder, whole-call refusal, + panic contained), `fix_lint` (safe, fenced, rounds, parse check, + per-rule note) +- [x] `rename` (definition's selector, whole set, `unchanged` repeat) +- [x] `expand_wildcard`, `convert_ports`, `organize_imports`, + `inline_module`, `propagate_ports`, `remove_port` +- [x] `add_port` (`module` or `file`+`line`), `extract_module` (new file / + same file), `instantiate` (named/wildcard, params, instance) +- [x] tests: every tool dry-run / real / repeat; three-file rename; refusals + leave the tree byte-identical; extract into a new file and over an + existing one; `fix_lint` beside a fence; CRLF `format`; stale-file, + created-file-appeared, read-only, late-failure and outside-root unit + tests on `apply` +- [x] timings on a copy of `hw/ip/aes` +- [x] gates through `tools/guard.sh`; sizes + +## Work log + +**2026-09-23 (dev, M3).** + +Built: `src/apply.rs` (the write path), `src/tools/edit.rs` (`dry_run`, the +whole-set read, `rename` and the six cursor refactorings), +`src/tools/format.rs` (`format`, `fix_lint`), `src/tools/refactor.rs` +(`add_port`, `extract_module`, `instantiate`); `tools/mod.rs` gains +`Effect` and the twelve entries; `main.rs` gains `mod apply;`. Fixtures: a +new tree `tests/fixtures/edit` (14 files: a package, `leaf` instantiated +from `mid.sv` and `top.sv` for the three-file rename, a `.*` instance, a +partial instance, a non-ANSI module, a module in its own file to inline, a +port only another file connects, an extract target, a badly formatted +file); M1's `design` and M2's `nav` trees are untouched. + +Decisions and deviations: + +1. **Byte comparison instead of a content hash** for the freshness rule — + same read, no collision (Assumptions). +2. **A read-only target is refused in the pre-write pass**, before any + file is written; `write_atomic` would refuse it too, but only after the + files before it in path order had landed. +3. **The "nothing to do" repeat of three engines is a refusal, not + `unchanged`** (Assumptions, MCP-9). +4. **`fix_lint` takes `rules`** (like `diagnostics`), so an agent can fix + one rule's findings; not in the brief, one parameter on the same + `Runs`. +5. **`instantiate` takes `file`** to pick among several declarations, the + way `unit_interface` does. +6. **CRLF**: `format` normalises to LF because the formatter does; the + test pins "the same bytes as `format_source`", not "CRLF kept". +7. **The one-line edits outside the lane** listed under Handshakes + (`nav.rs` visibility, `qa_m1.rs` count). + +Timings (release build, macOS arm64, a `cp -R` of opentitan `hw/ip/aes` — +124 indexed files, 29 046 lines — into the session scratch directory; the +checkout was only read, and its `git status` is the same before and after — +three files modified before this lane started, none by it): + +| call | wall (ms) | +|---|---| +| index build at the first call | 49–57 | +| `rename` `op_i` → `cipher_op_i` at `rtl/aes_cipher_core.sv:123`, `dry_run` (3 files, 4 macro-argument warnings) | 136 first call, 76 warm | +| the same `rename`, written | 75–79 | +| the same position again (`cipher_op_i` → `cipher_op_i`) | 10 (`unchanged`, no engine run) | +| `expand_wildcard` at `dv/err_injection_if/fi_core_wrapper.sv:21` (`fi_core_if fi_if (.*)`), `dry_run` | 54–59 | +| the same, written | 54–67 | +| the same again | 51 (the engine's "`fi_if` writes no `.*` to expand") | + +Each call re-reads and re-parses the 124 files (the whole-set rule); on the +whole opentitan checkout that is M2's 1.6–2.6 s per call, which M6 measures +for `rename`. + +Tests: `lucisv_mcp` 151 → 166 (+1 ignored, the opentitan census) — 5 +`apply` unit tests, 10 new wire tests, the `tools/list` wire test rewritten +for the edit annotations; `lucisv_core` gains the six +diff tests the CLI loses (count unchanged across the two crates). + +Gates (each through `tools/guard.sh`, one cargo invocation at a time): +`cargo fmt -p lucisv_mcp -p lucisv_core -p lucisv -- --check` clean; +`cargo clippy -p lucisv_mcp -p lucisv_core -p lucisv --all-targets` clean; +`cargo test -p lucisv_mcp` 43 + 51 + 43 + 29 passed, 1 ignored; +`cargo test -p lucisv -p lucisv_core` 30 + 113 + 117 passed; +`cargo test --workspace` 4 625 passed, 0 failed, 47 ignored (4 610 before). + +Sizes (production lines: non-blank, non-comment, before `mod tests`): +`apply.rs` 216, `tools/edit.rs` 194, `tools/format.rs` 220, +`tools/refactor.rs` 241, `tools/mod.rs` 176, `tools/diagnostics.rs` 330, +`lucisv_core/src/diff.rs` 127, `lucisv/src/diff.rs` 1. No function over 40 +lines. + +**2026-09-23 (dev, M3 rework after QA's FAIL; lead's rulings).** + +- Finding 1 (blocking, engine; ruled out of lane → M3.5): `vlog_refactor` + untouched. The `rename` description (`tools/edit.rs:126`) gains "A `.*` + or `.name` shorthand connection bound to the renamed name is not + rewritten yet (known engine limit, M3.5); check `dry_run` on designs + using them."; Assumptions gains *Known limits*. QA's test stays ignored, + reason "QA finding 1: engine limit, fixed in M3.5". +- Finding 2 (blocking, fixed): `project/files.rs:38` `FileSet::skipped` + keeps the paths the size cap drops; `project/mod.rs:256` + `Project::skipped()` returns them and the non-UTF-8 files with why + (`unreadable` now keeps paths; `unreadable()` answers the same strings). + `tools/source.rs:155` `WholeSet` is the one whole-set read (`read`, + `mentioning`, `warning`, `word_in_bytes`), replacing both + `edit.rs::sources` and `nav.rs::all_files`. `tools/edit.rs:241` + `whole_set` refuses when a skipped file spells a name the edit changes, + and `finish` (`edit.rs:258`) lists the skipped files under `warnings:`; + every edit tool names its stake (`edit.rs:149–210`, `refactor.rs:134, + 142, 183`). `references` ends with the same line as `warning:` + (`nav.rs:311`). Deviation: the byte search is whole-word (Assumptions). + QA's test un-ignored; two new wire tests + (`a_file_the_index_skipped_is_never_edited_around`: refusal wording, + `add_port` by module, the warning line on a name no skipped file spells, + `references`' warning) and one unit test (`word_in_bytes`). +- Finding 3 (non-blocking, engine): Handshake MCP-10 filed; QA's test stays + ignored with that reason. +- Finding 4 (ruled no change): `dry_run: null` is absent — Assumptions says + so; QA's test renamed `qa_a_null_dry_run_is_absent_and_a_non_boolean_is_refused` + and asserts exactly that. +- Finding 5 (fixed): `tools/refactor.rs:270` `identifier` — a simple + identifier that is not a keyword (`vlog_parser::token::is_keyword`), or an + escaped one ending in its space; anything else is refused naming the rule. + QA's test un-ignored; a wire test adds `\u-x ` accepted and `1u`, `\u-x` + (no space) refused. + +Gates (through `tools/guard.sh`, one at a time): fmt `--check` rc 0; +clippy over `lucisv_mcp`/`lucisv_core`/`lucisv` `--all-targets` clean; +`cargo test -p lucisv_mcp` 44 + 0 (1 ignored) + 51 + 43 + 27 (2 ignored) + +31 passed; `cargo test --workspace` **4 655 passed, 0 failed, 49 ignored** +(QA's 4 649 + 3 un-ignored + 3 new; 52 − 3 ignored). Sizes (production +lines): `apply.rs` 216 (unchanged — QA's `#[path]` include still builds), +`tools/edit.rs` 222, `tools/format.rs` 220, `tools/refactor.rs` 261, +`tools/mod.rs` 176, `tools/diagnostics.rs` 330, `tools/nav.rs` 340, +`tools/source.rs` 185, `project/mod.rs` 242, `project/files.rs` 153. + +**2026-09-23 (lead, after the QA re-check).** Two fixes applied by the lead +rather than a third dev round, both a few lines: every whole-set tool (the +nine edits over the indexed set and `references`) now walks the roots +before it answers (`rewalk: true`), so a file written in the last 5 s is in +the set — QA finding 6, its test un-ignored; and the size-cap branch of the +walk makes the same root check the indexed branch makes, so a large file +reached through a symlink out of the root is neither indexed nor recorded +as skipped (finding 7, un-ignored). Cost of the walk on opentitan `hw/`: +≈140 ms per edit call, against the 1.6–2.6 s the whole-set read already +costs. Gates re-run by the lead through `tools/guard.sh`. + +## QA log + +**2026-09-23 (QA, M3). Verdict: FAIL — two blocking findings (1 in +`vlog_refactor::rename`, inherited; 2 in this lane's whole-set read), three +non-blocking.** Everything the lane itself promises about the write path +held under attack: no refusal moved a byte, no write left a root, no file +was ever torn, `format`/`fix_lint` are byte-identical to the CLI. The two +blockers are wrong answers — a "verified" rename that reports success and +leaves the design broken — which the brief ranks blocking wherever they come +from. + +Tests: `crates/lucisv_mcp/tests/qa_m3.rs` — 19 `qa_*` tests green + 5 +`#[ignore = "QA finding N"]` (each confirmed failing under `--ignored`). The +file includes the production `src/apply.rs` verbatim through `#[path]` over +two stand-ins (`project::Project` with `roots`/`relative`/`open`, +`tools::Answer`), so `apply::commit` is attacked directly with stale texts — +no black box can hook the gap between a tool's read and its write; the +dev's five `apply` unit tests therefore also run a second time in that +binary (counted in the 24 it reports). + +What was attacked, and how (all green unless a finding says otherwise): + +1. **Corruption hunt.** Every tool (14 real calls: rename by position and by + `name`+`unit`, the six cursor tools, `add_port` both ways, extract new-file + and same-file, `format`, `fix_lint`): the files that move are exactly the + reported ones; each reported `+a -r` equals the signed lines of the + dry-run diff; the dry-run diff equals `lucisv_core::diff::unified` of + (before, what the real call wrote); the same call again answers + `unchanged` or a refusal and moves nothing. 25 refusals across all twelve + edit tools (engine, argument and path refusals) leave every byte **and + mode bit** of the tree, and of an outside directory reachable by a + symlink, identical. Comments beside every edited span survive (a port + with a trailing comment renamed, a `.*` with leading/trailing/block + comments expanded, a block with a leading comment and a trailing one + extracted; each comment's count over the tree is unchanged). `format` of a + file the safety net refuses leaves the tree identical; `fix_lint` leaves + `// lucisv: off` and `// verilog_format: off` regions byte-identical and + never applies `always-comb`'s unsafe fix, even with `rules: + "always-comb"` (answers `unchanged`). +2. **Write freshness.** Directly: a stale first, middle and last file (same + length, one byte changed — no size or mtime shortcut could catch it), a + file deleted, a file replaced by a directory, a created path taken by a + dangling symlink or a directory, a read-only last file — each refused + naming the file, nothing written; a file rewritten with the same bytes + (new inode and mtime) is fresh by the byte rule and lands. Black box: a + `rename` back and forth for 80 rounds while a thread rewrites `mid.sv` + atomically every 50 ms (unrenamed/renamed text + a marker) — after every + call each file is wholly one form or the other, every "changed on disk" + refusal names `rtl/mid.sv`, and real writes happen (asserted). The same + race on a `cp -R` of opentitan `hw/ip/aes` (`op_i` ↔ `cipher_op_i`, + 3 files, scratch script): writer at 50 ms — 300 calls, 178 freshness + refusals naming `rtl/aes_core.sv`, 122 engine refusals (mixed tree), no + torn file; writer at 400 ms — 200 calls, 77 written, 18 freshness + refusals, no torn file. +3. **Paths.** `extract_module` new names `../evil`, `/tmp/evil`, + `\../../evil `, `a/b`, empty — refused by the engine's plain-identifier + rule; a source reached through a symlinked directory inside the root, and + an absolute path outside — "outside every root"; a dangling symlink (to + outside) or a directory at the created path — "already exists"; a + read-only `rtl/top.sv` (last of the rename's three) — "is read-only; + nothing written." with `leaf.sv`/`mid.sv` untouched; the same for + `format` and `fix_lint`. A symlinked file alias: `files: "alias.sv, + real.sv"` is one file, the real file is written and the link kept. + Symlinked files/dirs pointing outside are not indexed (M1's rule), so a + rename never reaches them. +4. **Concurrency.** `lucisv --check` in a loop over a 60-file tree while + the server formats it five times (tree re-dirtied each round): every + check exits 0/1, the final files equal the CLI's in-place output. On the + aes copy (124 files, scratch script): 8 rounds of three `lucisv --check` + runs plus, every other round, an in-place `lucisv` racing the server's + 124-file `format` — no crash, every round's final tree byte-identical to + the CLI's output. +5. **`format` = the CLI's bytes.** CRLF file (CRLF → LF, byte-identical to + `lucisv` in place and `--stdout`); a nested `lucisv.toml` (`line-length = + 40`, `indent = 4`) — its config is used, as the CLI does; a fenced region; + `lines` `2,1-2,99`, `4,2`, `4-4,2-2`, `50-60` (past EOF: `unchanged`), + `1-999` — each equal to `lucisv --lines`; `3-1` refused; a duplicate in + `files` (`w.sv, w.sv,./w.sv`) diffs once. On the aes copy: the server's + `format` of all 124 files (242 ms release) is byte-identical to `lucisv` + on every file. +6. **`rename`.** The fixture rename equals `vlog_refactor::rename` over all + files, file for file (in-test oracle); on aes the `op_i` rename equals a + throwaway oracle binary (scratch crate) on all three files. A bare `name` + picks the declaration `references` picks (same file set); an ambiguous + `q` is refused listing `rtl/ext.sv:4` and `rtl/leaf.sv:4`; a keyword, a + name already declared, an escaped name (`\a+b `, the engine refuses + escaped new names by policy) and an empty name are refused; a hit inside a + macro's arguments surfaces the engine's warning in `warnings:`. **See + findings 1 and 2.** +7. **Engine refusals are refusals.** Two or more per tool, tree unchanged: + `expand_wildcard` (positional list; a `bind` instance), `convert_ports` + (already ANSI ×2), `organize_imports` (a `` `define`` in scope; a line + past the end), `inline_module` (positional; `.*`; no instance), + `propagate_ports` (all connected; `.*`; positional), `remove_port` (port + still used ×2), `add_port` (existing port; an ordered instantiation of + the wrong length), `extract_module` (no item selected; a name already on + disk). MCP-8 reproduced as filed (`s.sv:9` is `spare_user`'s connection). +8. **`dry_run` diffs.** Dry-run diff = the diff of the real run (test 1). + On aes, the three-file rename's dry-run diff applies with `patch -p0` + onto a fresh copy and reproduces the real run byte for byte; it lists all + three files. Its hunks are coarser than GNU `diff -u` (16 signed lines + vs 12 for the same change; a two-line rename in `leaf.sv` reports `+4 + -4`) — the CLI's resync, documented in Assumptions; noted, not a finding. +9. **MCP-1.** `git worktree` of 82bbba0 in the scratch dir (removed + afterwards), its release `lucisv` built there: `--diff` over the whole aes + copy (36 498 lines) and over `corpus/picorv32/picorv32.v` (6 226), + `corpus/common_cells/src/fifo_v3.sv` (277), `.../addr_decode.sv` (96) + is byte-identical old vs new, exit codes equal. The moved file differs + from 82bbba0's `crates/lucisv/src/diff.rs` only in its module doc comment. +10. **Sizes/style** (production lines = non-blank, non-`//` lines before + `#[cfg(test)]`): `apply.rs` 216, `tools/edit.rs` 194, `tools/format.rs` + 220, `tools/refactor.rs` 241, `tools/mod.rs` 176, `tools/diagnostics.rs` + 330, `tools/nav.rs` 343, `lucisv_core/src/diff.rs` 127, + `lucisv/src/diff.rs` 1 — the dev's numbers. No function over 50 lines. + No `unwrap`/`expect`/`panic!`/`#[allow]`/`unsafe` in the lane's + production code (`format.rs:66` is the word "unsafe" in a description). + `cargo tree -p lucisv_core -e normal`: `lucisv_core` alone. +11. **Gates** (each through `tools/guard.sh`, one cargo invocation at a + time): `cargo fmt -p lucisv_mcp -p lucisv_core -p lucisv -- --check` + rc 0; `cargo clippy -p lucisv_mcp -p lucisv_core -p lucisv --all-targets` + clean, rc 0; `cargo test -p lucisv_mcp` 43 + 0 (1 ignored) + 51 + 43 + + 24 (5 ignored) + 29 passed; `cargo test -p lucisv -p lucisv_core` 30 + + 113 + 117 passed; `cargo test --workspace` **4 649 passed, 0 failed, + 52 ignored** (4 625 + 24; 47 + 5). + +Findings: + +- **1 — BLOCKING (engine, pre-existing; `vlog_refactor::rename`, reached + here and from `lucisv-server`).** Renaming a port bound by an implicit + connection, or a net such a connection binds, writes a "verified" edit + that silently rewires the design. `leaf (input d)`, `top` instantiating + `leaf u_leaf (.*)` with its own `d`, `top2` with `leaf u_leaf (.clk, .d, + .q)`: + (a) rename `leaf.d` → `din`: `leaf.sv` renamed, `top.sv` untouched — `.*` + no longer binds the port (the engine's own `expand_wildcard` then says + "no net … named `din` … lucisv wrote it unconnected"); `top2.sv`'s `.d` + becomes `.din`, which now names a net `top2` does not have; + (b) rename `top.d` → `x`: only the declaration moves; `.*` stops binding + `leaf.d`; (c) rename `top2.d` → `x`: `.d` is left naming nothing. All + answer success with no warning. Reproduced with a direct + `vlog_refactor::rename` call (scratch oracle), so it is the engine's. + `check::verify`'s resolution identity (`crates/vlog_refactor/src/check/ + mod.rs:41`) cannot see it: neither `.*` nor `.name` spells a reference the + resolver records. Fix (vlog_refactor, outside this lane — a Handshake + request): rewrite `.name` as `.new(old)` / `.old(new)`, and refuse (or + expand first) a rename that changes a name a `.*` binds, the way + `inline_module` refuses `.*` and `remove_port` warns about it. Test: + `qa_rename_never_breaks_an_implicit_port_connection`. +- **2 — BLOCKING (this lane; `tools/edit.rs:209` `sources`).** The whole-set + read is "every indexed file", and the index skips files over 1 MiB + (`project/files.rs:100`) and files that are not UTF-8 (M1's rule, named + only in `project_overview`). A rename whose uses sit in such a file writes + the others and answers success without a word: a 1.08 MB `big.sv` with + `leaf u_l (.clk(clk), .d(x), .q(y))` keeps `.d(x)` after `leaf.d` → + `din_i` ("files: 1 changed"); the same for a copy of `mid.sv` with a + Latin-1 `©` in its header comment — common in vendor RTL. Every engine + that edits instantiations (`rename`, `remove_port`, `add_port`, + `propagate_ports`) is exposed the same way. Suggested fix: keep the + skipped paths (`FileSet::skipped_large` is a count today) and, before + writing, refuse when a skipped file's bytes contain the name being + changed (the old name for `rename`, the module name for the port tools): + "`rtl/big.sv` is not indexed (over 1 MiB) and spells `d`; nothing + written." — or at minimum list the skipped files under `warnings:`. Test: + `qa_rename_says_so_when_a_skipped_file_mentions_the_name`. +- **3 — non-blocking (engine, pre-existing).** `extract_module` into a CRLF + file writes the instantiation with bare LF (`adder u_adder (\n .a(a),\n + …`), leaving `ext.sv` mixed; the created file is LF. Valid Verilog, + nothing lost; `vlog_refactor/src/extract/render.rs` renders `\n` only. + Test: `qa_extract_module_keeps_a_crlf_file_crlf`. +- **4 — non-blocking.** `"dry_run": null` is read as absent and the edit is + **written**, while `"true"` and `1` are refused as non-booleans. For a + flag whose default is "write", an explicit null should be refused like any + other non-boolean (`Args` validation of `Ty::Bool`, M1's file). Test: + `qa_a_null_dry_run_writes_nothing`. +- **5 — non-blocking.** `instantiate` takes any `instance` string: `""` + renders `pm #(…) (.*);`, `é`, `a b`, `u_x); evil (` and `module` render + text that does not parse (`tools/refactor.rs`, `instantiate`). It writes + nothing, so nothing is corrupted, but the text is handed to an agent to + paste; the engine's plain-identifier check would refuse these. Test: + `qa_instantiate_refuses_an_instance_name_that_is_not_an_identifier`. + +Observations (not findings): the formatter on a CRLF file with a fence (or +`lines`) keeps CRLF inside the fence and writes LF elsewhere — CLI +identical, the formatter's own behaviour; `fix_lint`'s `posix-eof` fix adds +the final newline at the end of an unterminated `// lucisv: off` region — +CLI identical (`fence::is_protected` treats EOF as outside); `lucisv check +--help` still says `--unsafe-fixes` "changes nothing" though `always-comb` +ships an unsafe fix — stale CLI help, out of lane. The opentitan checkout +was only copied from (its `git status` shows the same three pre-existing +modifications before and after). + +**2026-09-23 (QA, M3 re-check after the rework). Verdict: FAIL — one new +blocking finding (6), a one-line-per-tool fix; everything the rulings asked +for is verified.** Finding 1 is not counted (lead's ruling: engine, lane +M3.5; its test stays ignored with that reason). If the lead rules finding 6 +a known limit instead, the rest of M3 passes. + +Re-derived by hand (release build, scratch copies of `tests/fixtures/edit`): + +- **Finding 2 — fixed as ruled.** A 1.08 MB `rtl/big.sv` and a Latin-1 + `rtl/lat.sv`, each with `leaf u_l (.clk(clk), .d(x), .q(y))`: `rename` + `d` → `din_i` (dry run and real) is refused, `` `rtl/big.sv` (skipped: + over 1 MiB) may reference `d`; … nothing written.`` (resp. `not UTF-8 + text`), tree unchanged. The name only inside other words (`data`, `d_q`, + `dd`, `d$x`, `x$d`, `\dx `, `odd` in a comment): written, three files, + the skipped file named once under `warnings:`, its bytes untouched. +- **The whole-word rule attacked.** `d` as the file's first byte, as its + last byte (no newline), in `.d(1)`, in `f(d)`, as the escaped `\d ` (the + same identifier), and between two `\xa9` bytes — all refused. An escaped + declaration `\a+b ` (the stake is spelled `\a+b`): the skipped file's + `\a+b` ended by a tab, a newline or EOF refuses; `a+b` as an expression + and the longer `\a+bc ` do not. An escaped declaration `\dd ` stakes `dd`, + so a skipped `.dd(1)` refuses too. The per-tool stakes of the README's + table: with a skipped file spelling only `cell old inv ext spare`, + `expand_wildcard`, `propagate_ports`, `inline_module`, `convert_ports`, + `remove_port` (module `spare`), `add_port` (by module and by position) + and `extract_module` are each refused naming their stake; + `organize_imports` writes and names the skipped file. +- **Leaving and entering the skipped set.** `big.sv` rewritten small and + UTF-8: the next call is still refused with the stale reason "(skipped: + over 1 MiB)" — the skipped list is the last walk's, so it lags up to + `REWALK_AFTER` (5 s), on the safe side; after 5.5 s the rename edits all + four files and the warning is gone. The other way, an indexed `mid.sv` + gaining a Latin-1 byte is refused on the very next call (the stamp sweep + loses it and walks). +- **The merge did not change `references`.** The pre-rework binary (82bbba0, + built in a scratch worktree, removed after) and the reworked one answer + `references` identically — text and `structuredContent` — at all 165 + identifier positions of `tests/fixtures/nav` and at 600 random positions of + the aes copy (158 answered, the rest the same refusals). In-suite: on the + nav fixture with one skipped file added, every answer is the plain one plus + exactly the trailing `warning:` line and `structuredContent.warning`. +- **Finding 5 — fixed.** `""`, `a b`, `u_x); evil (`, `module` refused + (the un-ignored test); the dev's wire test covers `\u-x ` accepted. +- **Finding 4 test edit.** Renamed to + `qa_a_null_dry_run_is_absent_and_a_non_boolean_is_refused`, `#[ignore]` + removed, doc comment rewritten for the ruling, and the assertion swapped + (null now asserts `fmt/messy.sv` written). It is *not only* a swap: a + loop was added asserting `"true"` and `1` are refused with nothing written + — extra assertions matching the new name, nothing of mine weakened. The + other un-ignored tests (2, 5) are byte-for-byte mine apart from rustfmt; + finding 1 and 3's `#[ignore]` reasons were reworded as ruled. +- **Race.** `qa_a_rename_racing_a_writer_never_tears_a_file` green; the + aes script once more at 50 ms: 150 calls, 82 freshness refusals all naming + `rtl/aes_core.sv`, 68 engine refusals, no torn file. + +New findings: + +- **6 — BLOCKING (this lane; every whole-set edit tool's `rewalk: false`, + `tools/edit.rs`, `tools/refactor.rs`).** The whole set is "every indexed + file", and a file created since the last walk enters the index only after + `REWALK_AFTER` (5 s, `project/mod.rs:23`); the edit tools do not walk. A + `rename` right after an agent writes `rtl/newer.sv` with `leaf u_l (.d(x))` + answers "files: 3 changed" and leaves `.d(x)` behind — the wrong answer of + finding 2, reached through time instead of size; a brand-new over-1 MiB + file escapes the skipped-file guard the same way (a dry run answered it + at once with no refusal; the same call 5.5 s later was refused). Suggested fix: `rewalk: true` on the whole-set edit + tools (the flag and `refresh(force_walk)` exist; `project_overview` uses + it). Cost measured on the opentitan `hw/` checkout (3 944 files, read + only): a forced-walk call 139–146 ms against 9–11 ms without, next to the + 1.6–2.6 s whole-set read each edit already pays. Test: + `qa_an_edit_sees_a_file_created_just_before_it`. +- **7 — non-blocking (`project/files.rs:103–105`).** The size-cap branch + records a file's canonical path as skipped without the root-containment + check the indexed branch makes, so an over-1 MiB file behind a symlink + leading out of the root refuses edits inside it, and the refusal prints + the file's absolute path outside the root. A small file behind the same + link is dropped (M1). Safe side (a false refusal, nothing written). Test: + `qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set`. + +Tests: `qa_m3.rs` +8 — seven `qa_recheck_*` green (refusal naming file and +reason; substring-only written with the warning; whole-word edges; escaped +names; every tool's stake; leaving/entering the skipped set; `references` +gains only the warning line) and finding 6's; plus finding 7's ignored. Now +34 passed, 4 ignored (1, 3, 6, 7). Sizes (same method): `apply.rs` 216, +`tools/edit.rs` 222, `tools/format.rs` 220, `tools/refactor.rs` 261, +`tools/source.rs` 185, `tools/nav.rs` 340, `project/mod.rs` 242, +`project/files.rs` 153; no `unwrap`/`expect`/`panic!`/`#[allow]` in their +production code. + +Gates (through `tools/guard.sh`, one at a time): `cargo fmt -p lucisv_mcp +-p lucisv_core -p lucisv -- --check` rc 0; `cargo clippy -p lucisv_mcp -p +lucisv_core -p lucisv --all-targets` 0 warnings, rc 0; `cargo test -p +lucisv_mcp` 44 + 0 (1 ignored) + 51 + 43 + 34 (4 ignored) + 31 passed; +`cargo test --workspace` **4 662 passed, 0 failed, 51 ignored** (4 655 + 7; +49 + 2). The M3 QA box in `TODO-MCP.md` stays open on finding 6. + +## Review + +**Lead, 2026-09-23.** Read `apply.rs` and the three tool files. The write +path is the block's safety story and it held under QA's race, permission and +symlink attacks: all-or-nothing, re-read before the first write, `write_atomic` +inside the roots only. Rulings: a skipped file (over 1 MiB, non-UTF-8) that +spells a changed name as a whole word refuses the edit — lucisv-mcp will not +edit around a file it cannot see; `dry_run: null` is absent; every whole-set +tool re-walks first. MCP-1 delivered as a pure move (`lucisv_core::diff`; +CLI `--diff` byte-identical). **The one blocking finding that stays open is +not this lane's:** `vlog_refactor::rename` leaves `.*` and `.name` shorthand +connections broken when a port or its bound net is renamed — a real +corruption the LSP has had all along, now exposed to agents. It is fixed in +its own engine lane, M3.5, before M4; until it lands the `rename` tool says +so in its description. MCP-8 (a false `remove_port` refusal on same-file +instantiations) and MCP-10 (CRLF in `extract_module`) are engine findings +filed for the owner. Committed as M3.