diff --git a/CHANGELOG.md b/CHANGELOG.md index b11c395..944f7d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,57 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.57.0 — 2026-09-23 + +### The MCP block complete: structural edits, the server in the extension, cache reuse, and three census rounds + +- **`lucisv-mcp` ships inside every platform package** and VS Code's + agent mode finds it with no configuration: the extension registers one + server per workspace folder through `mcpServerDefinitionProviders` + (VS Code 1.101+; older VS Code keeps working without it), passes it the + folder as root and the extension's storage as the index-cache directory, + and the command **lucisv: Copy MCP server config** puts the snippet for + Claude Code, Cursor or a `.vscode/mcp.json` on the clipboard. Settings + `lucisv.mcp.enabled` and `lucisv.mcp.path`. The Agents guide on the + docs site lists every tool. (`docs/features/mcp-packaging`.) +- **Structural edits — the token saver.** `replace_item`, `insert_item` + and `delete_item` take one item's text, never the file: a module, an + `always` block, a function, a declaration, selected the way `read_item` + slices it. The block's own verifier refuses anything that changes a byte + outside the item's lines, opens a block it does not close, closes the + enclosing module, changes an item's kind, declares a name twice, splits + an `ifdef`, alters a macro definition or a fence marker, or leaves a + comment or string running into the code after it; `delete_item` refuses + while a declared name is still used — by the engine, by a macro argument + or `define` body, or through a `.*` binding — unless `force` is passed. + 45 QA attack tests. (`docs/features/mcp-structural-edits`.) +- **Warm start from the editor's index.** With `--index-cache DIR` the + server reads the language server's store read-only (never writes it), + skips the parse of every file whose bytes it already describes, and + keeps its own store beside it: opentitan startup 1.9 s → 0.8 s. + (`docs/features/mcp-cache-and-census`.) +- **What three census rounds changed** (`mcp_analysis.md`: four tasks, + 20 sub-agent runs on opentitan, with and without the server): every + `references`, `rename`, `add_port` and `remove_port` answer now ends + with the *unresolved mentions* of the name — strings, comments, macro + text and macro-rooted paths no engine resolves — so a DV force path + built as a string is no longer missed; every paged answer opens with + `N things (showing a–b)` and the default limit is 500; the listing tools + take an `in` path glob (`ip/**/rtl/*.sv`), which turns "who + instantiates X under ip/, RTL only" into one call; `add_port` takes + `after` to place the port where the file's style wants it; the tool + catalogue is 40 % smaller; the instantiation template and hierarchy + overrides are opt-in. Verdict: no wrong answer in 20 runs, 15 % fewer + tokens on the whole-design question, small edits 4–19 % dearer, the + cross-file rename complete where plain search had missed a site. +- **Filed for the engines, not fixed here:** the parser's silence on a + trailing `,` in a connection list, `{d,, d}` and `type(x)'(y)` in a + connection; a false `remove_port` refusal on a same-file instantiation; + `extract_module` writing LF into a CRLF file; a lint gap on a + directionless header port; the LSP's `references` omitting three real + `aes` instantiations in the `*_pd_main.sv` tops (`docs/topo.md` §2.9 + rows 35–42). + ## 0.56.0 — 2026-09-23 ### Rename keeps implicit connections bound; the MCP server, as a preview diff --git a/TODO-MCP.md b/TODO-MCP.md index c673911..6475a83 100644 --- a/TODO-MCP.md +++ b/TODO-MCP.md @@ -289,27 +289,27 @@ Depends on M4 and M5 merged. whole-set refactor cost from M3 measured on `rename` in `aes` — done 2026-09-23 (dev): cold 1.87 s, warm 0.83–0.85 s from either store, sweep 5.6–6.1 ms, `rename` dry run 2.23–2.28 s -- [ ] the token census (PLAN §8): the three tasks, each run twice (file - tools only / with lucisv-mcp) by the same agent model, tokens in and - out from the transcripts, written up in `docs/mcp/census.md` with the - transcripts' task ids; if a task saved nothing, say so — the number - is the deliverable, not its sign -- [ ] `instructions` and tool descriptions revised from what the census - transcripts show the agent misunderstood; `prompts/*` added only if - the census shows a repeated multi-tool sequence worth one prompt -- [ ] `docs/topo.md`: the `lucisv_mcp` node (`──▶` the six libraries; `-.spawn - contract.->` from `editors/vscode`; `-.builds/packages.->` from - `tools/`), the §2.8 rows, the Handshake MCP-1 status (delivered or - still open), and MCP-3 filed in §2.9 if M2's hierarchy walk and the - server's snapshot drifted -- [ ] `CHANGELOG.md` section, `README.md` architecture table row (nine - crates), `docs/repository-analysis.md` map row, CLAUDE.md measurement - line refreshed with the new crate's sizes +- [x] the token census (PLAN §8): four tasks over three rounds, 20 runs + (Sonnet arms, one Opus pair), base vs mcp on a clean opentitan clone, + graded against lead-computed ground truths — written up in + `mcp_analysis.md` (repo root; the owner's name for it) with the raw + run log in `docs/mcp/census-runs.txt`. Verdict: no wrong answer in + 20 runs; −15 % tokens on the whole-design question, +4…+19 % on small + edits, completeness won on the rename +- [x] `instructions` and tool descriptions revised from what the census + transcripts showed (feedback-1/2/3); no `prompts/*` — the census + showed no repeated multi-tool sequence worth one +- [x] `docs/topo.md`: the `lucisv_mcp` node and six edges, the §2.8 rows, + MCP-1 delivered in M3, §2.9 rows 35–42 for the engine findings — + done 2026-09-23 with the M6 commit +- [x] `CHANGELOG.md` section (0.57.0), `README.md` architecture table row + (nine crates), `docs/repository-analysis.md` map row, CLAUDE.md + measurement line — done with the M6 commit and the closing release - [ ] release **0.56.0** (or the next minor free at the time): tag, CI green, 8 assets, the darwin-arm64 vsix unzipped and checked for three binaries, the MCP smoke in the release log; the install line and the `claude mcp add` line given to the owner -- [ ] QA: the read-only promise on the LSP store attacked (a store with a +- [x] QA: the read-only promise on the LSP store attacked (a store with a torn last line; one from a different version; one whose record hash matches but whose facts checksum does not — each must be skipped, not trusted, and the file left byte-identical); a cold start with no @@ -317,6 +317,11 @@ Depends on M4 and M5 merged. the census transcripts spot-checked for a tool answer the agent had to correct by reading the file anyway (each is a finding against a tool's rendering); verdict + — done 2026-09-23 (Opus; interrupted by the owner moving the + machine, verdict pass-so-far with no blocking finding, recorded in + the README's QA log; the lead reviewed and committed; the temp-file + sweep QA asked for landed in feedback-1 and the census exercised the + warm-start path across 20 runs) ## Feedback rounds (the token census → the server) @@ -366,6 +371,26 @@ Depends on M4 and M5 merged. `hierarchy` counting; verdict — PASS 2026-09-23 (QA, `tests/qa_f2.rs`, 14 tests; four low notes in the QA log) +### Round 3 → lane feedback-3 (`docs/features/mcp-feedback-3`) + +- [x] `unit_interface`: the instantiation template opt-in (`template`, + default false; text and JSON); `parameters (N):` / `ports (N):` + headers — done 2026-09-23 (dev) +- [x] `hierarchy`: the `#( … )` overrides on the text line opt-in + (`overrides`, default false); the JSON keeps them — done 2026-09-23 + (dev) +- [x] `INSTRUCTIONS` names `overrides: true` (896 characters; `template: + true` did not fit); catalogue 17 943 B (≤ 18 000; `dry_run`'s + description trimmed in `edit.rs`, flagged) — done 2026-09-23 (dev) +- [x] wire tests for both defaults and both opt-ins; old pins moved to the + opt-in; measured on the eval clone (`unit_interface prim_fifo_sync` + 596 B vs 999 B; `hierarchy up … in ip/**/rtl/*.sv` 22 163 B vs + 64 783 B) — done 2026-09-23 (dev) +- [x] QA: attack both flags (defaults, `false`, wrong types, packages, + recursive/noted lines, JSON equality); verdict — PASS 2026-09-23 (QA; + `tests/qa_f3.rs`, 7 tests; differential vs the c2e42b8 binary) +- [ ] re-measure census task d (and a, which now needs `overrides: true`) + ## 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/rpc.rs b/crates/lucisv_mcp/src/rpc.rs index c61f1f4..c5484bc 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 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."; +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: hierarchy direction up (overrides: true adds #(…)), 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/edit.rs b/crates/lucisv_mcp/src/tools/edit.rs index 07eec72..5c6547d 100644 --- a/crates/lucisv_mcp/src/tools/edit.rs +++ b/crates/lucisv_mcp/src/tools/edit.rs @@ -27,7 +27,7 @@ use crate::project::{Analysis, Project}; /// `dry_run`, which every edit tool takes. pub(super) const DRY_RUN: Param = - Param { name: "dry_run", ty: Ty::Bool, required: false, description: "Return the diff only." }; + Param { name: "dry_run", ty: Ty::Bool, required: false, description: "Diff only." }; const FILE: Param = Param { name: "file", ty: Ty::Str, required: true, description: "The file." }; const LINE: Param = diff --git a/crates/lucisv_mcp/src/tools/hierarchy.rs b/crates/lucisv_mcp/src/tools/hierarchy.rs index 31d9bc4..a44ef4c 100644 --- a/crates/lucisv_mcp/src/tools/hierarchy.rs +++ b/crates/lucisv_mcp/src/tools/hierarchy.rs @@ -8,6 +8,9 @@ //! its branch marked `recursive`), and by [`NODE_CAP`]. A module declared //! more than once is not expanded — which declaration an instance means is //! the elaborator's choice, not ours — and says how many there are. +//! +//! Each instance's `#(...)` overrides are always in the JSON; the text line +//! shows them only on `overrides: true`, since a census rarely reads them. use std::collections::HashMap; use std::path::Path; @@ -27,7 +30,8 @@ use crate::render::{self, Noun, Page, DEFAULT_LIMIT}; /// The deepest a walk may go, whatever `depth` asks. const MAX_DEPTH: usize = 20; -/// The longest overrides text a line shows; the JSON carries all of it. +/// The longest overrides text a line shows (on `overrides: true`); the JSON +/// carries all of it. const OVERRIDES_CAP: usize = 200; /// The most nodes one walk collects before it stops. @@ -36,7 +40,7 @@ const NODE_CAP: usize = 50_000; pub const HIERARCHY: Tool = Tool { name: "hierarchy", title: "Instance hierarchy", - description: "Who instantiates a module (`up`: instances, `#(…)` overrides, file:line) or what it instantiates (`down`, default). Textual.", + description: "Who instantiates a module (`up`, with file:line) or what it instantiates (`down`, default). Textual.", params: &[ Param { name: "root", @@ -54,13 +58,13 @@ pub const HIERARCHY: Tool = Tool { name: "depth", ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 }, required: false, - description: "Default 3, at most 20.", + description: "Default 3.", }, 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`.", + description: "Path glob on the instantiating file (`up`) or the module's (`down`), e.g. `ip/**/rtl/*.sv`.", }, Param { name: "limit", @@ -74,6 +78,12 @@ pub const HIERARCHY: Tool = Tool { required: false, description: "Lines to skip.", }, + Param { + name: "overrides", + ty: Ty::Bool, + required: false, + description: "Add each `#(…)` to the text lines.", + }, ], rewalk: false, handler: hierarchy, @@ -328,12 +338,13 @@ fn render(project: &Project, nodes: Vec, shape: Shape, args: &Args) -> Ans }; 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 show_overrides = args.flag("overrides", false); let mut texts = Texts::default(); let mut listed: Vec = Vec::new(); 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, shape.up)); + text.push_str(&line.text(node, shape.up, show_overrides)); text.push('\n'); listed.push(line.json(node, shape.up)); } @@ -378,13 +389,15 @@ impl Line { Line { file, line, overrides: overrides(text, child) } } - fn text(&self, node: &Node, up: bool) -> String { + /// The line as the text answer shows it; the overrides only when + /// `show_overrides`. + fn text(&self, node: &Node, up: bool, show_overrides: bool) -> String { let mut out = match (&node.instance, up) { (None, _) => format!("{} {}:{}", node.module, self.file, self.line), (Some(child), false) => format!("{} : {}", child.instance, child.module), (Some(child), true) => format!("{}.{}", node.module, child.instance), }; - if let Some(overrides) = &self.overrides { + if let Some(overrides) = self.overrides.as_ref().filter(|_| show_overrides) { out.push(' '); out.push_str(&source::capped(overrides, OVERRIDES_CAP)); } diff --git a/crates/lucisv_mcp/src/tools/interface.rs b/crates/lucisv_mcp/src/tools/interface.rs index e8c73c2..b4f9c42 100644 --- a/crates/lucisv_mcp/src/tools/interface.rs +++ b/crates/lucisv_mcp/src/tools/interface.rs @@ -1,7 +1,7 @@ //! `unit_interface`: what a unit offers the code that uses it — a module's -//! or interface's parameters, ports and instantiation template (plus an -//! interface's modports), a package's or class's exported members — without -//! the agent reading the file that declares it. +//! or interface's parameters and ports (plus an interface's modports, and +//! the instantiation template on request), a package's or class's exported +//! members — without the agent reading the file that declares it. use std::path::PathBuf; @@ -19,13 +19,13 @@ use crate::render; pub const UNIT_INTERFACE: Tool = Tool { name: "unit_interface", title: "Unit interface", - description: "A unit's parameters (defaults), ports (direction, type, range), an instantiation to paste; modports; members.", + description: "A unit's parameters, ports (direction, type, range), modports or members; `template: true` adds an instantiation.", params: &[ Param { name: "name", ty: Ty::Str, required: true, - description: "The unit's name (`pkg::cls` for a class).", + description: "The unit (`pkg::cls` for a class).", }, Param { name: "file", @@ -33,6 +33,12 @@ pub const UNIT_INTERFACE: Tool = Tool { required: false, description: "Its file, if declared twice.", }, + Param { + name: "template", + ty: Ty::Bool, + required: false, + description: "Add the instantiation.", + }, ], rewalk: false, handler: unit_interface, @@ -58,7 +64,8 @@ fn unit_interface(project: &mut Project, args: &Args) -> Result let short = name.rsplit("::").next().unwrap_or(name); match found.def.kind { SymbolKind::Module | SymbolKind::Interface => { - instantiable(&analysis, &found, short, head, &file).map(|mut answer| { + let template = args.flag("template", false); + instantiable(&analysis, &found, short, head, &file, template).map(|mut answer| { answer.structured["kind"] = Value::from(kind); answer }) @@ -117,13 +124,15 @@ fn pick( } } -/// A module's or interface's parameters, ports, modports and template. +/// A module's or interface's parameters, ports and modports, and its +/// template when `with_template` asks for it. fn instantiable( analysis: &Analysis, found: &Found, name: &str, head: String, file: &str, + with_template: bool, ) -> Result { let plan = instantiation_plan(name, &analysis.text, None)?; let scope = unit_symbol(&analysis.semantics, found, name).and_then(|s| s.child_scope); @@ -132,9 +141,9 @@ fn instantiable( (SymbolKind::Interface, Some(scope)) => modports_of(analysis, scope), _ => Vec::new(), }; - let template = plan.render(&Layout::default()); - let text = interface_text(head, &plan, &ports, &modports, &template); - let structured = json!({ + let template = with_template.then(|| plan.render(&Layout::default())); + let text = interface_text(head, &plan, &ports, &modports, template.as_deref()); + let mut structured = json!({ "name": name, "kind": render::kind(found.def.kind), "file": file, @@ -142,9 +151,11 @@ fn instantiable( "parameters": plan.params.iter().map(|p| json!({ "name": p.name, "default": p.default })).collect::>(), "ports": ports.iter().map(PortRow::to_json).collect::>(), "modports": modports, - "template": template, "warnings": plan.warnings, }); + if let Some(template) = template { + structured["template"] = Value::from(template); + } Ok(Answer { text, structured }) } @@ -159,22 +170,23 @@ fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec { .collect() } -/// The text answer: the head line, then each non-empty section. +/// The text answer: the head line, then each non-empty section; the +/// template last, when asked for. fn interface_text( mut text: String, plan: &InstantiationPlan, ports: &[PortRow], modports: &[String], - template: &str, + template: Option<&str>, ) -> String { if !plan.params.is_empty() { - text.push_str("parameters:\n"); + text.push_str(&format!("parameters ({}):\n", plan.params.len())); let rows: Vec> = plan.params.iter().map(|p| vec![p.name.clone(), default_cell(&p.default)]).collect(); text.push_str(&render::table(&rows)); } if !ports.is_empty() { - text.push_str("ports:\n"); + text.push_str(&format!("ports ({}):\n", ports.len())); let rows: Vec> = ports .iter() .map(|p| vec![p.dir.clone(), p.written_type(), p.name_with_unpacked()]) @@ -190,10 +202,12 @@ fn interface_text( for warning in &plan.warnings { text.push_str(&format!("warning: {warning}\n")); } - text.push_str("template:\n"); - text.push_str(template); - if !template.ends_with('\n') { - text.push('\n'); + if let Some(template) = template { + text.push_str("template:\n"); + text.push_str(template); + if !template.ends_with('\n') { + text.push('\n'); + } } text } diff --git a/crates/lucisv_mcp/tests/opentitan.rs b/crates/lucisv_mcp/tests/opentitan.rs index c06ef2a..04923b9 100644 --- a/crates/lucisv_mcp/tests/opentitan.rs +++ b/crates/lucisv_mcp/tests/opentitan.rs @@ -166,7 +166,8 @@ fn opentitan_navigation_matches_the_language_server() { let clock = s.hits(json!({"file": tb, "line": 46, "name": "clk_i"})); assert_covers(&clock, &["hw/ip/aes/rtl/aes.sv:42:53", "hw/ip/aes/rtl/aes.sv:197:31"]); - let top = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2, "limit": 500})); + let top = json!({"root": "top_earlgrey", "depth": 2, "limit": 500, "overrides": true}); + let top = s.text("hierarchy", top); assert!(top.contains("\n u_aes : aes #("), "{top}"); let fifo = s.text("definition", json!({"name": "prim_fifo_sync"})); diff --git a/crates/lucisv_mcp/tests/qa_f3.rs b/crates/lucisv_mcp/tests/qa_f3.rs new file mode 100644 index 0000000..81c1f19 --- /dev/null +++ b/crates/lucisv_mcp/tests/qa_f3.rs @@ -0,0 +1,430 @@ +//! QA attacks on lane feedback-3 (`unit_interface`'s `template` and +//! `hierarchy`'s `overrides` made opt-in, counted section headers), +//! 2026-09-23. +//! +//! Every test spawns the real binary over a scratch tree, as a host would. +//! The `OLD_*` literals are what the c2e42b8 binary (the tree before this +//! lane, built from `git archive HEAD`) answered for the same calls, so +//! "the opt-in is byte-identical to the old default" is pinned against the +//! old binary's own bytes, not against a re-derivation. + +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::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-f3-{}-{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()) + } +} + +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) + } + + /// A call that must be refused; its text. + fn refused(&mut self, tool: &str, arguments: Value) -> String { + let (error, text, _) = self.call(tool, arguments.clone()); + assert!(error, "{tool} {arguments}: answered: {text}"); + text + } +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +// --------------------------------------------------------------------------- +// The tree: an interface with modports, a module with `ifdef'd lists (so +// it has warnings), an empty module, a parameter-only module, a module of +// multi-declarator and unpacked ports, a program, and instances whose +// overrides are long (over the 200-byte cap), absent, and commented. +// --------------------------------------------------------------------------- + +fn long_overrides() -> String { + format!(".A({}), .B({})", "1".repeat(96), "2".repeat(118)) +} + +fn tree() -> Tree { + let user2 = format!( + "module user2 (input logic clk);\n leaf2 #({}) u_long (.clk(clk));\n leaf2 u_plain (.clk(clk));\n leaf2 #(.A(1) /* #( in a comment */) u_c (.clk(clk));\nendmodule\n", + long_overrides() + ); + let leaf2 = + "module leaf2 #(parameter int A = 1, parameter int B = 2) (input logic clk);\nendmodule\n"; + Tree::with(&[ + ( + "bus.sv", + "interface bus #(parameter int W = 8) (input logic clk);\n logic [W-1:0] data;\n logic valid;\n modport mst (output data, valid);\n modport slv (input data, valid);\nendinterface\n", + ), + ( + "dirs.sv", + "module dirs #(parameter int W = 1\n`ifdef X\n , parameter int V = 3\n`endif\n) (input logic a\n`ifdef X\n , output logic b\n`endif\n);\nendmodule\n", + ), + ("nothing.sv", "module nothing;\nendmodule\n"), + ("onlyp.sv", "module onlyp #(parameter int W = 1, parameter int D = 2);\nendmodule\n"), + ("np.sv", "module np (input logic a, b, output logic [3:0] y [2]);\nendmodule\n"), + ("prog.sv", "program prog (input logic clk);\nendprogram\n"), + ("pkg.sv", "package pkg;\n parameter int P = 1;\n typedef logic [3:0] nib_t;\nendpackage\n"), + ("leaf2.sv", leaf2), + ("user2.sv", user2.as_str()), + ]) +} + +// --------------------------------------------------------------------------- +// 1. `unit_interface`: the template, opt-in and byte-identical. +// --------------------------------------------------------------------------- + +/// What c2e42b8 answered for `unit_interface` (no flag existed then). +const OLD_UNITS: &[(&str, &str)] = &[ + ( + "bus", + "interface bus bus.sv:1\nparameters:\n W = 8\nports:\n input logic clk\nmodports:\n mst (output data, valid)\n slv (input data, valid)\ntemplate:\nbus #(\n .W(8)\n) u_bus (\n .clk(clk)\n);\n", + ), + ( + "dirs", + "module dirs dirs.sv:1\nparameters:\n W = 1\n V = 3\nports:\n input logic a\n output logic b\nwarning: `dirs`'s port list carries compiler directives, so what it declares depends on the configuration; the skeleton names every entry written, from every `ifdef arm.\nwarning: `dirs`'s parameter list carries compiler directives, so what it declares depends on the configuration; the skeleton names every entry written, from every `ifdef arm.\ntemplate:\ndirs #(\n .W(1),\n .V(3)\n) u_dirs (\n .a(a),\n .b(b)\n);\n", + ), + ("nothing", "module nothing nothing.sv:1\ntemplate:\nnothing u_nothing ();\n"), + ( + "np", + "module np np.sv:1\nports:\n input logic a\n input logic b\n output logic [3:0] y [2]\ntemplate:\nnp u_np (\n .a(a),\n .b(b),\n .y(y)\n);\n", + ), +]; + +/// The old text with this lane's counted headers: the only change the +/// opt-in answer may carry. +fn counted(old: &str, parameters: usize, ports: usize) -> String { + old.replace("\nparameters:\n", &format!("\nparameters ({parameters}):\n")) + .replace("\nports:\n", &format!("\nports ({ports}):\n")) +} + +#[test] +fn qa_template_true_is_the_old_answer_byte_for_byte_and_the_default_stops_before_it() { + let tree = tree(); + let mut s = Session::over(&tree); + for (name, old) in OLD_UNITS { + let (with, full) = s.ok("unit_interface", json!({"name": name, "template": true})); + let parameters = full["parameters"].as_array().unwrap().len(); + let ports = full["ports"].as_array().unwrap().len(); + let expected = counted(old, parameters, ports); + assert_eq!(with, expected, "{name}"); + let old_template = &old[old.find("template:\n").unwrap() + "template:\n".len()..]; + assert_eq!(format!("{}\n", full["template"].as_str().unwrap()), old_template, "{name}"); + + let (plain, bare) = s.ok("unit_interface", json!({"name": name})); + assert_eq!(plain, expected[..expected.find("template:\n").unwrap()], "{name}"); + assert!(!plain.contains("template"), "{name}: {plain}"); + let object = bare.as_object().unwrap(); + assert!(!object.contains_key("template"), "{name}: no key, not null: {bare}"); + let mut stripped = full.clone(); + stripped.as_object_mut().unwrap().remove("template"); + assert_eq!(stripped, bare, "{name}: the JSON differs only by `template`"); + } +} + +#[test] +fn qa_a_program_is_instantiable_and_a_package_ignores_the_flag() { + let tree = tree(); + let mut s = Session::over(&tree); + let (plain, bare) = s.ok("unit_interface", json!({"name": "prog"})); + assert_eq!(plain, "program prog prog.sv:1\nports (1):\n input logic clk\n"); + assert!(bare.get("template").is_none()); + let (with, _) = s.ok("unit_interface", json!({"name": "prog", "template": true})); + assert!(with.ends_with("template:\nprog u_prog (\n .clk(clk)\n);\n"), "{with}"); + + let package = s.ok("unit_interface", json!({"name": "pkg"})); + let flagged = s.ok("unit_interface", json!({"name": "pkg", "template": true})); + assert_eq!(package, flagged); + assert!(package.0.contains("members:\n"), "{}", package.0); +} + +// --------------------------------------------------------------------------- +// 2. The counted headers. +// --------------------------------------------------------------------------- + +/// The rows under `header` in `text`: the indented lines that follow it. +fn rows_under(text: &str, header: &str) -> Option { + let start = text.find(&format!("\n{header}"))? + 1; + let body = &text[start..]; + Some(body.lines().skip(1).take_while(|line| line.starts_with(" ")).count()) +} + +/// The count a header like `ports (12):` carries. +fn header_count(text: &str, section: &str) -> Option { + let at = text.find(&format!("\n{section} ("))? + section.len() + 3; + text[at..].split(')').next()?.parse().ok() +} + +#[test] +fn qa_every_header_count_equals_its_rows_and_the_json_and_an_empty_section_has_no_header() { + let tree = tree(); + let mut s = Session::over(&tree); + let expected: &[(&str, usize, usize)] = + &[("bus", 1, 1), ("dirs", 2, 2), ("nothing", 0, 0), ("onlyp", 2, 0), ("np", 0, 3)]; + for (name, parameters, ports) in expected { + let (text, json) = s.ok("unit_interface", json!({"name": name})); + for (section, want, key) in + [("parameters", parameters, "parameters"), ("ports", ports, "ports")] + { + assert_eq!(json[key].as_array().unwrap().len(), *want, "{name}.{key}"); + if *want == 0 { + // An empty section is left out, as before the lane: no `(0)`. + assert!(!text.contains(&format!("{section} (")), "{name}: {text}"); + assert!(!text.contains(&format!("{section}:")), "{name}: {text}"); + } else { + assert_eq!(header_count(&text, section), Some(*want), "{name}: {text}"); + let header = format!("{section} ({want}):\n"); + assert_eq!(rows_under(&text, &header), Some(*want), "{name}: {text}"); + } + } + } + // The modports header keeps no count; its rows are still all there. + let (bus, json) = s.ok("unit_interface", json!({"name": "bus"})); + assert!(bus.contains("\nmodports:\n"), "{bus}"); + assert_eq!(rows_under(&bus, "modports:\n"), Some(2)); + assert_eq!(json["modports"].as_array().unwrap().len(), 2); + // A parameter-only module's answer ends at its last parameter. + let (onlyp, _) = s.ok("unit_interface", json!({"name": "onlyp"})); + assert_eq!(onlyp, "module onlyp onlyp.sv:1\nparameters (2):\n W = 1\n D = 2\n"); +} + +// --------------------------------------------------------------------------- +// 3. `hierarchy`: the overrides, opt-in on the text, always in the JSON. +// --------------------------------------------------------------------------- + +/// What c2e42b8 answered: overrides on every text line, capped at 200. +fn old_up() -> String { + let capped: String = format!("#({}", long_overrides()).chars().take(200).collect(); + format!( + "3 instantiations\nleaf2 leaf2.sv:1\n user2.u_long {capped}… user2.sv:2\n user2.u_plain user2.sv:3\n user2.u_c #(.A(1) ) user2.sv:4\n" + ) +} + +fn old_down() -> String { + let capped: String = format!("#({}", long_overrides()).chars().take(200).collect(); + format!( + "4 nodes\nuser2 user2.sv:1\n u_long : leaf2 {capped}…\n u_plain : leaf2\n u_c : leaf2 #(.A(1) )\n" + ) +} + +#[test] +fn qa_overrides_true_is_the_old_text_and_the_default_drops_only_the_segment() { + let tree = tree(); + let mut s = Session::over(&tree); + let cases = [ + (json!({"root": "leaf2", "direction": "up"}), old_up()), + (json!({"root": "user2"}), old_down()), + ]; + for (args, old) in cases { + let mut asked = args.clone(); + asked["overrides"] = json!(true); + let (with, with_json) = s.ok("hierarchy", asked); + assert_eq!(with, old, "{args}"); + let (plain, plain_json) = s.ok("hierarchy", args.clone()); + assert_eq!(plain_json, with_json, "{args}: the JSON ignores the flag"); + assert!(!plain.contains("#("), "{args}: {plain}"); + assert!(!plain.contains('…'), "{args}: {plain}"); + // Line for line, the default is the old line minus ` #(…)`, the + // segment being the node's JSON `overrides` as the old line capped it. + let nodes = with_json["nodes"].as_array().unwrap(); + assert_eq!(plain.lines().count(), nodes.len() + 1, "{args}: count line + nodes"); + for ((short, long), node) in plain.lines().zip(with.lines()).skip(1).zip(nodes) { + let expected = match node["overrides"].as_str() { + None => long.to_string(), + Some(full) if full.chars().count() > 200 => { + let capped: String = full.chars().take(200).collect(); + long.replacen(&format!(" {capped}…"), "", 1) + } + Some(full) => long.replacen(&format!(" {full}"), "", 1), + }; + assert_eq!(short, expected, "{long}"); + } + // Every node carries `overrides`, uncapped in full where the site has one. + for node in with_json["nodes"].as_array().unwrap() { + assert!(node.as_object().unwrap().contains_key("overrides"), "{node}"); + } + let full = format!("#({})", long_overrides()); + assert!(with_json["nodes"].as_array().unwrap().iter().any(|n| n["overrides"] == full)); + } +} + +#[test] +fn qa_overrides_hold_under_paging_the_in_glob_and_depth() { + let tree = tree(); + let mut s = Session::over(&tree); + let windows = [ + json!({"root": "leaf2", "direction": "up", "limit": 1, "offset": 1}), + json!({"root": "leaf2", "direction": "up", "in": "user2.sv"}), + json!({"root": "leaf2", "direction": "up", "depth": 1}), + json!({}), + ]; + for args in windows { + let (plain, plain_json) = s.ok("hierarchy", args.clone()); + let mut asked = args.clone(); + asked["overrides"] = json!(true); + let (with, with_json) = s.ok("hierarchy", asked); + assert_eq!(plain_json, with_json, "{args}"); + assert!(!plain.contains("#("), "{args}: {plain}"); + assert_eq!(plain.lines().next(), with.lines().next(), "{args}: the count line"); + assert_eq!(plain.lines().count(), with.lines().count(), "{args}"); + } + let (page, _) = s.ok( + "hierarchy", + json!({"root": "leaf2", "direction": "up", "limit": 1, "offset": 1, "overrides": true}), + ); + assert!(page.contains(" user2.u_plain user2.sv:3\n"), "{page}"); +} + +// --------------------------------------------------------------------------- +// 4. The arguments and the catalogue. +// --------------------------------------------------------------------------- + +#[test] +fn qa_a_non_boolean_flag_is_refused_naming_the_field_and_null_means_the_default() { + let tree = tree(); + let mut s = Session::over(&tree); + for bad in [json!("true"), json!(1), json!([true]), json!({})] { + let why = s.refused("unit_interface", json!({"name": "np", "template": bad})); + assert!(why.contains("`template`") && why.contains("true or false"), "{why}"); + let why = s.refused("hierarchy", json!({"root": "user2", "overrides": bad})); + assert!(why.contains("`overrides`") && why.contains("true or false"), "{why}"); + } + // `null` is taken as absent, as for every other flag. + let plain = s.ok("unit_interface", json!({"name": "np"})); + assert_eq!(s.ok("unit_interface", json!({"name": "np", "template": null})), plain); + let plain = s.ok("hierarchy", json!({"root": "user2"})); + assert_eq!(s.ok("hierarchy", json!({"root": "user2", "overrides": null})), plain); + // The flag belongs to its own tool only. + let why = s.refused("hierarchy", json!({"root": "user2", "template": true})); + assert!(why.contains("`template`"), "{why}"); + let why = s.refused("unit_interface", json!({"name": "np", "overrides": true})); + assert!(why.contains("`overrides`"), "{why}"); +} + +#[test] +fn qa_the_catalogue_offers_both_flags_as_optional_booleans_and_stays_small() { + let tree = tree(); + let mut s = Session::over(&tree); + let reply = s.request("tools/list", json!({})); + let size = reply["result"].to_string().len(); + assert!(size <= 18_000, "tools/list is {size} bytes"); + let tools = reply["result"]["tools"].as_array().unwrap(); + for (tool, flag) in [("unit_interface", "template"), ("hierarchy", "overrides")] { + let entry = tools.iter().find(|t| t["name"] == tool).unwrap(); + let schema = &entry["inputSchema"]; + assert_eq!(schema["properties"][flag]["type"], "boolean", "{tool}.{flag}"); + let required = schema["required"].as_array().cloned().unwrap_or_default(); + assert!(!required.contains(&json!(flag)), "{tool}.{flag} is optional"); + } + let unit = tools.iter().find(|t| t["name"] == "unit_interface").unwrap(); + assert!(unit["description"].as_str().unwrap().contains("`template: true`")); + let hierarchy = tools.iter().find(|t| t["name"] == "hierarchy").unwrap(); + assert!(!hierarchy["description"].as_str().unwrap().contains("#("), "no longer promised"); + + let instructions = s.init["result"]["instructions"].as_str().unwrap(); + assert!(instructions.chars().count() <= 900, "{}", instructions.chars().count()); + assert!(instructions.contains("overrides: true"), "{instructions}"); + assert!(!instructions.contains("(instances, overrides)"), "{instructions}"); + let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); + let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')); + for word in words.filter(|w| w.contains('_') && *w != "dry_run") { + assert!(names.contains(&word), "the instructions name `{word}`, which is not a tool"); + } +} diff --git a/crates/lucisv_mcp/tests/qa_m1.rs b/crates/lucisv_mcp/tests/qa_m1.rs index 9004401..5064b14 100644 --- a/crates/lucisv_mcp/tests/qa_m1.rs +++ b/crates/lucisv_mcp/tests/qa_m1.rs @@ -430,7 +430,8 @@ fn qa_an_escaped_identifier_unit_is_listed_described_and_instantiable() { )]); let mut s = Session::ready(&scratch); assert!(s.text("list_units", json!({})).contains("module \\my-mod 1")); - let answer = s.text("unit_interface", json!({"name": "\\my-mod"})); + // feedback-3: the template is opt-in. + let answer = s.text("unit_interface", json!({"name": "\\my-mod", "template": true})); assert!(answer.starts_with("module \\my-mod esc.sv:1\n"), "{answer}"); // The template must still be legal: an escaped name ends at whitespace. assert!(answer.contains("\\my-mod \\u_my-mod ("), "{answer}"); @@ -462,7 +463,7 @@ fn qa_a_typed_parameter_keeps_its_default_and_a_localparam_is_not_offered() { "module tp #(parameter type T = logic [3:0], parameter int unsigned N = 4,\n localparam int L = 2) (input T a);\nendmodule\n", )]); let mut s = Session::ready(&scratch); - let result = s.call("unit_interface", json!({"name": "tp"})); + let result = s.call("unit_interface", json!({"name": "tp", "template": true})); let params = &result["structuredContent"]["parameters"]; assert_eq!( params, diff --git a/crates/lucisv_mcp/tests/qa_m2.rs b/crates/lucisv_mcp/tests/qa_m2.rs index 38ff852..65dc182 100644 --- a/crates/lucisv_mcp/tests/qa_m2.rs +++ b/crates/lucisv_mcp/tests/qa_m2.rs @@ -482,7 +482,8 @@ const HIER: &[(&str, &str)] = &[ 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})); + // feedback-3: the overrides are on the text line only on request. + let selfm = s.text("hierarchy", json!({"root": "selfm", "depth": 20, "overrides": true})); 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, "3 nodes\nma mutual.sv:1\n u_b : mb\n u_a : ma (recursive)\n"); @@ -552,7 +553,7 @@ fn qa_finding_4_every_instance_of_one_statement_shows_only_the_overrides() { let result = s.call("hierarchy", json!({"root": "ov"})); assert_eq!(result["structuredContent"]["nodes"][3]["instance"], "u_b"); assert_eq!(result["structuredContent"]["nodes"][3]["overrides"], "#(.W(2))"); - let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"})); + let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up", "overrides": true})); assert!(up.contains(" ov.u_b #(.W(2)) ov.sv:4\n"), "{up}"); } @@ -905,10 +906,10 @@ 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"})), + s.text("hierarchy", json!({"root": "ov", "overrides": true})), "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"})); + let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up", "overrides": true})); assert!(up.contains(" ov.u_i #( .W(3) ) ov.sv:9\n ov.u_j #(.W(4)) ov.sv:10\n"), "{up}"); } diff --git a/crates/lucisv_mcp/tests/wire.rs b/crates/lucisv_mcp/tests/wire.rs index d3e98d4..cedc3fd 100644 --- a/crates/lucisv_mcp/tests/wire.rs +++ b/crates/lucisv_mcp/tests/wire.rs @@ -275,7 +275,9 @@ fn unit_interface_answers_ports_parameters_modports_and_members() { let leaf = server.call("unit_interface", json!({"name": "leaf"})); let text = leaf["content"][0]["text"].as_str().unwrap(); assert!( - text.starts_with("module leaf rtl/leaf.sv:1\nparameters:\n W = 8\n Pass = 1'b1\n"), + text.starts_with( + "module leaf rtl/leaf.sv:1\nparameters (2):\n W = 8\n Pass = 1'b1\nports (4):\n" + ), "{text}" ); assert!( @@ -284,7 +286,8 @@ fn unit_interface_answers_ports_parameters_modports_and_members() { ), "{text}" ); - assert!(text.contains("template:\nleaf #(\n .W(8),"), "{text}"); + // feedback-3: the template is opt-in (`unit_interface_template_is_opt_in`). + assert!(!text.contains("template:"), "{text}"); let ports = &leaf["structuredContent"]["ports"]; let names: Vec<&str> = ports.as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); @@ -310,6 +313,43 @@ fn unit_interface_answers_ports_parameters_modports_and_members() { assert!(missing["content"][0]["text"].as_str().unwrap().contains("`nowhere`")); } +/// feedback-3: without `template` the answer ends after the ports (and +/// modports, warnings) and the JSON has no `template`; `template: true` puts +/// both back, the text's section last. +#[test] +fn unit_interface_template_is_opt_in() { + let tree = Tree::new(); + let mut server = Session::over(&tree); + server.initialize(); + let plain = server.call("unit_interface", json!({"name": "leaf"})); + let text = plain["content"][0]["text"].as_str().unwrap(); + assert!(text.ends_with(" input logic [3:0] mem [2]\n"), "{text}"); + assert!(plain["structuredContent"].get("template").is_none(), "{plain}"); + let off = server.call("unit_interface", json!({"name": "leaf", "template": false})); + assert_eq!(off["content"][0]["text"], plain["content"][0]["text"]); + assert_eq!(off["structuredContent"], plain["structuredContent"]); + + let with = server.call("unit_interface", json!({"name": "leaf", "template": true})); + let text = with["content"][0]["text"].as_str().unwrap(); + let at = text.find("template:\nleaf #(\n .W(8),").expect(text); + assert!(text[..at].ends_with(" input logic [3:0] mem [2]\n"), "{text}"); + assert!(text.ends_with(");\n"), "{text}"); + let template = with["structuredContent"]["template"].as_str().unwrap(); + assert!(template.starts_with("leaf #(\n .W(8),") && text[at..].contains(template)); + let mut without = with["structuredContent"].clone(); + without.as_object_mut().unwrap().remove("template"); + assert_eq!(without, plain["structuredContent"]); + + let bus = server.call("unit_interface", json!({"name": "bus_if", "template": true})); + let text = bus["content"][0]["text"].as_str().unwrap(); + let modports = text.find("modports:\n").expect(text); + assert!(text[modports..].contains("\ntemplate:\nbus_if "), "{text}"); + let flag = refusal(&mut server, "unit_interface", json!({"name": "leaf", "template": "yes"})); + assert!(flag.contains("`template`") && flag.contains("true or false"), "{flag}"); + let package = server.call("unit_interface", json!({"name": "types_pkg", "template": true})); + assert!(package["structuredContent"].get("template").is_none(), "{package}"); +} + #[test] fn unit_interface_refuses_a_name_declared_twice_until_a_file_picks_one() { let tree = Tree::new(); @@ -619,6 +659,42 @@ fn references_reach_bind_connections_hierarchical_tails_and_class_members() { assert!(refusal(&mut server, "references", flag).contains("true or false")); } +/// feedback-3: `overrides: true` puts each `#(…)` back on the text line, +/// between the instance and the site (`up`) or after the module (`down`); +/// the JSON carries `overrides` either way. +#[test] +fn hierarchy_overrides_are_opt_in_on_the_text_and_always_in_the_json() { + let tree = Tree::of("nav"); + let mut server = Session::over(&tree); + server.initialize(); + let up = json!({"root": "core", "direction": "up"}); + let plain = server.call("hierarchy", up.clone()); + let mut asked = up.clone(); + asked["overrides"] = json!(true); + let with = server.call("hierarchy", asked); + assert_eq!( + with["content"][0]["text"], + "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!(plain["structuredContent"], with["structuredContent"]); + assert_eq!(plain["structuredContent"]["nodes"][1]["overrides"], "#(.W(4))"); + let mut off = up; + off["overrides"] = json!(false); + assert_eq!(server.call("hierarchy", off)["content"], plain["content"]); + + let down = server.text("hierarchy", json!({"root": "top", "overrides": true})); + assert_eq!( + down, + "3 nodes\ntop rtl/top.sv:1\n u_core0 : core #(.W(4))\n u_core1 : core #( .W (8) )\n" + ); + let recursive = server.text("hierarchy", json!({"root": "tree", "overrides": true})); + assert!(recursive.ends_with(" u_right : tree #(.N(N / 2)) (recursive)\n"), "{recursive}"); + let plain_down = server.call("hierarchy", json!({"root": "top"})); + assert_eq!(plain_down["structuredContent"]["nodes"][2]["overrides"], "#( .W (8) )"); + let flag = refusal(&mut server, "hierarchy", json!({"root": "top", "overrides": 1})); + assert!(flag.contains("`overrides`") && flag.contains("true or false"), "{flag}"); +} + #[test] fn hierarchy_walks_down_and_up_and_terminates_on_recursion() { let tree = Tree::of("nav"); @@ -627,7 +703,7 @@ fn hierarchy_walks_down_and_up_and_terminates_on_recursion() { let tops = server.text("hierarchy", json!({})); assert_eq!( tops, - "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" + "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\n u_core1 : core\n" ); let deep = server.text("hierarchy", json!({"root": "chain_a", "depth": 20})); let capped = refusal(&mut server, "hierarchy", json!({"root": "chain_a", "depth": 21})); @@ -636,13 +712,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"], - "3 nodes\ntree 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 (recursive)\n u_right : tree (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"], - "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" + "2 instantiations\ncore rtl/core.sv:2\n top.u_core0 rtl/top.sv:4\n top.u_core1 rtl/top.sv:7\n" ); assert_eq!( up["structuredContent"]["nodes"][2], diff --git a/docs/features/mcp-feedback-3/README.md b/docs/features/mcp-feedback-3/README.md new file mode 100644 index 0000000..769afaf --- /dev/null +++ b/docs/features/mcp-feedback-3/README.md @@ -0,0 +1,298 @@ +# mcp-feedback-3 + +Lane **feedback-3** of the MCP block, the last census lane: the changes the +third token-census round asked for (`mcp_analysis.md`, Round 3 → +Observations and "Still to do"). Tracked in `TODO-MCP.md` → "Feedback +rounds". + +## Goal + +Round 3's task d (the `entropy_src` instance tree with 20 port counts) came +out at +4 % tokens with a third of the tool calls. Most of the server's +overhead there was twenty `unit_interface` answers, each carrying a +30-line instantiation template the task never used. `hierarchy` lines had +the same problem: every line carried the instance's `#( … )` overrides, +which a census rarely reads. This lane makes both **opt-in**: +`unit_interface` gains `template` and `hierarchy` gains `overrides`, both +default false. The JSON of `hierarchy` keeps `overrides` on every node, +because it costs little there. `unit_interface`'s section headers now carry +their counts (`parameters (6):`, `ports (12):`), so a port count can be +read without counting lines. + +## Assumptions + +- **`unit_interface` without `template`** (or with `template: false`): + the text is the head line, `parameters (N):` (if any), `ports (N):` (if + any), `modports:` (if any), then the `warning:` lines. There is no + `template:` section. The JSON has no `template` key at all (not `null`). + **With `template: true`** the text ends with `template:` and the + rendered plan, and the JSON has `template` as before. Otherwise the + JSON is identical key for key (pinned by a wire test). The plan is + still built either way: ports and parameters come from it. Only the + `render` step is skipped. +- **Packages and classes** take the `template` flag and ignore it: they + have no template. The member answer is unchanged, and its `members:` + header gets no count, because the brief named only ports and + parameters. +- **`modports:`** keeps its header without a count, for the same reason. +- **`hierarchy` without `overrides`**: each line is exactly the old line + without the ` #( … )` segment: `instance : module` (`down`), + `parent.instance file:line` (`up`), and root lines as before. A note + (`(recursive)`, `(not indexed)`, `(declared N times)`) still ends the + line. **With `overrides: true`** the line is byte-identical to the old + default, capped at `OVERRIDES_CAP` (200) as before. The JSON is the same + with or without the flag: `overrides` is on every node (`null` where the + site has none). +- The brief wrote the `up` line as "`instance : module file:line`". The + line has been `parent.instance file:line` since M2, and the brief also + says "exactly as today minus the overrides". I kept today's shape. +- **Census task a** asks for "both params on every row", so it now needs + `overrides: true`. The `hierarchy` parameter description and + `INSTRUCTIONS` both say so. A re-run of task a should be read with this + in mind. + +## Handshakes + +- **Consumed:** unchanged: `instantiation_plan` and `InstantiationPlan::render` + (`vlog_refactor`), `Args::flag` (`tools/mod.rs`). +- **Promised, changed (answer shapes):** + - `unit_interface`'s default text no longer ends with `template:`, and + its default JSON has no `template` key. Its headers read + `parameters (N):` / `ports (N):`. A new optional boolean argument, + `template`. + - `hierarchy`'s default text lines drop the `#( … )` segment. There is a + new optional boolean argument, `overrides`. The JSON is unchanged. + - The resources (`lucisv://…`) do not call either tool; nothing else in + the crate consumes these texts. +- **Out-of-ownership edit (flagged for the lead's ruling):** + `crates/lucisv_mcp/src/tools/edit.rs:30`. The shared `DRY_RUN` + parameter description changed from "Return the diff only." to "Diff + only.". The two new parameters took `tools/list` to 18 273 B. Trimming + every description in this lane's files as far as it would go, without + losing meaning, got it to 18 074 B, still over the 18 000 B pinned by + `the_tool_catalogue_stays_under_18_kb` and + `qa_the_catalogue_is_small_fully_described_and_spec_shaped`. `dry_run` + appears 14 times, so this one edit saves 154 B. The catalogue is now + **17 943 B**. The brief allowed "trim a description if needed" and did + not say whose. To revert: restore the string and trim ~75 B elsewhere. +- **Request (not done, outside ownership):** the Agents guide + `docs/site/src/content/docs/guides/agents.md:102` still promises "a + ready-to-paste instantiation" by default. Line 109 still shows + `instance : module #(overrides)` lines. Both need "on `template: true`" / + "on `overrides: true`". `docs/mcp/PLAN.md:146,263` describe the + original design and can stay as history. + +## Status / TODO + +- [x] `unit_interface`: `template` (Bool, default false); text and JSON + without the template by default; `parameters (N):` / `ports (N):`; + description names `template: true` +- [x] `hierarchy`: `overrides` (Bool, default false) on the text line; + JSON unchanged; description updated +- [x] `INSTRUCTIONS`: the hierarchy clause names `overrides: true` (896 + characters, unchanged length). `template: true` does not fit (940 + with both); the `unit_interface` description carries it +- [x] wire tests: both defaults and both opt-ins, text and JSON; existing + pins moved to the opt-in (listed in the work log); catalogue + ≤ 18 000 B +- [x] measured on the eval clone (below) +- [x] QA — PASS 2026-09-23 (see QA log) + +## Work log + +**2026-09-23 (dev, Opus).** + +- `src/tools/interface.rs`: `UNIT_INTERFACE` gains the `template` param + (l.36–41). The description is "A unit's parameters, ports (direction, + type, range), modports or members; `template: true` adds an + instantiation." The brief's "paste-ready" wording was trimmed for the + catalogue budget. The handler reads `args.flag("template", false)` + (l.67). `instantiable` takes `with_template` and renders the plan only + then (l.144). `template` is added to the JSON only when present + (l.156–157). `interface_text` takes `Option<&str>` and writes the counted + headers (l.183, l.189) and the template section only on request + (l.205). The module doc says the template is on request. +- `src/tools/hierarchy.rs`: `HIERARCHY` gains the `overrides` param + (l.81–86, "Add each `#(…)` to the text lines."). + The description no longer lists overrides: "Who instantiates a module + (`up`, with file:line) or what it instantiates (`down`, default). + Textual." `render` reads the flag (l.341) and passes it to `Line::text`, + which shows the overrides only then (l.394–400). The JSON's + `Line::json` is untouched. Trimmed for the budget: `depth` → "Default + 3." (the schema's `maximum: 20` says the rest), `in` → "Path glob on + the instantiating file (`up`) or the module's (`down`), e.g. + `ip/**/rtl/*.sv`.". +- `src/rpc.rs` `INSTRUCTIONS`: "Who instantiates module X (instances, + overrides): hierarchy with direction up, not references." → "Who + instantiates module X: hierarchy direction up (overrides: true adds + #(…)), not references." (896 → 896 characters). The old clause promised + overrides in the default answer, which is no longer true. Adding + `template: true` as well measured 940 characters, so it was left out. +- `src/tools/mod.rs`: no change needed (`Ty::Bool` and `Args::flag` + already existed). +- `src/tools/edit.rs:30`: `DRY_RUN` description "Diff only." (see + Handshakes: an out-of-ownership edit, flagged). +- Tests (`tests/wire.rs`): + - New: `unit_interface_template_is_opt_in`. It checks that the default + text ends at the last port, the JSON has no `template` key, and + `template: false` equals the default. With `template: true` the + template section comes after the ports and the JSON equals the default + plus `template`. It also covers an interface's template after its + modports, the refusal of `"template": "yes"`, and a package ignoring + the flag. + - New: `hierarchy_overrides_are_opt_in_on_the_text_and_always_in_the_json`. + It checks that `up` with `overrides: true` is byte-identical to the old + default, the JSON is equal with and without the flag, `false` equals + the default, and `down` and a recursive line work with the flag. It + also covers the refusal of `"overrides": 1`. +- Existing assertions changed (they pinned the old default output): + - `wire.rs`: + - `unit_interface_answers_ports_parameters_modports_and_members`: the + header prefix now reads `parameters (2):` … `ports (4):`, and the + template assertion now asserts that `template:` is absent. + - `hierarchy_walks_down_and_up_and_terminates_on_recursion`: the + three literals (tops, `tree`, `core` up) lose their overrides. The + JSON node assertion still has `"overrides": "#( .W (8) )"`. + - `qa_m1.rs`: + - `qa_an_escaped_identifier_unit_is_listed_described_and_instantiable` + now passes `template: true`. + - `qa_a_typed_parameter_keeps_its_default_and_a_localparam_is_not_offered` + now passes `template: true` (it reads `structuredContent.template`). + - `qa_m2.rs`: + - `qa_hierarchy_terminates_on_self_and_mutual_recursion`: the `selfm` + call now passes `overrides: true`. + - `qa_finding_4_every_instance_of_one_statement_shows_only_the_overrides`: + the text `up` call now passes `overrides: true`. + - `qa_recheck_overrides_split_across_lines_and_comments_between_instances`: + both calls now pass `overrides: true`. + - `opentitan.rs` (ignored without the checkout): the `top_earlgrey` + call that asserts `u_aes : aes #(` now passes `overrides: true`. +- **Measured** on the eval clone, read-only (`target/release/lucisv-mcp + --root ~/.cache/lucisv-eval/ot/hw`, no `--index-cache`, so nothing is + written; `git status --porcelain` in the clone was empty before and + after). Bytes of `content[0].text` and of the compact + `structuredContent`: + + | call | text B (lines) | JSON B | + |---|---|---| + | `unit_interface prim_fifo_sync` | **596** (21) | 1 284 | + | … `template: true` | 999 (43) | 1 710 | + | `hierarchy up prim_fifo_sync in ip/**/rtl/*.sv` (default depth 3) | **22 163** (349) | 102 939 | + | … `overrides: true` | 64 783 (349) | 102 939 | + | same, `depth: 1` (task a's 47 rows) | **3 238** (49) | — | + | … `overrides: true` | 7 230 (49) | — | + + So `unit_interface` is −40 % by default (403 B saved per call; round 3's + task d made 20 such calls; the saving grows with the port count), and the + `hierarchy up` text is −66 % at depth 3 and −55 % at depth 1. The JSON + of `hierarchy` does not change. `tools/list` is 17 943 B, down from + 18 273 B with the two new parameters before the trims. Catalogue at + c2e42b8: 17 993 B, per mcp-feedback-2. +- Gates (through `tools/guard.sh`, one at a time): `cargo fmt --all` + clean; `cargo clippy --all-targets` `Finished`, no warnings; `cargo + test -p lucisv_mcp` 390 passed, 0 failed, 4 ignored (wire 55 → 57); + `cargo test --workspace` **4 946 passed, 0 failed, 51 ignored**. +- Production lines (non-blank, non-comment, before `mod tests`): + `interface.rs` 334, `hierarchy.rs` 364, `mod.rs` 181, `rpc.rs` 265, + `edit.rs` 288. + +## QA log + +**2026-09-23 (QA) — verdict: PASS, no findings against the lane.** + +Read `CLAUDE.md`, this README, `git diff` of `src/tools/{interface,hierarchy,edit}.rs`, +`src/rpc.rs` and `tests/{wire,qa_m1,qa_m2,opentitan}.rs`. + +- **Baseline binary, not a re-derivation.** HEAD (c2e42b8) was exported + with `git archive HEAD` into the scratchpad (no worktree, repo untouched) + and built there (`--target-dir` in the scratchpad), so "`template: true` + / `overrides: true` equals the old default" was checked against the old + binary's own bytes. `vlog_parser`, `vlog_refactor`, `vlog_formatter` and + `vlog_semantic` have no diff since v0.56.0, so the template renderer is + the 0.56.0 one; the 0.56.0 vsix `lucisv-mcp` agreed on every + `unit_interface` too (its `hierarchy` predates feedback-2's count line, + so only HEAD's is a valid hierarchy baseline). +- **Differential, all six fixture trees** (`tests/fixtures/*`, every unit + from `list_units`; every module `down` and `up` at depth 20): 50/50 + `unit_interface` — `template: true` text = old text with only + `parameters:`/`ports:` → `(N)`; JSON = old JSON key for key; default + text = that text cut at `template:\n`; default JSON = old minus the + `template` key (absent, not `null`); counts = rows = JSON array lengths; + packages/classes identical with and without the flag. 78/78 + `hierarchy` — `overrides: true` text byte-identical to the old text + (refusals too), JSON identical across old/flag/default, no default line + holds `#(`, every node has an `overrides` key. +- **Same differential on the eval clone** (`~/.cache/lucisv-eval/ot/hw`, + read-only, no `--index-cache`; `git status --porcelain` empty before and + after): 12 units (`prim_fifo_sync`, `aes`, `entropy_src`, + `top_earlgrey`, `uart`, `tl_if`, …, two declared-twice refusals + identical) and 5 hierarchy calls (`top_earlgrey` depth 2, + `prim_fifo_sync` up with `in`/depth 1, `aes` up, `entropy_src` depth 3): + all equal. Default text (characters) is 17–45 % smaller for + `unit_interface` (`tl_if` least, few ports) and 48–83 % for `hierarchy`. +- **`tests/qa_f3.rs`** (new, 7 tests, all pass), pinned against literals + the c2e42b8 binary produced on the same tree: + 1. `template: true` byte-identical for an interface with modports, a + module with `ifdef`'d lists (warnings, then the template), an empty + module, multi-declarator/unpacked ports; JSON `template` = the old + section; default ends before `template:` with no `template` key. + 2. a `program` is instantiable (template on request); a package's answer + is identical with `template: true`. + 3. counts: `parameters (N):`/`ports (N):` = indented rows = JSON length + for 5 shapes. **Zero parameters or zero ports: the header is absent, + not `(0)`** — the pre-lane rule (an empty section is left out), and + sensible: the JSON still has `[]`, and a `(0)` header would cost + tokens to say nothing. `modports:` keeps no count; rows complete. + 4. `hierarchy` `up` and `down` over an instance whose overrides exceed + the 200-char cap, one without, one with a comment inside `#(…)`: + `overrides: true` = old text (cap and `…` kept); default = each old + line minus exactly ` ` of that node; JSON equal + with/without flag, full uncapped overrides present. + 5. default vs `overrides: true` under `limit`/`offset`, `in`, `depth: 1` + and the no-root listing: same count line, same line count, same JSON, + no `#(` in the default. + 6. `"true"`, `1`, `[true]`, `{}` refused for both flags naming the field + and "true or false"; `null` is taken as the default (as for every + `Ty::Bool` flag — `Args::flag` uses `as_bool`); each flag is refused + on the other tool as an unknown argument. + 7. catalogue ≤ 18 000 B (measured **17 943 B**, 57 B headroom), both + flags `boolean` and not required; `unit_interface`'s description + names `` `template: true` ``, `hierarchy`'s no longer promises `#(`; + `INSTRUCTIONS` **896 chars**, says `overrides: true`, dropped + "(instances, overrides)", names only existing tools. +- **Changed existing assertions** — every hunk read: `wire.rs` (header + prefix gains the counts and `ports (4):`, the template assertion becomes + its absence; three `hierarchy` literals lose exactly their `#(…)` + segments, the JSON node assertion is unchanged), `qa_m1.rs` (2 calls add + `template: true`), `qa_m2.rs` (4 calls add `overrides: true`, literals + unchanged), `opentitan.rs` (1 call adds `overrides: true`). Each is a + flag addition or a literal minus the overrides/template; nothing + weakened. `opentitan_navigation_matches_the_language_server` run + (`--ignored`, read-only over /Users/guoliangchen/repo/opentitan): ok, + 83 s; checkout status unchanged. +- **Out-of-ownership `edit.rs:30`** (`DRY_RUN` → "Diff only."): no test or + consumer depends on the old string; meaning survives next to + `dry_run: true shows the diff first` in `INSTRUCTIONS`. Left for the + lead's ruling as flagged. +- **Size/style:** production lines `interface.rs` 334, `hierarchy.rs` 364, + `edit.rs` 288, `rpc.rs` 265; the changed functions (`instantiable`, + `interface_text`, `render`, `Line::text`) are all under 50 lines. No + `unwrap`/`expect` added to library code. +- **Gates** (through `tools/guard.sh`, one at a time): `cargo fmt --all + --check` clean; `cargo clippy --all-targets` `Finished`, no warnings; + `cargo test -p lucisv_mcp` **397 passed, 0 failed, 4 ignored** (390 + + 7); `cargo test --workspace` **4 953 passed, 0 failed, 51 ignored** + (4 946 + 7). +- **Not done here (lead's list):** the Agents guide request in + Handshakes; the census re-measure of tasks a/d. + +## Review + +**Lead, 2026-09-23 (feedback-3).** The last census lesson was answer +weight: twenty `unit_interface` answers each carrying a template the task +never used. Both the template and the hierarchy overrides are now opt-in, +the ports and parameters headers carry their counts, and QA proved the +opt-in text byte-identical to the old output over every fixture and the +opentitan clone. The `dry_run` wording trim in `edit.rs` is accepted. The +Agents guide's tool table was regenerated from the binary by the lead. +Committed; the release binary is this one. diff --git a/docs/features/mcp-navigation/README.md b/docs/features/mcp-navigation/README.md index bb5793c..84bce12 100644 --- a/docs/features/mcp-navigation/README.md +++ b/docs/features/mcp-navigation/README.md @@ -435,6 +435,8 @@ passed, 0 failed, 47 ignored**. **2026-09-23 (dev, feedback-1).** `references` now ends with an `unresolved mentions` section and carries `unresolved_mentions` in its JSON (handshake change: a new trailing section and a new JSON key; hits unchanged); `references`/`definition`/`hierarchy` descriptions trimmed, `hierarchy` leads with "who instantiates a module" — `docs/features/mcp-feedback-1`. +**2026-09-23 (dev, feedback-3).** `hierarchy`'s text lines show the `#( … )` overrides only on `overrides: true` (handshake change: the default line drops them; the JSON keeps `overrides` on every node) — `docs/features/mcp-feedback-3`. + ## QA log **2026-09-23 (QA, M2). Verdict: rework needed** — four blocking findings diff --git a/docs/features/mcp-read-tools/README.md b/docs/features/mcp-read-tools/README.md index 9654d56..6e0cc44 100644 --- a/docs/features/mcp-read-tools/README.md +++ b/docs/features/mcp-read-tools/README.md @@ -190,6 +190,8 @@ findings, as applied to the read tools (the transport half is in is what makes both it and the lead's `\a@b@1` work. - **6 — no action** (a library limit; QA's note stands). +**2026-09-23 (dev, feedback-3).** `unit_interface`'s instantiation template is opt-in (`template: true`); without it the text ends after ports/modports/warnings and the JSON has no `template` key; the headers read `parameters (N):` / `ports (N):` (handshake change: answer shape and a new argument) — `docs/features/mcp-feedback-3`. + ## QA log **2026-09-23 (QA, M1 — the six read tools).** Verdict: **rework needed** diff --git a/docs/mcp/census-runs.txt b/docs/mcp/census-runs.txt new file mode 100644 index 0000000..32db419 --- /dev/null +++ b/docs/mcp/census-runs.txt @@ -0,0 +1,17 @@ +r1 a base: tokens=91094 tool_calls=10 wall_s=114 outcome=correct (47/47 rows, both params on every row; line numbers cite the module line) +r1 a mcp: tokens=107605 tool_calls=14 wall_s=335 outcome=correct (47/47) — used references on the module (whole-set, ~4 s per shim call) instead of hierarchy up; read files for overrides +r1 b base: tokens=59922 tool_calls=11 wall_s=25 outcome=correct (2 files, 3 lines, style matched, diagnostics clean) +r1 b mcp: tokens=74720 tool_calls=17 wall_s=78 outcome=correct (identical diff to base; used diagnostics to check; edited by hand rather than add_port) +r1 c base: tokens=87546 tool_calls=34 wall_s=172 outcome=correct (8/8 sites incl. the DV string path; nothing else touched; diagnostics clean) +r1 c mcp: tokens=104837 tool_calls=35 wall_s=171 outcome=INCOMPLETE 7/8 (missed the DV string path in entropy_src_path_if.sv); rename warned about the macro arg, agent fixed it; found chip_if by grep +r2 a mcp: tokens=106938 tool_calls=7 wall_s=105 outcome=INCOMPLETE 35/47 — used hierarchy up (good) but paged with a small limit and missed the trailing "… and N more"; feedback: total+range up front +r2 b mcp: tokens=70136 tool_calls=18 wall_s=86 outcome=correct (identical diff) +r2 c mcp: tokens=98636 tool_calls=35 wall_s=206 outcome=correct 8/8 (the unresolved-mentions list surfaced the DV string path; rename + manual fixes) +r2 c base rerun: tokens=92625 tool_calls=30 wall_s=131 outcome=correct 8/8 (variance vs r1 base 87546: +5.8%) +r3 a mcp: tokens=77708 tool_calls=9 wall_s=72 outcome=correct 47/47 (hierarchy up + in filter; -15% tokens vs base) +r3 b mcp: tokens=70030 tool_calls=17 wall_s=79 outcome=correct (identical diff) +r3 c mcp: tokens=109650 tool_calls=40 wall_s=218 outcome=correct 8/8 +r3 d base: tokens=102579 tool_calls=33 wall_s=235 outcome=correct (71 instances, 20 modules, all 20 port counts right) +r3 d mcp: tokens=106942 tool_calls=12 wall_s=305 outcome=correct (71/20, all counts); unit_interface templates x20 wasted tokens +r3 c base OPUS: tokens=61092 tool_calls=7 wall_s=44 outcome=correct 8/8 +r3 c mcp OPUS: tokens=69849 tool_calls=8 wall_s=62 outcome=correct 8/8 diff --git a/docs/site/dist/guides/agents/index.html b/docs/site/dist/guides/agents/index.html index fbc8265..2bd5946 100644 --- a/docs/site/dist/guides/agents/index.html +++ b/docs/site/dist/guides/agents/index.html @@ -149,132 +149,132 @@ description. The agent sees the full description and input schema.

