From 4671b9170457a0359eab5062ae26cc57e82e496e Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 23 Sep 2026 20:44:06 -0700 Subject: [PATCH] MCP feedback-1: unresolved mentions on references and the edit tools, a smaller catalogue, hierarchy/references routing, add_port `after`, temp sweep; census round 1 written up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Census round 1 (mcp_analysis.md, Sonnet arms on the opentitan clone): the mcp arm used more tokens than plain file tools on all three tasks (+18/+25/+20 %) and was incomplete on the rename — the `rename` tool renamed what the engine sees and warned about the macro argument, but nothing listed the old name still spelled as text (a DV force path built as the string ".state_q"), which the base arm's broad search found. Fixes (crates/lucisv_mcp/src/tools/{mentions,place,place/slot,place/verify}.rs + descriptions): `references`, `rename`, `remove_port` and `add_port` end with every whole-word spelling of the name in strings, comments, macro text, define bodies and macro-rooted paths that no engine answer accounted for, ranked edited-files-first, capped at 50, computed on the texts as written; `hierarchy` leads with "who instantiates a module", `references` routes a module name there, `instructions` say so; `tools/list` 30.2 kB → 18.0 kB with every argument still documented; `add_port` takes `after` — the engine appends, the placer moves the header element and each instance's connection to after the anchor in the neighbours' layout, refuses any list holding an unreadable element (an `(* attr *)` port the parser keeps as text would otherwise make the next port inherit the new type — QA's blocking find), and a checker compares every port's declaration text and pairs each comment with its anchoring name against the engine's result; stale `index-cache-mcp.*.tmp` files older than 10 min swept before a write. QA (Opus, two rounds): 23 qa_f1 tests. Gates through tools/guard.sh: fmt, clippy, workspace 4 918 passed. Co-Authored-By: Claude Fable 5.1 --- TODO-MCP.md | 25 + crates/lucisv_mcp/src/cache.rs | 30 + crates/lucisv_mcp/src/rpc.rs | 2 +- crates/lucisv_mcp/src/tools/defines.rs | 10 +- crates/lucisv_mcp/src/tools/diagnostics.rs | 12 +- crates/lucisv_mcp/src/tools/edit.rs | 143 ++-- crates/lucisv_mcp/src/tools/format.rs | 23 +- crates/lucisv_mcp/src/tools/hierarchy.rs | 12 +- crates/lucisv_mcp/src/tools/interface.rs | 6 +- crates/lucisv_mcp/src/tools/item.rs | 37 +- crates/lucisv_mcp/src/tools/mentions.rs | 352 ++++++++ crates/lucisv_mcp/src/tools/mod.rs | 5 +- crates/lucisv_mcp/src/tools/nav.rs | 77 +- crates/lucisv_mcp/src/tools/place.rs | 448 ++++++++++ crates/lucisv_mcp/src/tools/place/slot.rs | 306 +++++++ crates/lucisv_mcp/src/tools/place/verify.rs | 310 +++++++ crates/lucisv_mcp/src/tools/read.rs | 27 +- crates/lucisv_mcp/src/tools/read_item.rs | 6 +- crates/lucisv_mcp/src/tools/refactor.rs | 69 +- .../tests/fixtures/feedback/dv/probe_if.sv | 7 + .../tests/fixtures/feedback/rtl/cipher.sv | 12 + .../tests/fixtures/feedback/rtl/core.sv | 11 + .../tests/fixtures/feedback/rtl/other_sm.sv | 8 + .../tests/fixtures/feedback/rtl/sm.sv | 11 + .../tests/fixtures/feedback/rtl/wrap.sv | 17 + crates/lucisv_mcp/tests/qa_f1.rs | 786 ++++++++++++++++++ crates/lucisv_mcp/tests/qa_m6.rs | 1 - crates/lucisv_mcp/tests/wire.rs | 209 +++++ docs/features/mcp-cache-and-census/README.md | 2 + docs/features/mcp-edit-tools/README.md | 2 + docs/features/mcp-feedback-1/README.md | 433 ++++++++++ docs/features/mcp-navigation/README.md | 2 + mcp_analysis.md | 125 +++ 33 files changed, 3348 insertions(+), 178 deletions(-) create mode 100644 crates/lucisv_mcp/src/tools/mentions.rs create mode 100644 crates/lucisv_mcp/src/tools/place.rs create mode 100644 crates/lucisv_mcp/src/tools/place/slot.rs create mode 100644 crates/lucisv_mcp/src/tools/place/verify.rs create mode 100644 crates/lucisv_mcp/tests/fixtures/feedback/dv/probe_if.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/feedback/rtl/cipher.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/feedback/rtl/core.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/feedback/rtl/other_sm.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/feedback/rtl/sm.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/feedback/rtl/wrap.sv create mode 100644 crates/lucisv_mcp/tests/qa_f1.rs create mode 100644 docs/features/mcp-feedback-1/README.md create mode 100644 mcp_analysis.md diff --git a/TODO-MCP.md b/TODO-MCP.md index 4f677b8..23d021f 100644 --- a/TODO-MCP.md +++ b/TODO-MCP.md @@ -318,6 +318,31 @@ Depends on M4 and M5 merged. to correct by reading the file anyway (each is a finding against a tool's rendering); verdict +## Feedback rounds (the token census → the server) + +### Round 1 → lane feedback-1 (`docs/features/mcp-feedback-1`) + +- [x] unresolved mentions (`src/tools/mentions.rs`): every whole-word + spelling of the name in strings, comments, macro text, `define bodies + and macro-rooted paths that no engine answer accounted for, capped at + 50; `references` ends with the section, `rename`/`remove_port`/ + `add_port` warn with it; `unresolved_mentions` in the JSON; opentitan + cost recorded — done 2026-09-23 (dev) +- [x] descriptions and `instructions`: `hierarchy` leads with "who + instantiates a module", `references` points a module name at + `hierarchy up`; every description trimmed; `tools/list` 30 221 B → + 17 981 B (≤ 18 kB, pinned by a wire test) — done 2026-09-23 (dev) +- [x] `add_port` `after`: the port placed after a named one in its line's + layout, each named connection after `.after(…)`; verified against the + engine's appending edit (`src/tools/place.rs`) — done 2026-09-23 (dev) +- [x] stale `index-cache-mcp.*.tmp` swept before the own store is written; + M6 QA's ignored test un-ignored — done 2026-09-23 (dev) +- [x] wire tests: mentions on `references` and `rename`, `after` byte-exact + on an `aes_core`-shaped fixture, catalogue size, sweep — done + 2026-09-23 (dev) +- [x] QA: attack the mentions scanner (false positives and misses) and the + `after` verifier; verdict + ## Open questions for the owner (answer before the lane that needs it) 1. **Engine bump** (M5): if `vsce` accepts the contribution point on diff --git a/crates/lucisv_mcp/src/cache.rs b/crates/lucisv_mcp/src/cache.rs index fb6b9b5..2b3539c 100644 --- a/crates/lucisv_mcp/src/cache.rs +++ b/crates/lucisv_mcp/src/cache.rs @@ -18,6 +18,7 @@ use std::collections::HashMap; use std::fs; use std::io; use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; use lucisv_core::cache::content_hash; use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT}; @@ -125,6 +126,7 @@ pub fn write_own(dir: &Path, records: &[(u64, &FileFacts)]) -> io::Result if !ignore.exists() { let _ = fs::write(&ignore, "*\n"); } + sweep_stale_temps(dir); let mut text = header(); text.push('\n'); let mut written = 0; @@ -147,6 +149,34 @@ pub fn write_own(dir: &Path, records: &[(u64, &FileFacts)]) -> io::Result Ok(written) } +/// How old a temporary store file must be before a writer counts it as a +/// dead writer's: a live writer renames its own within a second or two. +const STALE_TEMP: Duration = Duration::from_secs(600); + +/// Remove the `index-cache-mcp..tmp` files in `dir` older than +/// [`STALE_TEMP`] — left by a writer killed between its write and its +/// rename (M6 QA finding 2). A younger one may be a concurrent writer's, +/// and is left alone; anything else in the directory is never touched. +fn sweep_stale_temps(dir: &Path) { + let Ok(entries) = fs::read_dir(dir) else { return }; + let now = SystemTime::now(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let ours = name + .strip_prefix(OWN_STORE) + .and_then(|rest| rest.strip_prefix('.')) + .and_then(|rest| rest.strip_suffix(".tmp")) + .is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit())); + let modified = entry.metadata().and_then(|meta| meta.modified()); + let stale = + modified.is_ok_and(|at| now.duration_since(at).is_ok_and(|age| age > STALE_TEMP)); + if ours && stale && entry.file_type().is_ok_and(|kind| kind.is_file()) { + let _ = fs::remove_file(entry.path()); + } + } +} + /// The first line of a store this build reads and writes. fn header() -> String { format!("lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t{VERSION}") diff --git a/crates/lucisv_mcp/src/rpc.rs b/crates/lucisv_mcp/src/rpc.rs index 290f25c..48d27d9 100644 --- a/crates/lucisv_mcp/src/rpc.rs +++ b/crates/lucisv_mcp/src/rpc.rs @@ -36,7 +36,7 @@ const NOT_INITIALIZED: i64 = -32002; const RESOURCE_NOT_FOUND: i64 = -32002; /// What the agent is told once, at `initialize`. -const INSTRUCTIONS: &str = "lucisv-mcp reads and edits the Verilog/SystemVerilog design under its roots, from the files on disk (never unsaved editor buffers). Read less: unit_interface gives a module's parameters and ports, outline what a file declares, read_item one module, function or always block; list_units, search_symbols, definition, references and hierarchy find the rest. Every edit is verified before anything is written, all-or-nothing, straight to disk; pass dry_run: true to see the diff first. One item: replace_item, insert_item, delete_item. Design-wide: rename, add_port, remove_port and the other refactorings update every file that needs it; format and fix_lint reformat and fix. Run diagnostics after an edit to check it. Paths are relative to a root; lines are 1-based, columns 1-based bytes."; +const INSTRUCTIONS: &str = "lucisv-mcp reads and edits the Verilog/SystemVerilog design under its roots, from the files on disk (never unsaved editor buffers). Read less: unit_interface gives a module's ports, outline a file's declarations, read_item one item; list_units, search_symbols, definition, references and hierarchy find the rest. Who instantiates module X (instances, overrides): hierarchy with direction up, not references. Every edit is verified, all-or-nothing, straight to disk; dry_run: true shows the diff first. One item: replace_item, insert_item, delete_item. Design-wide: rename, add_port, remove_port and other refactorings; format, fix_lint. rename, references and the port edits list the name's unresolved mentions (strings, comments, macro text) to check. Run diagnostics after an edit. A position: file + line (+ col or name). Paths are relative to a root; lines are 1-based, columns 1-based bytes."; /// A JSON-RPC error object. #[derive(Debug, Serialize)] diff --git a/crates/lucisv_mcp/src/tools/defines.rs b/crates/lucisv_mcp/src/tools/defines.rs index e5c980b..22cde7c 100644 --- a/crates/lucisv_mcp/src/tools/defines.rs +++ b/crates/lucisv_mcp/src/tools/defines.rs @@ -20,31 +20,31 @@ const BODY_CAP: usize = 200; pub const DEFINES: Tool = Tool { name: "defines", title: "Macro definitions", - description: "The `define table: name, parameters, body (on one line) and file:line — of one `file`, of one macro `name` across the project (every definition; which one a use sees depends on include order, so none is picked), or of the whole project. Prefer it over grepping for `define.", + description: "The `define table (name, parameters, body, file:line) of one `file`, one macro `name`, or all.", params: &[ Param { name: "file", ty: Ty::Str, required: false, - description: "Only this file's table (its `undef`s included), relative to a root or absolute inside one.", + description: "Only this file's table.", }, Param { name: "name", ty: Ty::Str, required: false, - description: "Only this macro, written with or without the backtick.", + description: "Only this macro (backtick optional).", }, Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Most entries to return (default 200).", + description: "Max entries (default 200).", }, Param { name: "offset", ty: Ty::Int { min: 0 }, required: false, - description: "Entries to skip, for paging past `… and N more` (default 0).", + description: "Entries to skip.", }, ], rewalk: false, diff --git a/crates/lucisv_mcp/src/tools/diagnostics.rs b/crates/lucisv_mcp/src/tools/diagnostics.rs index f9e71e6..c9e7cfc 100644 --- a/crates/lucisv_mcp/src/tools/diagnostics.rs +++ b/crates/lucisv_mcp/src/tools/diagnostics.rs @@ -31,37 +31,37 @@ use crate::render::{self, DEFAULT_LIMIT}; pub const DIAGNOSTICS: Tool = Tool { name: "diagnostics", title: "Diagnostics", - description: "Parse errors and lint findings for one `file`, or for every indexed file, grouped by file as `line:col severity message [rule]` — what `lucisv check` over the whole tree reports (cross-file rules on), under the project's lucisv.toml [lint] settings and waivers. Filter with `rules` (like --select) and `severity`. The whole-project form lints every file and returns the first `limit` findings with the total.", + description: "Parse errors and lint findings (`line:col severity message [rule]`) of `file` or all files.", params: &[ Param { name: "file", ty: Ty::Str, required: false, - description: "One file, relative to a root or absolute inside one (default: every indexed file).", + description: "One file (default: all).", }, Param { name: "rules", ty: Ty::Str, required: false, - description: "Comma-separated rule names or severities to run instead of the configured set, like `--select`.", + description: "Rules or severities to run.", }, Param { name: "severity", ty: Ty::Enum(&["error", "warning", "style"]), required: false, - description: "Only findings of this severity (parse errors are `error`).", + description: "Only this severity.", }, Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Most findings to return (default 200).", + description: "Most findings (default 200).", }, Param { name: "offset", ty: Ty::Int { min: 0 }, required: false, - description: "Findings to skip, for paging past `… and N more` (default 0).", + description: "Findings to skip.", }, ], rewalk: false, diff --git a/crates/lucisv_mcp/src/tools/edit.rs b/crates/lucisv_mcp/src/tools/edit.rs index 2c4d2b0..2c49634 100644 --- a/crates/lucisv_mcp/src/tools/edit.rs +++ b/crates/lucisv_mcp/src/tools/edit.rs @@ -15,8 +15,10 @@ use std::path::{Path, PathBuf}; -use vlog_refactor::RefactorEdit; +use vlog_parser::span::TextRange; +use vlog_refactor::{RefactorEdit, TextEdit}; +use super::mentions::{self, Focus}; use super::select::{target, Target}; use super::source::WholeSet; use super::{nav, Answer, Args, Param, Tool, Ty}; @@ -24,37 +26,16 @@ use crate::apply::{self, Plan}; use crate::project::{Analysis, Project}; /// `dry_run`, which every edit tool takes. -pub(super) const DRY_RUN: Param = Param { - name: "dry_run", - ty: Ty::Bool, - required: false, - description: "Return the unified diff and write nothing (default false).", -}; +pub(super) const DRY_RUN: Param = + Param { name: "dry_run", ty: Ty::Bool, required: false, description: "Return the diff only." }; -const FILE: Param = Param { - name: "file", - ty: Ty::Str, - required: true, - description: "The file holding the position, relative to a root or absolute inside one.", -}; -const LINE: Param = Param { - name: "line", - ty: Ty::Int { min: 1 }, - required: false, - description: "1-based line in `file`; alone it means the line's first non-blank character.", -}; -const COL: Param = Param { - name: "col", - ty: Ty::Int { min: 1 }, - required: false, - description: "1-based column in bytes on `line`.", -}; -const NAME: Param = Param { - name: "name", - ty: Ty::Str, - required: false, - description: "The name written at the position: with `line`, its occurrence on that line; without, its occurrence in `file`.", -}; +const FILE: Param = Param { name: "file", ty: Ty::Str, required: true, description: "The file." }; +const LINE: Param = + Param { name: "line", ty: Ty::Int { min: 1 }, required: false, description: "Line." }; +const COL: Param = + Param { name: "col", ty: Ty::Int { min: 1 }, required: false, description: "Byte column." }; +const NAME: Param = + Param { name: "name", ty: Ty::Str, required: false, description: "The name on `line`." }; /// The position arguments of the six cursor refactorings, then `dry_run`. const AT: &[Param] = &[FILE, LINE, COL, NAME, DRY_RUN]; @@ -69,7 +50,7 @@ type Stake = fn(&Analysis, u32) -> Vec; pub const EXPAND_WILDCARD: Tool = Tool { name: "expand_wildcard", title: "Expand .* connections", - description: "Replace one instantiation's `.*` with the named connections it binds, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a `bind` instance, a positional list, and a port list whose binding depends on `ifdef`s, with the reason. `dry_run` returns the diff.", + description: "Replace one instance's `.*` with the named connections it binds.", params: AT, rewalk: true, handler: expand_wildcard, @@ -78,7 +59,7 @@ pub const EXPAND_WILDCARD: Tool = Tool { pub const CONVERT_PORTS: Tool = Tool { name: "convert_ports", title: "Convert ports to ANSI", - description: "Rewrite a module's non-ANSI header (`module m(a, b); input a; …`) as an ANSI port list, verified before anything is written. Point at the module: `file`+`line` (+`col`, or the module `name`). Refuses a header it cannot convert exactly, with the reason. `dry_run` returns the diff.", + description: "Rewrite a module's non-ANSI header as an ANSI port list.", params: AT, rewalk: true, handler: convert_ports, @@ -87,7 +68,7 @@ pub const CONVERT_PORTS: Tool = Tool { pub const ORGANIZE_IMPORTS: Tool = Tool { name: "organize_imports", title: "Organize imports", - description: "Remove the unused `import` items of the scope at a position and sort the rest, verified before anything is written. Point into the scope with `file`+`line`. Refuses where it cannot judge (a macro or `include` in the scope, an unknown package), with the reason. `dry_run` returns the diff.", + description: "Remove the unused `import`s of the scope at a position and sort the rest.", params: AT, rewalk: true, handler: organize_imports, @@ -96,7 +77,7 @@ pub const ORGANIZE_IMPORTS: Tool = Tool { pub const INLINE_MODULE: Tool = Tool { name: "inline_module", title: "Inline a module instance", - description: "Replace one instantiation with the body of the module it instantiates, its connections substituted, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses what it cannot substitute exactly, with the reason. `dry_run` returns the diff.", + description: "Replace one instance with its module's body, connections substituted.", params: AT, rewalk: true, handler: inline_module, @@ -105,7 +86,7 @@ pub const INLINE_MODULE: Tool = Tool { pub const PROPAGATE_PORTS: Tool = Tool { name: "propagate_ports", title: "Connect missing ports", - description: "Add a named connection for every port one instantiation leaves unconnected, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a positional or `.*` list, and an instance that already connects every port. `dry_run` returns the diff.", + description: "Add a named connection for every port one instance leaves unconnected.", params: AT, rewalk: true, handler: propagate_ports, @@ -114,7 +95,8 @@ pub const PROPAGATE_PORTS: Tool = Tool { pub const REMOVE_PORT: Tool = Tool { name: "remove_port", title: "Remove a port", - description: "Delete one module port and its connection from every instantiation in the project, verified before anything is written. Point at the port: `file`+`line` (+`col`, or the port `name`). Refuses a port the body still uses, a positional instantiation, and a deletion that would drop a comment. `dry_run` returns the diff.", + description: + "Delete one port and its connection in every instantiation; refused while the body uses it.", params: AT, rewalk: true, handler: remove_port, @@ -123,23 +105,23 @@ pub const REMOVE_PORT: Tool = Tool { pub const RENAME: Tool = Tool { name: "rename", title: "Rename a symbol", - description: "Rename one declaration and every reference to it across the project, verified before anything is written. Select as for `definition`: `file`+`line`+`col`, `file`+`line`+`name`, `file`+`name`, or `name` (+`unit`). Refuses an invalid or clashing name and a use it cannot account for; a name already `new_name` is `unchanged`. A `.*` or `.name` connection that bound the renamed name is written out explicitly (listed in `warnings`).", + description: "Rename a declaration and its references; select as `definition`. `.*`/`.name` bindings are written out; unresolved textual mentions are listed.", params: &[ Param { required: false, ..FILE }, Param { - description: "1-based line in `file`; give `col` too, or the `name` written on that line.", + description: "Line.", ..LINE }, COL, Param { - description: "The name to rename: alone, looked up across the project; with `file`, its occurrence there; with `file` and `line`, its occurrence on that line.", + description: "Name; alone, looked up project-wide.", ..NAME }, Param { name: "unit", ty: Ty::Str, required: false, - description: "With a bare `name`: the module, interface, package or class declaring it.", + description: "Unit declaring a bare `name`.", }, Param { name: "new_name", @@ -175,12 +157,21 @@ fn propagate_ports(project: &mut Project, args: &Args) -> Result } fn remove_port(project: &mut Project, args: &Args) -> Result { - let port_and_module = |analysis: &Analysis, offset: u32| { - let mut names = name_at(analysis, offset); - names.extend(instantiated(analysis, offset)); - names + let (path, offset) = cursor(project, args)?; + let analysis = project.analysis(&path)?; + let port = name_at(&analysis, offset); + let mut names = port.clone(); + names.extend(instantiated(&analysis, offset)); + let unit = enclosing(&analysis, offset); + let set = whole_set(project, Some(&path), &names)?; + let edit = vlog_refactor::remove_port(&set.files, &path, offset)?; + let Some(port) = port.first() else { return finish(project, edit, &set, args) }; + let told = Told { + name: port, + lead: format!("the removed port `{port}` is still spelled"), + home: &path, }; - at_cursor(project, args, vlog_refactor::remove_port, port_and_module) + finish_telling(project, edit, &set, args, told, unit.first().map(String::as_str)) } /// The declared name at a position. @@ -266,6 +257,60 @@ pub(super) fn finish( apply::run(project, plan, args.flag("dry_run", false)) } +/// The name an edit changes, for the unresolved-mentions warning: the name, +/// how the warning begins, and the file declaring it. +pub(super) struct Told<'a> { + pub name: &'a str, + pub lead: String, + pub home: &'a Path, +} + +/// [`finish`], and the unresolved mentions of `told.name` the edit left +/// alone named under `warnings:` (and as `unresolved_mentions`) — found in +/// the texts as the edit writes them, so each `file:line` is right after +/// the write (QA finding 4). +pub(super) fn finish_telling( + project: &Project, + edit: RefactorEdit, + set: &WholeSet, + args: &Args, + told: Told, + unit: Option<&str>, +) -> Result { + let accounted: Vec<(PathBuf, Vec)> = + edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect(); + let mut plan = Plan::from_refactor(edit, &set.files)?; + let written = set.files.iter().map(|(path, text)| { + let change = plan.changes.iter().find(|change| &change.path == path); + (path.as_path(), change.map_or(text.as_str(), |change| change.after.as_str())) + }); + let focus = Focus { name: told.name, home: told.home, unit, accounted: &accounted }; + let mentions = mentions::find(project, written, &focus); + plan.warnings.extend(set.warning(project)); + if !mentions.is_empty() { + plan.warnings.push(mentions.warning(&told.lead)); + } + let mut answer = apply::run(project, plan, args.flag("dry_run", false))?; + answer.structured["unresolved_mentions"] = mentions.json(); + Ok(answer) +} + +/// Where each of one file's edits lands in the text as written: its start +/// shifted by what the edits before it added or removed, its length the +/// new text's. +fn written_ranges(edits: &[TextEdit]) -> Vec { + let mut sorted: Vec<&TextEdit> = edits.iter().collect(); + sorted.sort_by_key(|edit| (edit.range.start, edit.range.end)); + let mut shift: i64 = 0; + let mut out = Vec::new(); + for edit in sorted { + let start = (i64::from(edit.range.start) + shift).max(0) as u32; + out.push(TextRange::new(start, start + edit.new_text.len() as u32)); + shift += edit.new_text.len() as i64 - i64::from(edit.range.len()); + } + out +} + fn rename(project: &mut Project, args: &Args) -> Result { let new_name = args.str("new_name").unwrap_or_default(); let (path, offset) = match target(project, args)? { @@ -279,5 +324,9 @@ fn rename(project: &mut Project, args: &Args) -> Result { } let set = whole_set(project, Some(&path), &names)?; let edit = vlog_refactor::rename(&set.files, &path, offset, new_name)?; - finish(project, edit, &set, args) + let Some(old) = names.first() else { return finish(project, edit, &set, args) }; + let unit = enclosing(&*project.analysis(&path)?, offset); + let told = + Told { name: old, lead: format!("the old name `{old}` is still spelled"), home: &path }; + finish_telling(project, edit, &set, args, told, unit.first().map(String::as_str)) } diff --git a/crates/lucisv_mcp/src/tools/format.rs b/crates/lucisv_mcp/src/tools/format.rs index 0b461b3..d843d04 100644 --- a/crates/lucisv_mcp/src/tools/format.rs +++ b/crates/lucisv_mcp/src/tools/format.rs @@ -28,23 +28,14 @@ use crate::project::{Analysis, Project}; /// CLI's reason: two overlapping fixes land in successive rounds. const MAX_FIX_ROUNDS: usize = 10; -const FILE: Param = Param { - name: "file", - ty: Ty::Str, - required: false, - description: "One file, relative to a root or absolute inside one.", -}; -const FILES: Param = Param { - name: "files", - ty: Ty::Str, - required: false, - description: "Several files, comma-separated, instead of `file`.", -}; +const FILE: Param = Param { name: "file", ty: Ty::Str, required: false, description: "The file." }; +const FILES: Param = + Param { name: "files", ty: Ty::Str, required: false, description: "Comma-separated files." }; pub const FORMAT: Tool = Tool { name: "format", title: "Format files", - description: "Format `file` (or the comma-separated `files`) as `lucisv format` does, under each file's lucisv.toml; `lines` (`12-40,55`, one file only) formats just the constructs meeting those lines. The formatter verifies its own output: a file it will not format safely refuses the whole call, naming it. An already formatted file is `unchanged`. `dry_run` returns the diff.", + description: "Format `file`/`files` as `lucisv format`; `lines` limits it.", params: &[ FILE, FILES, @@ -52,7 +43,7 @@ pub const FORMAT: Tool = Tool { name: "lines", ty: Ty::Str, required: false, - description: "1-based line ranges such as `12-40,55`; only with a single file.", + description: "Line ranges such as `12-40,55` (one file only).", }, DRY_RUN, ], @@ -63,7 +54,7 @@ pub const FORMAT: Tool = Tool { pub const FIX_LINT: Tool = Tool { name: "fix_lint", title: "Apply safe lint fixes", - description: "Apply the safe automatic fixes of the lint findings in `file` (or the comma-separated `files`), as `lucisv check --fix` does: the project's [lint] config and waivers, never inside a `// lucisv: off` fence, never an unsafe fix. Reports which rules were fixed and how many findings remain (`diagnostics` lists them). `rules` narrows the run like --select. `dry_run` returns the diff.", + description: "Apply the safe lint fixes to `file`/`files`; says what remains.", params: &[ FILE, FILES, @@ -71,7 +62,7 @@ pub const FIX_LINT: Tool = Tool { name: "rules", ty: Ty::Str, required: false, - description: "Comma-separated rule names or severities to fix instead of the configured set.", + description: "Rules or severities to fix.", }, DRY_RUN, ], diff --git a/crates/lucisv_mcp/src/tools/hierarchy.rs b/crates/lucisv_mcp/src/tools/hierarchy.rs index aa093e0..ae9db81 100644 --- a/crates/lucisv_mcp/src/tools/hierarchy.rs +++ b/crates/lucisv_mcp/src/tools/hierarchy.rs @@ -35,37 +35,37 @@ const NODE_CAP: usize = 50_000; pub const HIERARCHY: Tool = Tool { name: "hierarchy", title: "Instance hierarchy", - description: "The instance tree as indented `instance : module #(overrides)` lines, down from `root` (default: every top-level module), or with `direction: up` every `parent.instance` that instantiates `root`, with file:line. Textual, not elaborated: `generate` and `ifdef` branches all appear. Prefer it over reading files to find who instantiates what.", + description: "Who instantiates a module (`up`: every instance with its name, `#(…)` overrides and file:line) or what a module instantiates (`down`, the default). Textual, all branches.", params: &[ Param { name: "root", ty: Ty::Str, required: false, - description: "The module to start from; required for `up` (default for `down`: every module nothing instantiates).", + description: "The module; required for `up`.", }, Param { name: "direction", ty: Ty::Enum(&["down", "up"]), required: false, - description: "`down` lists what `root` instantiates (default); `up` lists what instantiates it.", + description: "`down` (default) or `up`.", }, Param { name: "depth", ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 }, required: false, - description: "Levels to walk (default 3, at most 20).", + description: "Levels (default 3, at most 20).", }, Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Most lines to return (default 200).", + description: "Most lines (default 200).", }, Param { name: "offset", ty: Ty::Int { min: 0 }, required: false, - description: "Lines to skip, for paging past `… and N more` (default 0).", + description: "Lines to skip.", }, ], rewalk: false, diff --git a/crates/lucisv_mcp/src/tools/interface.rs b/crates/lucisv_mcp/src/tools/interface.rs index 617e231..e8c73c2 100644 --- a/crates/lucisv_mcp/src/tools/interface.rs +++ b/crates/lucisv_mcp/src/tools/interface.rs @@ -19,19 +19,19 @@ use crate::render; pub const UNIT_INTERFACE: Tool = Tool { name: "unit_interface", title: "Unit interface", - description: "The interface of one unit by name: a module's or interface's parameters with defaults, ports in declaration order (direction, type, range) and a ready-to-paste instantiation; an interface's modports; a package's or class's members. Prefer it over reading the declaring file. Refuses a name declared in several files unless `file` picks one.", + description: "A unit's parameters (defaults), ports (direction, type, range), an instantiation to paste; modports; members.", params: &[ Param { name: "name", ty: Ty::Str, required: true, - description: "The unit's name; a class inside a package may be written `pkg::cls`.", + description: "The unit's name (`pkg::cls` for a class).", }, Param { name: "file", ty: Ty::Str, required: false, - description: "The declaring file, when the name is declared more than once.", + description: "Its file, if declared twice.", }, ], rewalk: false, diff --git a/crates/lucisv_mcp/src/tools/item.rs b/crates/lucisv_mcp/src/tools/item.rs index a840597..98d494d 100644 --- a/crates/lucisv_mcp/src/tools/item.rs +++ b/crates/lucisv_mcp/src/tools/item.rs @@ -35,29 +35,16 @@ use span::{ }; use verify::{Expect, Splice}; -const FILE: Param = Param { - name: "file", - ty: Ty::Str, - required: true, - description: "The file, relative to a root or absolute inside one.", -}; -const ITEM: Param = Param { - name: "item", - ty: Ty::Str, - required: true, - description: "`read_item`'s selector: `name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).", -}; -const TEXT: Param = Param { - name: "text", - ty: Ty::Str, - required: true, - description: "The item's source text. Surrounding blank space is dropped; line endings follow the file's.", -}; +const FILE: Param = Param { name: "file", ty: Ty::Str, required: true, description: "The file." }; +const ITEM: Param = + Param { name: "item", ty: Ty::Str, required: true, description: "`read_item`'s selector." }; +const TEXT: Param = + Param { name: "text", ty: Ty::Str, required: true, description: "The source text." }; pub const REPLACE_ITEM: Tool = Tool { name: "replace_item", title: "Replace one item", - description: "Replace one item (read_item's selector) with `text`, verified before anything is written: the file must still parse; `text` must be ONE item of the same kind (a module stays a module) declaring the same names unless `rename: true` (references are then NOT updated; `rename` does that). Bytes outside the item never change. A `text` beginning with a comment replaces the item's own leading comments; one ending in a same-line comment, its trailing one. `text` equal to the item is `unchanged`. `dry_run` returns the diff.", + description: "Replace one item with `text`: one item, same kind and names (unless `rename`; references untouched). Comments around `text` replace the item's own.", params: &[ FILE, ITEM, @@ -66,7 +53,7 @@ pub const REPLACE_ITEM: Tool = Tool { name: "rename", ty: Ty::Bool, required: false, - description: "Allow the text to declare other names than the item did (default false).", + description: "Allow other declared names.", }, DRY_RUN, ], @@ -77,20 +64,20 @@ pub const REPLACE_ITEM: Tool = Tool { pub const INSERT_ITEM: Tool = Tool { name: "insert_item", title: "Insert items", - description: "Insert `text` (one item or more) before or after the item `anchor` names (read_item's selector), or with `anchor: \"end\"` as the last items of the file's last module, package or class (`end@NAME` for that unit), verified before anything is written: the file must still parse and `text` must be complete items the scope may hold. A blank line separates them from neighbouring items. Refused inside a `// lucisv: off` fence. `dry_run` returns the diff.", + description: "Insert items `text` before or after item `anchor`, or at `end` (`end@NAME`) of the last unit (unit NAME).", params: &[ FILE, Param { name: "anchor", ty: Ty::Str, required: true, - description: "An item selector (as `read_item`), `end`, or `end@NAME`.", + description: "An item selector, `end`, or `end@NAME`.", }, Param { name: "position", ty: Ty::Enum(&["before", "after"]), required: false, - description: "Before or after the anchor item (default after); ignored for `end`.", + description: "`before` or `after` (default).", }, TEXT, DRY_RUN, @@ -102,7 +89,7 @@ pub const INSERT_ITEM: Tool = Tool { pub const DELETE_ITEM: Tool = Tool { name: "delete_item", title: "Delete one item", - description: "Delete one item (read_item's selector) and its own leading comments (up to a blank line), verified before anything is written. Refused while a name it declares is referenced anywhere in the project — a `.*` that binds it and a spelling inside a macro count — (the first sites are listed) unless `force: true`, and inside a `// lucisv: off` fence. An item holding a `define/`undef is refused too unless `force` (the macros are named under warnings). A declaration of several names goes whole. A second identical call is refused: no such item. `dry_run` returns the diff.", + description: "Delete one item and its leading comments; refused while its names are used (sites listed) or it holds a `define, unless `force`.", params: &[ FILE, ITEM, @@ -110,7 +97,7 @@ pub const DELETE_ITEM: Tool = Tool { name: "force", ty: Ty::Bool, required: false, - description: "Delete even though references remain or the item holds macro definitions (default false); both are listed under warnings.", + description: "Delete anyway.", }, DRY_RUN, ], diff --git a/crates/lucisv_mcp/src/tools/mentions.rs b/crates/lucisv_mcp/src/tools/mentions.rs new file mode 100644 index 0000000..49f620e --- /dev/null +++ b/crates/lucisv_mcp/src/tools/mentions.rs @@ -0,0 +1,352 @@ +//! Unresolved mentions: every whole-word spelling of a name that no engine +//! answer accounted for and that sits where no lucisv engine looks — inside +//! a string literal, a comment, a macro call's text, a `` `define`` body, or +//! a hierarchical path rooted at a macro (`` `X_HIER.u_core.name``). +//! +//! These are the spellings a rename leaves behind without a word: a DV +//! force path built as the string `".state_q"`, a probe through a macro +//! path, a comment naming the signal. lucisv cannot tell whether any of them +//! means *this* declaration — a word is a word — so they are listed, never +//! edited, and the agent decides (feedback round 1, `mcp_analysis.md`). +//! +//! The pass reads nothing new: the engines were handed every indexed file's +//! text already (`source::WholeSet`), so each text is byte-searched for the +//! name, and only a text that spells it is lexed. The index's word censuses +//! (`files_mentioning`, `files_naming_in_macros`) cannot narrow it further: +//! comments and strings are not in them. + +use std::path::{Path, PathBuf}; + +use serde_json::{json, Value}; +use vlog_parser::span::TextRange; +use vlog_parser::token::{Token, TokenKind}; +use vlog_parser::{tokenize, LineIndex}; + +use super::source::{capped, word_in}; +use crate::project::Project; + +/// The most mentions an answer lists; the rest are counted. +pub const CAP: usize = 50; + +/// The longest line text a mention shows. +const LINE_CAP: usize = 160; + +/// One unresolved spelling: where, what kind of text holds it, and the line. +pub struct Mention { + pub file: String, + pub line: u32, + pub kind: &'static str, + pub text: String, +} + +/// The mentions an answer lists (at most [`CAP`]) and how many there are. +#[derive(Default)] +pub struct Mentions { + pub listed: Vec, + pub total: usize, +} + +/// What the search is about: the name, where it is declared (the listing +/// starts nearest to it), and the spans the engine already accounted for. +pub struct Focus<'a> { + pub name: &'a str, + /// The declaration's file. + pub home: &'a Path, + /// The unit declaring the name, when known: a line naming it (an + /// instance `u_` on a macro path) is listed early. + pub unit: Option<&'a str>, + /// Per file, the spans an engine returned (hits) or rewrote (edits). + pub accounted: &'a [(PathBuf, Vec)], +} + +impl Mentions { + /// Whether there is nothing to say. + pub fn is_empty(&self) -> bool { + self.total == 0 + } + + /// One indented line per mention, `file:line kind: text`, then the cap. + pub fn lines(&self, indent: &str) -> String { + let mut out = String::new(); + for mention in &self.listed { + let (file, line, kind) = (&mention.file, mention.line, mention.kind); + out.push_str(&format!("{indent}{file}:{line} {kind}: {}\n", mention.text)); + } + let rest = self.total - self.listed.len(); + if rest > 0 { + out.push_str(&format!("{indent}… and {rest} more\n")); + } + out + } + + /// The `unresolved_mentions` JSON: the listed ones. + pub fn json(&self) -> Value { + let listed: Vec = self + .listed + .iter() + .map(|m| json!({ "file": m.file, "line": m.line, "text": m.text, "kind": m.kind })) + .collect(); + Value::from(listed) + } + + /// The sentence an edit tool puts under `warnings:` — `lead` is how it + /// begins (`the old name `x` is still spelled`) — the list below it. + pub fn warning(&self, lead: &str) -> String { + let places = if self.total == 1 { "1 place" } else { "these places" }; + let mut text = format!( + "{lead} as text at {places} lucisv does not resolve (strings, comments, macro text; {} in all); check whether these are references:\n", + self.total + ); + text.push_str(self.lines(" ").trim_end()); + text + } +} + +/// The unresolved mentions of `focus.name` across `files`, nearest first. +pub fn find<'t>( + project: &Project, + files: impl Iterator, + focus: &Focus, +) -> Mentions { + let mut found: Vec<(u8, usize, Mention)> = Vec::new(); + for (path, text) in files { + if !text.contains(focus.name) { + continue; + } + let accounted = focus.accounted.iter().find(|(held, _)| held.as_path() == path); + let spans = accounted.map_or(&[][..], |(_, spans)| spans.as_slice()); + let lines = LineIndex::new(text); + let mut last_line = 0; + for (at, kind) in spellings(text, focus.name) { + let end = at + focus.name.len() as u32; + if spans.iter().any(|span| span.start <= at && end <= span.end) { + continue; + } + let line = lines.line_col(at).0; + if line == last_line { + continue; + } + last_line = line; + let source = lines + .line_range(line) + .and_then(|range| text.get(range.start as usize..range.end as usize)) + .unwrap_or(""); + let rank = rank(accounted.is_some(), focus.unit, source); + let file = project.relative(path); + let mention = Mention { file, line, kind, text: capped(source, LINE_CAP) }; + found.push((rank, shared_components(path, focus.home), mention)); + } + } + // Files the engine touched, then lines naming the declaring unit, then + // nearest to the declaration's directory; file and line order within. + found.sort_by(|a, b| (b.0, b.1, &a.2.file, a.2.line).cmp(&(a.0, a.1, &b.2.file, b.2.line))); + let total = found.len(); + let listed = found.into_iter().take(CAP).map(|(_, _, mention)| mention).collect(); + Mentions { listed, total } +} + +/// How early a mention is listed: 2 in a file the engine touched, 1 on a +/// line that spells the declaring unit's name (`u_` included), 0 +/// otherwise. +fn rank(touched: bool, unit: Option<&str>, line: &str) -> u8 { + if touched { + 2 + } else if unit.is_some_and(|unit| !unit.is_empty() && line.contains(unit)) { + 1 + } else { + 0 + } +} + +/// How many leading path components two paths share. +fn shared_components(a: &Path, b: &Path) -> usize { + a.components().zip(b.components()).take_while(|(x, y)| x == y).count() +} + +/// Every whole-word spelling of `name` in `text` that lies in a comment, a +/// string, a macro call, a `` `define`` body, or ends a macro-rooted path, +/// as `(byte offset, kind)` in source order. A file that does not lex has +/// every spelling listed (`text`): nothing in it was resolved. +fn spellings(text: &str, name: &str) -> Vec<(u32, &'static str)> { + let Ok(tokens) = tokenize(text) else { + return words(text, 0, name).into_iter().map(|at| (at, "text")).collect(); + }; + let mut out = Vec::new(); + for (i, token) in tokens.iter().enumerate() { + for comment in token.leading.iter().chain(token.trailing.as_ref()) { + let at = comment.span.start; + out.extend(words(&comment.text, at, name).into_iter().map(|at| (at, "comment"))); + } + let (at, source) = (token.span.start, token.text.as_str()); + match token.kind { + TokenKind::String => { + out.extend(words(source, at, name).into_iter().map(|at| (at, "string"))) + } + TokenKind::Ident if token.is_macro() => { + let after = macro_name_end(source); + let found = words(&source[after..], at + after as u32, name); + out.extend(found.into_iter().map(|at| (at, "macro"))); + } + TokenKind::Directive => { + let Some((formals, body)) = define_parts(source) else { continue }; + // A formal argument of that name shadows it in the body. + if word_in(&source[formals..body], name).is_some() { + continue; + } + let found = words(&source[body..], at + body as u32, name); + out.extend(found.into_iter().map(|at| (at, "define"))); + } + TokenKind::Ident if token.text == name && macro_rooted(&tokens, i) => { + out.push((at, "path")); + } + _ => {} + } + } + out.sort_by_key(|(at, _)| *at); + out +} + +/// Every whole-word occurrence of `name` in `text`, as offsets from `base`. +fn words(text: &str, base: u32, name: &str) -> Vec { + let mut out = Vec::new(); + let mut from = 0; + while let Some(found) = text.get(from..).and_then(|rest| word_in(rest, name)) { + out.push(base + (from + found) as u32); + from += found + name.len(); + } + out +} + +/// Where a macro use's own name ends (`` `NAME`` then its arguments). +fn macro_name_end(text: &str) -> usize { + 1 + ident_len(text.get(1..).unwrap_or("")) +} + +/// The length of the identifier `text` starts with. +fn ident_len(text: &str) -> usize { + let glued = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$'; + text.find(|c: char| !glued(c)).unwrap_or(text.len()) +} + +/// A `` `define`` directive's formal argument list and body: where the list +/// starts (past the macro's name) and where the body starts (past the list). +/// `None` for any other directive. +fn define_parts(text: &str) -> Option<(usize, usize)> { + let rest = text.strip_prefix("`define")?; + let name_at = text.len() - rest.trim_start().len(); + let formals = name_at + ident_len(&text[name_at..]); + if !text[formals..].starts_with('(') { + return Some((formals, formals)); + } + let mut depth = 0usize; + for (offset, c) in text[formals..].char_indices() { + match c { + '(' => depth += 1, + ')' if depth == 1 => return Some((formals, formals + offset + 1)), + ')' => depth = depth.saturating_sub(1), + _ => {} + } + } + Some((formals, text.len())) +} + +/// Whether the identifier at `i` ends a dotted path whose head is a macro +/// (`` `HIER.u_a[0].name``, `` `HIER(1).name``) — a path no engine follows. +fn macro_rooted(tokens: &[Token], i: usize) -> bool { + let symbol = |at: usize, text: &str| { + tokens.get(at).is_some_and(|t| t.kind == TokenKind::Symbol && t.text == text) + }; + let mut at = i; + loop { + if at < 2 || !symbol(at - 1, ".") { + return false; + } + let mut head = at - 2; + // Skip the selects of the segment before the dot: `u_a[0][1]`. + while symbol(head, "]") { + let mut depth = 0usize; + loop { + if symbol(head, "]") { + depth += 1; + } else if symbol(head, "[") { + depth -= 1; + if depth == 0 { + break; + } + } + let Some(before) = head.checked_sub(1) else { return false }; + head = before; + } + let Some(before) = head.checked_sub(1) else { return false }; + head = before; + } + match tokens.get(head) { + Some(token) if token.is_macro() => return true, + Some(token) if token.kind == TokenKind::Ident => at = head, + _ => return false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(src: &str, name: &str) -> Vec<(u32, &'static str)> { + spellings(src, name) + } + + fn lines_of(src: &str, name: &str) -> Vec<(u32, &'static str)> { + let lines = LineIndex::new(src); + spellings(src, name).into_iter().map(|(at, kind)| (lines.line_col(at).0, kind)).collect() + } + + #[test] + fn strings_comments_macro_text_and_macro_paths_are_found() { + let src = "module m;\n\ + // state_q holds the state\n\ + logic state_q;\n\ + initial $display(\"%m.state_q\");\n\ + `ASSERT(A, state_q == 0)\n\ + `define PROBE(x) x.state_q\n\ + assign o = `HIER.u_fsm[0].state_q;\n\ + assign p = `SPI(1).u.state_q;\n\ + assign q = u_fsm.state_q;\n\ + endmodule /* state_q */\n"; + assert_eq!( + lines_of(src, "state_q"), + [ + (2, "comment"), + (4, "string"), + (5, "macro"), + (6, "define"), + (7, "path"), + (8, "path"), + (10, "comment"), + ] + ); + } + + #[test] + fn a_word_inside_another_and_a_formal_argument_are_not_mentions() { + assert!(kinds("// state_qq and xstate_q\n", "state_q").is_empty()); + assert!(kinds("`define F(state_q) state_q + 1\n", "state_q").is_empty()); + assert!(kinds("`define G(a) a\n", "a").is_empty()); + assert!(kinds("`state_q\n", "state_q").is_empty(), "a macro's own name"); + assert_eq!(kinds("`ifdef state_q\n`endif\n", "state_q"), []); + } + + #[test] + fn a_file_that_does_not_lex_lists_every_spelling() { + assert_eq!(kinds("x = \"state_q\n state_q", "state_q").len(), 2); + } + + #[test] + fn ranking_prefers_touched_files_then_the_unit_then_nearness() { + assert_eq!(rank(true, None, ""), 2); + assert_eq!(rank(false, Some("main_sm"), "`HIER.u_main_sm.state_q"), 1); + assert_eq!(rank(false, Some("main_sm"), "`HIER.u_ack_sm.state_q"), 0); + let (a, b) = (Path::new("/hw/ip/es/rtl/a.sv"), Path::new("/hw/ip/es/dv/b.sv")); + assert_eq!(shared_components(a, b), 4); + } +} diff --git a/crates/lucisv_mcp/src/tools/mod.rs b/crates/lucisv_mcp/src/tools/mod.rs index b0229c3..247fe67 100644 --- a/crates/lucisv_mcp/src/tools/mod.rs +++ b/crates/lucisv_mcp/src/tools/mod.rs @@ -10,7 +10,9 @@ mod format; mod hierarchy; mod interface; mod item; +mod mentions; mod nav; +mod place; mod read; mod read_item; mod refactor; @@ -133,8 +135,9 @@ fn describe(tool: &Tool, effect: Effect) -> Value { "title": tool.title, "description": tool.description, "inputSchema": schema(tool.params), + // The display name is `title` above; `annotations.title` would + // repeat it in a catalogue every session reads. "annotations": { - "title": tool.title, "readOnlyHint": read_only, "destructiveHint": false, "idempotentHint": idempotent, diff --git a/crates/lucisv_mcp/src/tools/nav.rs b/crates/lucisv_mcp/src/tools/nav.rs index d13419b..3d65e35 100644 --- a/crates/lucisv_mcp/src/tools/nav.rs +++ b/crates/lucisv_mcp/src/tools/nav.rs @@ -15,9 +15,11 @@ use std::path::{Path, PathBuf}; use serde_json::{json, Value}; +use vlog_parser::span::TextRange; use vlog_parser::token::{Token, TokenKind}; use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex}; +use super::mentions::{self, Focus, Mentions}; use super::select::{macro_name, target, Target}; use super::source::{self, checked_site, Site, Texts, WholeSet}; use super::{Answer, Args, Param, Tool, Ty}; @@ -25,41 +27,28 @@ use crate::project::{Analysis, Project}; use crate::render::{self, DEFAULT_LIMIT}; /// The selector's arguments, shared by both tools. -const FILE: Param = Param { - name: "file", - ty: Ty::Str, - required: false, - description: "The file holding the position, relative to a root or absolute inside one.", -}; -const LINE: Param = Param { - name: "line", - ty: Ty::Int { min: 1 }, - required: false, - description: "1-based line in `file`; give `col` too, or the `name` written on that line.", -}; -const COL: Param = Param { - name: "col", - ty: Ty::Int { min: 1 }, - required: false, - description: "1-based column in bytes on `line`.", -}; +const FILE: Param = Param { name: "file", ty: Ty::Str, required: false, description: "The file." }; +const LINE: Param = + Param { name: "line", ty: Ty::Int { min: 1 }, required: false, description: "Line." }; +const COL: Param = + Param { name: "col", ty: Ty::Int { min: 1 }, required: false, description: "Byte column." }; const NAME: Param = Param { name: "name", ty: Ty::Str, required: false, - description: "The name: alone, looked up across the project (`` `NAME`` for a macro); with `file`, its first occurrence there; with `file` and `line`, its occurrence on that line.", + description: "Name; alone, looked up project-wide (`` `NAME`` for a macro).", }; const UNIT: Param = Param { name: "unit", ty: Ty::Str, required: false, - description: "With a bare `name`: the module, interface, package or class declaring it.", + description: "Unit declaring a bare `name`.", }; pub const DEFINITION: Tool = Tool { name: "definition", title: "Go to definition", - description: "Where a name is declared: every declaration site as file:line:col, its kind and the declaration's own source line (a name declared in several places lists them all, never a guess). Select by position (`file`, `line`, `col`), by `file`+`line`+`name`, or by `name` (and `unit`) across the project; also answers a macro use and an `include` line. Prefer it over grepping for the declaration.", + description: "Where a name (or macro) is declared: file:line:col, kind and line of each declaration. Select by position, `file`+`name`, or `name` (+`unit`).", params: &[FILE, LINE, COL, NAME, UNIT], rewalk: false, handler: definition, @@ -68,7 +57,7 @@ pub const DEFINITION: Tool = Tool { pub const REFERENCES: Tool = Tool { name: "references", title: "Find references", - description: "Every use of one declaration across the project, grouped by file as line:col and the line's text — the same occurrences a rename would edit. Select as for `definition`; a bare `name` must name one declaration. Refuses a name lucisv cannot resolve to one declaration, with the reason.", + description: "Uses of one declaration (a net, port, parameter, member…), then its unresolved mentions in strings, comments, macro text. Select as `definition`. For 'who instantiates module X' use `hierarchy` with direction up.", params: &[ FILE, LINE, @@ -79,19 +68,19 @@ pub const REFERENCES: Tool = Tool { name: "include_declaration", ty: Ty::Bool, required: false, - description: "List the declaration itself too (default true).", + description: "Include the declaration (default true).", }, Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Most hits to return (default 200).", + description: "Most hits (default 200).", }, Param { name: "offset", ty: Ty::Int { min: 0 }, required: false, - description: "Hits to skip, for paging past `… and N more` (default 0).", + description: "Hits to skip.", }, ], rewalk: true, @@ -294,6 +283,7 @@ fn references(project: &mut Project, args: &Args) -> Result { let found = vlog_refactor::find_references(&set.files, &path, offset, include) .map_err(engine_refusal)?; let partial = set.warning(project); + let mentions = unresolved(project, &set, &analysis, (&path, offset), &found, args); let mut texts = Texts::default(); for (held, text) in set.files { texts.hold(held, text); @@ -306,6 +296,11 @@ fn references(project: &mut Project, args: &Args) -> Result { }) .collect(); let mut answer = render_hits(&hits, args); + if !mentions.is_empty() { + answer.text.push_str(MENTIONS_LABEL); + answer.text.push_str(&mentions.lines(" ")); + } + answer.structured["unresolved_mentions"] = mentions.json(); // A file the index skipped was not searched: the census is partial. if let Some(partial) = partial { answer.text.push_str(&format!("warning: {partial}\n")); @@ -314,6 +309,38 @@ fn references(project: &mut Project, args: &Args) -> Result { Ok(answer) } +/// The section `references` ends with when the name is also spelled where +/// no engine looks. +const MENTIONS_LABEL: &str = + "unresolved mentions (strings, comments, macro text — not resolved by lucisv):\n"; + +/// The declaration's unresolved mentions across the set, the engine's hits +/// accounted for — on the first page only; later pages repeat nothing. +fn unresolved( + project: &Project, + set: &WholeSet, + analysis: &Analysis, + (path, offset): (&Path, u32), + found: &[(PathBuf, TextRange)], + args: &Args, +) -> Mentions { + let name = vlog_refactor::rename_name_at(&analysis.semantics, offset); + let (Some(name), 0) = (name, args.count("offset", 0)) else { + return Mentions::default(); + }; + let mut accounted: Vec<(PathBuf, Vec)> = Vec::new(); + for (file, span) in found { + match accounted.iter_mut().find(|(held, _)| held == file) { + Some((_, spans)) => spans.push(*span), + None => accounted.push((file.clone(), vec![*span])), + } + } + let unit = vlog_refactor::enclosing_module(&analysis.text, offset); + let focus = Focus { name: &name, home: path, unit: unit.as_deref(), accounted: &accounted }; + let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str())); + mentions::find(project, files, &focus) +} + /// The one declaration a bare `name` selects for `references` (and `rename`). pub(super) fn declaration_position( project: &mut Project, diff --git a/crates/lucisv_mcp/src/tools/place.rs b/crates/lucisv_mcp/src/tools/place.rs new file mode 100644 index 0000000..8855494 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/place.rs @@ -0,0 +1,448 @@ +//! `add_port`'s `after`: the new port placed right after a named one, in the +//! layout of the line it follows, and each named connection placed right +//! after the instance's `.after(…)`. +//! +//! The engine (`vlog_refactor::add_port`) only appends. So it runs first, +//! unchanged, and its verified edit is the reference: this module moves the +//! header's new element, and each instance's new connection, to the slot +//! after the anchor's separator ([`slot`]) — and then checks that the +//! result is the engine's result with elements moved and nothing else +//! ([`verify`]). +//! +//! What it refuses (the engine's refusals come first): a non-ANSI or empty +//! port list; a port list, or the connection list of an instance it would +//! place into, holding an element the parser could not read (it cannot see +//! what that element inherits or binds — QA finding 5); an `after` that is +//! not a port; a next port that would inherit from the new one; an anchor +//! inside an `` `ifdef`` arm; and a positional instantiation unless `after` +//! is the last port. An instance whose connection cannot be placed (no +//! `.after(…)`, an `` `ifdef`` around it) keeps the engine's appended +//! connection and is said under `warnings`. + +mod slot; +mod verify; + +use std::path::{Path, PathBuf}; + +use vlog_parser::ast::{AnsiPort, Connections, Instance, Item, ItemKind, ListDirective}; +use vlog_parser::ast::{ListElem, Module, PortList, RawText}; +use vlog_parser::span::TextRange; +use vlog_parser::token::{Token, TokenKind}; +use vlog_parser::{parse_source_tolerant, tokenize}; +use vlog_refactor::{RefactorEdit, TextEdit}; + +use super::read_item::child_items; +use crate::render::one_line; +use slot::{aligned_connection, aligned_port, slot}; + +/// What is being placed: the module, where it is written, the anchor port, +/// the new port's name and declaration, and how a file is named in a +/// sentence (root-relative, as every answer names it). +pub struct Spec<'a> { + pub module: &'a str, + pub file: &'a Path, + pub after: &'a str, + pub port: &'a str, + pub declaration: &'a str, + pub show: &'a dyn Fn(&Path) -> String, +} + +/// The engine's appending `edit`, re-placed after `spec.after` and +/// verified against it; the warnings name each instance left appended. +pub fn after( + files: &[(PathBuf, String)], + edit: &RefactorEdit, + spec: &Spec, +) -> Result { + let home = text_of(files, spec.file)?; + let (tree, _) = parse_source_tolerant(home); + let module = find_module(&tree.items, spec.module) + .ok_or_else(|| format!("lucisv can no longer find `{}`.", spec.module))?; + let (header, region, last_port) = header(home, module, spec)?; + let mut placed = RefactorEdit { warnings: edit.warnings.clone(), ..RefactorEdit::default() }; + for (path, edits) in &edit.edits { + let mut kept: Vec = edits.clone(); + if path == spec.file { + kept.retain(|edit| !region.contains(edit.range.start)); + kept.extend(header.iter().cloned()); + } + let text = text_of(files, path)?; + let tokens = lexed(text, spec, path)?; + let (tree, _) = parse_source_tolerant(text); + let mut instances = Vec::new(); + collect_instances(&tree.items, spec.module, &mut instances); + for instance in instances { + let inside = |edit: &TextEdit| { + instance.span.start <= edit.range.start && edit.range.start <= instance.span.end + }; + let appended: Vec = kept.iter().filter(|e| inside(e)).cloned().collect(); + if appended.is_empty() || positional(instance, last_port, spec, path)? { + continue; + } + let at = || format!("`{}` in {}", instance.name, (spec.show)(path)); + if let Some(raw) = unreadable_connection(instance) { + return Err(unreadable(&at(), raw)); + } + match connection(text, &tokens, instance, &appended, spec) { + Ok(edits) => { + kept.retain(|edit| !inside(edit)); + kept.extend(edits); + } + Err(why) => placed.warnings.push(format!( + "{}: the connection of `{}` was appended at the end ({why}).", + at(), + spec.port + )), + } + } + kept.sort_by_key(|edit| (edit.range.start, edit.range.end)); + placed.edits.push((path.clone(), kept)); + } + verify::verify(files, edit, &placed, spec)?; + Ok(placed) +} + +fn text_of<'f>(files: &'f [(PathBuf, String)], path: &Path) -> Result<&'f str, String> { + files + .iter() + .find(|(held, _)| held == path) + .map(|(_, text)| text.as_str()) + .ok_or_else(|| format!("the edit names `{}`, which was not read", path.display())) +} + +fn lexed(text: &str, spec: &Spec, path: &Path) -> Result, String> { + tokenize(text).map_err(|_| format!("{} does not lex.", (spec.show)(path))) +} + +/// The module called `name`, looked for in modules and packages. +fn find_module<'t>(items: &'t [Item], name: &str) -> Option<&'t Module> { + items.iter().find_map(|item| match &item.kind { + ItemKind::Module(module) if module.name == name => Some(module), + ItemKind::Module(module) => find_module(&module.items, name), + ItemKind::Package { items, .. } => find_module(items, name), + _ => None, + }) +} + +/// Every instance of `module` in `items`, generate blocks and `bind`s +/// included. +fn collect_instances<'t>(items: &'t [Item], module: &str, out: &mut Vec<&'t Instance>) { + for item in items { + match &item.kind { + ItemKind::Instantiation(inst) if inst.module == module => out.extend(&inst.instances), + ItemKind::Bind(bind) if bind.inst.module == module => out.extend(&bind.inst.instances), + kind => child_items(kind).into_iter().for_each(|c| collect_instances(c, module, out)), + } + } +} + +/// Whether `next`, written right after the new port (directed `new_dir`, +/// placed after an anchor directed `anchor_dir`), would take something +/// from it that it took from the anchor before: with neither direction nor +/// type it inherits both; with a type but no direction, the direction — +/// harmless only when the two directions are the same. A modport port +/// (`bus_if.mp bus`) has no direction to inherit (QA finding 3); an +/// unreadable element cannot be judged. +fn inherits(next: &ListElem, new_dir: Option<&str>, anchor_dir: Option<&str>) -> bool { + let ListElem::Ok(next) = next else { return true }; + if next.dir.is_some() { + return false; + } + if next.ty.is_implicit() && next.net.is_none() { + return true; + } + let modport = next.ty.name.contains('.'); + !modport && (new_dir.is_none() || new_dir != anchor_dir) +} + +/// The header edit placing the new port after the anchor, the port list's +/// bytes (where the engine's appended element lands), and whether the +/// anchor is the last port. +fn header( + text: &str, + module: &Module, + spec: &Spec, +) -> Result<(Vec, TextRange, bool), String> { + let PortList::Ansi(ports) = &module.ports else { + return Err(format!( + "`after` places a port in an ANSI port list, and `{}` has none; omit `after`.", + spec.module + )); + }; + // `index` counts every element, readable or not, as + // `ListDirective::before` does (QA finding 5b). + let found = ports.iter().enumerate().find_map(|(index, element)| { + element.ok().filter(|port| port.name == spec.after).map(|port| (index, port)) + }); + let Some((index, anchor)) = found else { + return Err(no_such_port(ports, spec)); + }; + if !balanced_before(&module.port_directives, index) { + return Err(format!( + "`{}` sits inside an `ifdef arm of the port list, so a port placed after it would exist in one configuration only; place it by hand.", + spec.after + )); + } + if let Some(raw) = ports.iter().find_map(error_of) { + return Err(unreadable(&format!("`{}`'s port list", spec.module), raw)); + } + let (new_dir, anchor_dir) = (new_direction(spec.declaration), anchor.dir.as_deref()); + let inheriting = |next: &&ListElem| inherits(next, new_dir.as_deref(), anchor_dir); + if let Some(next) = ports.get(index + 1).filter(inheriting) { + let name = next.ok().map_or("", |port| port.name.as_str()); + return Err(format!( + "`{name}` takes its direction (or type) from the port before it, so a port placed after `{}` would change it; name another `after`.", + spec.after + )); + } + let tokens = lexed(text, spec, spec.file)?; + let at = slot(text, &tokens, anchor.span) + .map_err(|why| format!("after `{}`, {why}.", spec.after))?; + let element = match &at.line { + Some(line) => aligned_port(text, line, anchor, spec.declaration), + None => one_line(spec.declaration), + }; + let region = list_region(&tokens, ports)?; + Ok((at.edits(&element), region, index + 1 == ports.len())) +} + +/// The refusal for an `after` no readable port is named. +fn no_such_port(ports: &[ListElem], spec: &Spec) -> String { + let names: Vec<&str> = ports.iter().filter_map(ListElem::ok).map(|p| p.name.as_str()).collect(); + let more = if names.len() > 12 { ", …" } else { "" }; + let shown = names.iter().take(12).copied().collect::>().join(", "); + format!("`{}` has no port `{}` (its ports: {shown}{more}).", spec.module, spec.after) +} + +/// The direction keyword a declaration starts with. +fn new_direction(declaration: &str) -> Option { + let tokens = tokenize(declaration).ok()?; + tokens.first().filter(|t| t.kind == TokenKind::Keyword).map(|t| t.text.clone()) +} + +/// The refusal for an element the parser could not read. +fn unreadable(list: &str, raw: &RawText) -> String { + format!( + "{list} holds `{}`, which lucisv cannot read, so it cannot tell what a port placed beside it would change; nothing written — omit `after` or place the port by hand.", + crate::tools::source::capped(&raw.text, 80) + ) +} + +/// The first element of an instance's connection list the parser could not +/// read. +fn unreadable_connection(instance: &Instance) -> Option<&RawText> { + match &instance.conns { + Connections::Named(conns) => conns.iter().find_map(error_of), + Connections::Ordered(conns) => conns.iter().find_map(error_of), + } +} + +fn error_of(element: &ListElem) -> Option<&RawText> { + match element { + ListElem::Error(raw) => Some(raw), + ListElem::Ok(_) => None, + } +} + +/// Whether the `` `ifdef``s written before element `index + 1` of a list +/// are all closed again — an element inserted there is unconditional. +/// `index` counts every element of the list, as `ListDirective::before` +/// does. +fn balanced_before(directives: &[ListDirective], index: usize) -> bool { + let mut depth = 0i32; + for directive in directives.iter().filter(|d| d.before <= index) { + match directive.raw.text.split_whitespace().next().unwrap_or_default() { + "`ifdef" | "`ifndef" => depth += 1, + "`endif" => depth -= 1, + _ => {} + } + } + depth == 0 +} + +/// The bytes from the first port to the port list's `)`. +fn list_region(tokens: &[Token], ports: &[ListElem]) -> Result { + let span = |element: &ListElem| match element { + ListElem::Ok(port) => port.span, + ListElem::Error(raw) => raw.span, + }; + let (Some(first), Some(last)) = (ports.first().map(span), ports.last().map(span)) else { + return Err("lucisv cannot find this module's port list.".to_string()); + }; + let close = tokens + .iter() + .find(|t| t.span.start >= last.end && t.kind == TokenKind::Symbol && t.text == ")") + .ok_or_else(|| "lucisv cannot find where this module's port list ends.".to_string())?; + Ok(TextRange::new(first.start, close.span.end)) +} + +/// Whether an instance connects by position — its appended connection +/// stays where the engine put it, which is right only when the new port is +/// last; anywhere else it is refused. +fn positional( + instance: &Instance, + last_port: bool, + spec: &Spec, + path: &Path, +) -> Result { + match &instance.conns { + Connections::Ordered(_) if last_port => Ok(true), + Connections::Ordered(_) => Err(format!( + "`{}` in {} connects `{}` by position, so a port placed after `{}` would shift every later connection; give it named connections first, or omit `after`.", + instance.name, + (spec.show)(path), + spec.module, + spec.after + )), + Connections::Named(_) => Ok(false), + } +} + +/// The edit placing one instance's new connection after `.after(…)`, its +/// expression taken from the engine's appended one. +fn connection( + text: &str, + tokens: &[Token], + instance: &Instance, + appended: &[TextEdit], + spec: &Spec, +) -> Result, String> { + let Connections::Named(conns) = &instance.conns else { + return Err("a positional list".to_string()); + }; + let found = conns.iter().enumerate().find_map(|(index, conn)| { + conn.ok().filter(|conn| conn.name == spec.after).map(|conn| (index, conn)) + }); + let Some((index, anchor)) = found else { + return Err(format!("it does not connect `.{}`", spec.after)); + }; + if !balanced_before(&instance.conn_directives, index) { + return Err(format!("`.{}` sits inside an `ifdef arm", spec.after)); + } + let written: String = appended.iter().map(|edit| edit.new_text.as_str()).collect(); + let expr = appended_expr(&written, spec.port) + .ok_or_else(|| "lucisv could not read the appended connection".to_string())?; + let at = slot(text, tokens, anchor.span)?; + let element = match &at.line { + Some(line) => aligned_connection(text, line, anchor, spec.port, &expr), + None => format!(".{}({expr})", spec.port), + }; + Ok(at.edits(&element)) +} + +/// The expression inside the engine's appended `.port(expr)`. +fn appended_expr(written: &str, port: &str) -> Option { + let open = written.find(&format!(".{port}("))? + port.len() + 2; + let mut depth = 1usize; + for (offset, c) in written[open..].char_indices() { + match c { + '(' => depth += 1, + ')' if depth == 1 => return Some(written[open..open + offset].trim().to_string()), + ')' => depth -= 1, + _ => {} + } + } + None +} + +/// The port a declaration's tokens name: the last identifier outside +/// brackets before any `=` default. +pub fn port_name(tokens: &[Token]) -> Option<&Token> { + let mut depth = 0usize; + let mut name = None; + for token in tokens { + match (token.kind, token.text.as_str()) { + (TokenKind::Symbol, "[" | "(" | "{") => depth += 1, + (TokenKind::Symbol, "]" | ")" | "}") => depth = depth.saturating_sub(1), + (TokenKind::Symbol, "=") if depth == 0 => break, + (TokenKind::Ident, _) if depth == 0 && !token.is_macro() => name = Some(token), + _ => {} + } + } + name +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::apply::Plan; + + const TOP: &str = "module top(input logic a, output logic y);\n m u_m (\n .a (a), // in\n .y (y)\n );\nendmodule\n"; + + fn design(header: &str) -> Vec<(PathBuf, String)> { + let m = format!("module m (\n{header}\n);\nendmodule\n"); + vec![(PathBuf::from("/d/m.sv"), m), (PathBuf::from("/d/top.sv"), TOP.to_string())] + } + + fn show(path: &Path) -> String { + path.file_name().map_or(String::new(), |name| name.to_string_lossy().into_owned()) + } + + fn spec<'a>(after: &'a str) -> Spec<'a> { + let (file, declaration) = (Path::new("/d/m.sv"), "input logic en"); + Spec { module: "m", file, after, port: "en", declaration, show: &show } + } + + fn engine(files: &[(PathBuf, String)]) -> RefactorEdit { + vlog_refactor::add_port(files, vlog_refactor::ModuleRef::Name("m"), "input logic en") + .unwrap() + } + + fn texts(files: &[(PathBuf, String)], edit: &RefactorEdit) -> Vec { + let plan = Plan::from_refactor(edit.clone(), files).unwrap(); + plan.changes.into_iter().map(|change| change.after).collect() + } + + fn refusal(files: &[(PathBuf, String)], after_port: &str) -> String { + after(files, &engine(files), &spec(after_port)).err().unwrap_or_default() + } + + #[test] + fn a_placed_port_and_connection_follow_their_anchors() { + let files = design(" input logic a, // first\n output logic y"); + let placed = after(&files, &engine(&files), &spec("a")).unwrap(); + let [m, top] = texts(&files, &placed).try_into().unwrap(); + let header = " input logic a, // first\n input logic en,\n output logic y\n"; + assert_eq!(m, format!("module m (\n{header});\nendmodule\n")); + // `top` has no `en`: the engine's placeholder, placed. + let placed = " .a (a), // in\n .en (/* TODO: connect */),\n .y (y)\n"; + assert!(top.contains(placed), "{top}"); + } + + #[test] + fn what_a_placement_cannot_see_or_would_change_is_refused() { + let inherit = refusal(&design(" input logic [7:0] a, b,\n output logic y"), "a"); + assert!(inherit.contains("`b` takes its direction"), "{inherit}"); + let typed = refusal(&design(" output logic a, logic [3:0] b,\n output logic y"), "a"); + assert!(typed.contains("`b` takes its direction"), "{typed}"); + let arm = refusal(&design("`ifdef X\n input logic a,\n`endif\n output logic y"), "a"); + assert!(arm.contains("inside an `ifdef arm"), "{arm}"); + let hidden = + refusal(&design(" input logic [7:0] a,\n (* keep *) b,\n output logic y"), "a"); + assert!(hidden.contains("`m`'s port list holds `(* keep *) b`"), "{hidden}"); + let mut files = design(" input logic a,\n output logic y"); + files[1].1 = + "module top(input logic a, en, output logic y);\n m u_m (a, y);\nendmodule\n".into(); + let edit = engine(&files); + let refused = after(&files, &edit, &spec("a")).unwrap_err(); + assert!(refused.contains("`u_m` in top.sv connects `m` by position"), "{refused}"); + assert!(after(&files, &edit, &spec("y")).is_ok(), "last is fine"); + } + + #[test] + fn a_modport_or_a_same_directed_typed_port_after_the_anchor_is_placed() { + let files = design(" input logic a,\n bus_if.mp bus,\n output logic y"); + assert!(after(&files, &engine(&files), &spec("a")).is_ok()); + let files = design(" input logic a, logic [3:0] b,\n output logic y"); + assert!(after(&files, &engine(&files), &spec("a")).is_ok()); + } + + #[test] + fn the_engines_appended_expression_is_read_back() { + assert_eq!(appended_expr(",\n .dbg_i(dbg_i)", "dbg_i").as_deref(), Some("dbg_i")); + let todo = appended_expr(", .d(/* TODO: connect */)", "d"); + assert_eq!(todo.as_deref(), Some("/* TODO: connect */")); + assert_eq!(appended_expr(".d(f(a))", "d").as_deref(), Some("f(a)")); + assert_eq!(appended_expr(".e(x)", "d"), None); + } +} diff --git a/crates/lucisv_mcp/src/tools/place/slot.rs b/crates/lucisv_mcp/src/tools/place/slot.rs new file mode 100644 index 0000000..2c573bd --- /dev/null +++ b/crates/lucisv_mcp/src/tools/place/slot.rs @@ -0,0 +1,306 @@ +//! Where a new list element goes after its anchor, and how it is written. +//! +//! The element always goes **after the separator that follows the anchor** +//! — past the anchor's `,` (and any comment on that comma's line), or, for +//! a last anchor, after a `,` added at the anchor's end and past the +//! comments on its line — never at the anchor's end, where it would take +//! over a comment written between the anchor and its comma (QA finding 1). +//! A new line copies the anchor's indentation and line ending, and, when +//! the anchor stands alone on its line, its column layout. + +use vlog_parser::ast::{AnsiPort, Connection}; +use vlog_parser::span::TextRange; +use vlog_parser::token::{Token, TokenKind}; +use vlog_parser::tokenize; +use vlog_refactor::TextEdit; + +use crate::render::one_line; + +/// The line an anchor starts on: where it starts, its indentation, and +/// whether the anchor is the first thing on it. +pub struct AnchorLine { + start: usize, + indent: String, + alone: bool, +} + +/// Where the new element is written: a `,` at `comma_at` when the anchor +/// was last, then `prefix element suffix` at `at`. `line` is the anchor's +/// line when the element gets a line of its own in the anchor's layout. +pub struct Slot { + comma_at: Option, + at: u32, + prefix: String, + suffix: &'static str, + pub line: Option, +} + +impl Slot { + /// The insertions writing `element` here. + pub fn edits(&self, element: &str) -> Vec { + let at = |offset: u32| TextRange::new(offset, offset); + let mut edits: Vec = self + .comma_at + .map(|comma| TextEdit { range: at(comma), new_text: ",".to_string() }) + .into_iter() + .collect(); + let new_text = format!("{}{element}{}", self.prefix, self.suffix); + edits.push(TextEdit { range: at(self.at), new_text }); + edits + } +} + +/// The slot after the element spanning `anchor`, read off the file's +/// tokens: the anchor must be followed by its list's `,` or `)`. +pub fn slot(text: &str, tokens: &[Token], anchor: TextRange) -> Result { + let index = tokens.iter().position(|t| t.span.start >= anchor.end); + let next = index.and_then(|i| tokens.get(i)).filter(|t| t.kind == TokenKind::Symbol); + let line = anchor_line(text, anchor.start as usize); + match next.map(|t| t.text.as_str()) { + Some(",") => { + let comma = next.map_or(anchor.end, |t| t.span.end); + let following = index.and_then(|i| tokens.get(i + 1)); + let Some(following) = following.filter(|t| starts_line(text, t.span.start as usize)) + else { + // The next element shares the comma's line: `a, en, b`. + let suffix = ","; + return Ok(Slot { + comma_at: None, + at: comma, + prefix: " ".into(), + suffix, + line: None, + }); + }; + let (at, newline) = line_end(text, comma as usize, tokens); + let indent = match line.alone { + true => line.indent.clone(), + false => indentation(text, following.span.start as usize), + }; + let prefix = format!("{newline}{indent}"); + let line = line.alone.then_some(line); + Ok(Slot { comma_at: None, at, prefix, suffix: ",", line }) + } + Some(")") => { + let close = next.map_or(anchor.end, |t| t.span.start); + let between = &text[anchor.end as usize..close as usize]; + if starts_line(text, close as usize) { + let (at, newline) = line_end(text, anchor.end as usize, tokens); + let prefix = format!("{newline}{}", line.indent); + let line = line.alone.then_some(line); + return Ok(Slot { comma_at: Some(anchor.end), at, prefix, suffix: "", line }); + } + if between.trim().is_empty() { + let prefix = ", ".to_string(); + return Ok(Slot { comma_at: None, at: anchor.end, prefix, suffix: "", line: None }); + } + // A comment between the last anchor and `)`: it stays the anchor's. + let prefix = " ".to_string(); + Ok(Slot { comma_at: Some(anchor.end), at: close, prefix, suffix: "", line: None }) + } + _ => Err("lucisv cannot find the `,` or `)` after it".to_string()), + } +} + +fn anchor_line(text: &str, from: usize) -> AnchorLine { + let start = text[..from].rfind('\n').map_or(0, |at| at + 1); + let before = &text[start..from]; + let alone = before.chars().all(|c| c == ' ' || c == '\t'); + AnchorLine { start, indent: indentation(text, from), alone } +} + +/// The blanks a line starts with, the line holding `offset`. +fn indentation(text: &str, offset: usize) -> String { + let start = text[..offset].rfind('\n').map_or(0, |at| at + 1); + text[start..].chars().take_while(|c| *c == ' ' || *c == '\t').collect() +} + +/// Whether only blanks precede `offset` on its line. +fn starts_line(text: &str, offset: usize) -> bool { + let start = text[..offset].rfind('\n').map_or(0, |at| at + 1); + text[start..offset].chars().all(|c| c == ' ' || c == '\t') +} + +/// The end of the line `from` is on — past any comment that closes on a +/// later line — before its line ending, and that line ending. +fn line_end(text: &str, from: usize, tokens: &[Token]) -> (u32, &'static str) { + let comments: Vec = tokens + .iter() + .flat_map(|t| t.leading.iter().chain(t.trailing.as_ref())) + .map(|comment| comment.span) + .collect(); + let mut at = from; + loop { + let newline = text[at..].find('\n').map_or(text.len(), |found| at + found); + match comments.iter().find(|c| (c.start as usize) < newline && newline < c.end as usize) { + Some(comment) => at = comment.end as usize, + None => { + return match text[..newline].strip_suffix('\r') { + Some(_) => ((newline - 1) as u32, "\r\n"), + None => (newline as u32, "\n"), + } + } + } + } +} + +/// Character columns on the anchor's line. +fn column(text: &str, line: &AnchorLine, offset: usize) -> usize { + text[line.start..offset].chars().count() +} + +/// `out` (which follows the line's indentation) padded so its end reaches +/// `col`; one space when it is already past or there is no column. +fn pad_to(out: &mut String, line: &AnchorLine, col: Option) { + let width = line.indent.chars().count() + out.chars().count(); + match col { + Some(col) if width < col => out.push_str(&" ".repeat(col - width)), + _ => out.push(' '), + } +} + +/// The declaration in the anchor's layout (without the indentation): +/// direction, type and name each at the anchor's column when the text +/// before it fits, else one space apart. +pub fn aligned_port(text: &str, line: &AnchorLine, anchor: &AnsiPort, declaration: &str) -> String { + let declaration = declaration.trim(); + let (Some(parts), Some(dir)) = (split_declaration(declaration), anchor.dir.as_deref()) else { + return one_line(declaration); + }; + let dir_end = anchor.span.start as usize + dir.len(); + if text.get(anchor.span.start as usize..dir_end) != Some(dir) { + return one_line(declaration); + } + let type_at = dir_end + (text[dir_end..].len() - text[dir_end..].trim_start().len()); + let name_at = anchor.name_span.start as usize; + let type_col = (type_at < name_at).then(|| column(text, line, type_at)); + let mut out = parts.dir.to_string(); + if !parts.ty.is_empty() { + pad_to(&mut out, line, type_col); + out.push_str(&one_line(parts.ty)); + } + pad_to(&mut out, line, Some(column(text, line, name_at))); + out.push_str(&one_line(parts.rest)); + out +} + +/// The connection `.port(expr)` in the anchor's layout: the `(` and the `)` +/// at the anchor's columns when they fit, the anchor's blanks inside them. +pub fn aligned_connection( + text: &str, + line: &AnchorLine, + anchor: &Connection, + port: &str, + expr: &str, +) -> String { + let plain = format!(".{port}({expr})"); + let Some(value) = anchor.expr.as_ref().filter(|_| anchor.after_dot.is_empty()) else { + return plain; + }; + let name_end = anchor.name_span.end as usize; + let open = name_end + (text[name_end..].len() - text[name_end..].trim_start().len()); + let close = (anchor.span.end as usize).saturating_sub(1); + let (start, end) = (value.span.start as usize, value.span.end as usize); + let blank = |from: usize, to: usize| { + text.get(from..to).filter(|gap| gap.chars().all(|c| c == ' ' || c == '\t')) + }; + let (Some(before_open), Some(inside), Some(_)) = + (blank(name_end, open), blank(open + 1, start), blank(end, close)) + else { + return plain; + }; + if text.get(open..open + 1) != Some("(") || text.get(close..close + 1) != Some(")") { + return plain; + } + let mut out = format!(".{port}"); + // An anchor that glues its `(` to the name is followed; else aligned. + if !before_open.is_empty() { + pad_to(&mut out, line, Some(column(text, line, open))); + } + out.push('('); + out.push_str(inside); + out.push_str(expr); + let width = line.indent.chars().count() + out.chars().count(); + let close_col = column(text, line, close); + match width < close_col { + true => out.push_str(&" ".repeat(close_col - width)), + false => out.push_str(inside), + } + out.push(')'); + out +} + +/// A declaration split where a layout puts its columns: the direction, the +/// type between it and the name, and the name with what follows it. +struct Parts<'a> { + dir: &'a str, + ty: &'a str, + rest: &'a str, +} + +fn split_declaration(declaration: &str) -> Option> { + let tokens = tokenize(declaration).ok()?; + let dir = tokens.first().filter(|t| t.kind == TokenKind::Keyword)?; + let name = super::port_name(&tokens)?; + let (dir_end, name_start) = (dir.span.end as usize, name.span.start as usize); + Some(Parts { + dir: &declaration[..dir_end], + ty: declaration[dir_end..name_start].trim(), + rest: declaration[name_start..].trim(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `text` with `element` written in the slot after `anchor`. + fn placed(text: &str, anchor: &str, element: &str) -> String { + let tokens = tokenize(text).unwrap(); + let start = text.find(anchor).unwrap() as u32; + let span = TextRange::new(start, start + anchor.len() as u32); + let slot = slot(text, &tokens, span).unwrap(); + let mut out = text.to_string(); + for edit in slot.edits(element).iter().rev() { + out.insert_str(edit.range.start as usize, &edit.new_text); + } + out + } + + #[test] + fn the_element_goes_after_the_separator_and_its_comments() { + let e = "input e"; + assert_eq!( + placed("(\n input a,\n input b\n);", "input a", e), + "(\n input a,\n input e,\n input b\n);" + ); + assert_eq!( + placed("(\n input a /* about a */,\n input b\n);", "input a", e), + "(\n input a /* about a */,\n input e,\n input b\n);" + ); + assert_eq!( + placed("(\n input b // about b\n , input c);", "input b", e), + "(\n input b // about b\n , input e, input c);" + ); + assert_eq!(placed("(input a, input b);", "input a", e), "(input a, input e, input b);"); + assert_eq!( + placed("(\n input y /* last */\n);", "input y", e), + "(\n input y, /* last */\n input e\n);" + ); + assert_eq!(placed("(input y /* c */);", "input y", e), "(input y, /* c */ input e);"); + assert_eq!(placed("(input y);", "input y", e), "(input y, input e);"); + assert_eq!( + placed("(\r\n input a, /* x\r\n y */\r\n input b\r\n);", "input a", e), + "(\r\n input a, /* x\r\n y */\r\n input e,\r\n input b\r\n);" + ); + } + + #[test] + fn a_declaration_splits_at_its_name() { + let parts = split_declaration("input logic [W-1:0] cfg [2] = 0").unwrap(); + assert_eq!((parts.dir, parts.ty, parts.rest), ("input", "logic [W-1:0]", "cfg [2] = 0")); + let parts = split_declaration("output pkg::t_e st").unwrap(); + assert_eq!((parts.ty, parts.rest), ("pkg::t_e", "st")); + assert_eq!(split_declaration("input dbg_i").unwrap().ty, ""); + } +} diff --git a/crates/lucisv_mcp/src/tools/place/verify.rs b/crates/lucisv_mcp/src/tools/place/verify.rs new file mode 100644 index 0000000..59e6fd3 --- /dev/null +++ b/crates/lucisv_mcp/src/tools/place/verify.rs @@ -0,0 +1,310 @@ +//! The check a placement must pass before anything is written: the placed +//! edit is the engine's verified edit with elements **moved and nothing +//! else**. Per file, against the engine's result: +//! +//! 1. the same tokens (kind and text), as a multiset; +//! 2. every comment attached to the same identifier — the one before it for +//! a comment on its token's line, the one after it for a comment on +//! lines of its own — so a comment cannot slide onto the new element +//! (QA finding 1); +//! 3. no more parse diagnostics; +//! 4. the module's port list, **every** element counted (an element the +//! parser could not read included, by its text): the engine's order with +//! the new port moved to right after the anchor; each port's declaration +//! the engine's, blanks collapsed (QA finding 5); and the port after the +//! new one does not inherit from it; +//! 5. every instance's connections the same: named ones as a set of +//! `.name(expr)` with blanks squeezed, positional ones in order. +//! +//! Guilty until proven innocent: each rule has an attack in this module's +//! tests. + +use std::path::PathBuf; + +use vlog_parser::ast::{Connections, Instance, Item, ListElem, PortList}; +use vlog_parser::span::TextRange; +use vlog_parser::token::TokenKind; +use vlog_parser::{parse_source_tolerant, tokenize}; +use vlog_refactor::RefactorEdit; + +use super::{collect_instances, find_module, inherits, Spec}; +use crate::apply::Plan; +use crate::render::one_line; + +/// Check `placed` against `engine` (see the module comment); the refusal +/// names the file and the rule broken. +pub fn verify( + files: &[(PathBuf, String)], + engine: &RefactorEdit, + placed: &RefactorEdit, + spec: &Spec, +) -> Result<(), String> { + let expected = Plan::from_refactor(engine.clone(), files)?; + let got = Plan::from_refactor(placed.clone(), files)?; + let refuse = |why: String| { + format!( + "placing `{}` after `{}` failed a check ({why}); nothing written.", + spec.port, spec.after + ) + }; + if expected.changes.len() != got.changes.len() { + return Err(refuse("a different set of files".into())); + } + for (want, have) in expected.changes.iter().zip(&got.changes) { + let shown = (spec.show)(&have.path); + if want.path != have.path { + return Err(refuse(format!("{shown} is not the engine's file"))); + } + let lexed = lexed(&have.after); + if lexed.is_none() || lexed != self::lexed(&want.after) { + return Err(refuse(format!("{shown} lexes to other tokens or comments"))); + } + let (want_tree, want_errors) = parse_source_tolerant(&want.after); + let (have_tree, have_errors) = parse_source_tolerant(&have.after); + if have_errors.len() > want_errors.len() { + return Err(refuse(format!("{shown} parses worse"))); + } + if have.path == spec.file { + let want = (want.after.as_str(), want_tree.items.as_slice()); + let have = (have.after.as_str(), have_tree.items.as_slice()); + ports_in_order(have, want, spec).map_err(&refuse)?; + } + let mut wanted = Vec::new(); + let mut had = Vec::new(); + collect_instances(&want_tree.items, spec.module, &mut wanted); + collect_instances(&have_tree.items, spec.module, &mut had); + let signature = |text: &str, instances: &[&Instance]| -> Vec> { + instances.iter().map(|instance| connections(text, instance)).collect() + }; + if signature(&want.after, &wanted) != signature(&have.after, &had) { + return Err(refuse(format!("{shown}'s connections differ"))); + } + } + Ok(()) +} + +/// Every token's kind and text, and every comment with the identifier it is +/// attached to, sorted: equal for two texts that hold the same tokens in +/// any order, with each comment still beside the same name. +fn lexed(text: &str) -> Option> { + let tokens = tokenize(text).ok()?; + let ident = |token: &vlog_parser::token::Token| token.kind == TokenKind::Ident; + let mut out: Vec = Vec::new(); + let mut last_ident = ""; + for (i, token) in tokens.iter().enumerate() { + out.push(format!("{:?} {}", token.kind, token.text)); + if !token.leading.is_empty() { + let next = tokens[i..].iter().find(|t| ident(t)).map_or("", |t| t.text.as_str()); + out.extend(token.leading.iter().map(|c| format!("comment before {next}: {}", c.text))); + } + if ident(token) { + last_ident = &token.text; + } + if let Some(comment) = &token.trailing { + out.push(format!("comment after {last_ident}: {}", comment.text)); + } + } + out.sort(); + Some(out) +} + +/// A port list's elements as the check compares them: each readable port +/// as `name: declaration` (blanks collapsed), each unreadable one by text. +fn port_elements(text: &str, items: &[Item], spec: &Spec) -> Option> { + let module = find_module(items, spec.module)?; + let PortList::Ansi(ports) = &module.ports else { return None }; + let written = |span: TextRange| one_line(text.get(span.as_range()).unwrap_or("")); + let elements = ports.iter().map(|element| match element { + ListElem::Ok(port) => (port.name.clone(), written(port.span)), + ListElem::Error(raw) => (String::new(), one_line(&raw.text)), + }); + Some(elements.collect()) +} + +/// The module's ports in the placed text are the engine's, each declared +/// as the engine left it, with the new one moved to right after the anchor; +/// the port after it does not inherit from it. +fn ports_in_order( + (have_text, have): (&str, &[Item]), + (want_text, want): (&str, &[Item]), + spec: &Spec, +) -> Result<(), String> { + let (Some(have_ports), Some(mut want_ports)) = + (port_elements(have_text, have, spec), port_elements(want_text, want, spec)) + else { + return Err(format!("`{}` has no ANSI port list", spec.module)); + }; + let new = want_ports.iter().position(|(name, _)| name == spec.port); + let Some(new) = new.map(|at| want_ports.remove(at)) else { + return Err("the engine's result has no new port".to_string()); + }; + let at = want_ports.iter().position(|(name, _)| name == spec.after).map_or(0, |at| at + 1); + want_ports.insert(at, new); + if have_ports != want_ports { + let names: Vec = + have_ports.iter().map(|(name, written)| format!("{name}: {written}")).collect(); + return Err(format!("the ports are {}", names.join("; "))); + } + let module = find_module(have, spec.module).ok_or("the module is gone")?; + let PortList::Ansi(ports) = &module.ports else { return Err("no port list".into()) }; + let dir = |at: usize| ports.get(at).and_then(ListElem::ok).and_then(|p| p.dir.as_deref()); + let anchor_dir = at.checked_sub(1).and_then(dir); + if ports.get(at + 1).is_some_and(|next| inherits(next, dir(at), anchor_dir)) { + return Err("the port after the new one would inherit from it".to_string()); + } + Ok(()) +} + +/// One instance's connections, blanks squeezed: sorted for a named list +/// (order does not bind) and in order for a positional one; an unreadable +/// element by its text. +fn connections(text: &str, instance: &Instance) -> Vec { + let squeeze = |span: TextRange| -> String { + text.get(span.as_range()).unwrap_or("").split_whitespace().collect() + }; + match &instance.conns { + Connections::Named(conns) => { + let mut out: Vec = conns + .iter() + .map(|conn| match conn { + ListElem::Ok(conn) => squeeze(conn.span), + ListElem::Error(raw) => squeeze(raw.span), + }) + .collect(); + out.sort(); + out + } + Connections::Ordered(conns) => conns + .iter() + .map(|conn| match conn { + ListElem::Ok(conn) => squeeze(conn.span), + ListElem::Error(raw) => squeeze(raw.span), + }) + .collect(), + } +} + +#[cfg(test)] +mod tests { + use std::path::Path; + + use vlog_refactor::TextEdit; + + use super::super::after; + use super::*; + + const TOP: &str = "module top(input logic a, output logic y);\n m u_m (\n .a (a), // in\n .y (y)\n );\nendmodule\n"; + + fn design(header: &str) -> Vec<(PathBuf, String)> { + let m = format!("module m (\n{header}\n);\nendmodule\n"); + vec![(PathBuf::from("/d/m.sv"), m), (PathBuf::from("/d/top.sv"), TOP.to_string())] + } + + fn show(path: &Path) -> String { + path.display().to_string() + } + + fn spec<'a>(after: &'a str, declaration: &'a str) -> Spec<'a> { + let file = Path::new("/d/m.sv"); + Spec { module: "m", file, after, port: "en", declaration, show: &show } + } + + fn engine(files: &[(PathBuf, String)], declaration: &str) -> RefactorEdit { + vlog_refactor::add_port(files, vlog_refactor::ModuleRef::Name("m"), declaration).unwrap() + } + + /// `edit` with the module file's edits replaced by `header`. + fn with_header(edit: &RefactorEdit, header: Vec) -> RefactorEdit { + let mut bad = edit.clone(); + bad.edits[0].1 = header; + bad + } + + fn insert(at: usize, text: &str) -> TextEdit { + TextEdit { range: TextRange::new(at as u32, at as u32), new_text: text.to_string() } + } + + /// Masked-corruption attacks: a placed edit that is not the engine's + /// with elements moved is refused, whatever it looks like. + #[test] + fn a_placement_that_is_not_a_move_is_refused() { + let files = design(" input logic a, // first\n output logic y"); + let decl = "input logic en"; + let edit = engine(&files, decl); + let good = after(&files, &edit, &spec("a", decl)).unwrap(); + assert!(verify(&files, &edit, &good, &spec("a", decl)).is_ok()); + let m = &files[0].1; + let first = m.find("// first").unwrap(); + // The anchor line's comment taken by the new line. + let stolen = with_header(&good, vec![insert(first, "\n input logic en, ")]); + assert!(verify(&files, &edit, &stolen, &spec("a", decl)).is_err()); + // A wider type on the new port. + let wide = m.find("\n output").unwrap(); + let wider = with_header(&good, vec![insert(wide, "\n input logic [1:0] en,")]); + assert!(verify(&files, &edit, &wider, &spec("a", decl)).is_err()); + // A connection to another signal. + let mut rewired = good.clone(); + let conn = rewired.edits[1].1.iter_mut().find(|e| e.new_text.contains(".en")).unwrap(); + conn.new_text = conn.new_text.replace("TODO: connect */", "*/ a"); + assert!(verify(&files, &edit, &rewired, &spec("a", decl)).is_err()); + // The engine's own append, where `after` asked for `a`. + let last = verify(&files, &edit, &edit, &spec("a", decl)).unwrap_err(); + assert!(last.contains("the ports are"), "{last}"); + } + + /// QA finding 5's pair: the type swapped between the anchor and the new + /// port — the same tokens, names in order, parse and connections. + #[test] + fn a_type_swapped_between_the_anchor_and_the_new_port_is_refused() { + let files = design(" input logic [7:0] a,\n output logic y"); + let decl = "input logic en"; + let edit = engine(&files, decl); + let m = &files[0].1; + let dims = m.find("[7:0] ").unwrap(); + let comma = m.find("a,").unwrap() + 2; + let swapped = with_header( + &edit, + vec![ + TextEdit { + range: TextRange::new(dims as u32, dims as u32 + 6), + new_text: String::new(), + }, + insert(comma, "\n input logic [7:0] en,"), + ], + ); + let said = verify(&files, &edit, &swapped, &spec("a", decl)).unwrap_err(); + assert!(said.contains("the ports are"), "{said}"); + } + + /// QA finding 1's shapes: a comment glued to the anchor's comma, and a + /// leading-comma list, each with the new element placed at the anchor's + /// end — the comment then documents the new port. + #[test] + fn a_comment_moved_onto_the_new_element_is_refused() { + for header in [ + " input logic a /* about a */,\n output logic y", + " input logic a // about a\n , output logic y", + ] { + let files = design(header); + let decl = "input logic en"; + let edit = engine(&files, decl); + let end = files[0].1.find("logic a").unwrap() + "logic a".len(); + let glued = with_header(&edit, vec![insert(end, ", input logic en")]); + let said = verify(&files, &edit, &glued, &spec("a", decl)).unwrap_err(); + assert!(said.contains("comments"), "{header}: {said}"); + // The slot after the separator keeps it. + let placed = after(&files, &edit, &spec("a", decl)).unwrap(); + assert!(verify(&files, &edit, &placed, &spec("a", decl)).is_ok(), "{header}"); + } + } + + #[test] + fn comments_pair_with_the_name_they_are_written_beside() { + let pairs = lexed("a /* x */, b // y\n// z\nc").unwrap(); + let comments: Vec<&String> = pairs.iter().filter(|p| p.starts_with("comment")).collect(); + assert_eq!( + comments, + ["comment after a: /* x */", "comment after b: // y", "comment before c: // z"] + ); + } +} diff --git a/crates/lucisv_mcp/src/tools/read.rs b/crates/lucisv_mcp/src/tools/read.rs index ce78f79..82bc636 100644 --- a/crates/lucisv_mcp/src/tools/read.rs +++ b/crates/lucisv_mcp/src/tools/read.rs @@ -15,19 +15,19 @@ const LIMIT: Param = Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Most entries to return (default 200).", + description: "Max entries (default 200).", }; const OFFSET: Param = Param { name: "offset", ty: Ty::Int { min: 0 }, required: false, - description: "Entries to skip, for paging past `… and N more` (default 0).", + description: "Entries to skip.", }; pub const PROJECT_OVERVIEW: Tool = Tool { name: "project_overview", title: "Project overview", - description: "Summarise the Verilog/SystemVerilog project under the roots: file count, units by kind, top-level modules (nothing instantiates them) and the largest files. Call it first to orient yourself instead of listing directories.", + description: "File count, units by kind, top-level modules, largest files. Call it first.", params: &[], rewalk: true, handler: project_overview, @@ -36,19 +36,19 @@ pub const PROJECT_OVERVIEW: Tool = Tool { pub const LIST_UNITS: Tool = Tool { name: "list_units", title: "List design units", - description: "List the modules, interfaces, packages, classes and programs declared in the project with their file:line, optionally filtered by kind and a name glob (`*`, `?`). Prefer it over grepping for `module` to find where a unit lives.", + description: "Modules, interfaces, packages, classes, programs with file:line, by `kind` and name `glob`.", params: &[ Param { name: "kind", ty: Ty::Enum(&["module", "interface", "package", "class", "program"]), required: false, - description: "Only units of this kind.", + description: "Only this kind.", }, Param { name: "glob", ty: Ty::Str, required: false, - description: "Only names matching this pattern; `*` is any run, `?` one character.", + description: "Name pattern with `*` and `?`.", }, LIMIT, OFFSET, @@ -60,19 +60,14 @@ pub const LIST_UNITS: Tool = Tool { pub const OUTLINE: Tool = Tool { name: "outline", title: "File outline", - description: "The declarations in one file as a tree with 1-based line ranges (units, ports, parameters, signals, functions, instances, blocks), plus its parse errors. Prefer it over reading a file to see what it contains; then use read_item for the part you need.", + description: "A file's declarations as a tree with line ranges, and its parse errors.", params: &[ - Param { - name: "file", - ty: Ty::Str, - required: true, - description: "The file, relative to a root or absolute inside one.", - }, + Param { name: "file", ty: Ty::Str, required: true, description: "The file." }, Param { name: "depth", ty: Ty::Int { min: 1 }, required: false, - description: "Levels to show; 1 is the file's units only (default: all).", + description: "Levels (1: units only; default all).", }, LIMIT, OFFSET, @@ -84,13 +79,13 @@ pub const OUTLINE: Tool = Tool { pub const SEARCH_SYMBOLS: Tool = Tool { name: "search_symbols", title: "Search symbols", - description: "Find declarations whose name contains `query` (case-insensitive) across the project: units, and the ports, parameters and package/class members other files can name. Answers file and line per hit; a module's internal signals are not included (use outline for those).", + description: "Declarations whose name contains `query` (any case): units, ports, parameters, package/class members.", params: &[ Param { name: "query", ty: Ty::Str, required: true, - description: "Substring of the name to find; empty matches everything.", + description: "Name substring; empty matches all.", }, LIMIT, OFFSET, diff --git a/crates/lucisv_mcp/src/tools/read_item.rs b/crates/lucisv_mcp/src/tools/read_item.rs index 638d8bf..ce7e148 100644 --- a/crates/lucisv_mcp/src/tools/read_item.rs +++ b/crates/lucisv_mcp/src/tools/read_item.rs @@ -20,19 +20,19 @@ use crate::render; pub const READ_ITEM: Tool = Tool { name: "read_item", title: "Read one item", - description: "The exact source text and 1-based line range of one item in a file: `name`, `kind:name` (e.g. `function:crc`), `name@LINE` when a name is declared twice, or `always@LINE` / `initial@LINE` / `final@LINE` / `assign@LINE` for the unlabelled block or assignment covering that line (`@LINE` is the last `@` followed only by digits, so `\\a@b@1` is `\\a@b` on line 1). Prefer it over reading the whole file; outline shows what there is.", + description: "One item's exact source and lines. Selector: `name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).", params: &[ Param { name: "file", ty: Ty::Str, required: true, - description: "The file, relative to a root or absolute inside one.", + description: "The file.", }, Param { name: "item", ty: Ty::Str, required: true, - description: "`name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).", + description: "The selector.", }, ], rewalk: false, diff --git a/crates/lucisv_mcp/src/tools/refactor.rs b/crates/lucisv_mcp/src/tools/refactor.rs index 8f1ce1e..b956ebf 100644 --- a/crates/lucisv_mcp/src/tools/refactor.rs +++ b/crates/lucisv_mcp/src/tools/refactor.rs @@ -7,38 +7,45 @@ use std::path::{Path, PathBuf}; use vlog_refactor::{instantiation_plan, module_definition, Home, Layout, ModuleRef}; -use super::edit::{enclosing, finish, whole_set, DRY_RUN}; +use super::edit::{enclosing, finish, finish_telling, whole_set, Told, DRY_RUN}; +use super::place; use super::{Answer, Args, Param, Tool, Ty}; use crate::project::Project; pub const ADD_PORT: Tool = Tool { name: "add_port", title: "Add a port", - description: "Add one ANSI port to a module and a connection for it to every instantiation in the project, verified before anything is written. Name the module by `module`, or by `file`+`line` inside its declaration; `declaration` is the port as written in the header (`input logic [7:0] cfg`). Refuses a port that exists, an ordered instantiation of a different length, and a list split by `ifdef`s. `dry_run` returns the diff.", + description: "Add an ANSI port to a module and connect it in every instantiation; `after` places it after a port, in its layout.", params: &[ Param { name: "module", ty: Ty::Str, required: false, - description: "The module's name (declared once in the project).", + description: "The module's name.", }, Param { name: "file", ty: Ty::Str, required: false, - description: "Instead of `module`: the file declaring it, with `line`.", + description: "Instead of `module`: its file, with `line`.", }, Param { name: "line", ty: Ty::Int { min: 1 }, required: false, - description: "1-based line inside the module's declaration in `file`.", + description: "A line inside the module.", }, Param { name: "declaration", ty: Ty::Str, required: true, - description: "One directed ANSI port declaration, e.g. `input logic [7:0] cfg`.", + description: "The port as written, e.g. `input logic [7:0] cfg`.", + }, + Param { + name: "after", + ty: Ty::Str, + required: false, + description: "Port to place it after (default last).", }, DRY_RUN, ], @@ -49,37 +56,37 @@ pub const ADD_PORT: Tool = Tool { pub const EXTRACT_MODULE: Tool = Tool { name: "extract_module", title: "Extract lines into a module", - description: "Move the whole items on lines `start_line`..`end_line` of a module into a new module `new_name`, whose ports come from the dataflow across the selection, and instantiate it in their place; verified before anything is written. `home: new_file` (default) creates `new_name.sv` beside the file (refused if it exists); `same_file` writes it below the module. Refuses a partial item and names it cannot carry. `dry_run` returns the diff.", + description: "Move whole items on lines `start_line`..`end_line` into a new module `new_name`, instantiated in their place.", params: &[ Param { name: "file", ty: Ty::Str, required: true, - description: "The file holding the module, relative to a root or absolute inside one.", + description: "The file.", }, Param { name: "start_line", ty: Ty::Int { min: 1 }, required: true, - description: "First line of the selection (1-based).", + description: "First line.", }, Param { name: "end_line", ty: Ty::Int { min: 1 }, required: true, - description: "Last line of the selection (1-based, included).", + description: "Last line (included).", }, Param { name: "new_name", ty: Ty::Str, required: true, - description: "The new module's name; nothing in the project may declare it yet.", + description: "A name nothing declares yet.", }, Param { name: "home", ty: Ty::Enum(&["new_file", "same_file"]), required: false, - description: "Where the new module goes: `new_file` (default) or `same_file`.", + description: "`new_file` (default, `new_name.sv`) or `same_file`.", }, DRY_RUN, ], @@ -90,37 +97,37 @@ pub const EXTRACT_MODULE: Tool = Tool { pub const INSTANTIATE: Tool = Tool { name: "instantiate", title: "Instantiation template", - description: "The text of an instantiation of module `name` for the agent to place — parameters with their defaults, the instance name, and each port connected to a same-named signal (`named`) or as `.*` (`wildcard`). Writes nothing. Refuses a module that is not indexed or is declared twice (pass `file` to pick one).", + description: "Instantiation text for module `name` to paste: parameter defaults, instance name, named or `.*` ports.", params: &[ Param { name: "name", ty: Ty::Str, required: true, - description: "The module (or interface) to instantiate.", + description: "The module or interface.", }, Param { name: "style", ty: Ty::Enum(&["named", "wildcard"]), required: false, - description: "`named` connections (default) or `.*`.", + description: "`named` (default) or `wildcard` (`.*`).", }, Param { name: "with_params", ty: Ty::Bool, required: false, - description: "Write the `#( … )` parameter overrides (default true).", + description: "Write the `#(...)` overrides (default true).", }, Param { name: "instance", ty: Ty::Str, required: false, - description: "The instance name (default `u_`).", + description: "Instance name (default `u_`).", }, Param { name: "file", ty: Ty::Str, required: false, - description: "The file declaring the module, when more than one does.", + description: "Its file, if declared twice.", }, ], rewalk: false, @@ -129,11 +136,12 @@ pub const INSTANTIATE: Tool = Tool { fn add_port(project: &mut Project, args: &Args) -> Result { let declaration = args.str("declaration").unwrap_or_default(); - match (args.str("module"), args.str("file"), args.int("line")) { + let (module, file, set, edit) = match (args.str("module"), args.str("file"), args.int("line")) { (Some(name), None, None) => { let set = whole_set(project, None, &[name.to_string()])?; let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(name), declaration)?; - finish(project, edit, &set, args) + let file = module_definition(project.index(), name).map(Path::to_path_buf)?; + (name.to_string(), file, set, edit) } (None, Some(file), Some(line)) => { let path = project.resolve(file)?; @@ -142,10 +150,25 @@ fn add_port(project: &mut Project, args: &Args) -> Result { let set = whole_set(project, Some(&path), &names)?; let module = ModuleRef::At { file: &path, offset }; let edit = vlog_refactor::add_port(&set.files, module, declaration)?; - finish(project, edit, &set, args) + let name = names.into_iter().next().unwrap_or_default(); + (name, path, set, edit) } - _ => Err("name the module by `module`, or by `file` and `line`, not both.".into()), - } + _ => return Err("name the module by `module`, or by `file` and `line`, not both.".into()), + }; + let tokens = vlog_parser::tokenize(declaration).unwrap_or_default(); + let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default(); + let show = &|path: &Path| project.relative(path); + let edit = match args.str("after") { + Some(after) => { + let spec = + place::Spec { module: &module, file: &file, after, port: &port, declaration, show }; + place::after(&set.files, &edit, &spec)? + } + None => edit, + }; + let lead = format!("the new port's name `{port}` is already spelled"); + let told = Told { name: &port, lead, home: &file }; + finish_telling(project, edit, &set, args, told, Some(&module)) } /// The byte offset where 1-based `line` of `path` starts; `end` asks for diff --git a/crates/lucisv_mcp/tests/fixtures/feedback/dv/probe_if.sv b/crates/lucisv_mcp/tests/fixtures/feedback/dv/probe_if.sv new file mode 100644 index 0000000..308833e --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/feedback/dv/probe_if.sv @@ -0,0 +1,7 @@ +`define CORE_HIER tb.u_core +`define SM_STATE `CORE_HIER.u_main_sm.state_q +interface probe_if; + string path = {"tb.u_core.u_main_sm", ".state_q"}; + logic seen; + assign seen = `CORE_HIER.u_main_sm.state_q; +endinterface diff --git a/crates/lucisv_mcp/tests/fixtures/feedback/rtl/cipher.sv b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/cipher.sv new file mode 100644 index 0000000..0cee29e --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/cipher.sv @@ -0,0 +1,12 @@ +module cipher #( + parameter bit Masking = 1 +) ( + input logic clk_i, + input logic rst_ni, + + // Data + input logic [31:0] data_i, + output logic valid_o +); + assign valid_o = data_i[0] & rst_ni; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/feedback/rtl/core.sv b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/core.sv new file mode 100644 index 0000000..ddf9c46 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/core.sv @@ -0,0 +1,11 @@ +module core ( + input logic clk_i, + output logic busy_o, + output logic probe_o +); + main_sm u_main_sm ( + .clk_i (clk_i), + .busy_o (busy_o) + ); + assign probe_o = u_main_sm.state_q; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/feedback/rtl/other_sm.sv b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/other_sm.sv new file mode 100644 index 0000000..d771025 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/other_sm.sv @@ -0,0 +1,8 @@ +module other_sm ( + input logic clk_i, + output logic busy_o +); + logic state_q; + always_ff @(posedge clk_i) state_q <= ~state_q; + assign busy_o = state_q; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/feedback/rtl/sm.sv b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/sm.sv new file mode 100644 index 0000000..7e8344f --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/sm.sv @@ -0,0 +1,11 @@ +// The main state machine; state_q is its register. +`define FLOP(d, q) always_ff @(posedge clk_i) q <= d; +module main_sm ( + input logic clk_i, + output logic busy_o +); + logic state_d, state_q; + `FLOP(state_d, state_q) + assign state_d = ~state_q; + assign busy_o = state_q; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/feedback/rtl/wrap.sv b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/wrap.sv new file mode 100644 index 0000000..4ce6fc7 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/feedback/rtl/wrap.sv @@ -0,0 +1,17 @@ +module wrap ( + input logic clk_i, + input logic rst_ni, + input logic dbg_i, + input logic [31:0] data_i, + output logic valid_o +); + cipher #( + .Masking ( 1 ) + ) u_cipher ( + .clk_i ( clk_i ), + .rst_ni ( rst_ni ), + + .data_i ( data_i ), // payload + .valid_o ( valid_o ) + ); +endmodule diff --git a/crates/lucisv_mcp/tests/qa_f1.rs b/crates/lucisv_mcp/tests/qa_f1.rs new file mode 100644 index 0000000..a299200 --- /dev/null +++ b/crates/lucisv_mcp/tests/qa_f1.rs @@ -0,0 +1,786 @@ +//! QA attacks on lane feedback-1 (unresolved mentions, `add_port`'s `after` +//! and its move-checker, the trimmed catalogue, the temp-store sweep), +//! 2026-09-23. +//! +//! Every test spawns the real binary over a scratch tree, as a host would. +//! Placements are asserted byte for byte; refusals with every file of the +//! tree byte-identical, under `dry_run` and for real. +//! +//! A test that pins a QA finding asserts the *correct* behaviour and is +//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are +//! numbered as in the QA log of `docs/features/mcp-feedback-1/README.md`. + +use std::collections::BTreeMap; +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::time::Duration; + +use serde_json::{json, Value}; + +const ANSWER_TIMEOUT: Duration = Duration::from_secs(120); + +static NEXT_DIR: AtomicUsize = AtomicUsize::new(0); + +/// A scratch tree holding the files a case writes; removed on drop. +struct Tree(PathBuf); + +impl Tree { + fn with(files: &[(&str, &str)]) -> Tree { + let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst); + let dir = + std::env::temp_dir().join(format!("lucisv-mcp-qa-f1-{}-{unique}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + for (name, text) in files { + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + Tree(fs::canonicalize(dir).unwrap()) + } + + /// Every file, root-relative, with its bytes. + fn snapshot(&self) -> BTreeMap> { + fn walk(dir: &Path, root: &Path, out: &mut BTreeMap>) { + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(&path, root, out); + } else { + let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned(); + out.insert(name, fs::read(&path).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + walk(&self.0, &self.0, &mut out); + out + } + + fn read(&self, file: &str) -> String { + fs::read_to_string(self.0.join(file)).unwrap() + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// One running server, initialised. +struct Session { + child: Child, + stdin: Option, + lines: Receiver, + next_id: i64, + /// The `initialize` reply. + init: Value, +} + +impl Session { + fn over(tree: &Tree) -> Session { + Session::spawn(&["--root", tree.0.to_str().unwrap()]) + } + + fn spawn(args: &[&str]) -> Session { + let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp")) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let stdout = child.stdout.take().unwrap(); + let (send, lines) = mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if send.send(line).is_err() { + break; + } + } + }); + let stdin = child.stdin.take().unwrap(); + let mut session = + Session { child, stdin: Some(stdin), lines, next_id: 0, init: Value::Null }; + session.init = session + .request("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}})); + session.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"})); + session + } + + fn send(&mut self, message: &Value) { + let stdin = self.stdin.as_mut().unwrap(); + writeln!(stdin, "{message}").unwrap(); + stdin.flush().unwrap(); + } + + fn request(&mut self, method: &str, params: Value) -> Value { + self.next_id += 1; + let id = self.next_id; + self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})); + let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered"); + let reply: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(reply["id"], id); + reply + } + + /// A tool call: whether it was refused, its text, its structured content. + fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) { + let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments})); + let result = &reply["result"]; + let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string(); + (result["isError"] == true, text, result["structuredContent"].clone()) + } + + /// Close stdin and wait for the server to exit on its own. + fn end(mut self) { + self.stdin.take(); + let _ = self.child.wait(); + } +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// A tree and a server over it. +fn served(files: &[(&str, &str)]) -> (Tree, Session) { + let tree = Tree::with(files); + let server = Session::over(&tree); + (tree, server) +} + +/// Run `tool` and assert it refuses with a sentence holding `why`, leaving +/// every file of the tree byte-identical — under `dry_run` and for real. +fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) -> String { + let before = tree.snapshot(); + let mut said = String::new(); + for dry_run in [true, false] { + let mut arguments = args.clone(); + arguments["dry_run"] = Value::from(dry_run); + let (error, text, _) = server.call(tool, arguments); + assert!(error, "{tool} {args}: not refused: {text}"); + assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}"); + assert!(before == tree.snapshot(), "{tool} {args}: a refusal wrote"); + said = text; + } + said +} + +/// Run `tool` for real and assert it wrote; its text and structured answer. +fn written(server: &mut Session, tool: &str, args: Value) -> (String, Value) { + let (error, text, structured) = server.call(tool, args.clone()); + assert!(!error, "{tool} {args}: refused: {text}"); + (text, structured) +} + +// --------------------------------------------------------------------------- +// 1. `add_port` `after`: placements, byte for byte. +// --------------------------------------------------------------------------- + +const M_HEADER: &str = "module m (\n input logic a, // anchor comment\n input logic b,\n output logic y /* last */\n);\n assign y = a & b;\nendmodule\n"; + +const M_TOP: &str = "module top (input logic a, b, en, output logic y);\n m u_m (\n .a (a), // in\n .b (b),\n .y (y)\n );\n m u_n (.a(a), .b(b), .y()), u_o (.a(a), .b(b), .y());\n generate if (1) begin : g_one\n m u_g (\n .a ( a ),\n .b ( b ),\n .y ( )\n );\n end endgenerate\nendmodule\n"; + +#[test] +fn qa_after_keeps_the_anchor_lines_comment_and_places_every_instance_shape() { + let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "a"}); + written(&mut server, "add_port", args.clone()); + // The anchor's own comment stays on the anchor's line; the new line + // follows it in the anchor's columns. + assert_eq!( + tree.read("rtl/m.sv"), + M_HEADER.replace("comment\n", "comment\n input logic en,\n") + ); + // One-per-line (aligned), two instances in one statement (inline, each + // placed), an instance in a generate block (aligned to its own anchor). + let want = M_TOP + .replace(" .a (a), // in\n", " .a (a), // in\n .en (en),\n") + .replace( + ".a(a), .b(b), .y()), u_o (.a(a), .b(b)", + ".a(a), .en(en), .b(b), .y()), u_o (.a(a), .en(en), .b(b)", + ) + .replace(" .a ( a ),\n", " .a ( a ),\n .en ( en ),\n"); + assert_eq!(tree.read("rtl/top.sv"), want); + // The same call again: the port exists, the engine refuses, nothing moves. + refused(&tree, &mut server, "add_port", args, "already has a port named `en`"); +} + +#[test] +fn qa_after_the_last_port_puts_the_comma_before_its_trailing_comment() { + let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "y"}); + written(&mut server, "add_port", args); + let header = " output logic y, /* last */\n input logic en\n);\n"; + assert_eq!( + tree.read("rtl/m.sv"), + M_HEADER.replace(" output logic y /* last */\n);\n", header) + ); + let top = tree.read("rtl/top.sv"); + assert!(top.contains(" .y (y),\n .en (en)\n );\n"), "{top}"); + assert!(top.contains(".y(), .en(en)), u_o (.a(a), .b(b), .y(), .en(en));"), "{top}"); +} + +#[test] +fn qa_after_keeps_crlf_and_tabs_and_places_an_instance_in_the_modules_own_file() { + let m = "module m (\r\n\tinput logic a,\t// tabbed\r\n\toutput logic y\r\n);\r\nendmodule\r\nmodule top2 (input logic a, en, output logic y);\r\n m u_s (\r\n .a (a),\r\n .y (y)\r\n );\r\nendmodule\r\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m)]); + let args = + json!({"file": "rtl/m.sv", "line": 2, "declaration": "input logic en", "after": "a"}); + written(&mut server, "add_port", args); + let want = m + .replace("// tabbed\r\n", "// tabbed\r\n\tinput logic en,\r\n") + .replace(" .a (a),\r\n", " .a (a),\r\n .en (en),\r\n"); + assert_eq!(tree.read("rtl/m.sv"), want); +} + +#[test] +fn qa_positional_instances_append_after_the_last_port_and_refuse_elsewhere() { + let top = "module top (input logic a, b, en, output logic y);\n m u_p (a, b, y);\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", top)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "b"}); + refused(&tree, &mut server, "add_port", args, "connects `m` by position"); + let args = json!({"module": "m", "declaration": "input logic en", "after": "y"}); + written(&mut server, "add_port", args); + assert_eq!(tree.read("rtl/top.sv"), top.replace("(a, b, y)", "(a, b, y, en)")); +} + +#[test] +fn qa_after_a_parameter_an_unknown_name_or_an_ifdef_arm_is_refused() { + let m = "module m #(parameter int W = 1) (\n input logic a,\n`ifdef X\n input logic b,\n`endif\n output logic y\n);\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m)]); + let decl = "input logic en"; + let args = json!({"module": "m", "declaration": decl, "after": "W"}); + refused(&tree, &mut server, "add_port", args, "`m` has no port `W` (its ports: a, b, y)"); + let args = json!({"module": "m", "declaration": decl, "after": "b"}); + refused(&tree, &mut server, "add_port", args, "inside an `ifdef arm"); + // Just before the arm, and just after it: placed outside it. + let args = json!({"module": "m", "declaration": decl, "after": "a", "dry_run": true}); + let text = written(&mut server, "add_port", args).0; + assert!(text.contains(" input logic a,\n+ input logic en,\n `ifdef X\n"), "{text}"); + let args = json!({"module": "m", "declaration": decl, "after": "y"}); + written(&mut server, "add_port", args); + let want = m.replace(" output logic y\n", " output logic y,\n input logic en\n"); + assert_eq!(tree.read("rtl/m.sv"), want); +} + +#[test] +fn qa_a_connection_anchor_in_an_ifdef_arm_keeps_the_engines_append_and_says_so() { + let m = "module m (\n input logic a,\n output logic y\n);\nendmodule\n"; + let top = "module top (input logic a, en, output logic y);\n m u_i (\n`ifdef X\n .a (a),\n`endif\n .y (y)\n );\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "a"}); + let (text, structured) = written(&mut server, "add_port", args); + assert!(text.contains("`u_i` in "), "{text}"); + assert!( + text.contains( + "the connection of `en` was appended at the end (`.a` sits inside an `ifdef arm)" + ), + "{text}" + ); + assert_eq!(structured["warnings"].as_array().unwrap().len(), 1, "{structured}"); + assert_eq!(tree.read("rtl/top.sv"), top.replace(" .y (y)\n", " .y (y),\n .en(en)\n")); + assert!(tree.read("rtl/m.sv").contains(" input logic a,\n input logic en,\n")); +} + +/// Apply a unified diff (as `apply::run` renders it) to `before`. +fn patch(before: &str, diff: &str) -> String { + let old: Vec<&str> = before.split_inclusive('\n').collect(); + let mut out = String::new(); + let mut at = 0usize; + for line in diff.split_inclusive('\n') { + if line.starts_with("---") || line.starts_with("+++") || line.starts_with('\\') { + continue; + } + if let Some(header) = line.strip_prefix("@@ -") { + let start: usize = header.split([',', ' ']).next().unwrap().parse().unwrap(); + while at + 1 < start { + out.push_str(old[at]); + at += 1; + } + } else if let Some(added) = line.strip_prefix('+') { + out.push_str(added); + } else if line.starts_with('-') { + at += 1; + } else { + out.push_str(old[at]); + at += 1; + } + } + old[at..].iter().for_each(|rest| out.push_str(rest)); + out +} + +#[test] +fn qa_the_dry_run_diff_is_exactly_what_the_real_run_writes() { + for after in ["a", "b", "y"] { + let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]); + let args = json!({"module": "m", "declaration": "input logic [3:0] en", "after": after}); + let mut dry = args.clone(); + dry["dry_run"] = Value::from(true); + let (_, preview) = written(&mut server, "add_port", dry); + let diffs: BTreeMap = preview["changed"] + .as_array() + .unwrap() + .iter() + .map(|c| (c["file"].as_str().unwrap().into(), c["diff"].as_str().unwrap().into())) + .collect(); + let before = tree.snapshot(); + written(&mut server, "add_port", args); + for (file, diff) in &diffs { + let old = String::from_utf8(before[file].clone()).unwrap(); + assert_eq!(patch(&old, diff), tree.read(file), "after {after}: {file}\n{diff}"); + } + assert_eq!(diffs.len(), 2); + } +} + +// --------------------------------------------------------------------------- +// Findings on `after` (QA log, findings 1–4). +// --------------------------------------------------------------------------- + +/// Finding 1: an anchor whose comment sits between it and its comma (or on +/// the anchor's line before a leading-comma next element) is placed inline +/// at the anchor's end, so the new port lands *between* the anchor and its +/// comment: `a, input logic en /* about a */,`. The comment now documents +/// the new port. `place::verify` compares comment texts as a sorted +/// multiset, so it forgives the move. Correct: the comment stays right +/// after its anchor (insert before the comma token, after the trivia). +#[test] +fn qa_a_comment_between_the_anchor_and_its_comma_stays_with_the_anchor() { + let m = "module m (\n input logic a /* about a */,\n input logic b // about b\n , input logic c,\n output logic y\n);\nendmodule\n"; + let top = "module top (input logic a, b, c, en, output logic y);\n m u_m (\n .a (a) /* conn a */,\n .b (b),\n .c (c),\n .y (y)\n );\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = + json!({"module": "m", "declaration": "input logic en", "after": "a", "dry_run": true}); + let (text, _) = written(&mut server, "add_port", args); + assert!(!text.contains("en /* about a */"), "the anchor's comment moved to `en`:\n{text}"); + assert!(!text.contains(".en(en) /* conn a */"), "the connection's comment moved:\n{text}"); + let args = + json!({"module": "m", "declaration": "input logic en", "after": "b", "dry_run": true}); + let (text, _) = written(&mut server, "add_port", args); + assert!(!text.contains("en // about b"), "the anchor's comment moved to `en`:\n{text}"); + drop(tree); +} + +/// Finding 2: the warnings and refusals `place.rs` writes name the file by +/// its absolute path (`path.display()`, place.rs:84 and :221); every other +/// answer names files relative to a root. +#[test] +fn qa_place_names_files_relative_to_the_root() { + let m = "module m (\n input logic a,\n output logic y\n);\nendmodule\n"; + let top = "module top (input logic a, en, output logic y);\n m u_i (\n`ifdef X\n .a (a),\n`endif\n .y (y)\n );\n m u_p (a, y);\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let root = tree.0.to_str().unwrap().to_string(); + let args = json!({"module": "m", "declaration": "input logic en", "after": "a"}); + let said = refused(&tree, &mut server, "add_port", args, "by position"); + assert!(!said.contains(&root) && said.contains("rtl/top.sv"), "{said}"); + fs::write(tree.0.join("rtl/top.sv"), top.replace(" m u_p (a, y);\n", "")).unwrap(); + let args = + json!({"module": "m", "declaration": "input logic en", "after": "a", "dry_run": true}); + let (text, _) = written(&mut server, "add_port", args); + assert!(!text.contains(&root) && text.contains("rtl/top.sv"), "{text}"); +} + +/// Finding 3: a next port that is an interface port (`bus_if.mp bus`) has +/// no direction, but does not inherit one either; `after` the port before +/// it is refused as if it did (place.rs:155). +#[test] +fn qa_a_modport_port_after_the_anchor_does_not_refuse() { + let n = "interface bus_if; logic v; modport mp(input v); endinterface\nmodule n (\n input logic clk,\n bus_if.mp bus,\n output logic y\n);\nendmodule\n"; + let (_tree, mut server) = served(&[("rtl/n.sv", n)]); + let args = + json!({"module": "n", "declaration": "input logic en", "after": "clk", "dry_run": true}); + let (error, text, _) = server.call("add_port", args); + assert!(!error, "{text}"); +} + +/// Finding 4: the edit tools list mentions with the line numbers of the +/// text *before* the edit; after a real write that adds or removes lines +/// (`add_port`, `remove_port`, a rename writing out `.*`), a mention below +/// the edit in an edited file names the wrong line. +#[test] +fn qa_mention_lines_name_the_file_as_written() { + let m = "module m (\n input logic a,\n input logic b,\n output logic y\n);\n // en gates y\n assign y = a & b;\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "a"}); + let (_, structured) = written(&mut server, "add_port", args); + let mention = &structured["unresolved_mentions"][0]; + let line = mention["line"].as_u64().unwrap() as usize; + let on_disk = tree.read("rtl/m.sv"); + assert_eq!(on_disk.lines().nth(line - 1).map(str::trim), mention["text"].as_str(), "{on_disk}"); +} + +/// Finding 5 (BLOCKING), a: a port list holding an element the parser +/// could not read (`(* keep *) b` — legal SV: an attribute on a port that +/// inherits `a`'s direction and type) hides that element from `place.rs`, +/// which reads the list through `ListElem::ok`. The port placed after `a` +/// lands before `b`, so `b` now inherits `input logic` — its width drops +/// from 8 to 1 — and `place::verify` (which also sees only the well-formed +/// ports, the same token multiset and the same error count) writes it. +/// Correct: refused, nothing written. +#[test] +fn qa_a_port_hidden_by_a_parse_error_does_not_change_its_inherited_type() { + let m = "module m (\n input logic [7:0] a,\n (* keep *) b,\n output logic y\n);\n assign y = ^b;\nendmodule\n"; + let top = "module top (input logic [7:0] a, b, input logic en, output logic y);\n m u_m (\n .a (a),\n .b (b),\n .y (y)\n );\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "a"}); + let before = tree.snapshot(); + let (error, text, _) = server.call("add_port", args); + assert!(error, "written: {text}\n{}", tree.read("rtl/m.sv")); + assert!(before == tree.snapshot()); +} + +/// Finding 5 (BLOCKING), b: `balanced_before` is handed the anchor's index +/// among the *well-formed* ports, but `ListDirective::before` counts every +/// element. One unreadable element before the anchor shifts the count, so +/// an anchor inside an `` `ifdef`` arm passes as outside it: the new port +/// is written inside the arm (it exists only when `X` is defined) while +/// every connection is unconditional — and the engine's own warning, still +/// in the answer, says the port was added "outside every conditional arm". +/// place.rs:161 (header) and :244 (connections) share the bug. +#[test] +fn qa_an_unreadable_element_does_not_let_an_anchor_in_an_ifdef_arm_through() { + let m = "module m (\n input logic a,\n (* keep *) input logic d,\n`ifdef X\n input logic b,\n`endif\n output logic y\n);\nendmodule\n"; + let top = "module top (input logic a, b, d, en, output logic y);\n m u_m (\n .a (a),\n .d (d),\n`ifdef X\n .b (b),\n`endif\n .y (y)\n );\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "b"}); + refused(&tree, &mut server, "add_port", args, "inside an `ifdef arm"); +} + +// --------------------------------------------------------------------------- +// Re-check of the rework (2026-09-23): the new rules, attacked. +// --------------------------------------------------------------------------- + +const PLAIN_M: &str = "module m (\n input logic a,\n output logic y\n);\nendmodule\nmodule o (input logic p, q);\nendmodule\n"; + +/// An unreadable connection (`..q (p)`) in an instance nothing is placed +/// into — another module's, and a `.*` instance of `m` the engine leaves +/// alone — does not refuse; in an instance the port is placed into, it does, +/// named root-relative, with nothing written. +#[test] +fn qa_r_only_an_affected_instances_unreadable_connection_refuses() { + let top = "module top (input logic a, en, p, output logic y);\n o u_o (\n .p (p),\n ..q (p)\n );\n m u_w (.*, ..z (p));\n m u_m (\n .a (a),\n .y (y)\n );\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", PLAIN_M), ("rtl/top.sv", top)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "a"}); + written(&mut server, "add_port", args.clone()); + assert_eq!( + tree.read("rtl/top.sv"), + top.replace(" .a (a),\n", " .a (a),\n .en (en),\n") + ); + assert!(tree.read("rtl/m.sv").contains(" input logic a,\n input logic en,\n")); + let affected = top.replace(" .y (y)\n", " .y (y),\n ..z (p)\n"); + let (tree, mut server) = served(&[("rtl/m.sv", PLAIN_M), ("rtl/top.sv", &affected)]); + let said = refused(&tree, &mut server, "add_port", args, "`u_m` in rtl/top.sv holds `..z (p)`"); + assert!(said.contains("nothing written"), "{said}"); +} + +/// The last anchor under an own-line comment, with an own-line comment +/// closing the list: the comma goes on the anchor, the new element right +/// below it, both comments stay where they were — header and connections. +#[test] +fn qa_r_own_line_comments_around_the_last_anchor_stay_put() { + let m = "module m (\n input logic a,\n // the result\n output logic y\n // end of ports\n);\nendmodule\n"; + let top = "module top (input logic a, en, output logic y);\n m u_m (\n .a (a),\n // the result\n .y (y)\n // end\n );\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "y"}); + written(&mut server, "add_port", args); + let header = " output logic y,\n input logic en\n // end of ports\n"; + assert_eq!(tree.read("rtl/m.sv"), m.replace(" output logic y\n // end of ports\n", header)); + let conns = " .y (y),\n .en (en)\n // end\n"; + assert_eq!(tree.read("rtl/top.sv"), top.replace(" .y (y)\n // end\n", conns)); +} + +/// A `//` comment after the separator on the anchor's line (with a block +/// comment before the separator too) stays on the anchor's line; a last +/// anchor with a comment before `)` on the same line keeps it; a +/// leading-comma list gets the element after the separator. +#[test] +fn qa_r_comments_on_the_anchors_line_stay_on_it() { + let m = "module m (\n input logic a /* c1 */, // c2\n input logic b // about b\n , output logic y\n);\nendmodule\nmodule n (input logic a, output logic y /* c */);\nendmodule\n"; + let top = "module top (input logic a, b, en, output logic y);\n m u_m (\n .a (a), // in a\n .b (b),\n .y (y)\n );\n n u_n (.a(a), .y(y) /* k */);\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = json!({"module": "m", "declaration": "input logic en", "after": "a"}); + written(&mut server, "add_port", args); + let want = m.replace("// c2\n", "// c2\n input logic en,\n"); + assert_eq!(tree.read("rtl/m.sv"), want); + let want_top = top.replace("// in a\n", "// in a\n .en (en),\n"); + assert_eq!(tree.read("rtl/top.sv"), want_top); + let args = json!({"module": "m", "declaration": "input logic f", "after": "b"}); + written(&mut server, "add_port", args); + let header = " input logic b // about b\n , input logic f, output logic y\n"; + assert_eq!( + tree.read("rtl/m.sv"), + want.replace(" input logic b // about b\n , output logic y\n", header) + ); + let args = json!({"module": "n", "declaration": "input logic en", "after": "y"}); + written(&mut server, "add_port", args); + let m_now = tree.read("rtl/m.sv"); + assert!( + m_now.contains("module n (input logic a, output logic y, /* c */ input logic en);"), + "{m_now}" + ); + let top_now = tree.read("rtl/top.sv"); + assert!(top_now.contains(" n u_n (.a(a), .y(y), /* k */ .en(en));"), "{top_now}"); +} + +/// A typed port without a direction after the anchor inherits the anchor's +/// direction: a new port of the same direction keeps it (placed, byte for +/// byte); of another direction would turn it (refused, nothing written). +#[test] +fn qa_r_a_typed_undirected_next_port_is_placed_only_under_the_same_direction() { + let m = "module m (\n input logic a,\n logic [3:0] b,\n output logic y\n);\nendmodule\n"; + let top = "module top (input logic a, en, input logic [3:0] b, output logic y);\n m u_m (\n .a (a),\n .b (b),\n .y (y)\n );\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = json!({"module": "m", "declaration": "output logic en", "after": "a"}); + refused(&tree, &mut server, "add_port", args, "`b` takes its direction"); + let args = json!({"module": "m", "declaration": "input logic en", "after": "a"}); + written(&mut server, "add_port", args); + assert_eq!( + tree.read("rtl/m.sv"), + m.replace(" input logic a,\n", " input logic a,\n input logic en,\n") + ); + assert_eq!( + tree.read("rtl/top.sv"), + top.replace(" .a (a),\n", " .a (a),\n .en (en),\n") + ); +} + +/// A rename that writes out a `.*` binding adds a line above the mentions; +/// the written answer names the lines of the file as written. +#[test] +fn qa_r_mention_lines_after_a_rename_writing_out_a_star_binding() { + let m = "module m (\n input logic a,\n output logic y\n);\n assign y = a;\nendmodule\n"; + let top = "module top (input logic a, output logic y);\n m u_m (\n .*\n );\n // a feeds u_m\n initial $display(\"a\");\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = json!({"file": "rtl/m.sv", "line": 2, "name": "a", "new_name": "a_i"}); + let (text, structured) = written(&mut server, "rename", args); + assert!(text.contains("added `.a_i(a)`"), "{text}"); + let on_disk = tree.read("rtl/top.sv"); + assert!(on_disk.contains(" .*,\n .a_i(a)\n"), "{on_disk}"); + let listed = structured["unresolved_mentions"].as_array().unwrap(); + assert_eq!(listed.len(), 2, "{structured}"); + for mention in listed { + let line = mention["line"].as_u64().unwrap() as usize; + let shown = on_disk.lines().nth(line - 1).map(str::trim); + assert_eq!(shown, mention["text"].as_str(), "{on_disk}"); + } +} + +/// Finding 6 (low, for the lead to rule): the rework computes mentions on +/// the texts as they *would be* written under `dry_run` too, so a dry run's +/// `file:line` names a line of a file that is not on disk — the comment at +/// top.sv:5 is listed as top.sv:6, which on disk is the `$display`. +#[test] +#[ignore = "QA finding 6"] +fn qa_r_dry_run_mention_lines_name_the_file_on_disk() { + let m = "module m (\n input logic a,\n output logic y\n);\n assign y = a;\nendmodule\n"; + let top = "module top (input logic a, output logic y);\n m u_m (\n .*\n );\n // a feeds u_m\n initial $display(\"a\");\nendmodule\n"; + let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]); + let args = + json!({"file": "rtl/m.sv", "line": 2, "name": "a", "new_name": "a_i", "dry_run": true}); + let (_, structured) = written(&mut server, "rename", args); + let on_disk = tree.read("rtl/top.sv"); + for mention in structured["unresolved_mentions"].as_array().unwrap() { + let line = mention["line"].as_u64().unwrap() as usize; + let shown = on_disk.lines().nth(line - 1).map(str::trim); + assert_eq!(shown, mention["text"].as_str(), "{on_disk}"); + } +} + +// --------------------------------------------------------------------------- +// 2. Unresolved mentions. +// --------------------------------------------------------------------------- + +const SM: &str = "module main_sm (\n input logic clk_i,\n output logic busy_o\n);\n logic state_q, state_q_d;\n // see tb.u_main_sm.state_q for the probe\n // state_q_d is not it, nor xstate_q\n `uvm_info(\"SM\", $sformatf(\"state_q=%0d\", state_q_d), UVM_LOW)\n `define F(state_q) state_q + 1\n `define G(x) x.state_q\n assign busy_o = state_q;\n initial $display(\"%m.state_q\");\n // \\state_q escaped\nendmodule\n"; + +const DV: &str = "module dv_x;\n logic a, b;\n assign a = `HIER.u_a[2].state_q;\n assign b = `HIER.u_a[2].state_q_d;\n assign b = `HIER.u_a[state_q].x;\nendmodule\n"; + +const CRLF: &str = + "module c;\r\n // one\r\n // state_q two\r\n string s = \"state_q\";\r\nendmodule\r\n"; + +/// Each listed mention as `file:line kind`. +fn sites(structured: &Value) -> Vec { + let listed = structured["unresolved_mentions"].as_array().unwrap(); + listed + .iter() + .map(|m| { + format!("{}:{} {}", m["file"].as_str().unwrap(), m["line"], m["kind"].as_str().unwrap()) + }) + .collect() +} + +#[test] +fn qa_mentions_find_every_kind_and_only_whole_words() { + let files = [("rtl/sm.sv", SM), ("rtl/sub/crlf.sv", CRLF), ("dv/x.sv", DV)]; + let (_tree, mut server) = served(&files); + let (text, structured) = + written(&mut server, "references", json!({"name": "state_q", "unit": "main_sm"})); + assert_eq!( + sites(&structured), + [ + // The file of the hits first: a hierarchical path in a comment, + // a string inside a macro's arguments, a `define body (not the + // `define whose formal is the name), a string, an escaped + // spelling in a comment. + "rtl/sm.sv:6 comment", + "rtl/sm.sv:8 macro", + "rtl/sm.sv:10 define", + "rtl/sm.sv:12 string", + "rtl/sm.sv:13 comment", + // Then nearest the declaration; CRLF lines counted right. + "rtl/sub/crlf.sv:3 comment", + "rtl/sub/crlf.sv:4 string", + // A macro-rooted path through an index; `state_q_d` and a + // name used as an index are not the path's last name. + "dv/x.sv:3 path", + ], + "{text}" + ); + assert!(text.contains(" rtl/sub/crlf.sv:4 string: string s = \"state_q\";\n"), "{text}"); + assert!(!text.contains('\r'), "no carriage return in a mention's text"); + // The JSON shape: exactly these four keys, a number for the line. + for mention in structured["unresolved_mentions"].as_array().unwrap() { + let keys: Vec<&String> = mention.as_object().unwrap().keys().collect(); + assert_eq!(keys, ["file", "kind", "line", "text"]); + assert!(mention["line"].is_u64()); + } + // A later page repeats nothing. + let args = json!({"name": "state_q", "unit": "main_sm", "offset": 1}); + let (text, structured) = written(&mut server, "references", args); + assert!(!text.contains("unresolved mentions"), "{text}"); + assert_eq!(structured["unresolved_mentions"], json!([])); +} + +#[test] +fn qa_mentions_are_capped_at_50_with_the_edited_file_first() { + let far: String = (0..60).map(|i| format!("// state_q far {i}\n")).collect::() + + "module far; endmodule\n"; + let files = [("rtl/sm.sv", SM), ("zz/far.sv", far.as_str())]; + let (tree, mut server) = served(&files); + let args = json!({"name": "state_q", "unit": "main_sm", "new_name": "st_q", "dry_run": true}); + let (text, structured) = written(&mut server, "rename", args); + let listed = sites(&structured); + assert_eq!(listed.len(), 50); + assert_eq!(listed[0], "rtl/sm.sv:6 comment", "the edited file first"); + assert_eq!(listed[5], "zz/far.sv:1 comment"); + assert_eq!(listed[49], "zz/far.sv:45 comment"); + assert!(text.contains("(strings, comments, macro text; 65 in all)"), "{text}"); + assert!(text.contains("\n … and 15 more"), "{text}"); + // The renamed spellings are not mentions; the edit left the rest alone. + assert!(!listed + .iter() + .any(|site| site.starts_with("rtl/sm.sv:5 ") || site.starts_with("rtl/sm.sv:11 "))); + written( + &mut server, + "rename", + json!({"name": "state_q", "unit": "main_sm", "new_name": "st_q"}), + ); + let sm = tree.read("rtl/sm.sv"); + assert_eq!( + sm, + SM.replace("logic state_q,", "logic st_q,").replace("busy_o = state_q;", "busy_o = st_q;") + ); +} + +// --------------------------------------------------------------------------- +// 3. The catalogue and the instructions. +// --------------------------------------------------------------------------- + +#[test] +fn qa_the_catalogue_is_small_fully_described_and_spec_shaped() { + let tree = Tree::with(&[]); + let mut server = Session::over(&tree); + let reply = server.request("tools/list", json!({})); + let size = reply["result"].to_string().len(); + assert!(size <= 18_000, "tools/list is {size} bytes"); + let tools = reply["result"]["tools"].as_array().unwrap(); + assert_eq!(tools.len(), 26); + for tool in tools { + let name = tool["name"].as_str().unwrap(); + assert!(tool["title"].as_str().is_some_and(|t| !t.is_empty()), "{name} keeps its title"); + assert!(tool["description"].as_str().is_some_and(|d| !d.is_empty()), "{name}"); + let annotations = tool["annotations"].as_object().unwrap(); + assert!(!annotations.contains_key("title"), "{name}: annotations.title is gone"); + for hint in ["readOnlyHint", "destructiveHint", "idempotentHint"] { + assert!(annotations[hint].is_boolean(), "{name}.{hint}"); + } + let schema = &tool["inputSchema"]; + assert_eq!(schema["type"], "object", "{name}"); + for (param, property) in schema["properties"].as_object().unwrap() { + let described = property["description"].as_str().is_some_and(|d| d.len() > 2); + assert!(described, "{name}.{param} lost its description"); + } + } + let add_port = tools.iter().find(|t| t["name"] == "add_port").unwrap(); + assert_eq!(add_port["inputSchema"]["properties"]["after"]["type"], "string"); + let required = add_port["inputSchema"]["required"].as_array().unwrap(); + assert!(!required.contains(&json!("after"))); + // The instructions: short, and every tool they name exists. + let instructions = server.init["result"]["instructions"].as_str().unwrap(); + assert!(instructions.chars().count() <= 900, "{}", instructions.chars().count()); + let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); + let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')); + for word in words.filter(|w| w.contains('_') && *w != "dry_run") { + assert!(names.contains(&word), "the instructions name `{word}`, which is not a tool"); + } + for word in + ["outline", "definition", "references", "hierarchy", "rename", "format", "diagnostics"] + { + assert!(names.contains(&word) && instructions.contains(word), "{word}"); + } +} + +// --------------------------------------------------------------------------- +// 4. The temp-store sweep. +// --------------------------------------------------------------------------- + +#[test] +fn qa_the_sweep_takes_only_old_files_of_the_exact_temp_name() { + let tree = Tree::with(&[("rtl/a.sv", "module a; endmodule\n")]); + let cache = tree.0.join("cache"); + fs::create_dir_all(&cache).unwrap(); + let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600); + let old = |path: &Path| { + fs::File::open(path).unwrap().set_modified(hour_ago).unwrap(); + }; + let stale = cache.join("index-cache-mcp.1.tmp"); + let spared_names = [ + "index-cache-mcp..tmp", + "index-cache-mcp.12a.tmp", + "index-cache-mcp.12.tmp.bak", + "index-cache.12.tmp", + "xindex-cache-mcp.12.tmp", + ]; + for name in std::iter::once("index-cache-mcp.1.tmp").chain(spared_names) { + fs::write(cache.join(name), "torn").unwrap(); + old(&cache.join(name)); + } + // An old directory of the exact name is not a file: left alone. + let dir = cache.join("index-cache-mcp.77.tmp"); + fs::create_dir_all(dir.join("inside")).unwrap(); + old(&dir); + let mut server = Session::spawn(&[ + "--root", + tree.0.to_str().unwrap(), + "--index-cache", + cache.to_str().unwrap(), + ]); + server.call("list_units", json!({})); + server.end(); + assert!(cache.join("index-cache-mcp").is_file(), "the own store is still written"); + assert!(!stale.exists(), "an hour-old `..tmp` is swept"); + for name in spared_names { + assert!(cache.join(name).exists(), "{name} is not ours to sweep"); + } + assert!(dir.join("inside").is_dir(), "a directory is never swept"); +} diff --git a/crates/lucisv_mcp/tests/qa_m6.rs b/crates/lucisv_mcp/tests/qa_m6.rs index a9af8ba..abab66d 100644 --- a/crates/lucisv_mcp/tests/qa_m6.rs +++ b/crates/lucisv_mcp/tests/qa_m6.rs @@ -536,7 +536,6 @@ fn qa_a_killed_session_leaves_the_previous_own_store_intact() { /// Correct behaviour: the next write sweeps a stale temp file of its own /// store's name (an old mtime, so a concurrent writer's live one is spared). #[test] -#[ignore = "QA finding 2"] fn qa_an_orphaned_temp_file_is_swept_by_the_next_write() { let scratch = Scratch::new(); fs::create_dir_all(scratch.cache()).unwrap(); diff --git a/crates/lucisv_mcp/tests/wire.rs b/crates/lucisv_mcp/tests/wire.rs index 250d50c..eee96ff 100644 --- a/crates/lucisv_mcp/tests/wire.rs +++ b/crates/lucisv_mcp/tests/wire.rs @@ -1402,3 +1402,212 @@ fn the_instructions_name_the_workflow_within_900_characters() { assert!(instructions.contains(word), "{word}: {instructions}"); } } + +// --------------------------------------------------------------------------- +// Feedback round 1 (`docs/features/mcp-feedback-1`): unresolved mentions, +// `add_port`'s `after`, the catalogue's size, the temp-file sweep. +// --------------------------------------------------------------------------- + +/// A server over a fresh copy of the feedback fixture. +fn feedback_tree() -> (Tree, Session) { + let tree = Tree::of("feedback"); + let mut server = Session::over(&tree); + server.initialize(); + (tree, server) +} + +/// The `file:line kind` of each listed mention, in order. +fn mention_sites(structured: &Value) -> Vec { + let listed = structured["unresolved_mentions"].as_array().unwrap(); + listed + .iter() + .map(|m| { + format!("{}:{} {}", m["file"].as_str().unwrap(), m["line"], m["kind"].as_str().unwrap()) + }) + .collect() +} + +#[test] +fn references_ends_with_the_mentions_no_engine_resolved() { + let (_tree, mut server) = feedback_tree(); + let args = json!({"name": "state_q", "unit": "main_sm"}); + let result = server.call("references", args); + assert_eq!(result["isError"], false, "{result}"); + let text = result["content"][0]["text"].as_str().unwrap(); + // The engine's hits, the hierarchical one in core.sv included … + assert!(text.contains("rtl/core.sv\n 10:30 "), "{text}"); + let (hits, mentions) = text + .split_once( + "unresolved mentions (strings, comments, macro text — not resolved by lucisv):\n", + ) + .unwrap(); + assert!(hits.contains("rtl/sm.sv\n"), "{text}"); + // … then every spelling no engine resolved: a comment, a macro + // argument, a `define body, a string and a macro-rooted path. + assert_eq!( + mention_sites(&result["structuredContent"]), + [ + "rtl/sm.sv:1 comment", + "rtl/sm.sv:8 macro", + "dv/probe_if.sv:2 define", + "dv/probe_if.sv:4 string", + "dv/probe_if.sv:6 path", + ] + ); + assert!( + mentions.contains( + " dv/probe_if.sv:4 string: string path = {\"tb.u_core.u_main_sm\", \".state_q\"};\n" + ), + "{mentions}" + ); + // An engine hit is never listed again, and another module's own + // `state_q` is a declaration of its own, not a mention. + assert!(!mentions.contains("core.sv") && !mentions.contains("other_sm.sv"), "{mentions}"); +} + +#[test] +fn references_without_a_textual_mention_has_no_section() { + let (_tree, mut server) = feedback_tree(); + let result = server.call("references", json!({"name": "busy_o", "unit": "core"})); + let text = result["content"][0]["text"].as_str().unwrap(); + assert!(!text.contains("unresolved mentions"), "{text}"); + assert_eq!(result["structuredContent"]["unresolved_mentions"], json!([])); +} + +#[test] +fn rename_warns_of_the_old_names_unresolved_mentions() { + let (tree, mut server) = feedback_tree(); + let args = json!({"name": "state_q", "unit": "main_sm", "new_name": "main_state_q"}); + let preview = server.call("rename", dry(&args, true)); + assert_eq!(preview["isError"], false, "{preview}"); + let text = preview["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("warnings:\n"), "{text}"); + assert!( + text.contains("the old name `state_q` is still spelled as text at these places lucisv does not resolve (strings, comments, macro text; 5 in all); check whether these are references:\n rtl/sm.sv:1 comment: "), + "{text}" + ); + assert!( + text.contains("\n dv/probe_if.sv:6 path: assign seen = `CORE_HIER.u_main_sm.state_q;\n"), + "{text}" + ); + // The hierarchical use in core.sv is renamed, so it is not a mention. + assert!(text.contains("+ assign probe_o = u_main_sm.main_state_q;"), "{text}"); + assert_eq!(mention_sites(&preview["structuredContent"]).len(), 5); + assert_eq!(read(&tree, "dv/probe_if.sv"), read_fixture("feedback", "dv/probe_if.sv")); + // Written, the same warning; the text it names is left as it was. + let written = server.text("rename", args); + assert!(written.contains("check whether these are references"), "{written}"); + assert!(read(&tree, "dv/probe_if.sv").contains("\".state_q\"")); +} + +fn read_fixture(fixture: &str, file: &str) -> String { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture); + fs::read_to_string(root.join(file)).unwrap() +} + +#[test] +fn add_port_after_places_the_port_and_the_connection_in_the_neighbours_layout() { + let (tree, mut server) = feedback_tree(); + let args = json!({"module": "cipher", "declaration": "input logic dbg_i", "after": "rst_ni"}); + let written = server.text("add_port", args.clone()); + assert!(written.starts_with("files: 2 changed, 0 created\n"), "{written}"); + let cipher = read(&tree, "rtl/cipher.sv"); + let header = " input logic clk_i,\n input logic rst_ni,\n input logic dbg_i,\n\n // Data\n"; + assert!(cipher.contains(header), "{cipher}"); + let wrap = read(&tree, "rtl/wrap.sv"); + let connections = " .rst_ni ( rst_ni ),\n .dbg_i ( dbg_i ),\n\n .data_i ( data_i ), // payload\n"; + assert!(wrap.contains(connections), "{wrap}"); + // Exactly one line more in each file: nothing else moved. + let fixture = |file: &str| read_fixture("feedback", file); + assert_eq!( + cipher.replace(" input logic dbg_i,\n", ""), + fixture("rtl/cipher.sv") + ); + assert_eq!( + wrap.replace(" .dbg_i ( dbg_i ),\n", ""), + fixture("rtl/wrap.sv") + ); + let again = server.call("add_port", args); + assert_eq!(again["isError"], true, "a second call finds the port: {again}"); +} + +#[test] +fn add_port_after_the_last_port_moves_its_comma_and_refuses_an_unknown_anchor() { + let (tree, mut server) = feedback_tree(); + let args = json!({"module": "cipher", "declaration": "output logic [1:0] err_o", "after": "valid_o", "dry_run": true}); + let preview = server.text("add_port", args); + // The type starts at the neighbour's type column, the name at its name + // column; the last port gains the comma. + let header = "- output logic valid_o\n+ output logic valid_o,\n+ output logic [1:0] err_o\n"; + assert!(preview.contains(header), "{preview}"); + let connection = "+ .valid_o ( valid_o ),\n+ .err_o ( /* TODO: connect */ )\n"; + assert!(preview.contains(connection), "{preview}"); + assert_eq!(read(&tree, "rtl/cipher.sv"), read_fixture("feedback", "rtl/cipher.sv")); + let unknown = server.call( + "add_port", + json!({"module": "cipher", "declaration": "input logic x_i", "after": "nope"}), + ); + assert_eq!(unknown["isError"], true); + let said = unknown["content"][0]["text"].as_str().unwrap(); + assert!( + said.contains("`cipher` has no port `nope` (its ports: clk_i, rst_ni, data_i, valid_o)"), + "{said}" + ); +} + +#[test] +fn the_tool_catalogue_stays_under_18_kb() { + let tree = Tree::new(); + let mut server = Session::over(&tree); + server.initialize(); + let reply = server.request("tools/list", json!({})); + let size = reply["result"].to_string().len(); + assert!(size <= 18_000, "tools/list is {size} bytes"); + for tool in reply["result"]["tools"].as_array().unwrap() { + for (name, property) in tool["inputSchema"]["properties"].as_object().unwrap() { + let described = property["description"].as_str().is_some_and(|d| !d.is_empty()); + assert!(described, "{}.{name} is documented", tool["name"]); + } + } + let hierarchy = reply["result"]["tools"] + .as_array() + .unwrap() + .iter() + .find(|t| t["name"] == "hierarchy") + .unwrap(); + assert!(hierarchy["description"] + .as_str() + .unwrap() + .starts_with("Who instantiates a module (`up`")); +} + +#[test] +fn a_stale_temp_store_is_swept_and_a_young_one_and_other_files_are_spared() { + let tree = Tree::new(); + let cache = tree.path("cache"); + fs::create_dir_all(&cache).unwrap(); + let stale = cache.join("index-cache-mcp.4242.tmp"); + let young = cache.join("index-cache-mcp.4343.tmp"); + let other = cache.join("index-cache-mcp.notes.tmp"); + for file in [&stale, &young, &other] { + fs::write(file, "torn").unwrap(); + } + let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600); + for file in [&stale, &other] { + fs::File::options().write(true).open(file).unwrap().set_modified(hour_ago).unwrap(); + } + let mut server = Session::spawn(&[ + "--root", + tree.0.to_str().unwrap(), + "--index-cache", + cache.to_str().unwrap(), + ]); + server.initialize(); + server.text("list_units", json!({})); + drop(server.stdin.take()); + server.child.wait().unwrap(); + assert!(cache.join("index-cache-mcp").is_file()); + assert!(!stale.exists(), "an hour-old temp store is a dead writer's"); + assert!(young.exists(), "a young one may be a live writer's"); + assert!(other.exists(), "only `..tmp` is ours to sweep"); +} diff --git a/docs/features/mcp-cache-and-census/README.md b/docs/features/mcp-cache-and-census/README.md index 0aaf281..4f89e80 100644 --- a/docs/features/mcp-cache-and-census/README.md +++ b/docs/features/mcp-cache-and-census/README.md @@ -214,6 +214,8 @@ two flagged edits (`rpc.rs` wiring beyond `INSTRUCTIONS`; `tests/qa_m4.rs`). +3 wire), ignored 2 → 3 (the opentitan timing test); workspace 4 846 → 4 858. +**2026-09-23 (dev, feedback-1).** QA finding 2 fixed: `write_own` first removes `index-cache-mcp..tmp` files older than 10 minutes (a younger one may be a live writer's); `qa_an_orphaned_temp_file_is_swept_by_the_next_write` un-ignored. `INSTRUCTIONS` revised (896 characters) — `docs/features/mcp-feedback-1`. + ## QA log **2026-09-23 (QA, Opus) — QA — interrupted** (the session was cut off before the workspace gate finished; everything below was run and is recorded as measured). diff --git a/docs/features/mcp-edit-tools/README.md b/docs/features/mcp-edit-tools/README.md index 8596759..7a0900f 100644 --- a/docs/features/mcp-edit-tools/README.md +++ b/docs/features/mcp-edit-tools/README.md @@ -397,6 +397,8 @@ as skipped (finding 7, un-ignored). Cost of the walk on opentitan `hw/`: ≈140 ms per edit call, against the 1.6–2.6 s the whole-set read already costs. Gates re-run by the lead through `tools/guard.sh`. +**2026-09-23 (dev, feedback-1).** `rename`, `remove_port` and `add_port` add one `warnings:` entry listing the name's unresolved textual mentions, and `unresolved_mentions` to their JSON (handshake change); `add_port` takes `after` (placement re-done on the MCP side, verified against the engine's appending edit, `src/tools/place.rs`); `remove_port` no longer goes through `at_cursor` — `docs/features/mcp-feedback-1`. + ## QA log **2026-09-23 (QA, M3). Verdict: FAIL — two blocking findings (1 in diff --git a/docs/features/mcp-feedback-1/README.md b/docs/features/mcp-feedback-1/README.md new file mode 100644 index 0000000..95c1bd4 --- /dev/null +++ b/docs/features/mcp-feedback-1/README.md @@ -0,0 +1,433 @@ +# mcp-feedback-1 + +Lane **feedback-1** of the MCP block: the changes the first token-census +round asked for (`mcp_analysis.md`, Round 1 → "Changes for round 2"). +Tracked in `TODO-MCP.md` → "Feedback rounds". + +## Goal + +Round 1 showed that `lucisv-mcp`'s answers were correct but not complete +enough, and not discoverable enough, to beat plain file tools: a rename left +a DV force-path string and a macro-rooted probe behind without a word, the +census agent asked `references` for "who instantiates X" instead of +`hierarchy up`, `add_port` could not place a port where the task wanted it, +and the tool catalogue cost every session ~7 500 tokens before any work. +This lane makes the answers say what the engines could not see (unresolved +mentions), points the agent at the right tool (descriptions and +instructions), makes a positioned port insertion one verified call +(`add_port`'s `after`), cuts the catalogue by 40 %, and sweeps the orphaned +temporary store M6 QA found. + +## Assumptions + +- **What a mention is.** A whole-word spelling of the name (not glued to an + identifier character on either side, `source::word_in`) that lies in: a + comment (every token's `leading`/`trailing` trivia), a `String` token, a + macro call's text after the macro's own name (every word — arguments, + strings and comments inside them alike), a `` `define`` body after the + macro name and formal list (a define whose formals spell the name is + skipped: the formal shadows it), or an identifier ending a dotted path + whose head is a macro token (`` `X_HIER.u_a[0].name``, `` `SPI(1).u.name``). + A file that does not lex lists every spelling as `text`. Plain + identifiers elsewhere are never mentions: they belong to some declaration + the engines resolve (another module's own `state_q` is not noise here). + `` `ifdef name`` and attributes are not searched. +- **Accounted for.** A spelling inside a span the engine returned — + `references`' hits, or any edit range of the rename/`remove_port`/ + `add_port` edit — is not a mention. The engines' own macro warnings + (rename's "appears in the arguments of…") still appear; the mentions list + repeats those sites, deliberately: it is the one complete list. +- **Why not `macro_spellings`.** `item/macros.rs::macro_spellings` answers + "is this identifier used here", so it skips strings inside macro text + (`` `define P ".state_q"``) — exactly the round-1 miss. The mentions + scanner word-searches the raw macro/define text instead. +- **Order and cap.** Listed nearest first: files the engine touched, then + lines spelling the declaring unit's name (catches `u_` on a macro + path), then by how many leading path components the file shares with the + declaration's file; file and line within. One mention per line. At most 50 + (`mentions::CAP`), then `… and N more`; lines capped at 160 characters. + On opentitan `state_q` (entropy_src main_sm) the three round-1 sites are + lines 1, 2 and 4 of 415. +- **Cost.** No new reads: the engines already hold every indexed file's text + (`WholeSet`). Each text is `str::contains`-filtered; only a text spelling + the name is lexed. The index word censuses (`files_mentioning`, + `files_naming_in_macros`) cannot narrow further — comments and strings are + not in them — so they are not used. Measured on the eval clone + (`~/.cache/lucisv-eval/ot/hw`, 3 944 files, release builds, same session + warm, two runs each), r1 binary → this lane: + | call | r1 | feedback-1 | mentions | + |---|---|---|---| + | `references` `state_q` (entropy_src_main_sm.sv:42) | 1.98 s | 2.04–2.09 s | 415 (50 listed) | + | `references` `clk_i` (aes_core.sv:30) | 2.37–2.39 s | 2.60–2.69 s | 50 listed | + | `rename` `state_q` dry run | 2.17–2.24 s | 2.34–2.39 s | 415 (50 listed) | + i.e. +0.06–0.3 s on a 2–2.7 s whole-set call. +- **`references` paging.** The section is on the first page only + (`offset` 0); later pages repeat nothing. +- **Descriptions.** `tools/list` measured as the compact JSON of the + `result` object: **30 221 B before, 17 981 B after** (−40.5 %). Tool + descriptions 9 095 → ~2 700 B, argument descriptions 7 621 → ~2 500 B, + `annotations.title` dropped (it repeated `title`). Every argument keeps a + description. The position rules left the descriptions for `INSTRUCTIONS` + (896 characters, under qa_m6's 900 cap). +- **Temp sweep.** Before writing its store, `cache::write_own` removes + `index-cache-mcp..tmp` files older than 10 minutes + (`STALE_TEMP`); a younger one may be a live concurrent writer's, and no + other file is touched. + +### `add_port` `after` — exactly what happens + +`vlog_refactor::add_port` only appends (header and connections), so it runs +first, unchanged; its verified edit is the reference. `tools/place.rs` then: + +1. **Header** (MCP side). The module's ANSI port named `after` is the + anchor; its index counts **every** element of the list, as + `ListDirective::before` does. Refused, in this order: a non-ANSI/empty + list; an unknown `after` (the ports are named); an anchor inside an + `` `ifdef`` arm; a list holding an element the parser could not read + (`(* keep *) b` — its text is named; lucisv cannot see what it + inherits); a next port that would inherit from the new one — no + direction and no type (inherits both), or a type but no direction when + the new port's direction differs from the anchor's (a modport port, + `bus_if.mp bus`, has no direction to inherit and is placed after). The + engine's header edits (those inside the port list's parens) are dropped + and the new element goes into the **slot after the anchor's separator** + (`place/slot.rs`), never at the anchor's end: + - anchor followed by `,` and the next element starting a later line: + a new line at the end of the comma's line (past a comment on it, and + past a block comment that closes on a later line), `element,`; + - `,` with the next element on the same line (`a, b`, a leading-comma + list ` , input c`): ` element,` right after the comma; + - a last anchor with `)` starting a later line: `,` at the anchor's end, + a new line at the end of the anchor's line (past its comments); + - a last anchor with `)` on its line: `, element` at the anchor's end, + or — a comment between — `,` at the anchor's end and ` element` + before the `)`. + A new line takes the anchor's line ending (CRLF kept); when the anchor + is alone on its line, its indentation and column layout (direction, + type, name at the anchor's columns when they fit), else the next + element's indentation and the declaration on one line. +2. **Connections.** For each instance of the module that the engine gave a + connection edit: a positional list is refused unless `after` is the last + port (then the engine's appended connection stands); a list holding an + unreadable element is refused (its text named); a named list whose + `.after(…)` sits outside any `` `ifdef`` arm (full-list index) gets the + engine's expression (read back from its appended `.port(expr)`, + `/* TODO: connect */` included) in the same slot after `.after(…)`'s + separator, aligned (`(` and `)` at the anchor's columns when they fit) + or inline. Otherwise the engine's appended connection stands and a + warning names the instance (root-relative) and why. +3. **Verification** (`place/verify.rs`, the refusal names the failed + check): the placed edit applied must, file by file, be the engine's + result with elements moved: the same sorted multiset of tokens (kind + + text); every comment attached to the same identifier — the nearest one + before it for a comment on its token's line (a `,` is never an anchor), + the nearest one after it for a comment on lines of its own; no more + parse diagnostics; the module's port list with **every** element + (unreadable ones by text) in the engine's order with the new port moved + after `after`, each port's declaration text (blanks collapsed) the + engine's, and the port after the new one not inheriting from it; every + instance's connections the same (named: sorted `name(expr)` with blanks + squeezed; positional: in order; unreadable elements by text). Then the + one write path, `apply::run`. + +## Handshakes + +- **Consumed:** `vlog_parser::{tokenize, parse_source_tolerant, LineIndex}`, + AST port/instance types; `vlog_refactor::{add_port, remove_port, rename, + find_references, rename_name_at, enclosing_module, module_definition, + RefactorEdit, TextEdit}`; `apply::Plan::from_refactor` (applies and + checks edits, used as-is by `place::verify`). +- **Promised (answer shapes):** `references` text gains the section + `unresolved mentions (strings, comments, macro text — not resolved by + lucisv):` with ` file:line kind: text` lines; `rename`, `remove_port` + and `add_port` gain one `warnings:` entry — "`` as text at these + places lucisv does not resolve (strings, comments, macro text; N in all); + check whether these are references:" with the same lines indented four. + All four add `"unresolved_mentions": [{file, line, text, kind}]` to their + JSON (empty when none); `kind` ∈ `comment`, `string`, `macro`, `define`, + `path`, `text`. `add_port` takes `after`. `tools/list` no longer carries + `annotations.title`. +- **Flag for the lead (ownership):** `src/tools/place.rs` is a new file not + in the lane's list — `refactor.rs` would have gone from 291 to ~770 lines + with it. It is only used by `refactor.rs`. The rework split it into + `place.rs` (driver and refusals), `place/slot.rs` (where and how an + element is written) and `place/verify.rs` (the move-checker), all new. +- **Mentions after an edit** (QA finding 4): `finish_telling` runs the + mentions pass on the texts as written (the plan's new text for an edited + file, the read text otherwise), with the edit's ranges shifted into the + written text, so `file:line` names the file as it is after the write — + and, for a dry run, the diff's new side. + +## Status / TODO + +- [x] `src/tools/mentions.rs` — the scanner, ranking, rendering +- [x] `references` section + JSON; `rename`/`remove_port`/`add_port` + warning + JSON (`edit::finish_telling`) +- [x] descriptions and `INSTRUCTIONS` (hierarchy/references wording; ≤ 18 kB) +- [x] `add_port` `after` (`src/tools/place.rs`), with attack tests on its + verifier +- [x] stale temp-store sweep; `qa_an_orphaned_temp_file_is_swept_by_the_next_write` + un-ignored +- [x] wire tests (mentions on `references`/`rename`, `after` byte-exact on an + `aes_core`-shaped fixture, last-port and unknown-anchor, catalogue + size, sweep) +- [x] opentitan cost measured (above) + +## Work log + +**2026-09-23 (dev, Opus).** + +- `mentions.rs` (212 production lines): `find` over the `WholeSet` texts, + `spellings` per file (comments, strings, macro text, define bodies, + macro-rooted paths), ranking, `Mentions::{lines, json, warning}`. +- `nav.rs`: `references` computes mentions before handing texts to + `Texts`; the section follows the hits; `unresolved_mentions` in JSON. +- `edit.rs`: `finish_telling` (accounted = the edit's ranges); `rename` + and `remove_port` (no longer through `at_cursor`) use it. +- `refactor.rs`: `add_port` takes `after`, resolves the module's file + (`module_definition` or the given file), runs `place::after`, and + finishes through `finish_telling` with the new port's name. +- `place.rs` (479 production lines): see "exactly what happens" above. + Decision: re-placing the engine's verified edit and verifying the moved + result against it, rather than asking for an engine change — no + Handshake on `vlog_refactor` needed. +- Descriptions: all 26 rewritten; `mod.rs` drops `annotations.title`. + 30 221 → 17 981 B. +- `cache.rs`: `sweep_stale_temps` before each own-store write. +- Tests: unit tests in `mentions.rs` (4) and `place.rs` (6, three of them + attacks/refusals on the verifier); 7 wire tests; fixture + `tests/fixtures/feedback/`. + +**2026-09-23 (dev, Opus) — rework on the QA verdict and the lead's +rulings.** All six `qa_f1` tests un-ignored; none contradicted a ruling +(5b's expects the `ifdef` refusal for an anchor inside an arm next to an +unreadable element, so the arm is checked before the unreadable-element +refusal — both refuse). +- **5 (blocking)**: `place.rs` `header` refuses a port list with an + unreadable element (named), after the `ifdef` check; `after` refuses an + affected instance whose connection list holds one; `balanced_before` is + handed full-list indices on both sides; `verify` compares the whole port + list, unreadable elements by text, each port as `name: declaration` + (blanks collapsed) against the engine's — the type-swap pair is a unit + test (`place/verify.rs`), refused. +- **1 (major)**: insertion moved to the slot after the separator + (`place/slot.rs`, unit-tested on `a /* about a */,`, a leading-comma list, + a last port with a block comment, a block comment spanning the comma's + line, CRLF); `verify` pairs each comment with its identifier (attacks: a + comment glued to the anchor's comma, a leading-comma list, the anchor + line's comment taken by the new line). Deviation from the ruling's + letter, for the reason: the ruling pairs every comment with its + *preceding* token; for a comment on lines of its own that would forbid + the placement round 1 asked for (`rst_ni,` ⏎ blank ⏎ `// Data` ⏎ + `data_i` — the new port goes right after `rst_ni`, so `// Data`'s + preceding name changes although it still sits above `data_i`). Such a + comment is paired with the identifier after it instead; a same-line + comment with the one before it (never a `,`). Both catch QA's attacks. +- **2**: every file `place.rs` names goes through `Spec::show` + (`project.relative`). +- **3**: `inherits`: no direction and no type → inherits both (refused); + a type but no direction → inherits the direction, refused only when the + new port's direction differs from the anchor's; a modport type + (`x.y`) → never. Stricter than the ruling's "both absent" in one case + (`output logic a, logic [3:0] b` with a new `input`: `b` would turn + input), unit-tested. +- **4**: `edit.rs::finish_telling` scans the written texts; + `mentions::find` now takes `(path, text)` pairs; `written_ranges` shifts + the edit ranges. + +## QA log + +**2026-09-23 (QA, Opus) — verdict: REWORK (1 blocking, 1 major, 3 low).** +Attacks in `crates/lucisv_mcp/tests/qa_f1.rs` (real binary over scratch +trees; placements byte-exact, refusals with the tree byte-identical under +`dry_run` and for real): 11 pass, 6 `#[ignore = "QA finding N"]` pin the +findings below (each fails today, run with `--ignored`). + +Verified, holds: +- `after` byte-exact on: an anchor with a `//` comment on its line (stays + there), the last port with a trailing `/* */` (comma before the comment, + the new line has none), tab indentation, CRLF (kept on the new line), + one-per-line aligned connections, two instances in one statement, an + instance in a generate block, an instance in the module's own file + (`file`+`line` selector), a positional instance with `after` = last + (appended) and elsewhere (refused, nothing written), an anchor just + before and just after an `` `ifdef`` arm (placed outside), an anchor in + an arm (refused), a parameter as `after` (refused, ports listed), a + connection anchor in an arm (engine's append kept, warning names the + instance), `.*` instances (the engine's warning; nothing placed), the + same call twice (engine refuses, nothing written). `dry_run`'s diff, + applied to the old text, is byte-for-byte what the real run writes (for + `after` = first, middle, last). +- Mentions: a hierarchical path in a comment, a string inside a macro's + arguments, a `` `define`` body listed and a `` `define`` with the name + as formal not, a macro-rooted path through `[2]`, an escaped `\name` in + a comment, `state_q_d`/`xstate_q`/a path ending in `state_q_d`/the name + as an index not listed; CRLF line numbers right and no `\r` in the + text; JSON keys exactly `file, kind, line, text`; `offset` > 0 has no + section and `[]`; the cap (60 far mentions + the edited file's: 50 + listed, edited file first, "65 in all", "… and 15 more"); a renamed + file's hits excluded and its other mentions kept. opentitan (eval clone, + release, through the shim): `references clk_i` at aes_core.sv:30 — + r1 4.00 s / 4.00 s, feedback-1 4.21 s / 4.22 s (+0.21 s, within the + recorded +0.06–0.3 s); 801 mentions, 50 listed; the clone left clean. +- Catalogue: `tools/list` 17 981 B (≤ 18 000), 26 tools, every argument + described, no argument lost against HEAD (only `after` added; checked + per file by `git show HEAD:`), `title` kept at tool level and absent + from `annotations`, the three hints booleans; `instructions` 896 chars, + every `snake_case` word it names is a tool (bar `dry_run`). +- Sweep: an hour-old `index-cache-mcp.1.tmp` goes; `..tmp`, `.12a.tmp`, + `.12.tmp.bak`, `index-cache.12.tmp`, `xindex-cache-mcp.12.tmp` (all an + hour old) and an old *directory* `index-cache-mcp.77.tmp` stay; the own + store is still written (plus the dev's young-file test). + +Findings: + +1. **Major — a comment re-attached to the new port, forgiven by the + checker.** An anchor whose comment sits between it and its comma + (`input logic a /* about a */,`), or on its line before a leading-comma + next element (`input logic b // about b` ⏎ `, input logic c`), is not + "alone on its line", so `inline` inserts at the anchor's *end* + (place.rs:173, :256): `input logic a, input logic en /* about a */,` and + `.a (a), .en(en) /* conn a */,` — the comment now documents `en`. + `verify` compares comment texts as a sorted multiset (place.rs:529–540), + so the move passes. Repro: + `qa_a_comment_between_the_anchor_and_its_comma_stays_with_the_anchor`. + Fix: insert `, element` at the start of the token after the anchor when + it is `,` or `)` (past the trivia), else at the anchor's end; and in + `verify`, compare each comment paired with its preceding non-`,` token. +2. **Low — absolute paths.** The warnings and refusals `place.rs` writes + use `path.display()` (place.rs:84, :221): + `` `u_n` in /private/var/…/rtl/top.sv: the connection … ``; every other + answer is root-relative. Repro: `qa_place_names_files_relative_to_the_root`. +3. **Low — false refusal.** A modport port after the anchor + (`bus_if.mp bus`) has no direction and inherits none, but place.rs:155 + refuses "takes its direction and type from the port before it". Repro: + `qa_a_modport_port_after_the_anchor_does_not_refuse`. (A bare + `bus_if bus` is ambiguous with a type; refusing that one is right.) +4. **Low — stale mention lines after a write.** `finish_telling` + (edit.rs, the `mentions::find` over `set.files`) lists mentions with the + *pre-edit* line numbers; after a real `add_port` (lines added), + `remove_port` (removed) or a `rename` that writes out `.*` bindings, a + mention below the edit in an edited file names the wrong line + (`rtl/m.sv:6 comment: // en gates y` — line 6 is now `);`). Repro: + `qa_mention_lines_name_the_file_as_written`. Fix: shift each mention by + the net newlines the file's edits insert before its offset, when not a + dry run. +5. **BLOCKING — an unreadable port-list element defeats the placer and the + checker (masked corruption, written to disk).** `place.rs` reads the + header through `ListElem::ok` (`ansi_ports`, place.rs:128–133) and so + does `verify` (`ports_in_order`, place.rs:542–564). An element the + parser could not read — `(* keep *) b`, legal SV, an attribute on a + port — is invisible to both: + - a) `input logic [7:0] a,` ⏎ `(* keep *) b,` with `after: "a"`: + the new `input logic en` lands between them, so `b` now inherits + `input logic` — **8 bits become 1** — and it is written (same tokens, + same parse-error count, same well-formed port order). Repro: + `qa_a_port_hidden_by_a_parse_error_does_not_change_its_inherited_type`. + - b) `balanced_before` gets the anchor's index among the *well-formed* + elements, but `ListDirective::before` counts all of them + (place.rs:161; the connection side has the same shape at :241–244). + With `(* keep *) input logic d` before an `` `ifdef X`` arm, `after: "b"` + (inside the arm) passes: the port is written **inside the arm** while + the connection is unconditional, and the engine's warning in the same + answer says it was added "outside every conditional arm". Repro: + `qa_an_unreadable_element_does_not_let_an_anchor_in_an_ifdef_arm_through`. + Fix: refuse `after` when the port list (or the anchor instance's + connection list) holds any `ListElem::Error`, or index the raw list + everywhere (the anchor's raw index for `balanced_before`, the raw next + element must be `Ok` with a direction). `verify` should re-derive the + same on the placed tree with raw indices, and compare each port's + declaration text (blanks squeezed) by name with the engine's: today a + crafted `input logic [7:0] a, input logic en` → + `input logic a, input logic [7:0] en` (a type swapped between the + anchor and the new port) has the same tokens, names in order, parse and + connections, and `verify` would accept it. These attack pairs belong in + `place.rs`'s unit tests next to `verify_refuses_a_placement_that_is_not_a_move` + (`verify` is private; QA cannot reach it from `tests/`). + +Observations (no test; for the lead): +- Layout: a multi-line anchor (`input logic` ⏎ `[7:0] e,`) measures its + name column across the newline (place.rs:339), so the new line's name is + pushed far right. Cosmetic. +- Ranking ignores kind: 60 comments in one file push that file's + macro-rooted path — the round-1 miss class — past the cap. Ranking + `path`/`string`/`define`/`macro` above `comment` within a rank would keep + the valuable ones listed. +- Out of lane (engine / parser, pre-existing): `vlog_refactor::add_port` + appends a connection *inside* an `` `else`` arm when the list's tail is + conditional (`.y ()` ⏎ `` `endif``); the parser reads `(* attr *)` on an + ANSI port as an error element (`after: "d"` answers "no port `d`"); the + unified diff re-lists unchanged lines as `-`/`+` near a file end without + a final newline. + +Gates (all through `tools/guard.sh`): +- `cargo fmt --all -- --check` — exit 0, no output. +- `cargo clippy --all-targets` — ``Finished `dev` profile [unoptimized + debuginfo] target(s) in 6.96s``, no warnings. +- `cargo test -p lucisv_mcp` — 347 passed, 0 failed, 9 ignored (qa_f1: `test result: ok. 11 passed; 0 failed; 6 ignored`). +- `cargo test --workspace` — 4 903 passed, 0 failed, 56 ignored (4 892 + 11). + +**2026-09-23 (QA, Opus) — re-check of the rework: PASS** (findings 1–5 +closed; one new low, finding 6, left for the lead). + +Re-derived by hand over stdio (the eval shim `mcp_call.sh` on the debug +binary, scratch trees): 5a `(* keep *) b` after an 8-bit `a` — refused, +"`m`'s port list holds `(* keep *) b`…; nothing written", both files +byte-identical (md5); 5b anchor `b` inside the arm behind an unreadable +`d` — refused "inside an `ifdef arm", and `after: "a"` in the same list +refused by the unreadable-element rule; 5c the type swap cannot be built +through the tool (the placer writes the declaration verbatim), so +confirmed as the unit test +`place::verify::tests::a_type_swapped_between_the_anchor_and_the_new_port_is_refused` +(passes); 1 `a /* about a */,` → the new line below it, the comment on +`a`'s line; `.a (a) /* conn a */,` likewise; `b // about b` ⏎ +`, input logic c` → `, input logic en, input logic c`. The six pinned +tests (findings 1–5) pass un-ignored and unchanged. + +New attacks (`qa_r_*` in `tests/qa_f1.rs`, all byte-exact or tree +byte-identical): an unreadable connection (`..q (p)`) in another module's +instance and in an untouched `.*` instance of `m` — placed, not refused; +in the instance placed into — refused, named `rtl/top.sv`; own-line +comments above the last anchor and closing the list — both stay, header +and connections; `a /* c1 */, // c2` — the new line goes below, both +comments on `a`'s line; a last anchor with `/* c */` before `)` on its +line — `y, /* c */ input logic en)`; a leading-comma list; a typed +undirected `logic [3:0] b` after the anchor — placed under `input`, +refused under `output` (nothing written); a rename writing out a `.*` +binding (one line added above the mentions) — each listed line is the +line on disk after the write (off-by-none). + +6. **Low — dry-run mention lines name a file that is not on disk.** The + rework computes mentions on the texts as they would be written, under + `dry_run` too: in the `.*` rename above, the dry run lists + `rtl/top.sv:6 comment: // a feeds u_m`, and line 6 on disk is the + `$display` (the comment is at 5 until the edit is written). The text is + shown beside the line, so an agent can recover; but a dry run's diff + and lines otherwise describe the file on disk. Repro: + `qa_r_dry_run_mention_lines_name_the_file_on_disk` (ignored). Either use + the pre-edit lines under `dry_run`, or say "lines as written" in the + warning — the lead's call. + +Gates (all through `tools/guard.sh`, one at a time): +- `cargo fmt --all -- --check` — exit 0, no output. +- `cargo clippy --all-targets` — ``Finished `dev` profile [unoptimized + debuginfo] target(s) in 3.21s``, no warnings. +- `cargo test -p lucisv_mcp` — 362 passed, 0 failed, 4 ignored (unit: `test result: ok. 73 passed`; qa_f1: `test result: ok. 22 passed; 0 failed; 1 ignored`). +- `cargo test --workspace` — 4 918 passed, 0 failed, 51 ignored (4 913 + 5 new). + +## Review + +**Lead, 2026-09-24 (feedback-1).** The first census round's lesson was +discoverability and completeness of what the server *says*, not the +correctness of what it answers, and this lane changes exactly that: an +"unresolved mentions" section on `references` and the edit tools (the DV +string path round 1 missed is now line 4 of the list on opentitan), a +catalogue 40 % smaller, `hierarchy`/`references` descriptions that route +"who instantiates X" to the right tool, and a positioned `add_port`. The +last is the one piece of new text-moving logic, and QA's first round found +the classic hole — an unreadable port element the placer could not see, so +the next port inherited the new one's type — fixed by refusing any list +with an unreadable element, full-list positions, and a checker that +compares every port's declaration text and pairs each comment with its +anchoring name. Ruling on QA's finding 6: under `dry_run` the mention line +numbers describe the file as it would be written; the line text beside +each number is the recovery, and the wording stays. Committed; the round-2 +binary is frozen from this commit. diff --git a/docs/features/mcp-navigation/README.md b/docs/features/mcp-navigation/README.md index febd358..245f4f1 100644 --- a/docs/features/mcp-navigation/README.md +++ b/docs/features/mcp-navigation/README.md @@ -433,6 +433,8 @@ passed, `opentitan` 1 ignored, `qa_m1` 51 passed, `qa_m2` 32 passed, `wire` 19 passed; `cargo test --workspace` exit 0 in 254 s, **4 599 passed, 0 failed, 47 ignored**. +**2026-09-23 (dev, feedback-1).** `references` now ends with an `unresolved mentions` section and carries `unresolved_mentions` in its JSON (handshake change: a new trailing section and a new JSON key; hits unchanged); `references`/`definition`/`hierarchy` descriptions trimmed, `hierarchy` leads with "who instantiates a module" — `docs/features/mcp-feedback-1`. + ## QA log **2026-09-23 (QA, M2). Verdict: rework needed** — four blocking findings diff --git a/mcp_analysis.md b/mcp_analysis.md new file mode 100644 index 0000000..9f1de99 --- /dev/null +++ b/mcp_analysis.md @@ -0,0 +1,125 @@ +# mcp_analysis.md — does lucisv-mcp help an agent? (the token census) + +Owner's brief (2026-09-23): after the MCP block is complete, run the server +against the OpenTitan tree, have sub-agents do real edits with and without +it, compare the token usage, feed what is learned back into the server, and +repeat for at least three rounds. This file is the record. It is written by +the lead; numbers are measured, not asserted. + +## Method + +**Harness.** `~/.cache/lucisv-eval/` (durable, outside the volatile session +scratchpad): a local clone of OpenTitan (`ot/`, `0098135`), the three task +prompts (`tasks/{a,b,c}.txt`), the frozen server binary per round +(`bin/lucisv-mcp-r`), and a stdio shim (`mcpc ''`, +`mcpc --list`) that runs one MCP session per call. Why a shim and +sub-agents rather than a headless `claude -p --mcp-config` session: the +`claude` CLI on this machine has an expired OAuth session that only the +owner can renew, and the lead's own agent harness cannot attach a new MCP +server mid-session. The shim costs the agent the same tokens a native tool +result would (the answer text lands in its context either way); what it +loses is the persistent process (each call re-indexes, ~1–2 s) and the +tool-schema exposure a host gives natively (the agent reads `--list` once +instead). + +**Arms.** For each task, one sub-agent per arm, same model, same prompt +text, same clean clone (`git checkout -- . && git clean -fdq` before every +run), one agent at a time: + +- **base** — ordinary file tools and search (`rg`), no lucisv binaries; +- **mcp** — the same, plus the shim and one paragraph telling it which + tools to prefer (the server's own `instructions`, paraphrased). + +**Model.** Claude Sonnet 5 for the arms (cost); one Opus 5.5 confirmation +run on the hardest task in the last round if the budget allows. The lead +grades. + +**Metrics per run.** Tokens (the harness's total for the sub-agent, input +plus output across all its turns), tool calls, wall time, and the outcome +graded against a lead-computed ground truth: + +- **a** (read-only census): set equality with `results/truth_a.txt` — the + 47 RTL instantiations of `prim_fifo_sync` under `hw/ip/` with their + `Width`/`Depth` overrides, computed with `hierarchy up` and checked by + hand against the files (DV, FPV, `ip_templates` and `top_*/ip_autogen` + excluded by the task's wording); +- **b** (two-file port propagation): the diff touches exactly + `aes_cipher_core.sv` and `aes_core.sv`, adds `input logic dbg_i` after + `rst_ni` in both, and connects `.dbg_i(dbg_i)` on the instance; both files + parse (`diagnostics`); style matches the neighbours; +- **c** (cross-file rename): the seven sites in `results/truth_c.txt` are + renamed — five the engine sees, plus a macro-argument use + (`` `PRIM_FLOP_SPARSE_FSM(…, state_q, …) ``) and a macro-rooted + hierarchical path in `top_earlgrey/dv/env/chip_if.sv` — and none of the + csrng/edn `state_q` sites move; +- **hygiene**: any file touched outside the task is a failure. + +**Rounds.** After each round the mcp-arm transcripts are read for tool +misuse, refusals the agent could not recover from, and answers it had to +re-derive by reading files anyway; each becomes a change to the server +(descriptions, `instructions`, rendering, a missing tool, a bug) through a +dev+QA lane, the binary is re-frozen, and the round repeats. + +## Round 1 — server at 0f4830a (M1–M6 as committed) + +| task | arm | tokens | tool calls | wall | outcome | +|---|---|---|---|---|---| +| a | base | 91 094 | 10 | 114 s | correct, 47/47 | +| a | mcp | 107 605 | 14 | 335 s | correct, 47/47 | +| b | base | 59 922 | 11 | 25 s | correct, clean | +| b | mcp | 74 720 | 17 | 78 s | correct, identical diff | +| c | base | 87 546 | 34 | 172 s | correct, 8/8 sites | +| c | mcp | 104 837 | 35 | 171 s | **incomplete**, 7/8 sites | + +### Observations + +**The server did not pay for itself in round 1.** On every task the mcp arm +used more tokens than the base arm (+18 %, +25 %, +20 %), took longer, and +on the rename it was less complete. Sonnet with plain file tools is a +strong baseline on a tree this well organised: `rg` finds instantiations +and hierarchical paths by text, and reading a 1 000-line file is cheap +compared with a catalogue of 26 tool schemas plus several calls that each +re-index the tree through the shim. What the transcripts show: + +1. **Wrong tool for the census (a).** The agent asked `references` for the + module name — a whole-set engine call, ≈4 s per shim call — and then + read the instantiating files for the overrides. `hierarchy up` answers + the question in one call, instance names and `#(…)` overrides included; + nothing in the descriptions told the agent so. +2. **The catalogue is a fixed tax.** The shim's condensed `--list` is + 11.6 kB (≈3 000 tokens; the raw `tools/list` JSON a native host sends is + 30.3 kB, ≈7 500 tokens). Read once, it costs the mcp arm those tokens + before any work — on a 25-second task (b) that is most of the gap. +3. **Verified edits were not the bottleneck on b.** Both arms produced the + identical three-line diff; the mcp arm's extra calls were `diagnostics` + checks (useful, but they cost). `add_port` was not used: it appends a + port, and the task wanted a specific position with the file's alignment. +4. **The rename missed what no engine sees, and said nothing (c).** The + `rename` tool renamed five sites and warned about the macro argument + (the agent fixed it). It found the macro-rooted `chip_if.sv` path by + its own search. It never looked for the DV string `".state_q"` that + builds a force path, because nothing in the answer said "the old name + is still spelled in these files as text". The base arm's broad `rg` + found it. A rename that lists the unresolved textual mentions of the + old name — strings, comments, macro text, across the whole set — would + have handed the agent exactly that list. +5. **What worked:** every `dry_run`/`diagnostics` answer was trusted and + correct; the macro-argument warning was acted on; the line-length lint + finding on `chip_if.sv` was fixed by the agent (the base arm left a + 105-column line). Correctness of the server's answers was never the + problem; discoverability and completeness of *what it says* were. + +**Changes for round 2 (dev+QA lane "feedback-1"):** (i) `rename` and +`references` end with an "unresolved mentions" section — every whole-word +spelling of the name in strings, comments and macro text across the whole +set, as `file:line`, with the sentence that the engine did not resolve them; +(ii) `hierarchy`'s description leads with "who instantiates X — instance +names and parameter overrides", `references`' description points a module +name at `hierarchy up`, and `instructions` say the same in one line; +(iii) `add_port` takes an optional `after` port name so a positioned +insertion is one verified call; (iv) descriptions trimmed by about 40 % (30 kB → ≤ 18 kB of `tools/list` +JSON) — the catalogue is read by every agent on every session; (v) M6 QA's orphaned +temp-file sweep. The shim's per-call re-index is a harness artefact, not a +product one; a native host keeps the process alive, so wall time is not +graded. +