Files
lucisv/crates/lucisv_mcp/tests/qa_m8.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

558 lines
22 KiB
Rust

//! QA attacks on lane M8 (`--read-only`), 2026-09-29.
//!
//! Every test copies a fixture into its own scratch directory, spawns the
//! real binary over it, writes a whole session to stdin, closes it and reads
//! every answer — the host's view, nothing else. The no-write promise is
//! checked by a snapshot of every entry under the root: a file's size, mtime
//! and bytes, a directory's mtime (which moves when anything is created,
//! renamed or removed in it, a temporary file included).
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::SystemTime;
use serde_json::{json, Value};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// The message a read-only server refuses `name` with.
fn refused(name: &str) -> String {
format!("unknown tool: {name} (the server runs --read-only)")
}
/// A scratch directory, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn empty() -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-m8-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Tree(fs::canonicalize(dir).unwrap())
}
/// A fresh copy of `tests/fixtures/<fixture>`.
fn of(fixture: &str) -> Tree {
let tree = Tree::empty();
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
copy_tree(&source, &tree.0);
tree
}
fn arg(&self) -> &str {
self.0.to_str().unwrap()
}
}
impl Drop for Tree {
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();
}
}
}
/// One entry under a root: a file's size, mtime and bytes; a directory's mtime.
type Entry = (Option<u64>, SystemTime, Option<Vec<u8>>);
fn snapshot(tree: &Tree) -> BTreeMap<String, Entry> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Entry>) {
let relative = |path: &Path| path.strip_prefix(root).unwrap().to_string_lossy().to_string();
let meta = fs::symlink_metadata(dir).unwrap();
out.insert(format!("{}/", relative(dir)), (None, meta.modified().unwrap(), None));
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let meta = fs::symlink_metadata(&path).unwrap();
if meta.is_dir() {
walk(&path, root, out);
} else {
let bytes = fs::read(&path).unwrap();
out.insert(
relative(&path),
(Some(meta.len()), meta.modified().unwrap(), Some(bytes)),
);
}
}
}
let mut out = BTreeMap::new();
walk(&tree.0, &tree.0, &mut out);
out
}
/// Run the binary with `args`, send `lines` (one JSON-RPC message each),
/// close stdin and wait for it to exit.
fn run(args: &[&str], lines: &[Value]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
for line in lines {
// A raw line is passed as a JSON string, everything else serialised.
let text = match line {
Value::String(raw) => raw.clone(),
other => other.to_string(),
};
writeln!(stdin, "{text}").unwrap();
}
drop(stdin);
child.wait_with_output().unwrap()
}
/// Every answer on stdout, by its id as JSON text (`"\"c\""`, `null`).
fn answers(output: &Output) -> BTreeMap<String, Value> {
let stdout = String::from_utf8(output.stdout.clone()).unwrap();
let mut out = BTreeMap::new();
for line in stdout.lines().filter(|l| !l.trim().is_empty()) {
let reply: Value = serde_json::from_str(line).expect("every stdout line is JSON");
out.entry(reply["id"].to_string()).or_insert(reply);
}
out
}
fn request(id: &str, method: &str, params: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
}
fn call(id: &str, name: Value, arguments: Value) -> Value {
request(id, "tools/call", json!({"name": name, "arguments": arguments}))
}
fn initialize(id: &str) -> Value {
request(id, "initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}))
}
/// Every shape of every edit tool, each a real write in full mode
/// (`qa_every_edit_shape_writes_in_full_mode`), on the `edit` fixture.
fn edit_shapes() -> Vec<(&'static str, Value)> {
vec![
("rename", json!({"name": "leaf", "new_name": "leaf2"})),
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
("port", json!({"module": "spare", "add": "input logic en"})),
("port", json!({"module": "spare", "add": "input logic en2", "after": "clk"})),
("port", json!({"module": "spare", "remove": "unused_i"})),
(
"edit_item",
json!({"file": "rtl/mid.sv", "op": "replace", "item": "u_leaf", "text": "leaf u_leaf (.clk(clk), .d(din), .q(dout));"}),
),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_b;"}),
),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_after", "item": "end", "text": "logic spare_a;"}),
),
("edit_item", json!({"file": "rtl/spare_user.sv", "op": "delete", "item": "spare_user"})),
("format", json!({"files": "fmt/messy.sv"})),
("format", json!({"files": "fmt/messy.sv", "fix": true})),
("format", json!({"files": "**/*.sv", "fix": true})),
("format", json!({"files": "rtl"})),
]
}
#[test]
fn qa_every_edit_shape_writes_in_full_mode() {
// The control for the promise: each shape really edits without the flag.
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let lines = [initialize("i"), call("c", json!(name), arguments.clone())];
let output = run(&["--root", tree.arg()], &lines);
let reply = &answers(&output)["\"c\""];
assert_eq!(reply["result"]["isError"], false, "{index} {name} {arguments}: {reply}");
assert_ne!(before, snapshot(&tree), "{index} {name} wrote nothing in full mode");
}
}
/// The malformed and near-miss calls a read-only server must refuse, each
/// with the code and message it must answer.
fn hostile_calls() -> Vec<(Value, i64, String)> {
let mut out = Vec::new();
// Names that differ from an edit tool by case, whitespace or spelling.
for name in [
"Rename",
"RENAME",
" rename",
"rename ",
"rename\n",
"rename\u{0}",
"edit-item",
"editItem",
"Format",
"port ",
"\u{ff52}ename",
"format\t",
] {
out.push((call(&format!("n{}", out.len()), json!(name), json!({})), -32602, refused(name)));
}
// A name that is not a string.
let not_string = "tools/call params need a string `name`".to_string();
for name in [json!(6), json!(["rename"]), json!({"name": "rename"}), json!(null), json!(true)] {
out.push((call(&format!("t{}", out.len()), name, json!({})), -32602, not_string.clone()));
}
// An edit name with malformed or smuggled arguments.
// The name is looked up before the arguments are read.
for arguments in
[json!(null), json!([]), json!("x"), json!({"name": 1}), json!({"mode": "full"})]
{
let line = call(&format!("a{}", out.len()), json!("rename"), arguments);
out.push((line, -32602, refused("rename")));
}
let meta = request(
"meta",
"tools/call",
json!({"name": "format", "arguments": {"files": "rtl"}, "_meta": {"mode": "full"}, "mode": "full"}),
);
out.push((meta, -32602, refused("format")));
out
}
#[test]
fn qa_read_only_never_changes_a_byte_whatever_arrives() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let mut lines = Vec::new();
// Before `initialize`: refused as not initialized, never run.
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
lines.push(call(&format!("early{index}"), json!(name), arguments));
}
lines.push(initialize("init"));
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
// Every edit shape as a request and as a notification (no id).
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
lines.push(call(&format!("edit{index}"), json!(name), arguments.clone()));
let params = json!({"name": name, "arguments": arguments});
lines.push(json!({"jsonrpc": "2.0", "method": "tools/call", "params": params}));
lines.push(
json!({"jsonrpc": "2.0", "method": format!("notifications/{name}"), "params": params}),
);
}
let hostile = hostile_calls();
lines.extend(hostile.iter().map(|(line, _, _)| line.clone()));
// A batch, a duplicate `name` key, a second `initialize` asking for more.
lines.push(json!([call("batched", json!("format"), json!({"files": "rtl"}))]));
lines.push(json!(r#"{"jsonrpc":"2.0","id":"dup","method":"tools/call","params":{"name":"check","name":"format","arguments":{"files":"rtl"}}}"#));
lines.push(request(
"reinit",
"initialize",
json!({"capabilities": {"experimental": {"mode": "full"}}}),
));
lines.push(call("after-reinit", json!("format"), json!({"files": "rtl"})));
for uri in [
"lucisv://overview",
"lucisv://rules",
"lucisv://unit/leaf",
"lucisv://unit/spare",
"lucisv://file/rtl/leaf.sv/outline",
"lucisv://file/fmt%2Fmessy.sv/outline",
"lucisv://format/fmt/messy.sv",
"lucisv://unit/..%2F..%2Fetc",
] {
lines.push(request(&format!("res {uri}"), "resources/read", json!({"uri": uri})));
}
for method in ["notifications/cancelled", "notifications/roots/list_changed", "notifications/x"]
{
lines.push(json!({"jsonrpc": "2.0", "method": method, "params": {"requestId": "edit0"}}));
}
lines.push(call("still", json!("check"), json!({})));
let output = run(&["--root", tree.arg(), "--read-only"], &lines);
assert!(output.status.success(), "{:?}", output.status);
let answers = answers(&output);
for index in 0..edit_shapes().len() {
assert_eq!(answers[&format!("\"early{index}\"")]["error"]["code"], -32002);
}
for (index, (name, _)) in edit_shapes().into_iter().enumerate() {
let reply = &answers[&format!("\"edit{index}\"")];
assert_eq!(reply["error"]["code"], -32602, "{reply}");
assert_eq!(reply["error"]["message"], refused(name), "{reply}");
}
for (line, code, message) in &hostile {
let reply = &answers[&line["id"].to_string()];
assert_eq!(reply["error"]["code"], *code, "{line} -> {reply}");
assert_eq!(reply["error"]["message"], *message, "{line} -> {reply}");
}
assert_eq!(answers["null"]["error"]["code"], -32600, "the batch is refused");
assert_eq!(answers["\"dup\""]["error"]["message"], refused("format"), "last key wins");
assert_eq!(answers["\"after-reinit\""]["error"]["message"], refused("format"));
assert_eq!(answers["\"still\""]["result"]["isError"], false);
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
}
/// The first `tools/list` answer's tool names for a server started with `args`.
fn listed(args: &[&str]) -> (Option<Vec<String>>, Output) {
let output = run(args, &[initialize("i"), request("l", "tools/list", json!({}))]);
let names = answers(&output).get("\"l\"").map(|reply| {
let tools = reply["result"]["tools"].as_array().unwrap();
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
});
(names, output)
}
#[test]
fn qa_argument_order_and_repetition_cannot_undo_read_only() {
let tree = Tree::of("design");
let root = tree.arg();
let five = ["hierarchy", "find", "outline", "read", "check"].map(String::from).to_vec();
for args in [
vec!["--read-only", "--root", root],
vec!["--root", root, "--read-only", "--read-only"],
vec!["--read-only", "--verbose", "--root", root, "--read-only"],
] {
let (names, output) = listed(&args);
assert_eq!(names.as_ref(), Some(&five), "{args:?}: {output:?}");
}
// A value for the flag is refused by the usage rule, never read as full.
for args in [
vec!["--root", root, "--read-only=false"],
vec!["--root", root, "--read-only", "false"],
vec!["--root", root, "--read-only=true"],
vec!["--root", root, "--readonly"],
vec!["--root", root, "--no-read-only"],
] {
let (names, output) = listed(&args);
assert_eq!(names, None, "{args:?} started a server");
assert_eq!(output.status.code(), Some(2), "{args:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("unknown option") && stderr.contains("[--read-only]"), "{stderr}");
}
}
/// The text of every `tools/call` and `resources/read` answer, by id.
fn texts(args: &[&str], lines: &[Value]) -> BTreeMap<String, String> {
let mut session = vec![initialize("i")];
session.extend_from_slice(lines);
let output = run(args, &session);
let mut out = BTreeMap::new();
for (id, reply) in answers(&output) {
let result = &reply["result"];
let text = result["content"][0]["text"]
.as_str()
.or_else(|| result["contents"][0]["text"].as_str())
.map(str::to_string)
.unwrap_or_else(|| reply.to_string());
out.insert(id, text);
}
out.remove("\"i\"");
out
}
#[test]
fn qa_the_read_tools_and_resources_answer_identically_in_both_modes() {
let reads = [
("design", "hierarchy", json!({})),
("design", "hierarchy", json!({"root": "top", "depth": 3, "peek": true})),
("design", "find", json!({"name": "leaf", "refs": true})),
("design", "outline", json!({"file": "rtl/top.sv"})),
("design", "read", json!({"item": "top"})),
("design", "check", json!({})),
("design", "check", json!({"file": "rtl/broken.sv"})),
("design", "find", json!({"nome": "x"})),
("edit", "hierarchy", json!({"root": "leaf", "up": true})),
("edit", "outline", json!({"unit": "spare"})),
("edit", "check", json!({"file": "fmt/messy.sv"})),
("edit", "read", json!({"item": "u_leaf", "file": "rtl/mid.sv"})),
];
for fixture in ["design", "edit"] {
let tree = Tree::of(fixture);
let mut lines: Vec<Value> = reads
.iter()
.enumerate()
.filter(|(_, (f, _, _))| *f == fixture)
.map(|(index, (_, name, arguments))| {
call(&format!("r{index}"), json!(name), arguments.clone())
})
.collect();
for uri in ["lucisv://overview", "lucisv://rules", "lucisv://unit/leaf", "lucisv://nope"] {
lines.push(request(uri, "resources/read", json!({"uri": uri})));
}
for method in ["resources/list", "resources/templates/list", "prompts/list"] {
lines.push(request(method, method, json!({})));
}
let full = texts(&["--root", tree.arg()], &lines);
let read_only = texts(&["--root", tree.arg(), "--read-only"], &lines);
assert_eq!(full.len(), lines.len(), "{fixture}: {full:?}");
assert_eq!(full, read_only, "{fixture}");
}
}
#[test]
fn qa_a_read_only_index_cache_outside_the_root_leaves_the_root_alone() {
// The store is written where it is told (the extension's workspace
// storage); the root is not, even with the store beside it.
let parent = Tree::empty();
let root = parent.0.join("root");
copy_tree(&Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/edit"), &root);
let tree = Tree(root);
let cache = parent.0.join("cache");
let before = snapshot(&tree);
let lines = [
initialize("i"),
call("c", json!("format"), json!({"files": "rtl"})),
call("k", json!("check"), json!({})),
];
let output = run(
&["--root", tree.arg(), "--index-cache", cache.to_str().unwrap(), "--read-only"],
&lines,
);
assert!(output.status.success());
assert_eq!(before, snapshot(&tree));
assert!(cache.join(".gitignore").exists(), "the store directory was written");
}
// ---------------------------------------------------------------------------
// Re-check 2026-09-29: `hierarchy`'s cap counts nodes, never peek lines.
// ---------------------------------------------------------------------------
/// `module name` with `count` instances of `child`, each written over 14
/// lines (header, 12 port lines, closer), so each peek block is cut to 12
/// lines and `…` — 14 answer lines per node.
fn wide_parent(name: &str, child: &str, count: usize) -> (String, String) {
let mut text = format!("module {name};\n");
for i in 0..count {
text.push_str(&format!(" {child} u_{i:03} (\n"));
for p in 0..12 {
let comma = if p < 11 { "," } else { "" };
text.push_str(&format!(" .p{p}(1'b0){comma}\n"));
}
text.push_str(" );\n");
}
text.push_str("endmodule\n");
(format!("{name}.sv"), text)
}
/// A 12-input leaf module.
fn leaf(name: &str) -> (String, String) {
let ports: Vec<String> = (0..12).map(|p| format!("input logic p{p}")).collect();
(format!("{name}.sv"), format!("module {name} ({});\nendmodule\n", ports.join(", ")))
}
/// `dN` declares N instances (N + 1 nodes with its root line); `uN` is
/// instantiated N times (N nodes up). Sizes sit on both caps' boundaries:
/// 300/301 nodes without `peek`, 100/101 with it.
fn boundary_tree() -> Tree {
let tree = Tree::empty();
let files = [
leaf("x"),
leaf("y"),
leaf("u100"),
leaf("u101"),
leaf("u300"),
leaf("u301"),
wide_parent("d99", "x", 99),
wide_parent("d100", "y", 100),
wide_parent("d299", "x", 299),
wide_parent("d300", "y", 300),
wide_parent("h100", "u100", 100),
wide_parent("h101", "u101", 101),
wide_parent("h300", "u300", 300),
wide_parent("h301", "u301", 301),
];
for (path, text) in files {
fs::write(tree.0.join(path), text).unwrap();
}
tree
}
/// Each call's text, in order, from one session in `mode_args`.
fn hierarchy_texts(tree: &Tree, calls: &[Value], mode_args: &[&str]) -> Vec<String> {
let mut args = vec!["--root", tree.arg()];
args.extend_from_slice(mode_args);
let mut lines = vec![initialize("i")];
lines.extend(
calls
.iter()
.enumerate()
.map(|(n, a)| call(&format!("h{n}"), json!("hierarchy"), a.clone())),
);
let answers = answers(&run(&args, &lines));
(0..calls.len())
.map(|n| {
let reply = &answers[&format!("\"h{n}\"")];
assert_eq!(reply["result"]["isError"], false, "{reply}");
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
})
.collect()
}
/// The node cap without `peek` (PLAN §10.1).
const PLAIN_CAP: usize = 300;
/// The node cap with `peek` (M8 rework 3).
const PEEK_CAP: usize = 100;
#[test]
fn qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek() {
let tree = boundary_tree();
// (arguments, nodes in the whole answer, statement indent)
let cases = [
(json!({"root": "d99"}), 100, " "),
(json!({"root": "d100"}), 101, " "),
(json!({"root": "d299"}), 300, " "),
(json!({"root": "d300"}), 301, " "),
(json!({"root": "u100", "up": true}), 100, " "),
(json!({"root": "u101", "up": true}), 101, " "),
(json!({"root": "u300", "up": true}), 300, " "),
(json!({"root": "u301", "up": true}), 301, " "),
];
let mut calls = Vec::new();
for (arguments, _, _) in &cases {
calls.push(arguments.clone());
let mut peeked = arguments.clone();
peeked["peek"] = json!(true);
calls.push(peeked);
}
let full = hierarchy_texts(&tree, &calls, &[]);
assert_eq!(full, hierarchy_texts(&tree, &calls, &["--read-only"]), "the modes disagree");
for (at, (arguments, total, indent)) in cases.iter().enumerate() {
let root_lines = usize::from(arguments["up"] != true);
let cut_line = |cap: usize| (*total > cap).then(|| format!("… and {} more", total - cap));
// Without peek: one line per node, at most 300, then the cut line.
let plain: Vec<&str> = full[2 * at].lines().collect();
let (plain_shown, plain_cut) = ((*total).min(PLAIN_CAP), cut_line(PLAIN_CAP));
assert_eq!(plain.len(), plain_shown + usize::from(plain_cut.is_some()), "{arguments}");
if let Some(cut) = &plain_cut {
assert_eq!(plain.last().copied(), Some(cut.as_str()), "{arguments}");
}
// With peek: the first 100 of the same node lines, then its own cut line.
let peek: Vec<&str> = full[2 * at + 1].lines().collect();
let (shown, cut) = ((*total).min(PEEK_CAP), cut_line(PEEK_CAP));
let nodes: Vec<&str> = peek.iter().copied().filter(|l| !l.starts_with(indent)).collect();
let mut expected: Vec<&str> = plain[..shown].to_vec();
if let Some(cut) = &cut {
expected.push(cut.as_str());
}
assert_eq!(nodes, expected, "{arguments}");
// Every instance node is followed by a whole block: 12 lines, then `…`.
let instances = shown - root_lines;
let cut_lines = usize::from(cut.is_some());
assert_eq!(peek.len(), root_lines + instances * 14 + cut_lines, "{arguments}");
let blocks = peek.iter().filter(|l| l.trim() == "…").count();
assert_eq!(blocks, instances, "{arguments}");
if cut.is_some() {
// The block before the cut line is whole: it ends in `…`.
assert_eq!(peek[peek.len() - 2].trim(), "…", "{arguments}");
}
}
}