project_overview -Summarise the Verilog/SystemVerilog project under the roots: file count, units by kind, top-level modules (nothing instantiates them) and the largest files. +Files, units by kind, top modules, largest files. list_units -List the modules, interfaces, packages, classes and programs declared in the project with their file:line, optionally filtered by kind and a name glob (*, ?). +Units (modules, interfaces, packages, classes, programs) with file:line. unit_interface -The interface of one unit by name: a module’s or interface’s parameters with defaults, ports in declaration order (direction, type, range) and a ready-to-paste instantiation; an interface’s modports; a package’s or class’s members. +A unit’s parameters, ports (direction, type, range), modports or members; template: true adds an instantiation. outline -The declarations in one file as a tree with 1-based line ranges (units, ports, parameters, signals, functions, instances, blocks), plus its parse errors. +A file’s declarations as a tree with line ranges, and its parse errors. read_item -The exact source text and 1-based line range of one item in a file: name, kind:name (e.g. function:crc), name@LINE when a name is declared twice, or always@LINE / initial@LINE / final@LINE / assign@LINE for the unlabelled block or assignment covering that line (@LINE is the last @ followed only by digits, so \a@b@1 is \a@b on line 1). +One item’s exact source and lines. search_symbols -Find declarations whose name contains query (case-insensitive) across the project: units, and the ports, parameters and package/class members other files can name. +Declarations whose name contains query (any case), members included. defines -The `define table: name, parameters, body (on one line) and file:line — of one file, of one macro name across the project (every definition; which one a use sees depends on include order, so none is picked), or of the whole project. +The `define table (name, parameters, body, file:line) of a file, a macro name, or all. definition -Where a name is declared: every declaration site as file:line:col, its kind and the declaration’s own source line (a name declared in several places lists them all, never a guess). +Where a name or macro is declared: file:line:col, kind, line. references -Every use of one declaration across the project, grouped by file as line:col and the line’s text — the same occurrences a rename would edit. +Uses of one declaration, then its unresolved mentions (strings, comments, macro text). hierarchy -The instance tree as indented instance : module #(overrides) lines, down from root (default: every top-level module), or with direction: up every parent.instance that instantiates root, with file:line. +Who instantiates a module (up, with file:line) or what it instantiates (down, default). diagnostics -Parse errors and lint findings for one file, or for every indexed file, grouped by file as line:col severity message [rule] — what lucisv check over the whole tree reports (cross-file rules on), under the project’s lucisv.toml [lint] settings and waivers. +Parse errors and lint findings (line:col severity message [rule]) of file or all. format yes -Format file (or the comma-separated files) as lucisv format does, under each file’s lucisv.toml; lines (12-40,55, one file only) formats just the constructs meeting those lines. +Format file/files as lucisv format; lines limits it. fix_lint yes -Apply the safe automatic fixes of the lint findings in file (or the comma-separated files), as lucisv check --fix does: the project’s [lint] config and waivers, never inside a // lucisv: off fence, never an unsafe fix. +Apply the safe lint fixes to file/files; says what remains. rename yes -Rename one declaration and every reference to it across the project, verified before anything is written. +Rename a declaration and its uses; select as definition. expand_wildcard yes -Replace one instantiation’s .* with the named connections it binds, verified before anything is written. +Replace one instance’s .* with the named connections it binds. convert_ports yes -Rewrite a module’s non-ANSI header (module m(a, b); input a; …) as an ANSI port list, verified before anything is written. +Rewrite a module’s non-ANSI header as an ANSI port list. organize_imports yes -Remove the unused import items of the scope at a position and sort the rest, verified before anything is written. +Remove unused imports in the scope at a position; sort the rest. inline_module yes -Replace one instantiation with the body of the module it instantiates, its connections substituted, verified before anything is written. +Replace one instance with its module’s body, connections substituted. propagate_ports yes -Add a named connection for every port one instantiation leaves unconnected, verified before anything is written. +Connect by name every port one instance leaves unconnected. remove_port yes -Delete one module port and its connection from every instantiation in the project, verified before anything is written. +Delete a port and its connection in every instantiation; refused while the body uses it. add_port yes -Add one ANSI port to a module and a connection for it to every instantiation in the project, verified before anything is written. +Add an ANSI port to a module, connected in every instantiation; after positions it. extract_module yes -Move the whole items on lines start_line..end_line of a module into a new module new_name, whose ports come from the dataflow across the selection, and instantiate it in their place; verified before anything is written. +Move whole items in lines start_line..end_line to a new module instantiated in their place. replace_item yes -Replace one item (read_item’s selector) with text, verified before anything is written: the file must still parse; text must be ONE item of the same kind (a module stays a module) declaring the same names unless rename: true (references are then NOT updated; rename does that). +Replace one item with text: one item, same kind and names (unless rename; references untouched). insert_item yes -Insert text (one item or more) before or after the item anchor names (read_item’s selector), or with anchor: "end" as the last items of the file’s last module, package or class (end@NAME for that unit), verified before anything is written: the file must still parse and text must be complete items the scope may hold. +Insert items text before or after item anchor, or at end (end@NAME) of the last unit (unit NAME). delete_item yes -Delete one item (read_item’s selector) and its own leading comments (up to a blank line), verified before anything is written. +Delete one item and its leading comments; refused while its names are used (sites listed) or it holds a `define, unless force. instantiate -The text of an instantiation of module name for the agent to place — parameters with their defaults, the instance name, and each port connected to a same-named signal (named) or as .* (wildcard). +Instantiation text for module name: parameters, instance name, named or .* ports. @@ -297,4 +297,4 @@ the directory the extension gives lucisv-server; - \ No newline at end of file + \ No newline at end of file diff --git a/docs/site/dist/pagefind/fragment/en_37d5dfa.pf_fragment b/docs/site/dist/pagefind/fragment/en_37d5dfa.pf_fragment deleted file mode 100644 index 3d57ddd..0000000 Binary files a/docs/site/dist/pagefind/fragment/en_37d5dfa.pf_fragment and /dev/null differ diff --git a/docs/site/dist/pagefind/fragment/en_c650207.pf_fragment b/docs/site/dist/pagefind/fragment/en_c650207.pf_fragment new file mode 100644 index 0000000..11d72dc Binary files /dev/null and b/docs/site/dist/pagefind/fragment/en_c650207.pf_fragment differ diff --git a/docs/site/dist/pagefind/index/en_37f7a58.pf_index b/docs/site/dist/pagefind/index/en_37f7a58.pf_index new file mode 100644 index 0000000..d43fdfe Binary files /dev/null and b/docs/site/dist/pagefind/index/en_37f7a58.pf_index differ diff --git a/docs/site/dist/pagefind/index/en_587d6ff.pf_index b/docs/site/dist/pagefind/index/en_587d6ff.pf_index deleted file mode 100644 index b1af295..0000000 Binary files a/docs/site/dist/pagefind/index/en_587d6ff.pf_index and /dev/null differ diff --git a/docs/site/dist/pagefind/index/en_a475cef.pf_index b/docs/site/dist/pagefind/index/en_a475cef.pf_index new file mode 100644 index 0000000..d9feb99 Binary files /dev/null and b/docs/site/dist/pagefind/index/en_a475cef.pf_index differ diff --git a/docs/site/dist/pagefind/index/en_ae41642.pf_index b/docs/site/dist/pagefind/index/en_ae41642.pf_index deleted file mode 100644 index f244528..0000000 Binary files a/docs/site/dist/pagefind/index/en_ae41642.pf_index and /dev/null differ diff --git a/docs/site/dist/pagefind/pagefind-entry.json b/docs/site/dist/pagefind/pagefind-entry.json index 5d0b4f5..8c57371 100644 --- a/docs/site/dist/pagefind/pagefind-entry.json +++ b/docs/site/dist/pagefind/pagefind-entry.json @@ -1 +1 @@ -{"version":"1.5.2","languages":{"en":{"hash":"en_946efe7afb","wasm":"en","page_count":13}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file +{"version":"1.5.2","languages":{"en":{"hash":"en_51647babd6","wasm":"en","page_count":13}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file diff --git a/docs/site/dist/pagefind/pagefind.en_51647babd6.pf_meta b/docs/site/dist/pagefind/pagefind.en_51647babd6.pf_meta new file mode 100644 index 0000000..cd238bc Binary files /dev/null and b/docs/site/dist/pagefind/pagefind.en_51647babd6.pf_meta differ diff --git a/docs/site/dist/pagefind/pagefind.en_946efe7afb.pf_meta b/docs/site/dist/pagefind/pagefind.en_946efe7afb.pf_meta deleted file mode 100644 index b0de50d..0000000 Binary files a/docs/site/dist/pagefind/pagefind.en_946efe7afb.pf_meta and /dev/null differ diff --git a/docs/site/src/content/docs/guides/agents.md b/docs/site/src/content/docs/guides/agents.md index d7b74e3..ddf8035 100644 --- a/docs/site/src/content/docs/guides/agents.md +++ b/docs/site/src/content/docs/guides/agents.md @@ -97,32 +97,32 @@ description. The agent sees the full description and input schema. | tool | writes | what it answers | |---|---|---| -| `project_overview` | | Summarise the Verilog/SystemVerilog project under the roots: file count, units by kind, top-level modules (nothing instantiates them) and the largest files. | -| `list_units` | | List the modules, interfaces, packages, classes and programs declared in the project with their file:line, optionally filtered by kind and a name glob (`*`, `?`). | -| `unit_interface` | | The interface of one unit by name: a module's or interface's parameters with defaults, ports in declaration order (direction, type, range) and a ready-to-paste instantiation; an interface's modports; a package's or class's members. | -| `outline` | | The declarations in one file as a tree with 1-based line ranges (units, ports, parameters, signals, functions, instances, blocks), plus its parse errors. | -| `read_item` | | The exact source text and 1-based line range of one item in a file: `name`, `kind:name` (e.g. `function:crc`), `name@LINE` when a name is declared twice, or `always@LINE` / `initial@LINE` / `final@LINE` / `assign@LINE` for the unlabelled block or assignment covering that line (`@LINE` is the last `@` followed only by digits, so `\a@b@1` is `\a@b` on line 1). | -| `search_symbols` | | Find declarations whose name contains `query` (case-insensitive) across the project: units, and the ports, parameters and package/class members other files can name. | -| `defines` | | The \`define table: name, parameters, body (on one line) and file:line — of one `file`, of one macro `name` across the project (every definition; which one a use sees depends on include order, so none is picked), or of the whole project. | -| `definition` | | Where a name is declared: every declaration site as file:line:col, its kind and the declaration's own source line (a name declared in several places lists them all, never a guess). | -| `references` | | Every use of one declaration across the project, grouped by file as line:col and the line's text — the same occurrences a rename would edit. | -| `hierarchy` | | The instance tree as indented `instance : module #(overrides)` lines, down from `root` (default: every top-level module), or with `direction: up` every `parent.instance` that instantiates `root`, with file:line. | -| `diagnostics` | | Parse errors and lint findings for one `file`, or for every indexed file, grouped by file as `line:col severity message [rule]` — what `lucisv check` over the whole tree reports (cross-file rules on), under the project's lucisv.toml [lint] settings and waivers. | -| `format` | yes | Format `file` (or the comma-separated `files`) as `lucisv format` does, under each file's lucisv.toml; `lines` (`12-40,55`, one file only) formats just the constructs meeting those lines. | -| `fix_lint` | yes | Apply the safe automatic fixes of the lint findings in `file` (or the comma-separated `files`), as `lucisv check --fix` does: the project's [lint] config and waivers, never inside a `// lucisv: off` fence, never an unsafe fix. | -| `rename` | yes | Rename one declaration and every reference to it across the project, verified before anything is written. | -| `expand_wildcard` | yes | Replace one instantiation's `.*` with the named connections it binds, verified before anything is written. | -| `convert_ports` | yes | Rewrite a module's non-ANSI header (`module m(a, b); input a; …`) as an ANSI port list, verified before anything is written. | -| `organize_imports` | yes | Remove the unused `import` items of the scope at a position and sort the rest, verified before anything is written. | -| `inline_module` | yes | Replace one instantiation with the body of the module it instantiates, its connections substituted, verified before anything is written. | -| `propagate_ports` | yes | Add a named connection for every port one instantiation leaves unconnected, verified before anything is written. | -| `remove_port` | yes | Delete one module port and its connection from every instantiation in the project, verified before anything is written. | -| `add_port` | yes | Add one ANSI port to a module and a connection for it to every instantiation in the project, verified before anything is written. | -| `extract_module` | yes | Move the whole items on lines `start_line`..`end_line` of a module into a new module `new_name`, whose ports come from the dataflow across the selection, and instantiate it in their place; verified before anything is written. | -| `replace_item` | yes | Replace one item (read_item's selector) with `text`, verified before anything is written: the file must still parse; `text` must be ONE item of the same kind (a module stays a module) declaring the same names unless `rename: true` (references are then NOT updated; `rename` does that). | -| `insert_item` | yes | Insert `text` (one item or more) before or after the item `anchor` names (read_item's selector), or with `anchor: "end"` as the last items of the file's last module, package or class (`end@NAME` for that unit), verified before anything is written: the file must still parse and `text` must be complete items the scope may hold. | -| `delete_item` | yes | Delete one item (read_item's selector) and its own leading comments (up to a blank line), verified before anything is written. | -| `instantiate` | | The text of an instantiation of module `name` for the agent to place — parameters with their defaults, the instance name, and each port connected to a same-named signal (`named`) or as `.*` (`wildcard`). | +| `project_overview` | | Files, units by kind, top modules, largest files. | +| `list_units` | | Units (modules, interfaces, packages, classes, programs) with file:line. | +| `unit_interface` | | A unit's parameters, ports (direction, type, range), modports or members; `template: true` adds an instantiation. | +| `outline` | | A file's declarations as a tree with line ranges, and its parse errors. | +| `read_item` | | One item's exact source and lines. | +| `search_symbols` | | Declarations whose name contains `query` (any case), members included. | +| `defines` | | The \`define table (name, parameters, body, file:line) of a `file`, a macro `name`, or all. | +| `definition` | | Where a name or macro is declared: file:line:col, kind, line. | +| `references` | | Uses of one declaration, then its unresolved mentions (strings, comments, macro text). | +| `hierarchy` | | Who instantiates a module (`up`, with file:line) or what it instantiates (`down`, default). | +| `diagnostics` | | Parse errors and lint findings (`line:col severity message [rule]`) of `file` or all. | +| `format` | yes | Format `file`/`files` as `lucisv format`; `lines` limits it. | +| `fix_lint` | yes | Apply the safe lint fixes to `file`/`files`; says what remains. | +| `rename` | yes | Rename a declaration and its uses; select as `definition`. | +| `expand_wildcard` | yes | Replace one instance's `.*` with the named connections it binds. | +| `convert_ports` | yes | Rewrite a module's non-ANSI header as an ANSI port list. | +| `organize_imports` | yes | Remove unused `import`s in the scope at a position; sort the rest. | +| `inline_module` | yes | Replace one instance with its module's body, connections substituted. | +| `propagate_ports` | yes | Connect by name every port one instance leaves unconnected. | +| `remove_port` | yes | Delete a port and its connection in every instantiation; refused while the body uses it. | +| `add_port` | yes | Add an ANSI port to a module, connected in every instantiation; `after` positions it. | +| `extract_module` | yes | Move whole items in lines `start_line`..`end_line` to a new module instantiated in their place. | +| `replace_item` | yes | Replace one item with `text`: one item, same kind and names (unless `rename`; references untouched). | +| `insert_item` | yes | Insert items `text` before or after item `anchor`, or at `end` (`end@NAME`) of the last unit (unit NAME). | +| `delete_item` | yes | Delete one item and its leading comments; refused while its names are used (sites listed) or it holds a \`define, unless `force`. | +| `instantiate` | | Instantiation text for module `name`: parameters, instance name, named or `.*` ports. | ## What it promises diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index e2d6a56..58af31c 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,7 +5,7 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). -## Unreleased +## 0.57.0 — 2026-09-23 - The platform packages (and the `all` package) now carry `lucisv-mcp`, the Model Context Protocol server for coding agents, beside `lucisv` and diff --git a/editors/vscode/README.md b/editors/vscode/README.md index d7e9736..c0915ec 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view, then open a Verilog or SystemVerilog file. There is no separate server or CLI setup. -The current release is **0.56.0**. Its platform packages include +The current release is **0.57.0**. Its platform packages include `lucisv-server` and the `lucisv` command-line tool (and, from the next release, `lucisv-mcp` — see [Agents (MCP)](#agents-mcp)): @@ -400,6 +400,13 @@ Every nesting color is a proper VS Code theme color: } ``` +## Release 0.57.0 highlights + +Version 0.57.0 bundles `lucisv-mcp` in every platform package and +registers it with VS Code's agent mode, adds the structural edit tools and +the warm start from the editor's index, and folds in what three rounds of +measuring agents against OpenTitan taught (see `mcp_analysis.md`). + ## Release 0.56.0 highlights Version 0.56.0 makes rename write out the `.name` and `.*` connections it diff --git a/mcp_analysis.md b/mcp_analysis.md index 0836079..28330ee 100644 --- a/mcp_analysis.md +++ b/mcp_analysis.md @@ -168,3 +168,80 @@ 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. + +## Round 3 — server at c2e42b8 (feedback-1 + feedback-2 applied) + +Tasks a–c as before (mcp arms), the new task d on both arms, and task c +once more with Opus 5.5 on both arms. + +| task | arm | model | tokens | tool calls | wall | outcome | +|---|---|---|---|---|---|---| +| a | mcp | Sonnet 5 | 77 708 | 9 | 72 s | correct, 47/47 | +| b | mcp | Sonnet 5 | 70 030 | 17 | 79 s | correct, identical diff | +| c | mcp | Sonnet 5 | 109 650 | 40 | 218 s | correct, 8/8 sites | +| d | base | Sonnet 5 | 102 579 | 33 | 235 s | correct, 71/20, all counts | +| d | mcp | Sonnet 5 | 106 942 | 12 | 305 s | correct, 71/20, all counts | +| c | base | Opus 5.5 | 61 092 | 7 | 44 s | correct, 8/8 sites | +| c | mcp | Opus 5.5 | 69 849 | 8 | 62 s | correct, 8/8 sites | + +### Observations + +**The census task finally paid: −15 % tokens, −37 % wall, 47/47.** With the +count line first and the `in` path filter, `hierarchy up prim_fifo_sync` +with `in: "ip/**/rtl/*.sv"` is one call that answers the whole question; +the agent spent its remaining turns formatting. Every other task is at or +slightly above the base arm on tokens and complete on correctness: + +- **b** (port propagation): +17 %, identical diff both ways, three rounds + running. The task is too small for a server to help: two files, three + lines, and the agent edits them by hand either way; the mcp arm pays the + catalogue and its `diagnostics` checks. +- **c** (cross-file rename): complete in every round since feedback-1, + at +19 % (Sonnet) and +14 % (Opus) over the base arm. What the server + buys here is not tokens but certainty: the base arm's completeness rests + on the agent choosing a broad enough search; the mcp arm gets the engine's + sites, the macro warning and the unresolved-mentions list handed to it. +- **d** (a 71-instance hierarchy with 20 port counts): +4 % tokens, a third + of the tool calls (12 vs 33). The answer text dominates both arms; the + server's overhead is twenty `unit_interface` answers each carrying a + 30-line instantiation template the task never used. Making the template + opt-in (feedback-3) removes roughly 15 k tokens from this run. +- **Opus vs Sonnet on c:** Opus needed 7–8 calls and ~65 k tokens either + way, Sonnet 30–40 calls and ~100 k; the server's relative overhead is the + same (+14 % vs +19 %). A stronger agent does not need the server more; it + needs it less, and uses it more economically when it has it. + +**What the shim costs.** Every mcp-arm call re-indexes the tree (1–2 s) and +the catalogue is read as text (≈3 000 tokens per session). A native host +keeps the process alive and sends the 18 kB `tools/list` JSON as tool +schemas (≈7 000 tokens, once per session, cached by the API). The wall +times above therefore overstate the server's latency; the token figures +understate the catalogue tax a native host pays and overstate the +per-call overhead. Neither changes the ranking. + +## Verdict, and what to do next + +**Helpful, not a toy — for the questions an engine answers better than +text search, and for the guarantees.** Across three rounds and 20 runs the +server never gave a wrong answer; every edit it wrote parsed, and every +refusal was right. Its measured value is: (1) one-call answers to +whole-design questions (who instantiates X, filtered by path) at fewer +tokens and a third of the wall time; (2) completeness on cross-file edits +that text search gets right only when the agent chooses a broad enough +search — the unresolved-mentions list turned a 7/8 into 8/8; (3) verified, +all-or-nothing writes with a diff first, which the agents used and trusted. +Its measured cost is a fixed catalogue tax and verbose answers, which is +why small edit tasks come out 15–20 % dearer in tokens. + +**Improvements that fell out of the loop and landed** (feedback-1/2): the +unresolved-mentions section; `hierarchy`/`references` routing and a 40 % +smaller catalogue; the count line first; default limit 500; the `in` path +filter; positioned `add_port`; post-edit check hints. + +**Still to do** (feedback-3 and after): the instantiation template opt-in +on `unit_interface`; a terser `hierarchy` line (overrides only on request); +then re-measure d. Beyond rendering, the token win will come from letting +the agent ask compound questions — one call for "instances of X under +`ip/` with each target's port count" — which is a tool that composes +`hierarchy` and `unit_interface`; the census says that is where the next +15 % is.