Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5316c0b127 | ||
|
|
74c56318c0 | ||
|
|
b757e82161 | ||
|
|
e992cca577 |
No files matched your search
@@ -4,6 +4,45 @@ 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.59.0 — 2026-09-29
|
||||
|
||||
### MCP read-only mode
|
||||
|
||||
PLAN §11, the owner's request of 2026-09-29: one binary, two modes.
|
||||
(`docs/features/mcp-read-only`.)
|
||||
|
||||
- **`lucisv-mcp --read-only`** offers exactly the five read tools —
|
||||
`hierarchy`, `find`, `outline`, `read`, `check`, in that order, with the
|
||||
same descriptions and schemas as full mode. The model-visible catalogue is
|
||||
1 797 bytes (budget ≤ 1 800) and the instructions 297 bytes (≤ 300), both
|
||||
pinned by `tests/read_only.rs`.
|
||||
- The mode filters the tool registry: `tools/call` of `rename`, `port`,
|
||||
`edit_item` or `format` is the unknown-tool error (`-32602`,
|
||||
`unknown tool: rename (the server runs --read-only)`); no edit handler is
|
||||
reachable. Resources answer as in full mode.
|
||||
- **No write inside a root**, whatever is called: a test snapshots every
|
||||
path, size and mtime (directories too) of a fixture copy, calls every
|
||||
full-catalogue tool name (the four edits with valid edit arguments, which
|
||||
a control test shows do write in full mode) and every resource, and finds
|
||||
the snapshot unchanged after the server exits. The server's own index
|
||||
store under `--index-cache` is still written (outside the roots unless
|
||||
`--index-cache` names a directory inside one).
|
||||
- **Full mode is byte-identical to 0.58.0** on the wire (`initialize`,
|
||||
`tools/list`); only the usage line gains `[--read-only]`.
|
||||
- **Extension:** setting `lucisv.mcp.mode` (`"full"` default, `"read-only"`)
|
||||
— the definition gains `--read-only` and the label becomes
|
||||
`lucisv read-only (<folder>)`; a change of the setting re-announces the
|
||||
servers. **lucisv: Copy MCP server config** follows it (server key
|
||||
`lucisv-ro`, args ending `--read-only`, the message names the mode).
|
||||
- `editors/vscode/mcp_smoke.js <binary> --read-only` smokes the mode (five
|
||||
tools, one `hierarchy`, `rename` refused, files untouched);
|
||||
`tools/release.sh` runs both smokes on the host binary and on the one
|
||||
embedded in the package.
|
||||
- `hierarchy` caps at 300 instances, 100 with `peek`; `peek` lines no
|
||||
longer count toward the cap (census round 5: `prim_fifo_sync` up with
|
||||
peek showed 20 of 77 instantiations). Without `peek` the answer is
|
||||
unchanged.
|
||||
|
||||
## 0.58.0 — 2026-09-24
|
||||
|
||||
### The lean MCP catalogue: nine tools, short answers, trusted writes
|
||||
|
||||
Generated
+9
-9
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
@@ -126,7 +126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -279,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -292,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -13,7 +13,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.58.0"
|
||||
version = "0.59.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
+34
@@ -448,6 +448,40 @@ Feature README `docs/features/mcp-lean-catalogue`. One dev (Opus), one QA
|
||||
(a −1 %, d parity, b +10 %, c +9 % vs the base re-run; 6/6 correct);
|
||||
gates: 4 922 tests / 0 failed, corpus 814/820
|
||||
|
||||
## M8. Read-only mode (0.59; PLAN §11 — owner's request 2026-09-29)
|
||||
|
||||
`lucisv-mcp --read-only`: five tools, ≤ 1 800 model-visible bytes,
|
||||
instructions ≤ 300, never writes inside a root; full mode unchanged.
|
||||
Feature README `docs/features/mcp-read-only`. One dev (Opus), one QA
|
||||
(Opus), on trunk.
|
||||
|
||||
- [x] server: `--read-only` parsed, in the usage line; the registry
|
||||
filtered by mode (`tools/list`, `tools/call`); read-only
|
||||
instructions; the unknown-tool message for the four edit tools
|
||||
- [x] tests (`tests/wire.rs` or a new `tests/read_only.rs`): names and
|
||||
order, both budgets, full mode unchanged byte for byte, every
|
||||
full-catalogue tool name called in read-only mode leaves the tree
|
||||
untouched (sizes, mtimes, names)
|
||||
- [x] extension: `lucisv.mcp.mode` setting, label, args, change event,
|
||||
copy-config (`lucisv-ro` key, `--read-only`), node tests;
|
||||
`mcp_smoke.js --read-only`; `tools/release.sh` runs both smokes
|
||||
- [x] docs: feature README; Agents guide (a "Read-only mode" section, the
|
||||
table's `writes` column already tells the five); extension
|
||||
README/CHANGELOG; `CHANGELOG.md` 0.59.0 (unreleased);
|
||||
`docs/topo.md` §2.8; `tools/RELEASING.md`; manual-acceptance rows
|
||||
- [x] QA: attack the no-write promise (every edit tool name, resources,
|
||||
malformed calls, a call racing a mode it does not have), the budgets,
|
||||
full-mode identity against the 0.58.0 binary, the extension tests
|
||||
- [x] census round 5 (lead): tasks a and d on `--read-only` — done
|
||||
2026-09-29 (74c5631): 7 runs, all correct; with same-day base controls
|
||||
a +8 %, d −8 % (parity); found and fixed the `peek` cap defect
|
||||
(`hierarchy` caps at 300 instances, 100 with `peek`)
|
||||
- [x] release 0.59.0 — tagged 2026-09-29; gates: clippy -D warnings, fmt,
|
||||
72 suites + 6 doc suites (4 937 passed, 0 failed), corpus 814/820,
|
||||
node tests 6/6. The first suite run stalled 25 min in the vlog_linter
|
||||
doc-test and was cut by the guard; the doc-tests passed in under a
|
||||
minute as their own gate
|
||||
|
||||
## Open questions for the owner (answer before the lane that needs it)
|
||||
|
||||
1. **Engine bump** (M5): if `vsce` accepts the contribution point on
|
||||
|
||||
@@ -22,8 +22,7 @@ use std::process::ExitCode;
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
/// What someone who spelled an argument wrong is told, on stderr.
|
||||
const USAGE: &str =
|
||||
"usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--verbose]";
|
||||
const USAGE: &str = "usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--read-only] [--verbose]";
|
||||
|
||||
/// The command line, parsed.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
@@ -35,6 +34,8 @@ pub struct Options {
|
||||
/// `--index-cache DIR`: the language server's index cache directory,
|
||||
/// read at startup; this server's own store is written there on exit.
|
||||
pub index_cache: Option<PathBuf>,
|
||||
/// `--read-only`: the five read tools only (PLAN §11).
|
||||
pub mode: tools::Mode,
|
||||
/// `--verbose`: per-call timing lines on stderr.
|
||||
pub verbose: bool,
|
||||
}
|
||||
@@ -88,6 +89,7 @@ fn parse_args(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
"--root" => options.roots.push(value("--root")?),
|
||||
"--filelist" => options.filelist = Some(value("--filelist")?),
|
||||
"--index-cache" => options.index_cache = Some(value("--index-cache")?),
|
||||
"--read-only" => options.mode = tools::Mode::ReadOnly,
|
||||
"--verbose" => options.verbose = true,
|
||||
other => return Err(format!("unknown option: {other}")),
|
||||
}
|
||||
@@ -114,13 +116,23 @@ mod tests {
|
||||
"f.f",
|
||||
"--index-cache",
|
||||
"c",
|
||||
"--read-only",
|
||||
"--verbose",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(options.roots, vec![PathBuf::from("a"), PathBuf::from("b")]);
|
||||
assert_eq!(options.filelist, Some(PathBuf::from("f.f")));
|
||||
assert_eq!(options.index_cache, Some(PathBuf::from("c")));
|
||||
assert_eq!(options.mode, tools::Mode::ReadOnly);
|
||||
assert!(options.verbose);
|
||||
assert_eq!(parse(&["--verbose"]).unwrap().mode, tools::Mode::Full);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_usage_line_names_every_flag() {
|
||||
for flag in ["--root", "--filelist", "--index-cache", "--read-only", "--verbose"] {
|
||||
assert!(USAGE.contains(flag), "{flag}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -111,7 +111,9 @@ fn run(
|
||||
tool: &str,
|
||||
argument: Option<(&str, &str)>,
|
||||
) -> Result<String, String> {
|
||||
let tool = tools::find(tool).ok_or_else(|| format!("no tool `{tool}`"))?;
|
||||
// A resource runs read tools only, so it answers the same in either mode.
|
||||
let tool =
|
||||
tools::find(tool, tools::Mode::ReadOnly).ok_or_else(|| format!("no tool `{tool}`"))?;
|
||||
let mut arguments = Map::new();
|
||||
if let Some((name, value)) = argument {
|
||||
arguments.insert(name.to_string(), Value::from(value));
|
||||
|
||||
@@ -13,7 +13,7 @@ use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::resources::{self, Resource};
|
||||
use crate::tools;
|
||||
use crate::tools::{self, Mode};
|
||||
use crate::transport::{Line, Transport};
|
||||
use crate::Options;
|
||||
|
||||
@@ -38,6 +38,17 @@ const RESOURCE_NOT_FOUND: i64 = -32002;
|
||||
/// What the agent is told once, at `initialize` (PLAN §10.3, ≤ 400 bytes).
|
||||
const INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
|
||||
|
||||
/// What the agent is told in `--read-only` mode (PLAN §11.1, ≤ 300 bytes).
|
||||
const INSTRUCTIONS_READ_ONLY: &str = "lucisv-mcp reads the SystemVerilog on disk (save first); it never edits. Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check for issues. Paths root-relative, lines 1-based.";
|
||||
|
||||
/// The instructions for `mode`.
|
||||
fn instructions(mode: Mode) -> &'static str {
|
||||
match mode {
|
||||
Mode::Full => INSTRUCTIONS,
|
||||
Mode::ReadOnly => INSTRUCTIONS_READ_ONLY,
|
||||
}
|
||||
}
|
||||
|
||||
/// A JSON-RPC error object.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct RpcError {
|
||||
@@ -195,7 +206,7 @@ impl Server {
|
||||
"initialize" => Ok(self.initialize(params.as_ref())),
|
||||
"ping" => Ok(json!({})),
|
||||
_ if self.version.is_none() => Err(fault(NOT_INITIALIZED, "server not initialized")),
|
||||
"tools/list" => Ok(tools::list()),
|
||||
"tools/list" => Ok(tools::list(self.options.mode)),
|
||||
"tools/call" => self.call_tool(params),
|
||||
"resources/list" => Ok(resources::list()),
|
||||
"resources/templates/list" => Ok(resources::templates()),
|
||||
@@ -217,7 +228,7 @@ impl Server {
|
||||
"protocolVersion": version,
|
||||
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
|
||||
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
|
||||
"instructions": INSTRUCTIONS,
|
||||
"instructions": instructions(self.options.mode),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -233,8 +244,8 @@ impl Server {
|
||||
let Some(Value::String(name)) = params.remove("name") else {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call params need a string `name`"));
|
||||
};
|
||||
let Some(tool) = tools::find(&name) else {
|
||||
return Err(fault(INVALID_PARAMS, format!("unknown tool: {name}")));
|
||||
let Some(tool) = tools::find(&name, self.options.mode) else {
|
||||
return Err(fault(INVALID_PARAMS, unknown_tool(&name, self.options.mode)));
|
||||
};
|
||||
let arguments = match params.remove("arguments") {
|
||||
None | Some(Value::Null) => Map::new(),
|
||||
@@ -319,6 +330,15 @@ fn open_project(options: &Options) -> Project {
|
||||
project
|
||||
}
|
||||
|
||||
/// The `-32602` message for a tool `mode` does not offer. In read-only mode
|
||||
/// it says why, so an agent does not retry an edit the server cannot make.
|
||||
fn unknown_tool(name: &str, mode: Mode) -> String {
|
||||
match mode {
|
||||
Mode::Full => format!("unknown tool: {name}"),
|
||||
Mode::ReadOnly => format!("unknown tool: {name} (the server runs --read-only)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A tool's answer as `tools/call` returns it.
|
||||
fn tool_result(answer: Result<tools::Answer, String>) -> Value {
|
||||
match answer {
|
||||
@@ -348,6 +368,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_instructions_stay_under_400_bytes() {
|
||||
assert!(INSTRUCTIONS.len() <= 400, "{}", INSTRUCTIONS.len());
|
||||
assert!(INSTRUCTIONS_READ_ONLY.len() <= 300, "{}", INSTRUCTIONS_READ_ONLY.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -32,9 +32,16 @@ const MAX_DEPTH: i64 = 20;
|
||||
/// The most nodes one walk collects before it stops.
|
||||
const NODE_CAP: usize = 50_000;
|
||||
|
||||
/// The most lines an answer holds before `… and N more`.
|
||||
/// The most lines the overview holds, and the most nodes (tree lines, the
|
||||
/// root's included) a tree answer without `peek` shows, before
|
||||
/// `… and N more`.
|
||||
const CAP: usize = 300;
|
||||
|
||||
/// The most nodes a tree answer with `peek` shows. A node's `peek` lines
|
||||
/// never count — the cap is on instances — but each costs up to 13 lines,
|
||||
/// so the answer stays short (PLAN §10.1).
|
||||
const PEEK_CAP: usize = 100;
|
||||
|
||||
/// The most source lines `peek` shows of one statement before `…`.
|
||||
const PEEK_LINES: usize = 12;
|
||||
|
||||
@@ -271,14 +278,21 @@ impl<'a> Walk<'a> {
|
||||
}
|
||||
|
||||
/// The nodes as lines, two spaces per level (`up` starts at no indent),
|
||||
/// each followed by its statement on `peek`; cut whole nodes at [`CAP`].
|
||||
/// each followed by its statement on `peek`; at most [`CAP`] nodes
|
||||
/// ([`PEEK_CAP`] with `peek`), then `… and N more` counting the nodes not
|
||||
/// shown.
|
||||
fn render_nodes(project: &Project, nodes: &[Node], up: bool, peek: bool) -> Vec<String> {
|
||||
let mut texts = Texts::default();
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
let cap = if peek { PEEK_CAP } else { CAP };
|
||||
for (at, node) in nodes.iter().enumerate() {
|
||||
if at == cap {
|
||||
lines.push(render::more(nodes.len() - at));
|
||||
return lines;
|
||||
}
|
||||
let level = if up { node.depth - 1 } else { node.depth };
|
||||
let indent = " ".repeat(level);
|
||||
let mut block = vec![format!("{indent}{}", node_line(project, &mut texts, node, up))];
|
||||
lines.push(format!("{indent}{}", node_line(project, &mut texts, node, up)));
|
||||
if let (true, Some(child)) = (peek, &node.instance) {
|
||||
let source = statement(project, &mut texts, child);
|
||||
// A blank line of the statement stays blank: no indent of ours.
|
||||
@@ -286,13 +300,8 @@ fn render_nodes(project: &Project, nodes: &[Node], up: bool, peek: bool) -> Vec<
|
||||
true => line,
|
||||
false => format!("{indent} {line}"),
|
||||
};
|
||||
block.extend(source.into_iter().map(shown));
|
||||
lines.extend(source.into_iter().map(shown));
|
||||
}
|
||||
if lines.len() + block.len() > CAP {
|
||||
lines.push(render::more(nodes.len() - at));
|
||||
return lines;
|
||||
}
|
||||
lines.extend(block);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
@@ -105,14 +105,39 @@ const TOOLS: &[(Tool, Effect)] = &[
|
||||
(format::FORMAT, Edit { idempotent: true }),
|
||||
];
|
||||
|
||||
/// The tool called `name`.
|
||||
pub fn find(name: &str) -> Option<&'static Tool> {
|
||||
TOOLS.iter().map(|(tool, _)| tool).find(|tool| tool.name == name)
|
||||
/// Which part of the registry the server offers (PLAN §11).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// Every tool, the edits included.
|
||||
#[default]
|
||||
Full,
|
||||
/// `--read-only`: the read tools alone; an edit tool is unknown.
|
||||
ReadOnly,
|
||||
}
|
||||
|
||||
/// The `tools/list` result: every tool, no pagination.
|
||||
pub fn list() -> Value {
|
||||
let tools: Vec<Value> = TOOLS.iter().map(|(tool, effect)| describe(tool, *effect)).collect();
|
||||
impl Mode {
|
||||
/// Whether a tool of this effect exists in this mode.
|
||||
fn offers(self, effect: Effect) -> bool {
|
||||
matches!((self, effect), (Mode::Full, _) | (Mode::ReadOnly, Read))
|
||||
}
|
||||
}
|
||||
|
||||
/// The tools `mode` offers, in `tools/list` order.
|
||||
fn offered(mode: Mode) -> impl Iterator<Item = (&'static Tool, Effect)> {
|
||||
TOOLS
|
||||
.iter()
|
||||
.filter(move |(_, effect)| mode.offers(*effect))
|
||||
.map(|(tool, effect)| (tool, *effect))
|
||||
}
|
||||
|
||||
/// The tool called `name`, when `mode` offers it.
|
||||
pub fn find(name: &str, mode: Mode) -> Option<&'static Tool> {
|
||||
offered(mode).map(|(tool, _)| tool).find(|tool| tool.name == name)
|
||||
}
|
||||
|
||||
/// The `tools/list` result: every tool `mode` offers, no pagination.
|
||||
pub fn list(mode: Mode) -> Value {
|
||||
let tools: Vec<Value> = offered(mode).map(|(tool, effect)| describe(tool, effect)).collect();
|
||||
json!({ "tools": tools })
|
||||
}
|
||||
|
||||
@@ -253,8 +278,20 @@ mod tests {
|
||||
assert_eq!(names.len(), unique.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_mode_offers_the_read_tools_alone_in_order() {
|
||||
let names = |mode| -> Vec<&str> { offered(mode).map(|(tool, _)| tool.name).collect() };
|
||||
assert_eq!(names(Mode::ReadOnly), ["hierarchy", "find", "outline", "read", "check"]);
|
||||
assert_eq!(names(Mode::Full).len(), TOOLS.len());
|
||||
for edit in ["rename", "port", "edit_item", "format"] {
|
||||
assert!(find(edit, Mode::ReadOnly).is_none(), "{edit}");
|
||||
assert!(find(edit, Mode::Full).is_some(), "{edit}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_names_the_offending_argument() {
|
||||
let find = |name| find(name, Mode::Full);
|
||||
let tool = find("check").unwrap();
|
||||
let unknown = validate(tool, args(json!({"fil": "x"}))).err().unwrap();
|
||||
assert!(unknown.contains("`fil`") && unknown.contains("file"), "{unknown}");
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! The `hierarchy` cap counts instances, never `peek` lines (census round 5,
|
||||
//! 2026-09-29): an agent asking for every instantiation of a module with
|
||||
//! `peek` gets every one up to 100 (300 without `peek`), each with its
|
||||
//! statement, not a quarter of them. Each test writes a generated design into a scratch directory and
|
||||
//! talks to the real binary over it.
|
||||
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A scratch design, removed on drop.
|
||||
struct Tree(PathBuf);
|
||||
|
||||
impl Tree {
|
||||
fn with(files: &[(&str, String)]) -> Tree {
|
||||
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
|
||||
let dir = std::env::temp_dir()
|
||||
.join(format!("lucisv-mcp-hierarchy-cap-{}-{unique}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
for (rel, text) in files {
|
||||
fs::write(dir.join(rel), text).unwrap();
|
||||
}
|
||||
Tree(fs::canonicalize(dir).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One `hierarchy` call over `tree` that must succeed: its text.
|
||||
fn hierarchy(tree: &Tree, arguments: Value) -> String {
|
||||
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 init = json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
|
||||
"protocolVersion": "2025-06-18", "capabilities": {},
|
||||
"clientInfo": {"name": "hierarchy_cap", "version": "0"}}});
|
||||
let params = json!({"name": "hierarchy", "arguments": arguments});
|
||||
let call = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params});
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
stdin.write_all(format!("{init}\n{call}\n").as_bytes()).unwrap();
|
||||
drop(stdin);
|
||||
let output = child.wait_with_output().unwrap();
|
||||
let stdout = String::from_utf8(output.stdout).unwrap();
|
||||
let reply: Value = stdout
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<Value>(line).unwrap())
|
||||
.find(|reply| reply["id"] == 1)
|
||||
.expect("the call is answered");
|
||||
assert_eq!(reply["result"]["isError"], false, "{reply}");
|
||||
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// `count` instantiations of `sub` in `top`, each written over `ports + 2`
|
||||
/// lines: the header, one line per port, the closer.
|
||||
fn crowded(count: usize, ports: usize) -> Tree {
|
||||
let names: Vec<String> = (0..ports).map(|p| format!("p{p}")).collect();
|
||||
let declared: Vec<String> = names.iter().map(|n| format!("input logic {n}")).collect();
|
||||
let sub = format!("module sub #(parameter int W = 1) ({});\nendmodule\n", declared.join(", "));
|
||||
let mut top = format!("module top;\n logic {};\n", names.join(", "));
|
||||
for i in 0..count {
|
||||
top.push_str(&format!(" sub #(.W({i})) u_{i:03} (\n"));
|
||||
for (at, name) in names.iter().enumerate() {
|
||||
let comma = if at + 1 < names.len() { "," } else { "" };
|
||||
top.push_str(&format!(" .{name}({name}){comma}\n"));
|
||||
}
|
||||
top.push_str(" );\n");
|
||||
}
|
||||
top.push_str("endmodule\n");
|
||||
Tree::with(&[("sub.sv", sub), ("top.sv", top)])
|
||||
}
|
||||
|
||||
/// The tree lines of an answer: every line that is not a peeked statement.
|
||||
fn node_lines(text: &str, statement_indent: &str) -> Vec<String> {
|
||||
text.lines().filter(|l| !l.starts_with(statement_indent)).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn up_with_peek_lists_every_instantiation_whatever_the_statements_cost() {
|
||||
// 30 instantiations of 14 lines each: peek shows 12 lines and `…` per
|
||||
// statement, 420 lines in all — every one is still there.
|
||||
let tree = crowded(30, 12);
|
||||
let text = hierarchy(&tree, json!({"root": "sub", "up": true, "peek": true}));
|
||||
let nodes = node_lines(&text, " ");
|
||||
let expected: Vec<String> =
|
||||
(0..30).map(|i| format!("top.u_{i:03} top.sv:{}", 3 + i * 14)).collect();
|
||||
assert_eq!(nodes, expected, "{text}");
|
||||
assert!(!text.contains("… and "), "{text}");
|
||||
assert_eq!(text.lines().count(), 30 * 14);
|
||||
// Each statement: its first 12 lines as written, then `…`.
|
||||
let first: Vec<&str> = text.lines().skip(1).take(13).collect();
|
||||
assert_eq!(first[0], " sub #(.W(0)) u_000 (");
|
||||
assert_eq!(first[11], " .p10(p10),");
|
||||
assert_eq!(first[12], " …");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_100_instances_with_peek_shows_100_and_over_300_without_shows_300() {
|
||||
let tree = crowded(350, 1);
|
||||
// Up with peek: 350 instantiations, 100 shown, each with its 3-line statement.
|
||||
let up = hierarchy(&tree, json!({"root": "sub", "up": true, "peek": true}));
|
||||
let lines: Vec<&str> = up.lines().collect();
|
||||
assert_eq!(lines.len(), 100 * 4 + 1, "{up}");
|
||||
assert_eq!(*lines.last().unwrap(), "… and 250 more");
|
||||
let nodes = node_lines(&up, " ");
|
||||
assert_eq!(nodes.len(), 101);
|
||||
assert_eq!(nodes[99], "top.u_099 top.sv:300");
|
||||
assert_eq!(lines[lines.len() - 2], " );", "the last statement is whole");
|
||||
// Down with peek: the root line and 99 instances make 100 nodes; 251 are left.
|
||||
let down = hierarchy(&tree, json!({"root": "top", "peek": true}));
|
||||
let nodes = node_lines(&down, " ");
|
||||
assert_eq!(nodes.len(), 101, "{down}");
|
||||
assert_eq!(nodes[0], "top top.sv:1");
|
||||
assert_eq!(nodes[99], " u_098: sub top.sv:297");
|
||||
assert_eq!(nodes[100], "… and 251 more");
|
||||
// Without peek: 300 lines, then the count.
|
||||
let plain = hierarchy(&tree, json!({"root": "sub", "up": true}));
|
||||
assert_eq!(plain.lines().count(), 301);
|
||||
assert!(plain.ends_with("\n… and 50 more\n"), "{plain}");
|
||||
let plain = hierarchy(&tree, json!({"root": "top"}));
|
||||
assert_eq!(plain.lines().count(), 301);
|
||||
assert!(plain.ends_with("\n… and 51 more\n"), "{plain}");
|
||||
}
|
||||
@@ -197,7 +197,7 @@ fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
|
||||
let expected = [
|
||||
(300, 101), // the root line + 400 instances
|
||||
(300, 100), // 400 instantiations
|
||||
(299, 251), // root + 149 two-line blocks; the 150th block would pass 300
|
||||
(199, 301), // root + 99 two-line blocks: with peek the cap is 100 nodes
|
||||
(300, 23), // counts line + 322 tops
|
||||
(300, 20), // 320 declarations
|
||||
(300, 51), // file:line + 350 ports
|
||||
@@ -220,9 +220,11 @@ fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
|
||||
assert_eq!(file, "rtl/big.sv");
|
||||
number.parse::<u32>().unwrap();
|
||||
}
|
||||
// A peek block is never split: the last shown line is a statement.
|
||||
// A peek block is never split: the last shown line is the 99th
|
||||
// instance's statement.
|
||||
let peek: Vec<&str> = said[2].text.lines().collect();
|
||||
assert_eq!(peek[298], " leaf u_148 (.a(a));");
|
||||
assert_eq!(peek[197], " u_098: leaf rtl/big.sv:101");
|
||||
assert_eq!(peek[198], " leaf u_098 (.a(a));");
|
||||
for line in said[7].text.lines().take(200) {
|
||||
assert!(line.starts_with("rtl/wide.sv:") && line.ends_with("[unused-signal]"), "{line}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
//! QA attacks on lane M8 (`--read-only`), 2026-09-29.
|
||||
//!
|
||||
//! Every test copies a fixture into its own scratch directory, spawns the
|
||||
//! real binary over it, writes a whole session to stdin, closes it and reads
|
||||
//! every answer — the host's view, nothing else. The no-write promise is
|
||||
//! checked by a snapshot of every entry under the root: a file's size, mtime
|
||||
//! and bytes, a directory's mtime (which moves when anything is created,
|
||||
//! renamed or removed in it, a temporary file included).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// The message a read-only server refuses `name` with.
|
||||
fn refused(name: &str) -> String {
|
||||
format!("unknown tool: {name} (the server runs --read-only)")
|
||||
}
|
||||
|
||||
/// A scratch directory, removed on drop.
|
||||
struct Tree(PathBuf);
|
||||
|
||||
impl Tree {
|
||||
fn empty() -> Tree {
|
||||
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-qa-m8-{}-{unique}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
Tree(fs::canonicalize(dir).unwrap())
|
||||
}
|
||||
|
||||
/// A fresh copy of `tests/fixtures/<fixture>`.
|
||||
fn of(fixture: &str) -> Tree {
|
||||
let tree = Tree::empty();
|
||||
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
|
||||
copy_tree(&source, &tree.0);
|
||||
tree
|
||||
}
|
||||
|
||||
fn arg(&self) -> &str {
|
||||
self.0.to_str().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) {
|
||||
fs::create_dir_all(to).unwrap();
|
||||
for entry in fs::read_dir(from).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let target = to.join(entry.file_name());
|
||||
if entry.file_type().unwrap().is_dir() {
|
||||
copy_tree(&entry.path(), &target);
|
||||
} else {
|
||||
fs::copy(entry.path(), target).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry under a root: a file's size, mtime and bytes; a directory's mtime.
|
||||
type Entry = (Option<u64>, SystemTime, Option<Vec<u8>>);
|
||||
|
||||
fn snapshot(tree: &Tree) -> BTreeMap<String, Entry> {
|
||||
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Entry>) {
|
||||
let relative = |path: &Path| path.strip_prefix(root).unwrap().to_string_lossy().to_string();
|
||||
let meta = fs::symlink_metadata(dir).unwrap();
|
||||
out.insert(format!("{}/", relative(dir)), (None, meta.modified().unwrap(), None));
|
||||
for entry in fs::read_dir(dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let meta = fs::symlink_metadata(&path).unwrap();
|
||||
if meta.is_dir() {
|
||||
walk(&path, root, out);
|
||||
} else {
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
out.insert(
|
||||
relative(&path),
|
||||
(Some(meta.len()), meta.modified().unwrap(), Some(bytes)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
walk(&tree.0, &tree.0, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Run the binary with `args`, send `lines` (one JSON-RPC message each),
|
||||
/// close stdin and wait for it to exit.
|
||||
fn run(args: &[&str], lines: &[Value]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
for line in lines {
|
||||
// A raw line is passed as a JSON string, everything else serialised.
|
||||
let text = match line {
|
||||
Value::String(raw) => raw.clone(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
writeln!(stdin, "{text}").unwrap();
|
||||
}
|
||||
drop(stdin);
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
/// Every answer on stdout, by its id as JSON text (`"\"c\""`, `null`).
|
||||
fn answers(output: &Output) -> BTreeMap<String, Value> {
|
||||
let stdout = String::from_utf8(output.stdout.clone()).unwrap();
|
||||
let mut out = BTreeMap::new();
|
||||
for line in stdout.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let reply: Value = serde_json::from_str(line).expect("every stdout line is JSON");
|
||||
out.entry(reply["id"].to_string()).or_insert(reply);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn request(id: &str, method: &str, params: Value) -> Value {
|
||||
json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
|
||||
}
|
||||
|
||||
fn call(id: &str, name: Value, arguments: Value) -> Value {
|
||||
request(id, "tools/call", json!({"name": name, "arguments": arguments}))
|
||||
}
|
||||
|
||||
fn initialize(id: &str) -> Value {
|
||||
request(id, "initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}))
|
||||
}
|
||||
|
||||
/// Every shape of every edit tool, each a real write in full mode
|
||||
/// (`qa_every_edit_shape_writes_in_full_mode`), on the `edit` fixture.
|
||||
fn edit_shapes() -> Vec<(&'static str, Value)> {
|
||||
vec![
|
||||
("rename", json!({"name": "leaf", "new_name": "leaf2"})),
|
||||
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
|
||||
("port", json!({"module": "spare", "add": "input logic en"})),
|
||||
("port", json!({"module": "spare", "add": "input logic en2", "after": "clk"})),
|
||||
("port", json!({"module": "spare", "remove": "unused_i"})),
|
||||
(
|
||||
"edit_item",
|
||||
json!({"file": "rtl/mid.sv", "op": "replace", "item": "u_leaf", "text": "leaf u_leaf (.clk(clk), .d(din), .q(dout));"}),
|
||||
),
|
||||
(
|
||||
"edit_item",
|
||||
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_b;"}),
|
||||
),
|
||||
(
|
||||
"edit_item",
|
||||
json!({"file": "rtl/leaf.sv", "op": "insert_after", "item": "end", "text": "logic spare_a;"}),
|
||||
),
|
||||
("edit_item", json!({"file": "rtl/spare_user.sv", "op": "delete", "item": "spare_user"})),
|
||||
("format", json!({"files": "fmt/messy.sv"})),
|
||||
("format", json!({"files": "fmt/messy.sv", "fix": true})),
|
||||
("format", json!({"files": "**/*.sv", "fix": true})),
|
||||
("format", json!({"files": "rtl"})),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_every_edit_shape_writes_in_full_mode() {
|
||||
// The control for the promise: each shape really edits without the flag.
|
||||
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
|
||||
let tree = Tree::of("edit");
|
||||
let before = snapshot(&tree);
|
||||
let lines = [initialize("i"), call("c", json!(name), arguments.clone())];
|
||||
let output = run(&["--root", tree.arg()], &lines);
|
||||
let reply = &answers(&output)["\"c\""];
|
||||
assert_eq!(reply["result"]["isError"], false, "{index} {name} {arguments}: {reply}");
|
||||
assert_ne!(before, snapshot(&tree), "{index} {name} wrote nothing in full mode");
|
||||
}
|
||||
}
|
||||
|
||||
/// The malformed and near-miss calls a read-only server must refuse, each
|
||||
/// with the code and message it must answer.
|
||||
fn hostile_calls() -> Vec<(Value, i64, String)> {
|
||||
let mut out = Vec::new();
|
||||
// Names that differ from an edit tool by case, whitespace or spelling.
|
||||
for name in [
|
||||
"Rename",
|
||||
"RENAME",
|
||||
" rename",
|
||||
"rename ",
|
||||
"rename\n",
|
||||
"rename\u{0}",
|
||||
"edit-item",
|
||||
"editItem",
|
||||
"Format",
|
||||
"port ",
|
||||
"\u{ff52}ename",
|
||||
"format\t",
|
||||
] {
|
||||
out.push((call(&format!("n{}", out.len()), json!(name), json!({})), -32602, refused(name)));
|
||||
}
|
||||
// A name that is not a string.
|
||||
let not_string = "tools/call params need a string `name`".to_string();
|
||||
for name in [json!(6), json!(["rename"]), json!({"name": "rename"}), json!(null), json!(true)] {
|
||||
out.push((call(&format!("t{}", out.len()), name, json!({})), -32602, not_string.clone()));
|
||||
}
|
||||
// An edit name with malformed or smuggled arguments.
|
||||
// The name is looked up before the arguments are read.
|
||||
for arguments in
|
||||
[json!(null), json!([]), json!("x"), json!({"name": 1}), json!({"mode": "full"})]
|
||||
{
|
||||
let line = call(&format!("a{}", out.len()), json!("rename"), arguments);
|
||||
out.push((line, -32602, refused("rename")));
|
||||
}
|
||||
let meta = request(
|
||||
"meta",
|
||||
"tools/call",
|
||||
json!({"name": "format", "arguments": {"files": "rtl"}, "_meta": {"mode": "full"}, "mode": "full"}),
|
||||
);
|
||||
out.push((meta, -32602, refused("format")));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_read_only_never_changes_a_byte_whatever_arrives() {
|
||||
let tree = Tree::of("edit");
|
||||
let before = snapshot(&tree);
|
||||
let mut lines = Vec::new();
|
||||
// Before `initialize`: refused as not initialized, never run.
|
||||
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
|
||||
lines.push(call(&format!("early{index}"), json!(name), arguments));
|
||||
}
|
||||
lines.push(initialize("init"));
|
||||
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
|
||||
// Every edit shape as a request and as a notification (no id).
|
||||
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
|
||||
lines.push(call(&format!("edit{index}"), json!(name), arguments.clone()));
|
||||
let params = json!({"name": name, "arguments": arguments});
|
||||
lines.push(json!({"jsonrpc": "2.0", "method": "tools/call", "params": params}));
|
||||
lines.push(
|
||||
json!({"jsonrpc": "2.0", "method": format!("notifications/{name}"), "params": params}),
|
||||
);
|
||||
}
|
||||
let hostile = hostile_calls();
|
||||
lines.extend(hostile.iter().map(|(line, _, _)| line.clone()));
|
||||
// A batch, a duplicate `name` key, a second `initialize` asking for more.
|
||||
lines.push(json!([call("batched", json!("format"), json!({"files": "rtl"}))]));
|
||||
lines.push(json!(r#"{"jsonrpc":"2.0","id":"dup","method":"tools/call","params":{"name":"check","name":"format","arguments":{"files":"rtl"}}}"#));
|
||||
lines.push(request(
|
||||
"reinit",
|
||||
"initialize",
|
||||
json!({"capabilities": {"experimental": {"mode": "full"}}}),
|
||||
));
|
||||
lines.push(call("after-reinit", json!("format"), json!({"files": "rtl"})));
|
||||
for uri in [
|
||||
"lucisv://overview",
|
||||
"lucisv://rules",
|
||||
"lucisv://unit/leaf",
|
||||
"lucisv://unit/spare",
|
||||
"lucisv://file/rtl/leaf.sv/outline",
|
||||
"lucisv://file/fmt%2Fmessy.sv/outline",
|
||||
"lucisv://format/fmt/messy.sv",
|
||||
"lucisv://unit/..%2F..%2Fetc",
|
||||
] {
|
||||
lines.push(request(&format!("res {uri}"), "resources/read", json!({"uri": uri})));
|
||||
}
|
||||
for method in ["notifications/cancelled", "notifications/roots/list_changed", "notifications/x"]
|
||||
{
|
||||
lines.push(json!({"jsonrpc": "2.0", "method": method, "params": {"requestId": "edit0"}}));
|
||||
}
|
||||
lines.push(call("still", json!("check"), json!({})));
|
||||
|
||||
let output = run(&["--root", tree.arg(), "--read-only"], &lines);
|
||||
assert!(output.status.success(), "{:?}", output.status);
|
||||
let answers = answers(&output);
|
||||
for index in 0..edit_shapes().len() {
|
||||
assert_eq!(answers[&format!("\"early{index}\"")]["error"]["code"], -32002);
|
||||
}
|
||||
for (index, (name, _)) in edit_shapes().into_iter().enumerate() {
|
||||
let reply = &answers[&format!("\"edit{index}\"")];
|
||||
assert_eq!(reply["error"]["code"], -32602, "{reply}");
|
||||
assert_eq!(reply["error"]["message"], refused(name), "{reply}");
|
||||
}
|
||||
for (line, code, message) in &hostile {
|
||||
let reply = &answers[&line["id"].to_string()];
|
||||
assert_eq!(reply["error"]["code"], *code, "{line} -> {reply}");
|
||||
assert_eq!(reply["error"]["message"], *message, "{line} -> {reply}");
|
||||
}
|
||||
assert_eq!(answers["null"]["error"]["code"], -32600, "the batch is refused");
|
||||
assert_eq!(answers["\"dup\""]["error"]["message"], refused("format"), "last key wins");
|
||||
assert_eq!(answers["\"after-reinit\""]["error"]["message"], refused("format"));
|
||||
assert_eq!(answers["\"still\""]["result"]["isError"], false);
|
||||
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
|
||||
}
|
||||
|
||||
/// The first `tools/list` answer's tool names for a server started with `args`.
|
||||
fn listed(args: &[&str]) -> (Option<Vec<String>>, Output) {
|
||||
let output = run(args, &[initialize("i"), request("l", "tools/list", json!({}))]);
|
||||
let names = answers(&output).get("\"l\"").map(|reply| {
|
||||
let tools = reply["result"]["tools"].as_array().unwrap();
|
||||
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
|
||||
});
|
||||
(names, output)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_argument_order_and_repetition_cannot_undo_read_only() {
|
||||
let tree = Tree::of("design");
|
||||
let root = tree.arg();
|
||||
let five = ["hierarchy", "find", "outline", "read", "check"].map(String::from).to_vec();
|
||||
for args in [
|
||||
vec!["--read-only", "--root", root],
|
||||
vec!["--root", root, "--read-only", "--read-only"],
|
||||
vec!["--read-only", "--verbose", "--root", root, "--read-only"],
|
||||
] {
|
||||
let (names, output) = listed(&args);
|
||||
assert_eq!(names.as_ref(), Some(&five), "{args:?}: {output:?}");
|
||||
}
|
||||
// A value for the flag is refused by the usage rule, never read as full.
|
||||
for args in [
|
||||
vec!["--root", root, "--read-only=false"],
|
||||
vec!["--root", root, "--read-only", "false"],
|
||||
vec!["--root", root, "--read-only=true"],
|
||||
vec!["--root", root, "--readonly"],
|
||||
vec!["--root", root, "--no-read-only"],
|
||||
] {
|
||||
let (names, output) = listed(&args);
|
||||
assert_eq!(names, None, "{args:?} started a server");
|
||||
assert_eq!(output.status.code(), Some(2), "{args:?}");
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(stderr.contains("unknown option") && stderr.contains("[--read-only]"), "{stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of every `tools/call` and `resources/read` answer, by id.
|
||||
fn texts(args: &[&str], lines: &[Value]) -> BTreeMap<String, String> {
|
||||
let mut session = vec![initialize("i")];
|
||||
session.extend_from_slice(lines);
|
||||
let output = run(args, &session);
|
||||
let mut out = BTreeMap::new();
|
||||
for (id, reply) in answers(&output) {
|
||||
let result = &reply["result"];
|
||||
let text = result["content"][0]["text"]
|
||||
.as_str()
|
||||
.or_else(|| result["contents"][0]["text"].as_str())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| reply.to_string());
|
||||
out.insert(id, text);
|
||||
}
|
||||
out.remove("\"i\"");
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_read_tools_and_resources_answer_identically_in_both_modes() {
|
||||
let reads = [
|
||||
("design", "hierarchy", json!({})),
|
||||
("design", "hierarchy", json!({"root": "top", "depth": 3, "peek": true})),
|
||||
("design", "find", json!({"name": "leaf", "refs": true})),
|
||||
("design", "outline", json!({"file": "rtl/top.sv"})),
|
||||
("design", "read", json!({"item": "top"})),
|
||||
("design", "check", json!({})),
|
||||
("design", "check", json!({"file": "rtl/broken.sv"})),
|
||||
("design", "find", json!({"nome": "x"})),
|
||||
("edit", "hierarchy", json!({"root": "leaf", "up": true})),
|
||||
("edit", "outline", json!({"unit": "spare"})),
|
||||
("edit", "check", json!({"file": "fmt/messy.sv"})),
|
||||
("edit", "read", json!({"item": "u_leaf", "file": "rtl/mid.sv"})),
|
||||
];
|
||||
for fixture in ["design", "edit"] {
|
||||
let tree = Tree::of(fixture);
|
||||
let mut lines: Vec<Value> = reads
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (f, _, _))| *f == fixture)
|
||||
.map(|(index, (_, name, arguments))| {
|
||||
call(&format!("r{index}"), json!(name), arguments.clone())
|
||||
})
|
||||
.collect();
|
||||
for uri in ["lucisv://overview", "lucisv://rules", "lucisv://unit/leaf", "lucisv://nope"] {
|
||||
lines.push(request(uri, "resources/read", json!({"uri": uri})));
|
||||
}
|
||||
for method in ["resources/list", "resources/templates/list", "prompts/list"] {
|
||||
lines.push(request(method, method, json!({})));
|
||||
}
|
||||
let full = texts(&["--root", tree.arg()], &lines);
|
||||
let read_only = texts(&["--root", tree.arg(), "--read-only"], &lines);
|
||||
assert_eq!(full.len(), lines.len(), "{fixture}: {full:?}");
|
||||
assert_eq!(full, read_only, "{fixture}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_read_only_index_cache_outside_the_root_leaves_the_root_alone() {
|
||||
// The store is written where it is told (the extension's workspace
|
||||
// storage); the root is not, even with the store beside it.
|
||||
let parent = Tree::empty();
|
||||
let root = parent.0.join("root");
|
||||
copy_tree(&Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/edit"), &root);
|
||||
let tree = Tree(root);
|
||||
let cache = parent.0.join("cache");
|
||||
let before = snapshot(&tree);
|
||||
let lines = [
|
||||
initialize("i"),
|
||||
call("c", json!("format"), json!({"files": "rtl"})),
|
||||
call("k", json!("check"), json!({})),
|
||||
];
|
||||
let output = run(
|
||||
&["--root", tree.arg(), "--index-cache", cache.to_str().unwrap(), "--read-only"],
|
||||
&lines,
|
||||
);
|
||||
assert!(output.status.success());
|
||||
assert_eq!(before, snapshot(&tree));
|
||||
assert!(cache.join(".gitignore").exists(), "the store directory was written");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Re-check 2026-09-29: `hierarchy`'s cap counts nodes, never peek lines.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `module name` with `count` instances of `child`, each written over 14
|
||||
/// lines (header, 12 port lines, closer), so each peek block is cut to 12
|
||||
/// lines and `…` — 14 answer lines per node.
|
||||
fn wide_parent(name: &str, child: &str, count: usize) -> (String, String) {
|
||||
let mut text = format!("module {name};\n");
|
||||
for i in 0..count {
|
||||
text.push_str(&format!(" {child} u_{i:03} (\n"));
|
||||
for p in 0..12 {
|
||||
let comma = if p < 11 { "," } else { "" };
|
||||
text.push_str(&format!(" .p{p}(1'b0){comma}\n"));
|
||||
}
|
||||
text.push_str(" );\n");
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
(format!("{name}.sv"), text)
|
||||
}
|
||||
|
||||
/// A 12-input leaf module.
|
||||
fn leaf(name: &str) -> (String, String) {
|
||||
let ports: Vec<String> = (0..12).map(|p| format!("input logic p{p}")).collect();
|
||||
(format!("{name}.sv"), format!("module {name} ({});\nendmodule\n", ports.join(", ")))
|
||||
}
|
||||
|
||||
/// `dN` declares N instances (N + 1 nodes with its root line); `uN` is
|
||||
/// instantiated N times (N nodes up). Sizes sit on both caps' boundaries:
|
||||
/// 300/301 nodes without `peek`, 100/101 with it.
|
||||
fn boundary_tree() -> Tree {
|
||||
let tree = Tree::empty();
|
||||
let files = [
|
||||
leaf("x"),
|
||||
leaf("y"),
|
||||
leaf("u100"),
|
||||
leaf("u101"),
|
||||
leaf("u300"),
|
||||
leaf("u301"),
|
||||
wide_parent("d99", "x", 99),
|
||||
wide_parent("d100", "y", 100),
|
||||
wide_parent("d299", "x", 299),
|
||||
wide_parent("d300", "y", 300),
|
||||
wide_parent("h100", "u100", 100),
|
||||
wide_parent("h101", "u101", 101),
|
||||
wide_parent("h300", "u300", 300),
|
||||
wide_parent("h301", "u301", 301),
|
||||
];
|
||||
for (path, text) in files {
|
||||
fs::write(tree.0.join(path), text).unwrap();
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
/// Each call's text, in order, from one session in `mode_args`.
|
||||
fn hierarchy_texts(tree: &Tree, calls: &[Value], mode_args: &[&str]) -> Vec<String> {
|
||||
let mut args = vec!["--root", tree.arg()];
|
||||
args.extend_from_slice(mode_args);
|
||||
let mut lines = vec![initialize("i")];
|
||||
lines.extend(
|
||||
calls
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(n, a)| call(&format!("h{n}"), json!("hierarchy"), a.clone())),
|
||||
);
|
||||
let answers = answers(&run(&args, &lines));
|
||||
(0..calls.len())
|
||||
.map(|n| {
|
||||
let reply = &answers[&format!("\"h{n}\"")];
|
||||
assert_eq!(reply["result"]["isError"], false, "{reply}");
|
||||
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The node cap without `peek` (PLAN §10.1).
|
||||
const PLAIN_CAP: usize = 300;
|
||||
/// The node cap with `peek` (M8 rework 3).
|
||||
const PEEK_CAP: usize = 100;
|
||||
|
||||
#[test]
|
||||
fn qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek() {
|
||||
let tree = boundary_tree();
|
||||
// (arguments, nodes in the whole answer, statement indent)
|
||||
let cases = [
|
||||
(json!({"root": "d99"}), 100, " "),
|
||||
(json!({"root": "d100"}), 101, " "),
|
||||
(json!({"root": "d299"}), 300, " "),
|
||||
(json!({"root": "d300"}), 301, " "),
|
||||
(json!({"root": "u100", "up": true}), 100, " "),
|
||||
(json!({"root": "u101", "up": true}), 101, " "),
|
||||
(json!({"root": "u300", "up": true}), 300, " "),
|
||||
(json!({"root": "u301", "up": true}), 301, " "),
|
||||
];
|
||||
let mut calls = Vec::new();
|
||||
for (arguments, _, _) in &cases {
|
||||
calls.push(arguments.clone());
|
||||
let mut peeked = arguments.clone();
|
||||
peeked["peek"] = json!(true);
|
||||
calls.push(peeked);
|
||||
}
|
||||
let full = hierarchy_texts(&tree, &calls, &[]);
|
||||
assert_eq!(full, hierarchy_texts(&tree, &calls, &["--read-only"]), "the modes disagree");
|
||||
for (at, (arguments, total, indent)) in cases.iter().enumerate() {
|
||||
let root_lines = usize::from(arguments["up"] != true);
|
||||
let cut_line = |cap: usize| (*total > cap).then(|| format!("… and {} more", total - cap));
|
||||
// Without peek: one line per node, at most 300, then the cut line.
|
||||
let plain: Vec<&str> = full[2 * at].lines().collect();
|
||||
let (plain_shown, plain_cut) = ((*total).min(PLAIN_CAP), cut_line(PLAIN_CAP));
|
||||
assert_eq!(plain.len(), plain_shown + usize::from(plain_cut.is_some()), "{arguments}");
|
||||
if let Some(cut) = &plain_cut {
|
||||
assert_eq!(plain.last().copied(), Some(cut.as_str()), "{arguments}");
|
||||
}
|
||||
// With peek: the first 100 of the same node lines, then its own cut line.
|
||||
let peek: Vec<&str> = full[2 * at + 1].lines().collect();
|
||||
let (shown, cut) = ((*total).min(PEEK_CAP), cut_line(PEEK_CAP));
|
||||
let nodes: Vec<&str> = peek.iter().copied().filter(|l| !l.starts_with(indent)).collect();
|
||||
let mut expected: Vec<&str> = plain[..shown].to_vec();
|
||||
if let Some(cut) = &cut {
|
||||
expected.push(cut.as_str());
|
||||
}
|
||||
assert_eq!(nodes, expected, "{arguments}");
|
||||
// Every instance node is followed by a whole block: 12 lines, then `…`.
|
||||
let instances = shown - root_lines;
|
||||
let cut_lines = usize::from(cut.is_some());
|
||||
assert_eq!(peek.len(), root_lines + instances * 14 + cut_lines, "{arguments}");
|
||||
let blocks = peek.iter().filter(|l| l.trim() == "…").count();
|
||||
assert_eq!(blocks, instances, "{arguments}");
|
||||
if cut.is_some() {
|
||||
// The block before the cut line is whole: it ends in `…`.
|
||||
assert_eq!(peek[peek.len() - 2].trim(), "…", "{arguments}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! `lucisv-mcp --read-only` (PLAN §11), pinned against the real binary: the
|
||||
//! five read tools within their budget, the edit tools unknown, full mode as
|
||||
//! 0.58.0 shipped it, and the promise that nothing inside a root is created,
|
||||
//! written, renamed or removed whatever is called.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// How long one answer may take before the test calls the server hung.
|
||||
const ANSWER_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// The five read tools, in the order `tools/list` gives them.
|
||||
const FIVE: [&str; 5] = ["hierarchy", "find", "outline", "read", "check"];
|
||||
|
||||
/// The four edit tools full mode adds after them.
|
||||
const EDITS: [&str; 4] = ["rename", "port", "edit_item", "format"];
|
||||
|
||||
/// The read-only ceilings (PLAN §11.1).
|
||||
const CATALOGUE_BUDGET: usize = 1_800;
|
||||
const INSTRUCTIONS_BUDGET: usize = 300;
|
||||
|
||||
/// The instructions 0.58.0 shipped (PLAN §10.3), which full mode keeps.
|
||||
const FULL_INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A fresh directory under the system temp dir, removed on drop.
|
||||
struct Tree(PathBuf);
|
||||
|
||||
impl Tree {
|
||||
fn empty() -> Tree {
|
||||
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
|
||||
let dir = std::env::temp_dir()
|
||||
.join(format!("lucisv-mcp-read-only-{}-{unique}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
Tree(fs::canonicalize(dir).unwrap())
|
||||
}
|
||||
|
||||
/// A fresh copy of `tests/fixtures/<fixture>`.
|
||||
fn of(fixture: &str) -> Tree {
|
||||
let tree = Tree::empty();
|
||||
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
|
||||
copy_tree(&source, &tree.0);
|
||||
tree
|
||||
}
|
||||
|
||||
fn arg(&self) -> &str {
|
||||
self.0.to_str().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) {
|
||||
fs::create_dir_all(to).unwrap();
|
||||
for entry in fs::read_dir(from).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let target = to.join(entry.file_name());
|
||||
if entry.file_type().unwrap().is_dir() {
|
||||
copy_tree(&entry.path(), &target);
|
||||
} else {
|
||||
fs::copy(entry.path(), target).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One running server.
|
||||
struct Session {
|
||||
child: Child,
|
||||
stdin: Option<ChildStdin>,
|
||||
lines: Receiver<String>,
|
||||
next_id: i64,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn spawn(args: &[&str]) -> Session {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let (send, lines) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if send.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let stdin = child.stdin.take();
|
||||
Session { child, stdin, lines, next_id: 0 }
|
||||
}
|
||||
|
||||
/// A server over `tree`, in read-only mode unless `full`, initialised;
|
||||
/// returns the `initialize` result too.
|
||||
fn over(tree: &Tree, full: bool) -> (Session, Value) {
|
||||
let mut args = vec!["--root", tree.arg()];
|
||||
if !full {
|
||||
args.push("--read-only");
|
||||
}
|
||||
let mut server = Session::spawn(&args);
|
||||
let init = server.initialize();
|
||||
(server, init)
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
|
||||
let stdin = self.stdin.as_mut().unwrap();
|
||||
writeln!(stdin, "{line}").unwrap();
|
||||
stdin.flush().unwrap();
|
||||
let reply = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
|
||||
let reply: Value = serde_json::from_str(&reply).expect("every stdout line is JSON");
|
||||
assert_eq!(reply["id"], id, "answers come back in order");
|
||||
reply
|
||||
}
|
||||
|
||||
fn initialize(&mut self) -> Value {
|
||||
let params = json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "read-only", "version": "0"}});
|
||||
self.request("initialize", params)["result"].clone()
|
||||
}
|
||||
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> Value {
|
||||
self.request("tools/call", json!({"name": tool, "arguments": arguments}))
|
||||
}
|
||||
|
||||
/// Close stdin and wait for the server to exit (it writes its own index
|
||||
/// store, when it has one, on the way out).
|
||||
fn finish(mut self) {
|
||||
drop(self.stdin.take());
|
||||
let status = self.child.wait().unwrap();
|
||||
assert!(status.success(), "{status}");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// The tools a `tools/list` answer offers.
|
||||
fn tools(server: &mut Session) -> Vec<Value> {
|
||||
server.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().clone()
|
||||
}
|
||||
|
||||
fn names(tools: &[Value]) -> Vec<String> {
|
||||
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
/// What the model reads every session: name, description and schema of
|
||||
/// every tool, compact JSON — the measure `wire.rs` budgets full mode by.
|
||||
fn visible_bytes(tools: &[Value]) -> usize {
|
||||
let visible: Vec<Value> = tools
|
||||
.iter()
|
||||
.map(|t| json!({"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]}))
|
||||
.collect();
|
||||
serde_json::to_string(&visible).unwrap().len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_offers_the_five_read_tools_in_order_within_both_budgets() {
|
||||
let tree = Tree::of("design");
|
||||
let (mut server, init) = Session::over(&tree, false);
|
||||
let instructions = init["instructions"].as_str().unwrap();
|
||||
assert!(instructions.len() <= INSTRUCTIONS_BUDGET, "instructions: {}", instructions.len());
|
||||
assert!(instructions.contains("it never edits"), "{instructions}");
|
||||
for name in FIVE {
|
||||
assert!(instructions.contains(name), "{name}: {instructions}");
|
||||
}
|
||||
let words: Vec<&str> = instructions.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
|
||||
for name in EDITS {
|
||||
assert!(!words.contains(&name), "{name}: {instructions}");
|
||||
}
|
||||
let offered = tools(&mut server);
|
||||
assert_eq!(names(&offered), FIVE);
|
||||
let bytes = visible_bytes(&offered);
|
||||
assert!(bytes <= CATALOGUE_BUDGET, "the read-only catalogue is {bytes} bytes");
|
||||
for tool in &offered {
|
||||
assert_eq!(tool["annotations"]["readOnlyHint"], true, "{tool}");
|
||||
}
|
||||
// The same five, word for word and schema for schema, as full mode's.
|
||||
let (mut full, _) = Session::over(&tree, true);
|
||||
assert_eq!(offered[..], tools(&mut full)[..5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_tool_in_read_only_mode_is_an_unknown_tool() {
|
||||
let tree = Tree::of("edit");
|
||||
let (mut server, _) = Session::over(&tree, false);
|
||||
for (name, arguments) in edit_calls() {
|
||||
let reply = server.call(name, arguments);
|
||||
assert!(reply.get("result").is_none(), "{name}: {reply}");
|
||||
assert_eq!(reply["error"]["code"], -32602, "{name}: {reply}");
|
||||
assert_eq!(
|
||||
reply["error"]["message"],
|
||||
format!("unknown tool: {name} (the server runs --read-only)")
|
||||
);
|
||||
}
|
||||
// A read tool still answers after the refusals.
|
||||
let reply = server.call("check", json!({"file": "rtl/leaf.sv"}));
|
||||
assert_eq!(reply["result"]["isError"], false, "{reply}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_mode_is_the_nine_tools_and_the_058_instructions() {
|
||||
let tree = Tree::of("design");
|
||||
let (mut server, init) = Session::over(&tree, true);
|
||||
assert_eq!(init["instructions"], FULL_INSTRUCTIONS);
|
||||
let offered = tools(&mut server);
|
||||
let expected: Vec<&str> = FIVE.iter().chain(EDITS.iter()).copied().collect();
|
||||
assert_eq!(names(&offered), expected);
|
||||
let reply = server.call("nope", json!({}));
|
||||
assert_eq!(reply["error"]["message"], "unknown tool: nope");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The promise: nothing inside a root changes, whatever is called.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A valid edit for each edit tool on the `edit` fixture — each one writes
|
||||
/// in full mode (`the_edit_calls_write_in_full_mode`).
|
||||
fn edit_calls() -> Vec<(&'static str, Value)> {
|
||||
vec![
|
||||
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
|
||||
("port", json!({"module": "spare", "add": "input logic en"})),
|
||||
(
|
||||
"edit_item",
|
||||
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_w;"}),
|
||||
),
|
||||
("format", json!({"files": "fmt/messy.sv", "fix": true})),
|
||||
]
|
||||
}
|
||||
|
||||
/// A plausible call of each read tool on the `edit` fixture.
|
||||
fn read_calls() -> Vec<(&'static str, Value)> {
|
||||
vec![
|
||||
("hierarchy", json!({})),
|
||||
("hierarchy", json!({"root": "top", "depth": 5, "peek": true})),
|
||||
("hierarchy", json!({"root": "leaf", "up": true})),
|
||||
("find", json!({"name": "d", "refs": true})),
|
||||
("outline", json!({"file": "rtl/leaf.sv"})),
|
||||
("outline", json!({"unit": "leaf"})),
|
||||
("read", json!({"item": "leaf"})),
|
||||
("check", json!({})),
|
||||
("check", json!({"file": "fmt/messy.sv"})),
|
||||
]
|
||||
}
|
||||
|
||||
/// Every entry under a tree, root-relative: a file's size and mtime, a
|
||||
/// directory's mtime (which moves when an entry is created, renamed or
|
||||
/// removed in it, even a temporary one).
|
||||
fn snapshot(tree: &Tree) -> BTreeMap<String, (Option<u64>, SystemTime)> {
|
||||
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, (Option<u64>, SystemTime)>) {
|
||||
let meta = fs::metadata(dir).unwrap();
|
||||
let relative = dir.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
|
||||
out.insert(format!("{relative}/"), (None, meta.modified().unwrap()));
|
||||
for entry in fs::read_dir(dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
walk(&path, root, out);
|
||||
} else {
|
||||
let meta = fs::metadata(&path).unwrap();
|
||||
let relative =
|
||||
path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
|
||||
out.insert(relative, (Some(meta.len()), meta.modified().unwrap()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
walk(&tree.0, &tree.0, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_mode_never_touches_the_tree_whatever_is_called() {
|
||||
let tree = Tree::of("edit");
|
||||
let cache = Tree::empty();
|
||||
let before = snapshot(&tree);
|
||||
let args = ["--root", tree.arg(), "--index-cache", cache.arg(), "--read-only"];
|
||||
let mut server = Session::spawn(&args);
|
||||
server.initialize();
|
||||
for (name, arguments) in read_calls().into_iter().chain(edit_calls()) {
|
||||
let reply = server.call(name, arguments);
|
||||
assert!(reply.get("result").is_some() || reply.get("error").is_some(), "{reply}");
|
||||
}
|
||||
// Every name again with no arguments, and with arguments it does not take.
|
||||
for name in FIVE.iter().chain(EDITS.iter()) {
|
||||
server.call(name, json!({}));
|
||||
server.call(name, json!({"force": true, "dry_run": false}));
|
||||
}
|
||||
for method in ["resources/list", "resources/templates/list"] {
|
||||
assert!(server.request(method, json!({})).get("result").is_some(), "{method}");
|
||||
}
|
||||
for uri in [
|
||||
"lucisv://overview",
|
||||
"lucisv://rules",
|
||||
"lucisv://unit/leaf",
|
||||
"lucisv://file/rtl/leaf.sv/outline",
|
||||
] {
|
||||
let reply = server.request("resources/read", json!({"uri": uri}));
|
||||
assert!(reply.get("result").is_some(), "{uri}: {reply}");
|
||||
}
|
||||
server.finish();
|
||||
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
|
||||
// The server's own store is outside the roots, and still written.
|
||||
assert!(fs::read_dir(&cache.0).unwrap().next().is_some(), "no index store was written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_edit_calls_write_in_full_mode() {
|
||||
// The control for the promise above: the same arguments are real edits.
|
||||
for (name, arguments) in edit_calls() {
|
||||
let tree = Tree::of("edit");
|
||||
let before = snapshot(&tree);
|
||||
let (mut server, _) = Session::over(&tree, true);
|
||||
let reply = server.call(name, arguments);
|
||||
assert_eq!(reply["result"]["isError"], false, "{name}: {reply}");
|
||||
server.finish();
|
||||
assert_ne!(before, snapshot(&tree), "{name} wrote nothing in full mode");
|
||||
}
|
||||
}
|
||||
@@ -76,8 +76,10 @@ Decisions where PLAN §10 is silent (the simplest thing, recorded):
|
||||
module to the end of the line holding its `;`, the common indentation
|
||||
removed, indented four spaces past the node's line, at most 12 lines then
|
||||
`…`. Nothing is shown when the file no longer spells the module there.
|
||||
- The 300-line cap cuts whole nodes (a node's peek block is never split);
|
||||
`… and N more` counts the nodes left. The 50 000-node walk cap stays, so
|
||||
- The cap is 300 nodes (instance lines, a root line included) without
|
||||
`peek` and 100 nodes with it, down and up alike; `peek` lines never count
|
||||
toward it, and a peek block is never split. `… and N more` counts the nodes not shown. (Was a 300-*line* cap
|
||||
until 2026-09-29, which with `peek` showed as few as 23 instances.) The 50 000-node walk cap stays, so
|
||||
on a cut walk `N` is a lower bound.
|
||||
- Unknown root: up to 10 module/interface names containing it, any case.
|
||||
|
||||
@@ -348,6 +350,32 @@ for `down`. `verify.rs` lost its dead forced path.
|
||||
exact; the pinned test stays ignored with its reason. **R3:** no change.
|
||||
- Catalogue 3 440 bytes, instructions 398 (unchanged).
|
||||
|
||||
### 2026-09-29 — dev (M8 rework 2: the hierarchy cap counts instances)
|
||||
|
||||
- Census round 5 found `hierarchy {"root":"prim_fifo_sync","up":true,
|
||||
"peek":true}` on the OpenTitan clone cut to 20 of 77 instantiations by
|
||||
the 300-line cap. Lead ruling: the cap counts nodes, never peek lines.
|
||||
`hierarchy.rs` `render_nodes` now stops at the 300th node; without
|
||||
`peek` the answer is byte-identical (one line per node). `qa_m7.rs`'s
|
||||
caps test updated (root + 400 with peek: 599 lines shown, `… and 101
|
||||
more`); new `tests/hierarchy_cap.rs` (30 fourteen-line instantiations,
|
||||
up + peek: all 30; 350 instantiations with peek: 300 shown, `… and 50
|
||||
more` up, `… and 51 more` down). Descriptions and byte budgets unchanged.
|
||||
PLAN §10.1's row amended.
|
||||
|
||||
### 2026-09-29 — dev (M8 rework 3: 100 instances with peek)
|
||||
|
||||
- QA finding 6 (M8): with the node cap alone a peeked answer reached
|
||||
150 kB (`top_earlgrey` depth 3, 3 759 lines). Lead ruling: 300 nodes
|
||||
without `peek`, 100 with it (`CAP`, `PEEK_CAP` in `hierarchy.rs`);
|
||||
everything else from rework 2 stands. Tests: `hierarchy_cap.rs` (350
|
||||
instantiations with peek: 100 shown, `… and 250 more` up, `… and 251
|
||||
more` down; without peek 300 and 50/51), `qa_m7.rs` caps test (root +
|
||||
400 with peek: 199 lines, then `… and 301 more`), QA's
|
||||
`qa_m8.rs` boundary test renamed
|
||||
`qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek`
|
||||
with 100/101-node fixtures added. PLAN §10.1's row amended again.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-24 — QA (M7)
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
# mcp-read-only
|
||||
|
||||
Lane **M8** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §11).
|
||||
|
||||
## Goal
|
||||
|
||||
One binary, two modes. `lucisv-mcp --read-only` offers only the five read
|
||||
tools (`hierarchy`, `find`, `outline`, `read`, `check`) and shorter
|
||||
instructions, so an agent that only needs to *understand* a design reads a
|
||||
catalogue half the size and talks to a server that cannot change it: no file
|
||||
inside a root is created, written, renamed or removed, whatever is called.
|
||||
Without the flag nothing changes — full mode is byte-identical to 0.58.0 on
|
||||
the wire. The VS Code extension chooses the mode by a setting
|
||||
(`lucisv.mcp.mode`), and its copy-config command keys a read-only server
|
||||
`lucisv-ro` so a host can carry both side by side.
|
||||
|
||||
## Assumptions
|
||||
|
||||
Where §11 is silent, the simplest thing, recorded:
|
||||
|
||||
- **The mode is a registry filter.** `tools::Mode { Full, ReadOnly }` lives
|
||||
in `tools/mod.rs`; `Mode::offers(Effect)` admits `Read` tools in read-only
|
||||
mode and every tool in full mode. `tools::list(mode)` and
|
||||
`tools::find(name, mode)` both go through the one filter, so the listed
|
||||
set and the callable set cannot disagree. No handler checks the mode.
|
||||
- **`Options.mode`** carries the mode (default `Full`); `--read-only` sets
|
||||
it. The flag takes no value and may be repeated harmlessly.
|
||||
- **Resources** run their read tools through `tools::find(name,
|
||||
Mode::ReadOnly)` — the strictest registry that has them — so a resource
|
||||
can never reach an edit tool in either mode and answers the same in both.
|
||||
- **The unknown-tool message** carries the ` (the server runs --read-only)`
|
||||
suffix for *any* unknown name in read-only mode, not only the four edit
|
||||
names: the sentence is true either way and the rule is one line. Full mode
|
||||
keeps `unknown tool: NAME` exactly.
|
||||
- **`check`'s description is shared.** The shipped description ("Parse
|
||||
errors and lint findings of `file` or the whole design, …") never said
|
||||
"after edits" — only the full-mode *instructions* do — so it reads right
|
||||
in both modes and there is one description (§11.1 allows this). The read
|
||||
tools' descriptions, schemas and annotations are identical in both modes
|
||||
(pinned by test).
|
||||
- **The instructions text deviates from §11.1 by one phrase.** The quoted
|
||||
text is 302 bytes, over its own 300-byte budget; "check for diagnostics"
|
||||
became "check for issues" (297 bytes). Nothing else changed.
|
||||
- **The promise covers the roots.** The index store under `--index-cache`
|
||||
is still written on exit. The extension passes VS Code's workspace
|
||||
storage, which is outside the folder. A user who points `--index-cache`
|
||||
at a directory *inside* a root gets that directory written (the store,
|
||||
its `.gitignore`); that is the user's own choice of store location, not a
|
||||
tool call, and is not guarded against.
|
||||
- **Extension:** only an unset `lucisv.mcp.mode` or exactly `"full"` is
|
||||
full mode; exactly `"read-only"` is read-only, and any other value fails
|
||||
safe to read-only with one line in the lucisv output channel (lead
|
||||
ruling on QA finding 2; was: anything but `"read-only"` is full). The change event already fires for every `lucisv.mcp.*`
|
||||
change (`affectsConfiguration('lucisv.mcp')`), so the mode needed no new
|
||||
listener — only a test. `--read-only` is appended *last* in the
|
||||
definition's args (after `--index-cache`) and in the snippet's args. The
|
||||
copy-config message names the mode in both modes (`(full mode)` /
|
||||
`(read-only mode)`), a wording change for full mode too.
|
||||
- **`mcp_smoke.js --read-only`** additionally checks the tiny project's two
|
||||
files are byte-identical after the session; with `--tool-table` it prints
|
||||
whatever the mode lists (the full-mode table is unchanged, compared
|
||||
byte for byte against the 0.58.0 script).
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** from the tool registry (M7): the `Effect` per tool in
|
||||
`TOOLS`. A new tool must be given the right `Effect` — an `Edit` tool
|
||||
marked `Read` would be offered in read-only mode. The five-name tests in
|
||||
`tools/mod.rs` and `tests/read_only.rs` pin the current set.
|
||||
- **Promises** to hosts: `--read-only` → exactly `hierarchy, find, outline,
|
||||
read, check` in that order, catalogue ≤ 1 800 model-visible bytes (1 797
|
||||
shipped), instructions ≤ 300 (297 shipped); `tools/call` of an edit name
|
||||
→ JSON-RPC `-32602` `unknown tool: NAME (the server runs --read-only)`;
|
||||
no write inside a root. Full mode: `initialize` and `tools/list`
|
||||
byte-identical to 0.58.0 (checked against the 0.58.0 release binary; the
|
||||
full catalogue stays 3 440 bytes, instructions 398).
|
||||
- **Promises** to the extension's users and to `release.sh`: setting
|
||||
`lucisv.mcp.mode` (`"full"` / `"read-only"`), label `lucisv read-only
|
||||
(<folder>)`, args `[…, "--read-only"]`, copy-config key `lucisv-ro`;
|
||||
`mcp_smoke.js <binary> --read-only` as the second MCP gate at both
|
||||
`release.sh` sites. Recorded in `docs/topo.md` §2.8.
|
||||
- **Requests:** none. Every file touched is on the lane's list.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] server: `--read-only` parsed and in the usage line; `Mode` filters
|
||||
the registry (`tools/list`, `tools/call`); read-only instructions;
|
||||
the unknown-tool message
|
||||
- [x] tests: `tests/read_only.rs` (names and order, both budgets, the five
|
||||
identical to full mode's, the four edit names unknown, full mode's
|
||||
nine names and 0.58.0 instructions, the no-write snapshot with every
|
||||
tool name and every resource, the full-mode control that the edit
|
||||
arguments do write); unit tests in `tools/mod.rs`, `rpc.rs`,
|
||||
`main.rs`
|
||||
- [x] extension: `lucisv.mcp.mode` in `package.json`; `mcp.js` args,
|
||||
label, copy-config key/args/message; `mcp_test.js`
|
||||
- [x] `mcp_smoke.js --read-only`; `tools/release.sh` runs both smokes at
|
||||
both sites; `tools/RELEASING.md`
|
||||
- [x] docs: Agents guide "Read-only mode" section, settings table and
|
||||
arguments line; extension README and CHANGELOG; `CHANGELOG.md`
|
||||
0.59.0 (unreleased); `docs/topo.md` §2.8; manual-acceptance rows
|
||||
26–27
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-29 — dev (Opus)
|
||||
|
||||
- Captured the 0.58.0 wire (`initialize` + `tools/list` over
|
||||
`tests/fixtures/design`) from a release build of HEAD before any change;
|
||||
after the change the full-mode output is `cmp`-identical to it.
|
||||
- `tools/mod.rs`: `Mode`, `Mode::offers`, `offered(mode)`; `list` and
|
||||
`find` take the mode. `rpc.rs`: `INSTRUCTIONS_READ_ONLY`,
|
||||
`instructions(mode)`, `unknown_tool(name, mode)`. `main.rs`:
|
||||
`Options.mode`, `--read-only`, the usage line. `resources.rs`: reads
|
||||
through `Mode::ReadOnly`.
|
||||
- Deviation: §11.1's instructions text measured 302 bytes against its own
|
||||
≤ 300 budget; "check for diagnostics" → "check for issues" (297).
|
||||
- Figures (release build): read-only catalogue 1 797 bytes, instructions
|
||||
297; full catalogue 3 440, instructions 398 (unchanged). The read-only
|
||||
catalogue is 3 bytes under its ceiling: any growth of the five read
|
||||
tools' descriptions or schemas now needs a trim elsewhere.
|
||||
- `tests/read_only.rs` copies the small `Tree`/`Session` helpers from
|
||||
`wire.rs` rather than sharing them (brief). The no-write test snapshots
|
||||
path → (size, mtime) for files and mtime for directories (so a temp file
|
||||
created and removed is caught), runs with `--index-cache` outside the
|
||||
tree, closes stdin and waits for exit before the second snapshot, and
|
||||
asserts the cache directory did get the store.
|
||||
- Extension: setting, provider args/label, copy-config snippet key and
|
||||
message; `mcp_smoke.js --read-only` (five tools, `hierarchy`, `rename`
|
||||
→ the exact `-32602` error, files untouched). Against the 0.58.0 binary
|
||||
`--read-only` fails as it should (`unknown option`).
|
||||
- Gates: `cargo fmt --all`; `cargo clippy --all-targets -- -D warnings`
|
||||
clean (guard exit 0); `cargo test -p lucisv_mcp` 14 suites, 373 passed,
|
||||
0 failed, 4 ignored (guard exit 0); `node --test editors/vscode/*_test.js`
|
||||
6/6; `mcp_smoke.js target/release/lucisv-mcp` OK in both modes.
|
||||
|
||||
### 2026-09-29 — dev (Opus), QA rework
|
||||
|
||||
- QA finding 2 (lead ruling 1): `mcp.js` `readOnlyMode(log)` — unset or
|
||||
exactly `"full"` → full; exactly `"read-only"` → read-only; anything else
|
||||
(`"Read-Only"`, `"readonly"`, `"Full"`, `null`, `true`, a number) →
|
||||
read-only plus one line, `lucisv: lucisv.mcp.mode is "<value>", not
|
||||
"full" or "read-only"; using read-only.`, through `activate`'s `log`
|
||||
(now passed to `serverDefinitions` and `copyConfig`, which share the
|
||||
rule). `mcp_test.js` `anUnknownModeFailsSafeToReadOnly` covers the three
|
||||
cases and the line; `theReadOnlySnippets` covers copy-config with
|
||||
`"readonly"`. One clause ("any other value is treated as read-only") in
|
||||
the `package.json` description, the extension README settings table and
|
||||
the Agents guide settings table.
|
||||
- QA finding 4 (lead ruling 2): `mcp_smoke.js --read-only` now checks the
|
||||
tool list (count and names) before the `rename` refusal; against a
|
||||
wrapper that drops `--read-only` it fails with `tools/list is 9 tools
|
||||
[…], expected 5 […]`.
|
||||
- No Rust changed. `node --test editors/vscode/*_test.js` 6/6; both smokes
|
||||
OK against `target/release/lucisv-mcp`.
|
||||
|
||||
### 2026-09-29 — dev (Opus), rework 2
|
||||
|
||||
- The `hierarchy` cap now counts instances, not peek lines (census round
|
||||
5 finding on `prim_fifo_sync` up + peek). The change and its tests are
|
||||
logged in `docs/features/mcp-lean-catalogue/README.md` (work log,
|
||||
2026-09-29); tool descriptions and both modes' byte figures unchanged.
|
||||
|
||||
### 2026-09-29 — dev (Opus), rework 3
|
||||
|
||||
- QA finding 6: the `hierarchy` cap is 300 instances without `peek`, 100
|
||||
with it (lead ruling). Logged in the M7 README (work log, rework 3).
|
||||
QA's boundary test in `qa_m8.rs` is renamed
|
||||
`qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek`
|
||||
(the QA log below still names it by its old name). Descriptions and both
|
||||
modes' byte figures unchanged.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-29 — QA (Opus)
|
||||
|
||||
**Verdict: PASS with findings** (two low, three informational; no
|
||||
corruption, no write, no reachable edit handler).
|
||||
|
||||
What was verified, and how:
|
||||
|
||||
- **No-write promise, fixture.** `tests/qa_m8.rs`
|
||||
`qa_read_only_never_changes_a_byte_whatever_arrives`: snapshot of every
|
||||
entry under a copy of `fixtures/edit` (file size + mtime + **bytes**,
|
||||
directory mtime so a temp file created and removed is caught), then one
|
||||
session with: 13 edit shapes (rename ×2, port add / add-after / remove,
|
||||
edit_item replace / insert_before / insert_after / delete, format with and
|
||||
without `fix`, `**/*.sv`, `rtl`) sent before `initialize` (all `-32002`),
|
||||
after it as requests (all `-32602` with the exact message), as
|
||||
notifications (`tools/call` with no id) and as `notifications/<name>`;
|
||||
12 near-miss names (`Rename`, `" rename"`, `"rename "`, `rename\n`,
|
||||
`rename\0`, `edit-item`, `editItem`, fullwidth `rename`, `format\t`, …);
|
||||
`name` as number / array / object / null / bool (`-32602` "need a string
|
||||
`name`"); edit names with null / array / string / smuggled `mode` arguments
|
||||
and a `_meta`/`mode` in params; a batch array (`-32600`); a duplicate
|
||||
`name` key (`check` then `format`: last key wins → refused); a second
|
||||
`initialize` asking for `experimental.mode: full` followed by `format`
|
||||
(still refused); eight resource URIs (the four real ones plus
|
||||
`lucisv://format/…`, `lucisv://unit/..%2F..%2Fetc`); three stray
|
||||
notifications. Snapshot identical after exit. Control
|
||||
`qa_every_edit_shape_writes_in_full_mode`: each of the 13 shapes writes in
|
||||
full mode. Mutation `Mode::offers` → `(Mode::ReadOnly, _)`: three QA tests
|
||||
fail; reverted, `cmp`-identical.
|
||||
- **No-write promise, opentitan** (`~/.cache/lucisv-eval/ot/hw`, release
|
||||
binary, `--read-only`, no `--index-cache`): `format **/*.sv fix` before
|
||||
`initialize`, then rename `uart_rx`, port add/remove on `uart_rx`,
|
||||
edit_item insert/delete in `ip/uart/rtl/uart_rx.sv`, format `**/*.sv`
|
||||
and `ip/uart/rtl`, `Format `, a notification-form format, the five reads
|
||||
and three resources (3 944 files indexed). Every edit answered `-32602`;
|
||||
`git status --short` empty before and after, `--ignored` set unchanged,
|
||||
no file newer than the run outside `.git`. `/Users/…/repo/opentitan`
|
||||
not touched.
|
||||
- **Reachability.** `tools::find` is the only way from a name to a handler;
|
||||
callers: `rpc.rs:247` (`self.options.mode`) and `resources.rs:116`
|
||||
(`Mode::ReadOnly`, and only `hierarchy`/`outline` are named). No cached
|
||||
`Tool` reference; `apply::run` is called only from `edit.rs`, `format.rs`,
|
||||
`item.rs` (and `port` through them). `Options` is built only by
|
||||
`Options::default()` in `parse_args` (`main.rs:82`) and in `rpc.rs`'s unit
|
||||
tests; `Server.options` is never reassigned.
|
||||
- **Arguments** (`qa_argument_order_and_repetition_cannot_undo_read_only`):
|
||||
flag first, last, repeated, mixed with `--verbose` → five tools;
|
||||
`--read-only=false`, `--read-only false`, `--read-only=true`,
|
||||
`--readonly`, `--no-read-only` → exit 2, `unknown option`, usage line
|
||||
naming `[--read-only]`, no server.
|
||||
- **Budgets, recomputed in Python** from the wire (compact JSON of name +
|
||||
description + inputSchema): read-only 1 797 bytes, 5 tools, all
|
||||
`readOnlyHint: true`, instructions 297; full 3 440, instructions 398. Sum
|
||||
of name + description + schema alone: 1 576 / 3 043. Mutation: 4 bytes
|
||||
appended to `hierarchy`'s description → `read_only.rs` fails ("the
|
||||
read-only catalogue is 1801 bytes"); reverted, `cmp`-identical.
|
||||
- **Full-mode identity.** `initialize` + `notifications/initialized` +
|
||||
`tools/list` + `resources/list` + `resources/templates/list` + an unknown
|
||||
tool, over `fixtures/design`: current release binary vs
|
||||
`~/.cache/lucisv-eval/bin/lucisv-mcp-r5` — identical except
|
||||
`serverInfo.version` (finding 3).
|
||||
- **Read answers across modes**
|
||||
(`qa_the_read_tools_and_resources_answer_identically_in_both_modes`): 12
|
||||
read calls (incl. a refusal) + 4 resource reads (incl. not-found) + the
|
||||
three list methods on `design` and `edit`: identical text in both modes.
|
||||
- **Extension.** `node --test editors/vscode/*_test.js` 6/6. The change
|
||||
event: `mcp.js:176-177` fires on `affectsConfiguration('lucisv.mcp')`,
|
||||
which VS Code answers true for `lucisv.mcp.mode` (pinned by the dev's
|
||||
test). Copy-config per host per mode pinned by `theThreeSnippets` /
|
||||
`theReadOnlySnippets`. `mcp_smoke.js` against the release binary: OK in
|
||||
both modes; `--read-only` against r5 (refuses the flag, exit 2) → smoke
|
||||
exit 1; against a wrapper that drops `--read-only` (a server listing nine
|
||||
tools) → smoke exit 1 (finding 4).
|
||||
- **Release script.** `bash -n tools/release.sh` OK; `set -eu` (line 32);
|
||||
both new invocations (host `$dist/lucisv-mcp-$version-$host`, embedded
|
||||
`$unpacked/$inner/lucisv-mcp`) are plain statements, so a failing smoke
|
||||
aborts the script.
|
||||
- **Docs.** The guide's two-key example parses as JSON and each entry has
|
||||
the shape copy-config emits for Claude Code / Cursor (`command`, `args`;
|
||||
`lucisv-ro` args end `--read-only`). Arguments line and usage line name
|
||||
the same five flags in the same order.
|
||||
- **Gates.** `cargo fmt --all` clean; `cargo clippy --all-targets -- -D
|
||||
warnings` clean (guard exit 0); `cargo test -p lucisv_mcp` 15 suites,
|
||||
378 passed, 0 failed, 4 ignored (guard exit 0, no `guard.sh:` line).
|
||||
|
||||
Findings, by severity:
|
||||
|
||||
1. **Low (docs, fixed).** The Agents guide
|
||||
(`docs/site/src/content/docs/guides/agents.md`, "Read-only mode", last
|
||||
paragraph) and `CHANGELOG.md` 0.59.0 said the index store "is outside
|
||||
the roots" — true only as the extension passes it. Repro:
|
||||
`lucisv-mcp --root R --index-cache R/.cache --read-only`, call `check`,
|
||||
close stdin → `R/.cache/.gitignore` and `R/.cache/index-cache-mcp`
|
||||
appear (the dev's recorded deviation). Reworded both to say the store is
|
||||
written where `--index-cache` points. PLAN §11.1 carries the same
|
||||
sentence; left for the lead.
|
||||
2. **Low (design, recorded).** `editors/vscode/mcp.js:57`: any
|
||||
`lucisv.mcp.mode` other than exactly `"read-only"` — `"Read-Only"`,
|
||||
`"readonly"`, `null`, `true` — is full mode, silently. That is the brief's
|
||||
rule and nothing dangerous is said, but a typo lands on the *permissive*
|
||||
mode; VS Code's only hint is the enum warning in `settings.json`. No
|
||||
change made.
|
||||
3. **Info.** `~/.cache/lucisv-eval/bin/lucisv-mcp-r5` reports
|
||||
`serverInfo.version` `0.57.0` (built before the 0.58.0 bump); the wire is
|
||||
otherwise byte-identical to the current full mode.
|
||||
4. **Info.** `mcp_smoke.js --read-only` against a server that ignores the
|
||||
flag fails on the `rename` check (`rename in read-only mode answered
|
||||
undefined`) before the tool-list check — it fails, but the message does
|
||||
not say "nine tools". Against r5 it fails the same way (the server
|
||||
exited 2 with its usage line on stderr).
|
||||
5. **Info.** `tools/release.sh` `smoke_embedded_mcp`: a failing smoke
|
||||
aborts before `rm -rf "$unpacked"`, leaving `target/vsix-check`
|
||||
(pre-existing pattern; the next run removes it first).
|
||||
|
||||
Tests added: `crates/lucisv_mcp/tests/qa_m8.rs` (5 tests, all green).
|
||||
|
||||
### 2026-09-29 — QA (Opus), re-check: `hierarchy` cap counts nodes
|
||||
|
||||
Rework under test: `tools/hierarchy.rs` `render_nodes` caps at 300 nodes
|
||||
(the down root line included), peek lines never count. **Verdict: PASS with
|
||||
one finding.**
|
||||
|
||||
- **No-peek identity with b757e82** (`lucisv-mcp-r6` vs a fresh release
|
||||
build): 43 calls on `fixtures/design` and 85 on `fixtures/edit` (every
|
||||
unit down / down depth 20 / up / up depth 20, with and without peek) —
|
||||
0 differ. Eval clone, 9 calls — `top_earlgrey` depth 2 (50 lines) and
|
||||
depth 3 (`… and 165 more`), `prim_fifo_sync` up (77) and up depth 3
|
||||
(`… and 1421 more`), `top_darjeeling` depth 3 (`… and 174 more`),
|
||||
`prim_flop` up (`… and 176 more`) and up depth 4 (`… and 45166 more`),
|
||||
`uart` depth 20, the overview (`… and 69 more`) — byte-identical, and
|
||||
identical again under `--read-only`.
|
||||
- **`prim_fifo_sync` up + peek** (eval clone): 1 078 lines, no cut. Its
|
||||
lines that are neither statement lines (4-space indent) nor blank are
|
||||
exactly the 77 lines of the no-peek answer, in order; every node is
|
||||
followed by at least one statement line; no block exceeds 12 lines + `…`
|
||||
(69 blocks end in `…`). r6 gave 21 of them then `… and 56 more`.
|
||||
- **`qa_m7.rs` diff vs HEAD:** one expected tuple `(299, 251)` → `(599,
|
||||
101)` (root + 299 two-line blocks, 401 − 300 = 101 — what the rule
|
||||
requires) and the peek assertion now pins *two* lines (`peek[597]` the
|
||||
299th instance's node line, `peek[598]` its statement) where it pinned
|
||||
one; no other assertion touched.
|
||||
- **Boundaries** (`qa_m8.rs`
|
||||
`qa_the_node_cap_is_exact_at_300_and_301_down_and_up_with_and_without_peek`,
|
||||
14-line statements so every block is cut to 12 + `…`): down 299
|
||||
instances (300 nodes) → 300 lines, no cut; down 300 → root + 299 and
|
||||
`… and 1 more`; up 300 → 300, no cut; up 301 → 300 and `… and 1 more`.
|
||||
With peek: the same node lines and cut line in the same order, exactly
|
||||
14 lines per instance node, the line before the cut is the last block's
|
||||
`…` (never split). The down count counts the root as a node consistently:
|
||||
401 nodes → `… and 101 more` = the 101 instances not shown.
|
||||
- **Modes:** every text above is identical in full and `--read-only` mode
|
||||
(asserted in the test, and on the eval clone with and without peek).
|
||||
- **Gates:** `cargo test -p lucisv_mcp` 16 suites, 381 passed, 0 failed, 4
|
||||
ignored (guard exit 0, no `guard.sh:` line); clippy `-p lucisv_mcp
|
||||
--all-targets -D warnings` clean. Eval clone `git status` empty.
|
||||
|
||||
Finding:
|
||||
|
||||
6. **Medium (answer size, design consequence).** A peeked answer is no
|
||||
longer bounded by ~300 lines but by 300 × 14 lines. Repro on the eval
|
||||
clone: `hierarchy {"root":"top_earlgrey","depth":3,"peek":true}` → 3 759
|
||||
lines, 151 224 bytes (r6: 295 lines, 10 152 bytes);
|
||||
`{"root":"prim_fifo_sync","up":true,"depth":3,"peek":true}` → 4 154
|
||||
lines, 152 356 bytes (r6: 10 457); `prim_flop` up peek → 2 984 lines,
|
||||
89 972 bytes. That is roughly 40 k tokens in one answer, against the
|
||||
lean catalogue's short-answer goal (PLAN §10). The fix the brief asked for
|
||||
(77 of 77) needs only ~31 KB; whether a byte ceiling on peek belongs
|
||||
beside the node cap is the lead's call. Not changed.
|
||||
|
||||
Tests added: `qa_m8.rs` `qa_the_node_cap_is_exact_at_300_and_301_down_and_up_with_and_without_peek`.
|
||||
|
||||
## Review
|
||||
|
||||
2026-09-29 (lead). Examined the diff, the registry filter, the QA log and
|
||||
the live wire in both modes. Accepted. `--read-only` lists five tools in
|
||||
1 797 model-visible bytes with 297-byte instructions; full mode is
|
||||
byte-identical to 0.58.0. QA could not make the read-only server write
|
||||
inside a root or reach an edit handler. Rulings: the dev's deviations 1–5
|
||||
stand (instructions say "check for issues"; any unknown tool name carries
|
||||
the read-only suffix); an unknown `lucisv.mcp.mode` value selects
|
||||
read-only and is logged (QA finding 2); the smoke checks the tool list
|
||||
first (finding 4); PLAN §11 now says the index store is written wherever
|
||||
`--index-cache` points. Gates at commit: lucisv_mcp 378 passed / 4
|
||||
ignored (15 suites), node tests 6/6, both smokes OK. Census round 5
|
||||
follows on this binary.
|
||||
@@ -32,6 +32,8 @@ hour. Record the release, the date and any failure in the table at the end.
|
||||
| 23 | Universal `lucisv-<v>.vsix` with no `lucisv-mcp` on PATH; start the server. | Same as 22 with `"lucisv-mcp" not found`; the language server (steps 1–5) unaffected. |
|
||||
| 24 | **lucisv: Copy MCP server config** → Claude Code; paste into `.mcp.json` of a scratch copy of a project; in a terminal there run `claude`, `/mcp`. Repeat for VS Code → `.vscode/mcp.json` in another window. | The info message names `.mcp.json` and warns the bundled path moves on update; Claude Code lists `lucisv` connected and answers `hierarchy` (no arguments); the `.vscode/mcp.json` server (`"type": "stdio"`) starts too. |
|
||||
| 25 | Optional, if a VS Code older than 1.101 is at hand: install the platform `.vsix` there. | Extension activates normally; Output → lucisv has one "no MCP server API (needs 1.101+)" line; the copy-config command still works. |
|
||||
| 26 | Set `lucisv.mcp.mode` to `read-only` (Settings UI, workspace scope); open **MCP: List Servers**; start the server and list its tools in agent mode. Reset the setting afterwards. | Without a reload the server is listed as `lucisv read-only (opentitan)`; it offers exactly five tools (`hierarchy`, `find`, `outline`, `read`, `check`); asking the agent to rename something gets no edit (the tool is not there). Back to `full`: `lucisv (opentitan)` with nine tools. |
|
||||
| 27 | With `lucisv.mcp.mode` = `read-only`, **lucisv: Copy MCP server config** → Claude Code; paste into a scratch `.mcp.json`. | The info message says `(read-only mode)`; the snippet's server key is `lucisv-ro` and its `args` end with `--read-only`; Claude Code's `/mcp` lists `lucisv-ro` connected with five tools. |
|
||||
|
||||
## Runs
|
||||
|
||||
|
||||
+68
-1
@@ -504,7 +504,7 @@ its text. The `annotations` stay (`readOnlyHint`, `destructiveHint: false`)
|
||||
|
||||
| tool | arguments | answers |
|
||||
|---|---|---|
|
||||
| `hierarchy` | `root?`, `up?` (bool), `depth?` (1–20, default 1), `peek?` (bool) | Without `root`: one line `N files, M modules, K top` then the top modules as `name file:line`. With `root`, down: the instance tree, one line per instance, two spaces per level: `instance: module file:line` where `file:line` is the **instantiation site**. `up`: every instantiation of `root`, `parent.instance file:line`, all levels up to `depth`. `peek: true` appends each instantiation statement's source under its line (indented, as written, at most 12 lines each then `…`). Cap 300 lines then `… and N more`. Unknown `root`: a refusal that lists up to 10 contains-matches. |
|
||||
| `hierarchy` | `root?`, `up?` (bool), `depth?` (1–20, default 1), `peek?` (bool) | Without `root`: one line `N files, M modules, K top` then the top modules as `name file:line`. With `root`, down: the instance tree, one line per instance, two spaces per level: `instance: module file:line` where `file:line` is the **instantiation site**. `up`: every instantiation of `root`, `parent.instance file:line`, all levels up to `depth`. `peek: true` appends each instantiation statement's source under its line (indented, as written, at most 12 lines each then `…`). Cap 300 instances, 100 with `peek`; peek lines do not count; then `… and N more`. Unknown `root`: a refusal that lists up to 10 contains-matches. |
|
||||
| `find` | `name`, `refs?` (bool) | Every declaration of `name` (whole-name, any case-exact): `kind name file:line`, then, with `refs`, per declaration its uses as `file:line` (one file per line, lines joined with `,` when several are in one file: `ip/uart/rtl/uart.sv:120,133,140`), then `unresolved:` and the textual mentions (strings, comments, macro text) the same way. No declaration: up to 20 contains-matches of declarations as a refusal (`no declaration named X; similar: …`). Cap 300 lines. |
|
||||
| `outline` | `file?` **or** `unit?` (exactly one) | `file`: its declarations as a tree with line ranges, two spaces per level: `kind name start–end`, parse errors first as `error line: message`. `unit`: its `file:line`, then parameters `param name = default` and ports `dir type[range] name` in declaration order, one per line; interfaces add modports, packages their exports. No template, no counts. Cap 300 lines. |
|
||||
| `read` | `item`, `file?` | The item's source, exact bytes, preceded by one line `file:start–end`. Selector as today's `read_item` (`name`, `kind:name`, `name@LINE`, `always@LINE`). Without `file` the item is looked up design-wide; several matches → a refusal listing them as `file:line`. |
|
||||
@@ -568,3 +568,70 @@ Agents guide's table.
|
||||
- The M4 attack suite green unchanged; `check` on the fixtures identical to
|
||||
the old `diagnostics` line set; `hierarchy` on opentitan's `top_earlgrey`
|
||||
identical instance set to the old tool.
|
||||
|
||||
## 11. Read-only mode (0.59 — the owner's request of 2026-09-29)
|
||||
|
||||
One binary, two modes. `lucisv-mcp --read-only` offers only the five read
|
||||
tools and shorter instructions; without the flag nothing changes (the nine
|
||||
tools of §10). The two co-exist: a host may configure both side by side
|
||||
under two names, and the extension chooses by a setting.
|
||||
|
||||
### 11.1 The server
|
||||
|
||||
- **Flag** `--read-only` (no value). Usage line:
|
||||
`usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--read-only] [--verbose]`.
|
||||
- **`tools/list`** in read-only mode: exactly `hierarchy, find, outline,
|
||||
read, check`, in that order, the same descriptions and schemas as in full
|
||||
mode except `check`, whose words "after edits" do not apply (one
|
||||
description for both modes if it reads right in both; otherwise a
|
||||
read-only wording). Model-visible bytes (compact JSON of name +
|
||||
description + inputSchema) **≤ 1 800**, pinned by test.
|
||||
- **`tools/call`** of `rename`, `port`, `edit_item` or `format` in
|
||||
read-only mode is the unknown-tool error (`-32602`), message
|
||||
`unknown tool: rename (the server runs --read-only)`. The edit handlers
|
||||
are not reachable: the mode filters the registry, it does not flag
|
||||
inside each handler.
|
||||
- **Instructions** in read-only mode, **≤ 300 bytes**, pinned by test:
|
||||
|
||||
> lucisv-mcp reads the SystemVerilog on disk (save first); it never
|
||||
> edits. Use it before reading files: hierarchy for instance trees and
|
||||
> top modules, find for a name's declarations and uses, outline for a
|
||||
> file or unit's ports, read for one item, check for issues. Paths
|
||||
> root-relative, lines 1-based.
|
||||
|
||||
- **The promise:** in read-only mode no file inside a root is created,
|
||||
written, renamed or removed by a tool, whatever is called. The server's
|
||||
own index store under `--index-cache` is still written (it is what makes
|
||||
the next start warm); the extension passes VS Code's workspace storage,
|
||||
which is outside the folder — a user who points `--index-cache` inside a
|
||||
root gets that directory written there. A test walks the fixture tree's
|
||||
sizes, mtimes and names before and after calling every tool name of the
|
||||
full catalogue.
|
||||
- Resources, transport, freshness, annotations: unchanged.
|
||||
|
||||
### 11.2 The extension
|
||||
|
||||
- Setting **`lucisv.mcp.mode`**: `"full"` (default) or `"read-only"`; any
|
||||
other value is treated as read-only and logged (a typo must not land on
|
||||
the mode that can write). In
|
||||
read-only mode the definition's args gain `--read-only` and its label is
|
||||
`lucisv read-only (<folder>)`; a change of the setting fires the
|
||||
provider's change event, like `lucisv.mcp.enabled`.
|
||||
- **lucisv: Copy MCP server config** follows the setting: in read-only
|
||||
mode the snippet's args end with `--read-only`, the server key is
|
||||
`lucisv-ro`, and the message says which mode was copied. (Two keys, so a
|
||||
user can paste both.)
|
||||
- `mcp_smoke.js <binary> --read-only` smokes that mode (five tools in
|
||||
order, one `hierarchy`, and `rename` answered with the unknown-tool
|
||||
error); `tools/release.sh` runs both smokes on the host binary and on
|
||||
the embedded one.
|
||||
|
||||
### 11.3 Acceptance
|
||||
|
||||
- Full mode byte-identical on the wire to 0.58.0 (`tools/list`,
|
||||
`instructions`), except the usage line.
|
||||
- Read-only budgets met and pinned; the no-write test green; the
|
||||
extension's node tests cover the setting, the label, the args and the
|
||||
snippet.
|
||||
- Census round 5 (lead): tasks a and d on the read-only mode, against
|
||||
round 4's full-mode figures.
|
||||
@@ -25,3 +25,12 @@ r4 d mcp sonnet tokens=104897 calls=22 wall=278s outcome=correct 71/20, all coun
|
||||
r4 c mcp sonnet tokens=101137 calls=45 wall=403s outcome=correct 8/8 sites in 4 files (rename wrote 2 files + listed the macro arg, chip_if path and the DV string path as unresolved; agent fixed those by hand); +16% vs r1 base, +9% vs r2 base rerun; agent lost time waiting on its own background rename (interim stop, nudged)
|
||||
r4 d mcp sonnet (re-run) tokens=99525 calls=24 wall=302s outcome=correct 71/20, all counts; mean of the two r4 runs 102 211 vs base 102 579
|
||||
r4 c mcp OPUS: tokens=68948 tool_calls=10 wall_s=214 outcome=correct 8/8 in 4 files (−1% vs r3 Opus mcp, +13% vs r3 Opus base)
|
||||
|
||||
# Round 5 — server b757e82 (M8 read-only mode, bin/lucisv-mcp-r6 --read-only, shim mcpc6ro, prompt_mcp_r5_ro.txt)
|
||||
r5 a read-only sonnet tokens=67230 calls=7 wall=41s outcome=correct 47/47 table, all values (prose first said 55 then corrected itself to 47); hierarchy up hit the 300-line cap (… and 56 more), agent fell back to grep over hw/ip
|
||||
r5 d read-only sonnet tokens=80487 calls=10 wall=121s outcome=correct 71/20, all counts (same content as the graded r4 answer); hierarchy depth 1 + outline unit per module
|
||||
r5 a read-only sonnet (re-run) tokens=72361 calls=7 wall=56s outcome=correct 47/47 (same table); hierarchy up truncated again, agent scanned the RTL sources; mean of the two r5 runs 69 796 vs base 91 094
|
||||
r5 d read-only sonnet (re-run) tokens=67104 calls=8 wall=151s outcome=correct 71/20, all counts; mean of the two r5 runs 73 796 vs base 102 579
|
||||
r5 a BASE control sonnet (same day, 2026-09-29) tokens=64817 calls=3 wall=40s outcome=correct 47/47 — the base arm is 29% cheaper than on 2026-09-23 (91 094): the sub-agent environment changed; earlier rounds are not comparable with round 5
|
||||
r5 d BASE control sonnet (same day) tokens=80194 calls=10 wall=78s outcome=correct 71/20, all counts (2026-09-23 base was 102 579)
|
||||
r5b a read-only sonnet (cap fix, bin r7) tokens=72247 calls=8 wall=50s outcome=correct 47/47; hierarchy up+peek now complete (77 instantiations, 31 kB); agent still cross-checked with grep; +11% vs same-day base 64 817
|
||||
@@ -32,12 +32,13 @@ agent mode can call its tools. The extension starts it as
|
||||
lucisv-mcp --root <folder> --index-cache <the extension's workspace storage>
|
||||
```
|
||||
|
||||
Two settings govern it:
|
||||
Three settings govern it:
|
||||
|
||||
| setting | default | what it does |
|
||||
|---|---|---|
|
||||
| `lucisv.mcp.enabled` | `true` | `false` withdraws the server from agent mode (takes effect without a reload) |
|
||||
| `lucisv.mcp.path` | `""` | a `lucisv-mcp` to use instead of the bundled one; empty means the bundled one, else `lucisv-mcp` on `PATH` |
|
||||
| `lucisv.mcp.mode` | `"full"` | `"read-only"` starts it with `--read-only`, listed as `lucisv read-only (<folder>)`; any other value is treated as read-only — see [Read-only mode](#read-only-mode) (takes effect without a reload) |
|
||||
|
||||
The universal `.vsix` carries no binaries: it looks `lucisv-mcp` up on
|
||||
`PATH`, and when there is none it says so in the **lucisv** output channel
|
||||
@@ -88,7 +89,8 @@ cargo build --release -p lucisv_mcp # target/release/lucisv-mcp
|
||||
|
||||
Arguments: `--root DIR` (repeatable; default the current directory),
|
||||
`--filelist FILE` (index exactly the files an EDA filelist names),
|
||||
`--index-cache DIR`, `--verbose` (per-call timing on stderr). Anything else is
|
||||
`--index-cache DIR`, `--read-only` (the five read tools only — see
|
||||
[Read-only mode](#read-only-mode)), `--verbose` (per-call timing on stderr). Anything else is
|
||||
refused with a usage line and exit status 2.
|
||||
|
||||
## Tools
|
||||
@@ -109,6 +111,41 @@ description. The agent sees the full description and input schema.
|
||||
| `edit_item` | yes | One item of `file` (selector as read): `op` replace it by `text` (same kind and names), insert `text` before/after it (item `end`/`end@UNIT`: a unit's end), or delete it if unused. |
|
||||
| `format` | yes | Format `files` (a path, directory or glob like `rtl/**/*.sv`) as lucisv format; `fix: true` applies safe lint fixes first. |
|
||||
|
||||
## Read-only mode
|
||||
|
||||
`lucisv-mcp --read-only` offers only the five read tools — `hierarchy`,
|
||||
`find`, `outline`, `read`, `check`, the rows without **writes** above — and
|
||||
shorter instructions: a smaller catalogue for the agent to read every
|
||||
session, and a server that cannot change the design. Without the flag
|
||||
nothing changes.
|
||||
|
||||
- **In VS Code**, set `lucisv.mcp.mode` to `"read-only"`: the extension
|
||||
hands agent mode a server started with `--read-only`, listed as
|
||||
`lucisv read-only (<folder>)` with five tools (no reload needed).
|
||||
**lucisv: Copy MCP server config** follows the setting: in read-only mode
|
||||
the snippet's args end with `--read-only` and its server key is
|
||||
`lucisv-ro`, so it can sit beside a full one.
|
||||
- **By hand**, both modes side by side under two names — the agent (or you)
|
||||
picks the one to enable:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"lucisv": { "command": "lucisv-mcp", "args": ["--root", "/path/to/project"] },
|
||||
"lucisv-ro": { "command": "lucisv-mcp", "args": ["--root", "/path/to/project", "--read-only"] }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
What it promises: **no file inside a root is created, written, renamed or
|
||||
removed, whatever is called.** An edit tool is not there to call — `tools/list`
|
||||
does not offer it and `tools/call` answers its name with the unknown-tool
|
||||
error, `unknown tool: rename (the server runs --read-only)`. The server's own
|
||||
index store under `--index-cache` is still written on exit (it is what makes
|
||||
the next start warm): the extension keeps it outside the workspace, but a
|
||||
directory you name inside a root is written like any other. Resources answer
|
||||
as in full mode.
|
||||
|
||||
## What it promises
|
||||
|
||||
- **Answers come from the disk.** Every call first re-checks the files it
|
||||
|
||||
@@ -662,6 +662,7 @@ engine-lane features are listed above; this table is the server-internal web.
|
||||
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-packaging) | handshake | The MCP spawn contract (2026-09-23): the binary `lucisv-mcp[.exe]` found by the same three-rung ladder as the server (`lucisv.mcp.path` → `bin/` → `PATH`), spawned by VS Code from `McpStdioServerDefinition(label, command, ["--root", folder, "--index-cache", storage], env, version)` — the constructor is positional — one per workspace folder; `serverInfo.name == "lucisv-mcp"`, exactly the nine lean tools in order — `hierarchy, find, outline, read, check, rename, port, edit_item, format` (`mcp_smoke.js` `TOOLS`; **amended by M7, 2026-09-23**, was ≥ 26); `mcp_smoke.js --tool-table` regenerates the Agents guide's table. Provider id `lucisv.mcp`; settings `lucisv.mcp.enabled`/`.path`; command `lucisv.mcp.copyConfig`. |
|
||||
| `release-prep / editor-platform-vsix ──▶ lucisv-mcp` (mcp-packaging) | depends | `release.sh` builds `-p lucisv_mcp` for every triple and stages it as the THIRD `bin/` entry (fifteen in the `all` package); `expect_vsix_bins` and `audit_artifacts.sh` pin the name; the seven `.vsix` names are unchanged. `mcp_smoke.js` is the gate beside `smoke.js`. |
|
||||
| `lucisv-mcp ──▶ lucisv-server` (index cache, M6) | depends (read-only) | MCP reads the server's `index-cache` store read-only when `--index-cache DIR` names it (header `CACHE_FORMAT`/`FACTS_FORMAT`/version must match, else ignored) and writes its own `index-cache-mcp` beside it; it never writes the server's file. A codec change on the server side costs MCP its warm start, never its correctness. |
|
||||
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-read-only, M8) | handshake | The read-only mode (2026-09-29, PLAN §11): setting `lucisv.mcp.mode` (`"full"` default / `"read-only"`) appends `--read-only` to the spawn args and labels the definition `lucisv read-only (<folder>)`; copy-config keys it `lucisv-ro`. The binary then lists exactly `hierarchy, find, outline, read, check` (≤ 1 800 model-visible bytes, instructions ≤ 300), answers the four edit names with `-32602` `unknown tool: NAME (the server runs --read-only)`, and writes nothing inside a root (`tests/read_only.rs`); full mode is byte-identical to 0.58.0. `mcp_smoke.js --read-only` is the second MCP gate in `release.sh`, host and embedded. |
|
||||
|
||||
### 2.9 Open handshakes (filed, not yet delivered — claim before working)
|
||||
|
||||
|
||||
@@ -5,6 +5,16 @@ 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).
|
||||
|
||||
## 0.59.0 — 2026-09-29
|
||||
|
||||
- New setting `lucisv.mcp.mode`: `"read-only"` offers agent mode a
|
||||
`lucisv read-only (<folder>)` server with only the five read tools —
|
||||
`hierarchy`, `find`, `outline`, `read`, `check` — that never writes a file
|
||||
in the workspace (`lucisv-mcp --read-only`). `"full"`, the default,
|
||||
changes nothing. **lucisv: Copy MCP server config** follows the setting:
|
||||
in read-only mode the snippet is keyed `lucisv-ro` and ends with
|
||||
`--read-only`, so a full and a read-only server can be pasted side by side.
|
||||
|
||||
## 0.58.0 — 2026-09-24
|
||||
|
||||
- `lucisv-mcp`, the agent server, now offers nine tools instead of 26 —
|
||||
|
||||
@@ -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.58.0**. Its platform packages include
|
||||
The current release is **0.59.0**. Its platform packages include
|
||||
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
|
||||
[Agents (MCP)](#agents-mcp)):
|
||||
|
||||
@@ -197,11 +197,12 @@ edit is verified and written whole, with no dry run.
|
||||
|---|---|
|
||||
| VS Code agent mode | On VS Code 1.101+, one `lucisv (<folder>)` server per workspace folder, listed under **MCP: List Servers**; trust it once and agent mode can call its tools (the full list is in the Agents guide). Folders added or removed update the list |
|
||||
| Other agents | **lucisv: Copy MCP server config** copies the snippet for Claude Code (`.mcp.json`), Cursor (`.cursor/mcp.json`) or VS Code (`.vscode/mcp.json`), naming the binary this extension runs |
|
||||
| Read-only mode | Set `lucisv.mcp.mode` to `read-only` and the server is `lucisv read-only (<folder>)`, started with `--read-only`: the five read tools only (`hierarchy`, `find`, `outline`, `read`, `check`), and no file in the workspace is ever written. The copied config follows the setting (server key `lucisv-ro`, so both can sit in one file) |
|
||||
| No binary, no error | With the universal package and no `lucisv-mcp` on `PATH`, one line in the lucisv output channel says so; nothing else changes |
|
||||
|
||||
The server reads files from disk, never unsaved buffers — save before asking
|
||||
an agent about a file. The extension starts it as `lucisv-mcp --root <folder>
|
||||
--index-cache <workspace storage>`. On VS Code older than 1.101 nothing is
|
||||
--index-cache <workspace storage>` (plus `--read-only` in read-only mode). On VS Code older than 1.101 nothing is
|
||||
registered (the engine requirement stays `^1.82.0`; `vsce` accepts the
|
||||
contribution point there). The tool list and the snippets are in the
|
||||
[Agents (MCP) guide](https://git.luci.ooo/lucio/lucisv/src/branch/master/docs/site/src/content/docs/guides/agents.md).
|
||||
@@ -328,6 +329,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
|
||||
| `lucisv.serverPath` | bundled | Explicit server override for advanced use; an unchanged setting uses the bundled server |
|
||||
| `lucisv.mcp.enabled` | `true` | Offer `lucisv-mcp` to VS Code's agent mode (1.101+), one server per workspace folder; `false` withdraws it without a reload |
|
||||
| `lucisv.mcp.path` | `""` | A `lucisv-mcp` to use instead of the bundled one (empty: bundled, else `PATH`); also what **lucisv: Copy MCP server config** names |
|
||||
| `lucisv.mcp.mode` | `"full"` | `"read-only"`: offer agent mode only the five read tools (`lucisv-mcp --read-only`, listed as `lucisv read-only (<folder>)`), without a reload; any other value is treated as read-only; also the mode **lucisv: Copy MCP server config** copies (key `lucisv-ro`) |
|
||||
| `lucisv.verbose` | `false` | Print how long every operation took in the lucisv output channel — one `timing:` line per request, notification, scan, widen, buffer flush, and per request that had to wait behind a rescan. **Restarts the language server when changed**, because it is an argument the server is started with |
|
||||
|
||||
The six `lucisv.index.*` settings and `lucisv.largeFile.threshold` arrive with
|
||||
@@ -402,6 +404,14 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.59.0 highlights
|
||||
|
||||
Version 0.59.0 adds a read-only mode to `lucisv-mcp`: with
|
||||
`lucisv.mcp.mode` set to `read-only` (or `--read-only` on the command
|
||||
line) the agent sees five tools — hierarchy, find, outline, read, check —
|
||||
in under 1.8 kB, and the server never writes inside the project. The full
|
||||
nine-tool mode is unchanged and stays the default.
|
||||
|
||||
## Release 0.58.0 highlights
|
||||
|
||||
Version 0.58.0 slims `lucisv-mcp` to nine tools whose whole catalogue is
|
||||
|
||||
+34
-12
@@ -52,26 +52,43 @@ function mcpEnabled() {
|
||||
return vscode.workspace.getConfiguration('lucisv').get('mcp.enabled') !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the server runs `--read-only`. Only unset or exactly `"full"` is full
|
||||
* mode: a value that is neither setting (`"readonly"`, `null`, a number) fails
|
||||
* safe to read-only, and says so in one line through `log`.
|
||||
*/
|
||||
function readOnlyMode(log = () => {}) {
|
||||
const mode = vscode.workspace.getConfiguration('lucisv').get('mcp.mode');
|
||||
if (mode === undefined || mode === 'full') return false;
|
||||
if (mode !== 'read-only') {
|
||||
log(`lucisv: lucisv.mcp.mode is "${String(mode)}", not "full" or "read-only"; using read-only.`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The workspace folders' paths, in order. */
|
||||
function folderPaths() {
|
||||
return (vscode.workspace.workspaceFolders || []).map((folder) => folder.uri.fsPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* One stdio definition per workspace folder, or none while the setting is off.
|
||||
* One stdio definition per workspace folder, or none while the setting is off;
|
||||
* in read-only mode each gets `--read-only` and says so in its label.
|
||||
* The constructor is positional (label, command, args, env, version) in
|
||||
* vscode.d.ts — an object argument would become the label — and `cwd` is a
|
||||
* plain property set afterwards.
|
||||
*/
|
||||
function serverDefinitions(context, bundledBinary, version) {
|
||||
function serverDefinitions(context, bundledBinary, version, log) {
|
||||
if (!mcpEnabled()) return [];
|
||||
const command = resolveBinary(context, bundledBinary);
|
||||
const storage = (context.storageUri || context.globalStorageUri || {}).fsPath;
|
||||
const readOnly = readOnlyMode(log);
|
||||
return (vscode.workspace.workspaceFolders || []).map((folder) => {
|
||||
const args = ['--root', folder.uri.fsPath];
|
||||
if (storage) args.push('--index-cache', storage);
|
||||
if (readOnly) args.push('--read-only');
|
||||
const definition = new vscode.McpStdioServerDefinition(
|
||||
`lucisv (${folder.name})`,
|
||||
readOnly ? `lucisv read-only (${folder.name})` : `lucisv (${folder.name})`,
|
||||
command,
|
||||
args,
|
||||
{},
|
||||
@@ -82,28 +99,33 @@ function serverDefinitions(context, bundledBinary, version) {
|
||||
});
|
||||
}
|
||||
|
||||
/** The JSON a host's config file wants for this server, pretty-printed. */
|
||||
function configSnippet(host, command, roots) {
|
||||
/**
|
||||
* The JSON a host's config file wants for this server, pretty-printed. A
|
||||
* read-only server is keyed `lucisv-ro`, so both snippets can be pasted side by side.
|
||||
*/
|
||||
function configSnippet(host, command, roots, readOnly = false) {
|
||||
const args = roots.flatMap((root) => ['--root', root]);
|
||||
if (readOnly) args.push('--read-only');
|
||||
const server = host.stdioType ? { type: 'stdio', command, args } : { command, args };
|
||||
return JSON.stringify({ [host.key]: { lucisv: server } }, null, 2);
|
||||
return JSON.stringify({ [host.key]: { [readOnly ? 'lucisv-ro' : 'lucisv']: server } }, null, 2);
|
||||
}
|
||||
|
||||
/** Ask which host, copy its snippet, and say which file it goes in. */
|
||||
async function copyConfig(context, bundledBinary) {
|
||||
/** Ask which host, copy its snippet in the configured mode, and say which mode and file. */
|
||||
async function copyConfig(context, bundledBinary, log) {
|
||||
const picked = await vscode.window.showQuickPick(
|
||||
HOSTS.map((host) => ({ label: host.label, description: host.file, host })),
|
||||
{ placeHolder: 'Copy the lucisv MCP server config for…' },
|
||||
);
|
||||
if (!picked) return;
|
||||
const command = resolveBinary(context, bundledBinary);
|
||||
await vscode.env.clipboard.writeText(configSnippet(picked.host, command, folderPaths()));
|
||||
const readOnly = readOnlyMode(log);
|
||||
await vscode.env.clipboard.writeText(configSnippet(picked.host, command, folderPaths(), readOnly));
|
||||
const bundled = bundledBinary && bundledBinary(context, BINARY);
|
||||
const moving = command === bundled
|
||||
? ' The binary path points into this extension and changes when it updates.'
|
||||
: '';
|
||||
vscode.window.showInformationMessage(
|
||||
`lucisv: copied the ${picked.host.label} MCP config — paste it into ${picked.host.file}.${moving}`,
|
||||
`lucisv: copied the ${picked.host.label} MCP config (${readOnly ? 'read-only' : 'full'} mode) — paste it into ${picked.host.file}.${moving}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -143,7 +165,7 @@ function activate(context, helpers = {}) {
|
||||
const { bundledBinary, outputChannel } = helpers;
|
||||
const log = (line) => outputChannel && outputChannel.appendLine(line);
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('lucisv.mcp.copyConfig', () => copyConfig(context, bundledBinary)),
|
||||
vscode.commands.registerCommand('lucisv.mcp.copyConfig', () => copyConfig(context, bundledBinary, log)),
|
||||
);
|
||||
if (!hasMcpApi()) {
|
||||
log('lucisv: this VS Code has no MCP server API (needs 1.101+); use "lucisv: Copy MCP server config" for other agents.');
|
||||
@@ -156,7 +178,7 @@ function activate(context, helpers = {}) {
|
||||
changed,
|
||||
vscode.lm.registerMcpServerDefinitionProvider(PROVIDER_ID, {
|
||||
onDidChangeMcpServerDefinitions: changed.event,
|
||||
provideMcpServerDefinitions: () => serverDefinitions(context, bundledBinary, version),
|
||||
provideMcpServerDefinitions: () => serverDefinitions(context, bundledBinary, version, log),
|
||||
resolveMcpServerDefinition: (definition) => resolveDefinition(definition, log),
|
||||
}),
|
||||
vscode.workspace.onDidChangeWorkspaceFolders(() => changed.fire()),
|
||||
|
||||
+48
-14
@@ -2,11 +2,13 @@
|
||||
// provider does (`--root <folder> --index-cache <dir>`, the folder as cwd) over
|
||||
// a tiny temporary project and drive one MCP session at it over stdio —
|
||||
// initialize, notifications/initialized, tools/list, one `hierarchy` without a
|
||||
// root (the project overview).
|
||||
// root (the project overview). With `--read-only` the server is started in that
|
||||
// mode and the smoke expects the five read tools, then one `rename` answered
|
||||
// with the unknown-tool error, and the project's files untouched (PLAN §11).
|
||||
// Plain node, no dependencies, hand-rolled newline-delimited JSON-RPC, like
|
||||
// `smoke.js` does for the language server.
|
||||
//
|
||||
// node mcp_smoke.js [path-to-lucisv-mcp] [--tool-table]
|
||||
// node mcp_smoke.js [path-to-lucisv-mcp] [--read-only] [--tool-table]
|
||||
//
|
||||
// `--tool-table` also prints the tools as the Markdown table checked into
|
||||
// docs/site/src/content/docs/guides/agents.md, so that page is regenerated
|
||||
@@ -19,13 +21,20 @@ const path = require('path');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const toolTable = args.includes('--tool-table');
|
||||
const named = args.find((arg) => arg !== '--tool-table') || 'lucisv-mcp';
|
||||
const readOnly = args.includes('--read-only');
|
||||
const named = args.find((arg) => arg !== '--tool-table' && arg !== '--read-only') || 'lucisv-mcp';
|
||||
// Resolved now: the server runs with the temporary project as its cwd, where a
|
||||
// relative path would no longer point at the binary. A bare name stays a PATH lookup.
|
||||
const binary = /[\\/]/.test(named) ? path.resolve(named) : named;
|
||||
|
||||
/** The lean catalogue, in order (PLAN §10.1, TODO-MCP M7). */
|
||||
const TOOLS = ['hierarchy', 'find', 'outline', 'read', 'check', 'rename', 'port', 'edit_item', 'format'];
|
||||
const FULL_TOOLS = ['hierarchy', 'find', 'outline', 'read', 'check', 'rename', 'port', 'edit_item', 'format'];
|
||||
|
||||
/** What this run expects `tools/list` to be: `--read-only` offers the five reads (PLAN §11.1). */
|
||||
const TOOLS = readOnly ? FULL_TOOLS.slice(0, 5) : FULL_TOOLS;
|
||||
|
||||
/** The error a read-only server answers an edit tool with. */
|
||||
const READ_ONLY_RENAME = { code: -32602, message: 'unknown tool: rename (the server runs --read-only)' };
|
||||
|
||||
/** Give up on a server that has not answered and exited by then. */
|
||||
const TIMEOUT_MS = 30000;
|
||||
@@ -35,14 +44,15 @@ function fail(message) {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
/** Two files, one instantiating the other: enough for a non-trivial overview. */
|
||||
/** The project's two files: one instantiating the other, enough for a non-trivial overview. */
|
||||
const SOURCES = {
|
||||
'top.sv': 'module top (input logic clk);\n sub u_sub (.clk(clk));\nendmodule\n',
|
||||
'sub.sv': 'module sub (input logic clk);\nendmodule\n',
|
||||
};
|
||||
|
||||
function makeProject() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'lucisv-mcp-smoke-'));
|
||||
fs.writeFileSync(
|
||||
path.join(root, 'top.sv'),
|
||||
'module top (input logic clk);\n sub u_sub (.clk(clk));\nendmodule\n',
|
||||
);
|
||||
fs.writeFileSync(path.join(root, 'sub.sv'), 'module sub (input logic clk);\nendmodule\n');
|
||||
for (const [name, text] of Object.entries(SOURCES)) fs.writeFileSync(path.join(root, name), text);
|
||||
fs.mkdirSync(path.join(root, '.cache'));
|
||||
return root;
|
||||
}
|
||||
@@ -62,11 +72,17 @@ const REQUESTS = [
|
||||
{ jsonrpc: '2.0', id: 2, method: 'tools/list' },
|
||||
{ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'hierarchy', arguments: {} } },
|
||||
];
|
||||
if (readOnly) {
|
||||
const rename = { name: 'rename', arguments: { name: 'sub', new_name: 'sub2' } };
|
||||
REQUESTS.push({ jsonrpc: '2.0', id: 4, method: 'tools/call', params: rename });
|
||||
}
|
||||
|
||||
/** Every request is written up front and stdin closed: the server answers in order and exits on EOF. */
|
||||
function session(root) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = spawn(binary, ['--root', root, '--index-cache', path.join(root, '.cache')], {
|
||||
const flags = ['--root', root, '--index-cache', path.join(root, '.cache')];
|
||||
if (readOnly) flags.push('--read-only');
|
||||
const server = spawn(binary, flags, {
|
||||
cwd: root,
|
||||
stdio: 'pipe',
|
||||
});
|
||||
@@ -91,7 +107,10 @@ function session(root) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Parse stdout, which must be JSON-RPC lines and nothing else. */
|
||||
/**
|
||||
* Parse stdout, which must be JSON-RPC lines and nothing else; only the
|
||||
* read-only `rename` may be an error, kept under the key `'rename'` for `check`.
|
||||
*/
|
||||
function answers(stdout) {
|
||||
const byId = new Map();
|
||||
for (const line of stdout.split('\n').filter((l) => l.trim() !== '')) {
|
||||
@@ -101,6 +120,10 @@ function answers(stdout) {
|
||||
} catch {
|
||||
fail(`stdout carried a line that is not JSON: ${line.slice(0, 200)}`);
|
||||
}
|
||||
if (readOnly && message.id === 4) {
|
||||
byId.set('rename', message.error);
|
||||
continue;
|
||||
}
|
||||
if (message.error) fail(`request ${message.id} failed: ${JSON.stringify(message.error)}`);
|
||||
byId.set(message.id, message.result);
|
||||
}
|
||||
@@ -116,7 +139,14 @@ function check(byId) {
|
||||
const listed = byId.get(2);
|
||||
const tools = (listed && listed.tools) || [];
|
||||
const names = tools.map((tool) => tool.name).join(', ');
|
||||
if (names !== TOOLS.join(', ')) fail(`tools/list is [${names}], expected [${TOOLS.join(', ')}]`);
|
||||
if (names !== TOOLS.join(', ')) {
|
||||
fail(`tools/list is ${tools.length} tools [${names}], expected ${TOOLS.length} [${TOOLS.join(', ')}]`);
|
||||
}
|
||||
// Checked after the tool list, so a server ignoring --read-only fails on its nine tools.
|
||||
const renameError = byId.get('rename');
|
||||
if (readOnly && JSON.stringify(renameError) !== JSON.stringify(READ_ONLY_RENAME)) {
|
||||
fail(`rename in read-only mode answered ${JSON.stringify(renameError)}, expected ${JSON.stringify(READ_ONLY_RENAME)}`);
|
||||
}
|
||||
const overview = byId.get(3);
|
||||
if (!overview) fail('no hierarchy answer');
|
||||
if (overview.isError) fail(`hierarchy is an error: ${JSON.stringify(overview.content)}`);
|
||||
@@ -146,8 +176,12 @@ async function main() {
|
||||
const { code, stdout } = await session(root);
|
||||
const { init, tools } = check(answers(stdout));
|
||||
if (code !== 0) fail(`the server exited with status ${code} after stdin closed`);
|
||||
for (const [name, text] of Object.entries(SOURCES)) {
|
||||
if (fs.readFileSync(path.join(root, name), 'utf8') !== text) fail(`${name} was written`);
|
||||
}
|
||||
const mode = readOnly ? ' (--read-only), rename refused' : '';
|
||||
console.log(
|
||||
`mcp smoke: OK — "${binary}" ${init.serverInfo.version}: initialize, ${tools.length} tools, hierarchy`,
|
||||
`mcp smoke: OK — "${binary}" ${init.serverInfo.version}: initialize, ${tools.length} tools, hierarchy${mode}`,
|
||||
);
|
||||
if (toolTable) console.log(markdownTable(tools));
|
||||
} finally {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Checks for `mcp.js`: the binary ladder, the provider registration and its
|
||||
// guard on a VS Code without the MCP API, and the copy-config snippets.
|
||||
// guard on a VS Code without the MCP API, the copy-config snippets, and the
|
||||
// read-only mode (`lucisv.mcp.mode`).
|
||||
//
|
||||
// node mcp_test.js
|
||||
//
|
||||
@@ -156,6 +157,54 @@ function changesAreAnnounced() {
|
||||
configListener({ affectsConfiguration: (section) => section === 'lucisv.mcp' });
|
||||
configListener({ affectsConfiguration: () => false });
|
||||
assert.equal(emitter.fired, 2, 'folder change and lucisv.mcp change fire; other settings do not');
|
||||
// VS Code answers a section prefix of the changed key: `lucisv.mcp.mode` affects `lucisv.mcp`.
|
||||
configListener({ affectsConfiguration: (section) => 'lucisv.mcp.mode'.startsWith(section) });
|
||||
assert.equal(emitter.fired, 3, 'a change of lucisv.mcp.mode fires');
|
||||
}
|
||||
|
||||
function readOnlyModeDefinitions() {
|
||||
const contributed = require('./package.json').contributes.configuration.properties['lucisv.mcp.mode'];
|
||||
assert.equal(contributed.default, 'full');
|
||||
assert.deepEqual(contributed.enum, ['full', 'read-only']);
|
||||
reset();
|
||||
folders = [folder('alpha'), folder('beta')];
|
||||
settings['mcp.mode'] = 'read-only';
|
||||
mcp.activate(context(), { bundledBinary: bundled(true) });
|
||||
const provider = registered[0].provider;
|
||||
const definitions = provider.provideMcpServerDefinitions();
|
||||
assert.deepEqual(definitions.map((d) => d.label), ['lucisv read-only (alpha)', 'lucisv read-only (beta)']);
|
||||
assert.deepEqual(definitions[0].args, ['--root', '/work/alpha', '--index-cache', '/storage/ws', '--read-only']);
|
||||
settings['mcp.mode'] = 'full';
|
||||
const full = provider.provideMcpServerDefinitions()[0];
|
||||
assert.equal(full.label, 'lucisv (alpha)', 'back to full: the plain label');
|
||||
assert.ok(!full.args.includes('--read-only'), 'back to full: no flag');
|
||||
}
|
||||
|
||||
function anUnknownModeFailsSafeToReadOnly() {
|
||||
reset();
|
||||
const log = [];
|
||||
mcp.activate(context(), { bundledBinary: bundled(true), outputChannel: { appendLine: (l) => log.push(l) } });
|
||||
const provider = registered[0].provider;
|
||||
const first = () => provider.provideMcpServerDefinitions()[0];
|
||||
// Unset and exactly "full": full mode, nothing logged.
|
||||
for (const value of [undefined, 'full']) {
|
||||
settings['mcp.mode'] = value;
|
||||
assert.equal(first().label, 'lucisv (alpha)', `${value}: full`);
|
||||
assert.ok(!first().args.includes('--read-only'), `${value}: no flag`);
|
||||
}
|
||||
// Exactly "read-only": read-only, nothing logged.
|
||||
settings['mcp.mode'] = 'read-only';
|
||||
assert.equal(first().label, 'lucisv read-only (alpha)');
|
||||
assert.deepEqual(log, [], 'a valid setting logs nothing');
|
||||
// Anything else: read-only, one line naming the value.
|
||||
for (const value of ['Read-Only', 'readonly', 'Full', null, true, 3]) {
|
||||
settings['mcp.mode'] = value;
|
||||
log.length = 0;
|
||||
const definition = first();
|
||||
assert.equal(definition.label, 'lucisv read-only (alpha)', `${value}: read-only`);
|
||||
assert.equal(definition.args[definition.args.length - 1], '--read-only', `${value}: flag`);
|
||||
assert.deepEqual(log, [`lucisv: lucisv.mcp.mode is "${String(value)}", not "full" or "read-only"; using read-only.`]);
|
||||
}
|
||||
}
|
||||
|
||||
function disabledOffersNothing() {
|
||||
@@ -221,6 +270,7 @@ async function theThreeSnippets() {
|
||||
assert.equal(informed.length, 1);
|
||||
assert.ok(informed[0].includes(file), `${label}: names ${file}`);
|
||||
assert.ok(informed[0].includes('changes when it updates'), `${label}: warns the bundled path moves`);
|
||||
assert.ok(informed[0].includes('(full mode)'), `${label}: names the mode`);
|
||||
}
|
||||
reset();
|
||||
settings.inspectPath = { globalValue: '/usr/local/bin/lucisv-mcp' };
|
||||
@@ -236,15 +286,52 @@ async function theThreeSnippets() {
|
||||
assert.deepEqual(copied, [], 'a dismissed pick copies nothing');
|
||||
}
|
||||
|
||||
async function theReadOnlySnippets() {
|
||||
const args = ['--root', '/work/alpha', '--read-only'];
|
||||
const want = {
|
||||
'Claude Code': { mcpServers: { 'lucisv-ro': { command: '/ext/bin/lucisv-mcp', args } } },
|
||||
Cursor: { mcpServers: { 'lucisv-ro': { command: '/ext/bin/lucisv-mcp', args } } },
|
||||
'VS Code': { servers: { 'lucisv-ro': { type: 'stdio', command: '/ext/bin/lucisv-mcp', args } } },
|
||||
};
|
||||
for (const [label, json] of Object.entries(want)) {
|
||||
reset();
|
||||
settings['mcp.mode'] = 'read-only';
|
||||
pickLabel = label;
|
||||
mcp.activate(context(), { bundledBinary: bundled(true) });
|
||||
await commands.get('lucisv.mcp.copyConfig')();
|
||||
assert.equal(copied[0], JSON.stringify(json, null, 2), `${label}: exact read-only JSON`);
|
||||
assert.ok(informed[0].includes('(read-only mode)'), `${label}: names the mode`);
|
||||
}
|
||||
// An unknown value copies the read-only server too, and says why.
|
||||
reset();
|
||||
settings['mcp.mode'] = 'readonly';
|
||||
pickLabel = 'Claude Code';
|
||||
const log = [];
|
||||
mcp.activate(context(), { bundledBinary: bundled(true), outputChannel: { appendLine: (l) => log.push(l) } });
|
||||
await commands.get('lucisv.mcp.copyConfig')();
|
||||
assert.equal(copied[0], JSON.stringify(want['Claude Code'], null, 2), 'readonly: the lucisv-ro snippet');
|
||||
assert.ok(informed[0].includes('(read-only mode)'));
|
||||
assert.deepEqual(log, ['lucisv: lucisv.mcp.mode is "readonly", not "full" or "read-only"; using read-only.']);
|
||||
// Two keys: the full and the read-only server fit in one config file.
|
||||
const host = mcp.HOSTS[0];
|
||||
const full = JSON.parse(mcp.configSnippet(host, 'b', ['/r']));
|
||||
const readOnly = JSON.parse(mcp.configSnippet(host, 'b', ['/r'], true));
|
||||
const both = { mcpServers: { ...full.mcpServers, ...readOnly.mcpServers } };
|
||||
assert.deepEqual(Object.keys(both.mcpServers), ['lucisv', 'lucisv-ro']);
|
||||
}
|
||||
|
||||
async function run() {
|
||||
theLadder();
|
||||
oneDefinitionPerFolder();
|
||||
changesAreAnnounced();
|
||||
readOnlyModeDefinitions();
|
||||
anUnknownModeFailsSafeToReadOnly();
|
||||
disabledOffersNothing();
|
||||
anOldVsCodeRegistersNothing();
|
||||
aMissingBinaryIsNotStarted();
|
||||
await theThreeSnippets();
|
||||
console.log('mcp: OK — binary ladder, one definition per folder, change events, enabled:false, old-VS Code guard, missing binary, three config snippets');
|
||||
await theReadOnlySnippets();
|
||||
console.log('mcp: OK — binary ladder, one definition per folder, change events, read-only definitions, unknown mode fails safe to read-only, enabled:false, old-VS Code guard, missing binary, three config snippets in both modes');
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "lucisv",
|
||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
||||
"version": "0.58.0",
|
||||
"version": "0.59.0",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
@@ -291,6 +291,19 @@
|
||||
"default": "",
|
||||
"markdownDescription": "Path to the `lucisv-mcp` executable. Empty (the default) uses the one bundled with the extension, else `lucisv-mcp` on PATH. Also the binary **lucisv: Copy MCP server config** names."
|
||||
},
|
||||
"lucisv.mcp.mode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"full",
|
||||
"read-only"
|
||||
],
|
||||
"enumDescriptions": [
|
||||
"All nine tools: the five reads and the four verified edits (rename, port, edit_item, format).",
|
||||
"The five read tools only (hierarchy, find, outline, read, check): the server never writes a file in the workspace."
|
||||
],
|
||||
"default": "full",
|
||||
"markdownDescription": "Which tools `lucisv-mcp` offers agent mode. `read-only` starts it with `--read-only` (listed as **lucisv read-only (folder)**): the five read tools, never a write inside the workspace. Any other value is treated as read-only. Also the mode **lucisv: Copy MCP server config** copies (server key `lucisv-ro`)."
|
||||
},
|
||||
"lucisv.verbose": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
|
||||
@@ -303,6 +303,63 @@ nothing where the old one cost 15–25 %; the small edit tasks now sit at
|
||||
server's answers. The remaining gap is bounded by how the agent works, not
|
||||
by what the server sends.
|
||||
|
||||
## Round 5 — server at b757e82 (M8, read-only mode)
|
||||
|
||||
`lucisv-mcp --read-only`: five tools (`hierarchy, find, outline, read,
|
||||
check`), a 1 797-byte catalogue, 297-byte instructions, and no way to
|
||||
write. Only the two read tasks apply. Each arm ran twice; **the base arm
|
||||
was re-run the same day as a control**, and that control is the finding.
|
||||
|
||||
| task | arm | model | tokens | tool calls | wall | outcome |
|
||||
|---|---|---|---|---|---|---|
|
||||
| a | read-only | Sonnet 5 | 67 230 | 7 | 41 s | correct, 47/47 |
|
||||
| a | read-only (re-run) | Sonnet 5 | 72 361 | 7 | 56 s | correct, 47/47 |
|
||||
| a | base (same day) | Sonnet 5 | 64 817 | 3 | 40 s | correct, 47/47 |
|
||||
| a | read-only, cap fixed | Sonnet 5 | 72 247 | 8 | 50 s | correct, 47/47 |
|
||||
| d | read-only | Sonnet 5 | 80 487 | 10 | 121 s | correct, 71/20, all counts |
|
||||
| d | read-only (re-run) | Sonnet 5 | 67 104 | 8 | 151 s | correct, 71/20, all counts |
|
||||
| d | base (same day) | Sonnet 5 | 80 194 | 10 | 78 s | correct, 71/20, all counts |
|
||||
|
||||
### Observations
|
||||
|
||||
**Against the old base figures the read-only mode looks 23–28 % cheaper;
|
||||
against a same-day base it is at parity** (a: mean 69.8 k vs 64.8 k, +8 %;
|
||||
d: mean 73.8 k vs 80.2 k, −8 %). The base arm itself fell from 91.1 k to
|
||||
64.8 k on task a and from 102.6 k to 80.2 k on task d between 2026-09-23
|
||||
and 2026-09-29 with no change to the task, the clone or the prompt: the
|
||||
sub-agent environment changed under the census. Two consequences. Rounds
|
||||
1–4 compared each mcp arm with a base arm measured the same day or within
|
||||
a day, so their deltas stand; round 5 must not be compared with them, and
|
||||
no figure in this file should be read as an absolute. And every future
|
||||
round needs its base arm re-run alongside.
|
||||
|
||||
- **a: the server's own answer was cut short.** Both read-only runs asked
|
||||
`hierarchy up` with `peek` (they needed the `#(…)` values), and the
|
||||
300-line cap, which counted peek lines, showed 20 of 77 instantiations
|
||||
and `… and 56 more`. Both agents then scanned the RTL sources themselves
|
||||
— which is what the base arm does, in 3 calls. Without `peek` the same
|
||||
call lists all 77 in 77 lines. Fixed after the round: the cap counts
|
||||
instances (300, or 100 with `peek`, which bounds a peeked answer near
|
||||
40 kB), peek lines do not count (0.59.0). Re-measured on the fixed
|
||||
binary: the one call now returns all 77 with their source (31 kB), the
|
||||
agent reported the server and its own search agreed — and still ran the
|
||||
search, so the cost did not move (72.2 k). A complete answer removes the
|
||||
need for the fallback; it does not remove the agent's habit of checking.
|
||||
- **d: the server answered.** `hierarchy` at depth 1 gave the 71 instances
|
||||
in one call and `outline unit:` the port counts; 8–10 calls, the same as
|
||||
the base arm's 10, with a wider spread in wall time (the shim re-indexes
|
||||
on every call).
|
||||
- **Catalogue.** Through the shim the read-only `--list` is 1.1 kB
|
||||
(≈ 300 tokens) against 2.1 kB for the nine tools; a native host sends
|
||||
1.8 kB of schemas against 3.4 kB. The saving is real and small: a few
|
||||
hundred tokens per session, below the run-to-run noise of any task here.
|
||||
|
||||
**What the round says.** Read-only mode does what it is for: a smaller
|
||||
surface that cannot write, with the same answers. It does not change the
|
||||
token picture, and nothing at the catalogue level will: on these tasks
|
||||
the model's own reading and answer dominate, and a current Sonnet with
|
||||
plain file tools is already efficient at both.
|
||||
|
||||
## Verdict, and what to do next
|
||||
|
||||
**Helpful, not a toy — for the questions an engine answers better than
|
||||
@@ -334,6 +391,16 @@ them as file writes"), not the server. For scoped edits (b) a design-wide
|
||||
`port add` is the wrong tool and the agent should edit the two files; for
|
||||
renames (c) the `unresolved:` list is what makes 8/8 repeatable.
|
||||
|
||||
**After round 5 (read-only mode, 0.59.0).** Six more runs, all correct.
|
||||
With a same-day base control the read-only server is at parity with file
|
||||
tools on both read tasks (+8 %, −8 %), and the control showed the base arm
|
||||
itself had become 22–29 % cheaper in six days — so no round here supports
|
||||
an absolute claim, only same-day comparisons. The round also found a real
|
||||
defect (the `peek` cap cutting `hierarchy up` to a quarter of its answer),
|
||||
fixed in 0.59.0. The honest summary of five rounds: the server is correct
|
||||
and safe, it matches file tools on cost, and it does not beat them on
|
||||
these tasks with these models.
|
||||
|
||||
**Superseded by the ruling above — kept for the record.** (feedback-3 and
|
||||
after, as planned before round 4): the instantiation template opt-in
|
||||
on `unit_interface`; a terser `hierarchy` line (overrides only on request);
|
||||
|
||||
+4
-2
@@ -127,8 +127,10 @@ It builds `--release`, copies the three binaries into `dist/` under
|
||||
version-and-host names, smoke-tests the server binary with
|
||||
`editors/vscode/smoke.js` and the MCP server with `editors/vscode/mcp_smoke.js`
|
||||
(initialize, `tools/list` with exactly the nine tools in order, one `hierarchy`
|
||||
over a tiny temporary project), packages the extension into `dist/lucisv-<version>.vsix`
|
||||
and into the host's platform package, runs both smoke tests again against the
|
||||
over a tiny temporary project; then again with `--read-only`: the five read
|
||||
tools in order, one `hierarchy`, `rename` answered with the unknown-tool error
|
||||
and the project's files untouched), packages the extension into `dist/lucisv-<version>.vsix`
|
||||
and into the host's platform package, runs the smoke tests (the MCP one in both modes) again against the
|
||||
binaries *unzipped out of* that package (and, with `--cross`, out of the `all`
|
||||
package), and writes `dist/SHA256SUMS`. `dist/` is gitignored and is
|
||||
deleted and recreated on every run.
|
||||
|
||||
+5
-2
@@ -132,12 +132,14 @@ fi
|
||||
# `smoke.js` is plain node with no dependencies, so this runs before `npm ci`.
|
||||
# The MCP server gets the same treatment from `mcp_smoke.js`: initialize,
|
||||
# tools/list (the nine tools, in order) and one `hierarchy` over stdio against a
|
||||
# tiny temp project.
|
||||
# tiny temp project; then again with `--read-only` (the five read tools, and
|
||||
# `rename` answered with the unknown-tool error).
|
||||
if command -v node >/dev/null 2>&1; then
|
||||
echo "==> smoke-testing the server binary"
|
||||
node "$repo_root/editors/vscode/smoke.js" "$dist/lucisv-server-$version-$host"
|
||||
echo "==> smoke-testing the MCP server binary"
|
||||
node "$repo_root/editors/vscode/mcp_smoke.js" "$dist/lucisv-mcp-$version-$host"
|
||||
node "$repo_root/editors/vscode/mcp_smoke.js" "$dist/lucisv-mcp-$version-$host" --read-only
|
||||
else
|
||||
echo " note: no node on PATH, skipping the server and MCP smoke tests" >&2
|
||||
fi
|
||||
@@ -255,7 +257,7 @@ smoke_embedded_server() { # vsix file name, the bin/ path inside the package
|
||||
}
|
||||
|
||||
# The same for the MCP server the package carries: unzipped, then driven through
|
||||
# initialize, tools/list and one `hierarchy` by `mcp_smoke.js`.
|
||||
# initialize, tools/list and one `hierarchy` by `mcp_smoke.js`, in both modes.
|
||||
smoke_embedded_mcp() { # vsix file name, the bin/ path inside the package
|
||||
vsix=$1
|
||||
inner=$2
|
||||
@@ -265,6 +267,7 @@ smoke_embedded_mcp() { # vsix file name, the bin/ path inside the package
|
||||
unzip -q "$dist/$vsix" -d "$unpacked"
|
||||
chmod +x "$unpacked/$inner/lucisv-mcp"
|
||||
node "$repo_root/editors/vscode/mcp_smoke.js" "$unpacked/$inner/lucisv-mcp"
|
||||
node "$repo_root/editors/vscode/mcp_smoke.js" "$unpacked/$inner/lucisv-mcp" --read-only
|
||||
rm -rf "$unpacked"
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user