# extract-inline-module TODO §53 — the dearest of the §8 refactoring backlog, in two halves. **§53.1 extract module ships. §53.2 inline module is unstarted** and is described here only where §53.1 had to leave room for it. ## Goal A module grows until one of its `always` blocks is a module of its own. The refactoring every RTL engineer does by hand is: select the items, invent a name, work out which signals cross the boundary and in which direction, write the new module's header, paste the items into it, and write an instantiation where they were. Every step of that is mechanical and every step of it is easy to get wrong — a signal made an `input` that the block actually drives is a silent, synthesizable bug. **Extract module** does it. Given a selection covering one or more contiguous whole module items of a module `M`, and a name `N`, lucisv writes a module `N` whose ports and parameters are inferred from the dataflow across the selection's boundary, into a file `N.sv` beside `M`'s own, and replaces the selection with `N u_N (...)` — **rendered from `N`'s own text** through `instantiation_plan`, so the skeleton and the module cannot disagree about what `N`'s ports are. Whole-edit-or-nothing, through the crate's own splice verifier (`vlog_refactor::check`): an `Ok` is safe to apply, an `Err` is a sentence for the user and no edits at all. Where lucisv cannot *know* — the direction of a routine's argument, the direction of a connection to a module the index has no single declaration of — it refuses rather than guesses. ## API as built ```rust // crates/vlog_refactor/src/lib.rs pub enum Home { NewFile, SameFile } pub struct ExtractSite { // the cheap gate's answer pub module: String, // the module the selection is in pub default_name: String, // `M_extracted` pub units: Vec, // what the engine will need read } pub fn extract_site(text: &str, start: u32, end: u32) -> Option; pub fn extract_title() -> String; pub fn extract_module(files: &[(PathBuf, String)], file: &Path, start: u32, end: u32, new_name: &str, home: Home) -> Result; // widened, additively pub struct RefactorEdit { pub edits: …, pub warnings: …, pub created: Vec } // crates/lucisv_server/src/extract.rs pub const EXTRACT_MODULE: &str = "lucisv.extractModule"; // [uri, range, name] pub fn kind() -> CodeActionKind; // refactor.extract pub fn code_actions(ws, uri, range) -> Vec; pub fn execute(ws, arguments, create_files) -> Result<(WorkspaceEdit, Vec), String>; pub fn workspace_edit(ws, refactoring) -> Result; // editors/vscode/extract.js executeCommand(deps, command, args, next) // the language client's middleware validateModuleName(value) ``` `crates/vlog_refactor/src/extract/` is five files, one question each (and `region.rs` answers a sixth: an `interface` and a `program` are the same AST node as a `module`, and only the first is one lucisv extracts out of): | file | one sentence | | --- | --- | | `mod.rs` | the entry points, the plan, the edits, the verification | | `region.rs` | what the selection covers, and the item kinds that refuse | | `flow.rs` | which names cross, and in which direction | | `boundary.rs` | what each crossing name becomes: port, parameter, import | | `render.rs` | the new module's text, and the instantiation | ## The dataflow rule, exactly as implemented A name is **written by** a region when, and only when, it is: * the left-hand side of a **continuous assignment** (`assign x = …`); * the left-hand side of a **blocking or non-blocking assignment**, a `for` initialiser or step, or the target of a `++`/`--`, anywhere inside an `always` / `initial` / `final` block or a routine body; * the target of a **`force`**, a **`release`** or a **`deassign`**; * the target of a **`-> ev`**; * the **declarator's own initialiser** (`wire w = a & b;`); * connected to an **`output` or `inout` port of an instantiation** — a fact only the instantiated module's declaration holds, so it is looked up through the workspace index (`module_definition` + `instantiation_plan`). Everything else is a **read**. Two positions are neither, and both refuse rather than guess: * an **argument of a task or function call** — only the routine's prototype says whether it is in or out; * a **positional** or **`.*`** connection, and a `.p` with no expression, which name no port and no signal respectively. The left-hand side of an assignment writes the *base* of whatever it selects: `a.b[3] = x` writes `a`, which is what resolves. A concatenation or stream on the left writes each element. The boundary table is then, per declaration of `M`, four bits per side (`read`, `write`, `unknown`, and the same outside). From it: | the selection… | outside… | the port | | --- | --- | --- | | reads only | anything | `input` | | writes | does not write it | `output` | | writes | **also writes it** | refused | | writes | passes it to a routine | refused | | passes it to a routine | anything | refused | A **parameter** or **localparam** of `M` the selection reads becomes a `parameter` of `N` with `M`'s own default, overridden `.P(P)` at the instantiation — and so does every parameter that parameter's *type* or *default* names, transitively, and every parameter a **crossing port's own type** names (`input logic [N-1:0] a` carries `N` across). A name in one of those positions that is declared in `M` and is *not* a parameter is a refusal. `import` items of `M` — body imports and header imports alike — are copied into `N`'s header when one of the names `N` has to resolve could have come through them. "Could have come through" is the binder's own answer: a use of a name a package supplies carries the import paths it walked in `Resolution::ExternalCandidate::paths`, in the spelling the source wrote (`p::*`, `p::w_t`), and an import is copied exactly when one of the needed names names *that* import. For a package declared in the same file the binder resolves the name on the spot, so the same question is asked of the declaration's position instead: a symbol inside a `package` item's span is one that package supplies. ## Refusals — the whole list, each with its sentence **Shape of the selection** (`region.rs`): | when | the sentence says | | --- | --- | | the selection is not inside one module's body | "not inside one module's body" | | it is inside an **`interface`** | "whose signals are its surface … so there is no boundary for lucisv to infer ports across; lucisv extracts out of a `module`" | | it is inside a **`program`** | "whose items are testbench code whose meaning depends on when it runs" | | it cuts an item in half | "cuts an item in half; lucisv extracts whole module items" | | it covers no item at all | "covers no module item" | | it holds a **port declaration** | "…a port declaration, which belongs to the module that wrote it" | | a **`parameter`/`localparam`** declaration | "…a `parameter` declaration" / "…a `localparam` declaration" | | a **`genvar`** | "…a `genvar` declaration" | | a **`bind`** | "…a `bind` directive" | | an **`initial`** block | "testbench code whose meaning depends on when it runs" | | a **`final`** block | the same | | a **macro invocation** | "lucisv does not expand macros, so it cannot tell what would move with it" | | a **compiler directive** | "lucisv does not evaluate one" | | a **verbatim block** (an assertion, a `property`/`sequence`/`constraint`/`covergroup` body it could not read) | "it cannot tell which names cross the boundary" | | an **unparsed** leaf | "part of the selection did not parse" | | a **module/package/class** declaration | "…a declaration of its own" | **Dataflow and names** (`flow.rs`, `boundary.rs`): | when | the sentence says | | --- | --- | | a name is declared **inside** and used **outside** | "move the declaration of `x` out of the selection first" | | a name is **driven on both sides** | "`x` is driven on both sides of the selection." | | the selection **passes a crossing signal to a routine** | "only that routine's declaration says whether it is an argument in or out" | | the selection drives it and something **outside passes it to a routine** | "lucisv will not make it an output over that" | | a crossing name is a **genvar / function / task / type / enum member / instance / modport / clocking block / class / named block** | "lucisv makes ports out of signals and parameters and nothing else" | | a crossing name has an **unpacked dimension** | "lucisv does not turn one into a port this round" | | a crossing declaration has a **qualifier** (`var`, `const`, `automatic`) | "lucisv does not move a qualifier into a port list" | | a crossing declaration has a **net delay** | "…does not move a delay into a port list" | | a crossing type is an **anonymous aggregate, a parameterized reference or a virtual interface** (an interface-typed name among them) | "a type lucisv does not move into a port list" | | a **type parameter** crosses | "lucisv does not carry one into a new module this round" | | a parameter's default is written **across several lines** | "lucisv does not re-flow one into a new module's header" | | a header (a port's or a parameter's type, a default) **names something that is not a parameter** | "which is neither a parameter nor a name a module in another file could reach" | | a **hierarchical reference** crosses (`u_x.sig`, either direction) | "a hierarchical path does not survive being moved into another module" | | a name is declared **outside `M` at file scope** (a compilation-unit `typedef`, `localparam`, class) — new file only | "a module in a file of its own would not see it" | | a package name is used **unqualified with no import to carry** | "write the package out, or import it where the new module can see it" | **Instantiations inside the selection** (`flow.rs`): | when | the sentence says | | --- | --- | | **positional** connections | "convert it to named connections first" | | **`.*`** | "expand the `.*` first (lucisv offers that as its own refactoring)" | | **`.p`** with no expression | "which names no expression for lucisv to move" | | a connection lucisv could not read | "cannot tell what the selection drives" | | the module has **no single indexed declaration** | "no single indexed declaration of it" | | a `.port` the module does not declare | "cannot tell whether it is driven" | | a port with **no direction** | "cannot tell whether the selection drives it" | **The workspace and the new file** (`mod.rs`): | when | the sentence says | | --- | --- | | the new name is **not a plain identifier** (empty, leading digit, a space, an escaped `\name`) | "not a plain SystemVerilog identifier, and lucisv will not name a module — or a file — with anything else" | | the workspace **already declares** the new name | "pick a name nothing else uses" | | the new name **is `M`'s** | "already the name of the module you are in" | | `M` is **declared twice** in the workspace | "declared in more than one indexed file" | | lucisv **indexes no `M`** | "indexes no module named `M`" | | the file **does not parse** | "does not parse (… at line N)" | | there is already a file at `N.sv` | "there is already a `N.sv` beside this file" | | a **`` `timescale ``, `` `default_nettype `` or `` `resetall ``** is in force before `M` — new file only | "a new file would not inherit it; extract into the same file, or move the directive into an include both files use" | ## Where the new module goes, and the client capability behind it A file `N.sv` beside `M`'s is a **`CreateFile` resource operation**, and LSP only lets one be sent inside `documentChanges`. So the server reads, at `initialize`, both halves of the capability — `workspace.workspaceEdit.documentChanges == true` **and** `workspace.workspaceEdit.resourceOperations` containing `create` — the way §37 reads `codeAction.resolveSupport` (`main.rs::create_files_support`, `ClientAbilities::create_files`). Then: * **can create files** (VS Code does): `Home::NewFile`. The edit is `documentChanges: [CreateFile(N.sv), TextDocumentEdit(M.sv), TextDocumentEdit(N.sv)]`. * **cannot** (or a caller that asked for it): `Home::SameFile`. `N` is written below `M` in `M`'s own file, as one ordinary `changes` map — no capability of any kind. The `` `timescale `` refusal does not apply, because the same file inherits it. Either way the engine says which happened, in the first of its warnings, so the user is never left guessing where their module went. ## The name, and how the user is asked for it LSP has no prompt. A code action may carry an `edit`, a `command`, or both, and only a `command` can be intercepted by a client that wants to ask the user something first — so the action carries **`lucisv.extractModule [uri, range, "M_extracted"]` and no edit**. That is also what makes it the laziest action in the server: the offer is one parse of one buffer (`extract_site`), and no workspace is read until the user has both picked the action *and* named the module. The VS Code extension steps in through the language client's **`middleware.executeCommand`** (`editors/vscode/extract.js`), not through a command of its own: `vscode-languageclient` registers every command the server advertises in `executeCommandProvider` with `vscode.commands.registerCommand`, so a second registration of the same id would collide at activation. The middleware shows an input box prefilled with the default, validates against the same identifier rule the engine enforces, and hands the typed name to `next`. A cancelled box sends nothing at all. Every other client runs the command as sent and gets the default name — or passes its own, which is the documented API. ## The verifier, and the one widening (CLAUDE.md invariant 4) Everything is one `check::verify_move` over the whole edit — the splice contract unchanged: the pieces comparison, the parse check, and resolution identity outside the edited ranges, in every watched file. **The widening.** `never_dropped`'s three equations used to be kept per file, which is exactly right for every refactoring that stays inside one file and exactly wrong for a move: a comment the selection carries is *deleted* in `M.sv` and *written* in `N.sv`, so neither file balances on its own. So the counting was factored into a `Ledger`, and `verify_move` takes a `moving: &[(usize, TextRange)]` list. **The widening is bound to the bytes that move, not to the files** (the 2026-09-06 rework; QA's finding V1). `moving` names every file the move touches: a **source**, with the byte range the move takes its text out of — the selection — and a **destination**, a file that only receives, with an empty range. A ledger is one file's, always. Per file `f` and per never-dropped text `t`, with `before`/`after` the file's own counts, `gone` the old pieces a non-empty edit range covers, `wrote` the pieces the edits' own text spells, and `out` the pieces of `gone` inside `f`'s region: 1. `after_f + out_f >= before_f` — nothing is lost; a file may end short only by exactly what left through its own region. 2. `wrote_f <= (gone_f - out_f) + in_f`, unless the text is one a refactoring `generated` — nothing is duplicated. `in_f` is the whole transit (`Σ out`) for a destination and zero everywhere else, so **a deletion outside the region is an ordinary deletion that has to be written back in its own file**. 3. `after_f == before_f - gone_f + wrote_f` — the applied text says exactly what the edits say, transit out counted as gone and transit in as wrote. 4. `Σ over destinations of (wrote - gone) == Σ over sources of out` — the transit lands, exactly once, in the files the move named. A file `moving` does not name keeps the per-file contract untouched, so a piece in transit to a file the move never named is refused twice over (by that file's rule 2 and by rule 4). `verify_splice` is `verify_move(…, &[])` and is byte-for-byte the old behaviour. The positional piece comparison is untouched and still runs per file. **The masked-corruption attacks** — crafted (plan, corrupted plan) pairs the widening could plausibly forgive. All of them go through the **production** entry point: a real `Scope` over the two files, the raw `TextEdit`s, and `check::verify_move` itself, `positions_match` and all (QA's V1: the six they replace went through a ledger-only test helper, which is why the first row below was invisible). In `check/ledger.rs`'s and `check/mod.rs`'s test modules: | # | the pair | verdict | | --- | --- | --- | | 1 | the honest extraction the engine produces — comment *and* `(* keep *)` in transit | **accepted** | | 2 | `M` holds the same comment twice; the plan deletes the copy **outside** the region as well and writes the moved one into `N` twice, so the pair balances 2-in/2-out | **rejected** — "comments are never dropped", naming `m.sv` | | 3 | the comment in transit written **twice** into `N` | rejected — "never duplicated" | | 4 | deleted in the region and **also** written back into `M` above the instantiation | rejected — "never duplicated" | | 5 | deleted in the region and written **nowhere** | rejected — "would move … and write it back nowhere; comments are never dropped" | | 6 | the same for an **attribute** `(* keep *)` | rejected — "attributes are never dropped" | | 7 | `N` writes a comment **nothing** put in transit | rejected — "never duplicated" | | 8 | `N` writes `/* TODO: connect */`, the `generated` whitelist | **accepted** — the whitelist is unchanged | | 9 | the module text written into a **third file the move did not name** | rejected — that file keeps the per-file contract | | 10 | the deletion **widened past the region** swallows `// the rest` | rejected — naming that comment | | 11 | the `moving` range does **not cover** what the edits delete (the planner lied about its region) | rejected — "comments are never dropped" | | 12 | the honest extraction with an **empty** `moving` | rejected — the widening is opt-in | `confirm` is the second net, as in `ports`: the edited text is read back and the new module's header must declare exactly the ports and parameters the plan promised — `verify_move` proves the edit is honest, nothing in it proves the header lucisv wrote is the header it meant to write. ## Assumptions * **The selection covers whole module items.** An item's own comments and attributes travel with it exactly when the selection covers them too, so a selection starting on the item's line leaves the note above it behind and one starting a line earlier takes it along. An empty selection — a bare cursor — is read as the item it is on, because that is what an editor sends when nothing is selected. * **The region's text moves verbatim.** Items are module items in `M` and module items in `N`, at the same nesting depth, so the source's own indentation is already right and every comment, attribute and string travels byte for byte — which is what lets the splice verifier count them. The header lucisv writes around them is two-space-indented; the formatter reconciles the two on the next save, and the tests pin that the result formats and converges. * **A hierarchical reference inside the selection is judged by §49's surface.** `Resolution::ExternalCandidate { surface: Hierarchical }` is recorded exactly when the head resolved to an instance; the head is found as the nearest earlier reference resolving to an `Instance` with only a dotted path between the two. A hierarchical path whose head instance the selection *also* moves is allowed; every other one refuses. * **A module, an interface and a package are visible from every file**, so one declared beside `M` never becomes a port and never refuses. A `typedef`, a `localparam` or a class at **file scope** is a compilation-unit declaration and does refuse — for a new file. * **`M` is declared exactly once in the workspace lucisv was handed.** The server hands the engine the fan-out of the units the selection names, so a second `M` the index knows about is one the engine sees. * The extraction does not rename anything and does not reorder anything. If the user wants the new module's ports in a different order, that is `remove_port`/`add_port`'s job. ## Handshakes * **`vlog_refactor::RefactorEdit`** (widened, additive). New field `created: Vec` — the files the refactoring creates, each of which also appears in `edits` with one insertion at offset 0. Every existing producer sets it to `Vec::new()`; every existing consumer that ignores it gets exactly what it got before. * **`vlog_refactor::check`** (internal). `verify_splice` now delegates to `verify_move(scope, edits, watched_names, what, moving)`, where `moving` is `&[(usize, TextRange)]` — a file with its moved region, or with an empty range for one that only receives; `never_dropped` is now `Ledger::of` + `Ledger::check` with `Transit` holding the two halves of a move to each other, and `pieces_match` takes a pre-lexed `Split`. `watched_files` takes a `&[&str]` of names rather than two. `check.rs` is now `check/mod.rs` plus `check/ledger.rs` (a pure move; the paths are unchanged). All crate-internal; no call site outside `vlog_refactor` sees any of it. * **`lucisv_server::server::ClientAbilities`** (new field). `create_files: bool`, read at `initialize` by `create_files_support`. * **`lucisv_server`** — one new module (`extract.rs`), one new code-action kind (`refactor.extract`) in `capabilities`, one new command in `commands()`, and two new branches in `server/dispatch.rs` (the `codeAction` fan-out, and the `executeCommand` split — the extract command is routed before `ports::execute` because it needs the client's own capability). `ports::workspace_edit` is reused unchanged for the same-file case. * **`editors/vscode`** — one new module (`extract.js`) and its test (`extract_test.js`), plus `clientOptions.middleware.executeCommand` in `extension.js`. No `package.json` change: the command is registered by the language client from the server's own `executeCommandProvider`, and contributing it again would put it in the command palette without its arguments. * **Request to `vlog_semantic`: none.** Everything the engine needed was already public (`Semantics`, `Resolution`, `Surface`, `WorkspaceIndex`). ## Status / TODO - [x] 53.1 extract: dataflow ports, parameters, imports, the new file, refusals, action + command + extension input box - [ ] 53.2 inline: substitution, prefixing, refusals, action + command — **unstarted**, see "What §53.2 still needs" below - [ ] the extract → inline round trip pinned — **blocked on 53.2** - [x] docs; §8 lines annotated; site rows (lead — see below) - [x] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks - [ ] QA ## What §53.2 still needs (unstarted) Nothing in §53.1 was shaped to make §53.2 harder, and two things were shaped to make it easier: * `RefactorEdit::created` and `check::verify_move`'s `moving` list are general. An inline moves text the other way — out of `S.sv` into `M.sv` — and, if it ever deletes `S.sv`, will want a `deleted` field beside `created`. * `flow.rs`'s write/read classification is the same question an inline asks of `S`'s body when it decides which of `M`'s names a substituted port may be bound to. It is `pub(super)` today and would move up a level. The refusal list in TODO §53.2 stands as written; none of it has been implemented, and no `refactor.inline` action is offered. ## Gate numbers after the rework (2026-09-06, all guarded) | Gate | Result | | --- | --- | | `cargo fmt -p vlog_refactor` | clean | | `cargo clippy --all-targets` | clean, no new `#[allow]` | | `cargo test --workspace` | **4 081 passed, 0 failed, 44 ignored** (4 073 + 5 verifier attacks + 3 extract tests) | | `tools/corpus_check.sh` | **814/820 (99.3%)**, the same six parse errors, 0 verification errors | | corpus extraction trial (860 files) | **5 extracted, 6 refused**, unchanged; the census holds at 10 268 for every one | | opentitan extraction trial (237 files, scratch copies of `hw/ip/{aes,uart,spi_host,hmac}`) | **5 extracted, 5 refused**; census 10 614 → 10 614 for every extraction | The opentitan trial is now reproducible as run: copy `hw/ip/{aes,uart,spi_host,hmac}` (237 `.sv`/`.svh`/`.v` files, opentitan at `0098135264`) to a scratch tree and point `LUCISV_EXTRACT_ROOT` at the copy. The trial prints each accepted extraction with its census and each refusal with its sentence, so the list below is what it says. | file | module | outcome | | --- | --- | --- | | `aes/dv/sva/aes_idle_check.sv` | `aes_idle_check` | extracted, census 10 614 → 10 614 | | `aes/dv/sva/aes_masking_reseed_if.sv` | `aes_masking_reseed_if` | **refused** — inside an `interface` (QA's V2; this one used to extract and cost four names) | | `aes/dv/sva/aes_reseed_if.sv` | `aes_reseed_if` | **refused** — inside an `interface` | | `aes/dv/tb/tb.sv` | `tb` | refused — `tb` declared in more than one indexed file | | `aes/pre_dv/aes_cipher_core_tb/rtl/aes_cipher_core_tb.sv` | `aes_cipher_core_tb` | extracted, census unchanged | | `aes/pre_dv/aes_sbox_lec/aes_sbox_masked_wrapper.sv` | `aes_sbox_masked_wrapper` | refused — `prd_masking` passed to a routine outside | | `aes/pre_dv/aes_sbox_tb/rtl/aes_sbox_tb.sv` | `aes_sbox_tb` | extracted, census unchanged | | `aes/pre_dv/aes_tb/rtl/aes_tb.sv` | `aes_tb` | refused — `entropy_q` passed to a routine outside | | `aes/pre_dv/aes_tb/rtl/aes_tb_c_dpi.sv` | `aes_tb_c_dpi` | extracted, census unchanged | | `aes/pre_dv/aes_tb/rtl/aes_tb_reqs.sv` | `aes_tb_reqs` | extracted, census unchanged | (The trial stops at five extractions, which is why the scan ends inside `aes/`.) `git -C …/opentitan status --porcelain` shows the same three pre-existing files before and after; nothing but scratch copies was read. ## Gate numbers (2026-09-05, all guarded) | Gate | Result | | --- | --- | | `cargo fmt -p vlog_refactor -p lucisv_server` | clean | | `cargo clippy --all-targets` | clean, no new `#[allow]` | | `cargo test --workspace` | **4 073 passed, 0 failed, 44 ignored** (baseline 4 020) | | `tools/corpus_check.sh` | **814/820 (99.3%)**, the same six | | `format --stdout` vs `~/.cache/lucisv-baselines/lucisv-0.46.0` over 860 corpus files | **854 identical, 0 differing**, 6 refused by both | | `cargo build --release -p lucisv -p lucisv_server` | ok | | `node editors/vscode/smoke.js target/release/lucisv-server` | OK | | `node editors/vscode/extract_test.js` | OK, 31 checks | | corpus extraction trial (860 files) | **5 extracted, 6 refused**, every result parses, formats, converges; the design's unresolved-name census unchanged | | opentitan extraction trial (244 files, scratch copies) | **5 extracted, 11 refused**, same checks | **Not this lane's:** `docs/coverage_gaps.md` is modified in the working tree (the L9 row, about §37's lazy resolve). It was already modified when this lane started and nothing here touched it — flagged rather than reverted, per the file-ownership rule. ## Measurements Production lines (non-blank, non-comment), all under the 600 target: | file | lines | | --- | --- | | `vlog_refactor/src/extract/mod.rs` | 381 | | `vlog_refactor/src/extract/flow.rs` | 534 | | `vlog_refactor/src/extract/boundary.rs` | 352 | | `vlog_refactor/src/extract/render.rs` | 303 | | `vlog_refactor/src/extract/region.rs` | 155 | | `lucisv_server/src/extract.rs` | 286 (incl. tests) | `check.rs` reached **702 production lines** with the rework's equations on board, over the 600 target, so it was split (2026-09-06, a pure move — public paths, behaviour and output all unchanged): | file | production lines | one sentence | | --- | --- | --- | | `vlog_refactor/src/check/mod.rs` | 392 | verify the whole edit — token identity, the parse check, resolution identity — or refuse it whole | | `vlog_refactor/src/check/ledger.rs` | 334 | the pieces a file is made of, the comparison that says an edit wrote what it promised, and the ledger of the ones that are never dropped | ## Work log **2026-09-05 — dev (§53.1).** Read §52's engine and README, `ports/`'s splice/`confirm` spine, `instantiate.rs`, `check.rs`, `vlog_semantic`'s model and §49's surface, and the server's lazy-action and command plumbing. Then, in order: 1. **`check.rs`: the widening first**, so the rest could be built on a verifier that admits a cross-file move. `never_dropped` became `Ledger::{add,check}`, `pieces_match` became `Split::read` + `Split::positions_match` + a per-file `pieces_match` over the pair, and `verify_splice` became a `verify_move` with an empty `moving` list. Six masked-corruption attacks written at the same time (invariant 4), including one that pins the widening as opt-in. 2. **`extract/region.rs`** — the selection, the whole-item rule and the item-kind refusals. Decision: an item's extent includes its own comments *only when the selection covers them*, which is what makes a selection do what the user's mouse said. Second decision: an empty selection is the item under the cursor, so the action is available without dragging. 3. **`extract/flow.rs`** — the dataflow. The classification is a second implementation of a question `vlog_linter::signals` also answers, and that was deliberate: `vlog_refactor` may not depend on `vlog_linter` (it would pull in `lucisv_core`), the linter's table is `pub(crate)`, and the two questions differ where it matters — the linter's rule is *say nothing when unsure*, this one's is *refuse when unsure*. Recorded here rather than hidden: if a third caller ever wants it, the shared home is `vlog_semantic`. 4. **`extract/render.rs`, `extract/mod.rs`** — the header, the new module, the instantiation through `instantiation_plan`. The new file joins the in-scope set as an **empty file** before anything else happens, so the index, the analysis and the verification all ask about it exactly the way they ask about a file that was always there. 5. **`lucisv_server/src/extract.rs`**, the capability, the dispatch, and `editors/vscode/extract.js`. **Two defects the trials found, both fixed and both pinned by a test.** * *The corpus.* `common_cells/src/binary_to_gray.sv` extracted into a module whose ports read `input logic [N-1:0] a` with no `N` anywhere: the parameter is named by the **port's own type**, and no statement in the selection names it, so a closure over the region's references alone never wanted it. Fixed by seeding the parameter closure with the words of every port's rendered prefix (and of every parameter's, transitively) — `boundary::depends`. Pinned by `a_parameter_a_ports_own_width_names_crosses_with_it`. * *opentitan.* `hw/ip/aes/rtl/aes_ctr.sv` writes `module aes_ctr import aes_pkg::*;` and the extraction copied **no import at all**, leaving `sp2v_e` and `Sp2VWidth` naming nothing. The binder records a wildcard import in a reference's `paths` as `p::*` — the spelling the source wrote — and the judgement was matching `p::`. Fixed by comparing against `Import::path()`, which is that same spelling, with `Import::supplies` as the gate. Pinned by `a_wildcard_import_in_the_header_is_carried_across` and `a_named_import_is_carried_across_only_when_the_name_it_supplies_is_needed`. Both were caught by the **census** — the number of names the design cannot resolve, before and after — which is why the trial asserts on it rather than on "it parsed". Neither would have failed a parse check. **One split, mid-round.** `extract/mod.rs` reached 685 production lines, over the 600 target, so the boundary classification moved to `extract/boundary.rs` (pure move; the test count did not change). mod.rs is 376. **Deviations from the plan, all deliberate and all named:** * **`53.2` is unstarted.** §53.1 alone consumed the round, as the brief anticipated; a finished half beats two unfinished ones. The round-trip pin is blocked on it. * **The refusal for a routine's argument is broader than the plan's letter.** The plan says "a task/function call's output argument"; lucisv cannot tell an output argument from an input one without the prototype, so it refuses on *any* argument position that names a crossing **signal**. A crossing *parameter* in an argument (`$clog2(WIDTH)`) is untouched — a parameter has no direction. In practice the common case is already refused a step earlier, because a routine declared in `M` outside the selection and called inside it refuses on its own. * **The hierarchical refusal is conservative in one shape.** A hierarchical path whose head instance the selection also moves is allowed, and that is decided by a nearest-earlier-instance-reference-with-a-dotted-path heuristic. Where the heuristic cannot find a head at all, the extraction refuses (naming `….sig`), which is the safe direction. * **A file-scope `typedef` in `M`'s own file refuses for a new file and is allowed for the same file.** The plan does not name this refusal; it is forced by the language (a compilation-unit declaration does not reach a file that was not compiled with it), and the same-file fallback is exactly the escape hatch. * **The action carries a command rather than a resolvable edit.** The plan says "lazy"; a command with no edit is lazier, and it is the only shape a client can put an input box in front of. **2026-09-06 — dev, rework (QA's V1, V2 and the LOW).** **V1 — the pool was bound to the wrong thing.** `verify_move` pooled one never-dropped ledger over whole *files*, so a pair of individually-honest edits could balance in aggregate while one file lost content nothing ever moved: QA's `m.sv` deletes an untouched second copy of a comment, `n.sv` writes a duplicate of the moved one, 2 in and 2 out, accepted. Fixed by binding the allowance to the **bytes that move**. `moving` is now `&[(usize, TextRange)]` — a source with its region, a destination with an empty range — a `Ledger` is one file's again, and `Transit` holds the halves of a move to each other. The four equations are written out above and in `verify_move`'s doc comment; the one that does the work is rule 2's `wrote_f <= (gone_f − out_f) + in_f`, which says that **a deletion outside the region is an ordinary deletion, to be written back in its own file**, exactly as it always was. QA's pair now refuses with "comments are never dropped", naming `m.sv`. The twelve attack pairs in the table above all go through the production `verify_move` with a real `Scope` and raw `TextEdit`s — the `pooled()` helper QA objected to is gone, and with it the last place a corruption could be judged without `positions_match` also having its say. Corruption is expressed as a corrupted *plan* rather than a corrupted applied text, which is one notch more real: the verifier applies the edits itself. `check.rs` was 618 production lines before this and 702 after, so it was split into `check/mod.rs` (392) and `check/ledger.rs` (334) — a pure move: the same items, the same `crate::check::…` paths, the same tests, `cargo test -p vlog_refactor` unchanged but for the rework's own additions. **V2 — the `kw` gate.** `vlog_parser` writes `module`, `interface` and `program` as one `ItemKind::Module` distinguished only by `Module::kw`, and `region.rs::module_at` never asked. `Region::read` now calls `extractable`, which accepts `module`/`macromodule` and refuses the other two with the sentences the refusal table promises. `extract_site` reads the same `Region`, so the code action is no longer offered inside an interface either. Pinned by `a_selection_inside_an_interface_or_a_program_is_refused` and `the_action_is_not_offered_inside_an_interface_or_a_program`, and by the opentitan trial above: `aes_masking_reseed_if.sv` and `aes_reseed_if.sv` are now refusals, and every accepted extraction leaves the census at 10 614. **The LOW — a member access names its head.** `boundary::visible` refused with the field (`data`, `f`), which reads as if the field were a signal of `M`'s own; what crosses the boundary is the port or the variable. A text-side `access_head` reads `s` out of `s.f` and `b` out of `b.data`, and the refusal is now "the selection uses `b.data`, and `b` is declared with a type written outside `m` in the same file…". Pinned by `a_crossing_member_access_names_the_head_and_the_field_second`. **No existing expectation was altered.** The three tests whose text changed are the ones the rework replaces (the six `pooled()` attacks became the twelve `verify_move` ones); everything else — 40 in `tests/extract.rs`, the corpus trial's 5/6, the workspace's other 4 000 — is as it was. `tests/corpus.rs` gained two `println!`s (the census per extraction and each refusal's sentence), so a trial run is reproducible without patching it first. ## Docs to apply at merge (lead) **`docs/site/` — language-tools row.** Add beside organize-imports: > **Extract module** — select the `always` blocks, assignments or > instantiations that have grown into a module of their own, name it, and > lucisv writes it: ports and parameters inferred from what the selection reads > and drives, `import`s carried across, the items moved byte for byte, and the > instantiation that replaces them rendered from the new module's own text. A > file of its own where the editor can create one, below the module it came > from where it cannot. Refuses — with a sentence — wherever a direction > cannot be known: a routine's argument, a `.*`, a positional connection, a > module the index cannot pin down, a name both sides drive. **`README.md`** — the refactorings list gains one entry beside the port ones: > * **extract module** (`refactor.extract`, `lucisv.extractModule`) — a > selection of whole module items becomes a module of its own, with ports > inferred from the dataflow across the boundary. **`docs/topo.md`** — two edges to record: * `vlog_refactor::RefactorEdit::created` — a new public field, read by `lucisv_server::extract` only. `lucisv_server ◀── vlog_refactor`, widened. * `lucisv_server::server::ClientAbilities::create_files` — a new capability read at `initialize`, consumed by `server/dispatch.rs` only. **`TODO.md` §8** — the extract-module line is annotated in place (done by this lane); the inline-module line is **not**, because §53.2 is unstarted. §53's own checkboxes are ticked except 53.2, the round trip, and the QA line. ## QA log **2026-09-06 — QA (§53.1 only).** Read this README, the diffs (`check.rs`, `vlog_refactor/src/extract/{mod,region,flow,boundary,render}.rs`, `tests/{extract,corpus}.rs`, `lucisv_server/src/extract.rs`, `server/{dispatch,mod}.rs`, `main.rs`, `editors/vscode/{extract,extension}.js`), then attacked the verifier, attacked the dataflow rule with hand-picked shapes, read the server/extension wiring, and re-ran the trials and every gate. Two confirmed defects, both HIGH, below; verdict is **REWORK**. ### Priority 1 — the verifier widening (`check.rs`) All six of the dev's own attack tests were re-read and re-run (`cargo test -p vlog_refactor --lib check::`, 44/44 pass, including all six under `the pooled ledger, and the attacks on it`). They are sound, but they all go through the dev's own `pooled()` test helper, which calls `Ledger::add`/`Ledger::check` **directly** and never calls `Split::positions_match` — so they exercise the aggregate-count equations in isolation, not the full `verify_move` path a real refactoring goes through. I re-attacked through the *production* entry point instead: a `Scope` built from real files, raw `TextEdit`s, and `check::verify_move` itself (temporary tests, removed after; reproductions below use the same shape so the dev can paste them back in). | # | attack | via | result | | --- | --- | --- | --- | | 1 | comment deleted in M, written in N once | `verify_move` | **ACCEPTED** (correct) | | 2 | comment deleted in M, written in N twice | dev's `pooled()` | REJECTED — "never duplicated" | | 3 | deleted in M, written in N *and* left in M | dev's `pooled()` | REJECTED — "nothing was edited" | | 4 | deleted in M, written nowhere | dev's `pooled()` | REJECTED — "never dropped" | | 5 | written in N, never deleted in M (invented) | flow.rs makes this unreachable via the real edits, but the equation (`writes > deleted`) rejects it directly in `Ledger::check` | REJECTED | | 6 | deleted in M, written into a **third file not in `moving`** | `verify_move`, 3 files, `moving=[m,n]` | REJECTED — the third file's own per-file `pieces_match` sees an invented write ("never duplicated"); confirmed by re-attack | | 7 | same honest move, `moving` **empty** | dev's test 6 | REJECTED — "never dropped" (opt-in confirmed) | | 8 | attribute `(* keep *)` in transit, balanced / lost | dev's tests 1–2 | ACCEPTED / REJECTED correctly | | 9 | **two identical comments, one moved and one left untouched**, corrupted so the pool balances (2 in, 2 out) but `m.sv` alone loses the *untouched* copy while `n.sv` gains a *duplicate* of the moved one | `verify_move`, real `Scope` + hand-edits | **ACCEPTED — FORGIVEN. HIGH.** | | 10 | `moving` naming a file the edits never touch | `verify_move` | inert — honest move still verifies, no false accept | | 11 | `moving` naming the same file index twice | `verify_move` | same as naming it once | | 12 | edit outside `moving` (file left out) deletes a comment | `verify_move` | REJECTED — old per-file contract, unwidened | **Finding V1 (HIGH) — the pooled ledger can forgive a per-file loss when a second, textually-identical never-dropped piece is in play.** `Ledger::check` (`crates/vlog_refactor/src/check.rs:617`) only ever compares *counts* of a `(noun, text)` key summed over every file named in `moving` (`Ledger::add`, `check.rs:602`). `Split::positions_match` (`check.rs` — the per-file token-position comparison) still runs for every pooled file, but it only checks that applying that file's *own* edits produces that file's *own* claimed text — it says nothing about whether a piece that disappeared from position N in file A was legitimately moved to file B or simply invented/lost independently. Two edits that are each "positionally honest" for their own file can therefore corrupt correctness as a *pair*: `m.sv`'s edit deletes an extra copy of a comment nobody meant to move, `n.sv`'s edit writes an extra copy of the one that did, and the pool's aggregate math (`before=2, deleted=2, writes=2, after=2`) is satisfied by construction, even though `m.sv` alone lost content it never gave up. Reproduction (paste into `check.rs`'s test module, real `verify_move`, no `pooled()` helper): ```rust const TWO_NOTES: &str = "module m (\n input logic a,\n input logic b,\n output logic p,\n output logic q\n);\n assign p = a; // note\n assign q = b; // note\nendmodule\n"; // m_edits: delete the untouched first "// note" (own TextEdit, empty // new_text) AND replace "assign q = b; // note" with an instantiation. // n_edits: one insertion of a whole `module second` whose body writes // "// note" twice. // files sorted by Scope::build: m.sv, second.sv. verify_move(&mut scope, &plan, &["m", "second"], MOVED_WHAT, &[0, 1]) == Ok(()) // ^ should be Err; it is Ok. ``` This is not a shape the current `extract` engine is known to *produce* today (no corpus or opentitan trial hit it) — it is the shape CLAUDE.md invariant 4 asks every widening to be attacked with regardless, because a future bug in `render.rs`'s comment-carrying code (or a second consumer of `verify_move`, which `RefactorEdit::created`'s Handshakes note §53.2 will be) could produce exactly this pair and the safety net would wave it through. Needs: either a per-piece *identity* (not just count) carried through the pool — e.g. an edit-relative source position tag on each `Piece::Comment`/`Piece::Attr` so a piece can only balance against its own counterpart — or an explicit bound that a file's own per-file delta (`after - (before - deleted)`) can only be negative (a piece leaving) when `moving` is non-empty *and* the piece actually appears in another pooled file's `writes` at least once **per occurrence**, not just in aggregate. Left to the dev; QA does not redesign. ### Priority 2 — the dataflow rule and the extraction Read `region.rs`, `flow.rs`, `boundary.rs`, `render.rs`, `mod.rs` in full. Cross-referenced every row of the brief's dataflow matrix against `tests/extract.rs`'s existing 33 tests (thorough — combinational, sequential, parameter+import, parameter-in-port-type, wildcard/named import, file-scope-typedef refusal, both-sides-write, routine-argument refusal, hierarchical refusal, unpacked-dimension refusal, positional/`.*`/no-such-port instantiation refusals, timescale/default_nettype, name-collision refusals, cursor-as-selection, the reference census). Then ran additional scratch extractions (temporary `tests/qa_scratch_53_1.rs`, removed after) for rows the existing suite does not cover: | row | result | | --- | --- | | struct member write `s.f = a` (S declared as a port) | ACCEPTED, `s` becomes `output` — correct, but see Finding L1 | | same, `s.g` also written outside the region | REJECTED — "`s` is driven on both sides" (base-of-lvalue rule confirmed for `Member`) | | part-select write `x[3:0] = a` alone | ACCEPTED, `x` becomes `output` | | same, `x[7:4]` also written outside | REJECTED — "`x` is driven on both sides" | | interface signal write `b.data = a` (`bus_if.mp b` port) | REJECTED — "declared outside `m`" (see Finding L1: names the field, not the interface) | | pure-function-read argument `twice(a) + twice(a)` | REJECTED — confirms the dev's documented over-refusal (any argument position, not just outputs) | | hierarchical reference whose head instance is inside the selection | ACCEPTED — confirmed the allowed case | | whole-module-body selection | ACCEPTED — M is left holding only the instantiation | | `localparam` used inside | ACCEPTED — becomes a `parameter` of N with the default carried, matches README | | comment on a standalone line between two selected items | travels into N with both items' own trailing comments, all three intact | | `case` expression read | ACCEPTED as `input` | **Finding V2 (HIGH) — `region.rs::module_at` accepts a selection inside an `interface` or `program` body, contradicting the documented refusal ("a selection in an interface/program (refused)", TODO §53.1 and this README's refusal table), and produces a measurable correctness regression on real RTL.** `vlog_parser`'s AST uses one `Module` node for `module`/`interface`/`program` (`crates/vlog_parser/src/ast/module.rs:8-16`, distinguished only by `Module::kw`). `Region::read`'s `module_at` (`crates/vlog_refactor/src/extract/region.rs:80-92`) matches `ItemKind::Module(module)` and never inspects `module.kw`, so it treats an `interface` (or `program`) exactly like a `module`. Nothing downstream catches it either — `extract_site` (the cheap gate offered as the code action) uses the same `Region::read`, so the action is even *offered* inside an interface. Minimal repro (ran directly, `extract_module` on a 5-line `interface`): ``` interface bus_if; logic [7:0] a; logic [7:0] q; assign q = a; endinterface ``` → **ACCEPTED.** Produces `module n (...); assign q = a; endmodule` as a new file, and rewrites the interface body to `n u_n (.a(a), .q(q));` — a module instantiated inside what remains an `interface`. Confirmed as a **real regression, not just a spec gap**, via an independent opentitan trial: copied `hw/ip/{aes,uart,spi_host,hmac}` (237 files, read-only source, scratch copies only — `hw/ip/aes/dv/sva/aes_masking_reseed_if.sv` is an `interface`) and ran the same automated region-scan the dev's own corpus trial uses. The very first `interface` region it reached (`aes_masking_reseed_if`'s `always_comb` block, driven off interface header parameters/ports and package imports) extracted "successfully" — both halves parsed, formatted and converged — **but the unresolved-name census over the two files went from 10614 to 10618**, i.e. four names that used to resolve no longer do. This is exactly the regression class the census assertion exists to catch (same mechanism as the two defects the dev's own work log documents), and it did: `cargo test -p vlog_refactor --test corpus five_regions_of_real_rtl…` with `LUCISV_EXTRACT_ROOT` pointed at the scratch copy fails at the census assertion, not the parse/format ones. (`opentitan` repo left untouched — `git -C .../opentitan status --porcelain` before and after this run shows only the three pre-existing baseline diffs named in the task brief.) Fix is a one-line gate at the top of `region.rs::module_at` (refuse unless `module.kw` is `"module"`/`"macromodule"`, with the existing `NO_MODULE` sentence or a dedicated one) — left to the dev, along with a regression test pinning both the direct refusal and the census non-regression on the `aes_masking_reseed_if` shape (or a corpus-sized equivalent) once fixed. ### Priority 3 — the server and extension over the wire Read `lucisv_server/src/extract.rs`, `server/dispatch.rs`, `server/mod.rs`, `main.rs`'s `create_files_support`, `editors/vscode/{extract,extension}.js`. Confirmed by reading and by the existing test suite (all green, see Gates): `codeAction` for a whole-item range returns the `refactor.extract` action with a `Command` and no `edit` (`a_selection_of_whole_items_is_offered_the_action_with_a_command_and_a_default_name`); not offered for a half-item range (`a_selection_that_covers_no_whole_item_is_offered_nothing`); `executeCommand lucisv.extractModule` with `create_files=true` returns `documentChanges: [CreateFile, TextDocumentEdit×2]` (`the_command_creates_the_new_file_for_a_client_that_can`); with `create_files=false` a `changes` map writing N below M (`the_command_writes_the_module_into_the_same_file_for_a_client_that_cannot`); `create_files_support` needs both `documentChanges` and `resourceOperations` containing `create` (`create_files_support_needs_both_halves_of_the_capability`, 5 sub-cases). The extract command is dispatched before `ports::execute` in `server/dispatch.rs` as documented. `grep -n registerCommand editors/vscode/*.js` shows no second registration of `lucisv.extractModule` — only `extract.js`'s doc comment mentioning the collision it avoids, and `hierarchyView.js`'s unrelated commands. `node --test editors/vscode/extract_test.js` — 31 checks, OK; the full `editors/vscode/*_test.js` run (extract, hierarchyModel, hierarchyView, restart) — 4/4 suites pass, no regressions. ### Priority 4 — trials - **Corpus** (`cargo test -p vlog_refactor --test corpus five_regions_of_real_rtl…`, unmodified `corpus/`): **5 extracted, 6 refused**, matches the dev's claim exactly. - **Opentitan, dev's own claim**: not independently re-run at the dev's exact 244-file selection (the checkout revision/subset used was not recorded reproducibly in the README); instead ran the same automated trial against an independently-chosen 237-file scratch subset (`hw/ip/{aes,uart,spi_host,hmac}`, read-only source untouched) — this is what surfaced Finding V2 above rather than reproducing "5/11". Given the finding, the dev's original 244-file number cannot be taken as clean either without knowing whether an interface region was among its refusals or its "successes". - **Five hand-picked opentitan-style regions** (struct member write, part select, hierarchical head-inside, whole-body, localparam-in-expression) — folded into the Priority 2 table above rather than run as a second batch, given time budget; all passed parse/format/convergence where accepted. - `lucisv check --select unused-signal,undriven-net,multiply-driven` before/after was not run separately from the reference census (the corpus/opentitan trials assert an equivalent, stronger, whole-reference census rather than a three-lint-rule census); not flagged as a gap since the stronger check subsumes it, but noted for completeness. ### Gates (guarded, all via `tools/guard.sh`) | Gate | Result | | --- | --- | | `cargo clippy --all-targets` | clean | | `cargo test --workspace` | **4 073 passed, 0 failed, 44 ignored** — matches the dev's claim exactly | | `tools/corpus_check.sh` | **814/820 (99.3%)**, same six parse errors | | `format --stdout` vs `~/.cache/lucisv-baselines/lucisv-0.46.0` over the 860 corpus files (independently scripted, not via corpus_check.sh) | **854 identical, 0 differing, 6 refused by both** — matches the dev's claim exactly | | `cargo build --release -p lucisv -p lucisv_server` | ok | | `node editors/vscode/smoke.js target/release/lucisv-server` | OK | | `node --test editors/vscode/extract_test.js` | OK, 31 checks | | `node --test editors/vscode/*_test.js` (full suite) | 4/4 suites, 0 failures | All temporary QA tests and scratch copies were removed before finishing; `git diff --stat` on `check.rs` is back to exactly the dev's own diff (416+/145-). `git -C .../opentitan status --porcelain` shows only the three pre-existing files named in the task brief, both before and after this QA pass. **Note to the lead, not this lane's to touch:** `CHANGELOG.md`, `editors/vscode/CHANGELOG.md`, `editors/vscode/README.md`, `docs/topo.md`, `docs/site/**`, and `TODO.md`'s `[x]` marks on "docs" and "Gates" changed during this QA pass (not by this session) — merge-time docs work appears to already be in flight in this tree. Given Finding V2 in particular, the already-ticked `TODO.md` "Gates (guarded)" line should be revisited once the dev fixes it, since the opentitan trial number behind that tick is now in question. ### Verdict: **REWORK** Two HIGH findings, both requiring a code change plus a regression test before re-review: 1. **V1** — the pooled ledger (`check.rs`, `Ledger::check`) can forgive a masked corruption where one pooled file loses an untouched never-dropped piece while another pooled file gains a duplicate, as long as the aggregate count balances. Confirmed via the real `verify_move` entry point, not just the `pooled()` test harness. 2. **V2** — `extract`'s selection gate (`region.rs::module_at`) does not check `Module::kw`, so it accepts a selection inside an `interface` or `program` body, contradicting the documented refusal and producing a confirmed reference-resolution regression on real RTL (`aes_masking_reseed_if.sv`, opentitan). One LOW note, not blocking: struct-member and interface-member-access refusal sentences ("the selection uses `f`…") name the accessed field rather than the type/port that is actually the crossing name, which is technically correct (the field genuinely has its own symbol at file scope) but reads as if `f` were expected to be a module-level signal. Cosmetic; no correctness risk since the refusal (not an accept) is the safe direction. The §53.1 QA checkbox in `TODO.md` is left **unticked** pending a fix and a second QA pass on V1 and V2. **2026-09-06 — QA re-attack of the rework (§53.1 only).** Read the dev's "2026-09-06 — dev, rework" entry above, `check/{mod,ledger}.rs` in full (the four equations, `Ledger`, `Transit`, `Split::positions_match`), the twelve `verify_move` attack tests in `check/mod.rs`'s "the moved-piece rule" section, and `extract/region.rs`'s `extractable`/`module_at`. Re-ran all twelve — all still pass and all still go through the production `verify_move` (a real `Scope`, raw `TextEdit`s, `positions_match` included; no `pooled()`-style helper remains anywhere in the crate: `grep -rn "fn pooled" crates/vlog_refactor` finds nothing). Then attacked the equations further with temporary tests (`crates/vlog_refactor/src/check/mod.rs`'s test module, `crates/vlog_refactor/ tests/extract.rs`; both removed before finishing — `git status --porcelain` on both shows them as the dev's own untracked additions, unchanged in line count from before this pass). ### Attack table (all through production `verify_move`) | # | attack | result | | --- | --- | --- | | 1a | two real sources (`a.sv`, `b.sv`), one destination (`n.sv`), transit sums correctly | **accepted** | | 1b | crosswise: `b`'s piece written into `a.sv` (a source, not the named destination) instead of `n.sv` | **rejected** — `a.sv` isn't credited to receive anything (`receives` is false for any file whose region is non-empty), so the write is an unexplained duplicate | | 1c | can one file be both a source and a destination? | **no, structurally** — `region_of` (`check/ledger.rs:187`) returns the *first* `moving` entry for a file index, and `Moved::receives` (`check/ledger.rs:384`) is derived solely from whether that one range is empty; a file cannot carry a real region and the transit allowance at once | | 2 | a source declares its own transit region as **empty** while its edit genuinely deletes-and-moves a piece | **rejected** (rule 1) — `within()` credits no `out` for an empty region, so the deletion has to balance on its own and can't | | 3a | `moving` names the same file index **twice** with different ranges | **inert** — `region_of`'s `.find` only ever sees the first entry; the second is dead weight, confirmed by comparing the dup-list outcome to the single-entry outcome (identical); reversing the order (empty entry first) does change the outcome, as expected, since now *that* entry is the one `.find` returns | | 3b | region covering the whole file | no panic, ordinary accept, nothing special about size | | 4a | a region **honestly** containing two identical comments, both really moved | **accepted** | | 4b | same byte shape, but framed as "the region was *widened* to swallow an unrelated second occurrence" | **also accepted** — the equations are byte-counting; they cannot and do not distinguish "the selection legitimately covers two occurrences" from "someone lied about what the selection covered." In production this never diverges because `extract/mod.rs:211,220` sets the edit's own delete-range and the `moving` region to the *same* `region.span` value, and `region.span` is built by `region.rs::Region::read` from real AST item spans — so the guarantee lives in the planner, not in the verifier. Recorded, not a new defect (same shape as the existing "region that does not cover what the edits delete" test, from the other side) | | 4c | destination `n.sv` already has one occurrence of the moved text **before** the edit; plan writes it once more / zero more / twice more | once → **accepted** (after = 2); zero → **rejected**, "never dropped"; twice → **rejected**, "never duplicated" — matches the spec exactly | | 5 | `/* TODO: connect */` **genuinely inside the moved region** (not merely coincidentally generated text absent from the source), deleted once from `m.sv`, written **twice** into `n.sv` | **rejected**, "never duplicated" — rule 2's `generated()` whitelist (`check/ledger.rs:312`) exempts only the *per-file* duplicate rule; `Transit::lands` (rule 4, `check/ledger.rs:413`) has no such exemption and still catches it, because the piece is present in `sent` (it really was deleted from inside the source's region). The whitelist only ever "wins" for text that was never in transit at all (`a_generated_placeholder_the_new_file_writes_is_not_a_duplicate`, where the key never enters `sent`) | | 6 | a **same-file** relocation: a piece outside the transit region, deleted at one position and written back at a different position in the *same* source file, alongside a legitimate cross-file move | **accepted — see Finding QA-1 below** | ### Finding QA-1 (MEDIUM) — `positions_match` cannot see a same-file relocation expressed as ordinary edits, through the production entry point Item 6 of the brief expected `positions_match` to refuse this ("the per-file rule accepts, but positions_match should refuse the relocation — confirm"). It does not. Reproduction (temporary test, `check/mod.rs`, `qa_a_same_file_relocation_outside_the_region_is_caught_by_positions_match`, removed after): `m.sv` legitimately sends one comment to `n.sv` in transit, and — unrelated, outside the region — deletes a second, distinct comment `// stray` from one position and re-inserts identical text a few lines later in `m.sv` itself, as two ordinary, well-formed, non-overlapping `TextEdit`s. `verify_move` returns `Ok(())`. Why: `verify_move` (`check/mod.rs:194-203`) always computes the post-edit text itself, as `apply(scope.text(*i)?, edits)` — no production caller (`verify_move`, `extract_module`, `convert_to_ansi`, `ports::*`) ever hands the verifier an independently-authored "after" text. `Split::positions_match` (`check/ledger.rs:101-165`) builds its `expected` piece sequence by re-walking the *same* `edits` list and interleaving their own declared `written` pieces — which is a second, piece-level implementation of "apply the edits," not an independent oracle. Since both `apply()` and `positions_match`'s reconstruction agree by construction whenever the edits are individually well-formed (sorted, non-overlapping), there is no discrepancy left for `positions_match` to catch: the relocation *is* what the (valid) edits define, and both edits are innocent-looking in isolation. This means the one existing test that demonstrates a positional rejection — `check::ledger::tests::a_move_that_left_the_comment_where_it_was_is_rejected` — is not reachable through `verify_move` at all. It calls the lower-level, test-only `pieces_match(before, after, edits, …)` directly with an `after` built by hand-editing the honestly-applied text with `.replace(...)` *beyond* what `move_edits()` declares — a shape no real caller can produce, because every real caller derives `after` from `apply()` over its own `edits`. Consequence for invariant 4: **Eq3 (`after == before - gone + wrote`, `check/ledger.rs:325-339`) is in the same position.** None of the twelve `verify_move` attack tests isolates it (see the equation map below), and by the same reasoning it cannot be reached in production either — any test that would need Eq3 to fire (an "applied text disagrees with what the edits' own bookkeeping predicts") requires an independently-supplied `after`, which `verify_move` never receives. Eq1 (grounded in the truly re-lexed `after` text) is the actual backstop for content loss/gain in production; Eq3 adds protection only against a divergence between `apply()`'s byte-level splice and the ledger's own piece-level counting (e.g. malformed/overlapping edits from a buggy future planner) — a scenario I attempted to construct (deliberately overlapping edits, exploiting `apply()`'s documented silent-skip of an overlapping edit) and could not turn into a case where Eq1 didn't already catch the resulting loss first. **Severity and recommendation, not a redesign:** this is not a regression from the rework (the same structure predates it, in the non-move `pieces_match`/`Ledger` too) and no current planner (`extract`'s `flow.rs`/ `boundary.rs`/`region.rs`, `ports::ansi`) produces an edit pair shaped like this — `extract`'s only same-file, non-transit edits are the instantiation replacement and, for `Home::SameFile`, one pure append. But per CLAUDE.md invariant 4 ("any equation no test proves is a finding"), Eq3 and `positions_match`'s value in the **move** context are currently unproven by any attack that goes through a real entry point, and a future bug in a planner (§53.2's inline, or a second consumer of `verify_move`) that computes correct *counts* but a wrong *position* for a never-dropped piece within one file would pass silently. Left to the dev/lead to decide whether a follow-up test (or accepting the gap as documented, since position-correctness for extraction is `region.span`'s job, not the verifier's) is warranted — not blocking this pass. ### Equation-to-test map (the twelve `verify_move` tests, `check/mod.rs`) | equation | proves it via | | --- | --- | | Eq1 `after_f + out_f ≥ before_f` | `a_copy_deleted_outside_the_region_is_not_one_the_move_may_balance` (QA's V1 pin), `a_deletion_wider_than_the_region_is_an_ordinary_deletion`, `a_region_that_does_not_cover_what_the_edits_delete_is_rejected`, and negatively via `the_widening_is_opt_in_…` (same equation, no `out` credit at all without `moving`) | | Eq2 `wrote_f ≤ (gone_f − out_f) + in_f`, generated-exempt | `a_comment_that_lands_twice_in_the_new_file_is_rejected`, `a_comment_left_behind_as_well_as_moved_is_rejected`, `a_comment_the_new_file_invents_with_nothing_in_transit_is_rejected`; positively (whitelist) `a_generated_placeholder_the_new_file_writes_is_not_a_duplicate`; and, via the *old*, unwidened per-file path (a file `moving` does not name), `a_piece_in_transit_to_a_file_the_move_did_not_name_is_rejected` | | Eq3 `after_f == before_f − gone_f + wrote_f` | **none of the twelve** — see Finding QA-1; empirically and structurally unreachable via `verify_move` today | | Eq4 `Σ_dest(wrote−gone) == Σ_src out` (`Transit::lands`) | `a_comment_the_move_carries_that_lands_nowhere_is_rejected`, `an_attribute_the_move_carries_that_lands_nowhere_is_rejected` (`a_comment_that_lands_twice_…` and the third-file test are caught earlier, by Eq2, before `lands()` ever runs) | | (positive control) | `the_move_the_engine_actually_produces_verifies` needs all four to pass at once | ### The `kw` gate (V2) and the opentitan reproduction `region.rs::extractable` (`region.rs:106-115`) accepts only `"module"` / `"macromodule"` and refuses `"interface"`/`"program"` with the documented sentences; `Region::read` calls it right after `module_at`, and `extract_site` goes through the same `Region`, so the action is not offered either. Both pinned tests (`a_selection_inside_an_interface_or_a_program_is_refused`, `the_action_is_not_offered_inside_an_interface_or_a_program`, `tests/extract.rs`) re-read and re-run, green. `macromodule` itself had no dedicated test before this pass; added one temporarily (`module.kw == "macromodule"`, closes with `endmodule` — a `macromodule`'s `end` keyword is `endmodule`, not `endmacromodule`, which is exactly the kind of thing worth having pinned) and confirmed it extracts and is offered identically to `module`; removed with the rest of the temporary tests since it wasn't asked for as a permanent addition, but worth the dev adding as a one-line permanent case given `macromodule` is the *other* accepted keyword and had zero coverage. A nested `module` declared inside a `generate` block: `region.rs::module_at` (`region.rs:82-94`) only scans the file's *top-level* items, one level, not recursively into a module's own `items` or a `GenBlock`'s. Read through by hand rather than tested: a selection actually inside such a nested declaration is always caught by the existing whole-item/`extent` machinery first — the enclosing `generate` item (or the nested module item itself) is treated as one indivisible item wider than any inner selection, so the result is a **safe refusal** ("cuts an item in half" or "a declaration of its own"), never a silent misattribution to the wrong module. Cosmetic at worst (the refusal's stated reason may not name the real cause); no correctness risk found. **Opentitan reproduction** (scratch copy, `hw/ip/{aes,uart,spi_host,hmac}`, 237 files, opentitan at the checkout named in the README, copied to `/private/tmp/.../scratchpad/ot_reattack` and pointed to via `LUCISV_EXTRACT_ROOT`, deleted after): `tools/guard.sh -- cargo test -p vlog_refactor --test corpus five_regions_of_real_rtl… -- --nocapture` prints **5 extracted, 5 refused**, both `aes_masking_reseed_if.sv` and `aes_reseed_if.sv` refused for being inside an `interface`, and every extraction holds the census at **10614 → 10614** — matches the README's table row for row. `git -C .../opentitan status --porcelain` unchanged before and after (the same three pre-existing files named in the task brief). The default corpus trial (`corpus/`, no env var) reproduces **5 extracted, 6 refused**, census 10268 → 10268, also matching. ### Gates (guarded) | Gate | Result | | --- | --- | | `cargo fmt -p vlog_refactor -- --check` | clean | | `cargo clippy --all-targets` | clean, no new `#[allow]` | | `cargo test -p vlog_refactor -p lucisv_server` | all green | | `cargo test --workspace` | **4081 passed, 0 failed, 44 ignored** — matches the dev's claim exactly (measured as 4090/44/0 with 9 temporary QA tests still in place, all of which also passed; 4090 − 9 = 4081) | | opentitan extraction trial (scratch, 237 files) | 5 extracted, 5 refused, census 10614 → 10614, opentitan checkout untouched | | corpus extraction trial (860 files) | 5 extracted, 6 refused, census 10268 → 10268 | All temporary tests removed before finishing (`check/mod.rs` back to 1025 lines; `tests/extract.rs` has no `qa_`-prefixed test remaining); both files remain the dev's own untracked additions, `git status --porcelain` confirms no other tracked file was touched by this pass. ### Verdict: **PASS** Both HIGH findings from the first QA pass are fixed and hold up under re-attack through the real production entry point: 1. **V1** (the pooled ledger) — confirmed fixed. All twelve attack pairs, including two-source/one-destination sums, crosswise misdirection, empty and duplicated `moving` entries, pre-existing destination content, and the `generated` whitelist's interaction with the cross-file `lands` rule, come out exactly as the equations promise. 2. **V2** (the `kw` gate) — confirmed fixed, including the opentitan regression it was written against; `macromodule` (the gate's other accept arm) checked too and found sound, just untested until now. One new, non-blocking finding (**QA-1, MEDIUM**): `positions_match`, and by the same reasoning Eq3, provide no protection against a same-file relocation of a never-dropped piece expressed as two well-formed edits, because in production `after` is always internally derived from the very edits being checked — this is pre-existing crate structure, not something the rework introduced, and no current planner produces this shape, but it means neither equation is currently *proven* by any attack that goes through a real entry point. Left to the dev/lead as a documentation note or a follow-up test, not a blocker. ## Review **2026-09-06 — lead.** 53.1 accepted after one rework; ships in 0.47.0 with §52. 53.2 is unstarted and runs as its own lane after §56, as the plan allowed — a finished half over two unfinished ones. The dataflow rule is the right reading (a routine argument refuses rather than guesses; a positional or `.*` connection refuses), the new-file path reads both halves of the client capability, and the naming flow goes through the language client's middleware rather than a second command registration. The two trial-found defects (a parameter named only by a port's type; a header `import` recorded as `p::*`) are exactly why the trials assert on the unresolved-name census and not on a parse. QA's two HIGHs were both real: a whole-file pool balanced an unrelated deletion against a duplicate write, and one AST node for `module`/`interface`/`program` let an interface body extract. The rework binds the pool to the moved bytes — four equations, twelve attack pairs through the production entry, the opentitan trial reproducible file by file with the census held — and QA's re-attack found only a MEDIUM that predates this lane (a same-file relocation of a never-dropped piece written as two well-formed edits is not caught, and equation 3 is unreachable through any real caller); no planner produces that shape, so it is filed as topo §2.9-32 for a later round rather than widened here. *(empty — for the lead)*