Files
lucisv/crates/lucisv_mcp/tests/qa_m3.rs
T
Guoliang ChenandClaude Mythos 5.2 a8c22dcab0
ci / linux (push) Failing after 34s
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 16s
release / build-and-publish (push) Successful in 5m22s
Release 0.65.9: lucisv-mcp no longer serves stale contents; the suite runs on Linux
TODO §70, closed.

- lucisv_mcp/src/project/files.rs: Stamp's racy rule (re-check by content a
  stamp taken too close to a timestamp it trusts) covered the mtime alone.
  On Linux, where ctime moves in 1 ms ticks, a same-size rewrite that
  restored the old mtime inside the tick of the server's read matched in
  every field and index-based answers came from the old text indefinitely.
  The rule now covers every trusted timestamp (mtime, and ctime where there
  is one), the window is 3 s, and a wall clock stepped back since the read
  distrusts the stamp. The decision is a pure compare(Seen, Clocks) with
  deterministic unit tests.
- Test-only: two stdin helpers tolerate BrokenPipe on the write to a child
  that exits before reading (lucisv cli.rs, lucisv_mcp qa_m8.rs); the
  didOpen latency test's budget is six parses of the same buffer, not 200 ms
  (lucisv_server e2e.rs); qa_m3's server is spawned before its checker
  thread, which removes a hang on a pipe inherited across threads on macOS.
- .gitea/workflows/ci.yml: a linux job on the luhpe-linux-x64 runner —
  clippy and cargo test --workspace on Linux x86-64.
- docs/features/mcp-transport describes the new rule and what it cannot see
  (Windows has no ctime; writable mmaps).

Linux: whole suite green 10/10 as root and 10/10 as a user (dev), 6/6 and
6/6 (QA). QA reproduced the stale read on 0.65.8 (65/65, 87/87 when the stat
was identical) and got 0 here. Dev, QA and lead review:
docs/features/linux-test-portability/README.md, Round 2.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.9) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree including cross; lucisv_mcp 388/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 13:03:59 -08:00

1229 lines
52 KiB
Rust

