diff --git a/.github/workflows/container-e2e.yml b/.github/workflows/container-e2e.yml index ca923fd3..2519272f 100644 --- a/.github/workflows/container-e2e.yml +++ b/.github/workflows/container-e2e.yml @@ -71,6 +71,7 @@ jobs: i8_canary_never_reaches_the_agent \ egress_proxy_never_resolves_a_listed_host_to_itself \ controls_e2e_pinned_harness_passes \ + parity_one_installed_server_one_traced_call \ control_each_kind_runs_on_the_real_base \ opencode_probe_reads_each_real_base_image_version \ plugin_environment_serves_live_mcp_tools \ diff --git a/__reports__/diet/leaves/parity_run_v0.md b/__reports__/diet/leaves/parity_run_v0.md new file mode 100644 index 00000000..209fc257 --- /dev/null +++ b/__reports__/diet/leaves/parity_run_v0.md @@ -0,0 +1,125 @@ +# Parity run leaf, v0 + +One cell with a real MCP server, run on Claude Code and on OpenCode with code mode at its default, +shows on each harness that the server is installed and that the stored trace holds the agent's call +to its tool as the same `ToolOrigin::Mcp`. + +Base `a1f14719` (`origin/feat/integrity` at the branch point). Tip: the tip of `leaf/l3-parity-run`. + +## Live record (step 2) + +Two runs of the guard's experiment shape, one per harness, on RiVault (reachable; `rv_health` ok). +The experiment is the guard's: one cell, `permission_mode = "bypassPermissions"`, model +`RiVault/Reasoning-Medium`, the declared server `parity` (`python3 servers/parity/parity_mcp.py` +from an agent input), code mode left out; only the `[harness]` name differs. The key's variable is +`RIVAULT_LLM_INFERENCE` (`rv_config.py var llm`); no key was printed. No run was repeated. + +| | Claude Code | OpenCode | +|---|---|---| +| job | `01a20f84-4e1a-7846-b388-c9ba5c76d190`, completed | `01a20f84-9378-71bd-9f47-12e2da5782fe`, completed | +| alias | `RiVault/Reasoning-Medium` | `RiVault/Reasoning-Medium` | +| model the proxy returned | `RiVault/Reasoning-Medium` (the `model` of the streamed answers, 8 times in stdout, once in stderr) | `RiVault/Reasoning-Medium` (the `model.id` of the export) | +| backing model | `deepseek-ai/DeepSeek-V4-Flash` (`rv_models.py`, the live listing; the proxy answers with the alias, not the backing name) | the same | +| resolved `mcp.*` (`candler inspect`) | `mcp.servers.parity.command = "python3"`, `.args = ["servers/parity/parity_mcp.py"]`, `.codemode = false` | the same three values | +| stored trace, tool calls | `ToolSearch` builtin, `ToolSearch` builtin, `mcp__parity__stamp` with origin `{kind: mcp, server: parity, tool: stamp}` | `parity_stamp` with origin `{kind: mcp, server: parity, tool: stamp}` | + +Both traces attribute the call to the same server and tool. The shape matches the guard's: Claude +Code reaches the tool through its own `ToolSearch` (it defers MCP tools), OpenCode lists it at once, +and the one MCP call reads the same in both stored traces. Numbers are not compared. The runs' store, +scratch worktree files and containers are removed (`docker ps -a` shows none of the job's; no +network is left). + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| Guard in `container-e2e` with real images, production gateway, scripted fake model; per harness the server in the resolved `mcp.*` values and in the rendered MCP file, and the scripted call stored as `ToolOrigin::Mcp` with one server and tool | PASS | `cargo nextest run -p candler --test it -E 'test(parity_one)' --run-ignored only`: PASS, 22.5 s locally; CI `PASS [37.879s] (3/23) ... guard_cli_e2e::parity_e2e::parity_one_installed_server_one_traced_call`; `container-e2e` green on PR 79 | +| Fails on the base on OpenCode with `origin: other` | PASS, on a different base than the leaf names | `origin/feat/integrity` already holds the trace-parity reader, so the failure is shown on `29573006` (merge of #74). The guard does not compile there unchanged (`ToolOrigin::mcp_tool` is absent); with its oracle adapted to the origin that had no `tool` (`{kind: mcp, server: parity}`) it fails: `opencode: MCP tool calls [] among [{"kind":"other"}]`. `candler inspect` shows no `mcp` member there either (`no mcp.servers.parity in null`, both harnesses) | +| No census, no server status | PASS | the guard reads `candler inspect`'s `mcp` member, the files in the run, and the stored trace | +| Same experiment file, harness the only difference; code mode at default, no code-mode case | PASS | the guard asserts the two files differ in exactly the line `name = "claude-code"` / `name = "opencode"`; `codemode` is not written, and the resolved value is `false` | +| Fixture needs nothing outside the base images | PASS | one stdlib `python3` file. Both agent base images carry `python3` (probed: `/usr/local/bin/python3` in the Claude Code and the OpenCode image; neither has `node`) | +| One live run per harness, same shape, call attributed to the server; store and containers removed | PASS | the live record above | +| Container-e2e added time | PASS | see Time | +| "What it leaves" at three levels | PASS | below | +| fmt, clippy `-D warnings`, nextest workspace, doc `-D warnings`, `container-e2e` | PASS | fmt clean; clippy clean after two doc backticks; `732 tests run: 732 passed, 32 skipped`; `cargo doc` exit 0; CI `container-e2e` success | +| Bite (step 3), edit A: OpenCode's reader drops the server from the origin | PASS (fails as it should) | `opencode: MCP tool calls [] among [{"kind":"other"}], expected [{"kind":"mcp","server":"parity","tool":"stamp"}]` | +| Bite, edit B: Claude Code's renderer skips the server | PASS (fails as it should) | `claude-code: 0 .mcp.json files hold the server under /mcpServers: []` and `claude-code: MCP tool calls [] among []` | + +Deviations: the guard is in `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs`, not +`candler-core`'s tests, because the producer it reads (run, resolved values, trace) is the +`candler` binary. The step 1 commit line is 77 characters and the `commit-msg` hook allows 72, so it +reads `test(runner): hold both harnesses to one MCP install and traced call`. The pull request title +is cut to 66 characters. The fresh verifier of step 3 is the lead's. + +## Time + +- Locally the guard runs in 22.5 s for both harnesses (images cached). +- CI, `Container e2e (Linux)` on PR 79: 7 min 40 s, of which the guard took 37.9 s. The latest run on + a leaf branch before it (`leaf/l3-pages`) took 7 min 12 s: about 28 s more. + +## What it leaves + +How it is developed. The guard was written by reading the i8 guard and the control runner once, +then run against the real images; two failed runs before the first pass cost seconds, not builds +(the fake model had to learn Claude Code's `ToolSearch`). Docker use: one fake-model image and +container per run, removed by exact id by the guard; the live runs used the cached images and their +stores are removed. No image was built that was not there. The two scratch builds (the old base, the +two bite edits) shared one scratch target dir, removed after. + +What it leaves in the code. One guard, one fixture file, one script in the fake model; the i8 guard +and this one share `Made`, `must` and `fake_host` instead of copying them. The guard builds no +state: the run, its resolved values, the rendered file and the trace all come from `candler run` +and `candler inspect`. It asserts what the leaf names and no more. The oracle for the origin is the +type's own constructor. Nothing is kept for another reader. + +How it is consumed. The experimenter's view does not change. A maintainer who lets one harness +install or trace a declared server differently now gets a red `container-e2e`, naming the harness, +the file or the origin that differs. + +## Not covered + +- Permission defaults. The experiment sets `permission_mode = "bypassPermissions"` (the mode both + drivers map; OpenCode refuses `default`), so the guard and the live runs prove MCP install and + trace parity, not what each harness does with no mode. That choice is still open. +- Code mode: no case, by the leaf. +- The rendered file is read from the run's stored home and workspace by name (`.mcp.json`, + `opencode.json`); a harness that renders under another name needs its row in the guard. +- A tool that is deferred behind a harness's own search (Claude Code) is reached by the fake model + through `ToolSearch`; a Claude Code version that changes that protocol breaks the script, not the + guard's assertions. + +## Observations for the lead + +- The leaf and the lead's reading assumed the OpenCode image has no `python3` and that `node` is on + both images. Probed on the local images: both have `python3`, neither has `node`. +- On the merge of #74 `candler inspect` shows no `mcp` member; it arrived with #77. + +## Review + +A fresh verifier read PR 79. Five findings, each fixed in a new commit (`a3884e78`, `f3c86903`). + +1. **Leak on failure.** `run_once` never gave `Made` the job id, so a timeout or a failed assertion + left the job's containers, sidecar and network. It takes `&mut Made` and sets `made.job` right + after parsing the launcher's output. Shown with a scratch edit that panics just after the id is + known (`leak probe job 01a20f97-f87b-79c0-96b5-1bcf4481c3a7`): after the test, `docker ps -a` and + `docker network ls`, filtered by `label=candler.job=`, print nothing, and no candler + container or network exists. The probe panics at the first moment after launch, so it shows the + cleanup runs, not what a later phase would hold. +2. **Reachability.** The origin alone is read by name, so a rendered but broken server passed. The + guard now also requires that the fake model received, in the request that follows its call + (`tool_use_id` `toolu_fake_stamp`), a tool result that is not an error and holds the fixture's + stamp `parity-stamp-5c1e`. The stored trace keeps no tool-result content (`tool_result` has + `is_error` and `denied` only), so the text is read from the fake model's recorded requests, the + record of what the model was handed; each run reads only the requests recorded during it. + Bite, the fixture returns `parity-stamp-0000` with the server still rendered and the call still + attributed: `claude-code: the model never received the stamp from the tool: [(false, + "[{\"text\":\"parity-stamp-0000\",...}]")]` and `opencode: ... [(false, "parity-stamp-0000")]`. + Second bite, the args name a file that is not there: Candler's own job ends with no sealed run, + and the guard fails with `a sealed run` followed by the job's events. +3. **Rendered file.** The file is now the one below the run's `workspace` (`.mcp.json`, Claude Code) + or `home` (`opencode/opencode.json`, OpenCode), where each driver writes it, and its program and + arguments must equal the resolved `mcp.servers.parity.command` and `.args`. +4. **Identity.** The two experiment files are compared as whole strings with the harness name + replaced by one placeholder, not line by line. +5. **Oracle.** The expected origin is the literal `{"kind":"mcp","server":"parity","tool":"stamp"}`, + the stored trace's form, not the type's constructor. diff --git a/assets/docker/fakemodel/fakemodel.py b/assets/docker/fakemodel/fakemodel.py index cd78279e..d238ac8a 100644 --- a/assets/docker/fakemodel/fakemodel.py +++ b/assets/docker/fakemodel/fakemodel.py @@ -26,6 +26,11 @@ is answered with text. A user message that carries a background job's completion is answered with a second text. Anything else is answered with text. c2 must stop. Every request is answered "hello". + p1 must call a tool. A first user prompt is answered with one call to the tool `stamp` of the + MCP server `parity`, under the name the request offers for it (`parity_stamp` for + OpenCode). A request that defers its MCP tools (Claude Code, which offers ToolSearch) is + answered with a ToolSearch for `mcp__parity__stamp` first, and its result with the call. + Anything else is answered with text. c3 must be slow. Every request is answered "hello" after FAKE_DELAY_SECS seconds, so that a run is live and its agent is mid-turn for that long. @@ -50,6 +55,7 @@ DIR = os.environ.get("FAKE_DIR", "/tmp/fake") OUT_TOKENS = int(os.environ.get("FAKE_OUT_TOKENS", "20")) DELAY_SECS = max(0, min(int(os.environ.get("FAKE_DELAY_SECS", "0")), 120)) +PARITY_TOOLS = ("mcp__parity__stamp", "parity_stamp") JOB_COMMAND = "sleep 20 && date +%s%N > /work/job.done && echo job-finished" LOCK = threading.Lock() COUNTER = [0] @@ -104,8 +110,34 @@ def last_user_state(messages): return "prompt" -def script_blocks(model, state): +def stamp_call(name): + """A call to the stamp tool under `name`.""" + return {"type": "tool_use", "id": "toolu_fake_stamp", "name": name, "input": {}} + + +def last_tool_result(messages): + """The tool_use_id of the last tool result of the last user message, or None.""" + content = messages[-1].get("content") if messages else None + ids = [b.get("tool_use_id") for b in content or [] + if isinstance(b, dict) and b.get("type") == "tool_result"] if isinstance(content, list) else [] + return ids[-1] if ids else None + + +def script_blocks(model, state, tools, messages): """The content blocks, the stop reason and a label of the answer for one request.""" + if model.startswith("p1"): + offered = [name for name in tools if name in PARITY_TOOLS] + if state == "prompt" and offered: + return [{"type": "text", "text": "I will call the stamp tool."}, + stamp_call(offered[0])], "tool_use", "p1-call" + if state == "prompt" and "ToolSearch" in tools: + search = {"type": "tool_use", "id": "toolu_fake_search", "name": "ToolSearch", + "input": {"query": "select:" + PARITY_TOOLS[0], "max_results": 1}} + return [{"type": "text", "text": "I will load the stamp tool."}, search], \ + "tool_use", "p1-search" + if state == "tool_result" and last_tool_result(messages) == "toolu_fake_search": + return [stamp_call(PARITY_TOOLS[0])], "tool_use", "p1-call" + return [{"type": "text", "text": "done"}], "end_turn", "p1-text" if model.startswith("c2"): return [{"type": "text", "text": "hello"}], "end_turn", "c2-hello" if model.startswith("c3"): @@ -206,7 +238,8 @@ def handle_any(self): decision, status = "unauthorised", 401 elif path == "/v1/messages" and self.command == "POST" and isinstance(body, dict): state = last_user_state(messages) - blocks, stop, label = script_blocks(model, state) + tools = [t.get("name", "") for t in body.get("tools") or [] if isinstance(t, dict)] + blocks, stop, label = script_blocks(model, state, tools, messages) decision = "%s/%s" % (label, state) message = message_json(model, blocks, stop) elif path == "/v1/messages/count_tokens": diff --git a/crates/candler/tests/fixtures/parity/parity_mcp.py b/crates/candler/tests/fixtures/parity/parity_mcp.py new file mode 100644 index 00000000..71a97b90 --- /dev/null +++ b/crates/candler/tests/fixtures/parity/parity_mcp.py @@ -0,0 +1,37 @@ +"""A stdio MCP server with one tool, `stamp`, written with the standard library alone.""" +import json +import sys + +TOOLS = [{ + "name": "stamp", + "description": "Returns the parity stamp, a fixed text. Takes no argument.", + "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, +}] +STAMP = "parity-stamp-5c1e" + + +def send(message): + sys.stdout.write(json.dumps(message) + "\n") + sys.stdout.flush() + + +for line in sys.stdin: + try: + msg = json.loads(line) + except ValueError: + continue + method, msg_id = msg.get("method"), msg.get("id") + if method == "initialize": + send({"jsonrpc": "2.0", "id": msg_id, "result": { + "protocolVersion": msg.get("params", {}).get("protocolVersion", "2025-03-26"), + "capabilities": {"tools": {}}, + "serverInfo": {"name": "parity", "version": "1.0.0"}, + }}) + elif method == "tools/list": + send({"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS}}) + elif method == "tools/call": + send({"jsonrpc": "2.0", "id": msg_id, + "result": {"content": [{"type": "text", "text": STAMP}], "isError": False}}) + elif msg_id is not None: + send({"jsonrpc": "2.0", "id": msg_id, + "error": {"code": -32601, "message": "unknown method"}}) diff --git a/crates/candler/tests/it/guard_cli_e2e.rs b/crates/candler/tests/it/guard_cli_e2e.rs index bb919924..2dbe59de 100644 --- a/crates/candler/tests/it/guard_cli_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e.rs @@ -806,3 +806,7 @@ mod shim_refusals { /// The ground-truth e2e: a real `candler run` of the real agent, seen from inside its container. #[path = "guard_cli_e2e/i8_e2e.rs"] mod i8_e2e; + +/// Both harnesses install and trace one declared MCP server the same way. +#[path = "guard_cli_e2e/parity_e2e.rs"] +mod parity_e2e; diff --git a/crates/candler/tests/it/guard_cli_e2e/i8_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/i8_e2e.rs index 628f5654..601d131a 100644 --- a/crates/candler/tests/it/guard_cli_e2e/i8_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/i8_e2e.rs @@ -37,7 +37,7 @@ const DELAY_SECS: u64 = 100; /// The name or address the fake model's certificate is for and the job's containers reach it by: /// `host.docker.internal` on Docker Desktop, the default bridge's gateway address on a Linux /// engine, which resolves no such name in a container the product starts. -fn fake_host(real: &Path) -> String { +pub(super) fn fake_host(real: &Path) -> String { if cfg!(target_os = "linux") { must( real, @@ -71,11 +71,11 @@ fn ere_escape(text: &str) -> String { /// What the test made and must give back, by exact id. #[derive(Default)] -struct Made { - real: PathBuf, - job: Option, - containers: Vec, - images: Vec, +pub(super) struct Made { + pub(super) real: PathBuf, + pub(super) job: Option, + pub(super) containers: Vec, + pub(super) images: Vec, } impl Drop for Made { @@ -111,7 +111,7 @@ impl Drop for Made { } /// What `docker ` printed on stdout, for a command that must succeed. -fn must(real: &Path, args: &[&str]) -> String { +pub(super) fn must(real: &Path, args: &[&str]) -> String { let out = docker(real, args); assert!( out.status.success(), diff --git a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs new file mode 100644 index 00000000..e2734028 --- /dev/null +++ b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs @@ -0,0 +1,410 @@ +//! One cell, one real MCP server, two harnesses: the server is installed on each and the stored +//! trace records the agent's call to its tool in the same form. +//! +//! The runs are the product's own: real Claude Code and real OpenCode, each in its agent base +//! image, behind the production gateway sidecar, against the scripted fake model +//! (`assets/docker/fakemodel`, model `p1`, which calls the tool `stamp` of the server `parity` +//! under the name the request offers for it). The fake model is reached through the machine +//! setting `[gateway] upstream_ca`. One experiment file is written once; the line `[harness]` +//! names is the only thing that differs between the two runs. +use std::fs; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use super::i8_e2e::{Made, fake_host, must}; +use super::{docker, real_docker}; +use crate::support::cli_run::{wait_for, world}; +use crate::support::seam::entries_under; + +/// The credential the fake model demands and the experiment's secret supplies. +const TOKEN: &str = "parity-fixture-token-0123456789"; + +/// The server the cell declares. +const SERVER: &str = "parity"; + +/// The text the fixture's tool returns. +const STAMP: &str = "parity-stamp-5c1e"; + +/// The id the fake model gives its call to the tool, which the answer to the call carries back. +const CALL_ID: &str = "toolu_fake_stamp"; + +/// The experiment of one cell, with the harness the one line `[harness]` names. +fn experiment(base: &str, harness: &str) -> String { + base.replace("@HARNESS@", harness) +} + +/// The answers to the stamp call among the requests the fake model recorded after the first +/// `skip`: whether each is an error, and its text. +fn stamp_answers(records: &str, skip: usize) -> Vec<(bool, String)> { + let mut found = Vec::new(); + for line in records.lines().skip(skip) { + let Ok(record) = serde_json::from_str::(line) else { + continue; + }; + let blocks = record["body"]["messages"] + .as_array() + .and_then(|messages| messages.last()) + .and_then(|message| message["content"].as_array()); + for block in blocks.into_iter().flatten() { + if block["type"] == "tool_result" && block["tool_use_id"] == CALL_ID { + let text = block["content"].as_str().map_or_else( + || block["content"].to_string(), + str::to_owned, // BORROW: .to_owned() makes the owned text + ); + found.push((block["is_error"] == true, text)); + } + } + } + found +} + +/// What the fake model has recorded so far: nothing before its first request. +fn records(real: &Path, fake: &str) -> String { + let out = docker(real, &["exec", fake, "cat", "/tmp/fake/records.jsonl"]); + String::from_utf8_lossy(&out.stdout).into_owned() +} + +/// The program and arguments of a rendered server entry, whether the file keeps them as a command +/// and its arguments or as one list. +fn argv_of(entry: &Value) -> Vec { + if let Some(list) = entry["command"].as_array() { + return list.clone(); // BORROW: .clone() copies the list + } + std::iter::once(entry["command"].clone()) // BORROW: .clone() copies the program + .chain(entry["args"].as_array().into_iter().flatten().cloned()) // BORROW: .cloned() copies the arguments + .collect() +} + +/// What a run of one harness stored: the resolved `mcp.*` values `candler inspect` shows, the +/// MCP files its driver rendered at the place the harness reads (the parsed files below the +/// run's workspace or home that end in the path), and the origin of each tool call of the stored +/// trace. +struct Observed { + mcp: Value, + rendered: Vec, + origins: Vec, +} + +/// The origin of every tool call among the events of the trace `text`, one JSON object per line. +fn call_origins(text: &str) -> Vec { + fn walk(value: &Value, found: &mut Vec) { + match value { + Value::Object(map) => { + if map.get("kind") == Some(&Value::from("tool_call")) + && let Some(origin) = map.get("origin") + { + found.push(origin.clone()); // BORROW: .clone() copies the origin + } + map.values().for_each(|inner| walk(inner, found)); + } + Value::Array(items) => items.iter().for_each(|inner| walk(inner, found)), + Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {} + } + } + let mut found = Vec::new(); + for line in text.lines() { + if let Ok(value) = serde_json::from_str::(line) { + walk(&value, &mut found); + } + } + found +} + +/// Runs the experiment `text` with the real `candler run` against the fake model at `endpoint` +/// and reads back what the sealed run stored, the MCP file being the one `place` names: +/// the directory of the run it is written under and the path it ends in. +fn run_once( + text: &str, + endpoint: &str, + ca: &Path, + place: (&str, &str), + made: &mut Made, +) -> Observed { + let world = world(); + let inputs = world.root.join("inputs").join("servers"); + fs::create_dir_all(&inputs).unwrap(); + fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/parity/parity_mcp.py"), + inputs.join("parity_mcp.py"), + ) + .unwrap(); + let config = world.root.join("config"); + fs::create_dir_all(config.join("candler")).unwrap(); + fs::write( + config.join("candler").join("config.toml"), + format!("[gateway]\nupstream_ca = \"{}\"\n", ca.display()), + ) + .unwrap(); + fs::write(world.work.join("env.lock"), "").unwrap(); + let written = text + .replace("http://127.0.0.1:9", endpoint) + .replace("@SKILLS@", &world.skills.display().to_string()); + fs::write(&world.experiment, written).unwrap(); + + let launched = Command::new(env!("CARGO_BIN_EXE_candler")) + .arg("run") + .arg(&world.experiment) + .args([ + "--set", + "isolation.build.lock=env.lock", + "--set", + "model.token_secret=FIXTURE_TOKEN", + ]) + .current_dir(&world.work) + .env_remove("CANDLER_STORE") + .env("XDG_STATE_HOME", &world.state) + .env("XDG_CONFIG_HOME", &config) + .env("FIXTURE_TOKEN", TOKEN) + .stdin(Stdio::null()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&launched.stdout).into_owned(); + assert!( + launched.status.success(), + "the launcher exits 0: {stdout}\n{}", + String::from_utf8_lossy(&launched.stderr) + ); + let job = stdout.trim().to_owned(); + made.job = Some(job.clone()); // BORROW: the cleanup owns the job id + let store = world.store(); + let events = store.join("jobs").join(&job).join("events.jsonl"); + let ended = wait_for(Duration::from_secs(600), || { + fs::read_to_string(&events).is_ok_and(|log| log.contains("job.ended")) + }); + let log = fs::read_to_string(&events).unwrap_or_default(); + assert!(ended, "the job ends\n{log}"); + + let run_dir = fs::read_dir(store.join("runs")) + .into_iter() + .flatten() + .flatten() + .map(|entry| entry.path()) + .find(|path| path.join("run.done").is_file()) + .unwrap_or_else(|| panic!("a sealed run\n{log}")); + let inspected = Command::new(env!("CARGO_BIN_EXE_candler")) + .arg("inspect") + .arg(&run_dir) + .current_dir(&world.work) + .env_remove("CANDLER_STORE") + .env("XDG_STATE_HOME", &world.state) + .output() + .unwrap(); + assert!(inspected.status.success(), "inspect exits 0: {inspected:?}"); + let record: Value = serde_json::from_slice(&inspected.stdout).unwrap(); + let trace = fs::read_to_string(run_dir.join("trace.jsonl")).unwrap_or_default(); + let rendered = entries_under(&run_dir.join(place.0)) + .into_iter() + .filter(|path| path.ends_with(place.1)) + .filter_map(|path| serde_json::from_slice(&fs::read(path).ok()?).ok()) + .collect(); + Observed { + rendered, + mcp: record["mcp"].clone(), // BORROW: .clone() copies the member + origins: call_origins(&trace), + } +} + +/// Guards: README (an MCP server of a cell is installed and its calls are traced alike on every +/// harness) -- one experiment, run with the real `candler run` on Claude Code and on `OpenCode`, +/// code mode at its default, shows on each: the declared server among the run's resolved `mcp.*` +/// values, and the scripted call stored in the trace as an MCP call of that server and tool. +/// +/// Oracle: the server name and tool the fixture declares and the fake model scripts, and the +/// origin the trace schema writes for them (`ToolOrigin::mcp_tool`); the two experiment files are +/// compared line by line. +/// +/// Bite: `OpenCode`'s reader dropping the server from the origin (`other`), or a driver that skips +/// the server (no tool is offered, the fake model answers with text, and no call is stored). +#[test] +#[ignore = "needs Docker; run with --run-ignored only"] +fn parity_one_installed_server_one_traced_call() { + let started = Instant::now(); + let real = real_docker(); + let host = fake_host(&real); + let publish = format!( + "{}::8443", + if cfg!(target_os = "linux") { + host.as_str() + } else { + "127.0.0.1" + } + ); + let before = must(&real, &["ps", "-aq"]); + let mut made = Made::default(); + made.real.clone_from(&real); // BORROW: the cleanup owns its client path + + let context = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/docker/fakemodel"); + let tag = format!("candler-fakemodel:parity-{}", std::process::id()); + must( + &real, + &[ + "build", + "-q", + "--label", + "candler.test=parity", + "-t", + &tag, + context, + ], + ); + made.images.push(must( + &real, + &["image", "inspect", "--format", "{{.Id}}", &tag], + )); + let fake = must( + &real, + &[ + "run", + "-d", + "--label", + "candler.test=parity", + "-p", + &publish, + "-e", + &format!("FAKE_TOKEN={TOKEN}"), + "-e", + &format!("FAKE_HOST={host}"), + &tag, + ], + ); + made.containers.push(fake.clone()); // BORROW: the cleanup owns its ids + let port = must(&real, &["port", &fake, "8443/tcp"]) + .lines() + .next() + .and_then(|line| line.rsplit(':').next()) + .expect("a host port") + .to_owned(); + assert!( + wait_for(Duration::from_secs(30), || { + docker(&real, &["exec", &fake, "test", "-f", "/tmp/fake/ca.pem"]) + .status + .success() + && docker(&real, &["logs", &fake]) + .stdout + .windows(5) + .any(|w| w == b"ready") + }), + "the fake model is ready" + ); + let scratch = tempfile::tempdir().unwrap(); + let ca = scratch.path().join("ca.pem"); + must( + &real, + &[ + "cp", + &format!("{fake}:/tmp/fake/ca.pem"), + &ca.display().to_string(), + ], + ); + let endpoint = format!("https://{host}:{port}"); + + // one experiment file; only the harness line differs + let base = { + let shape = world(); + let text = fs::read_to_string(&shape.experiment) + .unwrap() + .replace(&shape.skills.display().to_string(), "@SKILLS@"); + text.replace("\"plan\"", "\"bypassPermissions\"") + .replace("\"fixture-model\"", "\"p1\"") + .replace( + "say hello", + "Call the MCP tool stamp of the server parity once, then reply done.", + ) + .replace("wall_s = 30", "wall_s = 300") + .replacen( + "[harness]\nname = \"claude-code\"", + "[harness]\nname = \"@HARNESS@\"", + 1, + ) + + &format!( + "\n[fixed.mcp.servers.{SERVER}]\ncommand = \"python3\"\nargs = [\"servers/parity/parity_mcp.py\"]\n\n\ + [[inputs]]\nkind = \"servers\"\npath = \"inputs/servers\"\nat = \"servers/parity\"\n" + ) + }; + let claude = experiment(&base, "claude-code"); + let opencode = experiment(&base, "opencode"); + assert_eq!( + claude.replace("claude-code", "@HARNESS@"), + opencode.replace("opencode", "@HARNESS@"), + "the harness is the only thing that differs between the two files" + ); + + let expected = json!({"kind": "mcp", "server": "parity", "tool": "stamp"}); + let mut failures = Vec::new(); + // each driver's MCP file: the directory of the run it is written under, and its path there + for (harness, text, place) in [ + ("claude-code", &claude, ("workspace", ".mcp.json")), + ("opencode", &opencode, ("home", "opencode/opencode.json")), + ] { + let skip = records(&real, &fake).lines().count(); + let seen = run_once(text, &endpoint, &ca, place, &mut made); + let answers = stamp_answers(&records(&real, &fake), skip); + if !answers + .iter() + .any(|(error, text)| !error && text.contains(STAMP)) + { + failures.push(format!( + "{harness}: the model never received the stamp from the tool: {answers:?}" + )); + } + let installed = seen + .mcp + .get(format!("mcp.servers.{SERVER}.command")) + .is_some(); + if !installed { + failures.push(format!( + "{harness}: no mcp.servers.{SERVER} in {}", + seen.mcp + )); + } + let resolved: Vec = + std::iter::once(seen.mcp[format!("mcp.servers.{SERVER}.command")].clone()) + .chain( + seen.mcp[format!("mcp.servers.{SERVER}.args")] + .as_array() + .into_iter() + .flatten() + .cloned(), + ) + .collect(); // BORROW: .clone() and .cloned() copy the resolved values + let rendered: Vec> = seen + .rendered + .iter() + .map(|config| { + argv_of( + config + .pointer("/mcpServers") + .or_else(|| config.pointer("/mcp/servers")) + .map_or(&Value::Null, |held| &held[SERVER]), + ) + }) + .collect(); + if rendered != [resolved.clone()] { + failures.push(format!( + "{harness}: the rendered file(s) at {place:?} hold {rendered:?}, the resolved command is {resolved:?}" + )); + } + let mcp_calls: Vec<&Value> = seen + .origins + .iter() + .filter(|origin| origin.get("kind") == Some(&Value::from("mcp"))) + .collect(); + if mcp_calls != [&expected] { + failures.push(format!( + "{harness}: MCP tool calls {mcp_calls:?} among {:?}, expected [{expected}]", + seen.origins + )); + } + } + drop(made); + assert_eq!( + must(&real, &["ps", "-aq"]), + before, + "no container is left behind" + ); + eprintln!("parity: {:?} wall", started.elapsed()); + assert!(failures.is_empty(), "{failures:#?}"); +}