Files
lucisv/crates/lucisv_mcp/tests/qa_m7.rs
T
lucioandClaude Fable 5.1 74c56318c0
ci / checks (push) Successful in 2m11s
ci / corpus (push) Successful in 45s
MCP: hierarchy caps at 300 instances (100 with peek), peek lines no longer count; census round 5 (read-only, same-day base control) written up; 0.59.0 notes dated
Round 5 found `hierarchy up` + `peek` cut to 20 of 77 instantiations by
the 300-line cap. Same-day base controls put read-only mode at parity
with file tools (a +8 %, d −8 %) and show the base arm itself moved
22–29 % in six days.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 01:38:54 -07:00

810 lines
33 KiB
Rust

//! QA attacks on lane M7 (the lean catalogue), 2026-09-24.
//!
//! Every test writes a small design into its own scratch directory, spawns
//! the real binary over it, sends `initialize` and a batch of `tools/call`s,
//! closes stdin and reads every answer — the host's view, nothing else.
//!
//! 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-lean-catalogue/README.md`.
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::{json, Value};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch design, removed on drop.
struct Tree(PathBuf);
impl Tree {
/// A tree holding `files` (`(relative path, text)`).
fn with(files: &[(&str, &str)]) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-m7-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let tree = Tree(fs::canonicalize(dir).unwrap());
for (rel, text) in files {
tree.write(rel, text);
}
tree
}
fn path(&self, rel: &str) -> PathBuf {
self.0.join(rel)
}
fn write(&self, rel: &str, text: &str) {
let path = self.path(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
fn read(&self, rel: &str) -> String {
fs::read_to_string(self.path(rel)).unwrap()
}
/// Every file's bytes, by relative path.
fn snapshot(&self) -> BTreeMap<String, Vec<u8>> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let rel = path.strip_prefix(root).unwrap().to_string_lossy().to_string();
out.insert(rel, fs::read(&path).unwrap());
}
}
}
let mut out = BTreeMap::new();
walk(&self.0, &self.0, &mut out);
out
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One answer: whether it was refused, and its text.
struct Said {
refused: bool,
text: String,
}
/// Run `calls` in one session over `tree`, in order.
fn session(tree: &Tree, calls: &[(&str, Value)]) -> Vec<Said> {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", tree.0.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut lines = vec![json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "qa_m7", "version": "0"}}})
.to_string()];
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}).to_string());
for (at, (tool, arguments)) in calls.iter().enumerate() {
let params = json!({"name": tool, "arguments": arguments});
let call =
json!({"jsonrpc": "2.0", "id": at + 1, "method": "tools/call", "params": params});
lines.push(call.to_string());
}
let mut stdin = child.stdin.take().unwrap();
stdin.write_all((lines.join("\n") + "\n").as_bytes()).unwrap();
drop(stdin);
let output = child.wait_with_output().unwrap();
let replies: Vec<Value> = String::from_utf8(output.stdout)
.unwrap()
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
(1..=calls.len())
.map(|id| {
let reply = replies.iter().find(|r| r["id"] == id).expect("every call is answered");
let result = &reply["result"];
Said {
refused: result["isError"] == true,
text: result["content"][0]["text"].as_str().unwrap_or_default().to_string(),
}
})
.collect()
}
/// One call that must succeed: its text.
fn text(tree: &Tree, tool: &str, arguments: Value) -> String {
let said = session(tree, &[(tool, arguments.clone())]).remove(0);
assert!(!said.refused, "{tool} {arguments}: {}", said.text);
said.text
}
/// One call that must be refused, leaving every file byte-identical.
fn refusal(tree: &Tree, tool: &str, arguments: Value) -> String {
let before = tree.snapshot();
let said = session(tree, &[(tool, arguments.clone())]).remove(0);
assert!(said.refused, "{tool} {arguments}: not refused: {}", said.text);
assert!(before == tree.snapshot(), "{tool} {arguments}: a refusal wrote");
said.text
}
/// The `… and N more` lines of an answer.
fn more_lines(text: &str) -> Vec<&str> {
text.lines()
.filter(|line| line.starts_with("… and ") || line.trim_start().starts_with("… and "))
.collect()
}
// ---------------------------------------------------------------------------
// Caps: exactly one `… and N more`, the count right, every line whole.
// ---------------------------------------------------------------------------
/// `big` instantiates `leaf` 400 times; `wide` has 350 ports and 320 nets
/// no one reads; 320 modules each declare `sig`.
fn crowded() -> Tree {
let mut big = String::from("module big;\n logic a;\n");
for i in 0..400 {
big.push_str(&format!(" leaf u_{i:03} (.a(a));\n"));
}
big.push_str("endmodule\n");
let ports: Vec<String> = (0..350).map(|i| format!(" input logic p{i}")).collect();
let mut wide = format!("module wide (\n{}\n);\n", ports.join(",\n"));
for i in 0..320 {
wide.push_str(&format!(" logic w{i};\n"));
}
wide.push_str("endmodule\n");
let mut files: Vec<(String, String)> = vec![
("rtl/leaf.sv".into(), "module leaf(input logic a);\nendmodule\n".into()),
("rtl/big.sv".into(), big),
("rtl/wide.sv".into(), wide),
];
for i in 0..320 {
files.push((
format!("rtl/m{i:03}.sv"),
format!("module m{i:03};\n logic sig;\nendmodule\n"),
));
}
let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect();
Tree::with(&borrowed)
}
#[test]
fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
let tree = crowded();
let calls = [
("hierarchy", json!({"root": "big"})),
("hierarchy", json!({"root": "leaf", "up": true})),
("hierarchy", json!({"root": "big", "peek": true})),
("hierarchy", json!({})),
("find", json!({"name": "sig"})),
("outline", json!({"unit": "wide"})),
("outline", json!({"file": "rtl/wide.sv"})),
("check", json!({})),
];
let said = session(&tree, &calls);
// (shown lines before the cut line, the count the cut line says)
let expected = [
(300, 101), // the root line + 400 instances
(300, 100), // 400 instantiations
(199, 301), // root + 99 two-line blocks: with peek the cap is 100 nodes
(300, 23), // counts line + 322 tops
(300, 20), // 320 declarations
(300, 51), // file:line + 350 ports
(300, 371), // module + 350 ports + 320 nets
(200, 120), // 320 unused nets
];
for ((call, said), (shown, rest)) in calls.iter().zip(&said).zip(expected) {
assert!(!said.refused, "{call:?}: {}", said.text);
let lines: Vec<&str> = said.text.lines().collect();
assert_eq!(more_lines(&said.text), [format!("… and {rest} more")], "{call:?}");
assert_eq!(lines.len(), shown + 1, "{call:?}");
assert_eq!(*lines.last().unwrap(), format!("… and {rest} more"), "{call:?}");
assert!(lines.iter().all(|line| !line.trim().is_empty()), "{call:?}");
}
// Every line before the cut is a whole fact: a tree line names its site.
for line in said[0].text.lines().skip(1).take(299) {
let (head, site) = line.trim_start().rsplit_once(' ').unwrap();
assert!(head.starts_with("u_") && head.ends_with(": leaf"), "{line}");
let (file, number) = site.split_once(':').unwrap();
assert_eq!(file, "rtl/big.sv");
number.parse::<u32>().unwrap();
}
// A peek block is never split: the last shown line is the 99th
// instance's statement.
let peek: Vec<&str> = said[2].text.lines().collect();
assert_eq!(peek[197], " u_098: leaf rtl/big.sv:101");
assert_eq!(peek[198], " leaf u_098 (.a(a));");
for line in said[7].text.lines().take(200) {
assert!(line.starts_with("rtl/wide.sv:") && line.ends_with("[unused-signal]"), "{line}");
}
}
// ---------------------------------------------------------------------------
// peek
// ---------------------------------------------------------------------------
const PEEKED: &str = "module leaf #(parameter int W = 1) (
input logic clk,
input logic [W-1:0] d,
output logic [W-1:0] q
);
always_ff @(posedge clk) q <= d;
endmodule
";
const PEEKER: &str = "module top (
input logic clk,
input logic [3:0] d,
output logic [3:0] q
);
logic [3:0] mid;
// a comment before the statement
leaf #(
.W(4) // width; with a semicolon in the comment
) u_a (
.clk, /* block ; comment */
.d (d),
.q (mid)
);
\tleaf #(.W(4)) u_b (.*);
leaf #(
.W(4)
) u_long (
.clk(clk),
// spaced
.d(mid),
.q(q)
// one
// two
// three
// four
// five
);
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
endmodule
";
#[test]
fn qa_peek_shows_a_commented_overridden_statement_exactly_and_cuts_at_12() {
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", PEEKER)]);
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
let expected = "top rtl/top.sv:1
u_a: leaf rtl/top.sv:10
leaf #(
.W(4) // width; with a semicolon in the comment
) u_a (
.clk, /* block ; comment */
.d (d),
.q (mid)
);
u_b: leaf rtl/top.sv:15
leaf #(.W(4)) u_b (.*);
u_long: leaf rtl/top.sv:18
leaf #(
.W(4)
) u_long (
.clk(clk),
// spaced
.d(mid),
.q(q)
// one
// two
// three
// four
// five
…
u_c: leaf rtl/top.sv:29
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
u_d: leaf rtl/top.sv:29
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
";
assert_eq!(down, expected);
// Up shows the same statements under `parent.instance` lines.
let up = text(&tree, "hierarchy", json!({"root": "leaf", "up": true, "peek": true}));
assert!(up.starts_with("top.u_a rtl/top.sv:10\n leaf #(\n .W(4) // width;"), "{up}");
assert_eq!(up.matches('…').count(), 1, "{up}");
// Exactly 12 lines is not cut.
let twelve = PEEKER.replace(" // five\n", "");
tree.write("rtl/top.sv", &twelve);
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
assert!(!down.contains('…'), "{down}");
}
#[test]
fn qa_peek_never_answers_a_whitespace_only_line() {
let spaced = PEEKER.replace(" .clk(clk),\n // spaced", " .clk(clk),\n\n // spaced");
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", &spaced)]);
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
// Lead's ruling on finding 4: the statement's blank line is an empty
// line — no indent, no trailing spaces; every other line stays exact.
assert!(down.lines().all(|line| line.is_empty() || !line.trim().is_empty()), "{down}");
assert!(down.contains(" .clk(clk),\n\n // spaced"), "{down}");
}
// ---------------------------------------------------------------------------
// Ambiguity and unknown names
// ---------------------------------------------------------------------------
const OTHER: &str = "module other (input logic clk);
logic mid;
assign mid = clk;
endmodule
";
const MID: &str = "module top2 (input logic clk);
logic mid;
assign mid = clk;
endmodule
";
#[test]
fn qa_ambiguous_and_unknown_names_are_refused_with_what_picks_one() {
let tree = Tree::with(&[
("rtl/leaf.sv", PEEKED),
("rtl/other.sv", OTHER),
("rtl/top2.sv", MID),
("rtl/dup.sv", "module leaf (input logic clk);\nendmodule\n"),
]);
let read = refusal(&tree, "read", json!({"item": "mid"}));
assert!(read.contains("rtl/other.sv:2, rtl/top2.sv:2") && read.contains("`file`"), "{read}");
let rename = refusal(&tree, "rename", json!({"name": "mid", "new_name": "m2"}));
assert!(rename.contains("rtl/other.sv:2, rtl/top2.sv:2"), "{rename}");
let module = refusal(&tree, "rename", json!({"name": "leaf", "new_name": "leaf2"}));
assert!(module.contains("rtl/dup.sv:1, rtl/leaf.sv:1"), "{module}");
// `file` picks one; `unit.name` picks one without it.
let picked = text(&tree, "read", json!({"item": "mid", "file": "rtl/top2.sv"}));
assert_eq!(picked, "rtl/top2.sv:2\nlogic mid;\n");
let renamed = text(&tree, "rename", json!({"name": "other.mid", "new_name": "m3"}));
assert_eq!(renamed, "renamed 2 sites in 1 file\n");
assert!(tree.read("rtl/top2.sv").contains("logic mid;"));
let find = refusal(&tree, "find", json!({"name": "lea"}));
assert_eq!(find, "no declaration named `lea`; similar: leaf.");
let none = refusal(&tree, "find", json!({"name": "qqq"}));
assert_eq!(none, "no declaration named `qqq`.");
let root = refusal(&tree, "hierarchy", json!({"root": "OTH"}));
assert_eq!(root, "no module or interface named `OTH`; similar: other.");
}
const FSM: &str = "module fsm (input logic clk, output logic busy);
typedef enum logic [1:0] {StIdle, StBusy} state_e;
state_e state_q;
function automatic logic helper(input logic x);
return ~x;
endfunction
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic lane_q;
end
assign busy = helper(state_q == StBusy);
always_ff @(posedge clk) state_q <= StIdle;
endmodule
";
#[test]
fn qa_find_and_rename_reach_every_declaration_outline_lists() {
let tree = Tree::with(&[("rtl/fsm.sv", FSM)]);
// `outline` lists these; `read` with `file` slices them; 0.57.0's
// `rename` renamed them by position. By name, the lean tools say they
// do not exist.
for name in ["state_e", "StIdle", "helper", "g_lane", "lane_q"] {
let said = session(&tree, &[("find", json!({"name": name}))]).remove(0);
assert!(!said.refused, "find {name}: {}", said.text);
}
let renamed = text(&tree, "rename", json!({"name": "StIdle", "new_name": "StRest"}));
assert!(renamed.starts_with("renamed 2 sites in 1 file"), "{renamed}");
}
#[test]
fn qa_find_near_matches_include_the_module_internals_find_lists() {
let tree = Tree::with(&[("rtl/other.sv", OTHER)]);
assert_eq!(text(&tree, "find", json!({"name": "mid"})), "var mid rtl/other.sv:2\n");
let near = refusal(&tree, "find", json!({"name": "mi"}));
assert!(near.contains("similar: mid"), "{near}");
}
// ---------------------------------------------------------------------------
// port
// ---------------------------------------------------------------------------
const SUB: &str = "module sub (
input logic clk,
input logic a,
output logic y
);
assign y = a;
endmodule
";
const P1: &str = "module p1 (input logic clk, input logic a, output logic y);
sub u_s (
.clk(clk),
.a (a),
.y (y)
);
endmodule
";
const P2: &str = "module p2 (input logic clk, input logic a, input logic b, output logic y);
logic y1, y2;
sub u_s1 (.clk, .a, .y(y1));
sub u_s2 (.*);
assign y = y1;
endmodule
";
#[test]
fn qa_port_refuses_bad_shapes_and_connects_every_instantiation_or_none() {
let tree = Tree::with(&[
("rtl/sub.sv", SUB),
("rtl/p1.sv", P1),
("rtl/p2.sv", P2),
("rtl/p3.sv", "module p3 (input logic clk, a, output logic y);\n sub u_pos (clk, a, y);\nendmodule\n"),
]);
let add = |after: Option<&str>| match after {
Some(after) => json!({"module": "sub", "add": "input logic b", "after": after}),
None => json!({"module": "sub", "add": "input logic b"}),
};
// A positional instantiation in one file refuses the whole edit.
let whole = refusal(&tree, "port", add(None));
assert!(whole.contains("p3.sv") && whole.contains("no edits were made"), "{whole}");
fs::remove_file(tree.path("rtl/p3.sv")).unwrap();
let anchor = refusal(&tree, "port", add(Some("nope")));
assert_eq!(anchor, "`sub` has no port `nope` (its ports: clk, a, y).");
let neither = refusal(&tree, "port", json!({"module": "sub"}));
assert_eq!(neither, "give exactly one of `add` and `remove`.");
let both =
refusal(&tree, "port", json!({"module": "sub", "add": "input logic b", "remove": "a"}));
assert_eq!(both, "give exactly one of `add` and `remove`.");
let stray = refusal(&tree, "port", json!({"module": "sub", "remove": "a", "after": "clk"}));
assert_eq!(stray, "`after` goes with `add`, not `remove`.");
let used = refusal(&tree, "port", json!({"module": "sub", "remove": "a"}));
assert!(used.contains("`a` is still used inside `sub`"), "{used}");
let unknown = refusal(&tree, "port", json!({"module": "nosuch", "add": "input logic b"}));
assert!(unknown.contains("`nosuch`"), "{unknown}");
// Three instantiations in two files, each connected.
let added = text(&tree, "port", add(Some("clk")));
assert!(
added.starts_with("added port b in module sub: 3 instantiations in 2 files\n"),
"{added}"
);
assert!(tree.read("rtl/sub.sv").contains(" input logic clk,\n input logic b,\n"));
assert!(
tree.read("rtl/p1.sv").contains(" .clk(clk),\n .b"),
"{}",
tree.read("rtl/p1.sv")
);
assert!(
tree.read("rtl/p2.sv").contains("sub u_s1 (.clk, .b(b), .a, .y(y1));"),
"{}",
tree.read("rtl/p2.sv")
);
assert!(tree.read("rtl/p2.sv").contains("sub u_s2 (.*);"));
}
// ---------------------------------------------------------------------------
// edit_item
// ---------------------------------------------------------------------------
const ITEMS: &str = "module m (input logic clk, output logic y);
logic used_sig;
logic unused_sig;
// the helper
function automatic logic helper(input logic x);
return ~x;
endfunction
assign used_sig = clk;
assign y = helper(used_sig);
endmodule
module n;
logic z;
endmodule
";
#[test]
fn qa_edit_item_refuses_used_deletes_and_renaming_replaces_and_inserts_at_a_units_end() {
let tree = Tree::with(&[("rtl/m.sv", ITEMS)]);
let edit = |op: &str, item: &str, text: Option<&str>| match text {
Some(text) => json!({"file": "rtl/m.sv", "op": op, "item": item, "text": text}),
None => json!({"file": "rtl/m.sv", "op": op, "item": item}),
};
let used = refusal(&tree, "edit_item", edit("delete", "used_sig", None));
assert_eq!(
used,
"still referenced: rtl/m.sv:8:10 `used_sig`; rtl/m.sv:9:21 `used_sig`; nothing written."
);
let called = refusal(&tree, "edit_item", edit("delete", "helper", None));
assert!(called.contains("rtl/m.sv:9:14 `helper`"), "{called}");
let renamed = refusal(&tree, "edit_item", edit("replace", "unused_sig", Some("logic other;")));
assert!(renamed.contains("`rename` renames"), "{renamed}");
let at_end = text(&tree, "edit_item", edit("insert_after", "end@n", Some(" logic w;")));
assert_eq!(at_end, "inserted declaration w rtl/m.sv:15\n");
assert!(tree.read("rtl/m.sv").ends_with("module n;\n logic z;\n\n logic w;\nendmodule\n"));
let nowhere = refusal(&tree, "edit_item", edit("insert_after", "end@nope", Some("logic q;")));
assert!(nowhere.contains("`nope`"), "{nowhere}");
// The control: an unused item goes, with its line.
let gone = text(&tree, "edit_item", edit("delete", "unused_sig", None));
assert_eq!(gone, "deleted declaration unused_sig rtl/m.sv:3\n");
}
// ---------------------------------------------------------------------------
// format
// ---------------------------------------------------------------------------
#[test]
fn qa_format_names_the_refused_file_writes_the_rest_and_refuses_an_empty_glob() {
let tree = Tree::with(&[
("rtl/a.sv", "module a(input logic x);\nlogic y;\nendmodule\n"),
("rtl/b.sv", "module b;\n logic y ;\nendmodule\n"),
("rtl/c.sv", "module c;\n logic y;\nendmodule\n"),
("rtl/bad.sv", "module bad(\n input logic x\n logic y;\nendmodule\n"),
]);
let nothing = refusal(&tree, "format", json!({"files": "rtl/**/*.vhd"}));
assert_eq!(nothing, "no indexed file matches `rtl/**/*.vhd`; nothing written.");
let bad = tree.read("rtl/bad.sv");
let answer = text(&tree, "format", json!({"files": "rtl/*.sv"}));
let lines: Vec<&str> = answer.lines().collect();
assert_eq!(lines[0], "formatted 3 files (1 unchanged)");
assert_eq!(lines.len(), 2, "{answer}");
assert!(lines[1].starts_with("not formatted: rtl/bad.sv (parse error: 3:3"), "{answer}");
assert_eq!(tree.read("rtl/a.sv"), "module a (input logic x);\n logic y;\nendmodule\n");
assert_eq!(tree.read("rtl/b.sv"), "module b;\n logic y;\nendmodule\n");
assert_eq!(tree.read("rtl/bad.sv"), bad);
let again = text(&tree, "format", json!({"files": "rtl"}));
assert!(
again.starts_with("formatted 3 files (3 unchanged)\nnot formatted: rtl/bad.sv"),
"{again}"
);
// Only the refused file: the call itself is a refusal.
let alone = refusal(&tree, "format", json!({"files": "rtl/bad.sv"}));
assert!(alone.starts_with("not formatted: rtl/bad.sv"), "{alone}");
}
// ---------------------------------------------------------------------------
// All-or-nothing
// ---------------------------------------------------------------------------
#[test]
fn qa_a_rename_whose_later_file_is_read_only_writes_nothing() {
let tree = Tree::with(&[("rtl/sub.sv", SUB), ("rtl/p1.sv", P1), ("rtl/p2.sv", P2)]);
let p2 = tree.path("rtl/p2.sv");
let mut permissions = fs::metadata(&p2).unwrap().permissions();
permissions.set_readonly(true);
fs::set_permissions(&p2, permissions.clone()).unwrap();
// `p1.sv` sorts first and would be written first: it must not be.
let refused = refusal(&tree, "rename", json!({"name": "sub", "new_name": "sub2"}));
assert_eq!(refused, "`rtl/p2.sv` is read-only; nothing written.");
#[allow(clippy::permissions_set_readonly_false)] // a test undoing its own chmod
permissions.set_readonly(false);
fs::set_permissions(&p2, permissions).unwrap();
let renamed = text(&tree, "rename", json!({"name": "sub", "new_name": "sub2"}));
assert_eq!(renamed, "renamed 4 sites in 3 files\n");
}
// ---------------------------------------------------------------------------
// Answer shape (PLAN §10.2)
// ---------------------------------------------------------------------------
#[test]
fn qa_answers_are_root_relative_one_fact_per_line_without_hints() {
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", PEEKER), ("rtl/fsm.sv", FSM)]);
let calls = [
("hierarchy", json!({})),
("hierarchy", json!({"root": "top", "depth": 3})),
("hierarchy", json!({"root": "leaf", "up": true})),
("find", json!({"name": "leaf", "refs": true})),
("find", json!({"name": "mid", "refs": true})),
("outline", json!({"file": "rtl/fsm.sv"})),
("outline", json!({"unit": "leaf"})),
("check", json!({})),
("check", json!({"file": "rtl/leaf.sv"})),
];
let root = tree.0.to_string_lossy().to_string();
for (call, said) in calls.iter().zip(session(&tree, &calls)) {
assert!(!said.refused, "{call:?}: {}", said.text);
assert!(said.text.ends_with('\n'), "{call:?}");
for line in said.text.lines() {
assert!(!line.trim().is_empty(), "{call:?}: a blank line in {}", said.text);
assert_eq!(line, line.trim_end(), "{call:?}");
assert!(!line.contains(&root) && !line.contains("/private/"), "{call:?}: {line}");
for hint in ["check:", "dry run", "use `", "call `", "next:"] {
assert!(!line.contains(hint), "{call:?}: {line}");
}
}
}
assert_eq!(text(&tree, "check", json!({"file": "rtl/leaf.sv"})), "ok\n");
}
// ---------------------------------------------------------------------------
// find refs: at most five declarations followed
// ---------------------------------------------------------------------------
#[test]
fn qa_find_refs_follows_five_declarations_and_says_so() {
let files: Vec<(String, String)> = (0..7)
.map(|i| {
let text = format!(
"module r{i} (output logic y);\n logic sig;\n assign y = sig;\nendmodule\n"
);
(format!("rtl/r{i}.sv"), text)
})
.collect();
let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect();
let tree = Tree::with(&borrowed);
let answer = text(&tree, "find", json!({"name": "sig", "refs": true}));
let mut expected = String::new();
for i in 0..7 {
expected.push_str(&format!("var sig rtl/r{i}.sv:2\n"));
if i < 5 {
expected.push_str(&format!(" rtl/r{i}.sv:3\n"));
}
}
expected.push_str("uses listed for 5 of 7 declarations\n");
assert_eq!(answer, expected);
}
// ---------------------------------------------------------------------------
// Re-check of the rework (2026-09-24): `declared.rs`, `rooted`, `similar`.
// ---------------------------------------------------------------------------
const LOCALS: &str = "module fsm (input logic clk, output logic busy);
typedef enum logic [1:0] {StIdle, StBusy} state_e;
state_e state_q;
function automatic logic helper(input logic x);
logic hl;
hl = ~x;
return hl;
endfunction
task automatic poke(output logic o);
o = 1'b0;
endtask
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic lane_q;
assign lane_q = gi[0];
end
always_comb begin
automatic logic tmp;
tmp = helper(state_q == StBusy);
busy = tmp | g_lane[0].lane_q;
end
always_ff @(posedge clk) state_q <= StIdle;
endmodule
";
#[test]
fn qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit() {
let cases = [
("state_e", "typedef state_e rtl/fsm.sv:2", "renamed 2 sites in 1 file"),
("StIdle", "enum_value StIdle rtl/fsm.sv:2", "renamed 2 sites in 1 file"),
("helper", "function helper rtl/fsm.sv:4", "renamed 2 sites in 1 file"),
("hl", "var hl rtl/fsm.sv:5", "renamed 3 sites in 1 file"),
("poke", "task poke rtl/fsm.sv:9", "renamed 1 site in 1 file"),
("gi", "genvar gi rtl/fsm.sv:12", "renamed 4 sites in 1 file"),
("tmp", "var tmp rtl/fsm.sv:17", "renamed 3 sites in 1 file"),
];
for (name, found, renamed) in cases {
let named = [
json!({"name": name, "new_name": "zz_new"}),
json!({"name": name, "new_name": "zz_new", "file": "rtl/fsm.sv"}),
json!({"name": format!("fsm.{name}"), "new_name": "zz_new"}),
];
for args in named {
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
assert_eq!(text(&tree, "find", json!({"name": name})), format!("{found}\n"));
assert_eq!(
text(&tree, "find", json!({"name": format!("fsm.{name}")})),
format!("{found}\n")
);
assert_eq!(text(&tree, "rename", args.clone()), format!("{renamed}\n"), "{args}");
let after = tree.read("rtl/fsm.sv");
let left = after
.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.any(|word| word == name);
assert!(!left, "{args}: `{name}` left in\n{after}");
}
}
}
#[test]
fn qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind() {
// `find g_lane refs` lists no use and `rename` answers `renamed 1 site`,
// leaving `g_lane[0].lane_q` naming a block that no longer exists —
// while `edit_item delete g_lane` sees the use (`rtl/fsm.sv:19:18`).
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
// Lead's ruling R1: the MCP layer refuses the rename, and the source
// is untouched.
let said = session(&tree, &[("rename", json!({"name": "g_lane", "new_name": "g_ln"}))]);
assert!(said[0].refused, "{}", said[0].text);
let why = &said[0].text;
assert!(why.starts_with("`rename` does not rename generate block labels"), "{why}");
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS);
}
#[test]
fn qa_rework_a_shared_base_name_is_named_by_path_or_left_alone() {
let tree = Tree::with(&[
("rtl/x/p1.sv", "module px (input logic clk);\n logic dup;\n assign dup = clk;\nendmodule\n"),
(
"rtl/y/p1.sv",
"module py (input logic clk);\n logic dup;\n assign dup = ~clk;\n sub u_s (.*);\nendmodule\n",
),
("rtl/z/sub.sv", "module sub (input logic clk, input logic a);\nendmodule\n"),
("rtl/z/p1b.sv", "module pz (input logic clk);\n logic a;\n sub u_s (.clk, .a);\nendmodule\n"),
]);
let both = refusal(&tree, "rename", json!({"name": "dup", "new_name": "d2"}));
assert!(both.contains("(rtl/x/p1.sv:2, rtl/y/p1.sv:2)"), "{both}");
let one = json!({"name": "dup", "new_name": "d2", "file": "rtl/y/p1.sv"});
assert_eq!(text(&tree, "rename", one), "renamed 2 sites in 1 file\n");
assert!(tree.read("rtl/y/p1.sv").contains("logic d2;"));
assert!(tree.read("rtl/x/p1.sv").contains("logic dup;"));
// The engine's sentences: `p1.sv` is two files, so it stays as said;
// `p1b.sv` is one, so it is named by its path.
let added = text(&tree, "port", json!({"module": "sub", "add": "input logic zz"}));
assert!(added.contains("`u_s` at p1.sv:4 connects with `.*` and p1.sv has"), "{added}");
assert!(added.contains("(rtl/z/p1b.sv:3)"), "{added}");
assert!(!added.contains("rtl/z/rtl/"), "{added}");
}
#[test]
fn qa_rework_an_enum_value_in_case_arms_is_renamed_across_files_with_its_mentions() {
let tree = Tree::with(&[
("rtl/st_pkg.sv", "package st_pkg;\n typedef enum logic [1:0] {StIdle, StRun, StDone} st_e;\nendpackage\n"),
(
"rtl/a.sv",
"module a import st_pkg::*; (input logic clk, output logic o);\n st_e s;\n // StRun is the busy state\n always_comb begin\n case (s)\n StIdle: o = 1'b0;\n StRun: o = 1'b1;\n default: o = 1'b0;\n endcase\n end\n always_ff @(posedge clk) s <= StRun;\nendmodule\n",
),
(
"rtl/b.sv",
"module b (input logic clk, output logic o);\n st_pkg::st_e s;\n initial $display(\"StRun\");\n always_comb begin\n unique case (s)\n st_pkg::StRun: o = 1'b1;\n default: o = 1'b0;\n endcase\n end\n always_ff @(posedge clk) s <= st_pkg::StIdle;\nendmodule\n",
),
]);
let found = text(&tree, "find", json!({"name": "StRun", "refs": true}));
let mentions = "unresolved:\n rtl/a.sv:3\n rtl/b.sv:3\n";
assert_eq!(
found,
format!("enum_value StRun rtl/st_pkg.sv:2\n rtl/a.sv:7,11\n rtl/b.sv:6\n{mentions}")
);
// Only in a comment or a string: no declaration, a sane near match.
assert_eq!(refusal(&tree, "find", json!({"name": "busy"})), "no declaration named `busy`.");
assert_eq!(
refusal(&tree, "find", json!({"name": "StRu"})),
"no declaration named `StRu`; similar: StRun."
);
let renamed = text(&tree, "rename", json!({"name": "st_pkg::StRun", "new_name": "StBusy"}));
assert_eq!(renamed, format!("renamed 4 sites in 3 files\n{mentions}"));
assert!(tree.read("rtl/b.sv").contains("st_pkg::StBusy: o"));
assert!(
tree.read("rtl/a.sv").contains("// StRun is")
&& tree.read("rtl/a.sv").contains("s <= StBusy;")
);
}
#[test]
fn qa_rework_an_escaped_net_is_still_found_through_the_index() {
let text_e = "module e (input logic clk, output logic o);\n logic \\my.sig ;\n assign \\my.sig = clk;\n assign o = \\my.sig ;\nendmodule\n";
let tree = Tree::with(&[("rtl/e.sv", text_e)]);
let found = text(&tree, "find", json!({"name": "\\my.sig", "refs": true}));
assert_eq!(found, "var \\my.sig rtl/e.sv:2\n rtl/e.sv:3,4\n");
}
#[test]
#[ignore = "QA re-check finding R2"]
fn qa_rework_an_escaped_local_outline_lists_is_found() {
// The word census holds identifier-shaped words only, so `declared.rs`
// never opens a file for an escaped name the index does not record.
let text_g = "module g (input logic clk, output logic o);\n function automatic logic fn(input logic x);\n logic \\loc.v ;\n \\loc.v = x;\n return \\loc.v ;\n endfunction\n assign o = fn(clk);\nendmodule\n";
let tree = Tree::with(&[("rtl/g.sv", text_g)]);
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
assert_eq!(text(&tree, "find", json!({"name": "\\loc.v"})), "var \\loc.v rtl/g.sv:3\n");
}