//! QA attacks on lane M3 (the edit tools and their one write path),
//! 2026-09-23 — ported to the lean catalogue (`rename`, `port`,
//! `edit_item`, `format`); the tools it dropped took their attacks with
//! them (`docs/features/mcp-lean-catalogue/README.md` lists which).
//!
//! Two kinds of test. The first half includes the production write path,
//! `src/apply.rs`, verbatim (`#[path]`) over a small stand-in for the
//! module it names (`Project`'s roots), 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<PathBuf>,
}
impl Project {
pub fn open(roots: Vec<PathBuf>, _filelist: Option<PathBuf>) -> 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()
}
}
}
#[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<String, (u32, Vec<u8>)> {
use std::os::unix::fs::PermissionsExt;
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, (u32, Vec<u8>)>) {
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<String, (u32, Vec<u8>)>,
after: &BTreeMap<String, (u32, Vec<u8>)>,
) -> Vec<String> {
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<ChildStdin>,
lines: Receiver<String>,
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()
}
/// 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<PathBuf> {
let path = Path::new(BIN).parent()?.join("lucisv");
path.exists().then_some(path)
}
// ================================================ 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<apply::Change> {
["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` writes it and says so.
fs::write(&read, &texts[0].1).unwrap();
let plan = apply::Plan::from_refactor(edit(&read, 0, 6), &texts).unwrap();
assert!(plan.warnings.is_empty());
let project = project::Project::open(vec![scratch.0.clone()], None);
let pristine = snapshot(&scratch.0);
let written = apply::run(&project, &plan).unwrap();
assert_eq!((written.changed, written.created), (vec!["r.sv".to_string()], vec![]));
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), ["r.sv"]);
assert_eq!(fs::read_to_string(&read).unwrap(), "z é; endmodule\n");
}
// ================================================ corruption hunt (attack 1)
/// Every edit tool, one real call over a fresh fixture copy: exactly the
/// expected files move, the answer's counts are the files that moved, and
/// the same call again writes nothing.
#[test]
fn qa_every_edit_writes_only_what_it_says_and_a_repeat_writes_nothing() {
let calls: [(&str, Value, &[&str]); 7] = [
(
"rename",
json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}),
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
),
(
"port",
json!({"module": "spare", "remove": "unused_i"}),
&["rtl/spare.sv", "rtl/spare_user.sv"],
),
(
"port",
json!({"module": "leaf", "add": "input logic en"}),
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
),
(
"port",
json!({"module": "leaf", "add": "input logic en", "after": "clk"}),
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
),
("format", json!({"files": "fmt/messy.sv"}), &["fmt/messy.sv"]),
("format", json!({"files": "fmt/messy.sv", "fix": true}), &["fmt/messy.sv"]),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_after", "item": "end", "text": "logic spare_q;"}),
&["rtl/leaf.sv"],
),
];
for (tool, arguments, expected) 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 said = server.text(tool, arguments.clone());
let written = snapshot(&scratch.0);
assert_eq!(moved(&pristine, &written), expected, "{tool} {arguments}: {said}");
if tool == "rename" {
assert!(said.starts_with("renamed 4 sites in 3 files\n"), "{said}");
}
// Not idempotent: the same insertion again would declare twice.
let again = server.call(tool, arguments.clone());
let said = text_of(&again);
assert!(
moved(&written, &snapshot(&scratch.0)).is_empty(),
"{tool}: the repeat wrote: {said}"
);
}
}
/// 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 leaf_d = |new_name: &str| json!({"name": "d", "file": "rtl/leaf.sv", "new_name": new_name});
let refused = [
("rename", leaf_d("module")),
("rename", leaf_d("clk")),
("rename", leaf_d("\\a+b ")),
("rename", json!({"name": "clk", "new_name": "ck"})),
("rename", json!({"name": "o", "file": "out/o.sv", "new_name": "p"})),
("port", json!({"module": "cell", "remove": "en"})),
("port", json!({"module": "pos", "remove": "en"})),
("port", json!({"module": "cell", "add": "input logic en"})),
("port", json!({"module": "cell", "add": "input logic newp"})),
("port", json!({"module": "leaf", "add": "input logic x", "after": "nope"})),
("edit_item", json!({"file": "rtl/leaf.sv", "op": "delete", "item": "leaf"})),
("edit_item", json!({"file": "out/o.sv", "op": "delete", "item": "o"})),
("format", json!({"files": "fmt/broken.sv"})),
("format", json!({"files": "out/o.sv"})),
("format", json!({"files": "/etc/hosts"})),
("format", json!({"files": "fpv/**/*.sv"})),
];
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 written out by the
/// rename, a port placed after a commented one.
#[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",
),
]);
let comments = [
"// the clock",
"// data in /* not nested */",
"// data out",
"// register",
"// the instance",
"// leading",
"// trailing star comment",
"/* block */",
];
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<usize> = comments.iter().map(|c| count(&scratch, c)).collect();
let mut server = Session::over(&scratch);
server.text("rename", json!({"name": "d", "file": "leaf.sv", "new_name": "din"}));
server.text("port", json!({"module": "leaf", "add": "input logic en", "after": "clk"}));
let after: Vec<usize> = comments.iter().map(|c| count(&scratch, c)).collect();
assert_eq!(before, after, "{:?}", snapshot(&scratch.0).keys().collect::<Vec<_>>());
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!({"name": from, "file": "rtl/leaf.sv", "new_name": to});
let original: Vec<String> = files.iter().map(|f| scratch.read(f)).collect();
server.text("rename", at("d", "din_i"));
let renamed: Vec<String> = 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::<Vec<_>>());
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_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();
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
let outside_pristine = snapshot(&outside.0);
let abs = outside.path("ext.sv");
for file in ["link/ext.sv", abs.to_str().unwrap()] {
let delete = json!({"file": file, "op": "delete", "item": "s"});
assert!(server.refusal("edit_item", delete).contains("outside every root"));
assert!(server.refusal("format", json!({"files": file})).contains("outside every root"));
let rename = json!({"name": "s", "file": file, "new_name": "t"});
assert!(server.refusal("rename", rename).contains("outside every root"));
}
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
assert!(moved(&outside_pristine, &snapshot(&outside.0)).is_empty());
}
#[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` 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!({"name": "d", "file": "rtl/leaf.sv", "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("format", json!({"files": "fmt/messy.sv", "fix": true}));
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"}));
assert_eq!(text, "formatted 1 file (0 unchanged)\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");
assert_eq!(server.text("format", json!({"files": "*.sv"})), "formatted 1 file (1 unchanged)\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<String> = 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:?}");
// The server is spawned before the checker starts, never while it runs.
// A spawn on one thread can inherit a pipe another thread is just
// creating for its child: macOS has no `pipe2`, so close-on-exec is set
// in a second step. Seen once under load (2026-11-19, `lsof`): the
// server held the write end of a `lucisv --check`'s stdout. That
// `output()` never saw EOF, `join` below waited on it, and the server,
// which lives until this test ends, never let go, so the test hung.
// Spawned first, the server cannot hold any of the checker's pipes.
let mut server = Session::over(&scratch);
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
})
};
for _ in 0..5 {
for (name, text) in &messy {
scratch.write(name, text);
}
let result = server.call("format", json!({"files": "m*.sv"}));
let said = text_of(&result);
assert!(result["isError"] == false || said.contains("changed on disk"), "{said}");
}
server.text("format", json!({"files": "m*.sv"}));
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.
#[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",
),
];
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!({"files": file}));
assert_eq!(mcp.read(file), cli_tree.read(file), "{file}");
}
}
// ================================================ fix (attack 1, 5)
/// `format` with `fix` writes what `lucisv check --fix` then `lucisv`
/// write: nothing inside a `// lucisv: off` or `// verilog_format: off`
/// fence, and never the unsafe `always-comb` fix.
#[test]
fn qa_fix_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);
server.text("format", json!({"files": "f.sv", "fix": true}));
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_comb"), "an unsafe fix was applied: {fixed:?}");
assert!(!fixed.contains("4'b1;;"), "the safe fix was not 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();
Command::new(&cli).arg("--no-cache").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<String, String> {
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", "file": "rtl/leaf.sv", "new_name": "din_i"}));
let written: Vec<String> = moved(&pristine, &snapshot(&scratch.0));
assert_eq!(written, expected.keys().cloned().collect::<Vec<_>>());
for (file, text) in &expected {
assert_eq!(&scratch.read(file), text, "{file}");
}
}
#[test]
fn qa_rename_by_name_writes_the_files_find_lists() {
let scratch = Scratch::edit_fixture();
let mut server = Session::over(&scratch);
let found = server.text("find", json!({"name": "din", "refs": true}));
let mut files: Vec<String> = found
.lines()
.map(|line| line.trim().rsplit(' ').next().unwrap().split(':').next().unwrap().to_string())
.collect();
files.sort();
files.dedup();
let pristine = snapshot(&scratch.0);
server.text("rename", json!({"name": "din", "new_name": "d_in"}));
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), files, "{found}");
// 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("pass `file`"), "{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!({"name": "sig_a", "new_name": "sig_b"}));
assert!(text.contains("\nwarning: `sig_a` appears in the arguments of the macro"), "{text}");
assert!(text.ends_with("unresolved:\n m.sv:3\n"), "{text}");
}
// ================================================ findings
/// Finding 1 (blocking, engine): renaming a port bound by an implicit
/// connection (`.*` or `.name`), or a net such a connection binds, must
/// refuse or rewrite the connection explicitly — never leave the binding
/// broken (M3.5).
#[test]
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!({"name": "d", "file": "leaf.sv", "new_name": "din"}),
// The net `.*` binds.
json!({"name": "d", "file": "top.sv", "new_name": "x"}),
// The net `.d` binds.
json!({"name": "d", "file": "top2.sv", "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 must not leave unrenamed a use in a file
/// the index skipped (over 1 MiB, or not UTF-8) without a word.
#[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.rename_d();
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 4 (lead's ruling: no change), kept for the flags that remain:
/// JSON null is "not given" for every argument; `"true"` and `1` are
/// refused as non-booleans.
#[test]
fn qa_a_null_flag_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!({"files": "fmt/messy.sv", "fix": not_boolean});
server.refusal("format", arguments);
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
}
let result = server.call("format", json!({"files": "fmt/messy.sv", "fix": null}));
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), ["fmt/messy.sv"], "{}", text_of(&result));
}
// ================================================ 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<u8> {
let mut bytes = b"// Copyright \xa9 2020 vendor\n".to_vec();
bytes.extend_from_slice(body);
bytes
}
impl Session {
/// A rename of `leaf`'s port `d` to `din_i`.
fn rename_d(&mut self) -> Value {
self.call("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}))
}
}
#[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<u8>, &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);
let result = server.rename_d();
assert_eq!(result["isError"], true, "{result}");
assert_eq!(
text_of(&result),
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<u8>, &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 result = server.rename_d();
let text = text_of(&result);
let line = format!("warning: 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 = text_of(&server.rename_d());
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 = text_of(&Session::over(&scratch).rename_d());
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!({"name": "\\a+b", "file": "rtl/esc.sv", "new_name": "ab"});
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 refuses over its stake when only a skipped file
/// spells it; a rename of a name the skipped file does not spell 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 = [
("port", json!({"module": "cell", "add": "input logic x_i"}), "cell"),
("port", json!({"module": "spare", "remove": "unused_i"}), "spare"),
("rename", json!({"name": "inv", "new_name": "inv2"}), "inv"),
("rename", json!({"name": "old", "new_name": "old2"}), "old"),
];
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("rename", json!({"name": "unused_i", "new_name": "spare_i"}));
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 at once
/// (every edit walks first); 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!(text_of(&server.rename_d()).starts_with("`rtl/big.sv`"));
scratch.write("rtl/big.sv", &format!("module big (input logic clk);\n{use_d}endmodule\n"));
let written = server.rename_d();
assert_eq!(written["isError"], false, "{written}");
assert!(!text_of(&written).contains("not indexed"), "{written}");
assert!(scratch.read("rtl/big.sv").contains(".din_i(x)"));
// 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 back = json!({"name": "din_i", "file": "rtl/leaf.sv", "new_name": "d"});
let said = server.refusal("rename", back);
assert!(
said.starts_with("`rtl/mid.sv` (skipped: not UTF-8 text) may reference `din_i`"),
"{said}"
);
}
/// `find`'s answers over a tree with a skipped file that spells nothing
/// differ from the plain tree's only by the one trailing warning line, for
/// every name the nav fixture spells.
#[test]
fn qa_recheck_find_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 = "warning: not indexed, so not searched or edited: rtl/zz.sv (not UTF-8 text)\n";
let mut words: Vec<String> = Vec::new();
for (file, (_, bytes)) in snapshot(&plain.0) {
if file.ends_with(".sv") || file.ends_with(".svh") {
let text = String::from_utf8(bytes).unwrap();
let spelled = text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
words.extend(
spelled
.filter(|w| w.starts_with(|c: char| c.is_ascii_alphabetic()))
.map(String::from),
);
}
}
words.sort();
words.dedup();
let mut answered = 0;
for word in words {
let args = json!({"name": word, "refs": true});
let (x, y) = (a.call("find", args.clone()), b.call("find", args.clone()));
if x["isError"] == true {
assert_eq!(x, y, "{args}");
continue;
}
answered += 1;
assert_eq!(text_of(&y), format!("{}{warning}", text_of(&x)), "{args}");
}
assert!(answered > 20, "{answered}");
}
/// Finding 6 (blocking): an edit sees a file created just before it — every
/// edit tool walks first (`rewalk: true`).
#[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("find", json!({"name": "leaf"}));
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.rename_d();
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 not in the skipped set.
#[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 = text_of(&server.rename_d());
assert!(!text.contains(outside.root()), "{text}");
}