From c2e42b884027b845e1c58f672f5468dde6ad6575 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 23 Sep 2026 21:50:34 -0700 Subject: [PATCH] MCP feedback-2: the count line leads every paged answer, default limit 500, `in` path-glob filter on the listing tools, post-edit check hint; census round 2 written up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Census round 2 (mcp_analysis.md): with feedback-1 the rename task became complete (the unresolved-mentions list surfaced the DV string path) at a token cost inside the base arm's run-to-run variance; the port task was unchanged; the census task regressed — the agent chose `hierarchy up` (right) but paged the 77-row answer with a small limit and never read the trailing "… and N more". Fixes: every paged text answer opens with `N (showing a–b)` (JSON gains `shown`), DEFAULT_LIMIT 500; `list_units`, `search_symbols`, `references`, `hierarchy`, `diagnostics` and `defines` take `in`, a root-relative path glob (`*` within a component, `**` across, `?`; a bare directory means everything below it) applied before paging — `hierarchy up prim_fifo_sync` with `in: "ip/**/rtl/*.sv"` answers the census's 47 in one call; the six design-wide edits end with `check: diagnostics on `. Catalogue 17 993 B, instructions 896 chars. QA (Opus): 14 qa_f2 tests, four notes. Gates through tools/guard.sh: fmt, clippy, workspace 4 943 passed (+1 lead test). Co-Authored-By: Claude Fable 5.1 --- TODO-MCP.md | 23 + crates/lucisv_mcp/src/render.rs | 91 ++- crates/lucisv_mcp/src/rpc.rs | 2 +- crates/lucisv_mcp/src/tools/defines.rs | 85 +- crates/lucisv_mcp/src/tools/diagnostics.rs | 80 +- crates/lucisv_mcp/src/tools/edit.rs | 87 +- crates/lucisv_mcp/src/tools/hierarchy.rs | 100 ++- crates/lucisv_mcp/src/tools/nav.rs | 52 +- crates/lucisv_mcp/src/tools/read.rs | 177 ++++- crates/lucisv_mcp/src/tools/refactor.rs | 35 +- .../tests/fixtures/paths/ip/aes/dv/aes_tb.sv | 5 + .../fixtures/paths/ip/aes/rtl/aes_core.sv | 8 + .../fixtures/paths/ip/aes/rtl/aes_pkg.sv | 3 + .../paths/ip/uart/rtl/sub/uart_fifo.sv | 2 + .../tests/fixtures/paths/ip/uart/rtl/uart.sv | 8 + .../tests/fixtures/paths/lucisv.toml | 2 + .../tests/fixtures/paths/top/chip.sv | 7 + crates/lucisv_mcp/tests/qa_f2.rs | 750 ++++++++++++++++++ crates/lucisv_mcp/tests/qa_m1.rs | 52 +- crates/lucisv_mcp/tests/qa_m2.rs | 43 +- crates/lucisv_mcp/tests/wire.rs | 308 ++++++- docs/features/mcp-feedback-2/README.md | 312 ++++++++ docs/features/mcp-navigation/README.md | 2 +- docs/features/mcp-read-tools/README.md | 6 +- docs/mcp/PLAN.md | 2 +- mcp_analysis.md | 45 ++ 26 files changed, 2062 insertions(+), 225 deletions(-) create mode 100644 crates/lucisv_mcp/tests/fixtures/paths/ip/aes/dv/aes_tb.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/paths/ip/aes/rtl/aes_core.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/paths/ip/aes/rtl/aes_pkg.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/paths/ip/uart/rtl/sub/uart_fifo.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/paths/ip/uart/rtl/uart.sv create mode 100644 crates/lucisv_mcp/tests/fixtures/paths/lucisv.toml create mode 100644 crates/lucisv_mcp/tests/fixtures/paths/top/chip.sv create mode 100644 crates/lucisv_mcp/tests/qa_f2.rs create mode 100644 docs/features/mcp-feedback-2/README.md diff --git a/TODO-MCP.md b/TODO-MCP.md index 23d021f..c673911 100644 --- a/TODO-MCP.md +++ b/TODO-MCP.md @@ -343,6 +343,29 @@ Depends on M4 and M5 merged. - [x] QA: attack the mentions scanner (false positives and misses) and the `after` verifier; verdict +### Round 2 → lane feedback-2 (`docs/features/mcp-feedback-2`) + +- [x] paging header: every paged answer opens `N ` or + `N (showing a–b)`; `shown` in the JSON; `DEFAULT_LIMIT` 500; + `hierarchy up` from one root counts instantiations (`render.rs`, + the seven paging tools) — done 2026-09-23 (dev) +- [x] `in` path glob (`*`, `**`, `?`, root-relative, before paging) on + `list_units`, `search_symbols`, `references`, `hierarchy`, + `diagnostics`, `defines`; ``0 (none match `in`)`` + (`read.rs::path_match`) — done 2026-09-23 (dev) +- [x] post-edit line `check: diagnostics on …` (`check after writing:` on a + dry run) on `rename`, `add_port`, `remove_port`, `expand_wildcard`, + `extract_module`, `inline_module` (`edit.rs::with_check`) — done + 2026-09-23 (dev) +- [x] `INSTRUCTIONS` names `in` (896 characters); catalogue 17 993 B + (≤ 18 000) — done 2026-09-23 (dev) +- [x] wire tests (header cut and whole per tool, `in` per tool with `**`, + `?`, no-match and an escaped name, the check line); fixture + `tests/fixtures/paths/` — done 2026-09-23 (dev) +- [x] QA: attack the path matcher, the "none match" rule and the + `hierarchy` counting; verdict — PASS 2026-09-23 (QA, + `tests/qa_f2.rs`, 14 tests; four low notes in the QA log) + ## 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/render.rs b/crates/lucisv_mcp/src/render.rs index 44de364..866aede 100644 --- a/crates/lucisv_mcp/src/render.rs +++ b/crates/lucisv_mcp/src/render.rs @@ -5,15 +5,28 @@ //! about it, never once per line; //! - lines and columns are 1-based, a position is `line:col`, a range is //! `first-last`; -//! - lists are capped, the cap is said with `… and N more` and the caller can -//! page with `offset`; +//! - lists are capped and open with their total — `N units`, or +//! `N units (showing a–b)` when cut; a cut list also ends `… and N more`, +//! and the caller can page with `offset`; //! - no prose and no markdown headings: a label is a bare word and a colon, //! a table only where the columns are fixed. +use serde_json::{json, Value}; use vlog_semantic::SymbolKind; /// How many entries a list answer holds unless the caller says otherwise. -pub const DEFAULT_LIMIT: usize = 200; +pub const DEFAULT_LIMIT: usize = 500; + +/// What a list answer counts, singular then plural. +#[derive(Clone, Copy)] +pub struct Noun(pub &'static str, pub &'static str); + +impl Noun { + /// `n` of this noun: `1 unit`, `3 units`. + fn count(self, n: usize) -> String { + format!("{n} {}", if n == 1 { self.0 } else { self.1 }) + } +} /// A declaration kind as one lower-case word — the keyword that declares it /// where there is one. @@ -106,6 +119,58 @@ pub fn page(items: &[T], offset: usize, limit: usize) -> (&[T], usize) { (&items[start..end], items.len() - end) } +/// One page of a list: the entries shown, where they start, and how many +/// the whole list holds. +pub struct Page<'a, T> { + pub shown: &'a [T], + pub offset: usize, + pub total: usize, +} + +impl<'a, T> Page<'a, T> { + /// The window `offset..offset + limit` of `items`. + pub fn of(items: &'a [T], offset: usize, limit: usize) -> Page<'a, T> { + let (shown, _) = page(items, offset, limit); + Page { shown, offset: offset.min(items.len()), total: items.len() } + } + + /// How many entries follow the page. + pub fn rest(&self) -> usize { + self.total - self.offset - self.shown.len() + } + + /// The line a list answer opens with: the total first, so an agent that + /// stops reading when the list looks done still knows it was cut. + pub fn header(&self, noun: Noun) -> String { + let total = noun.count(self.total); + if self.shown.len() == self.total { + return format!("{total}\n"); + } + match self.span() { + Some((first, last)) if first == last => format!("{total} (showing {first})\n"), + Some((first, last)) => format!("{total} (showing {first}–{last})\n"), + None => format!("{total} (showing none: `offset` is past the end)\n"), + } + } + + /// The shown entries' 1-based positions, `[first, last]`; `[0, 0]` for + /// an empty page. + pub fn shown_json(&self) -> Value { + let (first, last) = self.span().unwrap_or((0, 0)); + json!([first, last]) + } + + fn span(&self) -> Option<(usize, usize)> { + let first = self.offset + 1; + (!self.shown.is_empty()).then(|| (first, self.offset + self.shown.len())) + } +} + +/// The whole text of a list the `in` path glob emptied. +pub fn none_match(noun: Noun) -> String { + format!("0 {} (none match `in`)\n", noun.1) +} + /// The line that says a list was cut, or nothing when it was not. pub fn more(out: &mut String, rest: usize) { if rest > 0 { @@ -224,6 +289,26 @@ mod tests { assert_eq!(out, "… and 2 more\n"); } + #[test] + fn a_page_opens_with_its_total_and_the_window_it_shows() { + const UNITS: Noun = Noun("unit", "units"); + let items: Vec = (0..77).collect(); + let cut = Page::of(&items, 0, 50); + assert_eq!(cut.header(UNITS), "77 units (showing 1–50)\n"); + assert_eq!((cut.rest(), cut.shown_json()), (27, json!([1, 50]))); + let last = Page::of(&items, 50, 50); + assert_eq!(last.header(UNITS), "77 units (showing 51–77)\n"); + assert_eq!(last.rest(), 0); + assert_eq!(Page::of(&items, 76, 5).header(UNITS), "77 units (showing 77)\n"); + let whole = Page::of(&items[..1], 0, 50); + assert_eq!(whole.header(UNITS), "1 unit\n"); + let past = Page::of(&items, 90, 5); + assert_eq!(past.header(UNITS), "77 units (showing none: `offset` is past the end)\n"); + assert_eq!((past.rest(), past.shown_json()), (0, json!([0, 0]))); + assert_eq!(Page::of(&items[..0], 0, 5).header(UNITS), "0 units\n"); + assert_eq!(none_match(UNITS), "0 units (none match `in`)\n"); + } + #[test] fn a_file_is_named_once_per_group() { let entries = vec![ diff --git a/crates/lucisv_mcp/src/rpc.rs b/crates/lucisv_mcp/src/rpc.rs index 48d27d9..c61f1f4 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 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."; +const INSTRUCTIONS: &str = "lucisv-mcp reads and edits the SystemVerilog design under its roots, from disk, never unsaved 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; `in` filters by path glob. Who instantiates module X (instances, overrides): hierarchy with direction up, not references. Every edit is verified, all-or-nothing, straight to disk, and names files for diagnostics; 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. 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 22cde7c..ef881b4 100644 --- a/crates/lucisv_mcp/src/tools/defines.rs +++ b/crates/lucisv_mcp/src/tools/defines.rs @@ -9,10 +9,13 @@ use std::path::{Path, PathBuf}; use serde_json::{json, Value}; use vlog_parser::defines::{Define, DefineKind}; +use super::read::{only_in, IN}; use super::source::{self, Texts}; use super::{Answer, Args, Param, Tool, Ty}; use crate::project::Project; -use crate::render::{self, DEFAULT_LIMIT}; +use crate::render::{self, Noun, Page, DEFAULT_LIMIT}; + +const DEFINES_NOUN: Noun = Noun("define", "defines"); /// A body longer than this many characters is cut, with `…`. const BODY_CAP: usize = 200; @@ -20,25 +23,17 @@ const BODY_CAP: usize = 200; pub const DEFINES: Tool = Tool { name: "defines", title: "Macro definitions", - description: "The `define table (name, parameters, body, file:line) of one `file`, one macro `name`, or all.", + description: + "The `define table (name, parameters, body, file:line) of a `file`, a macro `name`, or all.", params: &[ - Param { - name: "file", - ty: Ty::Str, - required: false, - description: "Only this file's table.", - }, - Param { - name: "name", - ty: Ty::Str, - required: false, - description: "Only this macro (backtick optional).", - }, + Param { name: "file", ty: Ty::Str, required: false, description: "Only this file." }, + Param { name: "name", ty: Ty::Str, required: false, description: "Only this macro." }, + IN, Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Max entries (default 200).", + description: "Default 500.", }, Param { name: "offset", @@ -60,29 +55,56 @@ struct Row { fn defines(project: &mut Project, args: &Args) -> Result { let name = args.str("name").map(|name| name.trim_start_matches('`')).filter(|n| !n.is_empty()); - let (rows, rest, total) = match args.str("file") { + let (rows, listing) = match args.str("file") { Some(file) => in_file(project, file, name, args)?, None => { - let mut all = indexed(project, name); + let select = |project: &Project| { + only_in(args, indexed(project, name), |(path, _)| project.relative(path)) + }; + let (mut all, mut emptied) = select(project); if all.is_empty() && name.is_some() && project.ensure_walked_for_miss() { - all = indexed(project, name); + (all, emptied) = select(project); } - let (shown, rest) = - render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); - (rows_of(project, shown), rest, all.len()) + let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + (rows_of(project, page.shown), Listing::of(&page, emptied)) } }; let entries: Vec<(String, String)> = rows .iter() .map(|row| (row.file.clone(), format!("{} {}", row.line, spelled(&row.define)))) .collect(); - let mut text = render::grouped(&entries); - render::more(&mut text, rest); - if total == 0 { - text = "no defines\n".to_string(); + let mut text = listing.header.clone(); + text.push_str(&render::grouped(&entries)); + render::more(&mut text, listing.rest); + if listing.total == 0 { + text = + if listing.emptied { render::none_match(DEFINES_NOUN) } else { "no defines\n".into() }; } let listed: Vec = rows.iter().map(row_json).collect(); - Ok(Answer { text, structured: json!({ "defines": listed, "total": total }) }) + let structured = json!({ "defines": listed, "total": listing.total, "shown": listing.shown }); + Ok(Answer { text, structured }) +} + +/// What an answer says about the page it shows, taken off a [`Page`] of +/// either form's list. +struct Listing { + header: String, + rest: usize, + total: usize, + shown: Value, + emptied: bool, +} + +impl Listing { + fn of(page: &Page, emptied: bool) -> Listing { + Listing { + header: page.header(DEFINES_NOUN), + rest: page.rest(), + total: page.total, + shown: page.shown_json(), + emptied, + } + } } /// One file's table as it is on disk now, filtered by `name`. @@ -91,7 +113,7 @@ fn in_file( file: &str, name: Option<&str>, args: &Args, -) -> Result<(Vec, usize, usize), String> { +) -> Result<(Vec, Listing), String> { let path = project.resolve(file)?; let analysis = project.analysis(&path)?; let shown_file = project.relative(&path); @@ -101,9 +123,10 @@ fn in_file( .iter() .filter(|define| name.is_none_or(|name| define.name == name)) .collect(); - let (shown, rest) = - render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); - let rows = shown + let (all, emptied) = only_in(args, all, |_| shown_file.clone()); + let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + let rows = page + .shown .iter() .map(|define| Row { file: shown_file.clone(), @@ -111,7 +134,7 @@ fn in_file( define: (*define).clone(), }) .collect(); - Ok((rows, rest, all.len())) + Ok((rows, Listing::of(&page, emptied))) } /// Every indexed definition (of `name`, when given), in file order. diff --git a/crates/lucisv_mcp/src/tools/diagnostics.rs b/crates/lucisv_mcp/src/tools/diagnostics.rs index c9e7cfc..7aa23e8 100644 --- a/crates/lucisv_mcp/src/tools/diagnostics.rs +++ b/crates/lucisv_mcp/src/tools/diagnostics.rs @@ -24,14 +24,16 @@ use vlog_linter::{ use vlog_parser::LineIndex; use vlog_semantic::{FileId, PackageExports, SymbolKind, WorkspaceIndex}; +use super::read::{in_glob, only_in, path_match, IN}; use super::{Answer, Args, Param, Tool, Ty}; use crate::project::{Analysis, Project}; -use crate::render::{self, DEFAULT_LIMIT}; +use crate::render::{self, Noun, Page, DEFAULT_LIMIT}; pub const DIAGNOSTICS: Tool = Tool { name: "diagnostics", title: "Diagnostics", - description: "Parse errors and lint findings (`line:col severity message [rule]`) of `file` or all files.", + description: + "Parse errors and lint findings (`line:col severity message [rule]`) of `file` or all.", params: &[ Param { name: "file", @@ -51,11 +53,12 @@ pub const DIAGNOSTICS: Tool = Tool { required: false, description: "Only this severity.", }, + IN, Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Most findings (default 200).", + description: "Default 500.", }, Param { name: "offset", @@ -96,33 +99,48 @@ fn diagnostics(project: &mut Project, args: &Args) -> Result { rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect() }); let mut runs = Runs::new(selected); - let mut findings = Vec::new(); - match args.str("file") { + let (mut findings, no_file) = match args.str("file") { Some(file) => { let path = project.resolve(file)?; let analysis = project.analysis(&path)?; let own = project.index().file_id(&path); let oracle = Mentions::of_file(project.index(), own); - findings = file_findings(project, &mut runs, &path, &analysis, &oracle)?; + (file_findings(project, &mut runs, &path, &analysis, &oracle)?, false) } - None => { - let census = Census::of(project.index()); - let paths: Vec = project.files().map(|(path, _)| path.clone()).collect(); - for path in paths { - let Ok(text) = std::fs::read_to_string(&path) else { continue }; - let analysis = Analysis::of(text); - let own = project.index().file_id(&path); - let oracle = Mentions { index: project.index(), census: Some(&census), own }; - findings.extend(file_findings(project, &mut runs, &path, &analysis, &oracle)?); - } - // Only a complete run knows a waiver matched nothing. - findings.extend(runs.unused_waivers(project)); - } - } + None => project_findings(project, &mut runs, in_glob(args))?, + }; if let Some(severity) = args.str("severity") { findings.retain(|finding| finding.severity == severity); } - Ok(render_findings(&findings, args)) + let (findings, emptied) = only_in(args, findings, |finding| finding.file.clone()); + Ok(render_findings(&findings, no_file || emptied, args)) +} + +/// Every indexed file's findings — only the files the `in` glob keeps, when +/// one is given — and whether the glob kept no file at all. +fn project_findings( + project: &Project, + runs: &mut Runs, + glob: Option<&str>, +) -> Result<(Vec, bool), String> { + let census = Census::of(project.index()); + let all: Vec = project.files().map(|(path, _)| path.clone()).collect(); + let kept = |path: &PathBuf| glob.is_none_or(|glob| path_match(glob, &project.relative(path))); + let paths: Vec = all.iter().filter(|path| kept(path)).cloned().collect(); + let mut findings = Vec::new(); + for path in &paths { + let Ok(text) = std::fs::read_to_string(path) else { continue }; + let analysis = Analysis::of(text); + let own = project.index().file_id(path); + let oracle = Mentions { index: project.index(), census: Some(&census), own }; + findings.extend(file_findings(project, runs, path, &analysis, &oracle)?); + } + // Only a complete run knows a waiver matched nothing: a filtered run + // does not say so. + if glob.is_none() { + findings.extend(runs.unused_waivers(project)); + } + Ok((findings, paths.is_empty() && !all.is_empty())) } /// The runs met so far in one call, one per governing config file — shared @@ -281,10 +299,13 @@ fn lint_finding(file: &str, lines: &LineIndex, violation: &Violation) -> Finding } } +const FINDINGS: Noun = Noun("finding", "findings"); + /// Findings grouped by file, paged; the JSON is the CLI's array shape. -fn render_findings(findings: &[Finding], args: &Args) -> Answer { - let (shown, rest) = - render::page(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); +/// `emptied` when the `in` glob removed everything there was. +fn render_findings(findings: &[Finding], emptied: bool, args: &Args) -> Answer { + let page = Page::of(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + let shown = page.shown; let entries: Vec<(String, String)> = shown .iter() .map(|f| { @@ -293,10 +314,11 @@ fn render_findings(findings: &[Finding], args: &Args) -> Answer { (f.file.clone(), line) }) .collect(); - let mut text = render::grouped(&entries); - render::more(&mut text, rest); + let mut text = page.header(FINDINGS); + text.push_str(&render::grouped(&entries)); + render::more(&mut text, page.rest()); if findings.is_empty() { - text = "no findings\n".to_string(); + text = if emptied { render::none_match(FINDINGS) } else { "no findings\n".to_string() }; } let listed: Vec = shown .iter() @@ -310,7 +332,9 @@ fn render_findings(findings: &[Finding], args: &Args) -> Answer { }) }) .collect(); - Answer { text, structured: json!({ "diagnostics": listed, "total": findings.len() }) } + let total = findings.len(); + let structured = json!({ "diagnostics": listed, "total": total, "shown": page.shown_json() }); + Answer { text, structured } } /// How many files write each word, and the first of them — the whole-project diff --git a/crates/lucisv_mcp/src/tools/edit.rs b/crates/lucisv_mcp/src/tools/edit.rs index 2c49634..07eec72 100644 --- a/crates/lucisv_mcp/src/tools/edit.rs +++ b/crates/lucisv_mcp/src/tools/edit.rs @@ -68,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`s of the scope at a position and sort the rest.", + description: "Remove unused `import`s in the scope at a position; sort the rest.", params: AT, rewalk: true, handler: organize_imports, @@ -76,7 +76,7 @@ pub const ORGANIZE_IMPORTS: Tool = Tool { pub const INLINE_MODULE: Tool = Tool { name: "inline_module", - title: "Inline a module instance", + title: "Inline an instance", description: "Replace one instance with its module's body, connections substituted.", params: AT, rewalk: true, @@ -86,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 instance leaves unconnected.", + description: "Connect by name every port one instance leaves unconnected.", params: AT, rewalk: true, handler: propagate_ports, @@ -96,7 +96,7 @@ pub const REMOVE_PORT: Tool = Tool { name: "remove_port", title: "Remove a port", description: - "Delete one port and its connection in every instantiation; refused while the body uses it.", + "Delete a port and its connection in every instantiation; refused while the body uses it.", params: AT, rewalk: true, handler: remove_port, @@ -104,8 +104,8 @@ pub const REMOVE_PORT: Tool = Tool { pub const RENAME: Tool = Tool { name: "rename", - title: "Rename a symbol", - description: "Rename a declaration and its references; select as `definition`. `.*`/`.name` bindings are written out; unresolved textual mentions are listed.", + title: "Rename", + description: "Rename a declaration and its uses; select as `definition`. Writes out `.*`/`.name` bindings, lists unresolved mentions.", params: &[ Param { required: false, ..FILE }, Param { @@ -136,7 +136,7 @@ pub const RENAME: Tool = Tool { }; fn expand_wildcard(project: &mut Project, args: &Args) -> Result { - at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated) + with_check(at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated), args) } fn convert_ports(project: &mut Project, args: &Args) -> Result { @@ -149,7 +149,7 @@ fn organize_imports(project: &mut Project, args: &Args) -> Result Result { - at_cursor(project, args, vlog_refactor::inline_module, instantiated) + with_check(at_cursor(project, args, vlog_refactor::inline_module, instantiated), args) } fn propagate_ports(project: &mut Project, args: &Args) -> Result { @@ -157,6 +157,10 @@ fn propagate_ports(project: &mut Project, args: &Args) -> Result } fn remove_port(project: &mut Project, args: &Args) -> Result { + with_check(remove_port_at(project, args), args) +} + +fn remove_port_at(project: &mut Project, args: &Args) -> Result { let (path, offset) = cursor(project, args)?; let analysis = project.analysis(&path)?; let port = name_at(&analysis, offset); @@ -295,6 +299,35 @@ pub(super) fn finish_telling( Ok(answer) } +/// How many changed files the check line names; the rest are counted. +const CHECK_CAP: usize = 5; + +/// An edit's answer, ending with the line that names the files to run +/// `diagnostics` on — the agents ran it anyway; saying which saves a +/// decision (feedback round 2). Nothing is added when nothing changed. +pub(super) fn with_check(answer: Result, args: &Args) -> Result { + let mut answer = answer?; + let mut files: Vec<&str> = ["changed", "created"] + .iter() + .filter_map(|key| answer.structured[*key].as_array()) + .flatten() + .filter_map(|entry| entry["file"].as_str()) + .collect(); + if files.is_empty() { + return Ok(answer); + } + files.sort_unstable(); + let when = if args.flag("dry_run", false) { "check after writing" } else { "check" }; + let mut line = + format!("{when}: diagnostics on {}", files[..files.len().min(CHECK_CAP)].join(", ")); + if files.len() > CHECK_CAP { + line.push_str(&format!(" and {} more", files.len() - CHECK_CAP)); + } + answer.text.push_str(&line); + answer.text.push('\n'); + 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. @@ -312,6 +345,10 @@ fn written_ranges(edits: &[TextEdit]) -> Vec { } fn rename(project: &mut Project, args: &Args) -> Result { + with_check(rename_at(project, args), args) +} + +fn rename_at(project: &mut Project, args: &Args) -> Result { let new_name = args.str("new_name").unwrap_or_default(); let (path, offset) = match target(project, args)? { Target::At { path, offset, .. } => (path, offset), @@ -330,3 +367,37 @@ fn rename(project: &mut Project, args: &Args) -> Result { 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)) } + +#[cfg(test)] +mod tests { + use serde_json::{json, Value}; + + use super::super::Args; + use super::{with_check, Answer}; + + fn answer(changed: &[&str], created: &[&str]) -> Result { + let entries = |files: &[&str]| -> Vec { + files.iter().map(|file| json!({ "file": file })).collect() + }; + let structured = json!({ "changed": entries(changed), "created": entries(created) }); + Ok(Answer { text: "files: …\n".into(), structured }) + } + + fn args(dry_run: bool) -> Args { + Args(json!({ "dry_run": dry_run }).as_object().cloned().unwrap_or_default()) + } + + #[test] + fn the_check_line_names_five_files_in_path_order_and_counts_the_rest() { + let changed = ["f.sv", "b.sv", "e.sv", "a.sv", "d.sv", "g.sv"]; + let said = with_check(answer(&changed, &["c.sv"]), &args(false)).unwrap(); + assert!(said + .text + .ends_with("\ncheck: diagnostics on a.sv, b.sv, c.sv, d.sv, e.sv and 2 more\n")); + let dry = with_check(answer(&["a.sv"], &[]), &args(true)).unwrap(); + assert!(dry.text.ends_with("\ncheck after writing: diagnostics on a.sv\n")); + let nothing = with_check(answer(&[], &[]), &args(false)).unwrap(); + assert_eq!(nothing.text, "files: …\n"); + assert!(with_check(Err("no".into()), &args(false)).is_err()); + } +} diff --git a/crates/lucisv_mcp/src/tools/hierarchy.rs b/crates/lucisv_mcp/src/tools/hierarchy.rs index ae9db81..31d9bc4 100644 --- a/crates/lucisv_mcp/src/tools/hierarchy.rs +++ b/crates/lucisv_mcp/src/tools/hierarchy.rs @@ -18,10 +18,11 @@ use vlog_semantic::{ Def, FileId, InstanceOccurrence, InstantiationEdge, SymbolKind, WorkspaceIndex, }; +use super::read::{in_glob, path_match}; use super::source::{self, Texts}; use super::{Answer, Args, Param, Tool, Ty}; use crate::project::Project; -use crate::render::{self, DEFAULT_LIMIT}; +use crate::render::{self, Noun, Page, DEFAULT_LIMIT}; /// The deepest a walk may go, whatever `depth` asks. const MAX_DEPTH: usize = 20; @@ -35,7 +36,7 @@ const NODE_CAP: usize = 50_000; pub const HIERARCHY: Tool = Tool { name: "hierarchy", title: "Instance hierarchy", - 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.", + description: "Who instantiates a module (`up`: instances, `#(…)` overrides, file:line) or what it instantiates (`down`, default). Textual.", params: &[ Param { name: "root", @@ -47,19 +48,25 @@ pub const HIERARCHY: Tool = Tool { name: "direction", ty: Ty::Enum(&["down", "up"]), required: false, - description: "`down` (default) or `up`.", + description: "Default `down`.", }, Param { name: "depth", ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 }, required: false, - description: "Levels (default 3, at most 20).", + description: "Default 3, at most 20.", + }, + Param { + name: "in", + ty: Ty::Str, + required: false, + description: "Path glob the instantiating file (`up`) or the module's (`down`) must match, e.g. `ip/**/rtl/*.sv`.", }, Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Most lines (default 200).", + description: "Default 500.", }, Param { name: "offset", @@ -114,10 +121,12 @@ struct Node { note: Option, } -/// A walk in progress: the edges by owner, what it collected, and the path -/// of modules above the current node. +/// A walk in progress: the edges by owner, the `in` glob, what it +/// collected, and the path of modules above the current node. struct Walk<'a> { + project: &'a Project, index: &'a WorkspaceIndex, + glob: Option<&'a str>, below: HashMap<(FileId, u32), Vec>, max_depth: usize, nodes: Vec, @@ -140,17 +149,27 @@ fn hierarchy(project: &mut Project, args: &Args) -> Result { } let max_depth = args.count("depth", 3); let index = project.index(); - let mut walk = Walk::new(index, max_depth, !up); + let mut walk = Walk::new(project, in_glob(args), max_depth, !up); let roots: Vec<(String, Def)> = match root { Some(root) => { modules_named(index, root).into_iter().map(|d| (root.to_string(), d)).collect() } - None => top_modules(index), + None => top_modules(index).into_iter().filter(|(_, def)| walk.keeps(def.file)).collect(), }; + let single_up = up && roots.len() == 1; for (name, def) in roots { walk.root(name, def, up); } - Ok(render(project, walk.nodes, up, args)) + let emptied = walk.glob.is_some() + && match root { + Some(root) if single_up => { + walk.nodes.len() == 1 && !index.instantiations_of(root).is_empty() + } + None => walk.nodes.is_empty() && !top_modules(index).is_empty(), + Some(_) => false, + }; + let shape = Shape { up, single_up, emptied }; + Ok(render(project, walk.nodes, shape, args)) } /// Every instantiable declaration of `name`. @@ -169,8 +188,10 @@ fn top_modules(index: &WorkspaceIndex) -> Vec<(String, Def)> { } impl<'a> Walk<'a> { - /// A walk over `index`; the owner table is built only for `down`. - fn new(index: &'a WorkspaceIndex, max_depth: usize, down: bool) -> Walk<'a> { + /// A walk over `project`'s index; the owner table is built only for + /// `down`. + fn new(project: &'a Project, glob: Option<&'a str>, max_depth: usize, down: bool) -> Walk<'a> { + let index = project.index(); let mut below: HashMap<(FileId, u32), Vec> = HashMap::new(); for (module, edges) in index.instantiations().filter(|_| down) { for edge in edges { @@ -183,7 +204,14 @@ impl<'a> Walk<'a> { for children in below.values_mut() { children.sort_by_key(|child| child.name.start); } - Walk { index, below, max_depth, nodes: Vec::new(), path: Vec::new() } + Walk { project, index, glob, below, max_depth, nodes: Vec::new(), path: Vec::new() } + } + + /// Whether the `in` glob (if any) keeps an entry in `file`. + fn keeps(&self, file: FileId) -> bool { + let Some(glob) = self.glob else { return true }; + let path = self.index.path(file); + path.is_some_and(|path| path_match(glob, &self.project.relative(path))) } fn full(&self) -> bool { @@ -220,6 +248,10 @@ impl<'a> Walk<'a> { return; } let declared = modules_named(self.index, &child.module); + // `in` asks for the module's own file; one not indexed has none. + if self.glob.is_some() && !declared.iter().any(|def| self.keeps(def.file)) { + continue; + } let recursive = self.path.contains(&child.module); let note = match declared.len() { _ if recursive => Some("recursive".to_string()), @@ -248,6 +280,9 @@ impl<'a> Walk<'a> { fn up(&mut self, module: &str, depth: usize) { let index = self.index; for edge in index.instantiations_of(module) { + if !self.keeps(edge.file) { + continue; + } for occurrence in &edge.instances { if self.full() { return; @@ -273,31 +308,46 @@ impl<'a> Walk<'a> { } } +const NODES: Noun = Noun("node", "nodes"); +const INSTANTIATIONS: Noun = Noun("instantiation", "instantiations"); + +/// How an answer is counted: `up` from one root counts the instantiations +/// under its root line, which every page repeats; any other walk counts +/// every line. `emptied` when the `in` glob removed every entry there was. +struct Shape { + up: bool, + single_up: bool, + emptied: bool, +} + /// The collected nodes, paged, as indented lines and as a flat JSON list. -fn render(project: &Project, nodes: Vec, up: bool, args: &Args) -> Answer { - let (shown, rest) = - render::page(&nodes, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); +fn render(project: &Project, nodes: Vec, shape: Shape, args: &Args) -> Answer { + let (lead, counted, noun) = match nodes.split_first() { + Some((root, rest)) if shape.single_up => (Some(root), rest, INSTANTIATIONS), + _ => (None, nodes.as_slice(), NODES), + }; + let page = Page::of(counted, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + let mut text = if shape.emptied { render::none_match(noun) } else { page.header(noun) }; let mut texts = Texts::default(); - let mut text = String::new(); let mut listed: Vec = Vec::new(); - for node in shown { + for node in lead.into_iter().chain(page.shown) { let line = Line::of(project, &mut texts, node); text.push_str(&" ".repeat(node.depth)); - text.push_str(&line.text(node, up)); + text.push_str(&line.text(node, shape.up)); text.push('\n'); - listed.push(line.json(node, up)); + listed.push(line.json(node, shape.up)); } - render::more(&mut text, rest); + render::more(&mut text, page.rest()); if nodes.len() >= NODE_CAP { text.push_str(&format!("tree cut at {NODE_CAP} nodes; lower `depth` or pick a `root`\n")); } - if nodes.is_empty() { + if nodes.is_empty() && !shape.emptied { text = "no modules\n".to_string(); } - let direction = if up { "up" } else { "down" }; + let direction = if shape.up { "up" } else { "down" }; let structured = json!({ - "direction": direction, "nodes": listed, "total": nodes.len(), - "cut": nodes.len() >= NODE_CAP, + "direction": direction, "nodes": listed, "total": counted.len(), + "shown": page.shown_json(), "cut": nodes.len() >= NODE_CAP, }); Answer { text, structured } } diff --git a/crates/lucisv_mcp/src/tools/nav.rs b/crates/lucisv_mcp/src/tools/nav.rs index 3d65e35..0107c0a 100644 --- a/crates/lucisv_mcp/src/tools/nav.rs +++ b/crates/lucisv_mcp/src/tools/nav.rs @@ -20,11 +20,12 @@ use vlog_parser::token::{Token, TokenKind}; use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex}; use super::mentions::{self, Focus, Mentions}; +use super::read::{in_glob, only_in, path_match, IN}; use super::select::{macro_name, target, Target}; use super::source::{self, checked_site, Site, Texts, WholeSet}; use super::{Answer, Args, Param, Tool, Ty}; use crate::project::{Analysis, Project}; -use crate::render::{self, DEFAULT_LIMIT}; +use crate::render::{self, Noun, Page, DEFAULT_LIMIT}; /// The selector's arguments, shared by both tools. const FILE: Param = Param { name: "file", ty: Ty::Str, required: false, description: "The file." }; @@ -36,7 +37,7 @@ const NAME: Param = Param { name: "name", ty: Ty::Str, required: false, - description: "Name; alone, looked up project-wide (`` `NAME`` for a macro).", + description: "Name; alone, looked up project-wide (`` `X`` is a macro).", }; const UNIT: Param = Param { name: "unit", @@ -47,8 +48,8 @@ const UNIT: Param = Param { pub const DEFINITION: Tool = Tool { name: "definition", - title: "Go to definition", - 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`).", + title: "Definition", + description: "Where a name or macro is declared: file:line:col, kind, line. Select by position, `file`+`name`, or `name`.", params: &[FILE, LINE, COL, NAME, UNIT], rewalk: false, handler: definition, @@ -57,7 +58,7 @@ pub const DEFINITION: Tool = Tool { pub const REFERENCES: Tool = Tool { name: "references", title: "Find references", - 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.", + description: "Uses of one declaration, then its unresolved mentions (strings, comments, macro text). Select as `definition`. Module instances: `hierarchy` up.", params: &[ FILE, LINE, @@ -68,13 +69,14 @@ pub const REFERENCES: Tool = Tool { name: "include_declaration", ty: Ty::Bool, required: false, - description: "Include the declaration (default true).", + description: "Default true.", }, + IN, Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, - description: "Most hits (default 200).", + description: "Default 500.", }, Param { name: "offset", @@ -295,7 +297,8 @@ fn references(project: &mut Project, args: &Args) -> Result { Some(Site::at(project.relative(file), text, lines, *span, "use")) }) .collect(); - let mut answer = render_hits(&hits, args); + let (hits, emptied) = only_in(args, hits, |hit| hit.file.clone()); + let mut answer = render_hits(&hits, emptied, args); if !mentions.is_empty() { answer.text.push_str(MENTIONS_LABEL); answer.text.push_str(&mentions.lines(" ")); @@ -337,8 +340,11 @@ fn unresolved( } 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) + // `in` keeps the mentions it keeps the hits of. + let kept = + |path: &Path| in_glob(args).is_none_or(|glob| path_match(glob, &project.relative(path))); + let files = set.files.iter().filter(|(path, _)| kept(path)); + mentions::find(project, files.map(|(path, text)| (path.as_path(), text.as_str())), &focus) } /// The one declaration a bare `name` selects for `references` (and `rename`). @@ -403,24 +409,30 @@ fn engine_refusal(sentence: String) -> String { format!("lucisv cannot follow this position: {out}") } -/// Hits grouped by file, `line:col text`, paged. -fn render_hits(hits: &[Site], args: &Args) -> Answer { - let (shown, rest) = - render::page(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); - let entries: Vec<(String, String)> = shown +const HITS: Noun = Noun("hit", "hits"); + +/// Hits grouped by file, `line:col text`, paged; `emptied` when the `in` +/// glob removed every hit there was. +fn render_hits(hits: &[Site], emptied: bool, args: &Args) -> Answer { + let page = Page::of(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + let entries: Vec<(String, String)> = page + .shown .iter() .map(|hit| (hit.file.clone(), format!("{}:{} {}", hit.line, hit.col, hit.text))) .collect(); - let mut text = render::grouped(&entries); - render::more(&mut text, rest); + let mut text = page.header(HITS); + text.push_str(&render::grouped(&entries)); + render::more(&mut text, page.rest()); if hits.is_empty() { - text = "no references\n".to_string(); + text = if emptied { render::none_match(HITS) } else { "no references\n".to_string() }; } - let listed: Vec = shown + let listed: Vec = page + .shown .iter() .map(|hit| json!({ "file": hit.file, "line": hit.line, "col": hit.col, "text": hit.text })) .collect(); - Answer { text, structured: json!({ "hits": listed, "total": hits.len() }) } + let structured = json!({ "hits": listed, "total": hits.len(), "shown": page.shown_json() }); + Answer { text, structured } } #[cfg(test)] diff --git a/crates/lucisv_mcp/src/tools/read.rs b/crates/lucisv_mcp/src/tools/read.rs index 82bc636..b40b78d 100644 --- a/crates/lucisv_mcp/src/tools/read.rs +++ b/crates/lucisv_mcp/src/tools/read.rs @@ -9,14 +9,10 @@ use vlog_semantic::{Def, DocumentSymbol, SymbolKind, WorkspaceIndex}; use super::{Answer, Args, Param, Tool, Ty}; use crate::project::Project; -use crate::render::{self, DEFAULT_LIMIT}; +use crate::render::{self, Noun, Page, DEFAULT_LIMIT}; -const LIMIT: Param = Param { - name: "limit", - ty: Ty::Int { min: 1 }, - required: false, - description: "Max entries (default 200).", -}; +const LIMIT: Param = + Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, description: "Default 500." }; const OFFSET: Param = Param { name: "offset", ty: Ty::Int { min: 0 }, @@ -24,10 +20,25 @@ const OFFSET: Param = Param { description: "Entries to skip.", }; +/// `in`, the path filter every whole-project listing takes. +pub(super) const IN: Param = Param { + name: "in", + ty: Ty::Str, + required: false, + description: "Path glob the file must match, e.g. `ip/**/rtl/*.sv`.", +}; + +/// How many top-level modules the overview names; the rest are counted. +const TOPS_CAP: usize = 200; + +const UNITS: Noun = Noun("unit", "units"); +const ENTRIES: Noun = Noun("entry", "entries"); +const SYMBOLS: Noun = Noun("symbol", "symbols"); + pub const PROJECT_OVERVIEW: Tool = Tool { name: "project_overview", title: "Project overview", - description: "File count, units by kind, top-level modules, largest files. Call it first.", + description: "Files, units by kind, top modules, largest files. Call it first.", params: &[], rewalk: true, handler: project_overview, @@ -35,8 +46,8 @@ pub const PROJECT_OVERVIEW: Tool = Tool { pub const LIST_UNITS: Tool = Tool { name: "list_units", - title: "List design units", - description: "Modules, interfaces, packages, classes, programs with file:line, by `kind` and name `glob`.", + title: "List units", + description: "Units (modules, interfaces, packages, classes, programs) with file:line.", params: &[ Param { name: "kind", @@ -50,6 +61,7 @@ pub const LIST_UNITS: Tool = Tool { required: false, description: "Name pattern with `*` and `?`.", }, + IN, LIMIT, OFFSET, ], @@ -79,7 +91,7 @@ pub const OUTLINE: Tool = Tool { pub const SEARCH_SYMBOLS: Tool = Tool { name: "search_symbols", title: "Search symbols", - description: "Declarations whose name contains `query` (any case): units, ports, parameters, package/class members.", + description: "Declarations whose name contains `query` (any case), members included.", params: &[ Param { name: "query", @@ -87,6 +99,7 @@ pub const SEARCH_SYMBOLS: Tool = Tool { required: true, description: "Name substring; empty matches all.", }, + IN, LIMIT, OFFSET, ], @@ -183,29 +196,87 @@ pub fn glob_match(pattern: &str, name: &str) -> bool { pattern[p..].iter().all(|&c| c == '*') } +/// Whether a root-relative `path` matches a path glob: `*` and `?` within +/// one component ([`glob_match`]), `**` as a whole component for any run of +/// components (none included). A trailing `/` means everything below. +pub fn path_match(pattern: &str, path: &str) -> bool { + let pattern = pattern.strip_prefix("./").unwrap_or(pattern); + // A bare directory (`ip/aes`, no wildcard) means everything below it, as + // it does for `.gitignore` and `rg -g` (feedback-2 QA note 2). + let literal = !pattern.contains(['*', '?']); + if literal && path.strip_prefix(pattern).is_some_and(|rest| rest.starts_with('/')) { + return true; + } + let mut parts: Vec<&str> = pattern.split('/').collect(); + if parts.last() == Some(&"") && parts.len() > 1 { + parts.pop(); + parts.push("**"); + } + // `**/**` means what `**` means; collapsing keeps the search linear-ish. + parts.dedup_by(|a, b| *a == "**" && *b == "**"); + let components: Vec<&str> = path.split('/').collect(); + components_match(&parts, &components) +} + +fn components_match(pattern: &[&str], path: &[&str]) -> bool { + match pattern.split_first() { + None => path.is_empty(), + Some((&"**", rest)) => (0..=path.len()).any(|skip| components_match(rest, &path[skip..])), + Some((first, rest)) => path + .split_first() + .is_some_and(|(part, below)| glob_match(first, part) && components_match(rest, below)), + } +} + +/// The call's `in` path glob; an empty one filters nothing. +pub(super) fn in_glob(args: &Args) -> Option<&str> { + args.str("in").filter(|glob| !glob.is_empty()) +} + +/// The entries whose root-relative file the call's `in` glob keeps (all of +/// them without one — `file` is then never asked), and whether the glob +/// removed every entry there was. +pub(super) fn only_in( + args: &Args, + items: Vec, + file: impl Fn(&T) -> String, +) -> (Vec, bool) { + let Some(glob) = in_glob(args) else { return (items, false) }; + let had = !items.is_empty(); + let kept: Vec = items.into_iter().filter(|item| path_match(glob, &file(item))).collect(); + let emptied = had && kept.is_empty(); + (kept, emptied) +} + fn list_units(project: &mut Project, args: &Args) -> Result { - let mut all = matching_units(project, args); + let select = + |project: &Project| only_in(args, matching_units(project, args), |u| u.file.clone()); + let (mut all, mut emptied) = select(project); // A glob names something the agent expects to exist — often a file it // has just written — so a miss walks once before it is believed. - if all.is_empty() && args.str("glob").is_some() && project.ensure_walked_for_miss() { - all = matching_units(project, args); + let named = args.str("glob").is_some() || in_glob(args).is_some(); + if all.is_empty() && named && project.ensure_walked_for_miss() { + (all, emptied) = select(project); } - let (shown, rest) = - render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); - let entries: Vec<(String, String)> = shown + let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + let entries: Vec<(String, String)> = page + .shown .iter() .map(|u| (u.file.clone(), format!("{} {} {}", u.kind, u.name, u.line))) .collect(); - let mut text = render::grouped(&entries); - render::more(&mut text, rest); + let mut text = page.header(UNITS); + text.push_str(&render::grouped(&entries)); + render::more(&mut text, page.rest()); if all.is_empty() { - text = "no units match\n".to_string(); + text = if emptied { render::none_match(UNITS) } else { "no units match\n".to_string() }; } - let structured: Vec = shown + let structured: Vec = page + .shown .iter() .map(|u| json!({ "name": u.name, "kind": u.kind, "file": u.file, "line": u.line })) .collect(); - Ok(Answer { text, structured: json!({ "units": structured, "total": all.len() }) }) + let structured = json!({ "units": structured, "total": all.len(), "shown": page.shown_json() }); + Ok(Answer { text, structured }) } /// The units `list_units`'s `kind` and `glob` select. @@ -247,7 +318,7 @@ impl Overview { .map(|&kind| (kind, all.iter().filter(|u| u.kind == kind).count())) .collect(); let tops = top_modules(project.index()); - let (shown, more_tops) = render::page(&tops, 0, DEFAULT_LIMIT); + let (shown, more_tops) = render::page(&tops, 0, TOPS_CAP); let (config, config_problem) = project.config(); let discovery = project.discovery(); let (build, age) = project.timing(); @@ -352,10 +423,11 @@ fn outline(project: &mut Project, args: &Args) -> Result { let depth = args.count("depth", usize::MAX); let mut rows: Vec<(usize, String, &'static str, u32, u32)> = Vec::new(); flatten(&analysis, &analysis.semantics.document_symbols(), 0, depth, &mut rows); - let (shown, rest) = - render::page(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + let page = Page::of(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + let shown = page.shown; let file = project.relative(&path); - let mut text = format!("{file}\n"); + let mut text = page.header(ENTRIES); + text.push_str(&format!("{file}\n")); let errors = &analysis.diagnostics; if let Some(first) = errors.first() { text.push_str(&format!( @@ -370,7 +442,7 @@ fn outline(project: &mut Project, args: &Args) -> Result { let indent = " ".repeat(level + 1); text.push_str(&format!("{indent}{kind} {name} {}\n", render::lines(*first, *last))); } - render::more(&mut text, rest); + render::more(&mut text, page.rest()); let symbols: Vec = shown .iter() .map(|(level, name, kind, first, last)| { @@ -383,6 +455,7 @@ fn outline(project: &mut Project, args: &Args) -> Result { .collect(); let structured = json!({ "file": file, "parse_errors": parse_errors, "symbols": symbols, "total": rows.len(), + "shown": page.shown_json(), }); Ok(Answer { text, structured }) } @@ -415,17 +488,18 @@ fn search_symbols(project: &mut Project, args: &Args) -> Result project.ensure_walked_for_miss(); } let index = project.index(); - let hits = index.workspace_symbols(query); - let (shown, rest) = - render::page(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); + let file_of = |file| project.relative(index.path(file).unwrap_or(Path::new(""))); + let (hits, emptied) = + only_in(args, index.workspace_symbols(query), |hit| file_of(hit.def.file)); + let page = Page::of(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT)); let mut entries = Vec::new(); let mut structured = Vec::new(); - for hit in shown { + for hit in page.shown { + let file = file_of(hit.def.file); let name = match hit.container { Some(unit) => format!("{unit}{}{}", separator(index, unit), hit.name), None => hit.name.to_string(), }; - let file = project.relative(index.path(hit.def.file).unwrap_or(Path::new(""))); // A line and no column: the index records a client (UTF-16) column // for units only, and every column this server prints is a byte one. let line = hit.def.lines.name; @@ -434,12 +508,15 @@ fn search_symbols(project: &mut Project, args: &Args) -> Result "name": name, "kind": render::kind(hit.def.kind), "file": file, "line": line, })); } - let mut text = render::grouped(&entries); - render::more(&mut text, rest); + let mut text = page.header(SYMBOLS); + text.push_str(&render::grouped(&entries)); + render::more(&mut text, page.rest()); if hits.is_empty() { - text = "no symbols match\n".to_string(); + text = if emptied { render::none_match(SYMBOLS) } else { "no symbols match\n".into() }; } - Ok(Answer { text, structured: json!({ "symbols": structured, "total": hits.len() }) }) + let total = hits.len(); + let structured = json!({ "symbols": structured, "total": total, "shown": page.shown_json() }); + Ok(Answer { text, structured }) } /// How a member is spelled after its unit: `unit.x` for a module or @@ -454,7 +531,17 @@ fn separator(index: &WorkspaceIndex, unit: &str) -> &'static str { #[cfg(test)] mod tests { - use super::glob_match; + use super::{glob_match, path_match}; + + #[test] + fn a_bare_directory_glob_means_everything_below_it() { + assert!(super::path_match("ip/aes", "ip/aes/rtl/aes.sv")); + assert!(super::path_match("ip/aes/", "ip/aes/rtl/aes.sv")); + assert!(!super::path_match("ip/aes", "ip/aes_x/rtl/aes.sv")); + assert!(!super::path_match("ip/aes", "ip/ae")); + assert!(super::path_match("ip/aes/rtl/aes.sv", "ip/aes/rtl/aes.sv")); + assert!(!super::path_match("ip/a?s", "ip/aes/rtl/aes.sv"), "a wildcard keeps glob rules"); + } #[test] fn globs_match_runs_and_single_characters() { @@ -466,4 +553,20 @@ mod tests { assert!(!glob_match("prim_*_async", "prim_fifo_sync")); assert!(glob_match("*_sync", "prim_fifo_sync")); } + + #[test] + fn path_globs_keep_star_in_one_component_and_let_double_star_span_many() { + assert!(path_match("ip/**/rtl/*.sv", "ip/aes/rtl/aes.sv")); + assert!(path_match("ip/**/rtl/*.sv", "ip/aes/sub/rtl/aes.sv")); + assert!(path_match("ip/**/rtl/*.sv", "ip/rtl/x.sv")); + assert!(!path_match("ip/**/rtl/*.sv", "ip/aes/dv/aes.sv")); + assert!(!path_match("ip/*/*.sv", "ip/aes/rtl/aes.sv")); + assert!(!path_match("*.sv", "ip/aes.sv")); + assert!(path_match("**/*.sv", "ip/aes.sv") && path_match("**/*.sv", "top.sv")); + assert!(path_match("ip/ae?/**", "ip/aes/rtl/aes.sv")); + assert!(!path_match("ip/ae?/**", "ip/aesx/rtl/aes.sv")); + assert!(path_match("ip/", "ip/aes/rtl/aes.sv") && path_match("./ip/**", "ip/a.sv")); + assert!(path_match("**/**/**/rtl/**", "a/b/rtl/c/d.sv")); + assert!(!path_match("ip/**", "hw/ip/aes.sv")); + } } diff --git a/crates/lucisv_mcp/src/tools/refactor.rs b/crates/lucisv_mcp/src/tools/refactor.rs index b956ebf..352b0cf 100644 --- a/crates/lucisv_mcp/src/tools/refactor.rs +++ b/crates/lucisv_mcp/src/tools/refactor.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use vlog_refactor::{instantiation_plan, module_definition, Home, Layout, ModuleRef}; -use super::edit::{enclosing, finish, finish_telling, whole_set, Told, DRY_RUN}; +use super::edit::{enclosing, finish, finish_telling, whole_set, with_check, Told, DRY_RUN}; use super::place; use super::{Answer, Args, Param, Tool, Ty}; use crate::project::Project; @@ -15,14 +15,10 @@ use crate::project::Project; pub const ADD_PORT: Tool = Tool { name: "add_port", title: "Add a port", - description: "Add an ANSI port to a module and connect it in every instantiation; `after` places it after a port, in its layout.", + description: + "Add an ANSI port to a module, connected in every instantiation; `after` positions it.", params: &[ - Param { - name: "module", - ty: Ty::Str, - required: false, - description: "The module's name.", - }, + Param { name: "module", ty: Ty::Str, required: false, description: "The module." }, Param { name: "file", ty: Ty::Str, @@ -39,7 +35,7 @@ pub const ADD_PORT: Tool = Tool { name: "declaration", ty: Ty::Str, required: true, - description: "The port as written, e.g. `input logic [7:0] cfg`.", + description: "As written, e.g. `input logic [7:0] cfg`.", }, Param { name: "after", @@ -55,8 +51,8 @@ pub const ADD_PORT: Tool = Tool { pub const EXTRACT_MODULE: Tool = Tool { name: "extract_module", - title: "Extract lines into a module", - description: "Move whole items on lines `start_line`..`end_line` into a new module `new_name`, instantiated in their place.", + title: "Extract a module", + description: "Move whole items in lines `start_line`..`end_line` to a new module instantiated in their place.", params: &[ Param { name: "file", @@ -80,13 +76,13 @@ pub const EXTRACT_MODULE: Tool = Tool { name: "new_name", ty: Ty::Str, required: true, - description: "A name nothing declares yet.", + description: "An unused name.", }, Param { name: "home", ty: Ty::Enum(&["new_file", "same_file"]), required: false, - description: "`new_file` (default, `new_name.sv`) or `same_file`.", + description: "Default `new_file` (`new_name.sv`).", }, DRY_RUN, ], @@ -97,7 +93,8 @@ pub const EXTRACT_MODULE: Tool = Tool { pub const INSTANTIATE: Tool = Tool { name: "instantiate", title: "Instantiation template", - description: "Instantiation text for module `name` to paste: parameter defaults, instance name, named or `.*` ports.", + description: + "Instantiation text for module `name`: parameters, instance name, named or `.*` ports.", params: &[ Param { name: "name", @@ -115,7 +112,7 @@ pub const INSTANTIATE: Tool = Tool { name: "with_params", ty: Ty::Bool, required: false, - description: "Write the `#(...)` overrides (default true).", + description: "Write `#(...)` overrides (default true).", }, Param { name: "instance", @@ -135,6 +132,10 @@ pub const INSTANTIATE: Tool = Tool { }; fn add_port(project: &mut Project, args: &Args) -> Result { + with_check(add_port_to(project, args), args) +} + +fn add_port_to(project: &mut Project, args: &Args) -> Result { let declaration = args.str("declaration").unwrap_or_default(); let (module, file, set, edit) = match (args.str("module"), args.str("file"), args.int("line")) { (Some(name), None, None) => { @@ -189,6 +190,10 @@ fn line_start(project: &mut Project, path: &Path, line: i64) -> Result Result { + with_check(extract_lines(project, args), args) +} + +fn extract_lines(project: &mut Project, args: &Args) -> Result { let file = args.str("file").unwrap_or_default(); let path = project.resolve(file)?; let (first, last) = (args.int("start_line").unwrap_or(1), args.int("end_line").unwrap_or(1)); diff --git a/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/dv/aes_tb.sv b/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/dv/aes_tb.sv new file mode 100644 index 0000000..497e9bd --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/dv/aes_tb.sv @@ -0,0 +1,5 @@ +`define AES_TB 1 +module aes_tb; + logic clk_i; + aes_core u_dut (.clk_i(clk_i), .q_o()); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/rtl/aes_core.sv b/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/rtl/aes_core.sv new file mode 100644 index 0000000..c85ba9e --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/rtl/aes_core.sv @@ -0,0 +1,8 @@ +`define AES_W 8 +module aes_core ( + input logic clk_i, + output logic [`AES_W - 1:0] q_o +); + logic \esc*name ; + assign q_o = '0; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/rtl/aes_pkg.sv b/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/rtl/aes_pkg.sv new file mode 100644 index 0000000..c22d8af --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/paths/ip/aes/rtl/aes_pkg.sv @@ -0,0 +1,3 @@ +package aes_pkg; + parameter int \esc*w = 4; +endpackage diff --git a/crates/lucisv_mcp/tests/fixtures/paths/ip/uart/rtl/sub/uart_fifo.sv b/crates/lucisv_mcp/tests/fixtures/paths/ip/uart/rtl/sub/uart_fifo.sv new file mode 100644 index 0000000..27ba0b6 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/paths/ip/uart/rtl/sub/uart_fifo.sv @@ -0,0 +1,2 @@ +module uart_fifo; +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/paths/ip/uart/rtl/uart.sv b/crates/lucisv_mcp/tests/fixtures/paths/ip/uart/rtl/uart.sv new file mode 100644 index 0000000..d2cd524 --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/paths/ip/uart/rtl/uart.sv @@ -0,0 +1,8 @@ +module uart ( + input logic clk_i, + input logic spare_i +); + logic idle_x; + aes_core u_aes (.clk_i(clk_i), .q_o()); + uart_fifo u_fifo (); +endmodule diff --git a/crates/lucisv_mcp/tests/fixtures/paths/lucisv.toml b/crates/lucisv_mcp/tests/fixtures/paths/lucisv.toml new file mode 100644 index 0000000..388e10a --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/paths/lucisv.toml @@ -0,0 +1,2 @@ +[lint] +select = ["unused-signal"] diff --git a/crates/lucisv_mcp/tests/fixtures/paths/top/chip.sv b/crates/lucisv_mcp/tests/fixtures/paths/top/chip.sv new file mode 100644 index 0000000..5fad33e --- /dev/null +++ b/crates/lucisv_mcp/tests/fixtures/paths/top/chip.sv @@ -0,0 +1,7 @@ +module chip ( + input logic clk_i, + input logic spare_i +); + uart u_uart (.*); + aes_core u_aes2 (.clk_i(clk_i), .q_o()); +endmodule diff --git a/crates/lucisv_mcp/tests/qa_f2.rs b/crates/lucisv_mcp/tests/qa_f2.rs new file mode 100644 index 0000000..1253373 --- /dev/null +++ b/crates/lucisv_mcp/tests/qa_f2.rs @@ -0,0 +1,750 @@ +//! QA attacks on lane feedback-2 (the count line on every paged answer, the +//! `in` path glob, the post-edit check line), 2026-09-23. +//! +//! Every test spawns the real binary over a scratch tree, as a host would. +//! The count line is checked by one rule applied to every paged tool over a +//! grid of windows: its total is the JSON `total`, its window the JSON +//! `shown`, the JSON list holds exactly the window, and the old +//! `… and N more` tail says `total − b`. +//! +//! 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-2/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-f2-{}-{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 + } +} + +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 { + let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp")) + .args(["--root", tree.0.to_str().unwrap()]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let stdout = child.stdout.take().unwrap(); + let (send, lines) = mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if send.send(line).is_err() { + break; + } + } + }); + let stdin = child.stdin.take().unwrap(); + let mut session = + Session { child, stdin: 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()) + } + + /// A call that must answer; its text and structured content. + fn ok(&mut self, tool: &str, arguments: Value) -> (String, Value) { + let (error, text, structured) = self.call(tool, arguments.clone()); + assert!(!error, "{tool} {arguments}: refused: {text}"); + (text, structured) + } + + fn text(&mut self, tool: &str, arguments: Value) -> String { + self.ok(tool, arguments).0 + } +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +// --------------------------------------------------------------------------- +// The tree: three depths under `ip/`, a `hw/ip/` decoy for anchoring, a +// `lib/` the RTL instantiates, an escaped name holding `*`, a comment +// mention outside `ip/`, a no-tabs finding and an unused external waiver. +// --------------------------------------------------------------------------- + +const TREE: &[(&str, &str)] = &[ + ( + "lucisv.toml", + "[lint]\nselect = [\"unused-signal\", \"no-tabs\", \"unused-waiver\"]\nwaivers = [\"w.waiver\"]\n", + ), + ("w.waiver", "waive --rule=no-tabs --location=nothing.sv\n"), + ( + "ip/x.sv", + "`define IPX 1\nmodule ipx (input logic clk_i);\n logic dead_a;\n leaf u_a (.clk_i(clk_i));\nendmodule\n", + ), + ( + "ip/aes/rtl/aes.sv", + "`define AES_A 1\n`define AES_B 2\nmodule aes (input logic clk_i);\n logic dead_b;\n leaf u_b (.clk_i(clk_i));\n mid u_m (.clk_i(clk_i));\nendmodule\n", + ), + ( + "ip/aes/rtl/sub/deep.sv", + "module deep (input logic clk_i);\n logic dead_c;\n leaf u_c (.clk_i(clk_i));\nendmodule\n", + ), + ( + "ip/aes/dv/tb.sv", + "module tb;\n logic clk_i; // clk_i drives leaf\n aes u_dut (.clk_i(clk_i));\n leaf u_d (.clk_i(clk_i));\nendmodule\n", + ), + ("hw/ip/y.sv", "module hwy (input logic clk_i);\n\tleaf u_e (.clk_i(clk_i));\nendmodule\n"), + ("lib/leaf.sv", "module leaf (input logic clk_i);\nendmodule\n"), + ( + "lib/mid.sv", + "module mid (input logic clk_i);\n leaf u_f (.clk_i(clk_i));\n deep u_g (.clk_i(clk_i));\nendmodule\n", + ), + ("doc/notes.sv", "// leaf is the unit under test\nmodule notes; endmodule\n"), + ("esc/e.sv", "module \\esc*mod (input logic a);\nendmodule\n"), +]; + +fn served() -> (Tree, Session) { + let tree = Tree::with(TREE); + let server = Session::over(&tree); + (tree, server) +} + +// --------------------------------------------------------------------------- +// 1. The count line, one rule for every paged tool. +// --------------------------------------------------------------------------- + +/// What an answer's first line says: its total and its window (`None` for +/// a whole list, `Some(None)` past the end, `Some(Some((a, b)))` cut). +struct Header { + total: usize, + window: Option>, +} + +/// Parse the count line, checking its noun agrees with the number. +fn header(text: &str) -> Header { + let first = text.lines().next().unwrap_or_default(); + let (count, rest) = first.split_once(' ').unwrap_or_else(|| panic!("no count line: {text}")); + let total: usize = count.parse().unwrap_or_else(|_| panic!("no count line: {text}")); + let (noun, window) = match rest.split_once(" (") { + Some((noun, window)) => (noun, Some(window.trim_end_matches(')'))), + None => (rest, None), + }; + assert_eq!(noun.ends_with('s'), total != 1, "singular only for one: {first}"); + let window = match window { + None => None, + Some("none match `in`") => { + assert_eq!(total, 0, "{first}"); + None + } + Some("showing none: `offset` is past the end") => Some(None), + Some(showing) => { + let span = showing.strip_prefix("showing ").unwrap_or_else(|| panic!("{first}")); + let (a, b) = span.split_once('–').unwrap_or((span, span)); + let (a, b): (usize, usize) = (a.parse().unwrap(), b.parse().unwrap()); + assert!(1 <= a && a <= b && b <= total, "{first}"); + assert!(a < b || !span.contains('–'), "one entry is `showing a`: {first}"); + assert!(a > 1 || b < total, "a whole list says no window: {first}"); + Some(Some((a, b))) + } + }; + Header { total, window } +} + +/// Check one answer against the rule: the count line's total is `total`, +/// its window is `shown`, the JSON `key` list holds the window (plus `lead` +/// lines that are not counted) and the tail counts what follows. +fn agrees(label: &str, text: &str, structured: &Value, key: &str, lead: usize) { + let listed = structured[key].as_array().map_or(0, Vec::len); + let total = structured["total"].as_u64().unwrap() as usize; + let tail = text.lines().find(|line| line.starts_with("… and ")); + if text.starts_with("no ") { + // An empty list keeps its old one-line answer. + assert_eq!((total, structured["shown"].clone()), (0, json!([0, 0])), "{label}"); + return; + } + let said = header(text); + assert_eq!(said.total, total, "{label}: the count line is the JSON total\n{text}"); + let (a, b) = match said.window { + None if total == 0 => (0, 0), + None => (1, total), + Some(None) => (0, 0), + Some(Some(span)) => span, + }; + assert_eq!(structured["shown"], json!([a, b]), "{label}: `shown` is the window\n{text}"); + let in_window = if a == 0 { 0 } else { b - a + 1 }; + assert_eq!(listed, in_window + lead, "{label}: the JSON lists the window\n{text}"); + match b < total && a > 0 { + true => assert_eq!(tail, Some(format!("… and {} more", total - b).as_str()), "{label}"), + false => assert_eq!(tail, None, "{label}: nothing follows\n{text}"), + } +} + +/// Every window worth trying on a list of `n`. +fn windows(n: usize) -> Vec { + let mut out = vec![json!({})]; + for (offset, limit) in + [(0, 1), (1, 1), (0, 2), (1, 2), (n - 1, 1), (n - 1, 5), (n, 1), (n + 3, 2), (1, n)] + { + out.push(json!({"offset": offset, "limit": limit})); + } + out.push(json!({"offset": 1})); + out +} + +/// The paged tools, each with arguments that give a list of several, the +/// JSON key of its list, and the lines it prints that the count leaves out. +fn paged_calls() -> Vec<(&'static str, Value, &'static str, usize)> { + vec![ + ("list_units", json!({}), "units", 0), + ("list_units", json!({"in": "ip/**"}), "units", 0), + ("search_symbols", json!({"query": "clk"}), "symbols", 0), + ("search_symbols", json!({"query": "clk", "in": "**/ip/**"}), "symbols", 0), + ("outline", json!({"file": "ip/aes/rtl/aes.sv"}), "symbols", 0), + ("references", json!({"name": "leaf"}), "hits", 0), + ("references", json!({"name": "leaf", "in": "ip/**"}), "hits", 0), + ("diagnostics", json!({}), "diagnostics", 0), + ("diagnostics", json!({"in": "ip/**"}), "diagnostics", 0), + ("defines", json!({}), "defines", 0), + ("defines", json!({"in": "ip/aes/**"}), "defines", 0), + ("defines", json!({"file": "ip/aes/rtl/aes.sv"}), "defines", 0), + ("hierarchy", json!({"root": "leaf", "direction": "up"}), "nodes", 1), + ("hierarchy", json!({"root": "leaf", "direction": "up", "depth": 1}), "nodes", 1), + ("hierarchy", json!({"root": "leaf", "direction": "up", "in": "ip/**"}), "nodes", 1), + ("hierarchy", json!({}), "nodes", 0), + ("hierarchy", json!({"in": "ip/**"}), "nodes", 0), + ("hierarchy", json!({"root": "tb", "depth": 5}), "nodes", 0), + ] +} + +fn merged(base: &Value, window: &Value) -> Value { + let mut out = base.clone(); + for (key, value) in window.as_object().unwrap() { + out[key] = value.clone(); + } + out +} + +#[test] +fn qa_every_paged_tool_agrees_with_its_json_over_every_window() { + let (_tree, mut server) = served(); + for (tool, base, key, lead) in paged_calls() { + let (_, whole) = server.ok(tool, base.clone()); + let n = whole["total"].as_u64().unwrap() as usize; + assert!(n >= 2, "{tool} {base}: the grid wants a list of several, got {n}"); + for window in windows(n) { + let arguments = merged(&base, &window); + let (text, structured) = server.ok(tool, arguments.clone()); + agrees(&format!("{tool} {arguments}"), &text, &structured, key, lead); + } + } +} + +#[test] +fn qa_the_count_line_pins_whole_cut_single_and_past_the_end() { + let (_tree, mut server) = served(); + let units = server.text("list_units", json!({})); + assert!(units.starts_with("9 units\ndoc/notes.sv\n"), "{units}"); + let one = server.text("list_units", json!({"limit": 1})); + assert_eq!(one, "9 units (showing 1)\ndoc/notes.sv\n module notes 2\n… and 8 more\n"); + let last = server.text("list_units", json!({"offset": 8, "limit": 3})); + assert_eq!(last, "9 units (showing 9)\nlib/mid.sv\n module mid 1\n"); + let past = server.text("list_units", json!({"offset": 9})); + assert_eq!(past, "9 units (showing none: `offset` is past the end)\n"); + let single = server.text("list_units", json!({"glob": "leaf"})); + assert_eq!(single, "1 unit\nlib/leaf.sv\n module leaf 1\n"); + assert_eq!(server.text("list_units", json!({"glob": "zz*"})), "no units match\n"); + + let outline = server.text("outline", json!({"file": "lib/leaf.sv"})); + assert_eq!(outline, "2 entries\nlib/leaf.sv\n module leaf 1-2\n port clk_i 1\n"); + let one = server.text("outline", json!({"file": "lib/leaf.sv", "depth": 1})); + assert_eq!(one, "1 entry\nlib/leaf.sv\n module leaf 1-2\n"); + let past = server.text("outline", json!({"file": "lib/leaf.sv", "offset": 7})); + assert_eq!(past, "2 entries (showing none: `offset` is past the end)\nlib/leaf.sv\n"); + + let hit = server.text("references", json!({"name": "notes"})); + assert_eq!(hit, "1 hit\ndoc/notes.sv\n 2:8 module notes; endmodule\n"); + let cut = server.text("references", json!({"name": "leaf", "limit": 2, "offset": 5})); + assert!(cut.starts_with("7 hits (showing 6–7)\nlib/leaf.sv\n"), "{cut}"); + assert!(!cut.contains("… and"), "{cut}"); + + let finding = server.text("diagnostics", json!({"file": "hw/ip/y.sv"})); + assert_eq!( + finding, + "1 finding\nhw/ip/y.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n" + ); + let define = server.text("defines", json!({"name": "IPX"})); + assert_eq!(define, "1 define\nip/x.sv\n 1 `define IPX 1\n"); + let symbol = server.text("search_symbols", json!({"query": "leaf"})); + assert_eq!(symbol, "1 symbol\nlib/leaf.sv\n module leaf 1\n"); +} + +// --------------------------------------------------------------------------- +// 2. `hierarchy`: `up` from one root counts instantiations, the root line +// on every page; any other walk counts nodes. +// --------------------------------------------------------------------------- + +const LEAF_UP: &str = "leaf lib/leaf.sv:1\n"; + +#[test] +fn qa_hierarchy_up_repeats_its_root_line_on_every_page_and_counts_only_instantiations() { + let (_tree, mut server) = served(); + let (whole, structured) = server.ok("hierarchy", json!({"root": "leaf", "direction": "up"})); + // Deeper lines are instantiations of the ancestors and are counted. + assert_eq!(structured["total"], 11); + assert_eq!(whole.lines().count(), 1 + 1 + 11, "{whole}"); + assert_eq!(structured["nodes"][0]["module"], "leaf", "{structured}"); + for offset in 0..13 { + let args = json!({"root": "leaf", "direction": "up", "limit": 2, "offset": offset}); + let (text, _) = server.ok("hierarchy", args); + let (_, body) = text.split_once('\n').unwrap(); + assert!(body.starts_with(LEAF_UP), "offset {offset}: {text}"); + assert_eq!(body.matches(LEAF_UP).count(), 1, "offset {offset}: {text}"); + } + let page = server.text( + "hierarchy", + json!({"root": "leaf", "direction": "up", "depth": 1, "limit": 2, "offset": 2}), + ); + assert_eq!( + page, + "6 instantiations (showing 3–4)\nleaf lib/leaf.sv:1\n aes.u_b ip/aes/rtl/aes.sv:5\n deep.u_c ip/aes/rtl/sub/deep.sv:3\n… and 2 more\n" + ); + let past = server.text("hierarchy", json!({"root": "leaf", "direction": "up", "offset": 40})); + assert_eq!( + past, + format!("11 instantiations (showing none: `offset` is past the end)\n{LEAF_UP}") + ); + let top = server.text("hierarchy", json!({"root": "tb", "direction": "up"})); + assert_eq!(top, "0 instantiations\ntb ip/aes/dv/tb.sv:1\n"); + let one = server.text("hierarchy", json!({"root": "aes", "direction": "up"})); + assert_eq!(one, "1 instantiation\naes ip/aes/rtl/aes.sv:3\n tb.u_dut ip/aes/dv/tb.sv:3\n"); +} + +#[test] +fn qa_hierarchy_up_from_a_root_declared_twice_counts_every_line_as_nodes() { + let tree = Tree::with(&[ + ("a/d1.sv", "module dup; endmodule\n"), + ("b/d2.sv", "module dup; endmodule\n"), + ("a/user.sv", "module user; dup u1 (); dup u2 (); endmodule\n"), + ]); + let mut server = Session::over(&tree); + let (text, structured) = server.ok("hierarchy", json!({"root": "dup", "direction": "up"})); + assert_eq!( + text, + "6 nodes\ndup a/d1.sv:1\n user.u1 a/user.sv:1\n user.u2 a/user.sv:1\ndup b/d2.sv:1\n user.u1 a/user.sv:1\n user.u2 a/user.sv:1\n" + ); + assert_eq!( + (structured["total"].clone(), structured["shown"].clone()), + (json!(6), json!([1, 6])) + ); + let cut = server.text("hierarchy", json!({"root": "dup", "direction": "up", "limit": 2})); + assert!( + cut.starts_with("6 nodes (showing 1–2)\ndup a/d1.sv:1\n") + && cut.ends_with("… and 4 more\n") + ); +} + +#[test] +fn qa_hierarchy_down_from_several_tops_counts_nodes() { + let (_tree, mut server) = served(); + let (tops, structured) = server.ok("hierarchy", json!({"depth": 1})); + assert_eq!( + tops, + "9 nodes\n\\esc*mod esc/e.sv:1\nhwy hw/ip/y.sv:1\n u_e : leaf\nipx ip/x.sv:2\n u_a : leaf\nnotes doc/notes.sv:2\ntb ip/aes/dv/tb.sv:1\n u_dut : aes\n u_d : leaf\n" + ); + assert_eq!(structured["total"], 9); + let cut = server.text("hierarchy", json!({"depth": 1, "offset": 3, "limit": 3})); + assert_eq!( + cut, + "9 nodes (showing 4–6)\nipx ip/x.sv:2\n u_a : leaf\nnotes doc/notes.sv:2\n… and 3 more\n" + ); +} + +// --------------------------------------------------------------------------- +// 3. `in`: the path matcher through the tools. +// --------------------------------------------------------------------------- + +/// The unit names `list_units` gives under `in`, or the whole text when the +/// answer is not a list. +fn units_in(server: &mut Session, glob: &str) -> Vec { + let (text, structured) = server.ok("list_units", json!({"in": glob})); + if structured["total"] == 0 { + return vec![text]; + } + let units = structured["units"].as_array().unwrap(); + units.iter().map(|u| u["name"].as_str().unwrap().to_string()).collect() +} + +#[test] +fn qa_in_star_stays_in_one_component_and_double_star_spans_zero_or_more() { + let (_tree, mut server) = served(); + let none = || vec!["0 units (none match `in`)\n".to_string()]; + // `*` never crosses a `/`: `sub/deep.sv` is not in `rtl/*.sv`. + assert_eq!(units_in(&mut server, "ip/aes/rtl/*.sv"), ["aes"]); + assert_eq!(units_in(&mut server, "ip/aes/rtl/**"), ["aes", "deep"]); + assert_eq!(units_in(&mut server, "ip/aes/rtl/**/*.sv"), ["aes", "deep"]); + // `**` spans zero components too. + assert_eq!(units_in(&mut server, "ip/**/x.sv"), ["ipx"]); + assert_eq!(units_in(&mut server, "**/x.sv"), ["ipx"]); + assert_eq!(units_in(&mut server, "ip/**/rtl/**/deep.sv"), ["deep"]); + // Anchored at the root: `ip/**` is not `hw/ip/**`. + assert_eq!(units_in(&mut server, "ip/**"), ["tb", "aes", "deep", "ipx"]); + assert_eq!(units_in(&mut server, "**/ip/**"), ["hwy", "tb", "aes", "deep", "ipx"]); + assert_eq!(units_in(&mut server, "hw/ip/*.sv"), ["hwy"]); + assert_eq!(units_in(&mut server, "*/ip/*"), ["hwy"]); + // `?` is one character of one component. + assert_eq!(units_in(&mut server, "ip/ae?/*/*.sv"), ["tb", "aes"]); + assert_eq!(units_in(&mut server, "ip/a?/**"), none()); + assert_eq!(units_in(&mut server, "l?b/m?d.sv"), ["mid"]); + assert_eq!(units_in(&mut server, "ip?x.sv"), none(), "`?` never matches a `/`"); + // A leading `./`, a trailing `/`, `**/**`. + assert_eq!(units_in(&mut server, "./lib/*"), ["leaf", "mid"]); + assert_eq!(units_in(&mut server, "lib/"), ["leaf", "mid"]); + assert_eq!(units_in(&mut server, "**/**/lib/**/**"), ["leaf", "mid"]); + // A whole-path glob is not a substring search. + assert_eq!(units_in(&mut server, "aes"), none()); + assert_eq!(units_in(&mut server, "*.sv"), none()); +} + +#[test] +fn qa_in_matches_paths_never_names_even_escaped_ones_holding_a_star() { + let (_tree, mut server) = served(); + let none = vec!["0 units (none match `in`)\n".to_string()]; + // The unit is named `\esc*mod `; the glob sees only `esc/e.sv`. + assert_eq!(units_in(&mut server, "\\esc*mod "), none); + assert_eq!(units_in(&mut server, "esc*"), none); + assert_eq!(units_in(&mut server, "esc*/*"), ["\\esc*mod"]); + let named = server.text("list_units", json!({"glob": "\\esc*mod", "in": "esc/e.sv"})); + assert_eq!(named, "1 unit\nesc/e.sv\n module \\esc*mod 1\n"); + let symbols = server.text("search_symbols", json!({"query": "esc*", "in": "esc/*"})); + assert!(symbols.starts_with("1 symbol\nesc/e.sv\n"), "{symbols}"); +} + +#[test] +fn qa_in_says_none_match_only_when_it_removed_something() { + let (_tree, mut server) = served(); + // Empty before the glob: the old answer, per tool. + let empty = [ + ("list_units", json!({"glob": "zz", "in": "nowhere/**"}), "no units match\n"), + ("search_symbols", json!({"query": "zz", "in": "nowhere/**"}), "no symbols match\n"), + ("defines", json!({"name": "ZZ", "in": "nowhere/**"}), "no defines\n"), + ("defines", json!({"file": "lib/mid.sv", "in": "nowhere/**"}), "no defines\n"), + ("diagnostics", json!({"file": "lib/mid.sv", "in": "nowhere/**"}), "no findings\n"), + ]; + for (tool, args, said) in empty { + assert_eq!(server.text(tool, args.clone()), said, "{tool} {args}"); + } + let refs = server.text("references", json!({"name": "clk_i", "unit": "leaf", "in": "zz/**"})); + assert_eq!(refs, "0 hits (none match `in`)\n"); + // Emptied by the glob: said so, per tool. + let emptied = [ + ("list_units", json!({"in": "nowhere/**"}), "0 units (none match `in`)\n"), + ("search_symbols", json!({"query": "clk", "in": "doc/*"}), "0 symbols (none match `in`)\n"), + ("defines", json!({"in": "lib/**"}), "0 defines (none match `in`)\n"), + ("defines", json!({"file": "ip/x.sv", "in": "lib/**"}), "0 defines (none match `in`)\n"), + ("diagnostics", json!({"in": "nowhere/**"}), "0 findings (none match `in`)\n"), + ( + "diagnostics", + json!({"file": "ip/x.sv", "in": "lib/*"}), + "0 findings (none match `in`)\n", + ), + ("hierarchy", json!({"in": "lib/**"}), "0 nodes (none match `in`)\n"), + ]; + for (tool, args, said) in emptied { + let (text, structured) = server.ok(tool, args.clone()); + assert_eq!(text, said, "{tool} {args}"); + assert_eq!( + (structured["total"].clone(), structured["shown"].clone()), + (json!(0), json!([0, 0])) + ); + } + // Matched files with nothing to say are clean, not "none match". + assert_eq!(server.text("diagnostics", json!({"in": "lib/**"})), "no findings\n"); + // `in` and a window together: the total is the filtered count. + let (text, structured) = + server.ok("references", json!({"name": "leaf", "in": "ip/**", "offset": 1, "limit": 2})); + assert!(text.starts_with("4 hits (showing 2–3)\n"), "{text}"); + assert!(text.contains("… and 1 more\n"), "{text}"); + assert_eq!(structured["total"], 4); + let past = server.text("list_units", json!({"in": "lib/*", "offset": 2})); + assert_eq!(past, "2 units (showing none: `offset` is past the end)\n"); +} + +#[test] +fn qa_in_on_references_keeps_only_the_mentions_in_matching_files() { + let (_tree, mut server) = served(); + let (all, structured) = server.ok("references", json!({"name": "leaf"})); + assert!(all.contains("doc/notes.sv:1 comment") && all.contains("ip/aes/dv/tb.sv:2 comment")); + assert_eq!(structured["unresolved_mentions"].as_array().unwrap().len(), 2); + let (rtl, structured) = server.ok("references", json!({"name": "leaf", "in": "ip/**"})); + assert!(!rtl.contains("doc/notes.sv"), "a mention outside the glob: {rtl}"); + assert!(rtl.contains("ip/aes/dv/tb.sv:2 comment"), "{rtl}"); + assert_eq!(structured["unresolved_mentions"].as_array().unwrap().len(), 1); + let lib = server.text("references", json!({"name": "leaf", "in": "lib/**"})); + assert_eq!( + lib, + "2 hits\nlib/leaf.sv\n 1:8 module leaf (input logic clk_i);\nlib/mid.sv\n 2:3 leaf u_f (.clk_i(clk_i));\n" + ); + // Hits emptied, a mention kept: both said. + let doc = server.text("references", json!({"name": "leaf", "in": "doc/*"})); + assert!(doc.starts_with("0 hits (none match `in`)\nunresolved mentions"), "{doc}"); + assert!(doc.ends_with(" doc/notes.sv:1 comment: // leaf is the unit under test\n"), "{doc}"); +} + +#[test] +fn qa_in_on_hierarchy_down_drops_a_whole_subtree_and_up_does_not_climb_through_a_drop() { + let (_tree, mut server) = served(); + // `mid` lives in `lib/`; its child `deep` lives in `ip/` but is under a + // dropped node, so it must not appear. + let aes = server.text("hierarchy", json!({"root": "aes", "depth": 5, "in": "ip/**"})); + assert_eq!(aes, "1 node\naes ip/aes/rtl/aes.sv:3\n"); + let tb = server.text("hierarchy", json!({"root": "tb", "depth": 5, "in": "**/rtl/**"})); + assert_eq!(tb, "2 nodes\ntb ip/aes/dv/tb.sv:1\n u_dut : aes\n"); + let tb = server.text("hierarchy", json!({"root": "tb", "depth": 5, "in": "lib/*"})); + assert_eq!(tb, "2 nodes\ntb ip/aes/dv/tb.sv:1\n u_d : leaf\n"); + // No root: tops by their own file, children by theirs. + let dv = server.text("hierarchy", json!({"in": "ip/aes/dv/*", "depth": 5})); + assert_eq!(dv, "1 node\ntb ip/aes/dv/tb.sv:1\n"); + // Up: `mid.u_g` (lib/) is dropped, so `aes.u_m` above it is not reached + // through it; `deep.u_c` (ip/) is kept. + let up = server.text("hierarchy", json!({"root": "deep", "direction": "up", "in": "ip/**"})); + assert_eq!(up, "0 instantiations (none match `in`)\ndeep ip/aes/rtl/sub/deep.sv:1\n"); + let up = server.text("hierarchy", json!({"root": "leaf", "direction": "up", "in": "ip/**"})); + assert_eq!( + up, + "5 instantiations\nleaf lib/leaf.sv:1\n tb.u_d ip/aes/dv/tb.sv:4\n aes.u_b ip/aes/rtl/aes.sv:5\n tb.u_dut ip/aes/dv/tb.sv:3\n deep.u_c ip/aes/rtl/sub/deep.sv:3\n ipx.u_a ip/x.sv:4\n" + ); +} + +#[test] +fn qa_in_on_whole_project_diagnostics_lints_matching_files_and_reports_no_unused_waiver() { + let (_tree, mut server) = served(); + let all = server.text("diagnostics", json!({})); + assert!(all.starts_with("5 findings\n"), "{all}"); + assert!(all.contains("w.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n")); + let (ip, structured) = server.ok("diagnostics", json!({"in": "ip/**"})); + assert_eq!( + ip, + "3 findings\nip/aes/rtl/aes.sv\n 4:9 warning `dead_b` is declared but never used [unused-signal]\nip/aes/rtl/sub/deep.sv\n 2:9 warning `dead_c` is declared but never used [unused-signal]\nip/x.sv\n 3:9 warning `dead_a` is declared but never used [unused-signal]\n" + ); + assert_eq!(structured["total"], 3); + for glob in ["**/*.sv", "hw/**", "*.waiver", "w.waiver"] { + let text = server.text("diagnostics", json!({"in": glob})); + assert!(!text.contains("unused-waiver"), "{glob}: {text}"); + } + // `in` + severity + a window. + let args = json!({"in": "**/ip/**", "severity": "warning", "offset": 2, "limit": 5}); + let (text, structured) = server.ok("diagnostics", args); + assert!(text.starts_with("3 findings (showing 3)\nip/x.sv\n"), "{text}"); + assert_eq!(structured["shown"], json!([3, 3])); +} + +// --------------------------------------------------------------------------- +// 4. The check line on the six design-wide edits. +// --------------------------------------------------------------------------- + +/// The last line of an answer. +fn last_line(text: &str) -> &str { + text.trim_end_matches('\n').rsplit('\n').next().unwrap_or_default() +} + +#[test] +fn qa_each_edit_ends_with_its_check_line_dry_and_real_and_nothing_else_does() { + let (tree, mut server) = served(); + let cases = [ + ("rename", json!({"name": "mid", "new_name": "mid2"}), "ip/aes/rtl/aes.sv, lib/mid.sv"), + ( + "add_port", + json!({"module": "deep", "declaration": "input logic en"}), + "ip/aes/rtl/sub/deep.sv, lib/mid.sv", + ), + ("expand_wildcard", json!({"file": "ip/wild.sv", "line": 2}), "ip/wild.sv"), + ( + "remove_port", + json!({"file": "lib/solo.sv", "line": 1, "name": "k"}), + "ip/wild.sv, lib/solo.sv", + ), + ("inline_module", json!({"file": "ip/wild.sv", "line": 2, "name": "u_l"}), "ip/wild.sv"), + ( + "extract_module", + json!({"file": "ip/x.sv", "start_line": 4, "end_line": 4, "new_name": "slot"}), + "ip/slot.sv, ip/x.sv", + ), + ]; + fs::write( + tree.0.join("lib/solo.sv"), + "module solo (input logic a, input logic k);\nendmodule\n", + ) + .unwrap(); + fs::write( + tree.0.join("ip/wild.sv"), + "module wild (input logic a, input logic k);\n solo u_l (.*);\nendmodule\n", + ) + .unwrap(); + for (tool, args, files) in cases { + let before = tree.snapshot(); + let mut dry = args.clone(); + dry["dry_run"] = json!(true); + let (text, structured) = server.ok(tool, dry); + assert_eq!( + last_line(&text), + format!("check after writing: diagnostics on {files}"), + "{tool}" + ); + assert_eq!(text.matches("diagnostics on").count(), 1, "{tool}: {text}"); + assert!(structured.get("check").is_none(), "{tool}: the JSON is unchanged"); + assert!(before == tree.snapshot(), "{tool}: a dry run wrote"); + let (text, _) = server.ok(tool, args.clone()); + assert_eq!(last_line(&text), format!("check: diagnostics on {files}"), "{tool}: {text}"); + // Once more: `unchanged` or a refusal, never a check line. + let (_, again, _) = server.call(tool, args.clone()); + assert!(!again.contains("diagnostics on"), "{tool} again: {again}"); + } + let unchanged = server.text("rename", json!({"name": "leaf", "new_name": "leaf"})); + assert_eq!(unchanged, "unchanged\n"); + // The edits outside the brief carry no line. + let args = json!({"file": "lib/leaf.sv", "line": 1, "dry_run": true}); + let (_, ports, _) = server.call("convert_ports", args); + assert!(!ports.contains("diagnostics on"), "{ports}"); +} + +#[test] +fn qa_the_check_line_names_five_files_in_path_order_and_counts_the_rest() { + let mut files: Vec<(String, String)> = + vec![("z/leaf.sv".into(), "module leaf (input logic a);\nendmodule\n".into())]; + for (i, dir) in ["q", "B", "a", "a/b", "m", "a.x", "c"].iter().enumerate() { + let text = format!("module u{i} (input logic a);\n leaf u_l (.a(a));\nendmodule\n"); + files.push((format!("{dir}/u{i}.sv"), text)); + } + let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect(); + let tree = Tree::with(&borrowed); + let mut server = Session::over(&tree); + let args = json!({"name": "leaf", "new_name": "leaf_r", "dry_run": true}); + let text = server.text("rename", args); + // Byte order: `B` < `a.x` < `a/` (`.` < `/`) < `c` …; 8 files, 5 named. + assert_eq!( + last_line(&text), + "check after writing: diagnostics on B/u1.sv, a.x/u5.sv, a/b/u3.sv, a/u2.sv, c/u6.sv and 3 more" + ); + let text = server.text("rename", json!({"name": "leaf", "new_name": "leaf_r"})); + assert!(text.ends_with("c/u6.sv and 3 more\n"), "{text}"); +} + +// --------------------------------------------------------------------------- +// 5. The catalogue and the instructions. +// --------------------------------------------------------------------------- + +#[test] +fn qa_catalogue_and_instructions_stay_in_budget_and_name_real_tools() { + let (_tree, mut server) = served(); + let instructions = server.init["result"]["instructions"].as_str().unwrap().to_string(); + assert!(instructions.chars().count() <= 900, "{} chars", instructions.chars().count()); + let reply = server.request("tools/list", json!({})); + assert!(reply["result"].to_string().len() <= 18_000); + let tools = reply["result"]["tools"].as_array().unwrap(); + 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), "`{word}` in the instructions is no tool"); + } + for bare in + ["outline", "definition", "references", "hierarchy", "format", "rename", "diagnostics"] + { + assert!(instructions.contains(bare) && names.contains(&bare), "{bare}"); + } + for tool in tools { + 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 takes_in = tool["inputSchema"]["properties"].get("in").is_some(); + let lists = + ["list_units", "search_symbols", "references", "hierarchy", "diagnostics", "defines"]; + assert_eq!(takes_in, lists.contains(&tool["name"].as_str().unwrap()), "{}", tool["name"]); + let limit = &tool["inputSchema"]["properties"]["limit"]["description"]; + assert!(limit.is_null() || limit.as_str().unwrap().contains("500"), "{}", tool["name"]); + } +} diff --git a/crates/lucisv_mcp/tests/qa_m1.rs b/crates/lucisv_mcp/tests/qa_m1.rs index b7f0e1b..9004401 100644 --- a/crates/lucisv_mcp/tests/qa_m1.rs +++ b/crates/lucisv_mcp/tests/qa_m1.rs @@ -477,14 +477,17 @@ fn qa_crlf_files_keep_their_line_numbers_and_read_item_returns_the_exact_bytes() let scratch = Scratch::with(&[("crlf.sv", text)]); let mut s = Session::ready(&scratch); let outline = s.text("outline", json!({"file": "crlf.sv"})); - assert_eq!(outline, "crlf.sv\n module crlf 2-9\n port clk 3\n port q 4\n var x 6\n"); + assert_eq!( + outline, + "4 entries\ncrlf.sv\n module crlf 2-9\n port clk 3\n port q 4\n var x 6\n" + ); let result = s.call("read_item", json!({"file": "crlf.sv", "item": "always@8"})); assert_eq!(result["structuredContent"]["lines"], json!([7, 8])); assert_eq!(result["structuredContent"]["text"], "always_ff @(posedge clk)\r\n q <= x;"); let module = s.call("read_item", json!({"file": "crlf.sv", "item": "crlf"})); let start = text.find("module").unwrap(); assert_eq!(module["structuredContent"]["text"], &text[start..text.len() - 2]); - assert_eq!(s.text("list_units", json!({})), "crlf.sv\n module crlf 2\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\ncrlf.sv\n module crlf 2\n"); } #[test] @@ -495,7 +498,10 @@ fn qa_multibyte_text_before_an_item_keeps_lines_right() { )]); let mut s = Session::ready(&scratch); let outline = s.text("outline", json!({"file": "utf.sv"})); - assert_eq!(outline, "utf.sv\n module utf 2-4\n port a 2\n var z 2\n var w 3\n"); + assert_eq!( + outline, + "4 entries\nutf.sv\n module utf 2-4\n port a 2\n var z 2\n var w 3\n" + ); let w = s.call("read_item", json!({"file": "utf.sv", "item": "w"})); assert_eq!(w["structuredContent"]["text"], "logic w;"); assert_eq!(w["structuredContent"]["lines"], json!([3, 3])); @@ -647,7 +653,7 @@ fn qa_an_escaped_name_holding_at_or_colon_is_selectable_by_itself() { fn qa_rename_then_recreate_in_the_same_mtime_second_is_seen() { let scratch = Scratch::with(&[("a.sv", "module alpha; endmodule\n")]); let mut s = Session::ready(&scratch); - assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n"); let old = mtime(&scratch.path("a.sv")); fs::rename(scratch.path("a.sv"), scratch.path("b.sv")).unwrap(); scratch.write("a.sv", b"module gamma; endmodule\n"); @@ -670,7 +676,7 @@ fn qa_a_same_size_rewrite_with_the_same_mtime_is_caught_by_the_racy_rule() { let old = mtime(&scratch.path("a.sv")); scratch.write("a.sv", b"module delta; endmodule\n"); set_mtime(&scratch.path("a.sv"), old); - assert_eq!(s.text("list_units", json!({})), "a.sv\n module delta 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module delta 1\n"); let answer = s.text("unit_interface", json!({"name": "delta"})); assert!(answer.starts_with("module delta a.sv:1"), "{answer}"); } @@ -688,7 +694,7 @@ fn qa_a_same_size_rewrite_that_restores_an_old_mtime_is_seen() { s.text("list_units", json!({})); scratch.write("c.sv", b"module chxrlie; endmodule\n"); set_mtime(&scratch.path("c.sv"), long_ago); - assert_eq!(s.text("list_units", json!({})), "c.sv\n module chxrlie 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chxrlie 1\n"); } #[test] @@ -700,7 +706,10 @@ fn qa_a_new_file_in_a_new_subdirectory_appears_at_the_next_walk() { // project_overview always walks; every later call sees the file. let overview = s.call("project_overview", json!({})); assert_eq!(overview["structuredContent"]["files"], 2); - assert_eq!(s.text("list_units", json!({"glob": "newbie"})), "n1/n2/n.sv\n module newbie 1\n"); + assert_eq!( + s.text("list_units", json!({"glob": "newbie"})), + "1 unit\nn1/n2/n.sv\n module newbie 1\n" + ); assert!(s.text("unit_interface", json!({"name": "newbie"})).contains("input k")); } @@ -729,7 +738,7 @@ fn qa_a_file_growing_past_one_mib_drops_out_of_the_index() { big.extend(std::iter::repeat_n(b'x', 1024 * 1024)); big.push(b'\n'); scratch.write("a.sv", &big); - assert_eq!(s.text("list_units", json!({})), "c.sv\n module charlie 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module charlie 1\n"); let overview = s.call("project_overview", json!({})); assert_eq!(overview["structuredContent"]["skipped_large"], 1); assert_eq!(overview["structuredContent"]["files"], 1); @@ -745,7 +754,7 @@ fn qa_a_gitignore_added_after_startup_drops_its_files_at_the_next_walk() { assert!(s.text("list_units", json!({})).contains("generated")); scratch.write(".gitignore", b"gen/\n"); s.text("project_overview", json!({})); - assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n"); } #[test] @@ -792,7 +801,7 @@ fn qa_the_walk_does_not_index_files_outside_the_roots_through_symlinks() { let scratch = Scratch::with(SMALL); std::os::unix::fs::symlink(outside.path("secret.sv"), scratch.path("link.sv")).unwrap(); let mut s = Session::ready(&scratch); - assert_eq!(s.text("list_units", json!({})), "x.sv\n module x 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\nx.sv\n module x 1\n"); s.refusal("unit_interface", json!({"name": "secret_mod"})); } @@ -808,11 +817,11 @@ fn qa_nested_roots_index_each_file_once() { s.initialize(); assert_eq!( s.text("list_units", json!({})), - "a.sv\n module alpha 1\nsub/b.sv\n module beta 1\n" + "2 units\na.sv\n module alpha 1\nsub/b.sv\n module beta 1\n" ); assert_eq!(s.call("project_overview", json!({}))["structuredContent"]["files"], 2); // The inner root still resolves its own relative paths. - assert!(s.text("outline", json!({"file": "b.sv"})).starts_with("sub/b.sv\n")); + assert!(s.text("outline", json!({"file": "b.sv"})).starts_with("1 entry\nsub/b.sv\n")); } #[test] @@ -820,7 +829,7 @@ fn qa_a_relative_root_is_resolved_against_the_working_directory() { let scratch = Scratch::with(&[("rtl/sub/b.sv", "module beta; endmodule\n")]); let mut s = Session::spawn_in(&["--root", "rtl/sub"], Some(&scratch.0)); s.initialize(); - assert_eq!(s.text("list_units", json!({})), "b.sv\n module beta 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\nb.sv\n module beta 1\n"); let roots = s.call("project_overview", json!({}))["structuredContent"]["roots"].clone(); assert_eq!(roots, json!([scratch.path("rtl/sub")])); } @@ -889,7 +898,7 @@ fn qa_rework_a_symlinked_directory_leaving_the_root_is_dropped_warned_and_a_loop std::os::unix::fs::symlink("rtl/in.sv", scratch.path("alias.sv")).unwrap(); std::os::unix::fs::symlink(&scratch.0, outside.path("back")).unwrap(); let mut s = Session::ready(&scratch); - assert_eq!(s.text("list_units", json!({})), "rtl/in.sv\n module inner_mod 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\nrtl/in.sv\n module inner_mod 1\n"); let overview = s.call("project_overview", json!({}))["structuredContent"].clone(); assert_eq!(overview["files"], 1); let warnings = overview["warnings"].as_array().unwrap(); @@ -962,11 +971,14 @@ fn qa_rework_every_by_name_tool_finds_a_file_written_just_now() { scratch.write("m1.sv", b"module fresh1 (input k1); endmodule\n"); assert!(s.text("unit_interface", json!({"name": "fresh1"})).contains("input k1")); scratch.write("m2.sv", b"module fresh2 (input k2); endmodule\n"); - assert_eq!(s.text("list_units", json!({"glob": "fresh2"})), "m2.sv\n module fresh2 1\n"); + assert_eq!( + s.text("list_units", json!({"glob": "fresh2"})), + "1 unit\nm2.sv\n module fresh2 1\n" + ); scratch.write("n/m/m3.sv", b"module fresh3 (input k3); endmodule\n"); assert_eq!( s.text("search_symbols", json!({"query": "fresh3"})), - "n/m/m3.sv\n module fresh3 1\n" + "1 symbol\nn/m/m3.sv\n module fresh3 1\n" ); // A package member and a class in a new file, by `pkg::cls`. scratch.write("p.sv", b"package fp; class fc; int f; endclass endpackage\n"); @@ -986,7 +998,7 @@ fn qa_rework_a_legitimate_miss_does_not_make_later_hits_walk() { assert_eq!(s.text("search_symbols", json!({"query": "zzqq"})), "no symbols match\n"); } scratch.write("late.sv", b"module late; endmodule\n"); - assert_eq!(s.text("list_units", json!({})), "x.sv\n module x 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\nx.sv\n module x 1\n"); assert!(s.text("outline", json!({"file": "late.sv"})).contains("module late 1")); s.text("project_overview", json!({})); assert!(s.text("list_units", json!({})).contains("late.sv")); @@ -1019,7 +1031,7 @@ fn qa_rework_a_file_that_stops_being_utf8_is_warned_and_leaves_the_index() { let mut s = Session::ready(&scratch); assert!(s.text("list_units", json!({})).contains("beta")); scratch.write("b.sv", b"module beta; // \xe9\xff\nendmodule\n"); - assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n"); let overview = s.call("project_overview", json!({}))["structuredContent"].clone(); assert_eq!(overview["warnings"], json!(["b.sv: not UTF-8 text"])); assert_eq!(overview["files"], 1); @@ -1041,10 +1053,10 @@ fn qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen() { s.text("list_units", json!({})); fs::rename(scratch.path("stash/c.txt"), scratch.path("c.sv")).unwrap(); assert_eq!(mtime(&scratch.path("c.sv")), long_ago); - assert_eq!(s.text("list_units", json!({})), "c.sv\n module chxrlie 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chxrlie 1\n"); // cp -p of a same-size file with the same old mtime: ctime moves. fs::write(scratch.path("stash/d.txt"), "module chyrlie; endmodule\n").unwrap(); fs::copy(scratch.path("stash/d.txt"), scratch.path("c.sv")).unwrap(); set_mtime(&scratch.path("c.sv"), long_ago); - assert_eq!(s.text("list_units", json!({})), "c.sv\n module chyrlie 1\n"); + assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chyrlie 1\n"); } diff --git a/crates/lucisv_mcp/tests/qa_m2.rs b/crates/lucisv_mcp/tests/qa_m2.rs index 66f736a..38ff852 100644 --- a/crates/lucisv_mcp/tests/qa_m2.rs +++ b/crates/lucisv_mcp/tests/qa_m2.rs @@ -342,7 +342,7 @@ fn qa_byte_columns_hold_after_multibyte_text_and_in_crlf_files() { } assert_eq!(s.sites(json!({"file": "crlf.sv", "line": 3, "name": "cc"})), ["crlf.sv:2:9 var"]); let crlf = s.text("references", json!({"file": "crlf.sv", "line": 3, "col": 10})); - assert_eq!(crlf, "crlf.sv\n 2:9 logic cc;\n 3:10 assign cc = a;\n"); + assert_eq!(crlf, "2 hits\ncrlf.sv\n 2:9 logic cc;\n 3:10 assign cc = a;\n"); assert!(s.pings()); } @@ -483,11 +483,11 @@ fn qa_hierarchy_terminates_on_self_and_mutual_recursion() { let scratch = Scratch::with(HIER); let mut s = Session::ready(&scratch); let selfm = s.text("hierarchy", json!({"root": "selfm", "depth": 20})); - assert_eq!(selfm, "selfm self.sv:1\n u_s : selfm #(.N(N-1)) (recursive)\n"); + assert_eq!(selfm, "2 nodes\nselfm self.sv:1\n u_s : selfm #(.N(N-1)) (recursive)\n"); let mutual = s.text("hierarchy", json!({"root": "ma", "depth": 20})); - assert_eq!(mutual, "ma mutual.sv:1\n u_b : mb\n u_a : ma (recursive)\n"); + assert_eq!(mutual, "3 nodes\nma mutual.sv:1\n u_b : mb\n u_a : ma (recursive)\n"); let up = s.text("hierarchy", json!({"root": "ma", "direction": "up", "depth": 20})); - assert_eq!(up, "ma mutual.sv:1\n mb.u_a mutual.sv:2\n ma.u_b mutual.sv:1 (recursive)\n mtop.u mutual.sv:3\n"); + assert_eq!(up, "3 instantiations\nma mutual.sv:1\n mb.u_a mutual.sv:2\n ma.u_b mutual.sv:1 (recursive)\n mtop.u mutual.sv:3\n"); } #[test] @@ -495,7 +495,8 @@ fn qa_hierarchy_depth_is_capped_and_bad_arguments_are_schema_refusals() { let scratch = Scratch::with(&[("chain.sv", &chain(30))]); let mut s = Session::ready(&scratch); let deep = s.text("hierarchy", json!({"root": "c0", "depth": 20})); - assert_eq!(deep.lines().count(), 21, "{deep}"); + // The count line, the root, twenty levels. + assert_eq!(deep.lines().count(), 22, "{deep}"); assert!(deep.ends_with("u19 : c20\n") && !deep.contains("c21"), "{deep}"); for depth in [json!(0), json!(-1), json!(2.5), json!("3")] { let refused = s.refusal("hierarchy", json!({"root": "c0", "depth": depth})); @@ -527,7 +528,7 @@ fn qa_hierarchy_marks_not_modules_duplicates_and_two_parents() { assert!(refused.contains(&format!("`{root}`")), "{refused}"); } let dupe = s.text("hierarchy", json!({"root": "usedupe"})); - assert_eq!(dupe, "usedupe usedupe.sv:1\n u_d : dupe (declared 2 times)\n"); + assert_eq!(dupe, "2 nodes\nusedupe usedupe.sv:1\n u_d : dupe (declared 2 times)\n"); let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"})); assert!(up.contains(" p1.u_l1 p1.sv:1\n p1.u_l2 p1.sv:1\n p2.u_l p2.sv:1\n"), "{up}"); } @@ -593,14 +594,14 @@ fn qa_diagnostics_follow_each_files_own_config_directory() { // Root config: select 3, ignore no-tabs, length 45, a/waived.sv waived. assert_eq!( s.text("diagnostics", json!({"file": "a/m.sv"})), - "a/m.sv\n 2:46 style line is 50 characters; the limit is 45 [line-length]\n" + "1 finding\na/m.sv\n 2:46 style line is 50 characters; the limit is 45 [line-length]\n" ); assert_eq!(s.text("diagnostics", json!({"file": "a/waived.sv"})), "no findings\n"); // b/lucisv.toml: its own select (no-tabs back) and its own line-length // 60, which the 59-character line 2 is inside (45 would flag it). assert_eq!( s.text("diagnostics", json!({"file": "b/n.sv"})), - "b/n.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n" + "1 finding\nb/n.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n" ); // `rules` replaces select; the config's ignore still applies. assert_eq!( @@ -696,7 +697,7 @@ fn qa_defines_list_every_definition_and_never_pick_one() { ("d.sv", "module d; localparam int P = `TWICE; endmodule\n"), ]); let mut s = Session::ready(&scratch); - let twice = "a.svh\n 1 `define TWICE 1\nb.svh\n 1 `define TWICE 2\n"; + let twice = "2 defines\na.svh\n 1 `define TWICE 1\nb.svh\n 1 `define TWICE 2\n"; assert_eq!(s.text("defines", json!({"name": "TWICE"})), twice); assert_eq!(s.text("defines", json!({"name": "`TWICE"})), twice); assert_eq!( @@ -711,7 +712,7 @@ fn qa_defines_list_every_definition_and_never_pick_one() { assert_eq!(s.text("defines", json!({"name": "NOPE"})), "no defines\n"); assert_eq!( s.text("defines", json!({"file": "b.svh", "name": "TWICE"})), - "b.svh\n 1 `define TWICE 2\n 2 `undef TWICE\n" + "2 defines\nb.svh\n 1 `define TWICE 2\n 2 `undef TWICE\n" ); assert_eq!(s.text("defines", json!({"file": "a.svh", "name": "NOPE"})), "no defines\n"); let missing = s.refusal("defines", json!({"file": "nope.sv"})); @@ -745,7 +746,9 @@ fn qa_resources_refuse_what_they_cannot_name_and_decode_escapes() { ] { let reply = read(&mut s, uri); let text = reply["result"]["contents"][0]["text"].as_str().unwrap_or(""); - assert!(text.starts_with(starts), "{uri}: {reply}"); + // The outline's count line, then the file. + let (_, file) = text.split_once('\n').unwrap_or_default(); + assert!(file.starts_with(starts), "{uri}: {reply}"); } for uri in [ "lucisv://unit/dup", @@ -791,16 +794,19 @@ fn qa_references_and_hierarchy_follow_edits_and_deletions() { assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3", "top.sv:4:3"]); assert_eq!( s.text("hierarchy", json!({"root": "top"})), - "top top.sv:1\n u1 : leaf\n u2 : leaf\n" + "3 nodes\ntop top.sv:1\n u1 : leaf\n u2 : leaf\n" ); fs::remove_file(scratch.path("top.sv")).unwrap(); assert!(s.refusal("hierarchy", json!({"root": "top"})).contains("`top`")); - assert_eq!(s.text("hierarchy", json!({"root": "leaf", "direction": "up"})), "leaf leaf.sv:1\n"); + assert_eq!( + s.text("hierarchy", json!({"root": "leaf", "direction": "up"})), + "0 instantiations\nleaf leaf.sv:1\n" + ); scratch.write("other.sv", "module other; leaf u9 (.a()); endmodule\n"); fs::remove_file(scratch.path("leaf.sv")).unwrap(); assert_eq!( s.text("hierarchy", json!({"root": "other"})), - "other other.sv:1\n u9 : leaf (not indexed)\n" + "2 nodes\nother other.sv:1\n u9 : leaf (not indexed)\n" ); assert!(s.refusal("definition", json!({"name": "leaf"})).contains("`leaf`")); } @@ -900,7 +906,7 @@ fn qa_recheck_overrides_split_across_lines_and_comments_between_instances() { let mut s = Session::ready(&scratch); assert_eq!( s.text("hierarchy", json!({"root": "ov"})), - "ov ov.sv:1\n u_a : leaf #(.W(2))\n u_b : leaf #(.W(2))\n u_c : leaf #(.W(2))\n u_d : leaf\n u_e : leaf\n u_f : leaf\n u_g : leaf #( .W(3) )\n u_h : leaf #( .W(3) )\n u_i : leaf #( .W(3) )\n u_j : leaf #(.W(4))\n u_k : leaf #(.W(5))\n u_l : leaf\n u_m : leaf\n" + "14 nodes\nov ov.sv:1\n u_a : leaf #(.W(2))\n u_b : leaf #(.W(2))\n u_c : leaf #(.W(2))\n u_d : leaf\n u_e : leaf\n u_f : leaf\n u_g : leaf #( .W(3) )\n u_h : leaf #( .W(3) )\n u_i : leaf #( .W(3) )\n u_j : leaf #(.W(4))\n u_k : leaf #(.W(5))\n u_l : leaf\n u_m : leaf\n" ); let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"})); assert!(up.contains(" ov.u_i #( .W(3) ) ov.sv:9\n ov.u_j #(.W(4)) ov.sv:10\n"), "{up}"); @@ -920,7 +926,8 @@ fn qa_recheck_depth_twenty_is_the_schema_maximum() { .clone(); let depth = &hierarchy["inputSchema"]["properties"]["depth"]; assert_eq!((depth["minimum"].clone(), depth["maximum"].clone()), (json!(1), json!(20))); - assert_eq!(s.text("hierarchy", json!({"root": "c0", "depth": 20})).lines().count(), 21); + // The count line, the root, twenty levels. + assert_eq!(s.text("hierarchy", json!({"root": "c0", "depth": 20})).lines().count(), 22); let refused = s.refusal("hierarchy", json!({"root": "c0", "depth": 21})); assert!(refused.contains("from 1 to 20"), "{refused}"); } @@ -1038,7 +1045,7 @@ fn qa_recheck_unused_waivers_match_lucisv_check_of_the_tree() { let mut s = Session::ready(&scratch); assert_eq!( s.text("diagnostics", json!({})), - "w.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n" + "1 finding\nw.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n" ); assert_eq!(s.text("diagnostics", json!({"rules": "no-tabs"})), "no findings\n"); assert_eq!(s.text("diagnostics", json!({"file": "m.sv"})), "no findings\n"); @@ -1055,7 +1062,7 @@ fn qa_recheck_one_files_diagnostics_are_its_lines_of_lucisv_check_dot() { let mut s = Session::ready(&scratch); assert_eq!( s.text("diagnostics", json!({"file": "top.sv"})), - "top.sv\n 2:12 error `leaf` declares no port `b` [unknown-port]\n" + "1 finding\ntop.sv\n 2:12 error `leaf` declares no port `b` [unknown-port]\n" ); assert_eq!(s.text("diagnostics", json!({"file": "leaf.sv"})), "no findings\n"); } diff --git a/crates/lucisv_mcp/tests/wire.rs b/crates/lucisv_mcp/tests/wire.rs index eee96ff..d3e98d4 100644 --- a/crates/lucisv_mcp/tests/wire.rs +++ b/crates/lucisv_mcp/tests/wire.rs @@ -334,10 +334,11 @@ fn outline_and_read_item_slice_one_file() { let mut server = Session::over(&tree); server.initialize(); let outline = server.text("outline", json!({"file": "rtl/top.sv"})); - assert!(outline.starts_with("rtl/top.sv\n module top 1-16\n port clk 4\n"), "{outline}"); + let head = "8 entries\nrtl/top.sv\n module top 1-16\n port clk 4\n"; + assert!(outline.starts_with(head), "{outline}"); assert!(outline.contains(" instance u_leaf 10\n"), "{outline}"); let shallow = server.text("outline", json!({"file": "rtl/top.sv", "depth": 1})); - assert_eq!(shallow, "rtl/top.sv\n module top 1-16\n"); + assert_eq!(shallow, "1 entry\nrtl/top.sv\n module top 1-16\n"); let broken = server.call("outline", json!({"file": "rtl/broken.sv"})); assert_eq!(broken["structuredContent"]["parse_errors"][0]["line"], 2); assert!(broken["content"][0]["text"].as_str().unwrap().contains("parse errors: 1 (first 2:14")); @@ -376,14 +377,14 @@ fn search_symbols_finds_units_and_members_by_substring() { json!([{"name": "types_pkg::word_t", "kind": "typedef", "file": "pkg/types_pkg.sv", "line": 4}]) ); let modules = server.text("search_symbols", json!({"query": "lea"})); - assert_eq!(modules, "rtl/leaf.sv\n module leaf 1\n"); + assert_eq!(modules, "1 symbol\nrtl/leaf.sv\n module leaf 1\n"); let capped = server.text("search_symbols", json!({"query": "", "limit": 1})); // A file written after startup is found by name without waiting for the // periodic walk (QA finding 3). fs::write(tree.path("rtl/brand_new.sv"), "module brand_new; endmodule\n").unwrap(); assert_eq!( server.text("search_symbols", json!({"query": "brand_new"})), - "rtl/brand_new.sv\n module brand_new 1\n" + "1 symbol\nrtl/brand_new.sv\n module brand_new 1\n" ); assert!(capped.contains("… and "), "{capped}"); } @@ -585,7 +586,7 @@ fn references_reach_bind_connections_hierarchical_tails_and_class_members() { let state = server.call("references", json!({"name": "state_q", "unit": "core"})); assert_eq!( state["content"][0]["text"], - "rtl/core.sv\n 9:17 logic [W-1:0] state_q;\n 12:5 state_q <= `ADD(d, 1);\n 13:14 assign q = state_q;\nrtl/core_bind.sv\n 1:37 bind core checker_m u_chk (.state_q(state_q));\nrtl/top.sv\n 8:25 assign peek = u_core0.state_q;\n" + "5 hits\nrtl/core.sv\n 9:17 logic [W-1:0] state_q;\n 12:5 state_q <= `ADD(d, 1);\n 13:14 assign q = state_q;\nrtl/core_bind.sv\n 1:37 bind core checker_m u_chk (.state_q(state_q));\nrtl/top.sv\n 8:25 assign peek = u_core0.state_q;\n" ); assert_eq!(state["structuredContent"]["total"], 5); assert_eq!( @@ -602,11 +603,11 @@ fn references_reach_bind_connections_hierarchical_tails_and_class_members() { assert_eq!(from_use, count); assert_eq!( count, - "tb/env.sv\n 4:7 s.count = 0;\ntb/sb.sv\n 2:7 int count;\n 4:5 count++;\n" + "3 hits\ntb/env.sv\n 4:7 s.count = 0;\ntb/sb.sv\n 2:7 int count;\n 4:5 count++;\n" ); let no_decl = json!({"name": "core", "include_declaration": false, "limit": 2}); let core = server.text("references", no_decl); - assert_eq!(core, "rtl/core_bind.sv\n 1:6 bind core checker_m u_chk (.state_q(state_q));\nrtl/top.sv\n 4:3 core #(.W(4)) u_core0 (.clk, .d, .q(q0));\n… and 1 more\n"); + assert_eq!(core, "3 hits (showing 1–2)\nrtl/core_bind.sv\n 1:6 bind core checker_m u_chk (.state_q(state_q));\nrtl/top.sv\n 4:3 core #(.W(4)) u_core0 (.clk, .d, .q(q0));\n… and 1 more\n"); let dual = server.call("references", json!({"name": "y", "unit": "dual"})); assert_eq!(dual["structuredContent"]["total"], 4); @@ -626,7 +627,7 @@ fn hierarchy_walks_down_and_up_and_terminates_on_recursion() { let tops = server.text("hierarchy", json!({})); assert_eq!( tops, - "chain_a rtl/chain.sv:1\n u_b : chain_b\n u_c : chain_c\n u_d : chain_d\nchecker_m rtl/checker_m.sv:1\ndual rtl/dual.sv:1\ntop rtl/top.sv:1\n u_core0 : core #(.W(4))\n u_core1 : core #( .W (8) )\n" + "9 nodes\nchain_a rtl/chain.sv:1\n u_b : chain_b\n u_c : chain_c\n u_d : chain_d\nchecker_m rtl/checker_m.sv:1\ndual rtl/dual.sv:1\ntop rtl/top.sv:1\n u_core0 : core #(.W(4))\n u_core1 : core #( .W (8) )\n" ); let deep = server.text("hierarchy", json!({"root": "chain_a", "depth": 20})); let capped = refusal(&mut server, "hierarchy", json!({"root": "chain_a", "depth": 21})); @@ -635,13 +636,13 @@ fn hierarchy_walks_down_and_up_and_terminates_on_recursion() { let recursive = server.call("hierarchy", json!({"root": "tree", "depth": 20})); assert_eq!( recursive["content"][0]["text"], - "tree rtl/tree.sv:1\n u_left : tree #(.N(N / 2)) (recursive)\n u_right : tree #(.N(N / 2)) (recursive)\n" + "3 nodes\ntree rtl/tree.sv:1\n u_left : tree #(.N(N / 2)) (recursive)\n u_right : tree #(.N(N / 2)) (recursive)\n" ); assert_eq!(recursive["structuredContent"]["nodes"][1]["note"], "recursive"); let up = server.call("hierarchy", json!({"root": "core", "direction": "up"})); assert_eq!( up["content"][0]["text"], - "core rtl/core.sv:2\n top.u_core0 #(.W(4)) rtl/top.sv:4\n top.u_core1 #( .W (8) ) rtl/top.sv:7\n" + "2 instantiations\ncore rtl/core.sv:2\n top.u_core0 #(.W(4)) rtl/top.sv:4\n top.u_core1 #( .W (8) ) rtl/top.sv:7\n" ); assert_eq!( up["structuredContent"]["nodes"][2], @@ -650,7 +651,7 @@ fn hierarchy_walks_down_and_up_and_terminates_on_recursion() { let chain = server.text("hierarchy", json!({"root": "chain_e", "direction": "up", "depth": 2})); assert_eq!( chain, - "chain_e rtl/chain.sv:5\n chain_d.u_e rtl/chain.sv:4\n chain_c.u_d rtl/chain.sv:3\n" + "2 instantiations\nchain_e rtl/chain.sv:5\n chain_d.u_e rtl/chain.sv:4\n chain_c.u_d rtl/chain.sv:3\n" ); assert!( refusal(&mut server, "hierarchy", json!({"direction": "up"})).contains("needs a `root`") @@ -668,7 +669,7 @@ fn diagnostics_follow_the_projects_lint_config_and_filters() { let all = server.call("diagnostics", json!({})); assert_eq!( all["content"][0]["text"], - "rtl/checker_m.sv\n 1:41 style line is 45 characters; the limit is 40 [line-length]\nrtl/core.sv\n 10:17 warning `spare` is declared but never used [unused-signal]\nrtl/core_bind.sv\n 1:41 style line is 46 characters; the limit is 40 [line-length]\nrtl/top.sv\n 4:41 style line is 43 characters; the limit is 40 [line-length]\n" + "4 findings\nrtl/checker_m.sv\n 1:41 style line is 45 characters; the limit is 40 [line-length]\nrtl/core.sv\n 10:17 warning `spare` is declared but never used [unused-signal]\nrtl/core_bind.sv\n 1:41 style line is 46 characters; the limit is 40 [line-length]\nrtl/top.sv\n 4:41 style line is 43 characters; the limit is 40 [line-length]\n" ); assert_eq!( all["structuredContent"]["diagnostics"][1], @@ -704,7 +705,8 @@ fn defines_lists_one_file_one_macro_or_the_project() { let tree = Tree::of("nav"); let mut server = Session::over(&tree); server.initialize(); - let table = "rtl/defs.svh\n 1 `define NAV_W 4\n 2 `define ADD(a, b = 1) ((a) + (b))\n"; + let table = + "2 defines\nrtl/defs.svh\n 1 `define NAV_W 4\n 2 `define ADD(a, b = 1) ((a) + (b))\n"; assert_eq!(server.text("defines", json!({})), table); assert_eq!(server.text("defines", json!({"file": "rtl/defs.svh"})), table); let add = server.call("defines", json!({"name": "`ADD"})); @@ -715,7 +717,7 @@ fn defines_lists_one_file_one_macro_or_the_project() { assert_eq!(server.text("defines", json!({"name": "NOPE"})), "no defines\n"); fs::write(tree.path("rtl/undef.sv"), "`define T 1\n`undef T\n").unwrap(); let local = server.text("defines", json!({"file": "rtl/undef.sv"})); - assert_eq!(local, "rtl/undef.sv\n 1 `define T 1\n 2 `undef T\n"); + assert_eq!(local, "2 defines\nrtl/undef.sv\n 1 `define T 1\n 2 `undef T\n"); } #[test] @@ -753,7 +755,7 @@ fn resources_list_and_read_the_overview_rules_units_and_outlines() { assert!(outline["result"]["contents"][0]["text"] .as_str() .unwrap() - .starts_with("rtl/top.sv\n module top 1-9\n")); + .contains("entries\nrtl/top.sv\n module top 1-9\n")); let overview = read(&mut server, "lucisv://overview"); assert!(overview["result"]["contents"][0]["text"] .as_str() @@ -792,7 +794,7 @@ fn an_escaped_name_is_followed_across_files() { let found = server.text("references", json!({"name": "\\my-mod"})); assert_eq!( found, - "rtl/esc.sv\n 1:8 module \\my-mod (input logic a);\nrtl/esc_user.sv\n 3:3 \\my-mod u_m (.a(a));\n" + "2 hits\nrtl/esc.sv\n 1:8 module \\my-mod (input logic a);\nrtl/esc_user.sv\n 3:3 \\my-mod u_m (.a(a));\n" ); let at = json!({"file": "rtl/esc_user.sv", "line": 3, "col": 4}); assert_eq!(sites(&mut server, at), ["rtl/esc.sv:1:8 module"]); @@ -1611,3 +1613,277 @@ fn a_stale_temp_store_is_swept_and_a_young_one_and_other_files_are_spared() { assert!(young.exists(), "a young one may be a live writer's"); assert!(other.exists(), "only `..tmp` is ours to sweep"); } + +// --------------------------------------------------------------------------- +// Feedback round 2 (`docs/features/mcp-feedback-2`): every paged answer opens +// with its total, the `in` path glob, the post-edit check line. +// --------------------------------------------------------------------------- + +/// A server over a fresh copy of the nested `paths` fixture: `ip/aes/rtl`, +/// `ip/aes/dv`, `ip/uart/rtl` (and its `sub/`), `top/`. +fn paths_tree() -> (Tree, Session) { + let tree = Tree::of("paths"); + let mut server = Session::over(&tree); + server.initialize(); + (tree, server) +} + +/// A call's text and its `total` and `shown`. +fn paged(server: &mut Session, tool: &str, arguments: Value) -> (String, Value, Value) { + let result = server.call(tool, arguments); + assert_eq!(result["isError"], false, "{tool}: {result}"); + let text = result["content"][0]["text"].as_str().unwrap().to_string(); + let structured = &result["structuredContent"]; + (text, structured["total"].clone(), structured["shown"].clone()) +} + +#[test] +fn every_paged_answer_opens_with_its_total_whole_or_cut() { + let (_tree, mut server) = paths_tree(); + let (whole, total, shown) = paged(&mut server, "list_units", json!({})); + assert!(whole.starts_with("6 units\nip/aes/dv/aes_tb.sv\n"), "{whole}"); + assert!(!whole.contains("… and"), "{whole}"); + assert_eq!((total, shown), (json!(6), json!([1, 6]))); + let (cut, total, shown) = paged(&mut server, "list_units", json!({"limit": 2})); + assert!(cut.starts_with("6 units (showing 1–2)\n") && cut.ends_with("… and 4 more\n")); + assert_eq!((total, shown), (json!(6), json!([1, 2]))); + let (last, _, shown) = paged(&mut server, "list_units", json!({"limit": 2, "offset": 5})); + assert!(last.starts_with("6 units (showing 6)\ntop/chip.sv\n"), "{last}"); + assert_eq!(shown, json!([6, 6])); + let (past, _, shown) = paged(&mut server, "list_units", json!({"offset": 9})); + assert_eq!(past, "6 units (showing none: `offset` is past the end)\n"); + assert_eq!(shown, json!([0, 0])); + + let (symbols, _, _) = paged(&mut server, "search_symbols", json!({"query": "clk_i"})); + assert!(symbols.starts_with("3 symbols\n"), "{symbols}"); + let args = json!({"query": "clk_i", "limit": 1, "offset": 1}); + let (symbols, _, shown) = paged(&mut server, "search_symbols", args); + assert!(symbols.starts_with("3 symbols (showing 2)\n"), "{symbols}"); + assert_eq!(shown, json!([2, 2])); + + let clk = json!({"name": "clk_i", "unit": "aes_core", "limit": 3}); + let (hits, total, _) = paged(&mut server, "references", clk); + assert!(hits.starts_with("4 hits (showing 1–3)\nip/aes/dv/aes_tb.sv\n"), "{hits}"); + assert!(hits.contains("… and 1 more\n"), "{hits}"); + assert_eq!(total, 4); + + let outline = json!({"file": "ip/uart/rtl/uart.sv", "limit": 1}); + let (entries, total, _) = paged(&mut server, "outline", outline); + assert_eq!( + entries, + "6 entries (showing 1)\nip/uart/rtl/uart.sv\n module uart 1-8\n… and 5 more\n" + ); + assert_eq!(total, 6); + + let (findings, _, _) = paged(&mut server, "diagnostics", json!({"limit": 1})); + assert!(findings.starts_with("2 findings (showing 1)\nip/aes/rtl/aes_core.sv\n")); + let (defines, _, shown) = paged(&mut server, "defines", json!({})); + assert!(defines.starts_with("2 defines\nip/aes/dv/aes_tb.sv\n"), "{defines}"); + assert_eq!(shown, json!([1, 2])); +} + +#[test] +fn hierarchy_counts_instantiations_up_and_nodes_down() { + let (_tree, mut server) = paths_tree(); + let up = json!({"root": "aes_core", "direction": "up"}); + let (whole, total, _) = paged(&mut server, "hierarchy", up); + assert_eq!( + whole, + "4 instantiations\naes_core ip/aes/rtl/aes_core.sv:2\n aes_tb.u_dut ip/aes/dv/aes_tb.sv:4\n uart.u_aes ip/uart/rtl/uart.sv:6\n chip.u_uart top/chip.sv:5\n chip.u_aes2 top/chip.sv:6\n" + ); + assert_eq!(total, 4); + // The root line heads every page; the window counts instantiations only. + let second = json!({"root": "aes_core", "direction": "up", "limit": 1, "offset": 1}); + let (cut, total, shown) = paged(&mut server, "hierarchy", second); + assert_eq!( + cut, + "4 instantiations (showing 2)\naes_core ip/aes/rtl/aes_core.sv:2\n uart.u_aes ip/uart/rtl/uart.sv:6\n… and 2 more\n" + ); + assert_eq!((total, shown), (json!(4), json!([2, 2]))); + let (none, _, _) = paged(&mut server, "hierarchy", json!({"root": "chip", "direction": "up"})); + assert_eq!(none, "0 instantiations\nchip top/chip.sv:1\n"); + let (down, total, _) = paged(&mut server, "hierarchy", json!({"root": "chip", "limit": 2})); + assert!(down.starts_with("5 nodes (showing 1–2)\nchip top/chip.sv:1\n"), "{down}"); + assert_eq!(total, 5); +} + +#[test] +fn in_filters_list_units_and_search_symbols_by_root_relative_path() { + let (_tree, mut server) = paths_tree(); + let (rtl, total, _) = paged(&mut server, "list_units", json!({"in": "ip/**/rtl/*.sv"})); + assert_eq!( + rtl, + "3 units\nip/aes/rtl/aes_core.sv\n module aes_core 2\nip/aes/rtl/aes_pkg.sv\n package aes_pkg 1\nip/uart/rtl/uart.sv\n module uart 1\n" + ); + assert_eq!(total, 3, "the total is the filtered count"); + // `?` is one character of one component; `*` never crosses a `/`. + let (aes, _, _) = paged(&mut server, "list_units", json!({"in": "ip/ae?/*/*.sv"})); + assert!(aes.starts_with("3 units\nip/aes/dv/aes_tb.sv\n"), "{aes}"); + let (shallow, _, _) = paged(&mut server, "list_units", json!({"in": "ip/*.sv"})); + assert_eq!(shallow, "0 units (none match `in`)\n"); + assert!(paged(&mut server, "list_units", json!({"in": ""})).0.starts_with("6 units\n")); + // Filtered before paging. + let (page, total, _) = + paged(&mut server, "list_units", json!({"in": "ip/**", "kind": "module", "limit": 1})); + assert!(page.starts_with("4 units (showing 1)\nip/aes/dv/aes_tb.sv\n"), "{page}"); + assert_eq!(total, 4); + // The glob is a path glob only: an escaped name with `*` in it is listed + // as written, and a name `glob` still works beside it. + let esc = json!({"query": "esc", "in": "ip/aes/rtl/aes_p?g.sv"}); + let (symbols, _, _) = paged(&mut server, "search_symbols", esc); + assert_eq!(symbols, "1 symbol\nip/aes/rtl/aes_pkg.sv\n parameter aes_pkg::\\esc*w 2\n"); + let (none, _, _) = + paged(&mut server, "search_symbols", json!({"query": "esc", "in": "top/**"})); + assert_eq!(none, "0 symbols (none match `in`)\n"); + let (missing, _, _) = paged(&mut server, "search_symbols", json!({"query": "zzz", "in": "**"})); + assert_eq!(missing, "no symbols match\n", "a glob that removed nothing is not blamed"); + let both = json!({"glob": "aes_*", "in": "**/dv/**"}); + let (named, _, _) = paged(&mut server, "list_units", both); + assert_eq!(named, "1 unit\nip/aes/dv/aes_tb.sv\n module aes_tb 2\n"); +} + +#[test] +fn in_filters_references_and_its_mentions() { + let (_tree, mut server) = paths_tree(); + let rtl = json!({"name": "clk_i", "unit": "aes_core", "in": "ip/**/rtl/*.sv"}); + let (hits, total, _) = paged(&mut server, "references", rtl); + assert_eq!( + hits, + "2 hits\nip/aes/rtl/aes_core.sv\n 3:31 input logic clk_i,\nip/uart/rtl/uart.sv\n 6:20 aes_core u_aes (.clk_i(clk_i), .q_o());\n" + ); + assert_eq!(total, 2); + let chip = json!({"name": "clk_i", "unit": "aes_core", "in": "top/chi?.sv"}); + let (hits, _, _) = paged(&mut server, "references", chip); + assert!(hits.starts_with("1 hit\ntop/chip.sv\n 6:21 "), "{hits}"); + let nowhere = json!({"name": "clk_i", "unit": "aes_core", "in": "fpv/**"}); + let (hits, _, _) = paged(&mut server, "references", nowhere); + assert_eq!(hits, "0 hits (none match `in`)\n"); +} + +#[test] +fn in_filters_hierarchy_by_the_instantiating_or_the_instantiated_file() { + let (_tree, mut server) = paths_tree(); + // Up: the file holding the instance. + let up = json!({"root": "aes_core", "direction": "up", "in": "ip/**/rtl/*.sv"}); + let (rtl, total, _) = paged(&mut server, "hierarchy", up); + assert_eq!( + rtl, + "1 instantiation\naes_core ip/aes/rtl/aes_core.sv:2\n uart.u_aes ip/uart/rtl/uart.sv:6\n" + ); + assert_eq!(total, 1); + let dv = json!({"root": "aes_core", "direction": "up", "in": "ip/ae?/dv/*"}); + let (dv, _, _) = paged(&mut server, "hierarchy", dv); + assert!(dv.ends_with("\n aes_tb.u_dut ip/aes/dv/aes_tb.sv:4\n"), "{dv}"); + let nowhere = json!({"root": "aes_core", "direction": "up", "in": "fpv/**"}); + let (none, _, _) = paged(&mut server, "hierarchy", nowhere); + assert_eq!(none, "0 instantiations (none match `in`)\naes_core ip/aes/rtl/aes_core.sv:2\n"); + // Down: the instantiated module's own file — `uart_fifo` lives in + // `rtl/sub/`, which `rtl/*.sv` does not reach. + let down = json!({"root": "chip", "in": "ip/**/rtl/*.sv"}); + let (down, _, _) = paged(&mut server, "hierarchy", down); + assert_eq!( + down, + "4 nodes\nchip top/chip.sv:1\n u_uart : uart\n u_aes : aes_core\n u_aes2 : aes_core\n" + ); + // No root: the top modules, by their own file — and their children by + // theirs, so nothing under `ip/` is listed. + let (tops, _, _) = paged(&mut server, "hierarchy", json!({"in": "top/**"})); + assert_eq!(tops, "1 node\nchip top/chip.sv:1\n"); + let (none, _, _) = paged(&mut server, "hierarchy", json!({"in": "fpv/**"})); + assert_eq!(none, "0 nodes (none match `in`)\n"); +} + +#[test] +fn in_filters_diagnostics_and_defines() { + let (_tree, mut server) = paths_tree(); + let (uart, total, _) = paged(&mut server, "diagnostics", json!({"in": "ip/uart/**"})); + assert_eq!( + uart, + "1 finding\nip/uart/rtl/uart.sv\n 5:9 warning `idle_x` is declared but never used [unused-signal]\n" + ); + assert_eq!(total, 1); + // An escaped name in a message is left as written. + let (aes, _, _) = paged(&mut server, "diagnostics", json!({"in": "ip/ae?/rtl/*"})); + assert!(aes.contains("`\\esc*name` is declared but never used"), "{aes}"); + let (clean, _, _) = paged(&mut server, "diagnostics", json!({"in": "top/**"})); + assert_eq!(clean, "no findings\n", "a matched file with nothing to say"); + let (none, _, _) = paged(&mut server, "diagnostics", json!({"in": "fpv/**"})); + assert_eq!(none, "0 findings (none match `in`)\n"); + let one = json!({"file": "ip/uart/rtl/uart.sv", "in": "top/**"}); + assert_eq!(paged(&mut server, "diagnostics", one).0, "0 findings (none match `in`)\n"); + + let (dv, total, _) = paged(&mut server, "defines", json!({"in": "ip/**/dv/*.sv"})); + assert_eq!(dv, "1 define\nip/aes/dv/aes_tb.sv\n 1 `define AES_TB 1\n"); + assert_eq!(total, 1); + let (none, _, _) = paged(&mut server, "defines", json!({"in": "fpv/**"})); + assert_eq!(none, "0 defines (none match `in`)\n"); +} + +#[test] +fn the_in_argument_is_offered_where_it_filters() { + let (_tree, mut server) = paths_tree(); + let reply = server.request("tools/list", json!({})); + let tools = reply["result"]["tools"].as_array().unwrap(); + let offers = |name: &str| { + let tool = tools.iter().find(|t| t["name"] == name).unwrap(); + tool["inputSchema"]["properties"]["in"]["type"] == "string" + }; + for name in + ["list_units", "search_symbols", "references", "hierarchy", "diagnostics", "defines"] + { + assert!(offers(name), "{name} takes `in`"); + } + assert!(!offers("outline") && !offers("rename")); + let instructions = server.initialize()["result"]["instructions"].as_str().unwrap().to_string(); + assert!(instructions.contains("`in` filters by path glob"), "{instructions}"); +} + +#[test] +fn edits_end_with_the_files_to_check() { + let (tree, mut server) = paths_tree(); + let rename = + json!({"file": "ip/uart/rtl/uart.sv", "line": 5, "name": "idle_x", "new_name": "spare_x"}); + let mut dry = rename.clone(); + dry["dry_run"] = json!(true); + let said = server.text("rename", dry); + assert!( + said.ends_with("\ncheck after writing: diagnostics on ip/uart/rtl/uart.sv\n"), + "{said}" + ); + let said = server.text("rename", rename); + assert!(said.ends_with("\ncheck: diagnostics on ip/uart/rtl/uart.sv\n"), "{said}"); + // Nothing changed, nothing to check. + let again = + json!({"file": "ip/uart/rtl/uart.sv", "line": 5, "name": "spare_x", "new_name": "spare_x"}); + assert_eq!(server.text("rename", again), "unchanged\n"); + + let port = json!({"module": "aes_core", "declaration": "input logic rst_ni"}); + let said = server.text("add_port", port); + assert!( + said.ends_with("\ncheck: diagnostics on ip/aes/dv/aes_tb.sv, ip/aes/rtl/aes_core.sv, ip/uart/rtl/uart.sv, top/chip.sv\n"), + "{said}" + ); + let spare = + json!({"file": "ip/uart/rtl/uart.sv", "line": 3, "name": "spare_i", "dry_run": true}); + let removed = server.text("remove_port", spare); + assert!( + removed.ends_with("\ncheck after writing: diagnostics on ip/uart/rtl/uart.sv\n"), + "{removed}" + ); + + let wildcard = json!({"file": "top/chip.sv", "line": 5, "dry_run": true}); + let said = server.text("expand_wildcard", wildcard); + assert!(said.ends_with("\ncheck after writing: diagnostics on top/chip.sv\n"), "{said}"); + + let inline = + json!({"file": "ip/uart/rtl/uart.sv", "line": 7, "name": "u_fifo", "dry_run": true}); + let said = server.text("inline_module", inline); + let check = "\ncheck after writing: diagnostics on ip/uart/rtl/uart.sv\n"; + assert!(said.ends_with(check), "{said}"); + + let extract = + json!({"file": "top/chip.sv", "start_line": 6, "end_line": 6, "new_name": "aes_slot"}); + let said = server.text("extract_module", extract); + assert!(said.ends_with("\ncheck: diagnostics on top/aes_slot.sv, top/chip.sv\n"), "{said}"); + assert!(tree.path("top/aes_slot.sv").is_file()); +} diff --git a/docs/features/mcp-feedback-2/README.md b/docs/features/mcp-feedback-2/README.md new file mode 100644 index 0000000..f3ce915 --- /dev/null +++ b/docs/features/mcp-feedback-2/README.md @@ -0,0 +1,312 @@ +# mcp-feedback-2 + +Lane **feedback-2** of the MCP block: the changes the second token-census +round asked for (`mcp_analysis.md`, Round 2 → "Changes for round 3"). +Tracked in `TODO-MCP.md` → "Feedback rounds". + +## Goal + +Round 2's task a regressed: the agent reached for `hierarchy up`, paged the +77-row answer with a small `limit`, never read the trailing `… and 28 more` +line and reported 35 of 47 instantiations as complete. Every census task +also spent turns dropping `dv/`, `fpv/` and template rows by hand. This lane +puts the total first on every paged answer (`77 instantiations (showing +1–50)`), raises the default page to 500, gives the listing tools a path +glob `in` applied to root-relative paths before paging, and ends the +design-wide edits with the one line that names the files to run +`diagnostics` on. + +## Assumptions + +- **The header.** Every paged text answer opens with `N ` when the + list is whole and `N (showing a–b)` when it is cut — `(showing a)` + for a one-entry window, ``(showing none: `offset` is past the end)`` past + the end; singular for 1 (`1 unit`). The trailing `… and N more` stays. + Nouns: `units` (`list_units`), `entries` (`outline`), `symbols` + (`search_symbols`), `hits` (`references`), `findings` (`diagnostics`), + `defines` (`defines`, `` `undef`` rows of the file form included), + `instantiations` (`hierarchy up` with one root line), `nodes` (every + other `hierarchy` walk). An **empty** list keeps its old one-line answer + (`no units match`, `no references`, `no findings`, `no defines`, `no + modules`), except `hierarchy up` from one root, which always has its root + line and now says `0 instantiations`. `project_overview` is not a paged + tool: its `top:` line keeps its own cap of 200 (`read.rs::TOPS_CAP`), so + the overview did not grow with `DEFAULT_LIMIT`. +- **`hierarchy up` from one root.** The window counts the instantiation + lines only; the root line heads every page, `offset`/`limit` skip and + cap instantiation lines, and the JSON's `total`/`shown` count them too + (`nodes` still starts with the root). Lines deeper than 1 are + instantiations of the ancestors and are counted. A root declared twice + (two root lines) is counted as `nodes`, all lines paged, as before. +- **JSON.** Every paged answer's `structuredContent` gains `"shown": [a, b]` + (1-based, inclusive; `[0, 0]` for an empty window) next to `total`, which + is the count after `in`. +- **`in`.** A glob over the root-relative path (`Project::relative`, + `/`-separated): `*` and `?` within one component (the existing + `glob_match`), `**` as a whole component for any run of components, none + included; `**/**` collapses to `**`; a leading `./` is dropped; a trailing + `/` means everything below. Anchored at the root: `ip/**` does not match + `hw/ip/x.sv` (write `**/ip/**`). `**` inside a component (`a**b`) is two + `*`s. An empty `in` filters nothing. The glob only ever sees paths — + names, escaped ones included (`\esc*w `), are never matched against it. + A file outside every root is shown absolute, and matches only a glob + starting with `/` or with `**`. A bare directory (`ip/aes`, no wildcard) + means everything below it, as for `.gitignore` (lead, after QA note 2). +- **What `in` filters, per tool.** `list_units`, `search_symbols`: the + declaring file. `references`: each hit's file, and the unresolved + mentions are searched only in matching files (the engine still runs over + the whole set — a use can resolve through any file). `defines`: the + defining file (both forms). `diagnostics`: the whole-project form lints + only matching files; the file form keeps its findings only when the file + matches; a filtered whole-project run does not report unused external + waivers (only a complete run knows a waiver matched nothing). + `hierarchy`: `up` keeps an instance when the file holding it matches + (the walk does not climb through a dropped instance); `down` keeps a + child when any declaration of its module lies in a matching file (a + module that is not indexed has no file and is dropped; a dropped child's + subtree is not walked); with no `root`, top modules are kept by their + own file. An explicit `root` line is always shown. +- **"none match".** ``0 (none match `in`)`` is said only when the + glob removed every entry there was; a list that was empty before the + glob keeps its old empty answer (`no symbols match`), and so does a + whole-project `diagnostics` whose matching files are clean (`no + findings`); ``0 findings (none match `in`)`` means no file matched. + `hierarchy`: `up` from one root when the module has instantiations and + none is kept (root line still shown); no-root `down` when no top module + is kept. +- **The check line.** `rename`, `add_port`, `remove_port`, + `expand_wildcard`, `extract_module` and `inline_module` end their text + with `check: diagnostics on ` (`check after writing: …` for a dry + run): the changed and created files, root-relative, in path order, the + first 5 then `and N more`. An `unchanged` answer and a refusal get none. + The line is appended after `apply::run` (below the diff on a dry run); + the JSON is unchanged. `convert_ports`, `organize_imports`, + `propagate_ports`, the item tools, `format` and `fix_lint` do not carry + it (not in the brief). +- **Catalogue.** `tools/list` measured as the test measures it + (`result.to_string().len()`): 17 981 B at 4671b91; with the `in` + arguments and the brief's wording it was 18 696 B; after the trims below + it is **17 993 B** (≤ 18 000, pinned by `the_tool_catalogue_stays_under_18_kb` + and `qa_the_catalogue_is_small_fully_described_and_spec_shaped`). The + generic `in` description is "Path glob the file must match, e.g. + `ip/**/rtl/*.sv`." — the brief's longer wording did not fit five times; + `hierarchy`'s says which file per direction. Trimmed, in this lane's + files only: every `limit` description to "Default 500."; `include_ + declaration` to "Default true."; `direction`/`depth`/`home` to their + defaults; the descriptions of `project_overview`, `list_units`, + `search_symbols`, `definition`, `references`, `hierarchy` (it still + starts "Who instantiates a module (`up`"; "all branches" dropped), + `diagnostics`, `defines`, `rename`, `organize_imports`, `propagate_ports`, + `remove_port`, `add_port`, `extract_module`, `instantiate`; titles + `List units`, `Definition`, `Rename`, `Inline an instance`, `Extract a + module`; `defines.name` lost "(backtick optional)" (still accepted). +- **`INSTRUCTIONS`** (896 characters): "; `in` filters by path glob" after + the finder tools; the edit sentence now says each edit "names files for + diagnostics" and the separate "Run diagnostics after an edit." is gone; + "Verilog/SystemVerilog" → "SystemVerilog", "from the files on disk + (never unsaved editor buffers)" → "from disk, never unsaved buffers" to + stay under 900. + +## Handshakes + +- **Consumed:** unchanged — `Project::{relative, index, files}`, + `WorkspaceIndex`, `apply::run`'s `structuredContent` + (`changed`/`created` arrays of `{file}`), which the check line reads. +- **Promised (answer shapes, changed):** the first line of every paged text + answer is the count line above; `structuredContent.shown` on every paged + answer; `hierarchy up` from one root pages and counts instantiation lines + (the root line repeated per page); six tools take `in`; six edit answers + end with the check line. The MCP resources (`lucisv://file/…/outline`) + run `outline` and so start with its count line too (`resources.rs` + untouched). +- **Flag for the lead (docs outside the lane):** `docs/mcp/PLAN.md` and + `docs/features/mcp-navigation/README.md` still say "default 200"; the + Agents guide, if it quotes answers, shows them without the count line. + +## Status / TODO + +- [x] `render.rs`: `Page` (window, `header`, `shown_json`, `rest`), + `Noun`, `none_match`; `DEFAULT_LIMIT` 500 +- [x] header + `shown` on `list_units`, `outline`, `search_symbols`, + `references`, `hierarchy`, `diagnostics`, `defines` +- [x] `in`: `read.rs::{path_match, in_glob, only_in, IN}`; wired into the + six tools +- [x] check line: `edit.rs::with_check` on the six edits +- [x] `INSTRUCTIONS` clause; catalogue ≤ 18 000 B +- [x] tests: unit (header, path glob, check cap), wire (8), existing + first-line pins updated +- [x] QA — PASS 2026-09-23 (see QA log) + +## Work log + +**2026-09-23 (dev, Opus).** + +- `render.rs`: `Page::of` wraps the old `page`; `header` puts the total + first; `none_match`. `page` and `more` stay (the overview's `top:` and + warnings lines use them). +- `read.rs`: `IN`, `in_glob`, `path_match`/`components_match` (split on + `/`, `**` recursion, `glob_match` per component), `only_in` (filter + + "emptied"); `list_units` filters before the walk-on-miss check, so a + glob or an `in` that misses walks once; `search_symbols` computes a hit's + relative path only when `in` is given; `outline` header; `TOPS_CAP`. +- `nav.rs`: `references` filters hits with `only_in` and passes only + matching files to `mentions::find`. +- `hierarchy.rs`: `Walk` holds the project and the glob; `keeps(file)`; + `down` skips a child whose module has no matching declaration, `up` + skips an edge in a non-matching file, no-root tops are filtered; `Shape` + (`up`, `single_up`, `emptied`) drives `render`, which pages the counted + slice and prints the lead root line on every page. +- `diagnostics.rs`: `project_findings` (the whole-project form, filtering + paths before linting, no unused-waiver report under `in`); file-form + findings go through `only_in`. +- `defines.rs`: both forms filter with `only_in`; a small `Listing` carries + the page facts out of either form. +- `edit.rs`/`refactor.rs`: `with_check` wraps `rename`, `remove_port`, + `expand_wildcard`, `inline_module`, `add_port`, `extract_module` (the + bodies moved to `rename_at`, `remove_port_at`, `add_port_to`, + `extract_lines`). +- Fixture `tests/fixtures/paths/` (ip/aes/{rtl,dv}, ip/uart/rtl/sub, top, + an escaped `\esc*w ` parameter and `\esc*name ` net, a `lucisv.toml` + selecting `unused-signal`). +- Existing assertions updated (the brief's allowance: they pinned the old + first line of a paged answer, or a line count that now includes it): + qa_m1 — the `list_units`/`outline`/`search_symbols` literals gain + `1 unit\n` etc. (16 tests), one outline `starts_with`; qa_m2 — `defines`, + `diagnostics`, `hierarchy` literals, two `lines().count()` 21 → 22, the + escaped-path resource loop reads past the count line; wire — the + `defines`, `diagnostics`, `hierarchy`, `references`, `outline`, + `search_symbols` literals and the outline resource check. +- Measured on the opentitan checkout (debug build, read-only): + `hierarchy up prim_fifo_sync depth 1` → `77 instantiations`, the same + with `in: "hw/ip/**/rtl/*.sv"` → `47 instantiations` (round 2's 47); + `list_units in hw/ip/aes/**` → 129 units in 32 ms. +- Gates (all through `tools/guard.sh`, one at a time): `cargo fmt --all + -- --check` exit 0; `cargo clippy --workspace --all-targets` `Finished`, + no warnings; `cargo test -p lucisv_mcp` 373 passed, 0 failed, 4 ignored + (unit 76, wire 55); `cargo test --workspace` exit 0, **4 929 passed, 0 + failed, 51 ignored** (4 918 before: +8 wire, +3 unit); the ignored + `opentitan` tests (`LUCISV_OPENTITAN` default path, `--ignored`) 2 + passed, the checkout only read. No guard kill. + +## QA log + +**2026-09-23 (QA, Opus) — verdict: PASS.** No correctness finding; four +low-severity notes for the lead (none blocks round 3). New file +`crates/lucisv_mcp/tests/qa_f2.rs` (14 tests, all passing, none ignored); +no source touched. + +- **Count line, one rule over every paged tool.** + `qa_every_paged_tool_agrees_with_its_json_over_every_window` runs 18 + base calls (`list_units`, `search_symbols`, `outline`, `references`, + `diagnostics`, `defines` both forms, `hierarchy` up/down/no-root, with + and without `in`) × 11 windows each (`limit` 1, 2, n; `offset` 0, 1, + n−1, n, n+3; default) and checks: the first line's number is the JSON + `total`; its window is the JSON `shown` (`[1, n]` whole, `[0, 0]` past + the end or empty); the JSON list holds exactly the window (+1 root line + for `hierarchy up` from one root); `… and N more` equals `total − b` and + is absent when nothing follows; singular only for 1; `(showing a)` only + for a one-entry window; no window on a whole list. All hold. Literal + pins for whole / cut / `(showing a)` / past the end (outline keeps its + file line past the end) / `1 unit`, `1 entry`, `1 hit`, `1 finding`, + `1 define`, `1 symbol`, `1 instantiation`. +- **`hierarchy` counting.** `up` from one root: the root line heads every + page (13 offsets, `limit` 2) exactly once, past the end included; + `total` counts the depth-2/3 lines too (11 = 13 lines − count − root); + a root with no instantiations `0 instantiations` + root line; a root + declared twice falls back to `nodes` with every line paged; no-root + `down` from five tops counts nodes (`9 nodes (showing 4–6)`). +- **`in`.** `*` stays in one component (`ip/aes/rtl/*.sv` does not reach + `rtl/sub/deep.sv`, `rtl/**` does); `**` spans zero components + (`ip/**/x.sv` ↔ `ip/x.sv`, `**/x.sv`); anchored (`ip/**` excludes + `hw/ip/y.sv`, `**/ip/**` and `*/ip/*` reach it); `?` is one character + and never `/`; `./`, trailing `/`, `**/**`; a whole-path glob is no + substring search (`aes`, `*.sv` at depth). A `*` in a directory name + and a space in one match literally. Names are never matched: the unit + `\esc*mod ` is not found by `in: "\esc*mod "` or `esc*`, only by its + path. "None match" only when the glob removed something — the old empty + answers stay for `list_units`, `search_symbols`, both `defines` forms, + file-form `diagnostics`; whole-project `diagnostics` over clean matched + files says `no findings`. `in` + `offset` + `limit`: total is the + filtered count. `references`: a mention outside the glob is dropped + (JSON `unresolved_mentions` too); hits emptied with a mention kept says + both. `hierarchy down`: a dropped child's subtree is not walked + (`tb` with `in: "lib/*"` shows `u_d : leaf` but not `lib/mid.sv` under + the dropped `aes`); `up` does not climb through a dropped instance. + Whole-project `diagnostics` with `in` never reports the unused waiver + (`**/*.sv`, `hw/**`, `*.waiver`, `w.waiver`), without `in` it does. +- **Check line.** All six edits, dry run (`check after writing:`, after + the diff, tree byte-identical, JSON without a new key) and real + (`check:`); repeated → `unchanged`/refusal with no line; `convert_ports` + carries none; 8 files → five in byte order (`B/` < `a.x/` < `a/b/` < + `a/` < `c/`) `and 3 more`, dry and real. +- **Changed assertions** (`qa_m1.rs` 16 literals + 1 `starts_with`, + `qa_m2.rs`, `wire.rs`): every hunk read — each only prepends the count + line or adds 1 to a line count (21 → 22 with the count line). Two + resource checks are marginally looser: `wire.rs:758` went from + `starts_with("rtl/top.sv\n…")` to `contains("entries\nrtl/top.sv\n…")`, + and the `qa_m2.rs:749` loop skips the first line unchecked; both still + pin the file line and the first entry. Not a weakening worth a finding. +- **Budgets.** Catalogue 17 993 B (≤ 18 000); `INSTRUCTIONS` 896 chars + (≤ 900); every tool name in it exists; every argument described; `in` + on exactly the six tools; every `limit` says 500. Production lines after + the lane: `read.rs` 454, `hierarchy.rs` 357, `nav.rs` 370, + `diagnostics.rs` 348, `edit.rs` 288, `render.rs` 172 — all under 600. +- **opentitan** (eval clone `~/.cache/lucisv-eval/ot/hw`, `--root …/hw` as + round 3 runs it, release binary, read-only, `git status` clean after): + `hierarchy up prim_fifo_sync depth 1` → `77 instantiations`; with + `in: "ip/**/rtl/*.sv"` → `47 instantiations` (round 2's 47); `limit 50` + → `77 instantiations (showing 1–50)`, `offset 50` → `(showing 51–77)`. + `references clk_i` (aes_core.sv:30) 2.60 / 2.69 s, 24 hits — the same + as feedback-1's recorded 2.60–2.69 s; with `in: "ip/aes/**"` 2.42 / + 2.44 s. `search_symbols ""` with `in` 0.11 s (95 237 → 2 671), a + pathological `**/*/**/*/…/zzz` glob 0.22 s. The ignored `opentitan` + tests (`--ignored`, default checkout, read-only) 2 passed. +- **Gates** (all through `tools/guard.sh`, one at a time): `cargo fmt + --all -- --check` exit 0; `cargo clippy --workspace --all-targets` + `Finished`, 0 warnings; `cargo test -p lucisv_mcp` 387 passed, 0 + failed, 4 ignored (qa_f2 14); `cargo test --workspace` exit 0, **4 943 + passed, 0 failed, 51 ignored** (4 929 + 14). No guard kill. + +Notes for the lead (low; no ignored test — each is a wording or design +call, not a spec violation): + +1. **Doc inaccuracy** (Assumptions, "`in`"): "A file outside every root … + matches only a glob starting with `/`" — a leading `**` matches it too + (`**` spans the empty first component of `/abs/…`). Repro: a + `--filelist` naming `/…/ext/outer.sv`, `list_units {"in": "**/*.sv"}` + lists it. Behaviour is reasonable; reword to "a glob starting with `/` + or `**`". +2. **A bare directory matches nothing**: `in: "ip/aes"` or + `"ip/uart/rtl"` → ``0 units (none match `in`)``; only `ip/aes/` or + `ip/aes/**` work. The answer lets an agent recover, at the cost of a + turn; gitignore/`rg -g` treat a pattern naming a directory as its + subtree. Either do that (a glob that matches a proper directory prefix + of the path keeps it) or say "a directory needs `/**`" — the + catalogue has 7 bytes left, so `INSTRUCTIONS` (4 chars left) cannot + carry it either without a trim. +3. **`diagnostics` `in: "**"`** keeps every file yet suppresses the + unused-waiver report; `paths.len() == all.len()` would be the exact + "complete run" test (`diagnostics.rs::project_findings`). As briefed, + kept. +4. **`hierarchy down` with an explicit `root`** whose glob drops every + child says `1 node` with no "none match" signal (as specified — the + root line is always shown), while `up` says + ``0 instantiations (none match `in`)``. The work-log example + `in: "hw/ip/**/rtl/*.sv"` → 47 is right for a server rooted at the + checkout top; round 3 roots at `hw`, where that glob answers + ``0 instantiations (none match `in`)`` and the one to quote is + `ip/**/rtl/*.sv` (verified 47 above). + +## Review + +**Lead, 2026-09-24 (feedback-2).** Round 2's regression on the census task +was a rendering fault, not an engine one: a 77-row answer paged with a small +limit and a count at the bottom the agent never read. The count line now +leads every paged answer, the default limit is 500, and the `in` path glob +returns exactly the rows a "under `ip/`, RTL only" question asks for — on +opentitan, `hierarchy up prim_fifo_sync` with `in: "ip/**/rtl/*.sv"` answers +47 instantiations in one call, the round-1 ground truth. QA passed it with +14 tests and four notes; the lead took note 2 (a bare directory glob means +everything below it, as `.gitignore` reads it) and the README's outside-root +sentence, and left notes 3 and 4 as documented behaviour. Committed; the +round-3 binary is frozen from this commit. diff --git a/docs/features/mcp-navigation/README.md b/docs/features/mcp-navigation/README.md index 245f4f1..bb5793c 100644 --- a/docs/features/mcp-navigation/README.md +++ b/docs/features/mcp-navigation/README.md @@ -142,7 +142,7 @@ instead of calling tools. language server's `pairs::missing_end_diagnostics`, not a library API, and the tolerant tree's diagnostics alone do not carry them. The whole-project form lints every indexed file (1.9 s on opentitan, 2 100 - findings) and returns the first `limit` (default 200) with the total. + findings) and returns the first `limit` (default 500 since feedback-2) with the total. **Unused external waivers**: the whole-project form, being a complete run, reports each `[lint] waivers` directive that suppressed nothing as an `unused-waiver` finding against the waiver file (`ExternalWaivers::unused` diff --git a/docs/features/mcp-read-tools/README.md b/docs/features/mcp-read-tools/README.md index 005e276..9654d56 100644 --- a/docs/features/mcp-read-tools/README.md +++ b/docs/features/mcp-read-tools/README.md @@ -78,11 +78,15 @@ rendering; no language knowledge lives in the MCP crate. | paths root-relative | `Project::relative`: relative to the first root holding the file, `/`-separated; absolute only for a file outside every root (a filelist entry) | | a file named once per group | `render::grouped` — the file on its own line, its entries indented two spaces under it (`list_units`, `search_symbols`); single-file answers name the file once at the top (`outline`, `read_item`, `unit_interface`'s head line) | | 1-based positions | lines always; `line:col` (byte column) where a column is given — today only `outline`'s parse errors; ranges `first-last`, a one-line range one number | -| capped lists | `limit` (default 200) and `offset` on every list tool; a cut list ends `… and N more`; `structuredContent` carries `total` so the agent can page | +| capped lists | `limit` (default 500) and `offset` on every list tool; the answer opens with its total — `N units`, or `N units (showing a–b)` when cut — and a cut list also ends `… and N more`; `structuredContent` carries `total` and `shown` so the agent can page | | no prose, no headings | labels are a bare word and a colon (`parameters:`, `ports:`, `modports:`, `template:`, `members:`); `none`/`no units match` for empty answers | | tables only for fixed columns | `render::table` — ports (direction, type-with-range, name), parameters (name, default), members, largest files; a column empty in every row takes no space | | a declaration as its own line | modports are shown as their declaration collapsed to one line; parameter defaults likewise | +Amended 2026-09-23 (lane feedback-2, `docs/features/mcp-feedback-2`): the +count line first, the default page 500, `shown` in the JSON; `list_units` +and `search_symbols` take the `in` path glob. + ## Handshakes Consumed: see `docs/features/mcp-transport/README.md` (one table for the diff --git a/docs/mcp/PLAN.md b/docs/mcp/PLAN.md index 18f2190..0e8a7d8 100644 --- a/docs/mcp/PLAN.md +++ b/docs/mcp/PLAN.md @@ -344,7 +344,7 @@ records MCP's own). - Paths root-relative; a file named once per group, never per line. - Line numbers 1-based, columns 1-based, in `file:line:col` form. -- Lists capped (`limit`, default 200) with `… and N more` — the agent can +- Lists capped (`limit`, default 500 since feedback-2) with `… and N more` — the agent can page with `offset`. - A declaration is shown as its own source line, trimmed, never the surrounding block. diff --git a/mcp_analysis.md b/mcp_analysis.md index 9f1de99..0836079 100644 --- a/mcp_analysis.md +++ b/mcp_analysis.md @@ -123,3 +123,48 @@ 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. +## Round 2 — server at 4671b91 (feedback-1 applied) + +Base arms are independent of the server, so rounds 2 and 3 re-run only the +mcp arms; task c's base arm is re-run once for run-to-run variance. + +| task | arm | tokens | tool calls | wall | outcome | +|---|---|---|---|---|---| +| a | mcp | 106 938 | 7 | 105 s | **incomplete**, 35/47 | +| b | mcp | 70 136 | 18 | 86 s | correct, identical diff | +| c | mcp | 98 636 | 35 | 206 s | correct, 8/8 sites | +| c | base (re-run) | 92 625 | 30 | 131 s | correct, 8/8 sites | + +### Observations + +**Completeness moved; tokens did not.** The rename (c) is now complete — +the unresolved-mentions list put the DV string path in front of the agent +and it fixed it — at 99 k tokens against the base arm's 88–93 k +(run-to-run variance on the base arm is about 6 %, so c is now a wash on +tokens and a win on correctness). Task b is unchanged: an identical +three-line diff either way, the mcp arm ~15 % dearer for its `diagnostics` +checks. Task a **regressed**: the agent now reached for `hierarchy up` +(7 calls, half the wall time) but paged the 77-row answer with a small +`limit` and never read the trailing "… and 28 more" line — 35 of 47 +instantiations reported as "complete and final". Two lessons: + +1. **Put the total first.** A paged answer must open with + `77 instantiations (showing 1–50)`; a count at the bottom is invisible + to an agent that stops reading when the table looks done. The default + `limit` of 200 is also too low for a "list everything" question on a + 4 000-file tree once DV and FPV rows are interleaved with RTL. +2. **Let the agent filter by path.** All three census tasks wanted "under + `ip/`, RTL only"; every mcp run spent turns dropping `dv/`, `fpv/`, + `ip_templates/` rows by hand. A path filter on the listing tools + (`in: "ip/**/rtl/*"`) would return exactly the rows asked for. + +**Changes for round 3 (lane "feedback-2"):** (i) every paged answer +opens with `N (showing a–b)` and the cap moves to 500 by default; +(ii) `hierarchy`, `references`, `list_units`, `search_symbols` and +`diagnostics` take an optional `in` path glob (`*`, `**`, `?`), applied to +root-relative paths; (iii) the `rename`/`add_port` answers end with one +line naming the files to check with `diagnostics` (the agents ran it +anyway; saying so saves a decision). Round 3 also adds a fourth, +understanding-heavy task (d: the instance tree of `entropy_src` to depth 3 +with each leaf module's port count) where reading files is the expensive +path, and repeats task c with Opus 5.5 on both arms once.