# refactor-instantiate M4 of the refactoring plan (`docs/features/refactor/README.md`): **module hinting**. ## Goal Give lucisv the thing rope gets from Python's type hints and no Verilog tool ships well: the workspace already knows every module's parameters and ports, so an instantiation should be *generated from the definition* rather than typed by hand. Typing a module name at item position offers the whole skeleton — parameter overrides carrying their declared defaults, every port as a named connection, the ports that already have a same-named signal in scope bound to it and the rest left as snippet tabstops — and once the connection list is open, signature help names the remaining ports with their directions and types. The facts live in `vlog_refactor` so Vim and a future CLI get the same answers; `lucisv_server` owns only the position gate, the snippet encoding and the LSP items. Nothing in this milestone edits a file. Everything it produces is *offered* text that the client inserts, which is why it is the one member of `vlog_refactor` with no verification pass: there is no existing code for it to corrupt. ## Assumptions - **The workspace index is the only thing that knows where a module lives.** `WorkspaceIndex` carries no port or parameter detail — only `Def { file, name_span, kind }` — so the defining file is parsed on demand. Measured before choosing that design: `parse_source_tolerant` over this repo's 820-file corpus is **158 µs per file on average, 4.6 ms worst case** (release build, 4.8 MB total). A completion capped at 64 items therefore costs ~10 ms of parsing in the ordinary case, which is why there is no `completionItem/resolve` dance and no cache: every item is returned complete. - **A skeleton the user accepts untouched must parse.** This is the editor-snippets assumption restated for generated text, and it is verified rather than assumed — see the corpus test under *Work log*. It is what forced parameter defaults through a parse-back probe. - **lucisv does not preprocess.** A port or parameter list split across `` `ifdef`` arms is read straight through, so the plan lists **every arm's** entries and says so in a warning. Policy chosen deliberately over refusing: a skeleton is a suggestion the user edits before it becomes code, unlike M3's port refactorings, which *rewrite existing code* and therefore refuse an insertion that would land inside an arm. Both behaviours are tested. - **A same-named signal is a connectable signal.** "Auto-connect" reuses M3's `visible_in` unchanged: the innermost `vlog_semantic` scope covering the site is walked outward, and a hit counts only when it is a `Net`/`Var`/`Port`/`Param`/`Genvar`/`TfArg`. No width or direction check is made — `.clk(clk)` is offered whenever a `clk` is in scope, exactly as `add_port` and `propagate_ports` already do it. - **`u_` is the instance name worth proposing.** It is a tabstop, so it costs one keystroke to reject. - **An `interface` is offered like a module.** `vlog_semantic` records both under `SymbolKind::Module` (`crates/vlog_semantic/src/model.rs`), and an interface really is instantiated the same way (`bus_if u_bus (.clk(clk));`), so nothing filters them out. A `program` is treated identically. If the semantic layer ever grows a separate kind for either, this becomes a choice rather than an inheritance. - **A `localparam` in a parameter port list is not overridable** and is not offered. A continuation entry (`#(parameter A = 1, B = 2)`) inherits the keyword of the entry before it, so the keyword is carried forward. - **The client's `snippetSupport` is read once, at `initialize`.** The protocol offers no way to learn it later, and a client that changes its mind mid-session is not a case worth modelling. - **The indent step comes from `lucisv.indent` (default 2), not from `lucisv.toml`.** `format::indent_width` discovers a config file from disk on every call; a completion request arrives on every keystroke, and walking the tree for a config file that often is not a trade worth making. Deviation from how the formatter resolves the same setting — recorded here so the lead can overrule it cheaply. ## Handshakes - **Consumes `vlog_semantic`**: `WorkspaceIndex::units`/`path` to find a module's defining file, `WorkspaceIndex::workspace_symbols` for the candidate list, and `Semantics` (through M3's `visible_in`) for the auto-connect question. Read-only; nothing new is asked of it. - **Consumes `vlog_parser`**: `parse_source_tolerant` for the defining file, `tokenize`'s output (via `Document.tokens`) for both position questions. `AnsiPort`/`NonAnsiPort`/`ParamPort`/`PortDecl` are read for names, directions and spans. - **Widened inside `vlog_refactor`**: `ports::find_module` and `ports::visible_in` went from private to `pub(crate)` so `instantiate.rs` reuses them instead of writing a second scope walk. No behaviour changed; both still have exactly one definition. - **Consumes `lucisv_server::pairs`** — `pairs::analyze` and the public `ScopeAnalysis`/`Pair`/`Unmatched` it already exposes — to decide whether the cursor is at module-item position. Nothing in `pairs.rs` was changed: the gate is built entirely from its published output, so editor-scopes keeps ownership of the matcher. - **Amended 2026-08-30 — where the plan is offered changed; the plan did not.** M4's completion item carried the whole instantiation. The owner's two-level ruling moved that to ghost text: the completion popup offers module *names* (level 1, a table scan), and `inline.rs` plans exactly one instantiation once the name before the cursor matches a module exactly and a space is typed after it (level 2; round 2 also replaced `module_definition`'s ambiguity refusal on that path with the server's `nearest_definition` chooser — `module_definition` itself is unchanged for its own callers). Every fact below still holds — the same `instantiation_plan`, the same `render_with`, the same auto-connect rule, the same `has_escaped_identifier` flag consulted before snippet encoding — but the *consumer* of the snippet spelling is now `inline.rs` rather than `completion::item`, which is gone. The escaped-name fallback differs on that path and only there: an inline completion has no plain-text spelling to fall back to, so such a plan is declined rather than inserted plainly (see *Escaped identifiers* and `docs/features/inline-instantiation/README.md`). Signature help and inlay hints, the other two consumers of `instantiation_plan`, are untouched. (Lead correction 2026-08-30: this entry originally said "`lucisv/instantiate`, the code action and the command are untouched" — no such action or command has ever existed; M4's user-facing surface was the popup skeleton alone.) - **Promises `lucisv_server`**: `instantiation_plan` never panics and never returns a plan whose plain rendering fails to parse — corpus-verified over all 454 modules, plus escaped-identifier cases the corpus does not contain (see the *Escaped identifiers* section). `render_with` is the single layout both the plain and the snippet spelling go through, so the two can never drift; a unit test pins that stripping a snippet's tabstops gives back the plain text byte for byte. `InstantiationPlan::has_escaped_identifier` is the flag the server must consult before choosing snippet encoding. - **`editors/vscode` needs no change.** `vscode-languageclient` advertises `completionItem.snippetSupport: true` on its own, and the extension sets no `initializationOptions` that would suppress it; `extension.js` was read to confirm. The static `contributes.snippets` templates of editor-snippets are unaffected — they are a manifest contribution the editor expands itself, and VS Code shows both lists side by side. - **Filed against `vlog_parser`, not fixed here (no action required for M4) — two gaps, both disclosed rather than worked around silently:** 1. The expression grammar rejects an inline aggregate as a parameter override argument, so `m #(.T(struct packed { logic a; })) u ();` does not parse ("unexpected keyword `struct` in expression"). Two corpus headers (`common_cells/src/ecc_encode.sv`, `ecc_decode.sv`) declare `parameter type` with such a default. M4 drops the default rather than writing back text lucisv cannot read. 2. An **interface-typed ANSI port** (`module m (iface_bus.mst bus, input logic clk);`) stops the whole header from parsing ("expected `)` (found \".\")"), so no `Module` item is produced and module hinting is silently unavailable for a pattern that is common in contemporary SV. M4 cannot work around this at all — there is no AST to read — but as of the 2026-08-24 rework the refusal *says* the file does not parse and names the diagnostic, instead of blaming an edit that never happened. Distinct from *instantiating* an interface, which works (see Assumptions). Both workarounds disappear by themselves if the grammar grows the cases. ## What it looks like `sub.sv` declares: ```systemverilog module sub #( parameter int WIDTH = 8 ) ( input logic clk, input logic [WIDTH-1:0] data, output logic ready ); ``` With `logic clk;` in scope, typing `su` inside `module top` offers one item whose insert is: ``` sub #( .WIDTH(${1:8}) ) ${2:u_sub} ( .clk(clk), .data(${3:data}), .ready(${4:ready}) ); ``` `clk` bound itself; `data` and `ready` are tabstops preloaded with the port's own name. A client that did not advertise snippet support gets the same text with every hole written as its default and no `${}` anywhere. Tabstops are numbered in the order the user tabs through them: each parameter override, then the instance name, then each port that did not auto-connect. Auto-connected ports get **no `// auto-connected` comment** — a deliberate deviation from the milestone brief, recorded in the *Work log*. A plan whose names are escaped identifiers is inserted as plain text whatever the client advertised — see *Escaped identifiers* below. Inside the connection list, `textDocument/signatureHelp` answers: ``` sub (input logic clk, input logic [WIDTH-1:0] data, output logic ready) ``` with the entry under the cursor highlighted — by name for a named list, by position for an ordered one — and the same for `#( ... )` against the parameters. ## Escaped identifiers SystemVerilog's escaped identifiers (`\my-port`, `\cost$`, `\a}b` — IEEE 1800 §5.6.1) are legal, absent from the corpus, and hostile to both of this feature's output grammars. Two separate problems, two separate answers. **Verilog's problem: an escaped identifier is terminated by whitespace and by nothing else.** So `.\my-port(sig),` lexes as *one* identifier that swallows the parens, the comma and the rest of the line, and the skeleton no longer parses. Fixed in the engine: `terminate` (`instantiate.rs`) writes the space after every splice whose text ends inside an escaped identifier, so the rendering is `.\my-port (\my-port ),`. The check is `ends_escaped` — does a `\` survive in the run of characters after the last whitespace — which is conservative by construction: a false positive costs one harmless space. The same spaces are written into `default_text`'s parse-back probe, so a default that legitimately ends in an escaped identifier is kept rather than dropped for want of a space the renderer was going to supply anyway. `instance_name` is escaped-aware too: an escaped module name yields `\u_name`, because `u_` glued in front of a `\name` is not an identifier at all. **LSP's problem: an escaped identifier may contain `$`, `}` and `\`** — exactly the snippet grammar's metacharacters. Per-hole escaping cannot help, because the *names* are written by the layout, outside every hole: there is no encoding of `.\W}idth (${1:8})` that a snippet parser reads back correctly. **Ruling (lead-approved): a plan containing any escaped identifier is inserted as plain text**, tabstops and all sacrificed, even when the client advertised `snippetSupport`. `InstantiationPlan::has_escaped_identifier` is the test. The user gets a correct skeleton with every default filled in and no tabstops to tab through — a small loss, confined to a naming style almost nobody uses, and the alternative is inserting text that does not parse. **Amended 2026-08-30.** `completion.rs::item` was the one place the flag was consulted; that item is gone with the two-level split, and the flag is now read by `inline.rs`'s instantiation ghost alone (lead correction: not also by a `lucisv/instantiate` rendering — no such command exists). The ruling above is unchanged **wherever a plain-text spelling exists**. Ghost text has none — an inline completion carries no `insertTextFormat` and no `snippetSupport` to negotiate, so "insert it plainly" is not an option there — and the ghost therefore *declines* such a plan outright. Same principle (never write text that does not parse), the only answer that path has. Regression-tested at both levels: the engine renders a parseable plain skeleton for a module whose module, parameter and port names are all escaped (two of them carrying `$` and `}`), and `inline.rs`'s `a_plan_with_an_escaped_identifier_gets_no_ghost` pins the server side. ## How precise the position gate is Honesty section, because the milestone asked for it. `completion.rs`'s `at_module_item` is a **heuristic over the token stream**, not a parse. Three conditions, all necessary: 1. the word being typed is the **first thing on its line** (only whitespace before it); 2. the innermost scope open at the cursor — from `pairs::analyze` — is `module`, `macromodule`, `interface`, `program`, `generate` or `begin`, and **no** enclosing scope is `function`, `task`, `class`, `covergroup`, `property`, `sequence`, `clocking`, `specify`, `primitive`, `fork`, or a `case` family; 3. when a `begin` is in the chain, the **outermost** one is not procedural — decided by reading backwards from that `begin` for `always*`/`initial`/ `final`/`@` before hitting a `;`, `end`, `begin`, `generate`, `endcase` or `join*`; plus every parenthesis opened since the innermost scope's keyword must be closed again, which is what keeps a port list and a connection list out. **What it gets right**, all tested: a module body, an `interface` body, inside `generate ... endgenerate`, inside a `for (genvar ...) begin : g` block; nothing offered inside `always_comb begin`, `always_ff @(...) begin`, `initial begin`, a `function` body, a `class` body, a module header's port list, a connection list, after `assign x = `, after `logic `, or at file scope outside any design unit. **What it gets wrong, deliberately:** - Two items written on one line (`wire a; sub u_sub (...);`) get no completion on the second, because of rule 1. An instantiation is written at the start of a line in every style guide there is, and the alternative — deciding what a bare identifier means mid-line — is a parse the buffer cannot supply while it is being typed. - A `begin` inside a `generate` inside a *procedural* construct cannot occur in legal Verilog, so rule 3 has no false negative there; but a `begin` reached from a construct rule 3 does not know (a `checker`, a UDP table) falls back to "not procedural" and may offer a completion where nothing can be instantiated. The cost is one unwanted list item, never a wrong edit. - Ports and parameters are not offered inside a connection list. That is the *next* completion feature and is not in M4's scope; signature help covers the same need for now. Signature help's list-finder has its own limit, also tested: it recognises a list when the token before its `(` reads as an instantiation (`#` after a name, or an instance name after a module name, optionally with the module's own `#( ... )` between them). A function call inside a connected expression (`.data(f(x))`) fails that test and is stepped past, which is right; a *variable* declaration that happens to look like an instantiation (`my_type_t my_var (` — legal, and genuinely ambiguous in the grammar) is treated as an instantiation, but answers nothing unless the index really does hold a module of that name. ## Status / TODO - [x] Engine module `crates/vlog_refactor/src/instantiate.rs`: `module_definition`, `instantiation_plan`, `module_names`, `InstantiationPlan`/`PlanParam`/`PlanPort`/`Layout`/`Site` - [x] Deterministic plain-text rendering (`render`) and the one seam the server's snippet goes through (`render_with`) - [x] Auto-connect via M3's `visible_in`, unchanged - [x] Refusals: unknown module, ambiguous duplicate definitions, a definition file that no longer declares the module - [x] `` `ifdef`` policy: list every arm, warn — documented and tested - [x] `textDocument/completion` + the capability, snippet/plain fallback by client capability, position gate - [x] `textDocument/signatureHelp` + the capability, `(` and `,` triggers, active parameter for named and ordered lists, ports and parameters - [x] Engine unit tests (29), server unit tests (completion 13, signature 14, capabilities/`snippetSupport` 4 new), one corpus property test, two e2e stdio round trips - [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`, `cargo test --workspace` - [x] `docs/features/lucisv-server/README.md` capability table updated - [x] QA rework (2026-08-24): escaped-identifier spacing + plain-text fallback, the `.*` wildcard in signature help, the parse-failure refusal message - [ ] Not done, backlog: declare-missing-signals companion action; completion of *port names* inside a connection list; a plan cache keyed on the defining file's text. ## Work log - **2026-08-24 (dev)** — read M1–M3 first: the umbrella plan, the ports and rename READMEs, `vlog_refactor`'s `Scope`, and `lucisv_server`'s dispatch, `state.rs` and `ports.rs`. **Design decision 1 — the engine takes an index and a file's text, not the file set.** M2/M3's entry points all take `&[(PathBuf, String)]` and build a `Scope`, which builds a whole `WorkspaceIndex` — every file parsed. That is right for a user-initiated refactoring and completely wrong for a keystroke. So `instantiate.rs` has two small entry points instead: `module_definition(index, name)` (a map lookup against the index the server already holds) and `instantiation_plan(name, definition_text, site)` (one parse of one file). Auto-connect reads the open buffer's own `Semantics`, which `Document` already carries. Net effect: a completion request does no workspace work at all beyond the lookup. **Design decision 2 — one renderer, two spellings.** The milestone puts the tabstop encoding in the server, which invites two copies of the layout. It is instead one function, `render_with(layout, hole)`, where `hole(n, default)` writes each fill-in; `render` passes the identity and the server passes `${n:default}`. Divergence is impossible by construction. **Deviation from the brief — no `// auto-connected` comments.** The milestone's example writes `.clk(clk), // auto-connected` into the inserted text. Not done: those comments are permanent (nothing later removes them), they would appear on the majority of connections in real RTL, and lucisv writing editorial comments into a user's design is a line the formatter has never crossed. The information is in the completion item's documentation panel instead ("connected, same name in scope"), where it is read once and costs the buffer nothing. One-line change in `completion.rs` if the lead disagrees. **Measured before deciding, not after.** The `completionItem/resolve` question (build 64 skeletons eagerly, or advertise `resolveProvider` and fill `insertText` later — which the spec does not actually permit for `textEdit`) was settled by measuring `parse_source_tolerant` over the corpus: 158 µs mean, 4.6 ms worst, 27 MB/s. Eager it is, capped at 64 items with `isIncomplete: true` when truncated so the client re-asks as the prefix narrows. The measurement harness was a throwaway test, run and deleted. **The corpus test found a real bug, which is why it exists.** Rendering a skeleton for all 454 modules the corpus declares and re-parsing each one caught two: `common_cells`' `ecc_encode`/`ecc_decode` declare `parameter type encoded_data_t = struct packed { ... }` across several lines, and the skeleton pasted the source's own indentation into a `#( ... )` on someone else's line *and* produced text lucisv's own parser rejects. Fixed by `default_text`: a default written across lines is dropped, and every surviving default is probed by writing it into a throwaway `m #(.P(...)) u ();` and requiring a clean parse. A default lucisv cannot write back is not offered — the tabstop comes up empty. The parser gap itself is filed in *Handshakes*, unfixed, because it belongs to another crate. **Port type text is display-only and collapsed to one line** (`PlanPort::ty`), so a port typed with a multi-line anonymous `struct` still reads as one line in a signature. Nothing writes it into a buffer, which is what makes collapsing safe there and unsafe for parameter defaults. **Files touched.** New: `crates/vlog_refactor/src/instantiate.rs`, `crates/lucisv_server/src/completion.rs`, `crates/lucisv_server/src/signature.rs`, this README. Edited: `crates/vlog_refactor/src/lib.rs` (module + re-exports + a paragraph on the one member that edits nothing), `crates/vlog_refactor/src/ports.rs` (`find_module` and `visible_in` to `pub(crate)`, no behaviour change), `crates/lucisv_server/src/main.rs` (two capabilities, `snippet_support`, `Server::new` gained the flag), `crates/lucisv_server/src/server.rs` (two dispatch arms, the flag on `Server`), `crates/vlog_refactor/tests/corpus.rs` and `crates/lucisv_server/tests/e2e.rs` (new tests only), `docs/features/lucisv-server/README.md` (capability table). **Not touched, deliberately:** `TODO.md`, the umbrella checklist, `pairs.rs`, `hover.rs` (module hover already works through nav), and every M3 code path. - **2026-08-24 (dev, QA rework)** — three lead rulings on QA's findings, all three implemented. Gates re-run: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` zero warnings, `cargo test --workspace` green at **1232 passed, 0 failed** (1222 before this round) — ten new tests (seven in `instantiate.rs`, one in `completion.rs`, two in `signature.rs`), plus one existing test renamed and re-asserted in place because it was pinning the message ruling 3 replaced. No commits. **Ruling 1 — escaped identifiers (QA MEDIUM #1).** Fixed at both levels and written up in full under *Escaped identifiers* above. Engine: `terminate` + `ends_escaped` put the required space after every splice point that ends inside an escaped identifier — audited all five in `render_with` and found two that needed it (`.{name}(` and the value inside the parens) and three that already had a space following them (the module name, whose two continuations both start with one, and the instance name). `instance_name` now yields `\u_name` for an escaped module. `default_text`'s probe gained the same spaces so a legal escaped default is no longer dropped. Server: took the lead's pre-approved out for the snippet half. Confirmed first that it really is unfixable rather than merely awkward — the failing render is `.\W}idth (${1:8})` … `${3:\\a}b} )`, where the port name's own `}` closes a placeholder the layout never opened and the instance default's `$1` reads as a nested tabstop; both are *outside* every hole, so `snippet_hole`'s escaping cannot reach them by construction. So: `has_escaped_identifier` on the plan, consulted once in `completion.rs::item`, and such a plan is inserted as plain text however the client is configured. The promise in *Handshakes* is true again, and now says what it is verified against. Added on top of what was asked: a test that stripping a snippet's tabstops gives back the plain rendering byte for byte, which is the "one seam, two spellings" claim turned into an assertion rather than an argument. **Ruling 2 — the dead `.*` branch (QA MEDIUM #2).** QA's diagnosis was exactly right: `*` lexes as a `Symbol`, and the `Symbol` arm `continue`d past the `is_sym("*")` test that could therefore never fire, so `.*` fell through to the ordered-connection count and highlighted port 0. The wildcard is now recognised inside the `Symbol` arm, *before* the depth bookkeeping, and sets `any_name` with no name — so `.*` highlights nothing, does not advance the ordered index, and a later `.ready(` after a `.*` still resolves by name. Dead condition deleted. Two regression tests from QA's repro (cursor at the `.*`, and a comma after it), plus the named-after-wildcard case. **Ruling 3 — the refusal message (QA LOW).** `instantiation_plan` now keeps the parse diagnostics and splits the message: a file with diagnostics gets "its file does not parse (`` at line N)", a clean parse that simply has no such module keeps "no longer declares it". Two tests — the garbage input the old test used (assertion updated, since it was pinning the wrong message) and QA's interface-typed-port case. The `vlog_parser` interface-port gap is now disclosed in *Handshakes* alongside the `parameter type` one, as QA suggested. **Files touched this round:** `crates/vlog_refactor/src/instantiate.rs`, `crates/lucisv_server/src/completion.rs`, `crates/lucisv_server/src/signature.rs`, this README. Nothing else; no behaviour outside M4 was reached. ## QA log **2026-08-24 — QA agent.** ### Gates - `cargo fmt --all -- --check` — clean. - `cargo clippy --all-targets` — clean, zero warnings, workspace-wide. - `cargo test --workspace` — green, **1222** tests (matches the Work log's number exactly; summed the per-crate `test result` lines myself rather than trusting the printed total). `cargo test --release -p vlog_refactor --test corpus every_module_in_the_corpus_yields_a_skeleton_that_parses -- --nocapture` re-run in isolation: `corpus skeletons: 454 planned, 81 refused, in 0.24s` — the 454 figure matches the README exactly. All three gates: **pass, claims confirmed.** ### Design review (`instantiate.rs`, `completion.rs`, `signature.rs`) Read against the spec and CLAUDE.md. `render`/`render_with` being the one seam both spellings go through is exactly the right shape — verified by reading, not just trusting the README, that `render` really does call `render_with` with the identity hole (`instantiate.rs:194-196`) and that `completion.rs::item` is the only other caller (`completion.rs:119-122`). `module_definition`/`find_module`/`visible_in` reuse from `ports.rs` is a clean `pub(crate)` widening with no behavior change, confirmed against `git diff` — a two-line diff, exactly as claimed. No `unwrap`/`expect`/ `panic!`/`unsafe` found in any non-test path of the three new files. ### Attacks — skeleton correctness (`instantiate.rs`) Probed via 12 temporary tests added to `instantiate.rs`'s and `completion.rs`'s own test modules (`cargo test qa_probe -- --nocapture`), run and then fully reverted — nothing left in the tree (confirmed with `grep -rn qa_probe` after cleanup, zero hits, and a final clean `cargo fmt` + `clippy` + `test --workspace` re-run). **Passed:** - Zero ports (`module bare;`) and zero params both render correctly: no dangling `#()` ever (guarded by `if !self.params.is_empty()`, `instantiate.rs:216`), and an empty port list renders `);` directly (`instantiate.rs:231-234`) — matches the existing `a_module_with_no_ports_and_no_parameters_still_plans` test. - ANSI port with an unpacked dimension (`input logic a [3:0]`) — the dimension is (correctly) display-only and never appears in the connection: skeleton renders `.a(a)`, which parses clean. Not a finding — a connection never needs to repeat the declared width. - `parameter type T = logic [7:0]`, a default referencing another parameter (`parameter D = W*2`), a default containing nested parens (`parameter AW = $clog2(W)`), and a default containing a `)` inside a string literal (`parameter string S = ")"`) — all four are kept (not dropped) and round-trip through `default_text`'s parse-back probe correctly, exactly as `instantiate.rs:294-306`'s doc comment describes: syntax-only checking, no width/reference resolution attempted or needed. - Auto-connect to a `genvar` and to a `parameter` (not just a net) — both bind, matching the Assumptions section's documented widened definition of "visible" (`Net`/`Var`/`Port`/`Param`/`Genvar`/`TfArg`) inherited unchanged from M3's `visible_in`. Not a finding; working as documented. - Auto-connect to a signal declared **after** the instantiation site (`// here` before `logic clk;` in the same module) — binds. This is correct Verilog scoping (module-scope declarations are visible throughout the module regardless of textual order) and is `visible_in`'s existing, already-QA'd-at-M3 behavior, reused unchanged; not a new finding. - A signal declared in an enclosing `generate`/`endgenerate` block before the site — binds, as expected. **MEDIUM — an escaped-identifier port name produces a skeleton `lucisv`'s own parser rejects, falsifying the feature's own stated invariant** `docs/features/refactor-instantiate/README.md`'s Handshakes section promises: *"`instantiation_plan` never panics and never returns a plan whose plain rendering fails to parse (corpus-verified)."* That promise is false for a module declaring an escaped identifier port — legal SystemVerilog, just absent from the corpus, which is why the corpus property test (`crates/vlog_refactor/tests/corpus.rs`) didn't catch it. ```systemverilog module m (input logic \my-port , input logic clk); endmodule ``` `instantiation_plan("m", ..., None).render(&Layout::default())` produces: ``` m u_m ( .\my-port(\my-port), .clk(clk) ); ``` which fails to re-parse: `expected \`)\` (found ".")`, at the `.` of `.clk` on the next line. Root cause: a SystemVerilog escaped identifier runs until the next whitespace character, and `render_with` (`crates/vlog_refactor/src/instantiate.rs:207-250`) writes `.{name}({expr})` with no whitespace anywhere around an escaped `name` — so `.\my-port(\my-port),` lexes as **one single token** (the backslash, every character up to the newline including `(`, `)`, and `,`), and the following line's leading `.` is what the parser chokes on. This is not specific to snippet encoding — `completion.rs`'s `snippet_hole` correctly escapes the backslash in the *default text* (`\` → `\\`, confirmed by the existing `a_tabstop_default_is_escaped...` test), but that's irrelevant here: the corruption is in the shared plain-text layout both spellings go through, so plain and snippet skeletons are equally broken. Confirmed via a temporary test in `instantiate.rs`'s test module (run, then reverted): `parse_source_tolerant` on the rendered skeleton reports exactly `expected \`)\` (found ".")`. Not a hard-invariant-1 violation (no existing file is touched or corrupted — this is offered text the user must accept via Tab, and the failure is loud, not silent: red squiggles the moment it lands). But it does concretely falsify a promise the feature's own README makes, for a legal port-naming style the corpus simply doesn't exercise. Not fixed — this needs a design call (write a trailing space after any hole whose following text is an escaped identifier, or after *every* hole unconditionally, or detect and special-case `\`-prefixed names) rather than a one-line patch; flagging for dev/lead. **LOW/informational, not filed as a MEDIUM finding — interface-typed ports are invisible to module hinting, with a slightly misleading refusal** ```systemverilog module m (iface_bus.mst bus, input logic clk); endmodule ``` `vlog_parser` itself cannot parse this port list (`expected \`)\` (found ".")`, confirmed directly against `parse_source_tolerant`), so no `Module` item is produced for `m` at all, and `instantiation_plan("m", ...)` refuses with *"the file that declared \`m\` no longer declares it, so lucisv cannot write an instantiation of it."* — a message that reads as "someone edited the file out from under the index" when the real cause is "the parser never supported this syntax." This is the identical class of gap the dev already found and disclosed in Handshakes for `parameter type ... = struct packed { ... }` (filed against `vlog_parser`, not fixed here) — just a different trigger (an interface-typed ANSI port, distinct from *instantiating* an interface, which the Assumptions section does correctly cover and which works). Interface ports are common in contemporary SV, so this quietly disables completion for a real, non-exotic pattern; worth the same Handshake-style disclosure the `parameter type` case already got, and worth a refusal message that distinguishes "does not parse" from "no longer declares it" if the dev revisits this area. Not filing as a blocking finding: it's a pre-existing `vlog_parser` limitation, not something `instantiate.rs` introduced, and the refusal is honest in substance (no skeleton is offered) even if imprecise in wording. ### Attacks — signature help (`signature.rs`) **MEDIUM — dead code means `.*` inside a connection list is never recognized, so it falls through into a wrong active-parameter count** `active_entry` (`crates/lucisv_server/src/signature.rs:219-257`) has this branch, evidently meant to treat `.*` as a name (so that, like an unknown `.name`, it highlights nothing rather than being mistaken for an ordered connection): ```rust if dot && depth == 0 && (is_name(token) || token.is_sym("*")) { ``` But this line is **unreachable for `*`**. `*` always lexes as `TokenKind::Symbol` (`crates/vlog_parser/src/token.rs`, `is_sym` requires `kind == TokenKind::Symbol`), and the loop's `if token.kind == TokenKind::Symbol { ... continue; }` branch (lines 229-244) unconditionally handles and `continue`s past every symbol token — including `*` — before this line is ever reached; `*` falls into that block's `_ => {}` arm, then hits the shared `dot = false; continue;`, silently discarding the pending `dot` flag from the preceding `.` without ever checking `is_sym("*")`. Consequence, reproduced with a temporary test (run, then reverted): `sub u_sub (.*` with the cursor right after `.*` returns `active_parameter = Some(0)` — the first port (`clk`) is highlighted, as if `.*` were an ordinary empty ordered connection at position 0, which is not what a wildcard connection is. (When a real named connection follows the `.*` before the cursor, e.g. `.*, .data(`, the later `.data` correctly overwrites `named`/`any_name`, so the bug is only visible with the cursor at or immediately after the `.*` itself — which is exactly when a user would be looking at signature help to decide what to type next.) Read-only and cosmetic — nothing is written to a buffer, this only mis-highlights a tooltip parameter — so I'm rating it MEDIUM rather than HIGH, but it's a genuine, reproducible bug with dead code sitting right next to the fix, not a design question. Not fixed here: the right repair (delete the two-line dead branch and instead special-case `*` inside the existing Symbol match, e.g. treat `.` immediately followed by `*` as "named, with no matching entry") is a small, mechanical change but touches control flow I'd rather the dev sign off on given how easy it is to get the depth bookkeeping subtly wrong a second time. ### Attacks — completion gating (`completion.rs`) All via temporary probes, reverted: - Cursor inside a `//` line comment, inside a `/* ... */` block comment, and inside a string literal (`$display("su`) — all three correctly offer **zero** items. `typed_word`/`at_module_item` operate over the token stream, and a comment or string is not an identifier token, so there's nothing for `typed_word` to find a word in; not a finding. - Case sensitivity: typing `SU` against a declared `sub` still offers the item (module_names' documented case-insensitive substring match, same contract the existing `a_module_with_no_ports...`/`the_candidate_list...` tests already pin at the engine level). Confirmed the behavior survives the full completion pipeline, not just `module_names` in isolation. Not a finding — matches the documented contract exactly. - 64-item cap + `isIncomplete`: built a 70-module workspace, asked for the `mod_` prefix (matches all 70) — got back exactly 64 items with `is_incomplete: true`, matching `LIMIT` and the README's claim exactly. - `sub #(8) u (a, b` (param list already closed, cursor in the port list) — traced `signature.rs::list_at` by hand against the actual token sequence: the innermost unclosed `(` is the *ports* one, and `list_at` correctly walks back through the closed `#(...)` via `matching_open` to confirm the module name, returning `Kind::Ports`. The existing `a_connection_list_after_a_parameter_override_is_still_found` test covers this exact shape without the literal `#(8)` numeral; traced by hand to be certain the numeral (vs. a named override) doesn't change the token-position arithmetic — it doesn't. - `.data(` with the cursor inside a **nested, unclosed** call (`.data(f(x,` with the cursor right after the inner comma) — traced by hand through `active_entry`'s depth counter: entering `f(` takes depth to 1 (or 2, depending on how deep), so the inner `,` hits the `_ => {}` arm (only depth-0 commas increment `commas`) and is correctly ignored; `named` stays pinned to `data` from before the nested call opened. Does not advance the port index, as required. The existing `a_call_inside_a_connected_expression_is_not_mistaken_for_a_list` test covers the *closed*-call case; I additionally hand-traced the *unclosed* (mid-typing) case since that's the state a real keystroke produces and it isn't quite what that test exercises — same result, no discrepancy. ### Real server binary over stdio Ran the dev's own `completion_and_signature_help_round_trip_over_the_wire` and `a_client_without_snippet_support_gets_the_skeleton_as_plain_text` (`crates/lucisv_server/tests/e2e.rs`) as part of the full-suite gate run — both pass, part of the workspace's 1222. They already exercise exactly what the brief asked for: one real `initialize` → `completion` round trip over stdio asserting the JSON-decoded snippet text is byte-for-byte the expected `${n:...}` syntax, one `signatureHelp` round trip with UTF-16 label-offset arithmetic checked against the decoded label string, and the advertised `completionProvider`/`signatureHelpProvider` capability shapes. Re-ran both in isolation (`cargo test -p lucisv_server --test e2e completion_and_signature_help_round_trip -- --nocapture` and the plain-text one) to confirm independently rather than trust the aggregate count — both pass standalone. ### The seven work-log decisions/deviations No disagreements to file. Specifically: 1. Two narrow entry points (`module_definition`, `instantiation_plan`) instead of M2/M3's whole-`Scope` construction — right call for a per-keystroke request; verified the completion path really does only one file-text lookup plus one parse per candidate (`completion.rs:96-100`), no workspace rebuild. 2. `render`/`render_with` as one seam — verified by reading, see Design review above; divergence between the two spellings is impossible by construction, confirmed. 3. No `// auto-connected` comments — reasonable; the stated reasons (permanent, majority-case noise, a line lucisv hasn't crossed elsewhere) are sound, and the alternative (documentation panel) genuinely carries the same information. Agree. 4. Measuring `parse_source_tolerant` before choosing eager-vs-`resolve` — sound methodology; the LIMIT=64 + `isIncomplete` result is verified above. 5. `default_text`'s parse-back probe, added because the corpus test found the `parameter type ... struct packed` case — verified it also correctly *keeps* everything it should (cross-param references, `$clog2(...)` nesting, string literals containing `)`), not just that it drops what it must. 6. Port type text collapsed to one line, display-only — confirmed nothing writes `PlanPort::ty` into a buffer (only `label()`, used by `documentation()` and `signature.rs`'s labels); safe as described. 7. `` `ifdef `` policy — list every arm + warn, the deliberate opposite of M3's refuse-and-name-the-arm — agree with the stated reasoning (nothing is written to an existing file until the user accepts the Tab-completed text, unlike M3's port refactorings which rewrite code that already exists), and confirmed both the port-list and parameter-list warning paths fire via the existing `a_conditional_port_list_lists_every_arm_and_says_so` / `a_conditional_parameter_list_warns_too` tests. ### Verdict **Ship-after-fixes.** Both MEDIUM findings are real, reproducible, and narrow — neither touches an existing file (hard invariant 1 is not at risk; this milestone edits nothing) and neither is a design-level rethink, but both are concrete bugs a lead should see fixed before this ships: the escaped-identifier skeleton corruption (falsifies the feature's own stated "always parses" promise) and the `.*` dead-code mis-highlight in signature help. The LOW/informational interface-port gap is the same shape as an already-disclosed, already-accepted `vlog_parser` limitation and does not block shipping on its own. ### Files touched during QA (all reverted; nothing left in the tree) `crates/vlog_refactor/src/instantiate.rs`, `crates/lucisv_server/src/completion.rs`, `crates/lucisv_server/src/signature.rs` — 12 temporary `qa_probe_*`/probe tests added, run with `--nocapture`, then removed. Verified clean with `grep -rn qa_probe` (zero hits) and a final `cargo fmt --all -- --check` + `cargo clippy --all-targets` + `cargo test --workspace` (1222 passed) re-run after cleanup. --- ## Round 2 — 2026-08-24 (QA agent) Dev reworked per lead rulings on both round-1 MEDIUM findings plus the LOW refusal-message note. Re-verified at mechanism level (hand-traced the new control flow, then confirmed every trace with a temporary probe — 11 probes across the three files this round, run then fully reverted). ### Gates - `cargo fmt --all -- --check` — clean. - `cargo clippy --all-targets` — clean, zero warnings, workspace-wide. - `cargo test --workspace` — green, **1232** tests, 0 failures (summed the per-crate `test result` lines myself; matches the claim exactly, +10 over round 1's 1222 — the dev's "8 new tests" plus this round's own count came out at +10, not +8; not chasing the discrepancy further since the gate itself is what matters and it's green either way). - `cargo test --release -p vlog_refactor --test corpus every_module_in_the_corpus_yields_a_skeleton_that_parses -- --nocapture` re-run standalone: `corpus skeletons: 454 planned, 81 refused, in 0.24s`, 0 unparseable (the assertion would have failed otherwise) — matches the claim exactly. All three gates: **pass, claims confirmed.** ### MEDIUM #1 (escaped identifiers) — mechanism review Read `terminate`/`ends_escaped` (`crates/vlog_refactor/src/instantiate.rs:297-320`) and audited all five splice points in `render_with` by hand against the dev's claim of "all five": 1. `.{param.name}(` — `terminate`d (line 257). 2. `{hole(n,¶m.default)})` — `terminate`d (line 259). 3. instance name before ` (` — **not** run through `terminate`; instead the literal `" ("` that always follows it supplies the space unconditionally (comment at line 268 says so explicitly). Confirmed this is sufficient: an escaped instance name can never need `terminate`'s help because nothing ever writes non-whitespace directly after it. 4. `.{port.name}(` — `terminate`d (line 285). 5. `{expr})` (the port's connection, whether auto-connected or a hole) — `terminate`d (line 287). All five accounted for, matches the claim. `instance_name()` builds `\u_bare` from `\bare` (`format!("\\u_{bare}")`, line 205) rather than gluing `u_` onto the escaped name — confirmed correct by trace and by probe (below): `u_` glued directly onto `\weird-mod` would produce `u_\weird-mod`, which is not a legal identifier at all (an escaped identifier's `\` must be the very first character); `\u_weird-mod` is. **Probed (temporary, reverted):** - An escaped **default** (`parameter Q = \esc-2`) as the **last** parameter in the list, immediately before the closing `)` of `#( ... )` — a splice point the dev's own new test doesn't isolate (their test uses a single-parameter module). Skeleton: `.Q(\esc-2 )` — parses. - A port name terminated by a **TAB** in the source rather than a space (`\my-port,`). The lexer's stored `name` field doesn't carry the terminator character at all (confirmed: `p.ports[0].name == "\\my-port"` regardless of whether the source used a space or a tab), so `terminate`'s hardcoded ASCII space is correct regardless of what the source used — this was never actually a live risk, but worth confirming rather than assuming. - An escaped **module** name with otherwise ordinary (non-escaped) ports — isolates the module-name-only case from the dev's own `escaped_names_everywhere...` test, which escapes module *and* param *and* port together and so can't tell which one is doing the work. `has_escaped_identifier()` correctly returns `true` from the module-name check alone; `instance_name()` correctly returns `\u_weird-mod`; the skeleton `\weird-mod \u_weird-mod (\n .a(a)\n);` parses. - `crates/lucisv_server/src/completion.rs:126`'s gate (`snippets && !plan.has_escaped_identifier()`) — confirmed it forces plain text for the module-name-only case too, not just the port/param-escaped cases the dev's test already covers. **New, LOW finding — the "one seam" byte-for-byte promise does not hold for a default containing `$` or `}` (metacharacters `snippet_hole` itself must escape), though nothing corrupts** The round-2 attack list specifically asked about metachar escaping at the tail of a default in a *non-escaped* plan, which turned up a real mechanism gap, distinct from MEDIUM #1: `terminate` (`instantiate.rs:304`) is called with `hole(n, &default)` — the **already snippet-encoded** string — not the raw default. When `default_text` yields something like `$clog2(8)` (no backslash, so `has_escaped_identifier()` is correctly `false` and the plan stays snippet-encodable), `snippet_hole` (`completion.rs:156-168`) escapes the `$` to `\$`, producing `${1:\$clog2(8)}`. That string now *contains* a backslash — introduced by snippet-escaping, nothing to do with SystemVerilog escaped identifiers — and `ends_escaped` can't tell the difference, so `terminate` adds its "harmless extra space": `.AW(${1:\$clog2(8)} )`. Confirmed end-to-end through the real `completion::item` pipeline with a temporary probe. Consequence, also confirmed with a probe that reimplements `snippet_hole` locally and calls `render_with` directly: `expand(snippet) != plain` for this case — `${1:\$clog2(8)} )` strips to `$clog2(8) )` (extra space) while `plain` renders `$clog2(8))` (no space). The dev's own new regression test, `a_snippet_expands_to_exactly_the_plain_rendering`, only exercises `SUB`, `bare`, and `p #(parameter W = 1)` — none of which has a `$`/`}` in any default — so it cannot see this divergence, and the Handshakes-style claim "byte-for-byte" is true only for defaults that don't need `snippet_hole`'s own escaping, not universally as stated. Not a corruption and not re-filing MEDIUM #1: both spellings still parse (an extra space inside parens is legal Verilog), and the code's own comment on `ends_escaped` already anticipates and accepts exactly this shape of false positive ("a false positive writes one harmless extra space") — this probe is the empirical confirmation that the anticipated harm really is limited to one space, not something worse. Filing as LOW: worth either tightening the "byte-for-byte" claim's wording (it's "byte-for-byte modulo one possible harmless space when the default needs snippet-escaping", not unconditionally byte-for-byte) or, if the dev wants it exact, having `terminate` receive the *raw* default alongside the already-encoded one so `ends_escaped` can check the source text instead of the wire text. Not blocking. **Minor observation, not filed as a finding** — a refusal message can cite a real but unrelated parse diagnostic. Probed: a file where the requested module is never declared at all (plain typo) but a *different*, unrelated module later in the same file has a genuine syntax error. The message reads "...its file does not parse (expected expression (found \";\") at line 3)..." — technically true (the file does have that error) but not the actual reason the requested module wasn't found. This is `diagnostics .first()`'s known limitation (`instantiate.rs:156`, picks the first diagnostic in the file, not one scoped to the request). Judged not worth filing: it's strictly more informative than round 1's blanket "no longer declares it" for every such case, still names a real, actionable problem in the file, and this exact scenario (index believes a module exists, direct `instantiation_plan` call with a name the index never vouched for) doesn't occur on the server's real completion path, where `module _definition` already filters to names the index found. ### MEDIUM #2 (`.*` dead code) — mechanism review Read the fix (`crates/lucisv_server/src/signature.rs:225-271`). The wildcard check now lives inside the `if token.kind == TokenKind::Symbol` arm, *before* the `match` that does depth bookkeeping: ```rust if dot && depth == 0 && token.text == "*" { named = None; any_name = true; dot = false; continue; } ``` This is reachable — `*` really does lex as `TokenKind::Symbol` (`crates/vlog_parser/src/token.rs`), so this branch is the first thing that sees it, unlike round 1's dead `is_name(token) || token.is_sym("*")` check which sat in the *non*-Symbol branch and could never see a Symbol token at all. Traced by hand: `named = None` (not `Some("*")`) means the function's final `let name = named?;` short-circuits to `None` the moment `any_name` is true from a wildcard — correct, "highlights nothing" rather than trying and failing a name lookup. The `depth == 0` guard confirmed by trace to correctly exclude a `*` inside a nested expression (e.g. `.data(a*b)`, multiplication) — depth is 1 there, so the wildcard branch never fires and `*` falls through to the ordinary `_ => {}` arm, which is what it should do. **Probed (temporary, reverted), covering the round-2 attack list exactly:** - `u_sub (.*` (wildcard, cursor immediately after, first position, nothing else typed) — `active_parameter: None`. Same as the dev's own test but independently re-derived. - `u_sub (.*, )` — cursor right before the closing paren, after the wildcard's trailing comma — `None`. (The dev's own test stops at the comma; this pushes one token further, to the position the round-2 brief named specifically.) - `u_sub (.*, a, b, ` — illegal-but-typeable mix of a wildcard with bare positional entries. **No panic.** `active_parameter: None` — `any_name` stays sticky `true` from the wildcard, so the later positional commas never get a chance to answer via the ordered-count branch; a reasonable, safe answer for input that shouldn't compile anyway. - `u_sub (a, .*, b, ` — positional, then wildcard, then more positional. **No panic.** `None`, same reasoning. - `u_sub (` with **no** wildcard at all, cursor right at the open paren — `active_parameter: Some(0)`, unchanged from round 1. Confirms the new Symbol-arm check (which runs on *every* Symbol token, not just `*`) adds no overhead or side effect to the ordinary, wildcard-free path — the `token.text == "*"` comparison simply never matches and execution falls through to the original `match` unchanged. No lost behavior found from deleting the dead branch: the only thing it ever did (for real) was the `is_name(token)` check on a non-Symbol token, which is identical to — and still performed by — the unchanged code below the Symbol arm (`if dot && depth == 0 && is_name(token) { ... }`, line 260). Nothing besides the never-reachable `|| token.is_sym("*")` disjunct was removed. ### LOW (refusal-message split) — mechanism review `instantiate.rs:150-165`: `diagnostics.first()` decides between the two messages. Confirmed via the existing three tests (`a_definition_that_no_longer_declares_the_module_is_refused`, `a_definition_that_does_not_parse_says_so_rather_than_blaming_an_edit`, `an_interface_typed_port_list_is_refused_as_a_parse_failure`) plus my own unrelated-diagnostic probe above. The interface-port case in particular now says "does not parse (expected \`)\` (found \".\") at line 1)" instead of blaming an edit that never happened — does what round 1 asked for. ### Verdict **Ship.** Both round-1 MEDIUM findings are fixed and hold up under mechanism-level review plus 11 targeted probes (including every case the round-2 attack list named — first-position wildcard, wildcard-then-comma, illegal wildcard/ordered mixes with an explicit no-panic check, an escaped-module-name-only plan, an escaped default at the last splice point before a list closes, and a whitespace-variant terminator). The LOW refusal-message fix does what was asked. One new LOW-severity, non-blocking observation surfaced by this round's own attack list (the "byte-for-byte" snippet/plain equivalence claim has an unstated exception for defaults needing `$`/`}` snippet-escaping, resulting in one harmless extra space in the snippet spelling only) — worth a follow-up note or a wording fix in the Handshakes claim, not a rework. ### Files touched during round-2 QA (all reverted; nothing left in the tree) Same three files as round 1 — 11 temporary probe tests added (`qa2_probe_*` in `instantiate.rs`, `completion.rs`, `signature.rs`), run with `--nocapture`, then removed. Verified clean with `grep -rn qa2_probe` (zero hits) and a final `cargo fmt --all -- --check` + `cargo clippy --all-targets` + `cargo test --workspace` (1232 passed) re-run after cleanup. ## Review **2026-08-24 — lead.** Reviewed after QA round 2's ship verdict; gates run independently (1232 tests, 0 failures, clippy silent). The single-renderer / two-spellings design held up under QA's stripping test, and the corpus property test (454 modules' skeletons re-parse) earned its keep by catching the multi-line-default bug during development. All seven dev deviations are accepted as argued — in particular no editorial comments in inserted text, the plain-text fallback for escaped-identifier plans (snippet metachars outside the holes are genuinely unreachable by hole escaping), and the ifdef list-and-warn policy, which is correctly the opposite of M3's refusal because a skeleton is edited before it compiles. QA's round-2 LOW (one extra space in the snippet spelling when a default carries `$`/`}` — both spellings still parse) is accepted as a cosmetic known limitation; fix it if `terminate` is ever touched again. Accepted; M4 checked off in the umbrella plan and TODO.md §8.