# 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.