diff --git a/TODO-MCP.md b/TODO-MCP.md index 3bc2678..c5f1954 100644 --- a/TODO-MCP.md +++ b/TODO-MCP.md @@ -186,25 +186,25 @@ lane: the LSP's rename inherits the fix. `tests/wire.rs` and `tests/attacks.rs` (new), fixtures, the `mcp-structural-edits` README. Depends on M3 merged. -- [ ] `replace_item`, `insert_item`, `delete_item` with the PLAN §4.3 +- [x] `replace_item`, `insert_item`, `delete_item` with the PLAN §4.3 contracts: bytes outside the span untouched (asserted by the test, not trusted), strict re-parse of the whole file (or no growth in tolerant error count when it did not parse before), one item at the position, the declared name matches unless `rename: true`, `delete_item` refuses over surviving references unless `force` -- [ ] `tests/attacks.rs`, written by the dev, every case asserted +- [x] `tests/attacks.rs`, written by the dev, every case asserted **refused with the tree byte-identical**: a `text` opening a block it does not close; one that closes the enclosing module; one that re-declares a port; a UTF-8 boundary inside the span; an item inside a format fence; a file with an unterminated string; an `insert_item` after `end` — the CLAUDE.md invariant-4 discipline applied to the block's own verifier -- [ ] README `mcp-structural-edits`: the contract as a table, the attack +- [x] README `mcp-structural-edits`: the contract as a table, the attack list, what the tool deliberately does not check (semantic sense of the new text) -- [ ] gates; sizes (`item.rs` is expected to be the largest file in the +- [x] gates; sizes (`item.rs` is expected to be the largest file in the crate; if it passes 600 lines the verifier moves to `item/verify.rs`) -- [ ] QA: re-attack with at least eight new cases (a `text` that is two +- [x] QA: re-attack with at least eight new cases (a `text` that is two items; an empty `text`; a `text` equal to the old bytes — must be a no-op, not a refusal; a macro-bracketed item; a `generate` block target; an item whose leading comment is shared with the previous diff --git a/crates/lucisv_mcp/src/tools/item.rs b/crates/lucisv_mcp/src/tools/item.rs new file mode 100644 index 0000000..d2931e4 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/item.rs @@ -0,0 +1,455 @@ +//! The structural edits — `replace_item`, `insert_item`, `delete_item` — the +//! general token saver: an agent sends one item's text, never the file. +//! +//! Each tool finds its place with `read_item`'s own slicer +//! ([`read_item::select`]), so the bytes it replaces are exactly the bytes +//! `read_item` showed; builds a [`Splice`]; hands it to [`verify::check`] +//! (the rules are there); and writes through `apply::run`, the one write +//! path (dry run, freshness, atomic write). Contract and rules: +//! `docs/features/mcp-structural-edits/README.md`. + +mod lexical; +mod macros; +mod refs; +mod span; +mod star; +mod verify; + +use std::path::PathBuf; +use std::rc::Rc; + +use serde_json::json; +use vlog_formatter::fence; +use vlog_parser::ast::{Item, ItemKind}; +use vlog_parser::span::TextRange; + +use super::edit::DRY_RUN; +use super::read_item::{child_items, select}; +use super::{Answer, Args, Param, Tool, Ty}; +use crate::apply::{self, Change, Plan}; +use crate::project::{Analysis, Project}; +use crate::render; +use span::{ + alone_before, blank_line_at, blank_line_before, line_start, own_lines, past_doubled_blank, + replace_region, SHARED_LINE, +}; +use verify::{Expect, Splice}; + +const FILE: Param = Param { + name: "file", + ty: Ty::Str, + required: true, + description: "The file, relative to a root or absolute inside one.", +}; +const ITEM: Param = Param { + name: "item", + ty: Ty::Str, + required: true, + description: "`read_item`'s selector: `name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).", +}; +const TEXT: Param = Param { + name: "text", + ty: Ty::Str, + required: true, + description: "The item's source text. Surrounding blank space is dropped; line endings follow the file's.", +}; + +pub const REPLACE_ITEM: Tool = Tool { + name: "replace_item", + title: "Replace one item", + description: "Replace one item (read_item's selector) with `text`, verified before anything is written: the file must still parse; `text` must be ONE item of the same kind (a module stays a module) declaring the same names unless `rename: true` (references are then NOT updated; `rename` does that). Bytes outside the item never change. A `text` beginning with a comment replaces the item's own leading comments; one ending in a same-line comment, its trailing one. `text` equal to the item is `unchanged`. `dry_run` returns the diff.", + params: &[ + FILE, + ITEM, + TEXT, + Param { + name: "rename", + ty: Ty::Bool, + required: false, + description: "Allow the text to declare other names than the item did (default false).", + }, + DRY_RUN, + ], + rewalk: false, + handler: replace_item, +}; + +pub const INSERT_ITEM: Tool = Tool { + name: "insert_item", + title: "Insert items", + description: "Insert `text` (one item or more) before or after the item `anchor` names (read_item's selector), or with `anchor: \"end\"` as the last items of the file's last module, package or class (`end@NAME` for that unit), verified before anything is written: the file must still parse and `text` must be complete items the scope may hold. A blank line separates them from neighbouring items. Refused inside a `// lucisv: off` fence. `dry_run` returns the diff.", + params: &[ + FILE, + Param { + name: "anchor", + ty: Ty::Str, + required: true, + description: "An item selector (as `read_item`), `end`, or `end@NAME`.", + }, + Param { + name: "position", + ty: Ty::Enum(&["before", "after"]), + required: false, + description: "Before or after the anchor item (default after); ignored for `end`.", + }, + TEXT, + DRY_RUN, + ], + rewalk: false, + handler: insert_item, +}; + +pub const DELETE_ITEM: Tool = Tool { + name: "delete_item", + title: "Delete one item", + description: "Delete one item (read_item's selector) and its own leading comments (up to a blank line), verified before anything is written. Refused while a name it declares is referenced anywhere in the project — a `.*` that binds it and a spelling inside a macro count — (the first sites are listed) unless `force: true`, and inside a `// lucisv: off` fence. A declaration of several names goes whole. A second identical call is refused: no such item. `dry_run` returns the diff.", + params: &[ + FILE, + ITEM, + Param { + name: "force", + ty: Ty::Bool, + required: false, + description: "Delete even though references remain (default false); they are listed under warnings.", + }, + DRY_RUN, + ], + rewalk: true, + handler: delete_item, +}; + +/// The file a call names: its path, its root-relative name and analysis. +/// A file that does not lex is refused here: no span in it can be trusted. +fn open(project: &mut Project, args: &Args) -> Result<(PathBuf, String, Rc), String> { + let path = project.resolve(args.str("file").unwrap_or(""))?; + let file = project.relative(&path); + let analysis = project.analysis(&path)?; + if analysis.tokens.is_empty() { + return Err(format!( + "`{file}` does not lex (an unterminated string or comment?); fix that first; nothing written." + )); + } + Ok((path, file, analysis)) +} + +/// One item node and where it sits: its sibling list and its index there. +struct Located<'a> { + item: &'a Item, + siblings: &'a [Item], + index: usize, +} + +/// The item node `selector` names. A declaration that is part of a larger +/// item (an ANSI port, a function argument) is refused: these tools edit +/// whole items. +fn target<'a>(analysis: &'a Analysis, selector: &str, file: &str) -> Result, String> { + let (_, span) = + select(analysis, selector).map_err(|why| format!("{why} in `{file}`; nothing written."))?; + locate(&analysis.tree.items, span).ok_or_else(|| { + format!( + "`{selector}` is part of a larger item (a port in a module header, an argument, a generate branch), not an item of its own; edit the enclosing item (`add_port`/`remove_port` for ports); nothing written." + ) + }) +} + +/// The item whose span is exactly `span`, searched through nested scopes. +fn locate(items: &[Item], span: TextRange) -> Option> { + for (index, item) in items.iter().enumerate() { + if item.span == span { + return Some(Located { item, siblings: items, index }); + } + if item.span.start <= span.start && span.end <= item.span.end { + return child_items(&item.kind).into_iter().find_map(|list| locate(list, span)); + } + } + None +} + +/// A refusal from the verifier, said for this file. +fn refused(file: &str) -> impl Fn(String) -> String + '_ { + move |why| format!("{why} (in `{file}`); nothing written.") +} + +/// Whether any byte of `start..end` (an insertion when empty) is fenced. +fn fenced(text: &str, start: u32, end: u32) -> bool { + let regions = fence::protected_regions(text); + fence::is_protected(®ions, start as usize, end as usize) +} + +const FENCED: &str = "lies inside a `// lucisv: off` fence, which no lucisv tool edits"; + +fn replace_item(project: &mut Project, args: &Args) -> Result { + let (path, file, analysis) = open(project, args)?; + let selector = args.str("item").unwrap_or("").trim(); + let located = target(&analysis, selector, &file)?; + let span = located.item.span; + let text = normalise(args.str("text").unwrap_or(""), &analysis.text, false)?; + let dry_run = args.flag("dry_run", false); + let (start, end) = replace_region(&analysis.text, located.item, &text); + // The item as it already is: a no-op, not a refusal (even in a fence). + if text == analysis.slice(start, end) { + return apply::run(project, Plan::default(), dry_run); + } + if fenced(&analysis.text, start, end) { + return Err(format!("`{selector}` {FENCED}; nothing written.")); + } + let class = verify::class_of(&located.item.kind); + let splice = Splice { start, old_end: end, text }; + let outcome = verify::check(&analysis, &splice, Expect::One(class)).map_err(refused(&file))?; + let new_span = outcome.items.first().map_or(span, |(_, span)| *span); + let was = verify::owned_names(&analysis, span); + let now = verify::owned_names(&outcome.analysis, new_span); + let warnings = name_rule(&was, &now, args.flag("rename", false))?; + let lines = outcome.analysis.line_span(new_span.start, new_span.end); + let note = format!("replaced {class}{}", named(&now)); + finish(project, (path, &analysis, outcome.text), note, lines, warnings, dry_run) +} + +/// The text declares the names the item did, unless `rename` allows others +/// — and then the answer warns that no reference followed. +fn name_rule(was: &[String], now: &[String], rename: bool) -> Result, String> { + if was == now { + return Ok(Vec::new()); + } + if !rename { + return Err(format!( + "the text declares {} where the item declared {}; pass `rename: true` to allow it (references are not updated; `rename` does that); nothing written.", + listed(now), + listed(was) + )); + } + Ok(vec![format!( + "{} replaced by {}: references are NOT updated (the `rename` tool renames with references)", + listed(was), + listed(now) + )]) +} + +fn insert_item(project: &mut Project, args: &Args) -> Result { + let (path, file, analysis) = open(project, args)?; + let anchor = args.str("anchor").unwrap_or("").trim(); + let before = args.str("position") == Some("before"); + let text = normalise(args.str("text").unwrap_or(""), &analysis.text, true)?; + let spot = match anchor.strip_prefix("end") { + Some(rest) if rest.is_empty() || rest.starts_with('@') => { + end_spot(&analysis, rest.trim_start_matches('@'), &file)? + } + _ => anchor_spot(&analysis, anchor, before, &file)?, + }; + let block = spot.block(&analysis.text, &text); + let splice = Splice { start: spot.at, old_end: spot.at, text: block }; + // The verifier first, so a text that cannot stand anywhere is refused + // as such; then the place. + let outcome = verify::check(&analysis, &splice, Expect::Some).map_err(refused(&file))?; + if fenced(&analysis.text, spot.at, spot.at) { + return Err(format!("the insertion point {FENCED}; nothing written.")); + } + let (first, last) = match (outcome.items.first(), outcome.items.last()) { + (Some((_, first)), Some((_, last))) => (*first, *last), + _ => return Err(format!("the text holds no item (in `{file}`); nothing written.")), + }; + let lines = outcome.analysis.line_span(first.start, last.end); + let classes: Vec<&str> = outcome.items.iter().map(|(class, _)| *class).collect(); + let names: Vec = outcome + .items + .iter() + .flat_map(|(_, span)| verify::owned_names(&outcome.analysis, *span)) + .collect(); + let note = format!("inserted {}{}", classes.join(", "), named(&names)); + let dry_run = args.flag("dry_run", false); + finish(project, (path, &analysis, outcome.text), note, lines, Vec::new(), dry_run) +} + +fn delete_item(project: &mut Project, args: &Args) -> Result { + let (path, file, analysis) = open(project, args)?; + let selector = args.str("item").unwrap_or("").trim(); + let located = target(&analysis, selector, &file)?; + let (start, end) = own_lines(&analysis.text, located.item) + .map_err(|why| format!("`{selector}` {why}; nothing written."))?; + let end = past_doubled_blank(&analysis.text, start, end); + if fenced(&analysis.text, start, end) || fence_comment(located.item) { + return Err(format!("`{selector}` {FENCED}; nothing written.")); + } + let removed = TextRange::new(start, end); + let force = args.flag("force", false); + let place = refs::Place { item: located.item.span, removed, scope: located.siblings }; + let warnings = refs::check(project, &path, &analysis, &place, force)?; + let class = verify::class_of(&located.item.kind); + let splice = Splice { start, old_end: end, text: String::new() }; + let outcome = verify::check(&analysis, &splice, Expect::Nothing).map_err(refused(&file))?; + let names = verify::owned_names(&analysis, located.item.span); + let lines = analysis.line_span(start, end); + let note = + format!("deleted {class}{} (old lines {})", named(&names), render::lines(lines.0, lines.1)); + let dry_run = args.flag("dry_run", false); + let plan = plan(path, &analysis, outcome.text, note, warnings); + apply::run(project, plan, dry_run) +} + +/// Whether the item's own leading comments hold a fence line: deleting one +/// would move a fence's edge. +fn fence_comment(item: &Item) -> bool { + item.meta.leading.iter().any(|comment| fence::fence_of(&comment.text).is_some()) +} + +/// The one-file plan: the analysed text before, the verified text after. +fn plan( + path: PathBuf, + analysis: &Analysis, + after: String, + note: String, + warnings: Vec, +) -> Plan { + let change = Change { path, before: analysis.text.clone(), after, created: false }; + Plan { changes: vec![change], note: Some(note), warnings, ..Plan::default() } +} + +/// Write (or diff) a replace or insert, its note carrying the new item's +/// lines and the hint; the lines are in `structuredContent.item` too. +fn finish( + project: &Project, + (path, analysis, after): (PathBuf, &Analysis, String), + note: String, + (first, last): (u32, u32), + warnings: Vec, + dry_run: bool, +) -> Result { + let lines = render::lines(first, last); + let note = format!( + "{note} (lines {lines})\nhint: run `format` with `lines: \"{lines}\"` to reflow; `diagnostics` to check" + ); + let mut answer = apply::run(project, plan(path, analysis, after, note, warnings), dry_run)?; + answer.structured["item"] = json!({ "lines": [first, last] }); + Ok(answer) +} + +/// `` `a`, `b` `` for a list of names; `nothing` when empty. +fn listed(names: &[String]) -> String { + if names.is_empty() { + return "nothing".to_string(); + } + names.iter().map(|name| format!("`{name}`")).collect::>().join(", ") +} + +/// ` `a`, `b`` after a kind word, or nothing. +fn named(names: &[String]) -> String { + if names.is_empty() { + String::new() + } else { + format!(" {}", listed(names)) + } +} + +/// `text` made ready to splice: surrounding blank space dropped (for an +/// insertion, the first line's indentation is kept), line endings made the +/// file's. Empty text is refused: deleting is `delete_item`'s. +fn normalise(text: &str, file_text: &str, keep_indent: bool) -> Result { + let trimmed = text.trim_end_matches(|c: char| c.is_ascii_whitespace()); + let trimmed = if keep_indent { + let first_code = trimmed.find(|c: char| !c.is_ascii_whitespace()).unwrap_or(0); + &trimmed[line_start(trimmed, first_code as u32) as usize..] + } else { + trimmed.trim_start_matches(|c: char| c.is_ascii_whitespace()) + }; + if trimmed.is_empty() { + return Err("`text` is empty; `delete_item` removes an item; nothing written.".into()); + } + let lf = trimmed.replace("\r\n", "\n"); + Ok(if line_ending(file_text) == "\r\n" { lf.replace('\n', "\r\n") } else { lf }) +} + +/// The file's line ending, judged by its first line. +fn line_ending(text: &str) -> &'static str { + match text.find('\n') { + Some(at) if text[..at].ends_with('\r') => "\r\n", + _ => "\n", + } +} + +/// Where an insertion lands: a line start, and whether an item neighbours +/// it above and below (the blank-line policy). +struct Spot { + at: u32, + above: bool, + below: bool, +} + +impl Spot { + /// `text` framed for this spot: a line break when the file's last line + /// has none, a blank line on each side that has a neighbouring item + /// unless one is already there, and the text's own line ending. + fn block(&self, file_text: &str, text: &str) -> String { + let nl = line_ending(file_text); + let mut block = String::new(); + if self.at as usize == file_text.len() + && !file_text.is_empty() + && !file_text.ends_with('\n') + { + block.push_str(nl); + } + if self.above && !blank_line_before(file_text, self.at) { + block.push_str(nl); + } + block.push_str(text); + block.push_str(nl); + if self.below && !blank_line_at(file_text, self.at) { + block.push_str(nl); + } + block + } +} + +/// Before the anchor item (and its leading comments) or after it (and its +/// trailing comment). +fn anchor_spot( + analysis: &Analysis, + selector: &str, + before: bool, + file: &str, +) -> Result { + let located = target(analysis, selector, file)?; + let (first, last) = own_lines(&analysis.text, located.item) + .map_err(|why| format!("`{selector}` {why}; nothing written."))?; + Ok(if before { + Spot { at: first, above: located.index > 0, below: true } + } else { + let below = located.index + 1 < located.siblings.len(); + Spot { at: last, above: true, below } + }) +} + +/// The line of a unit's end keyword: `unit` is empty for the file's last +/// unit, else a selector naming a module, interface, program, package or +/// class. +fn end_spot(analysis: &Analysis, unit: &str, file: &str) -> Result { + let is_unit = |item: &Item| { + matches!(item.kind, ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_)) + }; + let item = if unit.is_empty() { + let last = analysis.tree.items.iter().rev().find(|item| is_unit(item)); + last.ok_or_else(|| { + format!("`{file}` declares no module, package or class; nothing written.") + })? + } else { + let located = target(analysis, unit, file)?; + if !is_unit(located.item) { + return Err(format!("`{unit}` is not a module, package or class; nothing written.")); + } + located.item + }; + let keyword = analysis + .tokens + .iter() + .filter(|t| item.span.start <= t.span.start && t.span.end <= item.span.end) + .rfind(|t| END_WORDS.contains(&t.text.as_str())) + .ok_or_else(|| format!("the unit has no end keyword in `{file}`; nothing written."))?; + if !alone_before(&analysis.text, keyword.span.start) { + return Err(format!("`{}` {SHARED_LINE}; nothing written.", keyword.text)); + } + let children = child_items(&item.kind); + let above = children.iter().any(|list| !list.is_empty()); + Ok(Spot { at: line_start(&analysis.text, keyword.span.start), above, below: false }) +} + +/// The keywords that close a unit `end` may name. +const END_WORDS: &[&str] = &["endmodule", "endinterface", "endprogram", "endpackage", "endclass"]; diff --git a/crates/lucisv_mcp/src/tools/item/lexical.rs b/crates/lucisv_mcp/src/tools/item/lexical.rs new file mode 100644 index 0000000..929e314 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/item/lexical.rs @@ -0,0 +1,175 @@ +//! The verifier's lexical rules — what a splice may do to the token stream +//! and its comments, before any parse is asked: +//! +//! - **1a.** `text` lexes on its own. A text ending in an open `/*`, string +//! or macro call lexes inside the file only by running into the code after +//! it — a `*/` further down closes it and the fence between is swallowed. +//! - **1b.** Outside the region nothing lexes differently: every token and +//! every comment before the region, and every one after it (shifted by +//! the length change), is the old file's — same kind, text and span. No +//! token or comment starts inside the region and ends past it, and no +//! comment the new bytes write is attached (`Token.leading`/`trailing`) +//! to a token outside them: a comment the text leaves on a line of its +//! own at its end would lead the next item, not this one. +//! - **7.** The region holds the same `lucisv: off`/`on` fence markers +//! before and after: a text neither opens nor closes a fence. + +use vlog_formatter::fence; +use vlog_parser::token::{Comment, Token, TokenKind}; + +use crate::project::Analysis; + +/// A splice's region in both files: `start..old_end` in the old one, +/// `start..new_end` in the new one. +#[derive(Clone, Copy)] +pub struct Region { + pub start: u32, + pub old_end: u32, + pub new_end: u32, +} + +/// One lexical element of a file: a token or a comment. +#[derive(Clone, Copy, PartialEq, Eq)] +struct Element<'a> { + kind: Option, + text: &'a str, + start: u32, + end: u32, +} + +impl Element<'_> { + fn describe(&self, analysis: &Analysis) -> String { + let line = analysis.lines.line_col(self.start).0; + let text: String = self.text.chars().take(24).collect(); + let what = if self.kind.is_some() { "token" } else { "comment" }; + format!("the {what} `{text}` at line {line}") + } +} + +fn comment(c: &Comment) -> Element<'_> { + Element { kind: None, text: &c.text, start: c.span.start, end: c.span.end } +} + +/// Every token and comment of a stream, in source order. +fn elements(tokens: &[Token]) -> Vec> { + let mut out = Vec::with_capacity(tokens.len() + tokens.len() / 4); + for token in tokens { + out.extend(token.leading.iter().map(comment)); + let (start, end) = (token.span.start, token.span.end); + out.push(Element { kind: Some(token.kind), text: &token.text, start, end }); + out.extend(token.trailing.iter().map(comment)); + } + out +} + +/// The elements before `start` and after `end` (shifted by `shift`); an +/// element that starts inside and ends past `end` is returned as `Err`. +fn sides<'a>( + all: &[Element<'a>], + start: u32, + end: u32, + shift: i64, +) -> Result<(Vec>, Vec>), Element<'a>> { + let moved = |at: u32| u32::try_from(i64::from(at) + shift).unwrap_or(u32::MAX); + let (mut before, mut after) = (Vec::new(), Vec::new()); + for element in all { + if element.start < start { + before.push(*element); + } else if element.start >= end { + after.push(Element { + start: moved(element.start), + end: moved(element.end), + ..*element + }); + } else if element.end > end { + return Err(*element); + } + } + Ok((before, after)) +} + +/// Rule 1a: `text` lexes on its own. +pub fn lexes_alone(text: &str) -> Result<(), String> { + vlog_parser::tokenize(text).map(|_| ()).map_err(|e| { + format!( + "the text does not lex on its own (rule 1a: {}); a comment, string or macro call it leaves open would run into the code after it", + e.message + ) + }) +} + +/// Rule 1b: the tokens and comments outside `start..old_end` (old) and +/// `start..new_end` (new) are the same, shifted; nothing straddles the new +/// region's end; no comment inside it is attached to a token outside it. +pub fn same_outside(old: &Analysis, new: &Analysis, region: Region) -> Result<(), String> { + let Region { start, old_end, new_end } = region; + let shift = i64::from(new_end) - i64::from(old_end); + let (was, now) = (elements(&old.tokens), elements(&new.tokens)); + let changed = |element: &Element| { + format!("the edit would change how the code outside the item lexes (rule 1b: {} would not survive as it is)", element.describe(old)) + }; + let (was_before, was_after) = sides(&was, start, old_end, shift).map_err(|e| changed(&e))?; + let (now_before, now_after) = sides(&now, start, new_end, 0).map_err(|element| { + format!( + "{} would run past the text's end into the code after it (rule 1b)", + element.describe(new) + ) + })?; + for (was, now) in [(&was_before, &now_before), (&was_after, &now_after)] { + if was != now { + let at = was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len()); + let element = was.get(at).or(was.last()).or(now.get(at)); + return Err(element.map_or_else( + || { + "the edit would change how the code outside the item lexes (rule 1b)" + .to_string() + }, + changed, + )); + } + } + attached_inside(new, start, new_end) +} + +/// Rule 1b's last clause: a comment the new bytes hold belongs to a token +/// they hold. +fn attached_inside(new: &Analysis, start: u32, end: u32) -> Result<(), String> { + let inside = |at: u32| start <= at && at < end; + for token in new.tokens.iter().filter(|token| !inside(token.span.start)) { + let stray = token.leading.iter().chain(&token.trailing).find(|c| inside(c.span.start)); + if let Some(comment) = stray { + let line = new.lines.line_col(comment.span.start).0; + return Err(format!( + "the comment at line {line} of the text would belong to the code after it, not to the item (rule 1b); put the comment before the item or on its last line" + )); + } + } + Ok(()) +} + +/// Rule 7: the fence markers inside the region are the same before and +/// after. +pub fn same_fences(old: &Analysis, new: &Analysis, region: Region) -> Result<(), String> { + let Region { start, old_end, new_end } = region; + let (was, now) = (markers(&old.tokens, start, old_end), markers(&new.tokens, start, new_end)); + if was == now { + return Ok(()); + } + let (verb, longer, shorter) = + if now.len() >= was.len() { ("add", &now, &was) } else { ("remove", &was, &now) }; + let at = longer.iter().zip(shorter.iter()).position(|(a, b)| a != b).unwrap_or(shorter.len()); + let marker = longer.get(at).copied().unwrap_or("// lucisv: off"); + Err(format!( + "the edit would {verb} the fence marker `{marker}` (rule 7); `lucisv: off`/`on` fences are written by hand, not through these tools" + )) +} + +/// The fence-marker comments starting in `start..end`, in order. +fn markers(tokens: &[Token], start: u32, end: u32) -> Vec<&str> { + elements(tokens) + .into_iter() + .filter(|e| e.kind.is_none() && start <= e.start && e.start < end) + .filter(|e| fence::fence_of(e.text).is_some()) + .map(|e| e.text.trim()) + .collect() +} diff --git a/crates/lucisv_mcp/src/tools/item/macros.rs b/crates/lucisv_mcp/src/tools/item/macros.rs new file mode 100644 index 0000000..8b96da8 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/item/macros.rs @@ -0,0 +1,108 @@ +//! `delete_item`'s macro rule: a name spelled inside a macro call's +//! arguments (`` `ASSERT_KNOWN(k, sig) ``) or a `` `define`` body is a use +//! no lucisv engine resolves — the lexer keeps a macro call as one token and +//! a `` `define`` as one directive. Each such spelling the engine and the +//! file's own tables did not account for is a *possible* use. + +use vlog_parser::defines::{collect_defines, DefineKind}; +use vlog_parser::span::TextRange; +use vlog_parser::token::{Token, TokenKind}; +use vlog_parser::tokenize; + +use crate::tools::source::word_in; + +/// Where `name` is spelled inside a macro call's arguments or a +/// `` `define`` body in `tokens`, outside `skip`: the byte offset of each +/// spelling (a `` `define``'s own start for a body). +pub fn macro_spellings(tokens: &[Token], name: &str, skip: TextRange) -> Vec { + let outside = |span: TextRange| span.end <= skip.start || span.start >= skip.end; + let mut out = Vec::new(); + for token in tokens.iter().filter(|token| outside(token.span)) { + match token.kind { + TokenKind::Ident if token.text.starts_with('`') => { + call_arguments(&token.text, token.span.start, name, &mut out); + } + TokenKind::Directive if defines_with_body_spelling(token, name) => { + out.push(token.span.start); + } + _ => {} + } + } + out +} + +/// The spellings of `name` in one macro call's arguments (`text` starts at +/// byte `at`), nested calls included. Arguments that do not lex are +/// searched as bytes. +fn call_arguments(text: &str, at: u32, name: &str, out: &mut Vec) { + let Some(open) = text.find('(') else { + return; + }; + let args = &text[open..]; + let base = at + open as u32; + match tokenize(args) { + Ok(tokens) => { + for token in tokens.iter().filter(|t| t.kind == TokenKind::Ident) { + let start = base + token.span.start; + if token.text == name { + out.push(start); + } else if token.text.starts_with('`') { + call_arguments(&token.text, start, name, out); + } + } + } + Err(_) => out.extend(word_in(args, name).map(|offset| base + offset as u32)), + } +} + +/// Whether a `` `define`` directive's body spells `name` as an identifier +/// that is not one of its own formal arguments. +fn defines_with_body_spelling(token: &Token, name: &str) -> bool { + let table = collect_defines(std::slice::from_ref(token)); + table.entries().iter().any(|define| { + let formal = define + .params + .iter() + .flatten() + .any(|param| param.split('=').next().is_some_and(|formal| formal.trim() == name)); + define.kind == DefineKind::Define && !formal && body_spells(&define.body, name) + }) +} + +/// Whether a macro body spells `name` as an identifier, nested calls +/// included (searched as bytes when the body does not lex on its own — +/// token pasting, escaped quotes). +fn body_spells(body: &str, name: &str) -> bool { + let Ok(tokens) = tokenize(body) else { + return word_in(body, name).is_some(); + }; + let mut found = Vec::new(); + for token in tokens.iter().filter(|t| t.kind == TokenKind::Ident) { + if token.text == name { + return true; + } + if token.text.starts_with('`') { + call_arguments(&token.text, 0, name, &mut found); + } + } + !found.is_empty() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spellings(src: &str, name: &str) -> Vec { + let tokens = tokenize(src).unwrap(); + macro_spellings(&tokens, name, TextRange::new(0, 0)) + } + + #[test] + fn a_name_in_a_macro_call_or_a_define_body_is_found() { + let src = "`define B(x) x + sig\nassign o = `ID(`W(sig));\n"; + assert_eq!(spellings(src, "sig"), [0, src.find("sig)").unwrap() as u32]); + assert!(spellings(src, "x").is_empty(), "a formal argument is not a use"); + assert!(spellings("assign o = `ID(a) + sig;\n", "sig").is_empty()); + assert!(spellings("`define S \"sig\"\n", "sig").is_empty(), "a string is not a use"); + } +} diff --git a/crates/lucisv_mcp/src/tools/item/refs.rs b/crates/lucisv_mcp/src/tools/item/refs.rs new file mode 100644 index 0000000..3a0f7f9 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/item/refs.rs @@ -0,0 +1,272 @@ +//! `delete_item`'s reference rule: an item is not deleted while a name it +//! owns (`verify::owned`) is still used anywhere in the project, unless the +//! agent says `force`. +//! +//! Uses are `vlog_refactor::find_references` over the whole indexed set, +//! read from disk now (`WholeSet`, M2's ruling) — the census `references` +//! answers with — plus what that engine cannot see: +//! +//! - a `.*` in the item's scope that binds the name ([`star`]) — it binds +//! without spelling it, so this runs for every name; +//! - a spelling inside a macro call's arguments or a `` `define`` body +//! ([`macros`]), a *possible* use; +//! - in the item's own file, a use the file's tables resolve to the +//! declaration or to nothing ([`local_uses`]). +//! +//! Apart from `.*`, a name no file spells outside the removed lines has no +//! use to find, so the rest runs only for names some other text spells (a +//! whole-word byte search): an identifier, escaped or not, is always +//! written out where it is used. + +use std::path::{Path, PathBuf}; + +use vlog_parser::ast::Item; +use vlog_parser::span::TextRange; +use vlog_parser::LineIndex; +use vlog_semantic::Symbol; + +use super::macros::macro_spellings; +use super::star::star_uses; +use super::verify; +use crate::project::{Analysis, Project}; +use crate::tools::source::{word_in, WholeSet}; + +/// How many surviving uses a refusal lists. +const SHOWN: usize = 5; + +/// The uses and doubts found, the first few spelled out. +#[derive(Default)] +struct Census { + shown: Vec, + total: usize, +} + +impl Census { + fn add(&mut self, line: impl FnOnce() -> String) { + if self.shown.len() < SHOWN { + self.shown.push(line()); + } + self.total += 1; + } + + fn render(&self) -> String { + let more = self.total - self.shown.len(); + let tail = if more > 0 { format!("; and {more} more") } else { String::new() }; + format!("{}{tail}", self.shown.join("; ")) + } +} + +/// Where a deletion sits: the item's span, the bytes the deletion takes +/// (its comments included), and the item list it is taken from. +pub struct Place<'a> { + pub item: TextRange, + pub removed: TextRange, + pub scope: &'a [Item], +} + +/// The warnings a deletion carries, or the refusal. +pub fn check( + project: &Project, + path: &Path, + analysis: &Analysis, + place: &Place, + force: bool, +) -> Result, String> { + let symbols = verify::owned(analysis, place.item); + if symbols.is_empty() { + return Ok(Vec::new()); + } + let set = WholeSet::read(project, Some(path)); + let own = set.files.iter().find(|(held, _)| held == path).map(|(_, text)| text.as_str()); + if own != Some(analysis.text.as_str()) { + let file = project.relative(path); + return Err(format!("`{file}` changed on disk while it was read; nothing written.")); + } + let names: Vec = symbols.iter().map(|symbol| symbol.name.clone()).collect(); + let mut census = Census::default(); + if let Some((skipped, why, name)) = set.mentioning(&names) { + let file = project.relative(skipped); + census.add(|| format!("{file} (skipped: {why}) may reference `{name}`")); + } + let scan = Scan { project, set: &set, path, analysis, place }; + for symbol in symbols { + scan.uses_of(symbol, &mut census); + } + let mut warnings: Vec = set.warning(project).into_iter().collect(); + if census.total == 0 { + return Ok(warnings); + } + if !force { + return Err(format!( + "still referenced: {}; nothing written (`force: true` deletes anyway).", + census.render() + )); + } + warnings.push(format!("deleted with references left: {}", census.render())); + Ok(warnings) +} + +/// What one deletion's reference scan reads. +struct Scan<'a> { + project: &'a Project, + set: &'a WholeSet, + path: &'a Path, + analysis: &'a Analysis, + place: &'a Place<'a>, +} + +/// The spans some rule already counted (or knows to be another name's), per +/// file: a macro spelling at one of them is not counted twice. +type Accounted = Vec<(PathBuf, TextRange)>; + +impl Scan<'_> { + /// Count the uses of one owned declaration that the deletion would leave. + fn uses_of(&self, symbol: &Symbol, census: &mut Census) { + let (name, removed) = (&symbol.name, self.place.removed); + if !within(symbol.name_span, removed) { + let line = self.analysis.lines.line_col(symbol.name_span.start).0; + census.add(|| { + format!("`{name}` is also declared on line {line}, which the deletion would leave incomplete") + }); + return; + } + self.stars(name, census); + if !mentioned(self.set, self.path, removed, name) { + return; + } + let accounted = self.references(symbol, census); + self.macros(name, &accounted, census); + } + + /// The engine's and the file's own uses, counted; what they account for. + fn references(&self, symbol: &Symbol, census: &mut Census) -> Accounted { + let (name, removed) = (&symbol.name, self.place.removed); + let mut uses = local_uses(self.analysis, symbol, removed); + let mut accounted: Accounted = self + .analysis + .semantics + .references() + .iter() + .filter(|use_| use_.name == *name) + .map(|use_| (self.path.to_path_buf(), use_.name_span)) + .collect(); + let found = vlog_refactor::find_references( + &self.set.files, + self.path, + symbol.name_span.start, + false, + ); + match found { + Ok(hits) => { + for (file, span) in hits { + if file != self.path { + census.add(|| site(self.project, self.set, &file, span, name)); + } else if !within(span, removed) && !uses.contains(&span) { + uses.push(span); + } + accounted.push((file, span)); + } + } + Err(why) => census.add(|| { + format!("the uses of `{name}` cannot all be listed ({})", why.trim_end_matches('.')) + }), + } + uses.sort_by_key(|span| span.start); + for span in uses { + census.add(|| site(self.project, self.set, self.path, span, name)); + } + accounted + } + + /// Rule `.*`: the implicit connections in the item's scope that bind + /// (or may bind) `name`. + fn stars(&self, name: &str, census: &mut Census) { + let index = self.project.index(); + for star in star_uses(index, self.place.scope, self.place.removed, name) { + let at = position(self.project, self.set, self.path, star.at); + census.add(|| match star.certain { + true => format!("bound by `.*` at {at} `{name}` (module `{}`)", star.module), + false => format!( + "possible use (`.*`) at {at} `{name}` (module `{}` does not resolve to one declaration)", + star.module + ), + }); + } + } + + /// Rule macros: every spelling of `name` inside a macro call or a + /// `` `define`` body, in any file of the set, that nothing accounted for. + fn macros(&self, name: &str, accounted: &Accounted, census: &mut Census) { + for (file, text) in &self.set.files { + if word_in(text, name).is_none() { + continue; + } + let (own, lexed); + let tokens = if file == self.path { + own = &self.analysis.tokens; + own + } else if let Ok(tokens) = vlog_parser::tokenize(text) { + lexed = tokens; + &lexed + } else { + let at = self.project.relative(file); + census.add(|| format!("possible use in {at} (it does not lex) `{name}`")); + continue; + }; + let skip = if file == self.path { self.place.removed } else { TextRange::new(0, 0) }; + let lines = LineIndex::new(text); + for offset in macro_spellings(tokens, name, skip) { + if !accounted.iter().any(|(held, span)| held == file && span.start == offset) { + let at = + format!("{}:{}", self.project.relative(file), lines.line_col(offset).0); + census.add(|| format!("possible use (macro) at {at} `{name}`")); + } + } + } + } +} + +fn within(inner: TextRange, outer: TextRange) -> bool { + outer.start <= inner.start && inner.end <= outer.end +} + +/// The uses of `symbol` the file's own tables hold outside the removed +/// bytes: resolved to it, or to nothing at all. The second kind is what the +/// cross-file engine does not follow (a hierarchical path into a generate +/// loop, `gen_l[0].z`); counting it may refuse a deletion that was safe, +/// never allow one that was not — `force` is the way past. +fn local_uses(analysis: &Analysis, symbol: &Symbol, removed: TextRange) -> Vec { + let semantics = &analysis.semantics; + let id = semantics.symbol_at(symbol.name_span.start); + semantics + .references() + .iter() + .filter(|use_| use_.name == symbol.name && !within(use_.name_span, removed)) + .filter(|use_| use_.resolved().is_none() || use_.resolved() == id) + .map(|use_| use_.name_span) + .collect() +} + +/// Whether any text of the set, the removed bytes aside, spells `name`. +fn mentioned(set: &WholeSet, path: &Path, removed: TextRange, name: &str) -> bool { + set.files.iter().any(|(held, text)| { + if held != path { + return word_in(text, name).is_some(); + } + let head = text.get(..removed.start as usize).unwrap_or(""); + let tail = text.get(removed.end as usize..).unwrap_or(""); + word_in(head, name).is_some() || word_in(tail, name).is_some() + }) +} + +/// `file:line:col `name`` for one use. +fn site(project: &Project, set: &WholeSet, file: &Path, span: TextRange, name: &str) -> String { + format!("{} `{name}`", position(project, set, file, span)) +} + +/// `file:line:col` of a span's start. +fn position(project: &Project, set: &WholeSet, file: &Path, span: TextRange) -> String { + let text = set.files.iter().find(|(held, _)| held == file).map_or("", |(_, t)| t.as_str()); + let (line, col) = LineIndex::new(text).line_col(span.start); + format!("{}:{line}:{col}", project.relative(file)) +} diff --git a/crates/lucisv_mcp/src/tools/item/span.rs b/crates/lucisv_mcp/src/tools/item/span.rs new file mode 100644 index 0000000..db9e934 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/item/span.rs @@ -0,0 +1,157 @@ +//! Which bytes an item owns: the lines `insert_item` and `delete_item` work +//! on, and the span `replace_item` replaces when its text brings comments. +//! +//! Two rules, stated once here and in the README: +//! +//! - **Own comments.** An item's leading comments (`Meta::leading`) are its +//! own back to the first gap holding a blank line: a banner a blank line +//! separates from the item belongs to what follows it, not to this item. +//! - **Own lines.** An item owns its lines unless another item's *code* +//! sits on its first or last line; a comment on the same line goes with +//! the item (`/* lead */ logic a;` owns its line). + +use vlog_parser::ast::Item; +use vlog_parser::tokenize; + +/// Why an item that does not own its lines is refused by insert and delete. +pub const SHARED_LINE: &str = "shares a line with other code; insert_item and delete_item work on items on lines of their own (run `format` first)"; + +/// The start of the item's own leading comments (the item's own start when +/// it has none): walking back over `Meta::leading`, up to the first gap +/// that holds a blank line. +pub fn own_comments_start(text: &str, item: &Item) -> u32 { + let mut first = item.span.start; + for comment in item.meta.leading.iter().rev() { + let gap = text.get(comment.span.end as usize..first as usize).unwrap_or("x"); + if !gap.trim().is_empty() || gap.matches('\n').count() > 1 { + break; + } + first = comment.span.start; + } + first +} + +/// The lines an item owns: from the line of its first own leading comment +/// to the end of its own last line (its trailing comment included). An item +/// whose first or last line holds other code owns no lines. +pub fn own_lines(text: &str, item: &Item) -> Result<(u32, u32), String> { + let first = own_comments_start(text, item); + if !alone_before(text, first) { + return Err(SHARED_LINE.to_string()); + } + let trailing = item.meta.trailing.as_ref().map_or(0, |comment| comment.span.end); + let last = alone_after(text, item.span.end.max(trailing)).ok_or(SHARED_LINE)?; + Ok((line_start(text, first), last)) +} + +/// The bytes `replace_item` replaces with `text`: the item's span, widened +/// back over its own leading comments when `text` begins with a comment, +/// and forward over its trailing comment when `text` ends with one on its +/// last line — so the same call twice finds its own text and is +/// `unchanged`. A text that does not lex is left to the verifier. +pub fn replace_region(file_text: &str, item: &Item, text: &str) -> (u32, u32) { + let (mut start, mut end) = (item.span.start, item.span.end); + let Ok(tokens) = tokenize(text) else { + return (start, end); + }; + let Some((eof, code)) = tokens.split_last() else { + return (start, end); + }; + let leads = code.first().is_some_and(|token| !token.leading.is_empty()); + let trails = + eof.leading.is_empty() && code.last().is_some_and(|token| token.trailing.is_some()); + if leads { + start = own_comments_start(file_text, item); + } + if let Some(comment) = item.meta.trailing.as_ref().filter(|_| trails) { + end = end.max(comment.span.end); + } + (start, end) +} + +/// `end`, moved past a blank line when the removal `start..end` would leave +/// two blank lines in a row. +pub fn past_doubled_blank(text: &str, start: u32, end: u32) -> u32 { + if blank_line_before(text, start) && blank_line_at(text, end) { + return alone_after(text, end).unwrap_or(end); + } + end +} + +/// The first byte of the line holding `at`. +pub fn line_start(text: &str, at: u32) -> u32 { + text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |nl| nl as u32 + 1) +} + +/// Whether only spaces and tabs stand between `at` and its line's start. +pub fn alone_before(text: &str, at: u32) -> bool { + let head = text.get(line_start(text, at) as usize..at as usize).unwrap_or("x"); + head.bytes().all(|b| b == b' ' || b == b'\t') +} + +/// The end of the line holding `at`, past its line ending (or the file's +/// end), when only blank space follows `at` on it. +fn alone_after(text: &str, at: u32) -> Option { + let rest = text.get(at as usize..)?; + let (line, next) = match rest.find('\n') { + Some(nl) => (&rest[..nl], at + nl as u32 + 1), + None => (rest, text.len() as u32), + }; + line.trim().is_empty().then_some(next) +} + +/// Whether the line starting at `at` is blank (and exists). +pub fn blank_line_at(text: &str, at: u32) -> bool { + (at as usize) < text.len() && alone_after(text, at).is_some() +} + +/// Whether the line ending just before `at` (a line start) is blank. +pub fn blank_line_before(text: &str, at: u32) -> bool { + at > 0 && blank_line_at(text, line_start(text, at - 1)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project::Analysis; + + /// The first item of the first module of `src`. + fn first_item(analysis: &Analysis) -> &Item { + match &analysis.tree.items[0].kind { + vlog_parser::ast::ItemKind::Module(module) => &module.items[0], + _ => panic!("not a module"), + } + } + + #[test] + fn a_blank_line_ends_an_items_own_comments() { + let src = "module m;\n // banner\n\n // own\n logic a;\nendmodule\n"; + let analysis = Analysis::of(src.to_string()); + let item = first_item(&analysis); + let (start, end) = own_lines(src, item).unwrap(); + assert_eq!(&src[start as usize..end as usize], " // own\n logic a;\n"); + } + + #[test] + fn a_comment_before_the_item_on_its_line_goes_with_it() { + let src = "module m;\n /* lead */ logic a;\nendmodule\n"; + let analysis = Analysis::of(src.to_string()); + let (start, end) = own_lines(src, first_item(&analysis)).unwrap(); + assert_eq!(&src[start as usize..end as usize], " /* lead */ logic a;\n"); + let shared = "module m; /* c */ logic a;\nendmodule\n"; + let analysis = Analysis::of(shared.to_string()); + assert!(own_lines(shared, first_item(&analysis)).is_err()); + } + + #[test] + fn a_text_with_comments_widens_the_replaced_span_over_the_items_own() { + let src = "module m;\n // doc\n logic a; // t\nendmodule\n"; + let analysis = Analysis::of(src.to_string()); + let item = first_item(&analysis); + let slice = |(s, e): (u32, u32)| &src[s as usize..e as usize]; + assert_eq!(slice(replace_region(src, item, "logic b;")), "logic a;"); + assert_eq!(slice(replace_region(src, item, "// x\nlogic b;")), "// doc\n logic a;"); + assert_eq!(slice(replace_region(src, item, "logic b; // y")), "logic a; // t"); + assert_eq!(slice(replace_region(src, item, "logic b;\n// own line")), "logic a;"); + } +} diff --git a/crates/lucisv_mcp/src/tools/item/star.rs b/crates/lucisv_mcp/src/tools/item/star.rs new file mode 100644 index 0000000..a092015 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/item/star.rs @@ -0,0 +1,96 @@ +//! `delete_item`'s implicit-connection rule: a `.*` binds a signal without +//! spelling it, so `find_references` (which returns only spans that spell +//! the name) never lists it. For each deleted name, every `.*` +//! instantiation in the item's own scope — its sibling items and the +//! generate blocks among them, the removed bytes aside — counts as a use +//! when its module (one declaration in the project index) has a port of +//! that name, and as a *possible* use when its module does not resolve to +//! exactly one declaration. + +use vlog_parser::ast::{Connections, Instantiation, Item, ItemKind}; +use vlog_parser::span::TextRange; +use vlog_semantic::{SymbolKind, WorkspaceIndex}; + +use crate::tools::read_item::child_items; + +/// One `.*` a deleted name meets: where the `.*` is written, and whether +/// the binding is certain (the module has the port) or only possible. +pub struct StarUse { + pub at: TextRange, + pub module: String, + pub certain: bool, +} + +/// The `.*` connections in `scope` that bind (or may bind) `name`. +pub fn star_uses( + index: &WorkspaceIndex, + scope: &[Item], + removed: TextRange, + name: &str, +) -> Vec { + let mut stars = Vec::new(); + collect(scope, removed, &mut stars); + stars + .into_iter() + .filter_map(|(instantiation, at)| { + let module = instantiation.module.clone(); + match binds(index, &module, name) { + Some(false) => None, + Some(true) => Some(StarUse { at, module, certain: true }), + None => Some(StarUse { at, module, certain: false }), + } + }) + .collect() +} + +/// Every instantiation with a `.*` in `items` and the generate constructs +/// among them, outside `removed`, with the `.*`'s span. +fn collect<'a>( + items: &'a [Item], + removed: TextRange, + out: &mut Vec<(&'a Instantiation, TextRange)>, +) { + for item in items { + let inside = removed.start <= item.span.start && item.span.end <= removed.end; + if inside { + continue; + } + match &item.kind { + ItemKind::Instantiation(instantiation) => { + out.extend(wildcard(instantiation).map(|at| (instantiation, at))); + } + ItemKind::GenerateRegion { .. } + | ItemKind::GenIf(_) + | ItemKind::GenFor(_) + | ItemKind::GenCase(_) + | ItemKind::GenBlock(_) => { + for children in child_items(&item.kind) { + collect(children, removed, out); + } + } + _ => {} + } + } +} + +/// The span of the first `.*` among an instantiation's connections. +fn wildcard(instantiation: &Instantiation) -> Option { + instantiation.instances.iter().find_map(|instance| match &instance.conns { + Connections::Named(conns) => { + conns.iter().filter_map(|conn| conn.ok()).find(|conn| conn.name == "*").map(|c| c.span) + } + Connections::Ordered(_) => None, + }) +} + +/// Whether `module` has a port `name`: `None` when the module does not +/// resolve to exactly one indexed module or interface. +fn binds(index: &WorkspaceIndex, module: &str, name: &str) -> Option { + let instantiable = + |kind: SymbolKind| matches!(kind, SymbolKind::Module | SymbolKind::Interface); + let declarations = index.units(module).iter().filter(|def| instantiable(def.kind)).count(); + if declarations != 1 { + return None; + } + Some(index.member(module, name).iter().any(|def| def.kind == SymbolKind::Port)) +} diff --git a/crates/lucisv_mcp/src/tools/item/verify.rs b/crates/lucisv_mcp/src/tools/item/verify.rs new file mode 100644 index 0000000..2d3a8cf --- /dev/null +++ b/crates/lucisv_mcp/src/tools/item/verify.rs @@ -0,0 +1,572 @@ +//! The verifier the three structural edits share — the one new piece of +//! logic in the MCP block, so it is guilty until proven innocent: every rule +//! here has an attack in `tests/attacks.rs`. +//! +//! An edit is a [`Splice`]: the bytes `start..old_end` of the file become +//! `text`. The splice itself cannot touch a byte outside that range (it is a +//! string replacement), so what is verified is what the new bytes do to the +//! **lexing and the parse**: +//! +//! 1. the new file lexes, and parses strictly when the old one did (else its +//! tolerant error count does not grow); (1a) `text` lexes on its own; +//! (1b) every token and comment outside the region is the old file's, +//! shifted, and the text's comments attach to the text's tokens — both +//! in [`lexical`]; +//! 2. every item outside the region — before it, after it, and the ones +//! enclosing it — is the same item as before: same depth, same kind +//! class, same start (items after the region shifted by the splice's +//! length change), same end. A text that leaves a block open, or closes +//! the enclosing module, moves some item's end and is refused; +//! 3. the items inside the region are what the tool expects ([`Expect`]), +//! one level below the enclosing items, and each is a kind the enclosing +//! scope may hold; +//! 4. no name is declared twice in one scope that was not already; +//! 5. the region's `` `ifdef``/`` `endif`` directives balance, in the old +//! bytes and in the new; +//! 6. the `` `define``/`` `undef`` entries inside the region are the same +//! before and after — except inside a directive or macro item at the +//! region's level, where editing the definition is the point; +//! 7. the region holds the same fence markers before and after +//! ([`lexical`]). +//! +//! What is deliberately **not** verified: whether the new text makes sense — +//! its types, widths, the names it reads. `diagnostics` answers that. + +use vlog_parser::ast::{Item, ItemKind}; +use vlog_parser::defines::DefineKind; +use vlog_parser::span::TextRange; +use vlog_parser::token::{Token, TokenKind}; +use vlog_semantic::Symbol; + +use super::lexical::{self, Region}; +use crate::project::Analysis; +use crate::tools::read_item::child_items; + +/// Replace the bytes `start..old_end` of a file with `text`. +pub struct Splice { + pub start: u32, + pub old_end: u32, + pub text: String, +} + +/// What the region must hold after the splice. +pub enum Expect { + /// Exactly one item, of this kind class (`replace_item`). + One(&'static str), + /// One item or more (`insert_item`). + Some, + /// Nothing (`delete_item`). + Nothing, +} + +/// A splice that passed: the new file, its analysis, and the items the +/// region now holds at its own level (kind class and span). +pub struct Outcome { + pub text: String, + pub analysis: Analysis, + pub items: Vec<(&'static str, TextRange)>, +} + +/// Check `splice` against `old` (see the module comment); the refusal is one +/// sentence naming the rule broken. +pub fn check(old: &Analysis, splice: &Splice, expect: Expect) -> Result { + let text = spliced(&old.text, splice)?; + let analysis = Analysis::of(text.clone()); + let new_end = splice.start + splice.text.len() as u32; + let region = Region { start: splice.start, old_end: splice.old_end, new_end }; + parses_as_well(old, &analysis, &splice.text)?; + lexical::same_outside(old, &analysis, region)?; + let shift = i64::from(new_end) - i64::from(splice.old_end); + let before = split(old, &outline(&old.tree.items), splice.start, splice.old_end, shift)?; + let after = split(&analysis, &outline(&analysis.tree.items), splice.start, new_end, 0)?; + same_surroundings(old, &before, &after)?; + let level = after.enclosing.len(); + let items: Vec<(&'static str, TextRange)> = after + .inside + .iter() + .filter(|node| node.depth == level) + .map(|node| (node.class, TextRange::new(node.start, node.end))) + .collect(); + expected(&items, &expect)?; + let container = after.enclosing.last().map_or("file", |node| node.class); + if let Some((class, _)) = items.iter().find(|(class, _)| !fits(container, class)) { + return Err(format!("a {class} cannot stand in a {container}'s scope")); + } + same_macros(old, &analysis, region, (&before, &after))?; + no_new_duplicates(old, &analysis)?; + balanced(&old.tokens, splice.start, splice.old_end, "the old item")?; + balanced(&analysis.tokens, splice.start, new_end, "the new text")?; + lexical::same_fences(old, &analysis, region)?; + Ok(Outcome { text, analysis, items }) +} + +/// The old text with the splice applied; a range off a character boundary +/// is refused, never adjusted. +fn spliced(old: &str, splice: &Splice) -> Result { + let (start, end) = (splice.start as usize, splice.old_end as usize); + match (old.get(..start), old.get(end..)) { + (Some(head), Some(tail)) if start <= end => Ok(format!("{head}{}{tail}", splice.text)), + _ => Err(format!("bytes {start}..{end} do not fall on character boundaries")), + } +} + +/// Rule 1: the new file lexes, and so does `text` alone (1a); it parses +/// strictly when the old one did, and otherwise has no more tolerant parse +/// errors than the old one. +fn parses_as_well(old: &Analysis, new: &Analysis, text: &str) -> Result<(), String> { + if new.tokens.is_empty() { + return Err("the file would no longer lex (an unterminated string or comment?)".into()); + } + lexical::lexes_alone(text)?; + if vlog_parser::parse_source(&old.text).is_ok() { + return vlog_parser::parse_source(&new.text) + .map(|_| ()) + .map_err(|e| format!("the file would no longer parse ({e})")); + } + let (was, would) = (old.diagnostics.len(), new.diagnostics.len()); + if would > was { + return Err(format!("the file already had {was} parse error(s) and would have {would}")); + } + Ok(()) +} + +/// One item of a file, flattened: how deep it sits, its kind class and span. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct Node { + depth: usize, + class: &'static str, + start: u32, + end: u32, +} + +/// Every item of a tree, depth first, in source order. +fn outline(items: &[Item]) -> Vec { + let mut out = Vec::new(); + flatten(items, 0, &mut out); + out +} + +fn flatten(items: &[Item], depth: usize, out: &mut Vec) { + for item in items { + let span = item.span; + out.push(Node { depth, class: class_of(&item.kind), start: span.start, end: span.end }); + for children in child_items(&item.kind) { + flatten(children, depth + 1, out); + } + } +} + +/// A file's items relative to a region, in the new file's coordinates. +struct Split { + /// Items wholly before or wholly after the region (the latter shifted). + outside: Vec, + /// Items containing the region (their ends shifted). + enclosing: Vec, + /// Items wholly inside it. + inside: Vec, +} + +/// Sort `nodes` around `start..end`, shifting what follows by `shift`. An +/// item that begins on one side of a region boundary and ends on the other +/// is the text opening or closing something it should not: refused. +fn split( + analysis: &Analysis, + nodes: &[Node], + start: u32, + end: u32, + shift: i64, +) -> Result { + let moved = |at: u32| u32::try_from(i64::from(at) + shift).unwrap_or(u32::MAX); + let mut out = Split { outside: Vec::new(), enclosing: Vec::new(), inside: Vec::new() }; + for node in nodes { + if end > start && start <= node.start && node.end <= end { + out.inside.push(*node); + } else if node.end <= start { + out.outside.push(*node); + } else if node.start >= end { + out.outside.push(Node { start: moved(node.start), end: moved(node.end), ..*node }); + } else if node.start < start && node.end >= end { + out.enclosing.push(Node { end: moved(node.end), ..*node }); + } else { + let line = analysis.lines.line_col(node.start).0; + return Err(format!( + "the {} at line {line} would begin on one side of the edit and end on the other; the text must open and close everything it starts", + node.class + )); + } + } + Ok(out) +} + +/// Rule 2: the items around the region are the items that were there. +fn same_surroundings(old: &Analysis, before: &Split, after: &Split) -> Result<(), String> { + let describe = |node: Option<&Node>| match node { + Some(node) => { + format!("the {} at line {}", node.class, old.lines.line_col(node.start).0) + } + None => "the end of the file".to_string(), + }; + for (was, now, place) in [ + (&before.enclosing, &after.enclosing, "around"), + (&before.outside, &after.outside, "outside"), + ] { + if was == now { + continue; + } + let at = was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len()); + return Err(format!( + "the edit would change how the file parses {place} the item ({} would not survive as it is); the text must be complete items that open and close within themselves", + describe(was.get(at).or(was.last())) + )); + } + Ok(()) +} + +/// Rule 3: the region holds what the tool promised. +fn expected(items: &[(&'static str, TextRange)], expect: &Expect) -> Result<(), String> { + match (expect, items) { + (Expect::One(class), [(found, _)]) if found == class => Ok(()), + (Expect::One(class), [(found, _)]) => Err(format!( + "the text is a {found} where a {class} was; replace_item keeps an item's kind (delete_item, then insert_item, to change it)" + )), + (Expect::One(_), many) => Err(format!( + "the text holds {} items where one was; replace_item replaces one item with one (insert_item adds more)", + many.len() + )), + (Expect::Some, []) => Err("the text holds no item".into()), + (Expect::Nothing, [_, ..]) => Err("the deletion would leave an item behind".into()), + _ => Ok(()), + } +} + +/// The kind class of an item: the unit of "the same kind" for +/// `replace_item`, and what [`fits`] asks about. The table is the README's. +pub fn class_of(kind: &ItemKind) -> &'static str { + match kind { + ItemKind::Module(module) => match module.kw.as_str() { + "interface" => "interface", + "program" => "program", + _ => "module", + }, + ItemKind::Package { .. } => "package", + ItemKind::Class(_) => "class", + ItemKind::DataDecl(_) + | ItemKind::ParamDecl(_) + | ItemKind::Typedef(_) + | ItemKind::Let(_) => "declaration", + ItemKind::PortDecl(_) => "port declaration", + ItemKind::Genvar(_) => "genvar", + ItemKind::ContAssign(_) => "assign", + ItemKind::Alias(_) => "alias", + ItemKind::Always { .. } => "always", + ItemKind::Initial(_) => "initial", + ItemKind::Final(_) => "final", + ItemKind::Instantiation(_) | ItemKind::GateInstantiation(_) => "instance", + ItemKind::Function(_) => "function", + ItemKind::Task(_) => "task", + ItemKind::GenerateRegion { .. } + | ItemKind::GenIf(_) + | ItemKind::GenFor(_) + | ItemKind::GenCase(_) + | ItemKind::GenBlock(_) => "generate", + ItemKind::Import(_) => "import", + ItemKind::Export(_) => "export", + ItemKind::Modport(_) => "modport", + ItemKind::Clocking(_) => "clocking", + ItemKind::Constraint(_) => "constraint", + ItemKind::Covergroup(_) => "covergroup", + ItemKind::PropSeqDecl(_) => "property", + ItemKind::Assertion(_) | ItemKind::DefaultDisable(_) => "assertion", + ItemKind::Verbatim(raw) => verbatim_class(&raw.text), + ItemKind::Bind(_) => "bind", + ItemKind::Defparam(_) => "defparam", + ItemKind::Timeunit(_) => "timeunit", + ItemKind::ElabTask(_) => "elaboration task", + ItemKind::MacroItem(_) => "macro", + ItemKind::Directive(_) => "directive", + ItemKind::Empty => "empty item", + ItemKind::Error(_) => "unparsed text", + } +} + +/// A verbatim item's class, read off its first words: the parser keeps a +/// concurrent assertion, and a constraint or covergroup its grammar did not +/// fit, as text — the same construct the parsed kinds classify. +fn verbatim_class(text: &str) -> &'static str { + let words: Vec<&str> = text + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .filter(|word| !word.is_empty()) + .take(3) + .collect(); + let has = |set: &[&str]| words.iter().any(|word| set.contains(word)); + if has(&["assert", "assume", "cover", "restrict", "expect"]) { + "assertion" + } else if has(&["covergroup"]) { + "covergroup" + } else if has(&["constraint"]) { + "constraint" + } else if has(&["property", "sequence"]) { + "property" + } else { + "verbatim" + } +} + +/// Kinds only a module-like body (module, interface, program, generate) holds. +const BODY_ONLY: &[&str] = &[ + "always", + "initial", + "final", + "assign", + "alias", + "instance", + "generate", + "port declaration", + "modport", + "clocking", + "assertion", + "defparam", + "genvar", + "elaboration task", +]; + +/// Whether an item of `class` may stand directly in a `container` (a kind +/// class, or `file` for the compilation unit) — IEEE 1800 A.1: a file or a +/// package holds no processes, instances or port declarations; a package +/// or a class holds no design units; a package stands only in a file. +fn fits(container: &str, class: &str) -> bool { + let unit = matches!(class, "module" | "interface" | "program" | "package"); + match container { + "file" => !BODY_ONLY.contains(&class), + "package" => !BODY_ONLY.contains(&class) && !unit, + "class" => !BODY_ONLY.contains(&class) && !unit && class != "bind", + _ => class != "package", + } +} + +/// Rule 6: the macro definitions whose directives lie in the region are the +/// same before and after, those inside a directive or macro item at the +/// region's level aside — a text may not define or undefine a macro that +/// code outside it reads, except by editing the `` `define`` item itself. +fn same_macros( + old: &Analysis, + new: &Analysis, + region: Region, + (before, after): (&Split, &Split), +) -> Result<(), String> { + let was = definitions(old, region.start, region.old_end, before); + let now = definitions(new, region.start, region.new_end, after); + if was == now { + return Ok(()); + } + let at = + was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len().min(now.len())); + let name = now.get(at).or(was.get(at)).map_or("", |define| define.1.as_str()); + Err(format!( + "the text changes a macro definition (`{name}`) nested in an item (rule 6); edit the `define item itself" + )) +} + +/// A define entry as compared: kind, name, parameters, body. +type Definition = (DefineKind, String, Option>, String); + +/// The `` `define``/`` `undef`` entries starting in `start..end`, except those +/// inside a directive or macro item at the split's own level. +fn definitions(analysis: &Analysis, start: u32, end: u32, split: &Split) -> Vec { + let level = split.enclosing.len(); + let exempt: Vec<&Node> = split + .inside + .iter() + .filter(|node| node.depth == level && matches!(node.class, "directive" | "macro")) + .collect(); + let in_exempt = |at: u32| exempt.iter().any(|node| node.start <= at && at < node.end); + analysis + .defines + .entries() + .iter() + .filter(|d| start <= d.span.start && d.span.start < end && !in_exempt(d.span.start)) + .map(|d| (d.kind, d.name.clone(), d.params.clone(), d.body.clone())) + .collect() +} + +/// Rule 4: every name the new file declares twice in one scope, it already +/// declared twice (counted per name). +fn no_new_duplicates(old: &Analysis, new: &Analysis) -> Result<(), String> { + let names = |analysis: &Analysis| { + let mut names: Vec = + analysis.semantics.duplicates().iter().map(|d| d.name.clone()).collect(); + names.sort(); + names + }; + let (was, now) = (names(old), names(new)); + let count = |list: &[String], name: &str| list.iter().filter(|n| *n == name).count(); + match now.iter().find(|name| count(&now, name) > count(&was, name)) { + Some(name) => Err(format!("`{name}` would be declared twice in one scope")), + None => Ok(()), + } +} + +/// Rule 5: the conditional-compilation directives starting inside +/// `start..end` open and close within it. +fn balanced(tokens: &[Token], start: u32, end: u32, what: &str) -> Result<(), String> { + let mut depth = 0usize; + let inside = tokens + .iter() + .filter(|t| t.kind == TokenKind::Directive && start <= t.span.start && t.span.start < end); + for token in inside { + let word = token.text.split_whitespace().next().unwrap_or(""); + match word { + "`ifdef" | "`ifndef" => depth += 1, + "`elsif" | "`else" if depth == 0 => return Err(unbalanced(what, word)), + "`endif" => depth = depth.checked_sub(1).ok_or_else(|| unbalanced(what, word))?, + _ => {} + } + } + if depth > 0 { + return Err(unbalanced(what, "`ifdef")); + } + Ok(()) +} + +fn unbalanced(what: &str, word: &str) -> String { + format!("{what} holds a `{}` whose other half is outside it", word.trim_start_matches('`')) +} + +/// The declarations an item owns: those it writes (by name, or — for a +/// non-ANSI port's body declaration — by its detail) where its neighbours +/// can name them. Names bound in a scope a construct inside the item opens +/// (a module's signals, a function's arguments, an unnamed `begin`'s +/// locals) are the item's business; the header scope a generate loop opens +/// for its genvar and label, which spans exactly the item, is see-through. +pub fn owned(analysis: &Analysis, span: TextRange) -> Vec<&Symbol> { + let within = |inner: TextRange| span.start <= inner.start && inner.end <= span.end; + analysis + .semantics + .symbols() + .iter() + .filter(|symbol| within(symbol.name_span) || symbol.detail_span.is_some_and(within)) + .filter(|symbol| seen_from_outside(analysis, symbol, span)) + .collect() +} + +/// Whether every scope between `symbol` and the first scope outside `span` +/// is one the item opened around itself (unnamed, spanning exactly it). +fn seen_from_outside(analysis: &Analysis, symbol: &Symbol, span: TextRange) -> bool { + let semantics = &analysis.semantics; + let mut at = Some(symbol.scope); + while let Some(id) = at { + // The file scope may span exactly the item when the file is that + // item and nothing else; it is never the item's own. + let Some(scope) = semantics.scope(id).filter(|_| id != semantics.file_scope()) else { + return true; + }; + let inside = span.start <= scope.span.start && scope.span.end <= span.end; + if !inside { + return true; + } + if scope.owner.is_some() || scope.span != span { + return false; + } + at = scope.parent; + } + true +} + +/// The names [`owned`] finds, sorted. +pub fn owned_names(analysis: &Analysis, span: TextRange) -> Vec { + let mut names: Vec = + owned(analysis, span).into_iter().map(|symbol| symbol.name.clone()).collect(); + names.sort(); + names +} + +#[cfg(test)] +mod tests { + use super::*; + + const SRC: &str = "module m (input logic d);\n logic a;\n always_comb a = d;\nendmodule\n"; + + fn run(start: u32, old_end: u32, text: &str, expect: Expect) -> Result { + let old = Analysis::of(SRC.to_string()); + check(&old, &Splice { start, old_end, text: text.into() }, expect) + } + + fn span_of(needle: &str) -> (u32, u32) { + let at = SRC.find(needle).unwrap() as u32; + (at, at + needle.len() as u32) + } + + #[test] + fn a_same_kind_item_passes_and_reports_its_span() { + let (start, end) = span_of("logic a;"); + let outcome = run(start, end, "logic [3:0] a;", Expect::One("declaration")).unwrap(); + assert_eq!(outcome.items.len(), 1); + assert_eq!(outcome.items[0].1, TextRange::new(start, start + 14)); + assert!(outcome.text.contains(" logic [3:0] a;\n always_comb")); + } + + #[test] + fn each_rule_refuses_with_its_own_sentence() { + let (start, end) = span_of("logic a;"); + let open = run(start, end, "always_comb begin a = d;", Expect::One("declaration")); + assert!(open.err().unwrap().contains("no longer parse")); + let closes = run(start, end, "logic a;\nendmodule\nmodule z;", Expect::One("declaration")); + assert!(closes.err().unwrap().contains("open and close")); + let two = run(start, end, "logic a; logic b;", Expect::One("declaration")); + assert!(two.err().unwrap().contains("holds 2 items")); + let kind = run(start, end, "initial a = 0;", Expect::One("declaration")); + assert!(kind.err().unwrap().contains("initial where a declaration was")); + let twice = run(start, end, "logic d;", Expect::One("declaration")); + assert!(twice.err().unwrap().contains("`d` would be declared twice")); + let half = run(start, end, "`ifdef X\nlogic a;", Expect::Some); + assert!(half.err().unwrap().contains("`ifdef"), "half"); + let split = run(start + 1, end, "x", Expect::Some); + assert!(split.is_err()); + } + + #[test] + fn a_file_scope_insert_must_be_a_kind_the_file_may_hold() { + let at = SRC.len() as u32; + let always = run(at, at, "always_comb x = 1;\n", Expect::Some); + assert!(always.err().unwrap().contains("always cannot stand in a file's scope")); + assert!(run(at, at, "module z; endmodule\n", Expect::Some).is_ok()); + } + + #[test] + fn verbatim_items_are_classed_by_their_words() { + assert_eq!(verbatim_class("a1: assert property (p);"), "assertion"); + assert_eq!(verbatim_class("covergroup cg @(e); endgroup"), "covergroup"); + assert_eq!(verbatim_class("static constraint c { x; }"), "constraint"); + assert_eq!(verbatim_class("sequence s; a; endsequence"), "property"); + assert_eq!(verbatim_class("?"), "verbatim"); + assert!(fits("module", "always") && !fits("package", "module") && !fits("class", "bind")); + } + + #[test] + fn owned_names_are_the_ones_bound_around_the_item() { + let analysis = Analysis::of(SRC.to_string()); + let whole = TextRange::new(0, SRC.len() as u32 - 1); + assert_eq!(owned_names(&analysis, whole), ["m"]); + let (start, end) = span_of("logic a;"); + assert_eq!(owned_names(&analysis, TextRange::new(start, end)), ["a"]); + let (start, end) = span_of("always_comb a = d;"); + assert!(owned_names(&analysis, TextRange::new(start, end)).is_empty()); + } + + #[test] + fn a_generate_loop_owns_its_label_and_an_unnamed_begin_keeps_its_locals() { + let src = "module g;\n for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end\n always begin\n int k;\n end\nendmodule\n"; + let analysis = Analysis::of(src.to_string()); + let span = |needle: &str, len: usize| { + let at = src.find(needle).unwrap() as u32; + TextRange::new(at, at + len as u32) + }; + let lp = span( + "for (genvar", + "for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end".len(), + ); + assert_eq!(owned_names(&analysis, lp), ["gen_l", "i"]); + let always = span("always begin", "always begin\n int k;\n end".len()); + assert!(owned_names(&analysis, always).is_empty()); + } +} diff --git a/crates/lucisv_mcp/src/tools/mod.rs b/crates/lucisv_mcp/src/tools/mod.rs index 17e8d0a..b0229c3 100644 --- a/crates/lucisv_mcp/src/tools/mod.rs +++ b/crates/lucisv_mcp/src/tools/mod.rs @@ -9,6 +9,7 @@ mod edit; mod format; mod hierarchy; mod interface; +mod item; mod nav; mod read; mod read_item; @@ -102,6 +103,9 @@ const TOOLS: &[(Tool, Effect)] = &[ (edit::REMOVE_PORT, Edit { idempotent: false }), (refactor::ADD_PORT, Edit { idempotent: false }), (refactor::EXTRACT_MODULE, Edit { idempotent: false }), + (item::REPLACE_ITEM, Edit { idempotent: true }), + (item::INSERT_ITEM, Edit { idempotent: false }), + (item::DELETE_ITEM, Edit { idempotent: true }), (refactor::INSTANTIATE, Read), ]; diff --git a/crates/lucisv_mcp/tests/attacks.rs b/crates/lucisv_mcp/tests/attacks.rs new file mode 100644 index 0000000..a57e0f8 --- /dev/null +++ b/crates/lucisv_mcp/tests/attacks.rs @@ -0,0 +1,764 @@ +//! The dev's attack suite on the structural edits' verifier (lane M4) — +//! CLAUDE.md invariant 4 applied to the MCP block's own safety net: every +//! case is an edit the verifier could plausibly let through, asserted +//! **refused with the tree byte-identical** (every file hashed before and +//! after). A few controls sit beside them: the nearest edit that must pass, +//! so a refusal is known to come from the rule and not from a broken setup. + +use std::collections::hash_map::DefaultHasher; +use std::collections::BTreeMap; +use std::fs; +use std::hash::{Hash, Hasher}; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::time::{Duration, Instant}; + +use serde_json::{json, Value}; + +const ANSWER_TIMEOUT: Duration = Duration::from_secs(120); + +static NEXT_DIR: AtomicUsize = AtomicUsize::new(0); + +/// A scratch tree: the `item` fixture plus the files a case adds. +struct Tree(PathBuf); + +impl Tree { + 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-attacks-{}-{unique}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/item"); + copy_tree(&fixture, &dir); + for (name, text) in files { + fs::write(dir.join(name), text).unwrap(); + } + Tree(fs::canonicalize(dir).unwrap()) + } + + /// Every file, root-relative, with the hash of its bytes. + fn hashes(&self) -> BTreeMap { + fn walk(dir: &Path, root: &Path, out: &mut BTreeMap) { + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(&path, root, out); + continue; + } + let mut hasher = DefaultHasher::new(); + fs::read(&path).unwrap().hash(&mut hasher); + let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned(); + out.insert(name, hasher.finish()); + } + } + let mut out = BTreeMap::new(); + walk(&self.0, &self.0, &mut out); + out + } + + fn read(&self, file: &str) -> String { + fs::read_to_string(self.0.join(file)).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 running server, initialised. +struct Session { + child: Child, + stdin: ChildStdin, + lines: Receiver, + next_id: i64, +} + +impl Session { + fn over(tree: &Tree) -> Session { + 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 stdout = child.stdout.take().unwrap(); + let (send, lines) = mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if send.send(line).is_err() { + break; + } + } + }); + let stdin = child.stdin.take().unwrap(); + let mut session = Session { child, stdin, lines, next_id: 0 }; + session.request("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}})); + session.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"})); + session + } + + fn send(&mut self, message: &Value) { + writeln!(self.stdin, "{message}").unwrap(); + self.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})); + let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered"); + let reply: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(reply["id"], id); + reply + } + + /// A tool call: whether it was refused, and its text. + fn call(&mut self, tool: &str, arguments: Value) -> (bool, String) { + let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments})); + let result = &reply["result"]; + let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string(); + (result["isError"] == true, text) + } +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// Run `tool` and assert it refuses with a sentence holding `why`, leaving +/// every file of the tree byte-identical — also under `dry_run`. +fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) { + let before = tree.hashes(); + for dry_run in [true, false] { + let mut arguments = args.clone(); + arguments["dry_run"] = Value::from(dry_run); + let (error, text) = server.call(tool, arguments); + assert!(error, "{tool} {args}: not refused: {text}"); + assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}"); + assert!(text.ends_with("nothing written.") || text.contains("nothing written"), "{text}"); + assert_eq!(before, tree.hashes(), "{tool} {args}: a refusal wrote"); + } +} + +/// Run `tool` and assert it wrote (the control beside an attack). +fn accepted(server: &mut Session, tool: &str, args: Value) -> String { + let (error, text) = server.call(tool, args.clone()); + assert!(!error, "{tool} {args}: refused: {text}"); + text +} + +fn core(item: &str, text: &str) -> Value { + json!({"file": "rtl/core.sv", "item": item, "text": text}) +} + +#[test] +fn a_text_that_opens_a_block_it_does_not_close_is_refused() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + let open = "always_ff @(posedge clk) begin\n r <= d;"; + refused(&tree, &mut server, "replace_item", core("always@12", open), "no longer parse"); + let unclosed_function = "function automatic int f(int a);\n return a;"; + let args = json!({"file": "rtl/core.sv", "anchor": "r", "text": unclosed_function}); + refused(&tree, &mut server, "insert_item", args, "no longer parse"); +} + +#[test] +fn a_text_that_closes_the_enclosing_module_is_refused() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + // Still a valid file: `r` ends `core` and the rest becomes `sneaky`. + let closes = "logic [7:0] r;\nendmodule\nmodule sneaky;"; + refused(&tree, &mut server, "replace_item", core("r", closes), "open and close"); + let end = json!({"file": "rtl/wrap.sv", "anchor": "end", "text": "endmodule\nmodule sneaky;"}); + refused(&tree, &mut server, "insert_item", end, "open and close"); +} + +#[test] +fn a_text_that_redeclares_a_port_is_refused_even_with_rename() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + // The duplicate rule fires before the name rule, so `rename` changes + // nothing: a port is never redeclared. + refused( + &tree, + &mut server, + "replace_item", + core("p", "logic d;"), + "`d` would be declared twice", + ); + let mut renamed = core("p", "logic d;"); + renamed["rename"] = Value::from(true); + refused(&tree, &mut server, "replace_item", renamed, "`d` would be declared twice"); + let insert = json!({"file": "rtl/core.sv", "anchor": "p", "text": "logic [3:0] clk;"}); + refused(&tree, &mut server, "insert_item", insert, "`clk` would be declared twice"); +} + +#[test] +fn two_items_where_one_was_and_an_empty_text_are_refused() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + let two = "logic p;\n logic p2;"; + refused(&tree, &mut server, "replace_item", core("p", two), "holds 2 items where one was"); + let empty_item = "logic p;;"; + refused(&tree, &mut server, "replace_item", core("p", empty_item), "holds 2 items"); + for empty in ["", " \n\t\r\n"] { + refused(&tree, &mut server, "replace_item", core("p", empty), "`delete_item` removes"); + let args = json!({"file": "rtl/core.sv", "anchor": "end", "text": empty}); + refused(&tree, &mut server, "insert_item", args, "`text` is empty"); + } +} + +const UTF8: &str = + "module u;\n logic a;// \u{fc}\u{20ac} note\n /*\u{e9}*/logic b;/*\u{df}*/\nendmodule\n"; + +#[test] +fn a_multibyte_neighbour_stays_byte_identical_and_a_non_ascii_name_is_refused() { + let tree = Tree::with(&[("rtl/u.sv", UTF8)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/u.sv", "item": "b", "text": "logic b\u{e9};"}); + refused(&tree, &mut server, "replace_item", args, "the file would no longer"); + let after = json!({"file": "rtl/u.sv", "anchor": "a", "text": "logic \u{e9};"}); + refused(&tree, &mut server, "insert_item", after, "would no longer"); + // The control: the comments hugging `b` on both sides, multibyte, stay. + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/u.sv", "item": "b", "text": "logic [1:0] b;"}), + ); + assert_eq!(tree.read("rtl/u.sv"), UTF8.replace("logic b;", "logic [1:0] b;")); + // A multibyte comment inside the new text is the agent's to write. + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/u.sv", "item": "b", "text": "logic b; // \u{e9}"}), + ); +} + +#[test] +fn nothing_inside_a_format_fence_is_edited() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + let fence = "`// lucisv: off` fence"; + refused(&tree, &mut server, "replace_item", core("keep_me", "logic keep_me;"), fence); + refused( + &tree, + &mut server, + "delete_item", + json!({"file": "rtl/core.sv", "item": "keep_me"}), + fence, + ); + for position in ["before", "after"] { + let args = json!({"file": "rtl/core.sv", "anchor": "keep_me", "position": position, "text": "logic z;"}); + refused(&tree, &mut server, "insert_item", args, fence); + } + // Deleting the fenced region's owner, or an item whose leading comment + // is the `on` fence, would move a fence. + refused( + &tree, + &mut server, + "delete_item", + json!({"file": "rtl/core.sv", "item": "core"}), + fence, + ); + refused( + &tree, + &mut server, + "delete_item", + json!({"file": "rtl/core.sv", "item": "always@22", "force": true}), + fence, + ); +} + +#[test] +fn a_file_or_a_text_with_an_unterminated_string_is_refused() { + let broken = "module s;\n initial $display(\"oops);\n logic a;\nendmodule\n"; + let tree = Tree::with(&[("rtl/s.sv", broken)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/s.sv", "item": "a", "text": "logic [1:0] a;"}); + refused(&tree, &mut server, "replace_item", args, "does not lex"); + let end = json!({"file": "rtl/s.sv", "anchor": "end", "text": "logic b;"}); + refused(&tree, &mut server, "insert_item", end, "does not lex"); + refused(&tree, &mut server, "replace_item", core("p", "logic p = \"x;"), "no longer lex"); +} + +#[test] +fn an_insert_after_endmodule_must_be_something_a_file_may_hold() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + // Both parse: the parser accepts module items at file scope. + for text in ["always_comb q = r;", "assign q = 8'h0;", "core u_again (.*);"] { + let args = + json!({"file": "rtl/wrap.sv", "anchor": "wrap", "position": "after", "text": text}); + refused(&tree, &mut server, "insert_item", args, "cannot stand in a file's scope"); + } + let in_package = + json!({"file": "rtl/item_pkg.sv", "anchor": "end", "text": "initial $display(1);"}); + refused(&tree, &mut server, "insert_item", in_package, "cannot stand in a package's scope"); + // The control: a module after a module. + let module = + json!({"file": "rtl/wrap.sv", "anchor": "wrap", "text": "module extra;\nendmodule"}); + accepted(&mut server, "insert_item", module); + assert!(tree.read("rtl/wrap.sv").ends_with("endmodule\n\nmodule extra;\nendmodule\n")); +} + +#[test] +fn a_valid_item_of_another_kind_is_refused() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + let function = "function automatic int f(int a);\n return a;\n endfunction"; + refused( + &tree, + &mut server, + "replace_item", + core("always@12", function), + "a function where a always was", + ); + let initial = "initial r = '0;"; + refused( + &tree, + &mut server, + "replace_item", + core("always@12", initial), + "initial where a always", + ); + refused( + &tree, + &mut server, + "replace_item", + core("p", "assign q = 8'h1;"), + "assign where a declaration", + ); + // The control: `always_ff` may become `always_comb` — one class. + accepted(&mut server, "replace_item", core("always@22", "always @* p = ^r;")); +} + +const ESCAPED: &str = "module e;\n logic \\a+b ;\n assign \\a+b = 1'b0;\nendmodule\n"; + +#[test] +fn an_escaped_name_is_matched_exactly() { + let tree = Tree::with(&[("rtl/e.sv", ESCAPED)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/e.sv", "item": "\\a+b", "text": "logic \\a+c ;"}); + refused( + &tree, + &mut server, + "replace_item", + args, + "declares `\\a+c` where the item declared `\\a+b`", + ); + let delete = json!({"file": "rtl/e.sv", "item": "\\a+b"}); + refused(&tree, &mut server, "delete_item", delete, "rtl/e.sv:3:10 `\\a+b`"); + let args = json!({"file": "rtl/e.sv", "item": "\\a+b", "text": "logic [1:0] \\a+b ;"}); + accepted(&mut server, "replace_item", args); + assert_eq!(tree.read("rtl/e.sv"), ESCAPED.replace("logic \\a+b", "logic [1:0] \\a+b")); +} + +#[test] +fn half_an_ifdef_is_refused_in_either_direction() { + let guarded = "module g;\n`ifdef FAST\n logic a;\n`endif\n logic b;\nendmodule\n"; + let tree = Tree::with(&[("rtl/g.sv", guarded)]); + let mut server = Session::over(&tree); + let open = "`ifdef FAST\n logic [7:0] r;"; + refused(&tree, &mut server, "replace_item", core("r", open), "holds 2 items"); + // One item — a module — carrying half a guard inside it. + let inside = "module tick (\n input logic clk\n);\n`ifdef X\nendmodule"; + let args = json!({"file": "rtl/tick.sv", "item": "tick", "text": inside}); + refused(&tree, &mut server, "replace_item", args, "`ifdef` whose other half"); + let close = json!({"file": "rtl/core.sv", "anchor": "r", "text": "`endif\nlogic z;"}); + refused(&tree, &mut server, "insert_item", close, "`endif` whose other half"); + let orphan = + json!({"file": "rtl/g.sv", "anchor": "b", "position": "before", "text": "`else\nlogic c;"}); + refused(&tree, &mut server, "insert_item", orphan, "`else` whose other half"); + // The controls: a balanced guard inserts; an item inside one replaces. + let whole = + json!({"file": "rtl/g.sv", "anchor": "b", "text": "`ifdef SLOW\n logic c;\n`endif"}); + accepted(&mut server, "insert_item", whole); + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/g.sv", "item": "a", "text": "logic [1:0] a;"}), + ); +} + +#[test] +fn an_insert_or_delete_on_a_shared_line_is_refused() { + let shared = "module n; logic q; logic w; endmodule\n"; + let tree = Tree::with(&[("rtl/n.sv", shared)]); + let mut server = Session::over(&tree); + let delete = json!({"file": "rtl/n.sv", "item": "q"}); + refused(&tree, &mut server, "delete_item", delete, "shares a line"); + let insert = json!({"file": "rtl/n.sv", "anchor": "w", "text": "logic e;"}); + refused(&tree, &mut server, "insert_item", insert, "shares a line"); + let end = json!({"file": "rtl/n.sv", "anchor": "end", "text": "logic e;"}); + refused(&tree, &mut server, "insert_item", end, "shares a line"); + // `replace_item` needs no line of its own: the span is the span. + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/n.sv", "item": "q", "text": "logic [1:0] q;"}), + ); + assert_eq!(tree.read("rtl/n.sv"), "module n; logic [1:0] q; logic w; endmodule\n"); +} + +#[test] +fn a_port_in_a_header_is_not_an_item_and_a_non_ansi_body_port_keeps_its_header() { + let non_ansi = + "module k (a, b);\n input [3:0] a;\n output b;\n assign b = 1'b0;\nendmodule\n"; + let tree = Tree::with(&[("rtl/k.sv", non_ansi)]); + let mut server = Session::over(&tree); + refused( + &tree, + &mut server, + "replace_item", + core("d", "input logic [3:0] d"), + "part of a larger item", + ); + refused( + &tree, + &mut server, + "delete_item", + json!({"file": "rtl/core.sv", "item": "clk"}), + "part of a larger item", + ); + let body = json!({"file": "rtl/k.sv", "item": "a"}); + refused(&tree, &mut server, "delete_item", body, "`a` is also declared on line 1"); + let widen = json!({"file": "rtl/k.sv", "item": "a", "text": "input [7:0] a;"}); + accepted(&mut server, "replace_item", widen); +} + +/// A module of `lines` lines: `logic sN;` declarations with one always +/// block in the middle. +fn big_module(lines: usize) -> String { + let mut text = String::from("module big (input logic clk);\n"); + for n in 0..lines - 3 { + if n == lines / 2 { + text.push_str(" always_ff @(posedge clk) s0 <= ~s0;\n"); + } else { + text.push_str(&format!(" logic s{n};\n")); + } + } + text.push_str("endmodule\n"); + text +} + +#[test] +fn a_forty_thousand_line_file_is_verified_in_bounded_time() { + let big = big_module(40_000); + let tree = Tree::with(&[("rtl/big.sv", &big)]); + let mut server = Session::over(&tree); + let line = big.lines().position(|l| l.contains("always_ff")).unwrap() + 1; + let item = format!("always@{line}"); + let timed = |server: &mut Session, tool: &str, args: Value| { + let started = Instant::now(); + let answer = server.call(tool, args); + (answer, started.elapsed().as_millis()) + }; + let before = tree.hashes(); + let open = + json!({"file": "rtl/big.sv", "item": item, "text": "always_ff @(posedge clk) begin"}); + let ((error, text), refused_ms) = timed(&mut server, "replace_item", open); + assert!(error && text.contains("no longer parse"), "{text}"); + assert_eq!(before, tree.hashes()); + let good = + json!({"file": "rtl/big.sv", "item": item, "text": "always_ff @(posedge clk) s0 <= s0;"}); + let ((error, text), replaced_ms) = timed(&mut server, "replace_item", good); + assert!(!error, "{text}"); + let insert = json!({"file": "rtl/big.sv", "anchor": "end", "text": "logic tail;"}); + let ((error, text), inserted_ms) = timed(&mut server, "insert_item", insert); + assert!(!error, "{text}"); + let delete = json!({"file": "rtl/big.sv", "item": "s7"}); + let ((error, text), deleted_ms) = timed(&mut server, "delete_item", delete); + assert!(!error, "{text}"); + println!( + "40 000 lines: refused replace {refused_ms} ms, replace {replaced_ms} ms, insert {inserted_ms} ms, delete {deleted_ms} ms" + ); +} + +const LOOP: &str = "module h;\n for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end\n assign gen_l[0].z = 1'b0;\nendmodule\n"; + +#[test] +fn a_generate_loop_owns_its_label() { + let tree = Tree::with(&[("rtl/h.sv", LOOP)]); + let mut server = Session::over(&tree); + let relabel = "for (genvar i = 0; i < 2; i++) begin : gen_m\n logic z;\n end"; + let args = json!({"file": "rtl/h.sv", "item": "gen_l", "text": relabel}); + refused( + &tree, + &mut server, + "replace_item", + args, + "declares `gen_m`, `i` where the item declared `gen_l`, `i`", + ); + let delete = json!({"file": "rtl/h.sv", "item": "gen_l"}); + refused(&tree, &mut server, "delete_item", delete, "rtl/h.sv:5:10 `gen_l`"); + // The control: a wider body under the same label. + let wider = "for (genvar i = 0; i < 2; i++) begin : gen_l\n logic [1:0] z;\n end"; + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/h.sv", "item": "gen_l", "text": wider}), + ); +} + +// ---- the rework's attacks (QA findings 1–8, 2026-09-23) -------------------- + +const FENCE_BELOW: &str = "module f; + logic a; + logic b; // b's own + // lucisv: off + /* hand aligned */ + logic keep_me; + // lucisv: on + logic z; +endmodule +"; + +/// Rule 1a/1b (finding 1): a text may not reach past its own end — an open +/// comment a later `*/` closes, or a comment left on a line of its own that +/// would lead the next item. +#[test] +fn a_text_reaching_past_its_end_is_refused_by_the_lexical_rules() { + let tree = Tree::with(&[("rtl/f.sv", FENCE_BELOW)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a; /* note"}); + refused(&tree, &mut server, "replace_item", args, "rule 1a"); + let args = json!({"file": "rtl/f.sv", "anchor": "a", "text": "logic y; /* note"}); + refused(&tree, &mut server, "insert_item", args, "rule 1a"); + let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a;\n // about b"}); + refused(&tree, &mut server, "replace_item", args, "rule 1b"); + // The control: a comment on the item's own line stays the item's. + let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a; /* note */"}); + accepted(&mut server, "replace_item", args); + assert_eq!(tree.read("rtl/f.sv"), FENCE_BELOW.replace("logic a;", "logic a; /* note */")); +} + +const DOCUMENTED: &str = "module d; + // Section banner + + // old doc of a + logic a; // old trailing + logic b; +endmodule +"; + +/// Finding 2: a text carrying the item's comments replaces the item's own +/// comments with it, so the same call twice is `unchanged`; a banner a blank +/// line separates from the item is not the item's. +#[test] +fn a_text_with_comments_replaces_the_items_own_and_repeats_unchanged() { + let tree = Tree::with(&[("rtl/d.sv", DOCUMENTED)]); + let mut server = Session::over(&tree); + let text = "// new doc of a\n logic [1:0] a; // new trailing"; + let args = json!({"file": "rtl/d.sv", "item": "a", "text": text}); + accepted(&mut server, "replace_item", args.clone()); + let once = tree.read("rtl/d.sv"); + let expected = DOCUMENTED.replace( + "// old doc of a\n logic a; // old trailing", + "// new doc of a\n logic [1:0] a; // new trailing", + ); + assert_eq!(once, expected); + let again = accepted(&mut server, "replace_item", args); + assert!(again.starts_with("unchanged"), "{again}"); + assert_eq!(tree.read("rtl/d.sv"), once); + // Without comments in the text, the item's comments stay where they are. + let args = json!({"file": "rtl/d.sv", "item": "a", "text": "logic a;"}); + accepted(&mut server, "replace_item", args); + assert_eq!(tree.read("rtl/d.sv"), once.replace("logic [1:0] a;", "logic a;")); +} + +const MACROS: &str = "`define ID(x) x +`define CHECK(s) initial assert (!$isunknown(s)); +module mc (output logic o); + logic in_arg; + logic in_nested; + logic in_other_body; + logic free; + assign o = `ID(in_arg); + `CHECK(`ID(in_nested)) + // free is only named in this comment + initial $display(\"free\"); +endmodule +"; +const MACRO_HEADER: &str = "`define READ_OTHER in_other_body\n"; + +/// Finding 3: a spelling inside a macro call (nested too) or another file's +/// `` `define`` body is a possible use; a comment or a string is not. +#[test] +fn a_name_spelled_inside_a_macro_is_a_possible_use() { + let tree = Tree::with(&[("rtl/mc.sv", MACROS), ("rtl/defs.svh", MACRO_HEADER)]); + let mut server = Session::over(&tree); + for (name, line) in [("in_arg", "rtl/mc.sv:8"), ("in_nested", "rtl/mc.sv:9")] { + let args = json!({"file": "rtl/mc.sv", "item": name}); + refused( + &tree, + &mut server, + "delete_item", + args, + &format!("possible use (macro) at {line} `{name}`"), + ); + } + let args = json!({"file": "rtl/mc.sv", "item": "in_other_body"}); + refused( + &tree, + &mut server, + "delete_item", + args, + "possible use (macro) at rtl/defs.svh:1 `in_other_body`", + ); + let forced = json!({"file": "rtl/mc.sv", "item": "in_arg", "force": true}); + let answer = accepted(&mut server, "delete_item", forced); + assert!(answer.contains("deleted with references left: possible use (macro)"), "{answer}"); + // The control: a name spelled only in a comment and a string goes. + accepted(&mut server, "delete_item", json!({"file": "rtl/mc.sv", "item": "free"})); +} + +const BANNERS: &str = "// File banner + +module fb; + // Registers + + // the a flop + logic a; + logic b; +endmodule +"; + +/// Finding 4: a comment a blank line separates from the item is not the +/// item's — not a section banner, not the file banner above a module. +#[test] +fn a_delete_leaves_the_comments_a_blank_line_separates_from_the_item() { + let tree = Tree::with(&[("rtl/fb.sv", BANNERS)]); + let mut server = Session::over(&tree); + accepted(&mut server, "delete_item", json!({"file": "rtl/fb.sv", "item": "a"})); + assert_eq!(tree.read("rtl/fb.sv"), BANNERS.replace(" // the a flop\n logic a;\n", "")); + accepted(&mut server, "delete_item", json!({"file": "rtl/fb.sv", "item": "fb"})); + assert_eq!(tree.read("rtl/fb.sv"), "// File banner\n\n"); +} + +/// Finding 5: a comment before the item on its line goes with the item; only +/// another item's code on the line makes it shared. +#[test] +fn a_same_line_comment_goes_with_its_item_and_code_still_shares_the_line() { + let src = "module sl;\n /* lead */ logic a;\n logic x; /* c */ logic y;\nendmodule\n"; + let tree = Tree::with(&[("rtl/sl.sv", src)]); + let mut server = Session::over(&tree); + let delete = json!({"file": "rtl/sl.sv", "item": "y"}); + refused(&tree, &mut server, "delete_item", delete, "shares a line"); + accepted(&mut server, "delete_item", json!({"file": "rtl/sl.sv", "item": "a"})); + assert_eq!(tree.read("rtl/sl.sv"), "module sl;\n logic x; /* c */ logic y;\nendmodule\n"); +} + +const DEFINES: &str = "`define W 1'b1 +module dm (output logic o, output logic p); + always_comb begin + p = 1'b0; + end + assign o = `W; +endmodule +"; + +/// Rule 6 (finding 6): a `` `define``/`` `undef`` nested in an item changes +/// code outside it — refused by replace, insert and delete; a directive item +/// of its own is the control. +#[test] +fn a_macro_definition_nested_in_an_item_is_refused() { + let tree = Tree::with(&[("rtl/dm.sv", DEFINES)]); + let mut server = Session::over(&tree); + let nested = "always_comb begin\n`undef W\n p = 1'b0;\n end"; + let args = json!({"file": "rtl/dm.sv", "item": "always@3", "text": nested}); + refused(&tree, &mut server, "replace_item", args, "changes a macro definition (`W`)"); + let insert = json!({"file": "rtl/dm.sv", "anchor": "always@3", "text": "initial begin\n`define W 1'b0\n end"}); + refused(&tree, &mut server, "insert_item", insert, "(rule 6)"); + let with_define = DEFINES.replace(" p = 1'b0;\n", "`define Q 1\n p = 1'b0;\n"); + let tree = Tree::with(&[("rtl/dm.sv", &with_define)]); + let mut server = Session::over(&tree); + let delete = json!({"file": "rtl/dm.sv", "item": "always@3"}); + refused(&tree, &mut server, "delete_item", delete, "(`Q`)"); + // The control: a directive item of its own may be inserted. + let args = json!({"file": "rtl/dm.sv", "anchor": "always@3", "text": "`define R 2"}); + accepted(&mut server, "insert_item", args); +} + +/// Rule 7 (finding 7): a text neither opens nor closes a fence. +#[test] +fn a_text_may_not_carry_a_fence_marker() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + let text = "// lucisv: off\n logic lo;"; + let args = json!({"file": "rtl/core.sv", "anchor": "p", "text": text}); + refused(&tree, &mut server, "insert_item", args, "fence marker `// lucisv: off`"); + let text = "always_comb begin\n // lucisv: on\n p = ^r;\n end"; + refused(&tree, &mut server, "replace_item", core("always@22", text), "(rule 7)"); + // The control: an ordinary comment in the same place. + let text = "always_comb begin\n // lucisv: parity\n p = ^r;\n end"; + accepted(&mut server, "replace_item", core("always@22", text)); +} + +const STARS: &str = "module sw; + logic clk; + logic rst_ni; + logic [7:0] d; + logic [7:0] q; + logic unrelated; + if (1) begin : g + core u_core (.*); + end +endmodule +module other; + logic d; + ghost u_ghost (.*); +endmodule +"; + +/// Finding 8: a `.*` binds without spelling the name — a port of the +/// instantiated module is a use (generate blocks included); a module the +/// index cannot resolve makes every name a possible use in that scope. +#[test] +fn a_signal_bound_by_a_dot_star_is_still_referenced() { + let tree = Tree::with(&[("rtl/sw.sv", STARS)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/sw.sv", "item": "d@4"}); + refused( + &tree, + &mut server, + "delete_item", + args, + "bound by `.*` at rtl/sw.sv:8:18 `d` (module `core`)", + ); + let args = json!({"file": "rtl/sw.sv", "item": "d@12"}); + refused( + &tree, + &mut server, + "delete_item", + args, + "possible use (`.*`) at rtl/sw.sv:13:18 `d` (module `ghost`", + ); + // The controls: a signal the module has no port for; a module's own `.*` + // does not reach another module's names. + accepted(&mut server, "delete_item", json!({"file": "rtl/sw.sv", "item": "unrelated"})); + let forced = json!({"file": "rtl/sw.sv", "item": "clk", "force": true}); + let answer = accepted(&mut server, "delete_item", forced); + assert!(answer.contains("bound by `.*` at rtl/sw.sv:7:18 `clk`"), "{answer}"); +} diff --git a/crates/lucisv_mcp/tests/fixtures/item/rtl/core.sv b/crates/lucisv_mcp/tests/fixtures/item/rtl/core.sv new file mode 100644 index 0000000..d59290a --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/item/rtl/core.sv @@ -0,0 +1,23 @@ +module core ( + input logic clk, + input logic rst_ni, + input logic [7:0] d, + output logic [7:0] q +); + logic [7:0] r; // the register + // Parity of r. + logic p; + + // Register the input. + always_ff @(posedge clk or negedge rst_ni) + if (!rst_ni) r <= '0; + else r <= d; + + assign q = r; + + // lucisv: off + logic keep_me; + // lucisv: on + + always_comb p = item_pkg::parity(r); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/item/rtl/item_pkg.sv b/crates/lucisv_mcp/tests/fixtures/item/rtl/item_pkg.sv new file mode 100644 index 0000000..bfd9836 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/item/rtl/item_pkg.sv @@ -0,0 +1,13 @@ +package item_pkg; + parameter int WIDTH = 8; + + // Parity of a word. + function automatic logic parity(logic [WIDTH-1:0] w); + return ^w; + endfunction + + // Nobody calls this one. + function automatic logic spare(logic a); + return a; + endfunction +endpackage diff --git a/crates/lucisv_mcp/tests/fixtures/item/rtl/tick.sv b/crates/lucisv_mcp/tests/fixtures/item/rtl/tick.sv new file mode 100644 index 0000000..3b72954 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/item/rtl/tick.sv @@ -0,0 +1,4 @@ +module tick ( + input logic clk +); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/item/rtl/wrap.sv b/crates/lucisv_mcp/tests/fixtures/item/rtl/wrap.sv new file mode 100644 index 0000000..b057aa8 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/item/rtl/wrap.sv @@ -0,0 +1,9 @@ +module wrap ( + input logic clk, + input logic rst_ni, + input logic [7:0] d, + output logic [7:0] q +); + core u_core (.*); + tick u_tick (.clk); +endmodule diff --git a/crates/lucisv_mcp/tests/qa_m1.rs b/crates/lucisv_mcp/tests/qa_m1.rs index db0b6ec..b7f0e1b 100644 --- a/crates/lucisv_mcp/tests/qa_m1.rs +++ b/crates/lucisv_mcp/tests/qa_m1.rs @@ -276,8 +276,8 @@ fn qa_everything_but_initialize_and_ping_waits_for_the_handshake() { assert!(s.pings()); s.initialize(); // M2 added five tools (defines, definition, references, hierarchy, - // diagnostics) to M1's six; M3 added twelve edit tools. - assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 23); + // diagnostics) to M1's six; M3 added twelve edit tools; M4 three more. + assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 26); } #[test] diff --git a/crates/lucisv_mcp/tests/qa_m4.rs b/crates/lucisv_mcp/tests/qa_m4.rs new file mode 100644 index 0000000..7a95fa6 --- /dev/null +++ b/crates/lucisv_mcp/tests/qa_m4.rs @@ -0,0 +1,1284 @@ +//! QA attacks on lane M4 (the structural edits and their verifier), +//! 2026-09-23. +//! +//! Every test spawns the real binary over a scratch tree, as a host would. +//! Refusals are asserted with every file of the tree byte-identical, under +//! `dry_run` and for real. Accepted edits are checked byte for byte against +//! the span `read_item` reported before the call: the bytes before it and +//! after it must be the bytes that were there (the prefix/suffix guarantee). +//! +//! 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-structural-edits/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::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::time::Duration; + +use serde_json::{json, Value}; + +const ANSWER_TIMEOUT: Duration = Duration::from_secs(120); + +static NEXT_DIR: AtomicUsize = AtomicUsize::new(0); + +/// A scratch tree: optionally the `item` fixture, plus the files a case adds. +struct Tree(PathBuf); + +impl Tree { + fn with(fixture: bool, files: &[(&str, &str)]) -> Tree { + let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst); + let dir = + std::env::temp_dir().join(format!("lucisv-mcp-qa-m4-{}-{unique}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("rtl")).unwrap(); + if fixture { + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/item"); + copy_tree(&source, &dir); + } + for (name, text) in files { + fs::write(dir.join(name), text).unwrap(); + } + Tree(fs::canonicalize(dir).unwrap()) + } + + /// Every file, root-relative, with its bytes. + fn snapshot(&self) -> BTreeMap> { + fn walk(dir: &Path, root: &Path, out: &mut BTreeMap>) { + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(&path, root, out); + } else { + let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned(); + out.insert(name, fs::read(&path).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + walk(&self.0, &self.0, &mut out); + out + } + + fn read(&self, file: &str) -> String { + fs::read_to_string(self.0.join(file)).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 running server, initialised. +struct Session { + child: Child, + stdin: ChildStdin, + lines: Receiver, + next_id: i64, +} + +impl Session { + fn over(tree: &Tree) -> Session { + 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 stdout = child.stdout.take().unwrap(); + let (send, lines) = mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if send.send(line).is_err() { + break; + } + } + }); + let stdin = child.stdin.take().unwrap(); + let mut session = Session { child, stdin, lines, next_id: 0 }; + session.request("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}})); + session.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"})); + session + } + + fn send(&mut self, message: &Value) { + writeln!(self.stdin, "{message}").unwrap(); + self.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})); + let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered"); + let reply: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(reply["id"], id); + reply + } + + /// A tool call: whether it was refused, its text, its structured content. + fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) { + let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments})); + let result = &reply["result"]; + let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string(); + (result["isError"] == true, text, result["structuredContent"].clone()) + } +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// Run `tool` and assert it refuses with a sentence holding `why`, leaving +/// every file of the tree byte-identical — also under `dry_run`. +fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) { + let before = tree.snapshot(); + for dry_run in [true, false] { + let mut arguments = args.clone(); + arguments["dry_run"] = Value::from(dry_run); + let (error, text, _) = server.call(tool, arguments); + assert!(error, "{tool} {args}: not refused: {text}"); + assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}"); + assert!(text.contains("nothing written"), "{text}"); + assert!(before == tree.snapshot(), "{tool} {args}: a refusal wrote"); + } +} + +/// Run `tool` and assert it wrote (or answered `unchanged`); its text. +fn accepted(server: &mut Session, tool: &str, args: Value) -> String { + let (error, text, _) = server.call(tool, args.clone()); + assert!(!error, "{tool} {args}: refused: {text}"); + text +} + +/// The byte span of `item` as `read_item` reports it: its lines and text, +/// turned into offsets (the text located on its first line). +fn span_of(server: &mut Session, text: &str, file: &str, item: &str) -> (usize, usize) { + let (error, answer, structured) = server.call("read_item", json!({"file": file, "item": item})); + assert!(!error, "read_item {item}: {answer}"); + let first = structured["lines"][0].as_u64().unwrap() as usize; + let body = structured["text"].as_str().unwrap(); + let line_start: usize = text.split_inclusive('\n').take(first - 1).map(str::len).sum(); + let at = line_start + text[line_start..].find(body).unwrap(); + (at, at + body.len()) +} + +/// The prefix/suffix guarantee: `after` is `before` with only the bytes of +/// one region changed, and that region lies in `bounds` (inclusive). +fn only_region_changed(before: &str, after: &str, bounds: (usize, usize)) { + let (b, a) = (before.as_bytes(), after.as_bytes()); + let prefix = b.iter().zip(a).take_while(|(x, y)| x == y).count(); + let max_suffix = b.len().min(a.len()) - prefix; + let suffix = + b.iter().rev().zip(a.iter().rev()).take(max_suffix).take_while(|(x, y)| x == y).count(); + let changed = (prefix, b.len() - suffix); + assert!( + bounds.0 <= changed.0 && changed.1 <= bounds.1, + "bytes {changed:?} changed, outside the span {bounds:?}\n--- before\n{before}\n--- after\n{after}" + ); +} + +fn strict(text: &str) -> bool { + vlog_parser::parse_source(text).is_ok() +} + +// ---- 1. replace_item: masked corruption ---------------------------------- + +const M: &str = "`define W 1'b1 +module m (input logic clk); + logic a; + logic b; + always_comb a = 1'b0; + assign b = `W; +endmodule +module t; +endmodule +"; + +#[test] +fn qa_a_directive_riding_along_with_an_item_is_two_items() { + let tree = Tree::with(false, &[("rtl/m.sv", M)]); + let mut server = Session::over(&tree); + for text in [ + "logic a;\n`define W 1'b0", + "`define W 1'b0\nlogic a;", + "`undef W\nlogic a;", + "`include \"x.svh\"\nlogic a;", + "`timescale 1ns/1ps\nlogic a;", + "logic a;\n`ifdef X", + "logic a; ;", + ] { + let args = json!({"file": "rtl/m.sv", "item": "a", "text": text}); + refused(&tree, &mut server, "replace_item", args, "holds 2 items where one was"); + } +} + +#[test] +fn qa_a_text_leaving_a_comment_open_to_the_end_of_file_does_not_lex() { + let tree = Tree::with(false, &[("rtl/m.sv", M)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/m.sv", "item": "a", "text": "logic a; /*"}); + refused(&tree, &mut server, "replace_item", args, "would no longer lex"); + let args = json!({"file": "rtl/m.sv", "anchor": "a", "text": "logic y; /*"}); + refused(&tree, &mut server, "insert_item", args, "would no longer lex"); +} + +const FENCED: &str = "module f; + logic a; + // lucisv: off + /* hand aligned */ + logic keep_me; + assign keep_me = 1'b0; + // lucisv: on + logic z; +endmodule +"; + +/// QA finding 1: a `text` ending in an open `/*` lexes when a later `*/` +/// closes it — it swallows the `// lucisv: off` line, and the next `format` +/// rewrites the hand-aligned code the fence protected. +#[test] +fn qa_a_text_leaving_a_comment_open_is_refused_even_when_a_later_one_closes_it() { + let tree = Tree::with(false, &[("rtl/f.sv", FENCED)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a; /*"}); + refused(&tree, &mut server, "replace_item", args, "comment"); + let args = + json!({"file": "rtl/f.sv", "anchor": "z", "position": "before", "text": "logic y; /*"}); + refused(&tree, &mut server, "insert_item", args, "comment"); +} + +#[test] +fn qa_a_text_carrying_a_unit_boundary_or_a_header_is_refused() { + let tree = Tree::with(false, &[("rtl/m.sv", M)]); + let mut server = Session::over(&tree); + for text in [ + "endmodule\nmodule x;\nlogic a;", + "logic a;\nendmodule\nmodule x;", + "logic a; endmodule module x;", + "module m2; logic a; endmodule", + ] { + let args = json!({"file": "rtl/m.sv", "item": "a", "text": text}); + refused(&tree, &mut server, "replace_item", args, "open and close"); + } + let args = json!({"file": "rtl/m.sv", "item": "a", "text": "module m2; logic a;"}); + refused(&tree, &mut server, "replace_item", args, "no longer parse"); + let args = json!({"file": "rtl/m.sv", "item": "t", "text": "module t;\nendmodule\nmodule t3;\nendmodule"}); + refused(&tree, &mut server, "replace_item", args, "holds 2 items"); + let args = json!({"file": "rtl/m.sv", "item": "a", "text": "logic a; (* keep *)"}); + refused(&tree, &mut server, "replace_item", args, "open and close"); +} + +#[test] +fn qa_another_kind_under_the_old_name_is_refused_with_or_without_rename() { + let tree = Tree::with(false, &[("rtl/m.sv", M)]); + let mut server = Session::over(&tree); + for rename in [false, true] { + let args = + json!({"file": "rtl/m.sv", "item": "always@5", "text": "logic q;", "rename": rename}); + refused(&tree, &mut server, "replace_item", args, "a declaration where a always was"); + let args = json!({"file": "rtl/m.sv", "item": "t", "text": "package t;\nendpackage", "rename": rename}); + refused(&tree, &mut server, "replace_item", args, "where a module was"); + } +} + +#[test] +fn qa_a_text_equal_to_the_item_is_unchanged_and_writes_nothing() { + let tree = Tree::with(true, &[]); + let mut server = Session::over(&tree); + let before = tree.snapshot(); + for text in ["logic p; \n\n", "\n\t logic p;\r\n", "logic p;"] { + for dry_run in [true, false] { + let args = + json!({"file": "rtl/core.sv", "item": "p", "text": text, "dry_run": dry_run}); + let answer = accepted(&mut server, "replace_item", args); + assert!(answer.starts_with("unchanged"), "{answer}"); + } + } + // A fenced item handed back as it is: also `unchanged`, not a refusal. + let args = json!({"file": "rtl/core.sv", "item": "keep_me", "text": "logic keep_me;"}); + assert!(accepted(&mut server, "replace_item", args).starts_with("unchanged")); + assert!(before == tree.snapshot()); +} + +#[test] +fn qa_a_byte_order_mark_in_the_text_is_refused() { + let tree = Tree::with(false, &[("rtl/m.sv", M)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/m.sv", "item": "a", "text": "\u{feff}logic a;"}); + refused(&tree, &mut server, "replace_item", args, "would no longer lex"); +} + +const GEN: &str = "module g #(parameter bit P = 1) (input logic clk); + logic a, b; + generate + if (P) begin : gen_a + always_ff @(posedge clk) a <= ~a; + end else begin : gen_b + always_ff @(posedge clk) b <= ~b; + end + endgenerate + for (genvar i = 0; i < 2; i++) begin : gen_l + logic z; + always_comb z = a; + end + // `ifdef FOO -- a comment, not a directive + logic c; + /* `endif also a comment */ + logic d; +endmodule +"; + +#[test] +fn qa_an_always_inside_a_generate_branch_is_replaced_in_place() { + let tree = Tree::with(false, &[("rtl/g.sv", GEN)]); + let mut server = Session::over(&tree); + for (item, text) in + [("always@5", "always_ff @(posedge clk) a <= a;"), ("always@12", "always_comb z = b;")] + { + let old = tree.read("rtl/g.sv"); + let span = span_of(&mut server, &old, "rtl/g.sv", item); + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/g.sv", "item": item, "text": text}), + ); + let new = tree.read("rtl/g.sv"); + only_region_changed(&old, &new, span); + assert!(strict(&new)); + } + // A text that would close the branch and open another is refused. + let split = "always_ff @(posedge clk) a <= a;\n end else begin : gen_c\n always_ff @(posedge clk) a <= ~a;"; + let args = json!({"file": "rtl/g.sv", "item": "always@5", "text": split}); + refused(&tree, &mut server, "replace_item", args, "no longer parse"); + let escape = "always_comb z = b;\n end\n begin : x"; + let args = json!({"file": "rtl/g.sv", "item": "always@12", "text": escape}); + refused(&tree, &mut server, "replace_item", args, "no longer parse"); +} + +#[test] +fn qa_a_directive_spelled_in_a_comment_does_not_trip_the_balance_rule() { + let tree = Tree::with(false, &[("rtl/g.sv", GEN)]); + let mut server = Session::over(&tree); + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/g.sv", "item": "c", "text": "logic [1:0] c;"}), + ); + let args = + json!({"file": "rtl/g.sv", "anchor": "c", "text": "// `ifdef in a comment\nlogic e;"}); + accepted(&mut server, "insert_item", args); + accepted(&mut server, "delete_item", json!({"file": "rtl/g.sv", "item": "d"})); + accepted(&mut server, "delete_item", json!({"file": "rtl/g.sv", "item": "c"})); + let text = tree.read("rtl/g.sv"); + assert!(strict(&text)); + assert!(!text.contains("`ifdef FOO") && !text.contains("`endif also"), "{text}"); +} + +#[test] +fn qa_a_crlf_file_stays_crlf_through_all_three_tools() { + let crlf = "module c;\r\n logic a;\r\n logic b;\r\nendmodule\r\n"; + let tree = Tree::with(false, &[("rtl/c.sv", crlf)]); + let mut server = Session::over(&tree); + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/c.sv", "item": "a", "text": "logic [1:0] a;\n"}), + ); + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/c.sv", "anchor": "a", "text": " logic x;\n logic y;"}), + ); + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/c.sv", "anchor": "end", "text": " logic e;\r\n logic f;"}), + ); + accepted(&mut server, "delete_item", json!({"file": "rtl/c.sv", "item": "x"})); + let text = tree.read("rtl/c.sv"); + assert_eq!( + text, + "module c;\r\n logic [1:0] a;\r\n\r\n logic y;\r\n\r\n logic b;\r\n\r\n logic e;\r\n logic f;\r\nendmodule\r\n" + ); +} + +/// QA finding 2: `replace_item` is `idempotentHint: true`, but a text that +/// carries a comment before or after its item grows the file on every +/// repeat (the span `read_item` reports excludes the comment). +#[test] +fn qa_the_same_replace_twice_is_unchanged_even_with_a_comment_in_the_text() { + let tree = Tree::with(true, &[]); + let mut server = Session::over(&tree); + for text in ["// doc of r\nlogic [7:0] r;", "logic p; // trailing"] { + let item = if text.contains(" r;") { "r" } else { "p" }; + let args = json!({"file": "rtl/core.sv", "item": item, "text": text}); + let (error, _, _) = server.call("replace_item", args.clone()); + let first = tree.read("rtl/core.sv"); + let (again_error, answer, _) = server.call("replace_item", args); + assert_eq!(tree.read("rtl/core.sv"), first, "a repeat changed the file"); + assert!(error || again_error || answer.starts_with("unchanged"), "{answer}"); + } +} + +// ---- 2. insert_item ------------------------------------------------------ + +const TWO: &str = "module a;\n logic x;\nendmodule\n\nmodule b;\n logic y;\nendmodule\n"; +const PKG: &str = + "package pk;\n parameter int W = 1;\nendpackage\n\nmodule after_pkg;\nendmodule\n"; +const CLS: &str = "class cls;\n int v;\n function void f();\n endfunction\nendclass\n"; + +#[test] +fn qa_end_is_the_last_unit_and_end_at_names_one() { + let tree = Tree::with(false, &[("rtl/two.sv", TWO), ("rtl/pk.sv", PKG)]); + let mut server = Session::over(&tree); + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/two.sv", "anchor": "end", "text": " logic t;"}), + ); + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/two.sv", "anchor": "end@a", "text": " logic u;"}), + ); + assert_eq!( + tree.read("rtl/two.sv"), + "module a;\n logic x;\n\n logic u;\nendmodule\n\nmodule b;\n logic y;\n\n logic t;\nendmodule\n" + ); + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/pk.sv", "anchor": "end@pk", "text": " parameter int V = 2;"}), + ); + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/pk.sv", "anchor": "end", "text": " logic t;"}), + ); + assert_eq!( + tree.read("rtl/pk.sv"), + "package pk;\n parameter int W = 1;\n\n parameter int V = 2;\nendpackage\n\nmodule after_pkg;\n logic t;\nendmodule\n" + ); + let args = json!({"file": "rtl/pk.sv", "anchor": "end@pk", "text": "always_comb x = 1;"}); + refused(&tree, &mut server, "insert_item", args, "cannot stand in a package's scope"); + let args = json!({"file": "rtl/pk.sv", "anchor": "end@W", "text": "logic q;"}); + refused(&tree, &mut server, "insert_item", args, "is not a module, package or class"); +} + +#[test] +fn qa_a_class_body_takes_a_method_but_no_process_unit_or_duplicate() { + let tree = Tree::with(false, &[("rtl/cls.sv", CLS)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/cls.sv", "anchor": "end", "text": "always_comb v = 1;"}); + refused(&tree, &mut server, "insert_item", args, "cannot stand in a class's scope"); + let args = json!({"file": "rtl/cls.sv", "anchor": "v", "text": "assign v = 1;"}); + refused(&tree, &mut server, "insert_item", args, "cannot stand in a class's scope"); + let args = json!({"file": "rtl/cls.sv", "anchor": "end", "text": "module inner; endmodule"}); + refused(&tree, &mut server, "insert_item", args, "would not survive"); + let args = json!({"file": "rtl/cls.sv", "anchor": "v", "text": "int v;"}); + refused(&tree, &mut server, "insert_item", args, "`v` would be declared twice"); + let method = " function void g();\n endfunction"; + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/cls.sv", "anchor": "end", "text": method}), + ); + assert!(strict(&tree.read("rtl/cls.sv"))); +} + +#[test] +fn qa_half_an_item_and_a_new_parse_error_in_a_broken_file_are_refused() { + let broken = "module br;\n logic a;\n assign = ;\n logic b;\nendmodule\n"; + let tree = Tree::with(false, &[("rtl/e.sv", "module e;\nendmodule\n"), ("rtl/br.sv", broken)]); + let mut server = Session::over(&tree); + for text in ["logic t;\nlogic", "logic t; assign t =", "always_comb begin"] { + let args = json!({"file": "rtl/e.sv", "anchor": "end", "text": text}); + refused(&tree, &mut server, "insert_item", args, "no longer parse"); + } + for text in ["logic c = ;", "assign b = 1;\nassign = ;"] { + let args = json!({"file": "rtl/br.sv", "anchor": "b", "text": text}); + refused( + &tree, + &mut server, + "insert_item", + args, + "already had 1 parse error(s) and would have 2", + ); + } + let args = json!({"file": "rtl/br.sv", "item": "a", "text": "logic a; assign ="}); + refused(&tree, &mut server, "replace_item", args, "open and close"); + // The control: a clean item into the broken file. + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/br.sv", "anchor": "b", "text": " logic c;"}), + ); +} + +#[test] +fn qa_the_same_insert_twice_inserts_again_unless_it_would_declare_twice() { + let tree = Tree::with(false, &[("rtl/z.sv", "module z;\n logic a;\nendmodule")]); + let mut server = Session::over(&tree); + let decl = json!({"file": "rtl/z.sv", "anchor": "a", "text": " logic dup;"}); + accepted(&mut server, "insert_item", decl.clone()); + refused(&tree, &mut server, "insert_item", decl, "`dup` would be declared twice"); + let assign = json!({"file": "rtl/z.sv", "anchor": "a", "text": " assign dup = 1'b1;"}); + accepted(&mut server, "insert_item", assign.clone()); + accepted(&mut server, "insert_item", assign); + let text = tree.read("rtl/z.sv"); + assert_eq!(text.matches("assign dup").count(), 2); + // The file had no final line ending; it still has none after `endmodule`. + assert!(text.ends_with("endmodule"), "{text:?}"); +} + +#[test] +fn qa_inserts_before_the_first_and_after_the_last_item_keep_the_blank_line_policy() { + let src = "module s;\n logic a;\n logic b;\nendmodule\n"; + let tree = Tree::with(false, &[("rtl/s.sv", src)]); + let mut server = Session::over(&tree); + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/s.sv", "anchor": "a", "position": "before", "text": " logic f;"}), + ); + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/s.sv", "anchor": "b", "text": " logic l;"}), + ); + assert_eq!( + tree.read("rtl/s.sv"), + "module s;\n logic f;\n\n logic a;\n logic b;\n\n logic l;\nendmodule\n" + ); +} + +// ---- 3. delete_item ------------------------------------------------------ + +const MAC: &str = "`define ID(x) x +`define ASSERT_KNOWN(n, s) initial assert (!$isunknown(s)); +`define IN_BODY in_body +module mac (output logic out); + logic in_expr; + logic in_stmt; + logic in_item; + logic in_body; + logic hier_target; + logic bind_target; + assign out = `ID(in_expr); + always_comb begin + `ID(in_stmt) = 1'b0; + end + `ASSERT_KNOWN(k, in_item) + initial $display(`IN_BODY); +endmodule +"; +const TOP: &str = "module top;\n mac u_mac ();\n wire w = u_mac.hier_target;\nendmodule\n"; +const BIND: &str = + "module chk (input logic s);\nendmodule\nbind mac chk u_chk (.s(bind_target));\n"; + +#[test] +fn qa_a_use_in_another_file_or_a_bind_refuses_the_delete() { + let tree = + Tree::with(false, &[("rtl/mac.sv", MAC), ("rtl/top.sv", TOP), ("rtl/bind.sv", BIND)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/mac.sv", "item": "hier_target"}); + refused(&tree, &mut server, "delete_item", args, "rtl/top.sv:3:18 `hier_target`"); + let args = json!({"file": "rtl/mac.sv", "item": "bind_target"}); + refused(&tree, &mut server, "delete_item", args, "rtl/bind.sv:3:24 `bind_target`"); + let forced = json!({"file": "rtl/mac.sv", "item": "hier_target", "force": true}); + let answer = accepted(&mut server, "delete_item", forced); + assert!(answer.contains("deleted with references left: rtl/top.sv:3:18"), "{answer}"); +} + +/// QA finding 3: a name used only in a macro argument (`` `ID(x) ``, +/// `` `ASSERT_KNOWN(n, x) `` — the OpenTitan pattern) or only in a macro +/// body (`` `define IN_BODY in_body ``) is deleted without a word: the +/// engine returns no use there, and the whole-word prefilter that saw the +/// spelling does not count it. +#[test] +fn qa_a_use_inside_a_macro_argument_refuses_the_delete() { + let tree = Tree::with(false, &[("rtl/mac.sv", MAC)]); + let mut server = Session::over(&tree); + for name in ["in_expr", "in_stmt", "in_item", "in_body"] { + let args = json!({"file": "rtl/mac.sv", "item": name}); + refused(&tree, &mut server, "delete_item", args, "still referenced"); + } +} + +#[test] +fn qa_a_forced_non_ansi_port_delete_still_parses_and_the_last_item_leaves_an_empty_module() { + let non_ansi = + "module k (a, b);\n input [3:0] a;\n output b;\n assign b = 1'b0;\nendmodule\n"; + let last = "module l;\n logic a;\n logic b;\nendmodule\n"; + let tree = Tree::with(false, &[("rtl/k.sv", non_ansi), ("rtl/l.sv", last)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/k.sv", "item": "a"}); + refused(&tree, &mut server, "delete_item", args, "`a` is also declared on line 1"); + let answer = accepted( + &mut server, + "delete_item", + json!({"file": "rtl/k.sv", "item": "a", "force": true}), + ); + assert!(answer.contains("warnings:"), "{answer}"); + assert!(strict(&tree.read("rtl/k.sv"))); + accepted(&mut server, "delete_item", json!({"file": "rtl/l.sv", "item": "b"})); + accepted(&mut server, "delete_item", json!({"file": "rtl/l.sv", "item": "a"})); + assert_eq!(tree.read("rtl/l.sv"), "module l;\nendmodule\n"); + let args = json!({"file": "rtl/l.sv", "item": "a"}); + refused(&tree, &mut server, "delete_item", args, "no declaration matches `a`"); +} + +const COMMENTS: &str = "// File banner: module m does things. + +module m; + // Section: registers + // (applies to everything below) + + // the a flop + logic a; + logic b; // b's trailing + // belongs to c + logic c; + logic d; /* trailing d + continues */ + logic e; +endmodule +"; + +#[test] +fn qa_a_comment_between_two_items_goes_with_the_item_it_leads() { + let tree = Tree::with(false, &[("rtl/m.sv", COMMENTS)]); + let mut server = Session::over(&tree); + accepted(&mut server, "delete_item", json!({"file": "rtl/m.sv", "item": "b"})); + let text = tree.read("rtl/m.sv"); + assert!(!text.contains("b's trailing") && text.contains(" // belongs to c\n logic c;")); + accepted(&mut server, "delete_item", json!({"file": "rtl/m.sv", "item": "c"})); + accepted(&mut server, "delete_item", json!({"file": "rtl/m.sv", "item": "d"})); + let text = tree.read("rtl/m.sv"); + assert!(!text.contains("belongs to c") && !text.contains("continues */"), "{text}"); + assert!(text.contains(" logic a;\n logic e;\nendmodule\n"), "{text}"); +} + +/// QA finding 4: `delete_item` takes every comment of `Meta::leading`, even +/// one a blank line separates from the item — a section banner, or the +/// file's header comment when the item is the module. +#[test] +fn qa_a_comment_a_blank_line_separates_from_the_item_is_not_deleted() { + let tree = Tree::with(false, &[("rtl/m.sv", COMMENTS)]); + let mut server = Session::over(&tree); + let (error, answer, _) = + server.call("delete_item", json!({"file": "rtl/m.sv", "item": "a", "dry_run": true})); + assert!(!error, "{answer}"); + assert!(!answer.contains("- // Section: registers"), "{answer}"); + assert!(answer.contains("- // the a flop"), "{answer}"); + let (error, answer, _) = + server.call("delete_item", json!({"file": "rtl/m.sv", "item": "m", "dry_run": true})); + assert!(!error, "{answer}"); + assert!(!answer.contains("-// File banner"), "{answer}"); +} + +#[test] +fn qa_deleting_an_else_branch_label_names_both_labels() { + let tree = Tree::with(false, &[("rtl/g.sv", GEN)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/g.sv", "item": "gen_b", "dry_run": true}); + let answer = accepted(&mut server, "delete_item", args); + assert!(answer.contains("deleted generate `gen_a`, `gen_b`"), "{answer}"); + let args = json!({"file": "rtl/g.sv", "item": "gen_a"}); + refused(&tree, &mut server, "delete_item", args, "part of a larger item"); +} + +#[test] +fn qa_an_item_inside_a_guard_is_deleted_and_the_guard_stays_balanced() { + let guarded = "module g;\n`ifdef FAST\n logic a;\n`endif\n logic b;\nendmodule\n"; + let tree = Tree::with(false, &[("rtl/g.sv", guarded)]); + let mut server = Session::over(&tree); + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/g.sv", "item": "a", "text": "logic [1:0] a;"}), + ); + accepted(&mut server, "delete_item", json!({"file": "rtl/g.sv", "item": "a"})); + assert_eq!(tree.read("rtl/g.sv"), "module g;\n`ifdef FAST\n`endif\n logic b;\nendmodule\n"); +} + +// ---- 4. the prefix/suffix guarantee over a run of accepted calls ---------- + +#[test] +fn qa_every_accepted_call_changes_only_its_own_region() { + let tree = Tree::with(true, &[("rtl/g.sv", GEN)]); + let mut server = Session::over(&tree); + let replaces = [ + // No comment in the text: the replaced bytes are read_item's span + // (a commented text widens it — ruling 2, its own test below). + ("rtl/core.sv", "r", "logic [15:0] r;"), + ("rtl/core.sv", "always@22", "always_comb p = ^r;"), + ("rtl/core.sv", "always@13", "always_ff @(posedge clk)\n r <= d;"), + ("rtl/item_pkg.sv", "spare", "function automatic logic spare(logic a);\n return !a;\n endfunction"), + ("rtl/wrap.sv", "u_core", "core u_core (.clk, .rst_ni, .d, .q);"), + ("rtl/g.sv", "gen_l", "for (genvar i = 0; i < 4; i++) begin : gen_l\n logic z;\n always_comb z = a;\n end"), + ("rtl/tick.sv", "tick", "module tick (\n input logic clk\n);\n logic unused;\nendmodule"), + ]; + for (file, item, text) in replaces { + let old = tree.read(file); + let span = span_of(&mut server, &old, file, item); + accepted(&mut server, "replace_item", json!({"file": file, "item": item, "text": text})); + only_region_changed(&old, &tree.read(file), span); + } + let inserts = [ + ("rtl/core.sv", "p", "before"), + ("rtl/core.sv", "p", "after"), + ("rtl/item_pkg.sv", "WIDTH", "after"), + ("rtl/g.sv", "c", "before"), + ]; + for (file, anchor, position) in inserts { + let old = tree.read(file); + let span = span_of(&mut server, &old, file, anchor); + let args = json!({"file": file, "anchor": anchor, "position": position, "text": " logic qa_new;"}); + accepted(&mut server, "insert_item", args); + let new = tree.read(file); + // A pure insertion, at a line start, before or after the anchor. + let at = if position == "before" { (0, span.0) } else { (span.1, old.len()) }; + only_region_changed(&old, &new, at); + assert!(new.len() > old.len() && new.contains(" logic qa_new;\n"), "{new}"); + assert!(strict(&new), "{new}"); + let old = new; + let span = span_of(&mut server, &old, file, "qa_new"); + accepted(&mut server, "delete_item", json!({"file": file, "item": "qa_new"})); + let new = tree.read(file); + let prefix = old.bytes().zip(new.bytes()).take_while(|(a, b)| a == b).count(); + let removed = old.len() - new.len(); + assert!(prefix <= span.0 && span.1 <= prefix + removed, "qa_new: {prefix}+{removed}"); + assert_eq!(&old[prefix + removed..], &new[prefix..]); + } + for (file, item) in + [("rtl/item_pkg.sv", "spare"), ("rtl/g.sv", "d"), ("rtl/core.sv", "always@13")] + { + let old = tree.read(file); + let span = span_of(&mut server, &old, file, item); + accepted(&mut server, "delete_item", json!({"file": file, "item": item, "force": true})); + let new = tree.read(file); + only_region_changed(&old, &new, (0, old.len())); + // The removed bytes are one run that covers the item. + let prefix = old.bytes().zip(new.bytes()).take_while(|(a, b)| a == b).count(); + let removed = old.len() - new.len(); + assert!( + prefix <= span.0 && span.1 <= prefix + removed, + "{item}: {prefix}+{removed} vs {span:?}" + ); + assert_eq!(&old[..prefix], &new[..prefix]); + assert_eq!(&old[prefix + removed..], &new[prefix..]); + } +} + +// ---- 5. many edits in a row ---------------------------------------------- + +#[test] +fn qa_two_hundred_replaces_in_a_row_each_verified_and_repeatable() { + let mut src = String::from("module many (input logic clk);\n"); + for n in 0..100 { + src.push_str(&format!(" logic s{n};\n always_ff @(posedge clk) s{n} <= ~s{n};\n")); + } + src.push_str("endmodule\n"); + let tree = Tree::with(false, &[("rtl/many.sv", &src)]); + let mut server = Session::over(&tree); + for n in 0..100 { + for (item, text) in [ + (format!("s{n}"), format!("logic [1:0] s{n};")), + ( + format!("always@{}", 3 + 2 * n), + format!("always_ff @(posedge clk) s{n} <= s{n} + 2'd1;"), + ), + ] { + let old = tree.read("rtl/many.sv"); + let span = span_of(&mut server, &old, "rtl/many.sv", &item); + let args = json!({"file": "rtl/many.sv", "item": item, "text": text}); + accepted(&mut server, "replace_item", args.clone()); + let new = tree.read("rtl/many.sv"); + only_region_changed(&old, &new, span); + assert!(strict(&new), "{item}"); + assert!(accepted(&mut server, "replace_item", args).starts_with("unchanged"), "{item}"); + assert_eq!(tree.read("rtl/many.sv"), new); + } + } +} + +// ---- findings of low severity --------------------------------------------- + +/// QA finding 5: an item with a block comment before it on its own line +/// (`/* lead */ logic a;` — exactly what a `replace_item` text with a +/// leading comment leaves) can be neither deleted nor used as an anchor: +/// "shares a line with other code (run `format` first)", and `format` keeps +/// the comment on that line. +#[test] +fn qa_an_item_led_by_a_block_comment_on_its_line_owns_that_line() { + let src = "module b;\n /* lead */ logic a;\n logic c;\nendmodule\n"; + let tree = Tree::with(false, &[("rtl/b.sv", src)]); + let mut server = Session::over(&tree); + let args = + json!({"file": "rtl/b.sv", "anchor": "a", "position": "before", "text": " logic z;"}); + accepted(&mut server, "insert_item", args); + accepted(&mut server, "delete_item", json!({"file": "rtl/b.sv", "item": "a"})); + assert_eq!(tree.read("rtl/b.sv"), "module b;\n logic z;\n\n logic c;\nendmodule\n"); +} + +/// QA finding 6 (a ruling for the lead): a `` `undef `` or `` `define `` +/// nested inside a replaced item is one item, so it is accepted — and it +/// changes code outside the span (`` `W `` below it is now undefined). The +/// README lists "the effect of directives the agent writes" as deliberately +/// not checked; this pins the stricter reading (a replace may not add a +/// macro definition or undefinition the old item did not have). +#[test] +fn qa_a_macro_directive_nested_in_a_replaced_item_is_refused() { + let tree = Tree::with(false, &[("rtl/m.sv", M)]); + let mut server = Session::over(&tree); + for directive in ["`undef W", "`define W 1'b0"] { + let text = format!("always_comb begin\n{directive}\n a = 1'b0;\n end"); + let args = json!({"file": "rtl/m.sv", "item": "always@5", "text": text}); + refused(&tree, &mut server, "replace_item", args, "`W"); + } +} + +// ---- resumed run: the rest of the attack list ------------------------------- + +const MISC: &str = "`define W 1'b1 +module misc (output logic o); + logic q; + logic w; + initial $display(\"a\"); + + always_comb begin + w = 1'b0; + end + assign o = `W; +endmodule +"; + +#[test] +fn qa_a_string_or_a_comment_spelling_code_is_only_text() { + let tree = Tree::with(false, &[("rtl/misc.sv", MISC)]); + let mut server = Session::over(&tree); + let cases = [ + ("initial@5", "initial $display(\"endmodule\\nmodule x; `ifdef\");"), + ("always@7", "// `ifdef X -- a comment\nalways_comb begin\n w = 1'b1;\n end"), + // The comment the case above wrote moved the always one line down. + ("always@8", "always_comb begin\n /* `endif */ w = 1'b0; // endmodule\n end"), + ]; + for (item, text) in cases { + let old = tree.read("rtl/misc.sv"); + let span = span_of(&mut server, &old, "rtl/misc.sv", item); + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/misc.sv", "item": item, "text": text}), + ); + let new = tree.read("rtl/misc.sv"); + only_region_changed(&old, &new, span); + assert!(strict(&new) && new.contains(text), "{new}"); + } +} + +#[test] +fn qa_a_directive_nested_in_an_always_must_balance_inside_the_text() { + let tree = Tree::with(false, &[("rtl/misc.sv", MISC)]); + let mut server = Session::over(&tree); + for (text, word) in [ + ("always_comb begin\n`ifdef X\n w = 1'b0;\n end", "`ifdef`"), + ("always_comb begin\n`endif\n w = 1'b0;\n`ifdef X\n end", "`endif`"), + ("always_comb begin\n`else\n w = 1'b0;\n end", "`else`"), + ] { + let args = json!({"file": "rtl/misc.sv", "item": "always@7", "text": text}); + refused(&tree, &mut server, "replace_item", args, word); + } + let balanced = + "always_comb begin\n`ifdef X\n w = 1'b1;\n`else\n w = 1'b0;\n`endif\n end"; + let args = json!({"file": "rtl/misc.sv", "item": "always@7", "text": balanced}); + accepted(&mut server, "replace_item", args); + assert!(strict(&tree.read("rtl/misc.sv"))); +} + +#[test] +fn qa_a_line_continued_directive_cannot_swallow_the_code_below_it() { + let tree = Tree::with(false, &[("rtl/misc.sv", MISC)]); + let mut server = Session::over(&tree); + // At `end` the next line is `endmodule`: swallowed, so refused. + let args = json!({"file": "rtl/misc.sv", "anchor": "end", "text": " `define CONT 1 \\"}); + refused(&tree, &mut server, "insert_item", args, "no longer parse"); + // Between items the continuation takes only the blank line the insert + // itself adds; every item survives. + let old = tree.read("rtl/misc.sv"); + let args = json!({"file": "rtl/misc.sv", "anchor": "q", "text": " `define CONT 1 \\"}); + accepted(&mut server, "insert_item", args); + let new = tree.read("rtl/misc.sv"); + assert!(new.contains(" `define CONT 1 \\\n\n logic w;\n"), "{new}"); + assert_eq!(new.replacen("\n `define CONT 1 \\\n\n", "", 1), old); +} + +#[test] +fn qa_a_forced_delete_leaves_uses_that_diagnostics_reports() { + let src = "module m (output logic o);\n logic q;\n assign o = q;\nendmodule\n"; + let tree = Tree::with(false, &[("rtl/m.sv", src)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/m.sv", "item": "q"}); + refused(&tree, &mut server, "delete_item", args, "still referenced: rtl/m.sv:3:14 `q`"); + let answer = accepted( + &mut server, + "delete_item", + json!({"file": "rtl/m.sv", "item": "q", "force": true}), + ); + assert!(answer.contains("deleted with references left: rtl/m.sv:3:14 `q`"), "{answer}"); + let (_, diagnostics, _) = server.call("diagnostics", json!({"file": "rtl/m.sv"})); + assert!(diagnostics.contains("`q` is declared nowhere"), "{diagnostics}"); +} + +#[test] +fn qa_a_trailing_comment_running_into_the_next_line_stays_with_its_item() { + let tree = Tree::with(false, &[("rtl/m.sv", COMMENTS)]); + let mut server = Session::over(&tree); + let old = tree.read("rtl/m.sv"); + accepted(&mut server, "delete_item", json!({"file": "rtl/m.sv", "item": "e"})); + assert_eq!(tree.read("rtl/m.sv"), old.replace(" logic e;\n", "")); + let args = json!({"file": "rtl/m.sv", "anchor": "d", "text": " logic n;"}); + accepted(&mut server, "insert_item", args); + let text = tree.read("rtl/m.sv"); + assert!( + text.contains(" logic d; /* trailing d\n continues */\n\n logic n;\nendmodule"), + "{text}" + ); +} + +#[test] +fn qa_the_line_after_a_fence_is_not_an_insertion_point() { + let tree = Tree::with(true, &[]); + let mut server = Session::over(&tree); + for (anchor, position) in [("keep_me", "before"), ("keep_me", "after")] { + let args = json!({"file": "rtl/core.sv", "anchor": anchor, "position": position, "text": " logic y;"}); + refused(&tree, &mut server, "insert_item", args, "fence"); + } + let args = json!({"file": "rtl/core.sv", "item": "keep_me", "text": "logic keep_me;"}); + refused(&tree, &mut server, "replace_item", args, "fence"); + let args = json!({"file": "rtl/core.sv", "item": "keep_me", "force": true}); + refused(&tree, &mut server, "delete_item", args, "fence"); +} + +/// QA finding 7: a text may carry a fence marker. `// lucisv: off` with no +/// `on` fences everything below it — code outside the span that `format`, +/// `delete_item` and the rest now refuse to touch. +#[test] +fn qa_a_text_carrying_a_fence_marker_is_refused() { + let tree = Tree::with(false, &[("rtl/misc.sv", MISC)]); + let mut server = Session::over(&tree); + let args = + json!({"file": "rtl/misc.sv", "anchor": "q", "text": " // lucisv: off\n logic lo;"}); + refused(&tree, &mut server, "insert_item", args, "fence"); + let args = json!({"file": "rtl/misc.sv", "item": "q", "text": "logic q; // lucisv: off"}); + refused(&tree, &mut server, "replace_item", args, "fence"); +} + +const SUB: &str = "module sub (input logic clk, input logic en, output logic o); + assign o = clk & en; +endmodule +"; +const STAR: &str = "module star; + logic clk; + logic en; + logic o; + sub u_sub (.*); +endmodule +"; + +/// QA finding 8: a signal used only through a `.*` implicit connection is +/// deleted without a word — `find_references` drops the `.*` span (it does +/// not slice back to the name), and the instance no longer elaborates. +#[test] +fn qa_a_signal_bound_only_by_a_dot_star_refuses_the_delete() { + let tree = Tree::with(false, &[("rtl/sub.sv", SUB), ("rtl/star.sv", STAR)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/star.sv", "item": "en"}); + refused(&tree, &mut server, "delete_item", args, "still referenced"); +} + +// ---- re-check of the rework (2026-09-23): the new rules attacked ------------ + +/// Lead ruling: a text ending in a trailing comment widens the replaced span +/// over the item's own trailing comment — exactly that, nothing else — and +/// the same call again is `unchanged`. +#[test] +fn qa_recheck_a_commented_text_replaces_exactly_the_widened_span() { + let tree = Tree::with(true, &[]); + let mut server = Session::over(&tree); + let old = tree.read("rtl/core.sv"); + let (start, _) = span_of(&mut server, &old, "rtl/core.sv", "r"); + let trailing = "// the register"; + let end = old.find(trailing).unwrap() + trailing.len(); + assert_eq!(&old[start..end], "logic [7:0] r; // the register"); + let text = "logic [15:0] r; /* wider */"; + let args = json!({"file": "rtl/core.sv", "item": "r", "text": text}); + accepted(&mut server, "replace_item", args.clone()); + let new = tree.read("rtl/core.sv"); + assert_eq!(new, format!("{}{text}{}", &old[..start], &old[end..])); + assert!(accepted(&mut server, "replace_item", args).starts_with("unchanged")); + assert_eq!(tree.read("rtl/core.sv"), new); + // Two comments either side repeat just as well. + for (item, text) in [("p", "/* x */ /* y */\nlogic p;"), ("p", "logic p; /* a */ /* b */")] { + let args = json!({"file": "rtl/core.sv", "item": item, "text": text}); + accepted(&mut server, "replace_item", args.clone()); + let once = tree.read("rtl/core.sv"); + assert!(accepted(&mut server, "replace_item", args).starts_with("unchanged"), "{text}"); + assert_eq!(tree.read("rtl/core.sv"), once); + } +} + +const OWN: &str = "module w; + logic a;logic b; + logic c; // c trailing + // banner + + // own one + // own two + logic d; // d trailing + logic e; + // lucisv: off + logic f; + // lucisv: on + logic z; +endmodule +"; + +#[test] +fn qa_recheck_a_leading_comment_widens_over_exactly_the_items_own_comments() { + let tree = Tree::with(false, &[("rtl/w.sv", OWN)]); + let mut server = Session::over(&tree); + let text = "/* new doc */\nlogic [1:0] d;"; + let args = json!({"file": "rtl/w.sv", "item": "d", "text": text}); + accepted(&mut server, "replace_item", args.clone()); + // The two own lines go; the banner above the blank line and the + // trailing comment (the text has none) stay. + let want = OWN.replace("// own one\n // own two\n logic d;", text); + assert_eq!(tree.read("rtl/w.sv"), want); + assert!(accepted(&mut server, "replace_item", args).starts_with("unchanged")); + // A comment trailing the item above is not the next item's own. + let text = "// doc e\nlogic e;"; + accepted(&mut server, "replace_item", json!({"file": "rtl/w.sv", "item": "e", "text": text})); + assert_eq!(tree.read("rtl/w.sv"), want.replace("logic e;", text)); +} + +#[test] +fn qa_recheck_a_text_glued_to_the_code_after_it_is_refused() { + let tree = Tree::with(false, &[("rtl/w.sv", OWN)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/w.sv", "item": "a", "text": "logic a;x"}); + refused(&tree, &mut server, "replace_item", args, "rule 1b"); + for (item, text) in [("a", "logic a"), ("c", "logic c")] { + let args = json!({"file": "rtl/w.sv", "item": item, "text": text}); + refused(&tree, &mut server, "replace_item", args, "no longer parse"); + } + // A comment left on a line of its own at the text's end would lead the + // next item: refused, for replace and for insert. + let args = json!({"file": "rtl/w.sv", "item": "e", "text": "logic e;\n// dangling"}); + refused(&tree, &mut server, "replace_item", args, "rule 1b"); + let args = json!({"file": "rtl/w.sv", "anchor": "c", "text": " logic n;\n // dangling"}); + refused(&tree, &mut server, "insert_item", args, "rule 1b"); +} + +#[test] +fn qa_recheck_rule_1a_refuses_what_is_left_open_and_only_that() { + let tree = Tree::with(false, &[("rtl/misc.sv", MISC)]); + let mut server = Session::over(&tree); + for text in ["initial $display(\"open);", "initial $display(\"x\"); /* open"] { + let args = json!({"file": "rtl/misc.sv", "item": "initial@5", "text": text}); + // The whole-file lex refuses first when nothing below closes it. + refused(&tree, &mut server, "replace_item", args, "lex"); + } + // A `*/` below would close the open comment inside the file: rule 1a. + let closes_later = "initial $display(\"x\"); /* open"; + fs::write(tree.0.join("rtl/misc.sv"), format!("{MISC}/* closes */\n")).unwrap(); + let args = json!({"file": "rtl/misc.sv", "item": "initial@5", "text": closes_later}); + refused(&tree, &mut server, "replace_item", args, "rule 1a"); + // Comment markers inside a string are not a comment. + let text = "initial $display(\"/* not a comment */ // nor this\");"; + let old = tree.read("rtl/misc.sv"); + let span = span_of(&mut server, &old, "rtl/misc.sv", "initial@5"); + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/misc.sv", "item": "initial@5", "text": text}), + ); + only_region_changed(&old, &tree.read("rtl/misc.sv"), span); +} + +#[test] +fn qa_recheck_a_fence_marker_is_neither_written_nor_widened_over() { + let tree = Tree::with(false, &[("rtl/w.sv", OWN)]); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/w.sv", "item": "e", "text": "logic e; // lucisv: off"}); + refused(&tree, &mut server, "replace_item", args, "rule 7"); + let args = json!({"file": "rtl/w.sv", "item": "e", "text": "// verilog_format: on\nlogic e;"}); + refused(&tree, &mut server, "replace_item", args, "rule 7"); + // `z`'s own leading comment is the `on` marker: a commented text would + // widen over it — refused; the plain text replaces the item alone. + let args = json!({"file": "rtl/w.sv", "item": "z", "text": "// doc z\nlogic z;"}); + refused(&tree, &mut server, "replace_item", args, "fence"); + accepted( + &mut server, + "replace_item", + json!({"file": "rtl/w.sv", "item": "z", "text": "logic [1:0] z;"}), + ); + assert_eq!(tree.read("rtl/w.sv"), OWN.replace(" logic z;", " logic [1:0] z;")); + // The item just above the `off` marker goes; the marker stays. + accepted(&mut server, "delete_item", json!({"file": "rtl/w.sv", "item": "e"})); + assert!(tree.read("rtl/w.sv").contains(" logic d; // d trailing\n // lucisv: off\n")); +} + +const SPELL: &str = "`define SUBSTR sig_x + xsig + sig_ +`define FORMAL(sig) sig + 1 +`define STR \"sig\" +`define ASSERT(n, e) initial assert (e); +module s; + logic sig; + logic hsig; + logic nsig; + logic isig; + logic plain; + if (1) begin : g1 + if (1) begin : g2 + na u_na (.*); + end + end + ifc u_ifc (.*); +endmodule +"; +const NA: &str = + "module na (nsig, o);\n input nsig;\n output o;\n assign o = nsig;\nendmodule\n"; +const IFC: &str = "interface ifc (input logic isig);\n logic v;\nendinterface\n"; +const HIER: &str = "module top;\n s u_s ();\n `ASSERT(chk, u_s.hsig)\nendmodule\n"; + +fn spell_tree() -> Tree { + Tree::with( + false, + &[("rtl/s.sv", SPELL), ("rtl/na.sv", NA), ("rtl/ifc.sv", IFC), ("rtl/top.sv", HIER)], + ) +} + +#[test] +fn qa_recheck_a_define_body_spelling_the_name_only_as_a_substring_is_no_use() { + let tree = spell_tree(); + let mut server = Session::over(&tree); + // `sig_x`, `xsig`, `sig_`, a formal `sig` and a string "sig": no use. + let answer = accepted(&mut server, "delete_item", json!({"file": "rtl/s.sv", "item": "sig"})); + assert!(!answer.contains("warnings"), "{answer}"); + assert!(!tree.read("rtl/s.sv").contains("logic sig;")); +} + +#[test] +fn qa_recheck_a_hierarchical_path_in_a_macro_argument_is_a_possible_use() { + let tree = spell_tree(); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/s.sv", "item": "hsig"}); + refused(&tree, &mut server, "delete_item", args, "possible use (macro) at rtl/top.sv:3 `hsig`"); +} + +#[test] +fn qa_recheck_a_dot_star_in_a_nested_generate_block_binds() { + let tree = spell_tree(); + let mut server = Session::over(&tree); + // `na` declares its ports non-ANSI; the `.*` sits two generate levels down. + let args = json!({"file": "rtl/s.sv", "item": "nsig"}); + refused( + &tree, + &mut server, + "delete_item", + args, + "bound by `.*` at rtl/s.sv:13:16 `nsig` (module `na`)", + ); +} + +#[test] +fn qa_recheck_a_dot_star_into_an_interface_instance_binds_and_a_stranger_does_not() { + let tree = spell_tree(); + let mut server = Session::over(&tree); + let args = json!({"file": "rtl/s.sv", "item": "isig"}); + refused( + &tree, + &mut server, + "delete_item", + args, + "bound by `.*` at rtl/s.sv:16:14 `isig` (module `ifc`)", + ); + // Neither `na` nor `ifc` has a port `plain`: deleted. + accepted(&mut server, "delete_item", json!({"file": "rtl/s.sv", "item": "plain"})); + // A `.*` into a module nobody declares may bind anything. + let unknown = SPELL.replace(" ifc u_ifc (.*);", " ifc u_ifc (.*);\n nowhere u_nw (.*);"); + fs::write(tree.0.join("rtl/s.sv"), unknown).unwrap(); + let args = json!({"file": "rtl/s.sv", "item": "plain"}); + refused( + &tree, + &mut server, + "delete_item", + args, + "possible use (`.*`) at rtl/s.sv:17:17 `plain`", + ); +} + +const DEF: &str = "`define W 1'b1 +module d (output logic o); + `define LOCAL 2 + logic q; + logic w; + always_comb w = 1'b0; + assign o = `W; +endmodule +"; + +#[test] +fn qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always() { + let tree = Tree::with(false, &[("rtl/d.sv", DEF)]); + let mut server = Session::over(&tree); + let nested = " always_comb begin\n`define W 1'b0\n w = 1'b1;\n end"; + let args = json!({"file": "rtl/d.sv", "anchor": "q", "text": nested}); + refused(&tree, &mut server, "insert_item", args, "rule 6"); + let undef = "always_comb begin\n`undef W\n w = 1'b1;\n end"; + let args = json!({"file": "rtl/d.sv", "item": "always@6", "text": undef}); + refused(&tree, &mut server, "replace_item", args, "rule 6"); + // Deleting the module deletes its nested `define LOCAL: refused, even + // forced (a define item is not selectable, so no tool removes one). + for force in [false, true] { + let args = json!({"file": "rtl/d.sv", "item": "d", "force": force}); + refused(&tree, &mut server, "delete_item", args, "rule 6"); + } + let args = json!({"file": "rtl/d.sv", "item": "LOCAL"}); + refused(&tree, &mut server, "delete_item", args, "no declaration matches `LOCAL`"); + // A directive item at the region's own level is the exemption. + for text in [" `define W2 1'b0\n logic r;", " `undef W2"] { + accepted( + &mut server, + "insert_item", + json!({"file": "rtl/d.sv", "anchor": "q", "text": text}), + ); + } + assert!(strict(&tree.read("rtl/d.sv"))); +} diff --git a/crates/lucisv_mcp/tests/wire.rs b/crates/lucisv_mcp/tests/wire.rs index fbaf8cb..1d1c5fd 100644 --- a/crates/lucisv_mcp/tests/wire.rs +++ b/crates/lucisv_mcp/tests/wire.rs @@ -198,14 +198,24 @@ fn tools_list_describes_every_tool_for_the_agent() { "remove_port", "add_port", "extract_module", + "replace_item", + "insert_item", + "delete_item", "instantiate" ] ); assert!(reply["result"].get("nextCursor").is_none()); // The edit tools write; those whose second identical call writes nothing // more say so. `instantiate` only answers with text. - let idempotent_edits = - ["format", "fix_lint", "expand_wildcard", "convert_ports", "organize_imports"]; + let idempotent_edits = [ + "format", + "fix_lint", + "expand_wildcard", + "convert_ports", + "organize_imports", + "replace_item", + "delete_item", + ]; for tool in tools { let name = tool["name"].as_str().unwrap(); let edits = names.iter().position(|n| *n == name).unwrap() >= 11 && name != "instantiate"; @@ -1087,3 +1097,196 @@ fn instantiate_takes_only_an_identifier_for_the_instance() { assert!(said.starts_with("`instance` must be one identifier"), "{bad}: {said}"); } } + +// --------------------------------------------------------------------------- +// M4: the structural edits, over a fresh copy of `tests/fixtures/item`. +// --------------------------------------------------------------------------- + +/// A server over a fresh copy of the item fixture. +fn item_tree() -> (Tree, Session) { + let tree = Tree::of("item"); + let mut server = Session::over(&tree); + server.initialize(); + (tree, server) +} + +/// A dry run shows the diff of `file` and writes nothing; the real call +/// writes `file` and nothing else. Returns the real call's text. +fn preview_then_write(server: &mut Session, tree: &Tree, tool: &str, args: &Value) -> String { + let file = args["file"].as_str().unwrap().to_string(); + let pristine = snapshot(tree); + let preview = server.text(tool, dry(args, true)); + assert!(preview.contains("(dry run: nothing written)"), "{tool}: {preview}"); + assert!(preview.contains(&format!("--- {file}\n")), "{tool}: {preview}"); + assert!(moved(&pristine, &snapshot(tree)).is_empty(), "{tool}: a dry run wrote"); + let applied = server.text(tool, dry(args, false)); + assert!(applied.starts_with("files: 1 changed, 0 created\n"), "{tool}: {applied}"); + assert!(applied.contains("hint: run `format` with") || tool == "delete_item", "{applied}"); + assert_eq!(moved(&pristine, &snapshot(tree)), [file], "{tool}: {applied}"); + applied +} + +fn read(tree: &Tree, file: &str) -> String { + fs::read_to_string(tree.path(file)).unwrap() +} + +#[test] +fn replace_item_changes_only_the_item_and_read_item_returns_the_new_text() { + let (tree, mut server) = item_tree(); + let original = read(&tree, "rtl/core.sv"); + let slice = server.call("read_item", json!({"file": "rtl/core.sv", "item": "always@12"})); + let old = slice["structuredContent"]["text"].as_str().unwrap().to_string(); + let at = original.find(&old).unwrap(); + let new = "always_ff @(posedge clk or negedge rst_ni)\n if (!rst_ni) r <= 8'h00;\n else r <= d;"; + let args = json!({"file": "rtl/core.sv", "item": "always@12", "text": new}); + let text = preview_then_write(&mut server, &tree, "replace_item", &args); + assert!(text.contains(" rtl/core.sv +1 -1\nreplaced always (lines 12-14)\n"), "{text}"); + // Not trusting the tool: the bytes before and after the item are the + // bytes that were there. + let written = read(&tree, "rtl/core.sv"); + assert_eq!(&written[..at], &original[..at]); + assert_eq!(&written[at + new.len()..], &original[at + old.len()..]); + let again = server.call("read_item", json!({"file": "rtl/core.sv", "item": "always@12"})); + assert_eq!(again["structuredContent"]["text"], new); + // The same call again, and the same text framed in blank space, are no-ops. + let before = snapshot(&tree); + assert_eq!(server.text("replace_item", args), "unchanged\n"); + let framed = + json!({"file": "rtl/core.sv", "item": "always@12", "text": format!(" {new}\n\n")}); + assert_eq!(server.text("replace_item", framed), "unchanged\n"); + assert_eq!(before, snapshot(&tree)); +} + +#[test] +fn replace_item_keeps_names_unless_rename_and_then_says_references_stay() { + let (tree, mut server) = item_tree(); + let before = snapshot(&tree); + let args = json!({"file": "rtl/core.sv", "item": "p", "text": "logic p_q;"}); + let said = refusal(&mut server, "replace_item", args.clone()); + assert!(said.contains("declares `p_q` where the item declared `p`"), "{said}"); + assert_eq!(before, snapshot(&tree)); + let mut renamed = args; + renamed["rename"] = Value::from(true); + let text = server.text("replace_item", renamed); + assert!(text.contains("replaced declaration `p_q` (lines 9)"), "{text}"); + assert!( + text.contains("warnings:\n `p` replaced by `p_q`: references are NOT updated"), + "{text}" + ); + assert!(read(&tree, "rtl/core.sv").contains(" // Parity of r.\n logic p_q;\n")); +} + +#[test] +fn insert_item_at_end_before_and_after_follows_the_blank_line_policy() { + let (tree, mut server) = item_tree(); + let original = read(&tree, "rtl/core.sv"); + let end = json!({"file": "rtl/core.sv", "anchor": "end", "text": " logic s;"}); + let text = preview_then_write(&mut server, &tree, "insert_item", &end); + assert!(text.contains("inserted declaration `s` (lines 24)"), "{text}"); + let expected = original.replace(");\nendmodule\n", ");\n\n logic s;\nendmodule\n"); + assert_eq!(read(&tree, "rtl/core.sv"), expected); + // Not idempotent: the same insertion again would declare `s` twice. + let twice = refusal(&mut server, "insert_item", end); + assert!(twice.contains("`s` would be declared twice"), "{twice}"); + + let after = json!({"file": "rtl/core.sv", "anchor": "r", "text": "\n\n logic t;\n"}); + preview_then_write(&mut server, &tree, "insert_item", &after); + let expected = expected + .replace("// the register\n // Parity", "// the register\n\n logic t;\n\n // Parity"); + assert_eq!(read(&tree, "rtl/core.sv"), expected); + + // Before an item goes above its leading comment; the blank line already + // there is not doubled. + let before = json!({"file": "rtl/core.sv", "anchor": "always@16", "position": "before", "text": "logic u;"}); + preview_then_write(&mut server, &tree, "insert_item", &before); + let expected = expected.replace( + " logic p;\n\n // Register", + " logic p;\n\nlogic u;\n\n // Register", + ); + assert_eq!(read(&tree, "rtl/core.sv"), expected); + + // `end@unit` in a package; the text may be several items. + let two = " localparam int A = 1;\n localparam int B = 2;"; + let pkg = json!({"file": "rtl/item_pkg.sv", "anchor": "end@item_pkg", "text": two}); + let text = server.text("insert_item", pkg); + assert!(text.contains("inserted declaration, declaration `A`, `B` (lines 14-15)"), "{text}"); + assert!(read(&tree, "rtl/item_pkg.sv").ends_with( + " endfunction\n\n localparam int A = 1;\n localparam int B = 2;\nendpackage\n" + )); +} + +#[test] +fn delete_item_refuses_a_live_reference_and_force_takes_its_leading_comment() { + let (tree, mut server) = item_tree(); + let original = read(&tree, "rtl/core.sv"); + let before = snapshot(&tree); + let args = json!({"file": "rtl/core.sv", "item": "p"}); + let said = refusal(&mut server, "delete_item", args.clone()); + assert!(said.starts_with("still referenced: rtl/core.sv:22:15 `p`; nothing written"), "{said}"); + // `core` holds a fenced region, which no tool deletes; the package is + // still named by `core`. + let module = + refusal(&mut server, "delete_item", json!({"file": "rtl/core.sv", "item": "core"})); + assert!(module.contains("`// lucisv: off` fence"), "{module}"); + let package = + refusal(&mut server, "delete_item", json!({"file": "rtl/item_pkg.sv", "item": "item_pkg"})); + assert!(package.contains("rtl/core.sv:22:19 `item_pkg`"), "{package}"); + let tick = refusal(&mut server, "delete_item", json!({"file": "rtl/tick.sv", "item": "tick"})); + assert!(tick.starts_with("still referenced: rtl/wrap.sv:8:3 `tick`;"), "{tick}"); + let called = + refusal(&mut server, "delete_item", json!({"file": "rtl/item_pkg.sv", "item": "parity"})); + assert!(called.contains("rtl/core.sv:22:"), "{called}"); + assert_eq!(before, snapshot(&tree)); + + let mut forced = args.clone(); + forced["force"] = Value::from(true); + let text = preview_then_write(&mut server, &tree, "delete_item", &forced); + assert!(text.contains("deleted declaration `p` (old lines 8-9)"), "{text}"); + assert!( + text.contains("warnings:\n deleted with references left: rtl/core.sv:22:15 `p`"), + "{text}" + ); + // Its own leading comment went; the neighbour's trailing comment stayed. + let expected = original.replace(" // Parity of r.\n logic p;\n", ""); + assert_eq!(read(&tree, "rtl/core.sv"), expected); + let gone = refusal(&mut server, "delete_item", forced); + assert!(gone.contains("no declaration matches `p`"), "{gone}"); +} + +#[test] +fn delete_item_takes_an_unused_item_and_the_blank_line_it_would_double() { + let (tree, mut server) = item_tree(); + let pkg = read(&tree, "rtl/item_pkg.sv"); + let spare = json!({"file": "rtl/item_pkg.sv", "item": "spare"}); + let text = preview_then_write(&mut server, &tree, "delete_item", &spare); + assert!(text.contains("deleted function `spare` (old lines 9-12)"), "{text}"); + let expected = pkg.replace( + " // Nobody calls this one.\n function automatic logic spare(logic a);\n return a;\n endfunction\n", + "", + ); + assert_eq!(read(&tree, "rtl/item_pkg.sv"), expected); + + let core = read(&tree, "rtl/core.sv"); + let assign = json!({"file": "rtl/core.sv", "item": "assign@16"}); + preview_then_write(&mut server, &tree, "delete_item", &assign); + let expected = core.replace("d;\n\n assign q = r;\n\n // lucisv", "d;\n\n // lucisv"); + assert_eq!(read(&tree, "rtl/core.sv"), expected); +} + +#[test] +fn structural_edits_keep_a_crlf_file_crlf() { + let tree = Tree::of("item"); + let source = "module c;\r\n logic a;\r\n logic b;\r\nendmodule\r\n"; + fs::write(tree.path("rtl/crlf.sv"), source).unwrap(); + let mut server = Session::over(&tree); + server.initialize(); + let replace = json!({"file": "rtl/crlf.sv", "item": "a", "text": "logic [1:0] a;\n"}); + server.text("replace_item", replace); + let insert = json!({"file": "rtl/crlf.sv", "anchor": "b", "text": " logic c;\n logic d;"}); + server.text("insert_item", insert); + server.text("delete_item", json!({"file": "rtl/crlf.sv", "item": "a"})); + assert_eq!( + read(&tree, "rtl/crlf.sv"), + "module c;\r\n logic b;\r\n\r\n logic c;\r\n logic d;\r\nendmodule\r\n" + ); +} diff --git a/docs/features/mcp-structural-edits/README.md b/docs/features/mcp-structural-edits/README.md new file mode 100644 index 0000000..50dbad2 --- /dev/null +++ b/docs/features/mcp-structural-edits/README.md @@ -0,0 +1,809 @@ +# mcp-structural-edits + +Lane **M4** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §4.3). + +## Goal + +The general token saver: an agent that wants to change one `always` block, +one function or one declaration sends **only that item's new text**, never +the file — `replace_item`, `insert_item`, `delete_item`. Each finds its +place with `read_item`'s own slicer, so the bytes it edits are exactly the +bytes `read_item` showed; each verifies the result before anything is +written (CLAUDE.md invariant 1: verified output or nothing); each writes +through M3's one write path (`apply::run`: `dry_run` diff, write-freshness, +atomic write). The verifier is the one new piece of logic in the MCP block, +so it ships with its attack suite (`tests/attacks.rs`) — invariant 4. + +## Assumptions + +### The contract + +| tool | arguments | does | refused when | +|---|---|---|---| +| `replace_item` | `file`, `item` (`read_item`'s selector), `text`, `rename?` (false), `dry_run?` | the bytes of exactly the span `read_item::select` returns become `text` (normalised, below) — widened over the item's own comments when the text brings comments of its own (below); nothing outside that span changes | `text` empty; the item is part of a larger item (an ANSI port, an argument); the span is fenced; any verifier rule (below) with `Expect::One(old class)`; the text declares other names than the item did and `rename` is false | +| `insert_item` | `file`, `anchor` (a selector, `end`, or `end@UNIT`), `position?` (`before`/`after`, default `after`, ignored for `end`), `text`, `dry_run?` | `text` becomes new items before the anchor (above its own leading comments) or after it (below its trailing comment), or the last items of a unit (`end`: the file's last module/interface/program/package/class; `end@UNIT`: that one) | `text` empty; the anchor (or the unit's end keyword) shares a line with other code; the insertion point is fenced; any verifier rule with `Expect::Some` | +| `delete_item` | `file`, `item`, `force?` (false), `dry_run?` | removes the item's lines, its own leading comments (`Meta::leading` back to the first blank line, below), its trailing comment, and the blank line the removal would leave doubled | the item shares a line; the removed bytes are fenced or its leading comments hold a fence line; a name it owns is still referenced — or possibly referenced, through a macro or a `.*` (below) — and `force` is false; any verifier rule with `Expect::Nothing` | + +Annotations: `replace_item` and `delete_item` are `idempotentHint: true` +(the same `replace_item` twice answers `unchanged`; a second `delete_item` +is refused "no declaration matches" — it writes nothing); `insert_item` is +`false` (the same insertion twice is refused only when it would declare a +name twice; otherwise it inserts again). `delete_item` walks the roots +first (`rewalk: true`, whole-set rule); the other two touch one file. + +The answer is `apply.rs`'s summary — `files: 1 changed, 0 created`, the +`path +a -b` line — then the note: `replaced always (lines 12-14)` / +`inserted declaration `s` (lines 24)` / `deleted function `spare` (old +lines 9-12)`, and for replace and insert one hint line: ``hint: run `format` +with `lines: "12-14"` to reflow; `diagnostics` to check``. +`structuredContent.item.lines` carries the new item's line range. Nothing +is formatted implicitly (PLAN open question 3: the agent's choice). + +### The verifier (`src/tools/item/verify.rs`) + +Every edit is a `Splice` (`start..old_end` becomes `text`), so no byte +outside the region can change — the wire tests compare the prefix and +suffix bytes anyway. What is checked is what the new bytes do to the parse: + +1. **Lex and parse.** The new file lexes. When the old file parses + strictly (`vlog_parser::parse_source`), the new one must; when it did + not, the tolerant diagnostic count must not grow. A file that does not + lex at all is refused up front (no span in it can be trusted). + - **1a.** The spliced `text` lexes **on its own** + (`vlog_parser::tokenize(text)`): a text ending in an open `/*`, string + or macro call lexes inside the file only by running into the code + after it — a later `*/` closes it and swallows what lies between (QA + finding 1: a fence comment). + - **1b.** The token stream **outside the region** is the old one: every + token and every comment (the `Token.leading`/`trailing` trivia, + flattened in source order) before the region, and every one after it + shifted by the length change, has the same kind, text and span as in + the old file; nothing starts inside the region and ends past it; and + no comment inside the new bytes is attached to a token outside them (a + comment the text leaves on a line of its own at its end would lead the + next item). Rules 1a/1b live in `src/tools/item/lexical.rs`; the + refusal names the rule (`rule 1a`, `rule 1b`). Order: whole-file lex, + 1a, strict parse, 1b, then rules 2–7. +2. **Surroundings.** Every item of the tree (depth first, all levels) is + classified against the region: before it, after it (shifted by the + length change), enclosing it (end shifted), or inside it. The before, + after and enclosing lists — depth, kind class, start, end — must be + identical in the old and new trees. An item that begins on one side of + a region boundary and ends on the other is refused by name ("the text + must open and close everything it starts"). This is what catches a text + that closes the enclosing module (still a valid file, `sneaky` module + and all), a stray attribute that glues onto the next item, and a block + left open that error recovery would otherwise absorb. +3. **Content.** The items inside the region at the enclosing level: + exactly one of the old kind class (replace), at least one (insert), + none (delete). Each must be a kind its container may hold (below). +4. **Duplicates.** No name is declared twice in one scope more times than + before (`Semantics::duplicates`, counted per name). This catches a port + re-declared in the body — even with `rename: true` — and a repeated + insert. +5. **Conditionals.** The `` `ifdef``/`` `ifndef``/`` `elsif``/`` `else``/ + `` `endif`` directive tokens starting inside the region balance, in the + old bytes and in the new (the parser keeps directives as raw items, so + half a guard parses). +6. **Macro definitions** (QA finding 6). The file's define table entries + (`Analysis.defines`) whose directive starts inside the region — kind, + name, parameters, body — are the same before and after, except those + inside a **directive or macro item at the region's own level** (kind + class `directive`/`macro`): replacing, inserting or deleting such an + item is editing the definition, which is the point. So a + `` `define``/`` `undef`` nested in an `always`, a function, or a module + the text replaces whole cannot be added, changed or removed by these tools ("the text + changes a macro definition (`W`) nested in an item (rule 6); edit the + `define item itself"), and a top-level `` `define`` item can be inserted. + Applied to all three tools (the ruling names replace and insert; a + delete removing a nested `` `define`` changes the code after it the + same way). +7. **Fence markers** (QA finding 7). The `lucisv: off`/`on` marker + comments (`fence::fence_of`, trailing ones included) starting inside the + region are the same before and after: a text neither opens nor closes a + fence ("the edit would add the fence marker `// lucisv: off` (rule 7)"). + +### Kind classes + +| class | `ItemKind` | +|---|---| +| module / interface / program | `Module` by keyword (`macromodule` is module) | +| package, class | `Package`, `Class` | +| declaration | `DataDecl`, `ParamDecl`, `Typedef`, `Let` | +| port declaration | `PortDecl` (non-ANSI body) | +| genvar | `Genvar` | +| assign, alias | `ContAssign`, `Alias` | +| always | `Always` (every `always*` keyword — one class) | +| initial, final | `Initial`, `Final` | +| instance | `Instantiation`, `GateInstantiation` | +| function, task | `Function`, `Task` | +| generate | `GenerateRegion`, `GenIf`, `GenFor`, `GenCase`, `GenBlock` | +| import, export, modport, clocking, bind, defparam, timeunit | one each | +| constraint, covergroup, property | `Constraint`, `Covergroup`, `PropSeqDecl` | +| assertion | `Assertion`, `DefaultDisable` | +| (verbatim) | a `Verbatim` item is classed by its first words: assert/assume/cover/restrict/expect → assertion; covergroup; constraint; property/sequence → property; else `verbatim` | +| elaboration task, macro, directive, empty item, unparsed text | `ElabTask`, `MacroItem`, `Directive`, `Empty`, `Error` | + +**Container rule** (IEEE 1800 A.1): in a file or a package, none of +always/initial/final/assign/alias/instance/generate/port declaration/ +modport/clocking/assertion/defparam/genvar/elaboration task; in a package +or a class, no module/interface/program/package either; in a class, no +bind; a package only in a file. The parser accepts `always_comb` after +`endmodule`, so this rule — not the parse — is what refuses it. + +### Normalisation and blank lines + +- **`text`**: trailing spaces, tabs and line endings are dropped, because + the line ending after the old item is outside the span and stays: the + new item ends at a line end exactly when the old one did — one newline, + never two. For `replace_item` leading blank space is dropped too (the + indentation before the span stays); for `insert_item` leading blank lines + are dropped and the first line's indentation is kept as written (no + re-indentation — `format` does that). Line endings become the file's + (judged by its first line): an LF text in a CRLF file is written CRLF. + An empty text is refused, never taken as a deletion. +- **Comments the text brings** (QA finding 2, lead ruling). When `text` + begins with a comment (its first token, lexed alone, has leading + trivia), the replaced span is widened back over the old item's **own** + leading comments (the own-comments rule below); when `text` ends with a + trailing comment on its last line (its last token has a trailing comment + and nothing follows), the span is widened forward over the old item's + trailing comment. The text's comments then *replace* the item's, and the + same call again finds its own text: `unchanged`. A text without comments + leaves the item's comments where they are. `read_item` is not changed + (it still shows the code span). A comment the text leaves on a line of + its own after its last token is refused by rule 1b. Implemented in + `span::replace_region`. +- A `text` equal to the replaced span's bytes after normalisation is + `unchanged` (also for a fenced item: nothing is written either way). +- **Blank lines (insert)**: a blank line separates the new items from a + neighbouring item on each side, unless that side's line is already blank. + No blank line is added between them and the enclosing unit's header (no + item above) or end keyword (`end`, or `after` the last item). A file + whose last line has no line ending gets one first. +- **Blank lines (delete)**: the removal takes whole lines; when the line + above and the line below the removed lines are both blank, the one below + goes too. + +### Own comments and own lines (`src/tools/item/span.rs`) + +- **Own comments** (QA finding 4). An item's leading comments + (`Meta::leading`) are its own walking back from the item up to the first + gap that holds a blank line: a section banner, or the file banner above a + module, separated by a blank line, belongs to what follows it and stays + when the item is deleted (it then leads the next item). +- **Own lines** (QA finding 5). An item owns its lines unless another + item's **code** sits on its first or last line; a comment on the same + line goes with the item (`/* lead */ logic a;` owns its line and can be + an anchor or deleted; `logic x; /* c */ logic a;` still shares). The + first line is judged from the first own comment; the last line runs to + the end of the trailing comment (which may continue onto later lines). + +### Names and references + +- **Owned names** (`verify::owned`): the symbols whose name — or, for a + non-ANSI body port declaration, whose detail — lies in the item, bound in + a scope a construct inside the item opens (the unnamed header scope a + generate loop opens around itself, spanning exactly the item, is + see-through). A module owns its name, not its signals; a declaration + `logic q, r;` owns `q` and `r`; an always block owns nothing (a + `begin : blk` label is owned; an unnamed `begin`'s locals are not); a + generate loop owns its label and its genvar. +- `replace_item` compares the sorted owned names before and after; a + difference is refused unless `rename: true`, and then the answer warns + that references were **not** updated and points at `rename`. +- `delete_item` (`src/tools/item/refs.rs`): for each owned name, if any + text of the whole set (the removed bytes aside) spells it as a whole word, + `vlog_refactor::find_references` over the whole set finds the uses; a use + outside the removed bytes, an engine refusal, a skipped file spelling the + name, or a name also declared outside the item (a non-ANSI header port) + refuses the delete — listing the first five as `file:line:col `name`` + and "and N more" — unless `force: true`, which deletes and lists them + under `warnings:`. The whole-word prefilter is sound for everything but a + `.*`, which binds without spelling the name — so the `.*` rule below + runs for every name. In the item's own file the file's semantic tables are + consulted too: a use of the name outside the removed bytes that resolves + to the declaration **or to nothing** counts — that is what catches + `gen_l[0].z`, a hierarchical path into a generate loop the engine does + not follow (MCP-12). It can refuse a safe deletion (an unresolved + same-named use elsewhere in the file); `force` is the way past. +- **Macros** (QA finding 3, `src/tools/item/macros.rs`). A whole-word + spelling of the name inside a macro call's arguments (the lexer keeps + `` `ID(x) `` as one token; nested calls are searched too) or inside a + `` `define`` body (not one of its formal arguments), in any file of the + whole set, that neither the engine nor the file's own reference table + accounted for, is a **possible use**: "possible use (macro) at + file:line `name`" — refused unless `force`, the skipped-file rule's + posture. Comments and strings are not searched (arguments and bodies are + lexed; a body that does not lex — token pasting — is searched as bytes). + A file of the set that spells the name and does not lex is a possible + use too. +- **`.*`** (QA finding 8, `src/tools/item/star.rs`). For each deleted + name, every `.*` instantiation in the item's own scope — its sibling + items and the generate constructs among them, the removed bytes aside — + whose module resolves through the project index to **one** module or + interface declaration with a port of that name is a use ("bound by `.*` + at file:line:col `name` (module `core`)"); a `.*` whose module does not + resolve to exactly one declaration is a possible use. Refused unless + `force`. A `.*` in another module, or in an enclosing scope of a + generate block the item sits in, cannot bind the name and is not + consulted. +- **Selection is `read_item`'s**, quirks included: the label of a generate + `else` branch (`gen_b` in `if (P) begin : gen_a … end else begin : gen_b + … end`) selects the whole `if` — deleting it deletes both branches, and + the note names both labels; the `then` branch's label selects that + branch's block, which is not an item, so it is refused as "part of a + larger item". + +### Deliberately not checked + +- Whether the new text makes sense: types, widths, the names it reads, a + port list that still matches its instantiations, whether an `always_ff` + still has a clock. `diagnostics` answers those; the tools say so. +- References to a name `replace_item` renamed or dropped (with `rename`). +- The effect of directives the agent writes **as items of their own** + (`` `define`` items at the region's level, `` `default_nettype``, + `` `timescale``) on the code after them — the agent's text means what it + says. A `` `define``/`` `undef`` nested inside another item is refused + (rule 6). +- A hierarchical use in **another file** that `find_references` does not + follow (`u_h.gen_l[0].z` into a generate loop; MCP-12). +- A name reached only through a macro that pastes it together + (`` `a``_b ``): no byte spells it, and no lucisv engine follows it. + +### The attack list (`tests/attacks.rs`) + +Every case asserts **refused, with every file of the tree hashed and +unchanged**, under `dry_run` and for real; a control beside most cases +asserts the nearest legal edit passes. + +| attack | rule that refuses it | +|---|---| +| a `text` opening a block it does not close (replace an `always`; insert a `function` without `endfunction`) | 1 (strict parse) | +| a `text` closing the enclosing module (`logic r;\nendmodule\nmodule sneaky;`; insert `endmodule\nmodule sneaky;` at `end`) | 2 (surroundings) | +| a `text` re-declaring a port (`logic d;`, with and without `rename`; insert `logic [3:0] clk;`) | 4 (duplicates) | +| two items where one was; `logic p;;` (an empty item rides along) | 3 | +| an empty or all-blank `text` (replace and insert) | normalisation | +| a UTF-8 edge: a non-ASCII identifier in the text; control: the multibyte comments hugging the item stay byte-identical, a multibyte comment in the text is accepted | 1 (lex) | +| an item inside a `// lucisv: off` fence: replace, delete, insert before/after; deleting the fence's owner module; deleting the item whose leading comment is the `on` fence | fence | +| a file with an unterminated string (replace, insert); a text with one | lex | +| `insert_item` after `endmodule`: `always_comb`, `assign`, an instance at file scope; `initial` in a package; control: a module after a module | 3 (container) | +| a valid item of another kind (a `function` or `initial` where an `always` was; an `assign` where a declaration was); control: `always_ff` → `always @*` | 3 (class) | +| an escaped name (`\a+b `): renaming without `rename`, deleting while referenced; control: widening it | names, references | +| half an `` `ifdef``: inserted `` `endif``, `` `else``; a module carrying an unclosed `` `ifdef``; replacing with `` `ifdef``+item (two items); controls: a balanced guard, an item inside a guard | 5, 3 | +| insert/delete on a line shared with other code; control: replace on a shared line | line ownership | +| a header port and a non-ANSI body port whose header still names it | not an item; references | +| a generate loop relabelled without `rename`; deleted while `gen_l[0].z` names it; control: a wider body under the same label | names, references (local uses) | +| a 40 000-line file: a refused replace, then replace, insert and delete (timed below) | 1 | +| *(rework)* an open `/*` a later comment closes (replace, insert); a comment left on its own line after the text's item; control: a same-line comment | 1a, 1b | +| *(rework)* a text with leading and trailing comments twice (`unchanged`, the old comments replaced, the banner kept); control: a text without comments keeps the item's | normalisation (comments) | +| *(rework)* a name used only in a macro argument, a nested call, another file's `` `define`` body; forced; control: a name only in a comment and a string | references (macros) | +| *(rework)* a section banner and a file banner a blank line separates from the deleted item | own comments | +| *(rework)* `/* lead */ logic a;` deleted; control: `logic x; /* c */ logic y;` shares | own lines | +| *(rework)* `` `undef``/`` `define`` nested in a replaced, inserted or deleted item; control: a `` `define`` item inserted | 6 | +| *(rework)* a `// lucisv: off` in an inserted text, a `// lucisv: on` inside a replaced `always`; control: an ordinary comment | 7 | +| *(rework)* a signal bound by a `.*` inside a generate block; a `.*` to an unindexed module; forced; controls: a signal no port names, another module's `.*` | references (`.*`) | + +## Handshakes + +Consumed (public APIs; no library crate changed): + +| crate / module | items | +|---|---| +| `vlog_parser` | `parse_source` (strict rule), `tokenize` (rule 1a, the text's comments, macro arguments), `ast::{Item, ItemKind, Meta, Instantiation, Connections}`, `token::{Token, TokenKind, Comment}`, `defines::{collect_defines, DefineKind}`, `span::TextRange`, `LineIndex` | +| `vlog_semantic` | `Semantics::{symbols, scope, file_scope, duplicates, references}`, `Symbol`, `WorkspaceIndex::{units, member}`, `SymbolKind` | +| `vlog_refactor` | `find_references` | +| `vlog_formatter` | `fence::{protected_regions, is_protected, fence_of}` | +| `lucisv_mcp` (M1–M3) | `read_item::{select, child_items}`, `apply::{run, Plan, Change}`, `source::{WholeSet, word_in}`, `edit::DRY_RUN`, `Analysis::of` | + +Promised: three tools with the contract above; `verify::check` is private +to `tools::item` (no second user yet). + +Edits outside the brief's file list, each forced by the lane: + +- `crates/lucisv_mcp/tests/qa_m1.rs`: the tool count in + `qa_everything_but_initialize_and_ping_waits_for_the_handshake` goes from + 23 to 26 (M2 and M3 made the same one-line edit). +- `crates/lucisv_mcp/src/tools/item/refs.rs`: a third file under `item/` + (the delete reference rule), split off so `item.rs` stays one sentence; + within the lane's `item` module. +- Rework (2026-09-23): four more files under `item/`, each one sentence — + `span.rs` (own comments, own lines, the replaced span; moved out of + `item.rs`), `lexical.rs` (rules 1a, 1b, 7), `macros.rs` (macro + spellings), `star.rs` (`.*` bindings). All within the lane's `item` + module; no library crate changed. + +Requests: + +- **MCP-11 → `vlog_refactor` (performance, non-blocking):** a + `find_references_many(files, file, offsets)` that builds the `Scope` once + for several declarations. `delete_item` on `logic a, b, c;` or an enum + typedef runs the whole-set engine once per owned name some other text + spells; one build would serve them all. +- **MCP-12 → `vlog_refactor` / `vlog_semantic` (a missed use, not a + corruption here):** `find_references` on a generate-loop label + (`for (…) begin : gen_l … end`) does not return `gen_l[0].z`. The + same-file case is covered by `refs.rs::local_uses`; a hierarchical use + from another file is not. Repro: `tests/attacks.rs` + `a_generate_loop_owns_its_label` passes only through `local_uses`. +- **MCP-13 → `vlog_linter` (a lint gap, out of lane):** a forced + `delete_item` of a non-ANSI body port declaration leaves + `module k (a, b); output b;` — a header port with no direction — and + `diagnostics` answers "no findings". A rule "a non-ANSI header port has + no direction declaration in the body" would report it. The forced + answer's warning names it today (`qa_a_forced_non_ansi_port_delete…`). + +Accepted, not a request: `.en(x)` in a named connection is counted as a +use of the instantiating module's own `en` by the whole-word prefilter + +engine (QA observation) — a false refusal, in the safe direction; `force` +is the way past. + +## Status / TODO + +- [x] `replace_item`, `insert_item`, `delete_item` registered (`tools/mod.rs`, + Effect rows), sharing `read_item::select` +- [x] the verifier: lex/parse rule, surroundings, content and kind class, + container rule, duplicates, conditionals +- [x] normalisation (trim, line endings), blank-line policy, own lines, + doubled blank line, fences +- [x] `delete_item` reference rule over the whole set, `force` +- [x] wire tests: dry run / real / repeat per tool; prefix and suffix bytes + compared; `read_item` after `replace_item`; insert at `end`, before, + after, `end@UNIT`, byte for byte; delete refused over references, + forced, leading comment gone and neighbour's trailing kept; doubled + blank; CRLF +- [x] `tests/attacks.rs` (15 tests) +- [x] gates; sizes; timings +- [x] rework (QA findings 1–8, lead rulings): rules 1a/1b, the comments a + text brings, own comments up to a blank line, own lines ignore + comments, rule 6 (macro definitions), rule 7 (fence markers), macro + and `.*` uses in `delete_item`; 8 QA tests un-ignored; 8 attacks +- [ ] lead ruling needed: `qa_every_accepted_call_changes_only_its_own_region` + (first replace) contradicts the finding-2 ruling — see the work log + +## Work log + +**2026-09-23 (dev, M4).** + +Built `src/tools/item.rs` (the three tools, selection, lines, blank +lines, normalisation, notes), `src/tools/item/verify.rs` (the verifier and +kind classes, 5 unit tests), `src/tools/item/refs.rs` (the delete +reference rule); three rows in `tools/mod.rs`; fixture tree +`tests/fixtures/item` (a package with a used and an unused function, a +module with a fenced region, a `.*` wrapper, a module instantiated by +name); six wire tests; `tests/attacks.rs`. + +Decisions: + +1. **One verifier rule instead of the brief's "the item at that position + is one item"**: the whole-outline comparison (rule 2) subsumes it and + also proves nothing *else* re-parsed — the attack that closes the + module parses cleanly and is caught only by it. +2. **A container rule** the brief did not list: the parser accepts module + items at file scope, so "insert after `endmodule`" needed it. +3. **A conditional-balance rule**: directives are raw items, so half an + `` `ifdef`` parses; replace refuses it by item count, insert only by + this rule. +4. **Duplicates are checked always**, not only under `rename`: a port + re-declared by an insert is the same attack. +5. **Insert and delete need items on lines of their own**; replace does + not (its span is the span). A one-line module is refused with "run + `format` first". +6. **An item that is only part of a larger one** (ANSI port, argument — + `read_item` slices those) is refused by these tools. +7. **Equality before the fence check**: an unchanged text is `unchanged` + even for a fenced item (nothing is written either way). +8. **Owned names see through a generate loop's header scope**, and + `delete_item` also counts the file's own unresolved same-named uses — + both found by probing a generate target before QA (the loop's label sits + in an unnamed scope spanning the loop, and the engine does not follow + `gen_l[0].z`). +9. **A non-ANSI body port declaration** whose header still names it is + refused by `delete_item` unless forced (deleting it would leave the + header naming an undeclared port). + +Timings (the 40 000-line module of `a_forty_thousand_line_file_is_verified_in_bounded_time`, +wall time per call over stdio, macOS arm64): + +| call | debug (ms) | release (ms) | +|---|---|---| +| refused replace (block left open; the first call, analysis included) | 1 446 | 282 | +| replace of one `always_ff` | 781 | 150 | +| insert at `end` | 1 358 | 276 | +| delete of an unused declaration | 1 338 | 258 | + +Each call parses the file four to five times (the cached analysis, the +strict parse of old and new, the new analysis, the fence scan). + +Tests: `lucisv_mcp` +6 unit (verify), +7 wire (6 M4 + CRLF), +15 attacks. + +Gates (each through `tools/guard.sh`, one cargo invocation at a time): +`cargo fmt -p lucisv_mcp -- --check` rc 0; `cargo clippy -p lucisv_mcp +--all-targets` clean; `cargo test -p lucisv_mcp` 50 unit + 15 attacks + 0 +(1 ignored, opentitan) + 51 qa_m1 + 43 qa_m2 + 37 qa_m3 (1 ignored) + 37 +wire, all passed; `cargo test --workspace` **4 789 passed, 0 failed, 49 +ignored** (4 762 before the lane). + +Sizes (production lines: non-blank, non-comment, before `mod tests`): +`tools/item.rs` 410, `tools/item/verify.rs` 321, `tools/item/refs.rs` 143, +`tools/mod.rs` 180. `verify::class_of` (a dispatch table over `ItemKind`) +is the longest function, ~50 lines; everything else is under 45. + +**2026-09-23 (dev, M4 rework — QA findings 1–8 under the lead's rulings).** + +Per finding (all eight `#[ignore = "QA finding N"]` removed from +`tests/qa_m4.rs`, their assertions untouched; one attack per fix added to +`tests/attacks.rs`): + +1. *Open comment swallowing a fence* — `item/lexical.rs` (new): rule 1a + (`lexes_alone`: `tokenize(text)` must succeed) and rule 1b + (`same_outside`: the flattened token + comment stream before and after + the region identical, shifted; nothing straddling the new region's end; + no comment of the new bytes attached to a token outside them). Wired in + `verify::check` / `parses_as_well`. `insert_item` now runs the verifier + before its fence check, so a text that cannot stand anywhere is refused + as such (the QA test's insert before the `// lucisv: on` line gets + "would no longer lex … comment", not "fenced"). Attack + `a_text_reaching_past_its_end_is_refused_by_the_lexical_rules`. +2. *Not idempotent with comments in the text* — `item/span.rs::replace_region`: + a text beginning with a comment widens the span back over the item's + own leading comments; one ending in a same-line trailing comment widens + it over the item's trailing comment; `unchanged` compares against the + widened span (`item.rs::replace_item`). `read_item` unchanged. Attack + `a_text_with_comments_replaces_the_items_own_and_repeats_unchanged`. +3. *Macro-argument / `` `define``-body uses* — `item/macros.rs` (new, + `macro_spellings`) + `refs.rs::Scan::macros`: spellings in macro call + arguments (nested calls too) and `` `define`` bodies (formals excluded), + in every file of the set, not accounted for by the engine's hits or the + own file's reference table → "possible use (macro) at file:line + `name`". A set file that spells the name and does not lex is a possible + use too. Attack `a_name_spelled_inside_a_macro_is_a_possible_use`. +4. *Deleting a banner* — `span.rs::own_comments_start`: the walk over + `Meta::leading` stops at the first gap holding a blank line. Attack + `a_delete_leaves_the_comments_a_blank_line_separates_from_the_item`. +5. *`/* lead */ logic a;`* — `span.rs::own_lines`: the first line is judged + from the first own comment, so a same-line leading comment goes with the + item; code of another item on the line still shares it. Attack + `a_same_line_comment_goes_with_its_item_and_code_still_shares_the_line`. +6. *Nested `` `define``/`` `undef``* — `verify.rs::same_macros` (rule 6): + define-table entries in the region equal before/after, those inside a + directive/macro item at the region's level exempt. **Interpretation to + confirm:** the ruling's exception is keyed to "the old item"; an insert + has none, so the literal reading would refuse inserting a `` `define`` + item at all — and would turn the passing QA test + `qa_a_line_continued_directive_cannot_swallow_the_code_below_it` (a + `` `define`` item inserted between items) red. I keyed the exemption to + the directive/macro items at the region's level on either side, which + is the ruling for replace and delete and lets an insert add a directive + item but not a define nested in anything. Applied to delete as well (a + nested `` `define`` removed changes the code after it the same way). + Attack `a_macro_definition_nested_in_an_item_is_refused`. +7. *Fence marker in a text* — `lexical.rs::same_fences` (rule 7): the + fence-marker comments starting in the region equal before/after (a + trailing one counts). Attack `a_text_may_not_carry_a_fence_marker`. +8. *`.*` binding* — `item/star.rs` (new, `star_uses`) + + `refs.rs::Scan::stars`, run for every owned name before the whole-word + prefilter: a `.*` in the item's sibling list or a generate construct + among it, outside the removed bytes, whose module resolves to one + indexed module/interface with a port of the name → "bound by `.*` at + file:line:col `name` (module `m`)"; unresolved → "possible use (`.*`)". + `refs::check` now takes a `Place` (item span, removed bytes, scope). + Attack `a_signal_bound_by_a_dot_star_is_still_referenced`. + +Also: `item.rs` split — the span and line helpers moved to `item/span.rs` +(a pure move plus the finding 4/5/2 changes); `insert_item` no longer +indexes `outcome.items[0]`; the replace/delete tool descriptions mention +the comment and `.*`/macro behaviour (the replace description is 520 +characters, under the 600 cap of `every_schema_is_closed…`). Out-of-lane +notes (the MCP-13 lint gap, the accepted `.en(x)` false refusal) are in +Handshakes. + +**For the lead — one QA assertion contradicts ruling 2.** +`qa_every_accepted_call_changes_only_its_own_region` (`tests/qa_m4.rs`, +its first replace: `r` in `rtl/core.sv` with `logic [15:0] r; /* wider */`) +asserts the changed bytes lie inside `read_item`'s span of `r` +(`logic [7:0] r;`, bytes 121–135). The text ends in a trailing comment on +its last line, so under ruling 2 the replaced span widens over `r`'s own +trailing `// the register` (bytes 128–151 change). Before the rework the +call produced `logic [15:0] r; /* wider */ // the register` — which is the +non-idempotent shape finding 2 is about (and which rule 1b now refuses as a +merged comment straddling the region). Left untouched, as instructed; it +is the only failing test. Either the test's text drops its comment, or its +bound for this case becomes the widened span. + +Tests: `lucisv_mcp` 54 unit (+4: 3 `span`, 1 `macros`), 23 attacks (+8), +35 qa_m4 (8 un-ignored; 34 pass, 1 fails as above), 37 wire, 51 qa_m1, +43 qa_m2, 37 qa_m3 (1 ignored). + +Gates (each through `tools/guard.sh`, one cargo invocation at a time): +`cargo fmt -p lucisv_mcp -- --check` rc 0; `cargo clippy -p lucisv_mcp +--all-targets` clean (rc 0); `cargo test -p lucisv_mcp` all green except +`qa_every_accepted_call_changes_only_its_own_region` (above); +`cargo test --workspace --no-fail-fast` **4 835 passed, 1 failed (that +test), 49 ignored** (4 816 + 8 un-ignored + 8 attacks + 4 unit − 1; 57 − 8 +ignored). No guard kill. + +Sizes (production lines: non-blank, non-`//`, before `#[cfg(test)]`): +`item.rs` 379, `item/verify.rs` 363, `item/refs.rs` 211, `item/lexical.rs` +132, `item/star.rs` 73, `item/span.rs` 69, `item/macros.rs` 67. Longest +function still `verify::class_of` (the dispatch table, 46); every new one is +under 40. + +## QA log + +**2026-09-23 (QA, M4) — verdict: REWORK (four blocking findings, 1, 3, 4 and 8).** + +This run resumes one an app restart cut off: the earlier QA agent's +`tests/qa_m4.rs` (27 tests, no log) was taken over, compiled and run as +found (21 passing, 6 finding tests failing as they should), kept, extended +by 8 tests and two cases, and every finding re-reproduced by hand over +stdio (`lucisv-mcp` driven by a scratch script). `tests/qa_m4.rs` now holds +35 tests: 27 pass, 8 are `#[ignore = "QA finding N"]` and assert the right +behaviour (each fails today, run with `--include-ignored`). + +What holds (each a passing `qa_*` test, refusals asserted with the tree +byte-identical under `dry_run` and for real): directives, `;;` and a second +unit riding along with an item (two items); `endmodule`/a module header/a +dangling attribute in a `text` (surroundings); another kind under the old +name with and without `rename`; `unchanged` for the old bytes plus blank +space and for a fenced item handed back; a BOM (lex); an `always` inside a +generate branch and inside a loop replaced in place, byte for byte, and a +text that closes the branch refused; directive words in comments and +strings do not trip the balance rule, a directive nested in an `always` +must balance inside the text (`` `ifdef``, `` `endif``…`` `ifdef``, +`` `else``; control: a balanced guard); CRLF through all three tools; +`end` with two units, `end@a`, `end@pk`, a package refusing an +`always_comb`, `end@W` refused; a class body (method yes; `always`, +`assign`, a module, a duplicate no); half an item; a file with a parse +error elsewhere (count may not grow; a clean item still goes in); the same +insert twice (declaration refused, `assign` inserted again); first/last +item blank-line policy byte for byte; a line-continued `` `define`` cannot +swallow code (at `end` refused; between items it takes only the blank +line the insert adds); delete refused over a hierarchical use in another +file and over a `bind`, forced with the site listed; a forced delete whose +uses `diagnostics` then reports (`undeclared-identifier`); the non-ANSI +body port (refused, forced result parses strictly); the last items of a +module; a trailing comment running into the next line stays with its item +on both sides; the `gen_b` quirk (the dry-run note names `gen_a`, `gen_b`; +`gen_a` refused as part of a larger item); an item inside a guard; the +fence from every side (insert before/after, replace, forced delete). + +**The prefix/suffix guarantee** (attack 4): `qa_every_accepted_call_changes_only_its_own_region` +takes `read_item`'s span before each of 7 replaces (a declaration, two +`always`, a package function, an instance, a generate loop, a whole +module), 4 insert/delete pairs and 3 forced deletes, and compares the +bytes before and after it; `qa_two_hundred_replaces_in_a_row…` does the +same for 200 calls plus 200 repeats (`unchanged`, file unchanged). No +drift anywhere. The strings/comments test and the generate test check it +too. + +Findings (numbers match the `#[ignore]` reasons): + +1. **BLOCKING — a `text` ending in an open `/*` swallows the fence + below it.** `verify.rs:101-115` (rule 1) asks only that the whole new + file lexes, and rule 2 compares items, not comments; a later `*/` in a + comment closes the new one. Repro: `module f; logic a; // lucisv: off + /* hand aligned */ logic keep_me; …` (one per line); `replace_item a` + with `logic a; /* note` → accepted; `format` (dry run) then rewrites + `logic keep_me;` → `logic keep_me;` and `assign keep_me =` → + `assign keep_me =` — hand-aligned code the fence protected. Same for + `insert_item`. Test `qa_a_text_leaving_a_comment_open_is_refused_even_when_a_later_one_closes_it`. + Fix: a lexical surroundings rule — every comment and token that begins + inside the region ends inside it (equivalently, the comments outside + the region are the old ones, shifted), or at least: `text` lexes on its + own. +2. **MEDIUM — `replace_item` is not idempotent when the text carries a + comment outside its item.** `item.rs:184` compares the text to the + item's span; a leading (`// doc\nlogic r;`) or trailing + (`logic p; // c`) comment lands in `Meta::leading`/`trailing`, outside + the new span, so every repeat adds one more copy — against + `idempotentHint: true`, and an agent retrying a call is the common case. + Test `qa_the_same_replace_twice_is_unchanged_even_with_a_comment_in_the_text`. + Fix (ruling): refuse a text whose items do not span it (comments go + inside the item or through `insert_item`), or compare the text with the + item plus its own comments, or drop the hint. +3. **BLOCKING — a use inside a macro argument or a macro body does not + stop `delete_item`.** `refs.rs:112-139`: `mentioned` sees the spelling, + but `find_references` and `local_uses` return no use there, so the + census is empty and the delete goes through with no warning. Repro: + `logic in_item;` used only in `` `ASSERT_KNOWN(k, in_item)`` (the + OpenTitan pattern), or `in_expr` in `` assign out = `ID(in_expr);``, or + `in_body` reached through `` `define IN_BODY in_body`` → deleted; the + design no longer compiles, reported as success. The README's + "deliberately not checked" names only token-pasted names. Test + `qa_a_use_inside_a_macro_argument_refuses_the_delete`. Fix: a + whole-word spelling outside comments and strings that the engine did + not account for (a macro call's arguments, a `` `define`` body) counts + as a doubt, as a skipped file does. +4. **BLOCKING — `delete_item` takes comments that are not the item's.** + `item.rs:397-403` (`own_lines`) walks `Meta::leading` back across blank + lines: deleting `a` in `// Section: registers\n// (applies to + everything below)\n\n// the a flop\nlogic a;` removes the section + banner; deleting module `m` removes the file banner above the blank + line. The PLAN says "its own leading comments"; the brief says the + header comment must survive. Test + `qa_a_comment_a_blank_line_separates_from_the_item_is_not_deleted`. + Fix: stop at the first gap holding a blank line (or at a comment whose + successor has `blank_before`). +5. **LOW — an item led by a block comment on its own line cannot be an + anchor or deleted.** `/* lead */ logic a;` — `own_lines` (`item.rs:394`) + asks whether the item's first byte starts its line, ignoring the + same-line leading comment; the refusal says "run `format` first", but + `format` keeps it that way, and `replace_item` with a leading block + comment produces exactly this shape. Test + `qa_an_item_led_by_a_block_comment_on_its_line_owns_that_line`. +6. **HIGH, for a ruling — a macro directive nested in a replaced item + changes code outside the span.** `` always_comb begin\n`undef W\n … + end`` (or `` `define W 1'b0``) replaces an `always` and is accepted; + `` assign b = `W;`` below it no longer compiles (or silently changes). + The README lists "the effect of directives the agent writes" as + deliberately not checked; the brief lists it as masked corruption. + `insert_item` of a `` `undef W``/`` `define W``/`` `default_nettype + none`` directive item is accepted the same way (arguably what an insert + of a directive is for). Test + `qa_a_macro_directive_nested_in_a_replaced_item_is_refused` pins the + stricter reading for `replace_item`. Cheap fix: `Analysis::defines` + entries inside the region must be the same before and after a replace. +7. **LOW — a text may carry a fence marker.** `insert_item` with + `// lucisv: off\n logic lo;` (no `on`) is accepted and fences every + line below it: `format` and `delete_item` then refuse code the agent + never touched (over-protection, no corruption). Test + `qa_a_text_carrying_a_fence_marker_is_refused`. Fix: refuse a text + holding a `fence::fence_of` comment. +8. **BLOCKING — a signal bound only by a `.*` connection is deleted + without a word.** `vlog_refactor::find_references` drops every span + that does not slice back to the name (`references.rs:49`), so the `.*` + site is never returned, and `refs.rs` trusts it (the README's argument + covers only the prefilter). Repro: `module star; logic clk; logic en; + logic o; sub u_sub (.*); endmodule` with `sub (input clk, en, output + o)` → `delete_item en` accepted; `u_sub` no longer elaborates. (`.name` + is caught.) Test `qa_a_signal_bound_only_by_a_dot_star_refuses_the_delete`. + Fix: in the item's own file, an instance with `.*` in the item's scope + whose module has a port of the name counts (M3.5's binding print knows + these), or conservatively any `.*` in that scope is a doubt. + +Observations (not M4 findings): a forced delete of a non-ANSI body port +leaves `module k (a, b); output b;` and `diagnostics` answers "no +findings" — a lint gap (a header port with no direction), though the +forced warning names it. `.en(x)` in a named connection is counted as a +use of the instantiating module's own `en` (a safe-direction false +refusal, as the README says). Inserting before an item whose leading +comment is `// lucisv: on` is refused as fenced (conservative, fine). + +Sizes (production lines: non-blank, non-`//` lines before +`#[cfg(test)]`, awk): `item.rs` 410, `item/verify.rs` 321, `item/refs.rs` +143, `tools/mod.rs` 180 — the dev's numbers. Functions: longest +`verify::class_of` 47 (a commented dispatch table), `refs::check` 41, +`Scan::uses_of` 38; none over 50. No `unwrap`/`expect`/`panic!` outside +`#[cfg(test)]` (the `outcome.items[0]`/`[len - 1]` in `insert_item` are +guarded by `Expect::Some`); no `#[allow]`. + +Timings (release, macOS arm64, wall time per call over stdio): the dev's +40 000-line test — refused replace 298 ms, replace 148 ms, insert 267 ms, +delete 257 ms (the dev's figures, reproduced within 20 ms); +`qa_two_hundred_replaces…` (a 200-item module, 200 replaces each followed +by a `read_item`, a strict re-parse in the test and an `unchanged` repeat) +0.69 s for the whole test, under 2 ms a call. + +Gates (each through `tools/guard.sh`, one cargo invocation at a time): +`cargo fmt -p lucisv_mcp -- --check` rc 0; `cargo clippy -p lucisv_mcp +--all-targets` clean (rc 0); `cargo test -p lucisv_mcp` 50 unit + 15 +attacks + 0 (1 ignored) + 51 qa_m1 + 43 qa_m2 + 37 qa_m3 (1 ignored) + 27 +qa_m4 (8 ignored) + 37 wire, all passed; `cargo test --workspace` **4 816 +passed, 0 failed, 57 ignored** (4 789 + 27; 49 + 8). No guard kill. + +To re-check after the rework: remove the `#[ignore]` of findings 1, 3, 4 +and 8 (and of 2, 5, 6, 7 as the lead rules) and run +`cargo test -p lucisv_mcp --test qa_m4`. + +**2026-09-23 (QA re-check, M4 rework) — verdict: PASS.** + +The eight findings were re-checked against the reworked tree and the +lead's rulings (1a/1b, 2 widening, 3 macros, 4 blank-line gap, 5 same-line +comment, 6 define entries, 7 fence markers, 8 `.*`). The 8 finding tests +the dev un-ignored all pass. + +Findings 1, 3, 4 and 8 were also re-derived by hand over stdio (scratch +driver, debug binary). 1: `logic a; /* note` above a fence with a later +`*/` is refused by "rule 1a: unterminated block comment", for both replace +and insert. 3: `in_expr` (`` `ID``), `in_item` (`` `ASSERT_KNOWN``) and +`in_body` (a `` `define`` body) are each refused as "possible use (macro) +at rtl/mac.sv:N". 4: deleting `a` keeps the section banner and the blank +line, and deleting module `c` keeps the file banner. 8: deleting `en` is +refused as "bound by `.*` at rtl/star.sv:5:14 `en` (module `sub`)", and +`force` deletes it with that warning. + +Lead ruling applied: in `qa_every_accepted_call_changes_only_its_own_region` +the `r` case's text is now `logic [15:0] r;` (bound: read_item's span). +The new `qa_recheck_a_commented_text_replaces_exactly_the_widened_span` +checks that `logic [15:0] r; /* wider */` changes exactly +`logic [7:0] r; // the register` (the new file is prefix + text + suffix, +byte for byte) and that its repeat is `unchanged`. Two-comment texts on +either side are checked the same way. + +The new rules were attacked with 10 more `qa_recheck_*` tests, all +passing: +- **1b, glued text:** `logic a;x` on the shared line `logic a;logic b;` is + refused by rule 1b (the token `xlogic` runs past the region). `logic a` + and `logic c` without `;` are refused by the parse. +- **1b, dangling comment:** a comment left on its own line at the end of a + replace or insert text is refused by rule 1b. +- **1a:** an open string, and an open `/*` with a `*/` further down the + file, are both refused (rule 1a, or the whole-file lex first). A string + holding `/*` and `//` is accepted, and only its span changes. +- **2, widening back:** where the old item had two own comment lines with + a blank line and a banner above them, a text starting with a comment + widens over exactly the two own lines; the repeat is `unchanged`. A + comment trailing the item above is not taken. +- **7, fences:** `logic e; // lucisv: off` and + `// verilog_format: on\nlogic e;` are refused (rule 7). Block comments + spelling `lucisv: on` are not fences (`fence::fence_of` matches `//` + only), which is correct. A commented text whose widened span would + cover `z`'s own `// lucisv: on` is refused as fenced, and a plain text + replaces `z` alone. Deleting the item just above `// lucisv: off` keeps + the marker. +- **3, macros:** `` `define`` bodies spelling `sig_x`/`xsig`/`sig_`, a + formal `sig` and a string `"sig"` are no use: `sig` is deleted with no + warning. `` `ASSERT(chk, u_s.hsig)`` in another file is a possible use. +- **8, `.*`:** a `.*` two generate levels down into a non-ANSI module + binds. A `.*` into an interface instance binds (`module `ifc``). A name + no `.*` target has as a port is deleted. A `.*` into an undeclared + module is a "possible use (`.*`)". +- **6, defines:** an `always` holding a `` `define`` (insert) or an + `` `undef`` (replace) is refused (rule 6). Inserting a `` `define`` + item, and a `` `define`` item together with a declaration, is accepted + (the exemption). + +Observations (low, not blocking; for the lead): +- **Rule 6 on `delete_item`:** a module holding a nested + `` `define LOCAL`` cannot be deleted, even with `force`. The refusal + says "the text changes a macro definition … edit the `define item + itself", but no selector reaches a `` `define`` item (`delete_item + LOCAL` answers "no declaration matches"), so the delete half of the + exemption is unreachable and the advice cannot be acted on. Pinned as + current behaviour in + `qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always`. + Suggestion: reword the refusal for delete ("the deletion would remove a + `define nested in the item; remove it by hand first"). +- **Rule 3 false refusals:** the rule scans the whole set, so a common + name spelled in any macro call anywhere (another module's + `` `ASSERT(…, clk)``) refuses the delete. This errs on the safe side, + and `force` gets past it. Each delete also lexes every file that spells + the name; this was not timed on OpenTitan. + +Sizes (production lines, same method as before): `item.rs` 379, +`item/verify.rs` 363, `item/refs.rs` 211, `item/lexical.rs` 132, +`item/star.rs` 73, `item/span.rs` 69, `item/macros.rs` 67, `tools/mod.rs` +180. The only function over 40 lines is `verify::class_of` (47, a +dispatch table). No `unwrap`/`expect`/`panic!` outside tests, and no +`#[allow]`. + +Timings (release): the 40 000-line test ran a refused replace in 294 ms, +a replace in 159 ms, an insert in 284 ms and a delete in 263 ms, within +16 ms of the first run. The whole 200-replace test ran in 0.72 s. + +Gates (each through `tools/guard.sh`, one at a time, no guard kill): +`cargo fmt -p lucisv_mcp -- --check` rc 0; `cargo clippy -p lucisv_mcp +--all-targets` clean (rc 0); `cargo test -p lucisv_mcp` 54 unit + 23 +attacks + 0 (1 ignored) + 51 qa_m1 + 43 qa_m2 + 37 qa_m3 (1 ignored) + 45 +qa_m4 + 37 wire, all passed; `cargo test --workspace --no-fail-fast` +**4 846 passed, 0 failed, 49 ignored** (the dev's 4 835 + the fixed test + +10 new). + +## Review + +**Lead, 2026-09-23 (M4).** This is the block's one new verifier, and it +earned invariant 4's treatment: the first QA round found four masked +corruptions (an open `/*` at the end of a text swallowing a fence; deletes +blind to macro-argument uses and to `.*` bindings; a delete taking a banner +comment), all fixed in a rework by a second dev after the app restart, with +rules 1a/1b (the text lexes alone; every token AND comment outside the region +is byte-identical, shifted), the widened replace span for commented texts, +own-comment and own-line rules stopping at a blank line, the define and +fence-marker invariants, and the macro and `.*` use scans. 45 QA tests and +23 dev attacks pin them. Two low items deferred to the evaluation rounds, +where real agent traffic will rank them: a forced delete of a module that +holds a `` `define`` is refused by rule 6 (ruling for the fix: `force` +relaxes rule 6 on delete, with a warning), and rule 3 lexes every file +spelling a common name on each delete (measure on opentitan before +changing). MCP-11/12/13 filed. Committed as M4.