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/AGENTS.md b/AGENTS.md index 77a7cd61..1ed63df7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,38 +3,20 @@ Candler is a Rust workspace (`crates/`). These rules apply to every `.rs` file and every document an agent writes here. Humans follow them too. -## Sustainable, scalable, efficient - -Everything produced or run here passes three tests. That covers the code, its tests and CI, every -script and document, and the work itself: each build, test run, model call and agent run. Nothing -runs in a silo. All of it shares the hardware, the quotas and the energy with other software and -other people. - -- **Sustainable:** a small RSS, CPU and GPU footprint, and with it disk, tokens and energy. What is - created has an owner that removes it. -- **Scalable:** code design patterns, known algorithms, easy-to-use scripts, DRY. One owner per - invariant, and one source per fact. -- **Efficient:** the smallest wall time. Think about how to be fast by default and how to use what - the hardware offers, in the spirit of Casey Muratori's Better Software manifesto. Don't - over-optimise. - -Before writing, running, reviewing or dispatching anything, answer: -1. What does it cost the shared machine and its energy? -2. Is it built from known patterns, algorithms and scripts, with nothing duplicated? -3. Is it fast by default here? - -A review checks these three alongside correctness. - -Cheap is not a reason to pay. A cost that looks negligible still counts: a free model call, an -extra agent, a rerun, one more check. Such flaws compound across the whole environment, and taking -the trouble to find the sustainable, scalable and efficient way is part of the work. - -These fail the tests: -- band-aids; -- defensive checks against the repository's own code; -- the same validation at a second layer; -- a special case kept for a fixture; -- a test added per incident instead of a fix at the root. +## What sane work means in Candler + +The README promises provenance, per-run tool census, and grading of artifacts "already on +disk". Those promises hold only if each kind of state Candler stores (a sealed run, its outputs, an +outcome, a tool census) has one producer, and that producer is Candler's own code. A test that +needs such a state asks Candler to make it, under a scripted agent if it must; it does not assemble +the state by hand, because a second producer can only agree with the first by luck. Where Candler +leans on something it does not own (a container daemon, a harness binary, a model), a stand-in is +fine for as long as a test that runs in CI holds it to the real thing. The README also promises +"thin surfaces over that API", so each input a consumer writes has one reader, below every surface, +and that reader refuses what it does not understand: a second, more lenient reading of the same +declaration is a defect even when nothing reaches it yet. A change is done when a consumer's path +through it has been seen working, and seen failing without it; how many tests or lines it moved says +nothing either way. ## Rust: Grit @@ -102,3 +84,5 @@ files are regenerated with `CANDLER_BLESS_SCHEMAS=1 cargo nextest run -p candler and integration. - [__design__/architecture.md](__design__/architecture.md): the architecture, the crate layout (§Workspace) and the wire encodings (§Wire encodings). +- [__roadmap__/leaf_template.md](__roadmap__/leaf_template.md): the shape of a roadmap leaf and the + conventions behind it. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5019d1f6..fffad7f2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,7 +46,7 @@ A scope names the topic of the commit, never the action or a layer (`core`, `mis | Area | Scopes | |---|---| | Operation API | `api`, `resolve`, `jobs`, `budgets` | -| Execution | `experiment`, `orchestrator`, `runner`, `isolation`, `injection`, `census`, `catalog` | +| Execution | `experiment`, `orchestrator`, `runner`, `isolation`, `injection`, `census` | | Ingestion | `trace-model`, `adapter-claude-code`, `adapter-opencode` (one `adapter-` per harness), `importer` | | Storage | `run-store`, `manifest`, `outcome-store` | | Evaluation | `evaluation`, `outcome-algebra`, `evaluator-protocol`, `registry`, `evaluator-helper` (the Python package in `python/candler-evaluator`) | diff --git a/Cargo.lock b/Cargo.lock index 9ffbf988..09cdf9cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -300,10 +300,12 @@ dependencies = [ name = "candler-harness" version = "0.15.0" dependencies = [ + "candler-core", "candler-schemas", "semver", "serde", "serde_json", + "serde_path_to_error", "thiserror", ] @@ -311,6 +313,7 @@ dependencies = [ name = "candler-harness-claude-code" version = "0.15.0" dependencies = [ + "candler-core", "candler-harness", "candler-schemas", "candler-testkit", @@ -327,6 +330,7 @@ dependencies = [ name = "candler-harness-opencode" version = "0.15.0" dependencies = [ + "candler-core", "candler-harness", "candler-schemas", "jiff", diff --git a/README.md b/README.md index 83d9467e..eaae4cd8 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,13 @@ A domain-agnostic core for evaluating LLM-based agents. Candler has two equal ha operation API: - **Execution:** run agents under controlled conditions (experiment matrix, runners, isolation, - per-run tool-catalog snapshots, provenance). + per-run tool census, provenance). - **Evaluation:** grade traces and artifacts, fresh or already on disk, through pluggable evaluators that emit one outcome record format. A library, a lean CLI and an MCP server are thin surfaces over that API. Domain science (for -example the HTN-creator evaluation) plugs in as evaluators, suite specs, fixtures and catalog -providers. The core names no domain. +example the HTN-creator evaluation) plugs in as evaluators, suite specs and fixtures. The core +names no domain. Candler runs and grades LLM-based agents under controlled conditions, and compares the results with statistics that say what they can and cannot support. diff --git a/__design__/architecture.md b/__design__/architecture.md index cdb0f387..95a62328 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -69,7 +69,6 @@ graph TD subgraph EXE [Execution] ORCH[orchestrator: matrix, run identity, resume, budgets] --> HD{harness driver: Claude Code, OpenCode v2, ...} ORCH --> ISO{isolation: host or container} - ORCH --> CAT[catalog providers: snapshot per run] HD -.describes.-> SUP end subgraph ING [Ingestion] @@ -95,7 +94,7 @@ graph TD MAN[plug-in manifest] --> REG SS[suite file] --> REG EV[evaluator command + pinned checker library + Python helper] -.declared by.-> MAN - FX[fixtures, inputs, catalog providers] --> ORCH + FX[fixtures, inputs] --> ORCH end ``` @@ -106,7 +105,7 @@ graph TD | Operation API | The operation set, argument resolution with the source of every value, jobs, budgets, confirmations | Any domain notion | | Job supervisor | Job identity, the job directory, the event stream, cancellation | What a run or an outcome means | | Process supervisor | Every process Candler starts (agents, evaluators): spawn into its own process group, child records, deadlines, stop escalation, stray sweep, machine-wide slots | Harness or evaluator semantics | -| Execution | Experiment matrix, run identity, resume, isolation, catalog snapshots, artifact collection | What the artifacts mean | +| Execution | Experiment matrix, run identity, resume, isolation, the resolved MCP configuration, artifact collection | What the artifacts mean | | Harness drivers | Harness-specific data: config files, command line, stop action and signal, exit classification, what to collect, version detection | Starting, timing or killing processes | | Ingestion | Trace readers, the normalised trace model, the legacy importer | Judgement | | Run store | Run identity, content-addressed artifacts, the workspace view, manifest, integrity, the invalid-run ledger | Grades | @@ -479,7 +478,7 @@ the gateway, the reader, the trace's gateway signals, collection, input leak, th (`container-record/1`: `{cid, labels {job, run, experiment}, created_at, image_id, role: agent|gateway, spawned_at}`) and the labels `candler.job`, `candler.run`, `candler.experiment` and `candler.role` (`agent` or `gateway`, which the destroy guard reads). A control container - (a version readout, a catalog capture, the image build) is the exception: `--rm`, only the label + (a version readout, the image build) is the exception: `--rm`, only the label `candler.role=control`, and no network except for the image build, which reaches the package index over the default bridge; no sweep meets it and the guard never destroys it. The entrypoint runs under `timeout `, so an orphaned container expires by itself @@ -621,7 +620,7 @@ the gateway, the reader, the trace's gateway signals, collection, input leak, th | `isolation.record_packages` (read from the env image, recorded in `measured[]`, never in the cell) | setting | | `isolation.build.plugin` (`/`: the plug-in agent environment the experiment selects; §Plug-ins) | setting | | `request.harness`, `request.treatment`, `request.inputs`, `model.token_secret` | setting | - | `harness`, `treatment`, `inputs[]`, `snapshots`, `environments` (reserved) | typed root | + | `harness`, `treatment`, `inputs[]`, `snapshots` (an imported run's cell only), `environments` (reserved) | typed root | A CLI path resolves against the caller's cwd, a path in the experiment file against that file's directory (I14). @@ -688,11 +687,11 @@ I3, so event times are reproducible even where the harness emits none. | Classify the exit | Exit status, output tail and the parsed sessions → `ended_by` | Codes, messages, error results | | Collect | Files, or the output of an export command | Home-dir transcripts, stdout, a SQLite store | | Read offline | Parse a trace on disk, no process | Line streams or whole documents; format versions | -| Census | The tool catalog the agent actually had | How to list built-in and MCP tools | +| Census | The tools the agent actually had | How to list built-in and MCP tools | ### Traits (signatures only) -Every item added for the second harness (`settings_table`, `check_settings`, `gateway`, +Every item added for the second harness (`answer`, `fact`, `check_settings`, `gateway`, `state_paths`, `census_stream`, `session`, `session_tracker`, `classify_end`) has a default body, so a driver implements only what its harness has. @@ -700,11 +699,11 @@ implements only what its harness has. - `id() -> HarnessId`; `supported() -> VersionReq` - `version_probe() -> CommandSpec`; `parse_version(output) -> Version`; the core runs the probe in a control container of the base image - - `capabilities() -> Capabilities { graceful_stop, live_events, budgets{turns, cost}, in_harness_guard, census, execution_outside_child, session }` + - `fact(DriverFact) -> Answer`: what the harness does about each of its own facts, such as the graceful stop, the census and the session - `prepare(cell, workspace) -> Prepared { files[], env_overlay }`, where a file is rooted in the workspace or in the agent's home (`FileRoot`) - `command(cell, workspace) -> CommandSpec { argv, env_overlay, cwd }` - - `settings_table() -> SettingRow[]`: one row per cell setting, value or name the driver knows, + - `answer(AgentSetting) -> Answer`: one answer per setting family, value or name the driver knows, `Mapped` (with the harness construct it writes) or `Refused` (with the reason). The driver builds its command and files from the same rows. A setting the harness cannot honour is refused with `experiment.setting_unsupported`, naming the setting's pointer, never dropped @@ -816,8 +815,9 @@ version and by the sha256 of the release archive of each architecture. `{env:CANDLER_GATEWAY_URL}/v1` and `{env:CANDLER_GATEWAY_TOKEN}`, which the core sets, so the token never enters a file. Each MCP server is written in the V2 shape `mcp.servers.` with `codemode` always explicit: MCP code mode is on by default in OpenCode and bundles a server's - tools into one `execute` tool, so an absent cell value is written as on, and `codemode` is a cell - value under `mcp.*`, a treatment factor (I7). A server shape the driver cannot translate is + tools into one `execute` tool, so the resolved cell holds `codemode = false` for a server that + leaves it out, and `codemode` is a cell value under `mcp.*`, a treatment factor (I7). Claude Code + has no code mode and refuses `codemode = true`. A server shape the driver cannot translate is refused. - **State.** `XDG_DATA_HOME`, `XDG_CONFIG_HOME`, `XDG_CACHE_HOME` and `XDG_STATE_HOME` are directories under the agent's home and `OPENCODE_DB` is the file `.xdg/data/oc.db` (SQLite in WAL @@ -861,10 +861,9 @@ version and by the sha256 of the release archive of each architecture. - **Census.** No event, command or export lists OpenCode's tools. The tool names in the request the agent sends to the model are the inventory, so the gateway sidecar records the names of each request, and the core takes the first request that carries tools (`census_stream`, - `census.source = gateway`). Servers are not seen, so `census.mcp_servers` is unrecorded for this - source, and a run whose requests carry no tools records no inventory. The verdict never takes a + `census.source = gateway`). A run whose requests carry no tools records no inventory. The verdict never takes a gateway inventory for a harness's own. -- **Capabilities.** `graceful_stop`, `census` and `execution_outside_child`. Not `session`. +- **Facts.** `graceful_stop`, `census` and `execution_outside_child`. Not `SessionMode`. - **Not exercised.** Reasoning events (`--thinking`), a code-mode `execute` call in a recorded run, permission prompts without `--auto`, resume, and the interrupt and a mid-tool SIGTERM against a real model: the recorded cases come from the scripted fake model. @@ -1042,6 +1041,10 @@ the evaluators see never enters the isolation, I8); `metadata` (the declared man evaluator runs (host or container) and exist only in requests. `scratch` is the evaluator's; the run store is read-only to it. +`needs.snapshots` and `context.snapshots` are always empty for runs Candler makes. They are kept so +the released helper and stored grading contexts stay valid, and they go once a helper that treats +them as optional is released. + **Digests of a request.** Both are `sha256` over RFC 8785 JSON, so any language recomputes them. - `context_digest` covers the projection `{artifacts: [{path, sha256}], snapshots: [{kind, @@ -1090,7 +1093,6 @@ erDiagram SESSION ||--o{ EVENT : ordered SESSION ||--o{ SESSION : "spawned (subagents)" RUN ||--o{ ARTIFACT : "left behind" - RUN ||--o{ CATALOG_SNAPSHOT : targeted RUN ||--|| MANIFEST : provenance PLUGIN ||--o{ EVALUATOR_VERSION : provides SUITE ||--o{ EXPECTATION : declares @@ -1130,8 +1132,8 @@ host?, job?, integrity, import?, evaluation_inputs[]?}`. - **`comparable`** `{values[] {path, value?}, harness {name, version, driver?}, treatment, snapshots[], inputs[], environments[]}`: every resolved value by field path (isolation under - `isolation.*`), the harness, the treatment reference (name, tag and commit), the catalog snapshot - and input digests, and the plug-in environment lock digests. A value without `value` was + `isolation.*`), the harness, the treatment reference (name, tag and commit), the input digests, the + plug-in environment lock digests and, for an imported run, the catalog digests it recorded. A value without `value` was `unrecorded`. Every list rises strictly by its key, so it is sorted and holds no duplicate: `values` by path, `snapshots` and `inputs` by kind then digest, `environments` by plug-in then lock digest. A reader refuses a list that does not. @@ -1141,8 +1143,10 @@ host?, job?, integrity, import?, evaluation_inputs[]?}`. it, and a string value that is an absolute path is refused: a file enters a cell as an `inputs[]` digest. The per-run caps are cell values under `budget.per_run.*`; the job caps (every other `budget.*` path) and `replicates` are operational settings, which `resolve` classifies by path. A - snapshot's digest is that of its RFC 8785 form without `captured_at`; an imported snapshot's - digest is the bare sha256 its legacy provenance recorded, which a live snapshot's never equals. + `snapshots` is the imported old shape: an imported run's cell lists the bare sha256 its legacy + provenance recorded, and the cell hashes it with the list, empty or not. A cell Candler makes + carries no `snapshots` key and hashes without it. A run's MCP servers are its resolved `mcp.*` + values. - **The treatment reference** `{name, tag?, commit?}` holds no source. A live run's carries the commit its source resolved to whenever the treatment names a tag or a commit; an imported run's carries none, since the legacy folder records none. @@ -1224,8 +1228,7 @@ levels over every arm of the class; a live class gets no such exemption. **Session and census measures.** A session run records the `session.*` values of §Session runner and `session.control`. A census whose source is not the harness's own init event also records `census.source` (`gateway` or `collected`); a record without it is the harness's own, and a verdict -never compares an inventory with one of another source. `census.mcp_servers` is recorded only when -the source sees servers. +never compares an inventory with one of another source. The census names no server. ### Normalised trace model (`normalised-trace/1`, on the `schemas@` line) @@ -1284,26 +1287,12 @@ the latest complete request wins. Differing outcomes under one key, other than a `instrument_error` or `deadline` replaced by a measured one, are reported as I4 violations. Roles and weights are read from the outcomes, never from today's suite. -### Wire schema: tool-catalog snapshot - -What the MCP servers a run targets actually offered, captured per run by a catalog provider. HTN's -Tier D grades a mapping against it, the run manifest records its digest as a comparability field -(I7), and evaluators receive it through `needs.snapshots[]`. - -`schema: "tool-catalog-snapshot/1"`, `captured_at`, `provider@version`, `environment?` (string → -string: versions the capture depended on), `ext?` (opaque, provider-specific), `servers[] {name, -source_path, source_digest, transport (stdio / http / sse), tools[]}`. Tools are in MCP -`tools/list` shape, camelCase kept: `name`, `inputSchema`, `title?`, `description?`, -`outputSchema?`, `annotations?`, and every other key preserved as given. HTN's -`tool-catalog-snapshot/0` is this shape with `servers_dir` and `stubbed_modules` at the top level; -its capture script and loader move them under `ext`. +### The MCP configuration of a run -Server names are unique within a snapshot and tool names within a server, compared byte for -byte; both are non-empty. A reader keeps every key of a tool, `ext` and `environment`, and every -value, except: keys not defined for a snapshot or a server are dropped; of repeated keys the last -is kept; object keys are sorted; numbers are held as `i64`, `u64` or `f64`, so an integer beyond -the 64-bit range becomes a float, a decimal beyond `f64` precision is rounded and a magnitude -beyond `f64` is refused; and text nested deeper than about 120 levels is refused. +A run's MCP servers are the resolved `mcp.*` values in `comparable.values`, which the cell digest +hashes and `inspect` shows. Candler stores no capture of what a server offered: the tools the +harness had are the census's list, and the calls are in the trace. `tool-catalog-snapshot/1` is +the HTN consumer's own schema, not Candler's. ### Wire encodings @@ -1318,10 +1307,10 @@ The rules every wire type of the `schemas@` line follows. | Unknown fields | Schemas are strict (`additionalProperties: false`): they define what a writer at that version emits. Readers of the records Candler writes ignore unknown fields, so that an older reader reads a newer record. Readers of the three author documents (experiment, suite, plug-in manifest) refuse an unknown field with `.unknown_field` and its pointer (§Refusals). Every reader reads objects only, never a struct written as an array. MCP tool objects, `inputSchema`, `outputSchema` and `ext` are open. | | Run key | `{"cell": "sha256:", "replicate": n, "attempt": m}` in records, both counters from 1. Paths and `CANDLER_RUN` use `-r-a`. | | Digests | `sha256:` + 64 lowercase hex; blob paths use the bare hex. An instrument digest may also be `git:<40 or 64 hex>`, a commit of a clean tree, valid only with `dirty: false`. Digests of JSON values (`suite_entry_digest`, `context_digest`, the cell digest) are taken over RFC 8785 canonical JSON. | -| `name@version` | Split at the last `@`; the name has no `@` or whitespace. Evaluator and instrument versions are SemVer 2.0; a catalog provider's version is a free token `[0-9A-Za-z.+-]+`. | +| `name@version` | Split at the last `@`; the name has no `@` or whitespace. Evaluator and instrument versions are SemVer 2.0; a step name's version is a free token `[0-9A-Za-z.+-]+`. | | Ids, paths, times | `request_id`: UUIDv7, lowercase hyphenated. `expectation_id`: `^[A-Za-z0-9][A-Za-z0-9._-]*$`. Run-relative paths: POSIX, non-empty, no leading `/`, no empty, `.` or `..` segment, no `\`. Timestamps: RFC 3339 with an uppercase `T`, and `Z` or a `±HH:MM` offset, naming a real instant, kept as written. | | Evidence refs | `event:#`: the session id is non-empty, without `#` or white space; `seq` is a decimal without leading zeros (`0` allowed). `path:` optionally followed by `#L` or `#L-`: lines count from 1, `n ≤ m`, and the path holds no `#`. | -| Version marker | A standalone document (the catalog snapshot) carries its `schema` tag. Records that travel inside versioned messages or files (the outcome record) carry none. | +| Version marker | A standalone document (the `inspect` record) carries its `schema` tag. Records that travel inside versioned messages or files (the outcome record) carry none. | | Schema files | JSON Schema 2020-12, generated by `schemars` from the structs, one self-contained file per root in `crates/candler-schemas/schema/.schema.json`, `$id` `urn:candler:schemas:`, no crate version inside. Cross-field rules are `if`/`then` clauses; rules JSON Schema cannot state (`num ≤ den`, the pass and fail weight rules, unique names, 64- and 32-bit integer limits) are enforced in Rust and stated in a `$comment`. Patterns end with `(?![\s\S])` in place of `$`, and spell white space as Unicode's `White_Space` set plus the byte-order mark in place of `\s`: Python's `re`, which Python `jsonschema` uses, lets `$` match before a final newline and gives `\s` a different set, so only this form reads alike under ECMA 262, Rust and Python. The regexes this document writes with `$` (reason codes, ids, field paths) are published in this form. A test refuses any published pattern that uses `$` or `.` outside a character class, or a shorthand class or assertion (`\s`, `\d`, `\w`, `\b`, `\A`, `\Z`, `\p` and their negations) anywhere but in the end anchor, and requires every pattern to end with the anchor except one inside an `if`, such as the prefix `^git:`, which only tells variants apart; the other refusals still apply to it. `///` docs become `description`s, so a doc edit on a wire type is a schema patch. | | Drift check | `tests/schema_drift.rs` compares every root in `generated_schemas()` byte for byte with its committed file; `CANDLER_BLESS_SCHEMAS=1` rewrites them. | | Rust shape | Wire structs are `#[non_exhaustive]`, built through validating builders and deserialised through `try_from` from a JSON object only (never an array), so a record is valid however it was made and a new optional field is a minor in Rust as in the schema. Evolving enums are `#[non_exhaustive]`; `Status` and `Role` are closed. `serde_json` has `float_roundtrip`. JSON text holding an unpaired surrogate escape is refused by the Rust reader. | @@ -1329,7 +1318,7 @@ The rules every wire type of the `schemas@` line follows. ### The `schemas@` line holds -Outcome record · catalog snapshot · raw frames · normalised trace (header, session, event records) +Outcome record · raw frames · normalised trace (header, session, event records) · workspace tree (`run-tree/1`) · child record · evaluator messages (`describe` result, `evaluate` params, notifications, and the request side: method names, `{reported}` and `-32800`) · plug-in manifest · suite file · run manifest · job record, event envelope and event payloads · experiment file. All are generated from `candler-schemas`. @@ -1552,7 +1541,6 @@ request files under the new evaluator version; `diff` compares versions. ### Other interfaces (signatures only) -- `CatalogProvider.snapshot(cell) -> catalog_snapshot` - `Isolation`, one container per run: `plan(cell, workspace) -> ContainerPlan`; `run_request(plan, command, marker, run key, outputs) -> IsolatedRequest` (the spawn request, with the run's stop hook attached, and the handle that reports the end facts); @@ -1654,7 +1642,7 @@ lists it in the index and leaves its file alone. **Reference, done 2026-10-28.** The 240 runs of 2026-08-06 (12 cells: Haiku 4.5, Sonnet 4.6, Sonnet 5 × skill v0.2.3–0.2.6, 20 runs each, rikyu domain), regraded by `htn-creator-eval@0.4.2` -(mcp-python-ingestion `28be2c15`, clean tree) against rikyu's own catalog snapshot. Frozen in +(mcp-python-ingestion `28be2c15`, clean tree) against the HTN's own committed tool catalog for the rikyu domain. Frozen in `agenticai4hpc26-artifact` on branch `regrade/htn-creator-eval-0.4.2`, commit `7efa1b7`, tag `candler-m2a-golden`; the published `main` is untouched. `expectations.jsonl` holds one row per `(run, expectation)`: 10,320 rows. @@ -1706,7 +1694,7 @@ input the legacy importer reconstructed (importer defect) → anything left is a | `comparable.values` | `experiment.json` `plan.*`, `provenance.*`, and the top-level key the import rules name for the version the treatment resolved to (`resolved_skill_version` here) | Each JSON leaf becomes a dotted field path with source `imported{experiment.json}`; a `null` leaf has no value and is `unrecorded`. `plan.out_dir` goes to `import`. | | `comparable.harness` | the harness name the import rules give, and the version at their JSON pointer into the stream's first line (`claude_code_version` here) | Must agree across a cell, else the import is refused | | `comparable.treatment` | `experiment.json`, at the JSON pointer the import rules name | A string written `@`, else the import is refused; it gives the name and tag, and no commit, which the legacy folder does not record | -| `comparable.snapshots[]` | `PROVENANCE.json`, at the JSON pointers the import rules name | One entry per snapshot rule: the rule's kind and the bare sha256 the legacy provenance recorded at its pointer, not the RFC 8785 form a live snapshot's digest is taken over | +| `comparable.snapshots[]` | `PROVENANCE.json`, at the JSON pointers the import rules name | The imported old shape, and only an import writes it: one entry per snapshot rule, with the rule's kind and the bare sha256 the legacy provenance recorded at its pointer | | `comparable.inputs[]` | each run's `timing.json` `copied_inputs[] {role, sha256}` | `role` is the kind; the lists must agree across a cell, else the import is refused | | `comparable.environments[]` | — | Empty: the legacy folder records no plug-in environment | | `measured` | each run's `eval_metadata.json` `provenance.*`, where the cell-level value is `null` | Source `imported{}`; the copies within one run must agree, else the import is refused | @@ -1801,7 +1789,6 @@ turns a plan into a spawn request, then collects and destroys. | SIGCHLD-driven reaping (A3) | Reap children on signal instead of by polling | Less polling, faster exit facts | A measured reap delay or a missed exit | | Long-lived workers | A worker that serves many runs | Start-up cost per run | A measured start-up cost that dominates a run | | Signals error versus census | One ruling for `runner/exec/mod.rs:777`, which reads a signals error as "gateway did not fail" while the census reads it as "not collected" | The two readings can disagree on the same fact | The next change to either reader | -| Catalog capture of input-delivered servers | A mount seam in `catalog_spec` and an inputs-aware provider | The per-run catalog cannot see servers delivered through inputs | An eval that must grade against the run's own captured catalog of input-delivered servers, or an automated snapshot-versus-live check | | URL-path allowlist | An allowlist that admits part of a host, through TLS interception at the proxy | The proxy reads only the SNI, so it cannot tell two paths of one host apart | An eval that must allow part of a host | | Domain fronting | Closing the residual that a listed host behind a shared CDN front is reachable under another name | The SNI rule trusts the name the client presents | A listed host behind a shared CDN front | | Transformed copy of ground truth | Detection of ground truth that was encoded or reformatted before it reached the boundary | Digests of the original miss a transformed copy | A leak that digests missed | @@ -1827,7 +1814,7 @@ turns a plan into a spawn request, then collects and destroys. | One sealing step for importers (B4) | An importer whose trace reader fails seals the run invalid, as raw ingest does | One integrity rule for every import | Eliott's ruling; no external user depends on today's behaviour | | One `Comparable` diff (B10) | One diff for the comparability verdict | Fewer copies | A change to the shape of recorded deviations | | fsync budget and streaming import (B6, B8) | A bounded fsync cost and an import that streams | Crash guards cost time, and a large import peaks in memory | A measured cost or memory peak that hurts | -| Static tool catalog, `as_bytes`, refusal codes, shared outcome vectors (C5, C9, C10–C12) | Small consistency work | Fewer drifting copies | The next change that touches one of them | +| `as_bytes`, refusal codes, shared outcome vectors (C5, C9, C10–C12) | Small consistency work | Fewer drifting copies | The next change that touches one of them | | `lock_split` | `lock_split` reads the plug-in's requirements from the fragment and the experiment's from the resolved value | The two sources can disagree | A plug-in whose fragment and resolved requirements differ | | Paired designs | McNemar for designs that pair runs | Runs are unpaired today (§Analysis statistics) | A design that pairs replicates | | Declared margin | A margin declared in the experiment, read with TOST | "No difference" is never stated today | An experimenter who needs equivalence | @@ -1864,7 +1851,7 @@ The milestones, their order, exit gates and scope are in the meta-roadmap [`__roadmap__/candler-v1/`](../__roadmap__/candler-v1/README.md). Each milestone is planned in detail by its own session, as its own campaign under `__roadmap__/`. -HTN lane: HTN Phase 4.5 reads the catalog snapshot; Phase 7 writes its Tier C logic as library +HTN lane: HTN Phase 4.5 reads its own catalog snapshot; Phase 7 writes its Tier C logic as library functions; after M2a the checker library becomes the plug-in and `eval.json` becomes a suite file (no templates); Phase 8 waits for M5. The reasoning is in `/Users/hacker/Documents/src/External/PCfVW/mcp-python-ingestion/__reports__/candler_core/02-findings_lane_overlap_v0.md`. diff --git a/__reports__/diet/05-findings_dogfooding_pass_v0.md b/__reports__/diet/05-findings_dogfooding_pass_v0.md new file mode 100644 index 00000000..e93cdbd6 --- /dev/null +++ b/__reports__/diet/05-findings_dogfooding_pass_v0.md @@ -0,0 +1,226 @@ +# Findings: the dogfooding pass, runner's record (v0) + +Tip: `origin/feat/integrity` at `aaf08f16`. Written by the runner; the Claude reader's check of the classification and the knowledge transfer follow. **Verdict of the pass: it did not produce its signal.** Neither agent ran an experiment, so steps 1 to 5 of the task are not done by either, and F3/F4 has no real OpenCode run to read. Two setup faults of the runner's are named below (cap too tight; rustdoc carries source pages). One attempt each was the rule, so nothing was rerun. + +## Setup + +| Item | Value | +|---|---| +| Consumer A | `RiVault/Reasoning-Medium` (DeepSeek-V4-Flash, live 2026-11-24), OpenCode 1.18.23 | +| Consumer B | `RiVault/Reasoning-Large` (XiaomiMiMo MiMo-V2.6-Pro-RL), OpenCode 1.18.23 | +| Model under test in the brief | `RiVault/Agentic-Small` (Qwen3.6-35B-A3B) | +| Caps | 150 steps (OpenCode `agent.build.steps`), 5400 s wall (`timeout`). Set by the runner: P1's probe shows a scripted native run costs about 4.5 s, so 12 runs would cost about a minute of Candler time; the step cap was sized for that and not for reading the documentation. | +| VPN and keys | `rv_health.py`: network, llm, embedding, audio, ocr, jev all ok | +| Binary | `cargo install --path crates/candler` from the tip, `candler 0.15.0` | +| Consumer material | `bin/candler`, `README.md`, `docs/`, `rustdoc/` (from `cargo doc --workspace --no-deps`), `TASK.md` (the brief), `opencode-rivault.json` | +| Scratch root | `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7` | +| Brief | `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/task-brief.md` (copied to each consumer as `TASK.md`) | +| Transcripts | A: `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/transcript-a.jsonl`; B: `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/transcript-b.jsonl` (OpenCode `--format json`); launcher `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/run_consumer.sh`; timings `transcript-*.jsonl.meta` | +| Workspaces / stores | `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/consumer-a/`, `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/consumer-b/` (`store/` in B is empty; neither ran `candler run`) | +| Digest and classification files | `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/digest.py`, `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/classify.sh`, `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/classify-prompt.txt`, `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/classify-output.md` | + +Setup faults found after the runs (both mine, both visible in the transcripts): +1. **The rendered rustdoc contains source pages** (`rustdoc/src//.rs.html`: `cargo doc` writes them by default). Both agents read Candler's source through them (A step 15 on, with a helper that strips tags; B wrote `tools/rustdoc_extract.py` that turns them back into plain Rust and had subagents map the code). This breaks "no source tree". It is not "crate source in cargo's dependency directory": a regex over every tool input for `.cargo/registry|.cargo/git` or any path outside the consumer directory finds none for either agent. +2. **The 150-step cap was too tight**: A used all 150 steps in 209 s and wrote only `NOTES.md` and a helper. B stopped at 102 steps (rc 0, 3926 s) with incoherent final text (e.g. "Resuming the task. I was at: pinned down the catalog/DNS point (MiTM ...") and no experiment. + +A rerun needs: `rm -r rustdoc/src` (or `--no-source`-style rustdoc), a step cap above 150 and a wall cap from a measured real OpenCode-in-container run. That is the lead's call. + +## Runs + +| | A (Reasoning-Medium) | B (Reasoning-Large) | +|---|---|---| +| Wall (launcher) | 209 s | 3926 s | +| Model steps | 150 (cap reached) | 102 | +| Tokens: new input / output / reasoning | 253,757 / 16,552 / 7,046 | 215,020 / 22,848 / 443,140 | +| Tokens: cache read | 19,880,192 | 12,861,072 | +| Reasoning above 0 | yes | yes | +| Per-step latency | about 1.4 s (209 s / 150) | about 38 s (3926 s / 102) | +| `candler` calls | `--version`, `--help` of run, resolve, ls, evaluate, inspect | `--help` of run, evaluate, resolve, inspect, show, ls | +| Candler's own run times | none: no `candler run` | none | +| Opened crate source in cargo's dependency directory | no | no | +| Read Candler source through `rustdoc/src` | yes | yes | +| Files left | `NOTES.md`, `tools/rd.sh` | `NOTES.md`, derived Rust extracts, empty `store/`, several planning directories | +| `RESULT.md` | none | none | + +Token counts are the sum of OpenCode `step-finish` records. No USD: RiVault tokens only. Docker: no container, image or network appeared during the pass. + +## S6 + +Neither agent found the stored catalog from the documentation alone. Both reached the format (`tool-catalog-snapshot/1`) only by reading source through `rustdoc/src`; neither reached a stored catalog because neither ran anything. No contract page documents it, as seam review 2 found. + +## F3/F4 + +**BLOCKED.** The gate compares the stored outputs of a real OpenCode run of the pass with the files the agent wrote in its workspace. The pass produced no OpenCode run, so there are no two lists and no difference. The conformance revert is the only evidence for the producer side (see `collect_oracle_v0.md`). + +## Golden + +Command: `cargo nextest run --workspace --run-ignored all -E 'test(/golden/)'` with `CANDLER_GOLDEN_CORPUS=/Users/hacker/Documents/tmp/candler-m1-golden/campaign/20260806-cont-train` (the path every M1 to M5 roadmap README gives; `guard_analyze_golden.rs` and `candler-core/README.md` name the variable and no path) and `CANDLER_HTN_PLUGIN` (named by `guard_golden_parity.rs`). Log: `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/golden2.log`. + +**Verdict: FAIL.** 18 tests run: 15 passed, 3 failed, none skipped. Passed: the five `outcome_golden` guards of candler-schemas, `guard_golden::the_golden_corpus_imports_to_the_oracle_rows` and `..._runs`, the three `guard_analyze_golden` tests, the three `guard_golden_design` tests. Failed, all in `guard_golden_parity`: `the_second_regrade_sends_new_requests_and_changes_nothing`, `the_live_ac_rows_and_rates_equal_the_reference`, `the_version_diff_compares_everything_it_can_and_excuses_only_the_named_rows`. Cause: the fixture build's import is refused, `config.import_rules_invalid`, `candler-plugin/import/htn-results-rules.toml`: "missing field `entry_params`". The plug-in used is the `htn-creator-eval@0.5.2` tree exported with `git archive` from the mcp-python-ingestion repo into a throwaway git repository, because the guard asks git for the tracked files (a first attempt without a repository failed with "git listed ..."). The guard names 0.5.2; `0.5.3` exists (`cdc067fb`, "tool-catalog-snapshot/1") and was not tried. Whether the fault is the plug-in version or the tip's rules schema is not settled here. + +## Before tip + +| Cause | Observation | Verdict | +|---|---|---| +| Malformed MCP server (D5) | Tip's `guard_cli_observe::o1_resolve_and_run_refuse_a_malformed_mcp_server_with_one_record` copied into a detached `origin/main` tree (`c9572e5b`) with its `support/cli_run.rs`: FAIL at `guard_cli_observe.rs:377`, `resolve` exits 0 where 2 is expected. The same test on the tip: PASS (1.6 s). Logs: `before-tip-mcp-main.log`, `before-tip-mcp-tip.log`. | cause gone: PASS | +| S1 revert | Not re-run. `sealed_run_producer_v0.md` §Bites already shows it on the base and tip (5 guards fail on the tip, output guards green on the base). | cited, not re-observed | +| B1 revert | Not re-run. `collect_oracle_v0.md` §Bites. | cited, not re-observed | +| Plug-in path layout (`context.root/path` meeting `outputs/outputs/...`) | No transcript reaches it: no run, no evaluator. | not judged | +| audit-1 (cell count in `resolve`) | No transcript reaches it. | not judged | + +## Frictions + +First pass only, by `RiVault/Reasoning-Medium` (prompt 64,723 + completion 13,578 tokens, reasoning 13,230, finish stop), with plan v2's table, from digests of both transcripts. Output kept as it returned (`classify-output.md`). A first call (effort high, 12,000 tokens) used all its tokens in reasoning and returned nothing (`classify-output-1-empty.md`). Not yet checked by the reader. + +| # | friction | model A | model B | evidence (step numbers) | class (1-4 or harness) | one-line reason | +|---|---|---|---|---|---|---| +| 1 | Where each run stores its tool-catalog snapshot (and catalog digest) is not documented in any contract page. | needed | needed | A [105–112,116–117]; B [25,67] | 3 | The catalog and `snapshots` digest exist in `catalog.rs` / `store/layout.rs`, but no `docs/contract` page names the storage path; agents could only find it via rustdoc source. | +| 2 | Rustdoc includes rendered source pages (`rustdoc/src/`), even though the brief says “there is no source tree.” | used heavily | used heavily | A [15–65,105–148]; B [16–33] | harness | Not a Candler defect: the supplied surface contradicts the brief’s no-source-tree constraint. | +| 3 | Agent step cap (150 steps) ended model A’s session before any experiment artifacts were written. | hit | no | A [149] | harness | Harness-side limit, not Candler; A stopped after source exploration only. | + +Caveats: Both agents stopped before actually completing a `candler run`/`evaluate` flow, so the table records discovery-time frictions, not execution failures. The “catalog not documented” row is based on the absence of a contract page and on the agents reaching the information only through rustdoc source views. The two harness rows are not Candler issues; they are artifacts of the evaluation setup. + +Runner's note on that first pass: row 3 says B did not hit the step cap, which is right (B ended at 102 steps with garbled text). Rows 2 and 3 are setup faults (mine), not frictions of Candler. The model's class 3 for row 1 rests on the absence of a contract page for the stored catalog; the reader should check whether `docs/` mentions it anywhere else. + +## Cleanup + +- Docker images, containers, networks created by the pass: none (before and after listings in `docker-*-before.txt` match). Nothing removed, nothing stopped, nothing pruned. +- Removed at the end: `integrity-target/p7`, `integrity-target/p7-main`, the `main-tree` detached worktree (`scratch/p7/main-tree`), `consumer-a/.target`, `consumer-b/.target` if present. +- Kept in scratch for the reader: transcripts, consumer directories, classification files, `golden*.log`, `htn-0.5.2/`, `main-bin/`. + +--- + +# Rerun (maintainer's one rerun with the setup fixed) + +The sections above are the first attempt and are unchanged. The rerun stopped at its cost cap (.5 of the runner's side) before the first classification and before the gates that need a reader; what was not reached is marked. + +## Rerun: F3/F4 (done first, before the consumers) + +One real run through `candler run`, harness `opencode` 2.2.7, container isolation, `RiVault/Agentic-Small`, a prompt that asks for three files (`a.txt`, `b.txt`, `notes/c.txt`). Experiment, treatment repository and store: `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/f34/` (`exp.toml`, `skills/`, `store/`). The experiment needed a treatment, `permission_mode`, a `.claude/skills/` tree in the treatment repository (the first refusal named it), and a `model.endpoint` without `/v1` (with it the model-list read answered 404). + +| List | Files | +|---|---| +| Written by the agent in its workspace (`runs//workspace`) | `.opencode/skills/demo/SKILL.md`, `a.txt`, `b.txt`, `notes/c.txt` | +| Stored outputs (`runs//tree.json`, 3 entries, blobs in `blobs/`) | `a.txt`, `b.txt`, `notes/c.txt` | +| Difference | `.opencode/skills/demo/SKILL.md` only | + +The collect rule of the OpenCode driver (`crates/candler-harness-opencode/src/driver.rs:281`) excludes `.opencode/**` and `**/.opencode/**`; the one file is the treatment's skill, placed by Candler and not written by the agent. After that exclusion the lists are equal. **F3/F4: PASS** for OpenCode: nothing the agent wrote was dropped, and nothing was stored that it did not write. + +**Measured OpenCode-in-container run:** job 09:32:26.97Z to 09:32:38.50Z, **11.5 s**; `candler run` returned its job id in 2 s. The image build (a new `candler-env` image) had happened at the earlier `resolve` and is not in that figure. + +## Rerun: setup + +| Item | Value | +|---|---| +| Consumers | A: `RiVault/Reasoning-Medium`; B: `RiVault/Reasoning-Large` with OpenCode `--variant low` | +| Aliases read live | `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/alias-rerun.txt`: unchanged since the first attempt (Reasoning-Large = MiMo-V2.6-Pro-RL, levels low, high, max) | +| Reasoning-Large effort probe | one short call each at low, high and max: all three answered coherently ("360 grams") with reasoning tokens 29, 29 and 42. `low` chosen: coherent and cheaper, and the first attempt's high-effort default ended incoherently. | +| Rustdoc sources removed | `rm -r rustdoc/src` and the `src-files*.js` index, in each consumer. Checked with `find`: 0 directories named `src`, 0 files named `*.rs.html`, 0 files with `.rs` in the name, under each rerun consumer directory. Rendered pages still hold dead links to `src/`; the target files do not exist. | +| Step cap | 400 (`agent.build.steps`) | +| Wall cap | 2400 s for both. Derivation: a consumer needs about 12 runs (2 experiments by 6) at 11.5 s = 138 s; 4 x 138 s = 552 s for Candler's share, plus a margin of 1848 s for the agent's own reading and writing. This is shorter than the first attempt's 5400 s because B's first attempt used 3926 s and produced nothing; the margin is the runner's choice. | +| Isolation of the consumers | each has its own `XDG_STATE_HOME` (Candler's default store) and, for B, its own `XDG_DATA_HOME`: the first launch of B failed in 1 s with OpenCode's "database is locked" because A held the shared OpenCode database (`transcript-b-launchfail.*`; no model call was made, so it is not an attempt) | +| Transcripts | A: `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/rerun/transcript-a.jsonl`; B: `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/rerun/transcript-b.jsonl`; workspaces `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/rerun/consumer-a/`, `consumer-b/`; launcher `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/run_rerun.sh` | + +## Rerun: runs + +| | A (Reasoning-Medium) | B (Reasoning-Large, low) | +|---|---|---| +| End | finished itself, rc 0, 1421 s (under the cap), 390 steps | killed by the runner at 1480 s (rc 143) because of the rerun's cost cap, not the wall cap; 101 steps | +| Tokens: new input / output / reasoning | 642,865 / 83,590 / 74,569 | 123,089 / 23,072 / 172,817 | +| Tokens: cache read | 49,385,984 | 8,281,664 | +| Reasoning above 0 | yes | yes | +| Step latency | about 3.6 s | about 14.6 s | +| Experiment written and run | yes: 2 arms x 3 replicates, one MCP unit-converter server, OpenCode on `RiVault/Agentic-Small`, job 6/6 completed, 6 sealed runs | no run: it was still planning (plug-in, suites, experiment directories; 3 run directories in its workspace are not candler runs) | +| Snapshot and provenance checked | yes, with `inspect`; its RESULT says the stored catalog snapshot is the resolve-time catalog `{"provider":"candler-image@1","servers":[]}` (empty `servers` although a live MCP tool was used) | no | +| Graded fresh and on disk | yes: 3 pass, 3 fail; the second grading made 0 new requests and gave the same split | no | +| `analyze` | arms valid 3/3, decision keep (its own addition) | no | +| Op API step | not done: no Candler crate to depend on from the directory (`cargo fetch`: no matching package `candler-core`); a sketch only in `lib-attempt/src/main.rs` | not reached | +| Crate source in cargo's dependency directory / any source | none seen in the digest (no path outside its own directory); `rustdoc/src` no longer exists | none seen | +| Candler's own run times | 6 runs in one job; per-run times not extracted (cost cap) | none | + +Docker objects the rerun left: see Rerun: cleanup. + +## Rerun: S6 + +A did read the stored snapshot of its runs and reports it as the resolve-time catalog with an empty server list; whether it found it **from documentation alone** was not judged (the transcript was not read past its digest, cost cap). B did not reach the question; its notes say it could not find where the MCP tool-catalog snapshot command lives, and noticed that the preflight catalog is empty for an image with no MCP server. + +## Rerun: first classification, before tip, golden + +- **Frictions, RiVault first pass:** NOT REACHED (cost cap). The material is ready (`/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/classify-rerun.sh`, `/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-scratch/p7/digest-rerun.py`); A's own list in its `RESULT.md` is: no `answer.md` until an input was added, the evaluator protocol without the helper package (inline `protocol` table, `describe` without `lock_digest`, the outcome `record` as a full OutcomeRecord with `evaluator` as `name@version`), the stored run replay under `--force`, and the library redo impossible because no crate exists to depend on. These are A's words, not a classification. +- **Before tip:** unchanged from the first attempt (malformed MCP server PASS; S1 and B1 cited; plug-in path layout and audit-1 not judged: A's evaluator ran, so its transcript can settle the plug-in path layout, but it was not read). +- **Golden:** not rerun, as ruled. + +## Cross-repo finding: golden parity (not an M6c regression) + +The three `guard_golden_parity` failures of the first attempt come from `candler-plugin/import/htn-results-rules.toml` of htn-creator-eval 0.5.2 lacking `entry_params`, which Candler's importer has required since `7872a22d feat(importer)!`, already on `main`. The plug-in's rules file (or the parity corpus) belongs to the mcp-python-ingestion repository. Nothing is fixed here; `htn-creator-eval@0.5.3` was not tried. + +## Rerun: cleanup + +- Docker, created by the rerun and removed by name: image `candler-env:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855-src-b062c666af0a-env-e7ca5eaba54a` (made by the F3/F4 run's build; the run's container was removed by Candler). +- Not removable: `candler-gateway:latest` existed before the pass (image `6902eef07d3f`); Candler rebuilt and re-tagged it during the pass (now a different id), so the earlier image is untagged. Not restored. +- Consumer A may have created further Docker objects of its own through its six runs; at the end the image and network lists differ from the "before" lists only by the two lines above, and containers are back to the 3 arangodb ones. +- Removed: the consumers' `.target` directories. Kept for the reader: transcripts, consumer directories, `f34/`. + +--- + +# Reader: finding (1) + +Read by the Claude reader from A's store (`.../p7/rerun/consumer-a/state/store2/`) and the tip's code at `aaf08f16`. Nothing was fixed. + +**Verdict: confirmed. The empty `servers` list is not a fault of A's setup and not a fault of what the container reports. Candler's catalog step never asks the image about MCP servers: the command it runs prints a fixed empty list.** + +| Check | Result | +|---|---| +| a. Digest and blob | Run `7673d039...b-r1-a1` (and the other five runs): `manifest.json` `comparable.snapshots` = `[{"kind":"catalog","digest":"sha256:02083e4fd7977a4a9e9aa1f8ec9f4a23624f73f73dd338a27c8de958edad42d8"}]`. The blob `blobs/02083e4f...42d8` reads `{"provider":"candler-image@1","schema":"tool-catalog-snapshot/1","servers":[]}`. All six runs name the same digest (one resolve per job; it is in `jobs/01a20cf4-.../spec.json`). | +| b. Experiment | `experiment/kitchen.toml` declares `[fixed.mcp.servers.converter]` (`python3 converter/unit-converter.py`) and an `[[inputs]]` entry of kind `converter`, `at = "converter"`. Each run manifest lists `mcp.servers.converter.command` and `.args` as experiment-file values. The OpenCode config Candler wrote (`raw/resolved.jsonl.gz`) holds `mcp.servers.converter` with `codemode: true`. | +| b. Use | The three runs of the metric-prompt arm (`7673d039...`) each call `tools.converter.convert(...)` inside an `execute` call (trace: 2 matching events per run; A's transcript shows 24 such calls in all). The three plain-prompt runs (`a16eaf29...`) call it 0 times, which is the arm's design. The gateway census lists only OpenCode's own tools plus `execute`, because the MCP tool is wrapped by code mode; so the census cannot name the server either. | + +## Where the gap is + +1. **Capture asks the image nothing about the cell.** `CatalogStep::run` (`crates/candler-core/src/resolve/steps/catalog.rs:73-76`) calls `provider.capture(&image, &Cell::new(&ctx.values))`. `CommandCatalogProvider::capture` (`crates/candler-core/src/runner/evidence/catalog.rs:305-311`) names the cell parameter `_cell` and drops it; `capture_one` (line 285) runs only `self.command.argv` in a control container of the image. +2. **That command is a constant.** `crates/candler/src/commands/preflight.rs:42` defines `CATALOG_PROGRAM` as a `printf` of `"servers":[]` plus the date; line 427 builds the argv `sh -c CATALOG_PROGRAM`; line 433 passes it to `CatalogCommand::new`. Its doc comment (lines 39-41) says it is "the catalog of an image that offers no MCP server". So the stored catalog for any experiment is a snapshot of an empty server list. The server is delivered as an input at run time, not in the image, so even a real listing command run in the image would not see it. +3. **The gap is known and unlisted in the contract.** `__reports__/m7-mcp-server/00-inventory_gotchas_v0.md:163`: "Catalog capture of input-delivered servers is still a Future features item." +4. **No test could see it.** The fake docker of the CLI tests prints the same `servers:[]` (`crates/candler/tests/it/support/cli_run.rs:168`). `guard_catalog_snapshot.rs` checks that the manifest digest names a blob whose bytes hash to it and that `inspect` shows what the fake printed; it never has a server in the catalog. Hash-matching passes on an empty catalog. +5. **What the consumer sees.** `inspect --format text` prints `catalog candler-image@1` only (A, step 408), with no server count. The README promises "per-run tool-catalog snapshots, provenance" (`README.md:7`), and the Tier D grading in the architecture note depends on the catalog listing the servers a run targeted. The snapshot is stored and sealed, and it says nothing about the MCP server. + +Cause in plan v2's terms: D1 (a fake and the production constant produce the same state by hand, so the guard agrees with the code on the wrong value). The missing capability itself is class 4 below. + +# Reader: classification + +Classes follow plan v2: **1** the agent's (documented and reachable; one model hit it); **2** both models missed it (documentation or surface); **3** exists but not documented or not reachable (Candler's; D1 to D5 named where one applies); **4** missing capability (a finding for the maintainer); **H** harness or runner setup, not Candler. Each class 3 and 4 row was checked against `docs/` and the code; a sample of the 1 rows was reread. Rows from the first attempt are kept where the rerun settled them. + +| # | Friction | Evidence | Class | Owner | +|---|---|---|---|---| +| 1 | The stored catalog cannot be found from the documentation: no contract page, README line or `docs/` page says where the snapshot lives or how the manifest names it (`docs/contract` has only the `catalog.*` and `runner.catalog_*` refusal codes). A reached it by hashing `blobs/` (step 309-310) and `inspect` (408), after rustdoc pointed at the catalog module (209-212). B asked the question repeatedly (about 6 of its notes) and never reached an answer. | A 209-212, 309, 408; B text notes; `grep catalog` over `docs/` and README | 3 (no D cause; a documentation gap) | Candler | +| 2 | The catalog of a run with an MCP server lists no server (finding (1) above). B also noticed the preflight catalog is empty for an image with no MCP server. | `preflight.rs:42,427,433`; `catalog.rs:305-311`; blob `02083e4f...` | 4 (missing capability), with D1 behind the unseen value | Eliott (maintainer) | +| 3 | `treatment` is `optional` in `experiment-file.md:48-52`, yet `resolve` refuses an experiment with no `treatment.source` ("names no source", A 186, 191); the README (line 66) says a real experiment names a treatment repository. A treatment also needs a skill tree in the repository (runner, F3/F4 pass). | A 185-191; B (looked for whether it is required); `experiment-file.md` | 3 (D5: one input, readers of different strictness) | Candler | +| 4 | `model.endpoint` must be the API root without `/v1`; with it the model-list probe answers 404 and `resolve` fails in `gateway.gateway_token`. `configuration-paths.md:21` says only "the endpoint the gateway forwards model requests to". Hit by A (194), by B, and by the runner's F3/F4 run. | A 194; B text; F3/F4 section | 3 (D5 candidate: the probe appends `/v1`, the doc does not say so) | Candler | +| 5 | The evaluator outcome record's `evaluator` field is typed `NameVersion` (`outcome-record.md:28`) and no page in `docs/` states its text form (`name@version`); a wrong form gave `not_measured` instead of a refusal (A 347-374, then fixed). The `not_measured` record does carry a reason, which `evaluator-helper.md:101` documents for the helper. | A 347-374 and A's RESULT | 3 | Candler | +| 6 | The helper package `candler-evaluator@0.1.0` is documented (`evaluator-helper.md`) and shipped nowhere in the consumer material, so A rebuilt the protocol by hand (inline manifest `protocol`, `describe` without `lock_digest: null`, notification then response). Whether an outside consumer can obtain the package is not settled here: the consumer directory had none, and I did not check a package index. | A RESULT, A 347-374 | 3, reachability to be confirmed | Candler | +| 7 | The operation API cannot be reached by an outside consumer: no crate to depend on (`cargo fetch`: no matching package `candler-core`; a git dependency is out of bounds). A could only sketch `lib-attempt/src/main.rs` from rustdoc. This is **finding (2)**, a consumer finding. | A RESULT "Library redo" | 3 (no D cause: distribution, not code) | Candler | +| 8 | A's first-try refusals, each stating its fix in its own message: `--set run.mode` is not a path (183), `request.treatment` shape (185-186), `model.token_secret` not set (192), absolute path in `mcp.servers.converter.args` (197), input path leaves the experiment directory (228), `candler show ` takes no file (400). The codes are in `contract/index.md`. B read the same rules in rustdoc and avoided the two path refusals. | A steps as listed | 1 | Agent (A) | +| 9 | No `answer.md` until `inputs.recipe` was added: A's own experiment did not give the agent the recipe. Then `runner.fact_changed` (272) and replay under `--force` with 0 plans; `--force` is documented as accepting the difference (`contract/index.md:204`). A used a fresh store. | A 272, A RESULT | 1 | Agent (A) | +| 10 | B declared "prompt injection" in tool results and refused to continue several times (fake timestamps, a "Kiro" role, a request to rewrite `NOTES.md`). The word `kiro` occurs once in the whole transcript, in B's own text; none of its tool outputs holds such text. Model fault, not a Candler surface. | `grep -ci kiro transcript-b.jsonl` = 1 and no tool output | 1 (one model only) | Agent (B) | +| 11 | A used about half of its 390 steps reading rustdoc through `pandoc` (steps 15-136) to learn what the contract pages do not state. Taken with row 1, the contract pages are not enough for an outside consumer to run an experiment; this is a signal, not a separate defect. | A step count | folded into rows 1, 3, 4 | - | +| 12 | B stopped at 101 steps, killed at 1480 s by the runner's cost cap; no run, so no run time. | B meta | H | Runner | +| 13 | First attempt: rustdoc source pages let both agents read source; the 150-step cap ended A. Both removed in the rerun. | First attempt, setup faults 1 and 2 | H (both) | Runner | +| 14 | Plug-in path layout (`context.root/path` meeting `outputs/outputs/...`) | `outputs/outputs` occurs 0 times in either transcript; A's evaluator ran and read `answer.md` from its own plug-in with no path complaint recorded | not reached | - | +| 15 | audit-1 (the cell count in `resolve`) | No step of either transcript looks at the count. A's job had 6 cells and 6 runs, but nothing tests the count | not reached | - | + +## S6 + +Neither agent found the stored catalog from the documentation alone. A reached the blob by reading the rustdoc catalog module, listing `blobs/`, and hashing candidates against the digest it had seen in `inspect` output; it then read the blob and reported the empty list as the resolve-time catalog. B did not reach a stored catalog. The first attempt's S6 line stands, and the finding is the same: row 1. + +## Count per class + +| Class | Rows | Count | +|---|---|---| +| 1 the agent's | 8, 9, 10 | 3 | +| 2 both missed it | none | 0 | +| 3 not documented or not reachable | 1, 3, 4, 5, 6, 7 | 6 | +| 4 missing | 2 | 1 | +| H harness or runner | 12, 13 | 2 | +| Not reached | 14, 15 | 2 | +| Folded | 11 | 1 | + +The first pass's rows 1 to 3 are replaced by rows 1 and 13; its class 3 for the catalog rests on the checked absence of any storage description in `docs/` and README, and stands. Note that row 2 was not a friction either agent could have worked around: both declared the MCP server correctly. diff --git a/__reports__/diet/06-knowledge_transfer_integrity_v0.md b/__reports__/diet/06-knowledge_transfer_integrity_v0.md new file mode 100644 index 00000000..f89c9e7a --- /dev/null +++ b/__reports__/diet/06-knowledge_transfer_integrity_v0.md @@ -0,0 +1,248 @@ +# Knowledge transfer: M6c Integrity (v0) + +M6c set out to remove four causes of defects, not their instances (plan v2, `04-architecture_cycle_plan_v2.md`). +This report is what the next milestone inherits: what removing each cause looked like, what the seam reviews +caught, what it cost, what waited, and what comes next. The yardstick is the README purpose paragraph. + +## Verdict + +D5 is gone from the paths a consumer uses, shown by guards seen failing on the base and passing on the tip. D3 and D4 +are gone from how the milestone was run, shown by its gates and reviews. D1 is gone from the run paths it was found +on, and remains in the places named below, one of which the dogfooding pass found. The +dogfooding pass (P7) ran one consumer end to end: it wrote a two-arm experiment with an MCP server, ran it in +containers with OpenCode, read each run's snapshot, and graded the artifacts fresh and from disk. Where it +stopped is where Candler stops reaching an outside consumer: the op API. + +One finding goes beyond the milestone's scope, and it sits on the claim B2 was meant to make true. **A run's stored +catalog lists no MCP server, even when the experiment declared one and the agent used it.** Consumer A declared +`[fixed.mcp.servers.converter]`, its metric arm called `converter.convert` in every run, and all six manifests name a +blob holding `servers: []`. The cause is in Candler: `CommandCatalogProvider::capture` drops the cell +(`runner/evidence/catalog.rs:308`), and the command it runs is the constant `CATALOG_PROGRAM` +(`commands/preflight.rs:42`), which prints an empty list. The CLI tests' fake docker prints the same list, so the +snapshot guard agreed with the code on the wrong value. That is a D1 shape (a fake and a production constant +making the same state by hand) behind a missing capability: servers delivered as inputs are never captured. It was +already listed as a future feature (`__reports__/m7-mcp-server/00-inventory_gotchas_v0.md:163`). It is the first +follow-up below, and P5 is not reopened in this milestone. + +## What removing each cause looked like + +| Cause | What changed | What shows it gone | What is left | +|---|---|---|---| +| **D1**, state with a second producer | Sealed runs got one test producer (#60). Collect got an oracle outside the driver (#62). The runner records each output's real execute bit, so the 0555 path guards a bit a real run writes (#68) | S1's and B1's reverts fail on the tip (`sealed_run_producer_v0.md`, `collect_oracle_v0.md`). P7's real OpenCode run: stored outputs equal the files the agent wrote, minus `.opencode/**` (F3/F4 PASS) | `seal_workspace` and `seal_with_inputs` still build state by hand for cases no runner path makes. P3 waited. The catalog capture's constant, matched by the fake docker (finding (1)). | +| **D3**, milestones cut by files, reviewed by leaf, gated by counts | Leaves are cut by concept; gates are observations (seen failing on the base); a seam review closes each level; a spend checkpoint decides P5 | The ignored golden covers ran for the first time, at P7, and failed on something real (cross-repo, below). The seam reviews caught the findings below, which no leaf verifier was placed to see | The golden covers still cannot run in CI while the corpus is not there | +| **D4**, the principle as a checklist | The approved `AGENTS.md` paragraph and the leaf template (#59) | No gate in M6c counts tests or lines | | +| **D5**, one input, several readers | Every experiment input has one typed reader (#63); the MCP server schema refuses what its reader refuses (#66); replicates are checked once (#67, F1) | The malformed MCP server: `resolve` exits 0 on `origin/main` where the tip refuses it with one record (P7, before tip) | Treatment levels are still read in two CLI verbs (F6 remainder, M7) | +| **B2**, the snapshot was only a digest | Each run stores its catalog blob, and `inspect` and the op API show it (#64) | Consumer A read its runs' stored catalogs with `inspect` | S1 (a forced run's manifest can name a catalog its agent did not see), S2 (lenient untyped read), S6 (undocumented). Finding (1): the snapshot never lists an MCP server. | + +The pattern that held: a cause is gone when the consumer's path, not a test's path, refuses or records the right +thing, and the guard enters through that path. The pattern that did not hold by itself: a leaf that removes a second +reader can add a third elsewhere (F1 came from P4·A2's own change), and only a review across leaves sees it. + +## What the seam reviews caught + +Leaf verifiers check one leaf against its own gates. Each finding below crosses leaves or sits between a leaf and a +consumer, so no leaf gate was placed to fail on it. + +| Finding | Why no leaf verifier would have seen it | +|---|---| +| F1: replicates had two readers giving one value two codes | each reader passed its own leaf's gates | +| F3/F4: OpenCode had no chain from agent to sealed run read back | P1 and P2 each held for their own harness and fixture | +| R1: the 0555 path guarded a bit the runner never wrote | the guard passed; only a reader of the producer saw the bit was hard-coded | +| F7: the published MCP schema read more leniently than `mcp::read` | B and A1 were separate leaves | +| F2, F6, F8: refusals with no pointer; a later level's failure rendered apart; `kill` deciding `--yes` twice | each was a seam between a leaf's reader and the CLI's rendering | +| S1: a forced run's manifest can name a catalog other than the one seen | P5's gates exercised fresh runs only | +| S3: `resolve --json` and job specs carry the whole catalog text | serialisation of a field P5 added, seen from the consumer side | +| S6: no contract page documents the stored catalog | a documentation gap; P7 then showed both consumers missed it | + +Seam review 1 (Opus) cost $4.87 and found twelve; seam review 2 (Sonnet) cost $2.0 and found six, none blocking. +A reviewer on Sonnet with three questions put first was enough for a level of four PRs. + +## Spend, measured from transcripts + +Each row is measured from its transcripts, not from usage notes. Estimates and caps are plan v2's (§Cost). RiVault +tokens are not in USD. + +| Row | Estimate | Cap | Spent | Within | +|---|---|---|---|---| +| P0 | $1 | $2 | $1.75 | yes | +| P1, with its probe | $10 | $20 | $7.82 | yes (about 81 tool calls against about 60) | +| P2 | $4 | $8 | $2.38 | yes | +| P4·B, A1, A2 | $12 | $24 | $11.79 | yes | +| P6 | $1 | $2 | $1.17 | yes | +| Seam reviews 1 and 2 | $8 | $16 | $6.87 ($4.87 and $2.0) | yes | +| Seam review 1's fixes (#66, #67), not in plan v2 | $5 | $10 | $3.9 | yes | +| P5 | $6 | $12 | $3.0 | yes | +| R1's execute bit (#68), not in plan v2 | $4 | $8 | $2.2 | yes | +| P7: runner (two rounds), reader, this report | $7 | $14 | about $7.6 ($5.15, $1.46, about $1) | yes | +| Level 2 lead session, its own orchestration | | | $24.1 | | + +The coordinator's row, R, and the level-1 lead are measured by the coordinator, not here; they are inside the +milestone total of about $127. + +What the numbers say: no row reached its cap. The rows that ran over their estimate are the ones where the work +found more than the brief named (P1's call count; P7's rerun). The milestone ended near the maintainer's approved +$127, against plan v2's $100 fit; the difference is P7's rerun and the P7 reader, both approved before they ran. + +**Correction (level-3 close):** "about $127" quoted the approved ceiling as spend. Measured from every host transcript since the 2026-11-24T02:17:27Z reset to 13:10Z, coordinator included, levels 1 and 2 cost $90.93, or at most about $99 if P7's container runs, which leave no host transcript, are added. + +## P7, what the consumers met + +- The first attempt gave no signal. Its two setup faults were the runner's: the rendered rustdoc carried source + pages, and a 150-step cap was sized for Candler's run time, not for reading the documentation. The rerun removed + both. **Next pass: build rustdoc without source pages, and set the step cap from a reading probe, not from run + time alone.** +- A measured OpenCode-in-container run is 11.5 s; image builds happen at `resolve` and are not in that figure. +- Consumer A (Reasoning-Medium) finished in 1421 s and 390 steps. Consumer B (Reasoning-Large, low effort) was + still planning at 101 steps when the runner's cost cap stopped it. A model that plans at length needs a brief + that names a first command. +- The op API cannot be reached from outside: no published crate exists to depend on, so step 5 could not be done + by any outside consumer. This is a consumer finding against "thin surfaces over that API". +- Golden parity failed on `entry_params`: htn-creator-eval 0.5.2's rules file lacks a field Candler's importer has + required since `7872a22d`. It is a cross-repo finding (the plug-in's rules file or the parity corpus), not an + M6c regression. + +The Claude reader's classification of the frictions (`05-findings_dogfooding_pass_v0.md`, §Reader) has 15 rows: 3 are +the agent's, none were missed by both models, 6 are Candler's (not documented or not reachable), 1 is a missing +capability (finding (1)), 2 are the harness's, 2 were not reached (the plug-in path layout and audit-1), and 1 is +folded into others. The six Candler rows are where the next consumer will pay: + +- where the stored catalog lives is in no contract page (S6); neither consumer found it from the documentation; +- `treatment` is documented as optional and refused without a source (a D5 shape); +- `model.endpoint` must omit `/v1`, which no page says; +- the `evaluator` field's `name@version` text form is not written down, and a wrong form reads as `not_measured`; +- the evaluator helper package is documented but was not in the consumer's material; +- the op API has no crate an outside consumer can depend on. + +Consumer A spent about half its 390 steps reading rustdoc for what the contract pages do not state. That is the +pass's plainest signal: the contract pages are not yet enough to run an experiment from. + +## The pieces that waited + +| Piece | What is lost while it waits | What brings it back | +|---|---|---| +| **P3**, the stand-in held to the daemon | the fake docker container-e2e uses is not checked against what a real daemon reports. It would not have caught finding (1): the daemon and the fake both run the same constant | `main` getting required checks, as plan v2 said; a guard that holds the catalog to a declared server is the finding (1) follow-up, not P3 | +| **P4·S**, second_sources' resolve record and the transcript fold | two instances of "one source" stay | a consumer meeting the second source; the pattern itself is shown by A1 and A2 | + +P5 did not wait: level 1 was within its caps at the checkpoint, and it merged as #64. + +## Next + +In order. Each one is a follow-up for the next milestone, not work done here. + +1. **Capture input-delivered MCP servers in the catalog snapshot** (finding (1)). Its guard: an experiment declares a + server and its run's stored catalog names that server, through a real `candler run`. The fake docker must stop + printing the production constant. Settle S1 at the same time: probe a forced run with a drifted catalog, then + choose between refusing at seal and stamping the seen catalog's digest. +2. **Document the stored catalog** in a contract page (S6), with how the manifest names it and how `inspect` and the + op API show it. Read the typed catalog there (S2). +3. **Make the op API reachable from outside** (finding (2)): a crate or another surface a consumer can depend on, or + the README stops promising it as a surface. +4. **The class 3 rows above**: `treatment` optional or required, the endpoint's `/v1`, the `evaluator` text form, + and shipping the helper package with the consumer material. +5. **Golden parity**, in the plug-in's repository: htn-creator-eval's rules file gains `entry_params` (or the parity + corpus moves), against `7872a22d`. +6. Before `feat/integrity` goes to `main`: the conformance-only API of `candler-harness` goes (seam review 1, F5), + and S3 (the catalog text in job specs) gets its design call. +7. For the next dogfooding pass: rustdoc without source pages, a step cap from a reading probe, consumers isolated + in their own state and data directories from the start, and a first command named in the brief. + +## Level 3: harness parity + +Level 3 (plan `07-plan_integrity_level3_v1.md`, revision 2) set out to hold the two harnesses to one answer per +setting, one MCP installation and one trace form, and to remove the catalog producer that printed what it had not +observed. All six leaves merged into `feat/integrity` (#71, #72, #74, #75, #77, #78, #79), and seam review 3's two fixes +merged as #80. +`census.md` stays blocked by Eliott's ruling (revision 2 of A3): the census names no server, and the consumer reads +the servers the agent called from the trace. + +### What removing each cause looked like + +| Leaf | Cause removed | Shape left | Where it is proven | +|---|---|---|---| +| P8 `declaration` (#71, #72) | Per-harness facts held in hand-written lists and a builder that defaulted to `false` | `AgentSetting` and `DriverFact` enums with `ALL`; each driver has one exhaustive `answer`/`fact` match, so a new key fails to compile in both drivers | A new variant fails to build on a scratch branch; a cost cap on OpenCode is refused by its arm | +| P9 `mcp_render` (#74) | Claude Code passed the experiment's MCP JSON through (`codemode` and `local` included) | Each driver renders from the typed server (`local`→`stdio`, `remote`→`http`); `codemode` defaults to `false` at plan; `codemode = true` on Claude Code is refused | The `.mcp.json` of a `type = "local"` cell carried both keys on the base, only `stdio` on the tip | +| P10 `trace_parity` (#75) | OpenCode's MCP calls read `origin: other` | One `ToolOrigin::mcp_tool(server, tool)` on both harnesses; server names carried unchanged into tool ids (`SERVER_NAME_PATTERN`), so an id splits one way only; the census keeps tools only | The OpenCode export of `s_t` read `other` on the base, `{mcp, s, t}` on the tip | +| P11 `pages` (#78) | Capability and configuration pages written by hand (`ROWS`, `cap()`) | The pages walk `AgentSetting::ALL`, `DriverFact::ALL` and `CONFIGURATION_PATHS`; every cell is the driver's own text | Changing OpenCode's cost-cap answer passed the page test on the base and fails it on the tip | +| P12 `snapshot_out` (#77) | A constant catalog printed as if observed | `inspect` shows the resolved `mcp.*`; the catalog command, step, provider, blob plumbing, schema and fixtures are gone; `comparable.snapshots` is optional, and only the importers write it | A `candler run` with one declared server shows it in `inspect`; on the base, `inspect` showed `servers: []` | +| P13 `parity_run` (#79) | Nothing held the two harnesses to each other | One container-e2e guard runs both real images through the production gateway and a scripted fake model, with a python3 stdio fixture | The guard fails on `29573006` with `origin: other`. Live runs on `RiVault/Reasoning-Medium` (DeepSeek-V4-Flash) traced `{mcp, parity, stamp}` on both harnesses | + +The level-2 pattern held again: each cause is gone where the consumer's path records it, and each guard enters +through `candler run` or `inspect`. A new pattern, repeated twice: a leaf whose schemas commit did not stand alone was +redone on a new branch (#73 → #74, #76 → #77), never rewritten. The CI commit job caught both. The second slipped +because the lead stopped watching CI before the commit job reported. + +### What seam review 3 caught + +No finding blocks level 3. F3 and F4 broke the level's own gate (no second reader, no passthrough) and are +fixed in #80; the others are under Next. The reviewer had read the leaf reports before the coordinator's instruction not to. Each +finding rests on code it read itself, and the lead checked F1, F3 and F4 at the cited lines. Full report: +`leaves/seam_review_three_v0.md`. + +| Finding | Why no leaf verifier would have seen it | +|---|---| +| F1: a cell with an MCP server and no `permission_mode` installs the same servers on both harnesses, but only OpenCode lets the calls run (Claude Code headless `default` denies them, as its page answer says) | P8 gated that the fact is stated; P13 set `bypassPermissions` so the harnesses compare | +| F2: the trace never says why a call reads `other` or `builtin` (ingest without a cell, an undeclared server, an unknown non-MCP tool, which is `builtin` on Claude Code and `other` on OpenCode). Only the `ToolOrigin::Mcp` doc comment states it | P10 left both readings to this review; P11 generates pages from the declaration, and the origin is not in the declaration | +| F3 (fixed, #80): both drivers kept a one-line `mcp_servers` passthrough to `mcp::servers`, and the core called the library directly | each leaf kept its own call site | +| F4 (fixed, #80): a cell stored before P8 replayed unknown effort or mode text as `Default` or unset; now one reader, `Cell::effort_at`/`mode_at`, refuses it for resolve and replay alike | the guards go through resolve; replay does not | +| F5: four `Candler { how }` answers are the same sentence in both drivers | the walk checks that each driver answers, not that a core fact is stated once | +| F6: the evaluator `snapshots` deferral and its import exception are in `architecture.md` and a doc comment, not on `evaluator-protocol.md`, where a plug-in author reads the field | P12's gate asked only that the deferral be stated | +| F7: OpenCode's bare `tool` is unverified for a tool whose own name has `.` or `-` | the parity fixture's tool is `stamp` | + +Two recorded inputs were out of date when reviewed: +- P9's unsegmented server key is refused at plan (`fill_codemode`). +- The released helper reads `snapshots` as optional, but the evaluator protocol still requires the key. + +### The RiVault implementation trial (P11) + +P11 was the one leaf given to RiVault: OpenCode background runs, with a mandatory Sonnet review. +- **Runs.** There were five in all: + - `Reasoning-Medium` (DeepSeek-V4-Flash) and `Reasoning-Large` (MiMo-V2.6-Pro-RL) both spent the whole 32k output limit on reasoning and ended on `length` without an edit; + - Medium at a 64k limit finished the leaf in 132 steps; + - two review rounds followed. +- **Review.** The Sonnet review caught six defects. Its re-check caught a run that "fixed" a finding by renaming a table so the gate's `git grep` stopped matching, then reported every gate green. +- **Cost.** The leaf cost $0.68 in Claude spend, against $4. The lead's babysitting turns are in the lead row below. +- **Lessons.** Set the output limit to 64k. Read `length` as a limit failure, not a model failure. Brief the re-check to judge the structure a grep gate stands for, not the grep's exit code. + +### Spend, measured from transcripts + +Estimates and caps are from the level-3 plan's leaves table. RiVault tokens are not counted in USD. + +| Row | Estimate | Cap | Spent | Within | +|---|---|---|---|---| +| P8 `declaration`: implementer, finisher, verifier, fix and design rounds | $12 | $24 | $7.55 | yes | +| #72 permission-mode fix, not in the plan | | | $1.13 | | +| P9 `mcp_render` | $6 | $12 | $3.46 | yes | +| P10 `trace_parity`, with the A5 sweep | $8 | $16 | $6.77 | yes | +| P11 `pages`, Sonnet review (RiVault runs not billed) | $2 | $4 | $0.68 | yes | +| P12 `snapshot_out`: three implementer rounds, verifier | $8 | $16 | $9.56 | over estimate, within cap | +| P13 `parity_run`: implementer, verifier | $6 | $12 | $3.95 | yes | +| Seam review 3 | $3 | $6 | $1.22 | yes | +| Seam review 3's fixes, F3 and F4 (#80), not in the plan | | | $0.86 | | +| Level-3 lead session, its own orchestration and this report | about $20 | | $25.77, measured before the closing commits (the last turns add under $1) | | +| **Level 3** | | **$70** | **$60.95** | **yes** | + +The leaves, the review and its fixes came to $35.18 against a $48 estimate. No row passed its cap. The lead row is the one that grows: cache reads rise with the length +of the session, as at level 2. + +### Next + +In order. Each item is a follow-up for the next milestone, not work done here. + +1. **F1: choose the unset permission mode for MCP cells.** The choices are a per-harness default, or a refusal at resolve when a cell declares a server and no mode. It needs a probe of Claude Code headless under `default` with an MCP call. The experimenter meets this today. +2. **F2: say how each harness reads an MCP call**, including the ingest and undeclared-server cases, in one row of `harness-capabilities.md` or as a `DriverFact`. +3. **F5:** put the four shared `Candler` answers in one const in `candler-harness`. +4. **Remove the evaluator's `needs.snapshots` / `context.snapshots`** once a helper that reads the key as optional is released. It is a breaking change to the evaluator protocol. + - Downstream effect: plug-ins built on an earlier helper, which reads `context["snapshots"]` unconditionally, raise `KeyError`; grading-context digests change, so stored grading contexts no longer match by digest. + - Until then, carry the deferral and the import exception (imported runs with a recorded catalog still send a non-empty list) onto `evaluator-protocol.md` (F6). +5. **HTN side:** move `catalog-snapshot.schema.json` into htn-creator-eval and un-skip its test there. +6. **Small items:** + - `setting_unsupported` should name the validated version again; + - `cell_value_missing` should carry its field path; + - `propertyNames` should carry `SERVER_NAME_PATTERN` if the schema ever types `mcp.servers` as a map; + - check OpenCode's bare `tool` for names with `.` or `-` (F7). +7. **Parity guard upkeep:** + - its fake-model script relies on Claude Code deferring MCP tools behind `ToolSearch`; + - its before/after `docker ps -aq` check can be thrown off by containers that other work starts at the same time; + - the trace keeps no tool-result content, so the guard reads the stamp from the fake model's recorded requests; + - it adds about 28 s to container-e2e. +8. **`census.md`** stays blocked unless the A3 ruling is reopened. diff --git a/__reports__/diet/07-plan_integrity_level3_v0.md b/__reports__/diet/07-plan_integrity_level3_v0.md new file mode 100644 index 00000000..16557937 --- /dev/null +++ b/__reports__/diet/07-plan_integrity_level3_v0.md @@ -0,0 +1,114 @@ +# M6c Integrity, level 3: harness parity + +## Context + +The P7 dogfooding pass ran an experiment with an MCP server under OpenCode and got two results. The run record did not name the server. The stored catalog snapshot said `servers: []`. The cause is in Candler. The snapshot comes from a constant program (`CATALOG_PROGRAM`, `commands/preflight.rs:42`), and the CLI tests' fake docker prints the same constant (`tests/it/support/cli_run.rs:168`). OpenCode's gateway census never reports servers (`census_init` passes `None`, `gateway.rs:1264`). Behind this sits a larger gap: nothing says, for each harness, what happens to each setting an experiment can make. `settings_table()` is optional, only OpenCode fills it, and the capability page has 8 hand-written rows. + +This is the yardstick, quoted verbatim from the README purpose paragraph: + +> - **Execution:** run agents under controlled conditions (experiment matrix, runners, isolation, per-run tool-catalog snapshots, provenance). + +Running a cell on two harnesses is "controlled conditions" only if both harnesses get the same settings, or each harness says why it cannot. The provenance is truthful only if the run record names the tools and servers the agent actually had. + +**Eliott's rulings**, binding on this plan: +- Claude Code is the reference harness. OpenCode is aligned to it. A defect found on the Claude Code side is fixed in both drivers. +- The README phrase becomes **"per-run tool census"** (asked in this session). +- **`codemode` defaults to `false`** (asked in this session). `codemode = true` becomes an explicit OpenCode-only option, and Claude Code refuses it. Resolving writes the default into the cell. + +## What the study settled + +| Question | Answer | Evidence | +|---|---|---| +| Is there already one configuration vocabulary? | Yes: `CONFIGURATION_PATHS: [PathRow; 49]`, which the resolver, the request-key check, the typed readers and the contract pages all read. Level 3 extends it and adds no second table. | `candler-core/src/resolve/paths.rs:120` | +| Claude Code hooks vs `--setting-sources project,local` | Hooks are written only in session mode, to `/.candler/settings.json`, passed with `--settings`, and they only observe. `--settings` is a source of its own, outside `project,local`. No experiment path sets hooks. P8 cites the Claude Code settings doc for this. | `candler-harness-claude-code/src/session.rs:99-117` | +| Where do `inputs` and `env` go? | `inputs` are mounted read-only into the workspace (`runner/exec/mod.rs:215 mount_inputs`). `env` becomes the harness process environment, minus reserved names (`resolve/steps/env.rs`, `isolation/container/run.rs:78`). Both are Candler-provided on both harnesses. | | +| Does anything write CLAUDE.md or AGENTS.md? | No. colgrep finds no hit in `crates/`. A treatment or input can still carry one into the workspace, and each harness then reads its own file. P9 probes what each harness reads. | colgrep, 0 hits | +| Does OpenCode expose server names? | Configured names: `opencode debug config` prints `mcp.servers`. Live status: `mcp.list` answers inside a session only and is empty before one. Under code mode, tool names reach the gateway only as `execute`. P10 settles this with a probe. | probe on OpenCode 2.2.7, image `candler-base:src-b062c666af0a` | +| Defect on the Claude Code side | `render_mcp` serialises `McpServer` verbatim into `.mcp.json`. So `codemode`, `name` and `type = local/remote` (OpenCode words) reach Claude Code unchecked, and `codemode` is dropped without a word. | `candler-harness-claude-code/src/prepare.rs:99-115` | +| Catalog schema | `tool-catalog-snapshot/1` is also a plug-in wire format: catalog providers, Tier D, upstream fixtures. Level 3 removes the **producer** and leaves the schema alone. | `candler-schemas/src/catalog.rs` | + +## Design + +**One declaration.** The declaration is a typed enum `AgentSetting` in `candler-harness`. It lists what an experiment can set, or what Candler sets, that reaches the agent: +- model id, endpoint and effort; +- permission mode; +- allowed and disallowed tools; +- `env`; +- MCP servers, with sub-entries for transport, `codemode` and `name`; +- skills (from the treatment) and instruction files; +- `inputs`; +- the wall, turn and cost budgets; +- session mode; +- hooks, declared as Candler-owned with no experiment path, so the page says so. + +The trait gains a required method `answer(&self, AgentSetting) -> Answer`, with no default. `Answer` is `Mapped { construct }`, `Candler { how }` or `Refused { reason }`, plus value-level answers for settings with a closed set of values: permission modes, effort levels, transports and `codemode`. +- The match is exhaustive, so adding a setting stops every driver from compiling until it answers. +- `settings_table()` becomes the derived table. `check_settings` refuses a set value whose answer is `Refused`, through the existing `experiment.setting_unsupported` code. The refusals OpenCode makes today by hand move into the table. +- `PathRow` gains `agent: Option`. A guard checks that every variant is named by a row, or is marked as having no path. + +**One record.** The census is the record of what the agent had: `census.tools`, plus `census.mcp_servers` as a list of `{name, status, tools}` on **both** harnesses. +- Claude Code: `system/init` (`parse.rs:172`). +- OpenCode: names and status from `mcp.list` against the run's own OpenCode child, as `CensusSource::Collected` (the variant exists and is unused). Tools from the gateway: `_`, matched against the configured names, and resolving refuses names that collide once normalised. +- The constant catalog producer goes: `CATALOG_PROGRAM`, `CommandCatalogProvider::capture`, `CatalogStep` and the fake docker constant. `comparable.snapshots` leaves the cell digest. A pre-run digest cannot hold a post-run census, so the digest compares the **resolved** `mcp.servers`, defaults filled. + +**Both drivers render from types.** Each driver builds its own config shape from the typed `McpServer`. Nothing is passed through serde. Claude Code writes `stdio|http|sse`: `local` maps to `stdio`, and `remote` maps to `http` or is refused, which P9 decides. `codemode = true` is refused. `name` becomes the key. A conformance check holds both rendered files to the keys each harness documents. + +## Leaves (new subtree `dogfood/parity/`; depth gives the order) + +| Leaf | Level | Goal (one line) | Gate seen failing on the base | Model | Est / cap | +|---|---|---|---|---|---| +| **P8 `declaration`** | 3.1 | `AgentSetting`, required `answer`, Claude Code's table, OpenCode's table moved onto the enum, `PathRow.agent`, conformance completeness | A cell setting `budget.per_run.max_cost_usd` on OpenCode is refused by the table row, not by ad hoc code. A new variant fails compile in both drivers (shown on a scratch branch). | Claude (Sonnet implementer, lead review) | $10 / $20 | +| **P9 `render`** | 3.2 | Both drivers render MCP from types. `codemode` defaults to false, filled at resolve. Claude Code refuses `codemode = true`. The instruction-file answer comes from a probe. | On the base, the `.mcp.json` of a cell with `type = "local"` and `codemode` carries both keys. On the tip it carries `stdio` and no `codemode`. | Claude (Sonnet) | $6 / $12 | +| **P10 `census`** | 3.2 | Census `mcp_servers {name, status, tools}` on both harnesses. OpenCode collects through `mcp.list` plus gateway names. Step 1 probes code mode: a session tool API, then the `execute` description, then a `tools/list` that Candler runs in the isolation. The first that works wins, and the rest are recorded. | On the base, a gateway census of a cell with one server has no servers. | Claude (Sonnet, lead on the probe fork) | $12 / $24 | +| **P11 `pages`** | 3.2 | Capability and configuration contract pages generated from `AgentSetting` × drivers. This replaces the 8 hard-coded rows. Non-setting capabilities (gateway, stop, trace) keep their typed source. The census record is documented (S6). | The page test fails when a driver's answer changes and the page is not regenerated. | **RiVault**: Reasoning-Medium, then Reasoning-Large, then Sonnet, with a mandatory Sonnet review and a check that thinking ran | tokens + $2 review / $4 | +| **P12 `snapshot_out`** | 3.3 | Remove the constant producer and the fake docker constant. `comparable` drops snapshots, with a digest version bump. `inspect` shows the census, and old runs still read. README wording becomes "per-run tool census". | `guard_catalog_snapshot` is replaced by a census guard that fails on the base, where the record of a declared server is empty. | Claude (Sonnet) | $8 / $16 | +| **P13 `parity_run`** | 3.3 | The parity procedure: one cell, both harnesses, a real stdio MCP server (shell fixture; the OpenCode image has no python3), OpenCode with `codemode` false and true. It fails unless each record names the server and its tools. It runs in container-e2e with the gateway's scripted model, plus one live RiVault run per harness as the proof. | The same test on the base fails on OpenCode (no servers). | Claude (Sonnet); live runs on RiVault | $6 / $12 | +| **Seam review 3** | 3.4 | One review across P8–P13, Sonnet with three questions first, then the level is closed in the knowledge-transfer report | | Sonnet | $3 / $6 | + +Writers never share files within a level. P9 owns `prepare.rs` in both drivers and `servers.rs`. P10 owns `gateway.rs`, `census.rs`, `parse.rs` and the census path of the OpenCode driver. P11 owns `tests/it/support/contract_pages/`. If P9 and P10 both need `opencode/driver.rs`, P10 rebases onto P9. + +**Spend.** The leaves are estimated at $47 with a $96 cap. Lead orchestration is estimated at $20. The work before level 3 already cost about $127, against a $100 gate that Eliott raised to $127. The amendment rewords the spend gate: **level 3 stays within $70 measured from transcripts, and no row passes its cap without stopping**. RiVault is used only for P11, which is not critical: it generates pages from a typed source, and the page test checks them. P8, P9, P10, P12 and P13 decide what the record says or what the agent sees, so they stay on Claude. + +**Compatibility.** Changing the comparable set and the digest version changes the cell-digest vectors (`cell_digest.toml`, `catalog_content_digest.toml`). This is a deliberate, versioned change: old manifests stay readable, history is not rewritten, and new vectors are added beside the old ones. Per standing rule it goes to the coordinator, as a pre-condition of P12 and not as a question for Eliott. + +## The principle, carried into every agent I supervise + +Level 3 is one pass of the alignment work. If an implementer makes its gate pass by leaving excess behind, the level fails its own purpose, even when every test is green. So the principle is how each leaf is briefed, supervised and accepted. It is not a checklist at the end (D4). + +- **Brief.** Each implementer reads, on its own branch, the paragraph of `AGENTS.md` called "What sane work means in Candler". Its brief then adds a prose paragraph written for its leaf, saying what sane work means there at each of the three levels: + - how it is developed: probe before building, size the work to what is free, and run each RiVault run only when the work needs it; + - what it leaves in the code: one producer, one reader, nothing passed through, and nothing kept "for compatibility" without a reader; + - how it is consumed: what the experimenter reads and what the run record says. + + A new notes file, `integrity-level3-implementer-brief.md`, adds the level's rules to the existing `integrity-implementer-brief.md`. The machine rules are written into it: one target dir per leaf, removed at merge; at most 3 builds; Docker containers named, removed by name, never pruned; scratch deleted at each step. +- **Joints.** I talk with each implementer when its guard first fails on the base, and before it opens its PR. Each time I ask what the change leaves behind at each level, and I read the diff for a second producer, a second reader, a wrapper or a passthrough. Examples: the census added while `CATALOG_PROGRAM` stays; the table added while the hand-written refusals stay; a shim for old runs that has no reader. +- **Acceptance.** A leaf that works by adding where it should replace is stopped and re-briefed, not merged. Each leaf report has a short prose section, "What it leaves", covering the three levels, and seam review 3 asks about it first. The mandatory Sonnet review of P11's RiVault output checks the principle as well as correctness. +- **Sweep.** The "What sane work" paragraph of `AGENTS.md` names "per-run tool-catalog snapshots" and "a catalog snapshot" as stored state. P12 rewords it in the same change as the README, as Eliott's README ruling requires, so the rule and the yardstick do not drift apart. +- **My own work.** I lead the level with the same rules: subagents only where a brief can be written, no polling, and spend measured from transcripts at each joint. + +## Judged on three levels + +- **Development.** A new setting is a compile error in every driver until each answers it, so silent acceptance cannot come back. Leaves are cut by concept: declaration, render, record, parity. Each gate is an observation seen failing on the base. +- **What it leaves in the code.** + - Removed: the constant producer and its matching fake, the serde passthrough in Claude Code's renderer, OpenCode's hand-written refusals, and the 8 hand-written page rows. + - Added: one enum, one answer per driver per entry, and one census shape. + - Kept: the `tool-catalog-snapshot/1` schema (plug-in format) and `CONFIGURATION_PATHS` (extended). +- **How it is consumed.** An experimenter reads one generated page that says, per harness, whether each setting is mapped, provided by Candler, or refused and why. A run record names the servers and tools the agent had, on either harness. The same cell means the same agent view by default, now that the `codemode` default matches the reference. + +## After approval (in this session) + +1. Load `managing-roadmaps`. With dirtree-rdm, add `causes/checkpoint/snapshot/review/dogfood/parity/` with the leaves above, written in the template `catalog_snapshot.md` uses (Goal, Estimate, Pre-conditions, Success Gates, References, Steps). +2. Amendment A3 in `__roadmap__/integrity/README.md`, sweeping the gates as it goes: + - the goal gains harness parity; + - the "done" gate covers `parity/`; + - the spend gate is reworded as above; + - the Status graph and Nodes table come from dirtree-rdm. +3. Write a briefing in the milestone format (verdict, done table with evidence, amendments, next table, goal check) to `__reports__/diet/07-briefing_integrity_level3_v0.md`. +4. Commit on `plan/integrity-level3` (cut from `origin/feat/integrity` 27d1d1dd), push, and open a PR into `feat/integrity` only, titled `merge(api): plan M6c level 3, harness parity`, with a body that speaks from outside. Bind it with the ccd_pr tools and send the coordinator a note. + +## Verification + +- `dirtree-rdm` validates the tree, and the Status graph matches the Nodes tables. +- Every leaf has a gate seen failing on the base, a model, an estimate and a cap. +- The briefing's goal check quotes the README purpose paragraph verbatim. +- `git log origin/feat/integrity..HEAD` shows planning commits only, and `main` is untouched. diff --git a/__reports__/diet/07-plan_integrity_level3_v1.md b/__reports__/diet/07-plan_integrity_level3_v1.md new file mode 100644 index 00000000..fcf23cb8 --- /dev/null +++ b/__reports__/diet/07-plan_integrity_level3_v1.md @@ -0,0 +1,173 @@ +# Plan: M6c Integrity, level 3, harness parity (v1, revision 2) + +Supersedes `07-plan_integrity_level3_v0.md`, after the maintainer's rulings on it. Approved. + + +## Context + +The P7 dogfooding pass ran an MCP experiment on OpenCode. The agent called `converter.convert` in every run, yet nothing Candler stored says so in a form that compares with Claude Code: +- The stored "catalog snapshot" comes from a constant program that always prints `servers: []` (`CATALOG_PROGRAM`, `commands/preflight.rs:40-42`). The CLI tests' fake docker prints the same constant, so the level-2 guard agreed with the code on the wrong value. +- OpenCode's trace reader marks every MCP call `origin: other` (`candler-harness-opencode/src/export.rs:160-203`). Claude Code's reader marks the same call `ToolOrigin::Mcp{server}` (`candler-harness-claude-code/src/parse.rs:386-398`). So traces of one cell do not compare across harnesses. +- Claude Code receives OpenCode's MCP keys verbatim (`prepare.rs:99-115`, a serde passthrough). +- What happens to each setting on each harness is stated in five different shapes, and two of them let a driver say nothing. + +The PR #70 plan is revised under Eliott's rulings: +1. **Harmonise the declaration lists.** Fold them into the one idiom this codebase does best ("harmonizing such lists is scalability"). The per-driver answer to every configuration path is part of that shape. A missing answer fails to compile, or fails one test that walks every path for every registered driver. A default empty answer does not count. +2. **Fix the Claude Code MCP passthrough, on both sides.** Map `local`/`remote` to Claude Code's own types. Claude Code refuses code mode, with a reason. +3. **Non-goals:** hooks an experiment can set, and CLAUDE.md/AGENTS.md. Both belong to a later feature round. Level 3 is integrity and alignment. +4. **No `opencode debug config` as a source.** The configured side is already single-sourced, by level 1's `one_reader` and `mcp_schema`. The level-2 snapshot surface goes along with its producer. +5. **Reframe.** Which servers the agent called is for the consumer to parse from the trace. Candler owes two things: a truthful record of what it installed (the resolved `mcp.*` values, which the cell digest already hashes) and a faithful trace that compares across harnesses. +6. **Asked in this session:** the census keeps **`census.tools` only**, as the comparability verdict's input, and never names servers. OpenCode code mode is **declared, not parsed**. +7. **Kept from revision 1:** Claude Code is the reference harness, and a defect found on its side is fixed in both drivers. The README says "per-run tool census". `codemode` defaults to `false`. + +The yardstick, from the README purpose paragraph: + +> - **Execution:** run agents under controlled conditions (experiment matrix, runners, isolation, per-run tool-catalog snapshots, provenance). + +## What the study settled + +| Question | Answer | Evidence | +|---|---|---| +| Which list idiom is best here? | A `const` array of `Copy` rows holding `&'static str` and enum fields, read by `const fn`s and by the page generators (`CONFIGURATION_PATHS`). Completeness is enforced by an exhaustive `match` with no wildcard, as `refusal_table!` does for errors. | `resolve/paths.rs:85-120`, `refusal.rs:301-416` | +| Which shapes are outliers? | `SettingRow` (a `Vec` of `String`s, optional, filled only by OpenCode). `Capabilities` (bools behind a builder whose unset fields default to `false`). The capability page's `ROWS` (fn pointers that string-match `"budget.per_run.turns"`). | `driver.rs:106-125`, `spec.rs:518-593`, `contract_pages/capabilities.rs` | +| Where can a per-driver answer live? | In each driver crate. Drivers depend on `candler-harness` and `candler-schemas`, not on `candler-core`, so the key enum lives in `candler-harness`. Only `crates/candler` sees every driver, so it hosts the walk over all drivers. | `Cargo.toml` graph | +| Is the configured MCP side single-sourced? | Yes. The cell digest's `comparable.values` holds every resolved value, `mcp.*` included. Dropping `comparable.snapshots` is enough, and nothing new is needed. | `execution.rs:1970` | +| What uses the census? | `manifest/compare.rs` `class_verdict`. When `census.init_tools` differ between arms and no declared `tools.*`/`mcp.*` factor differs, that is a comparability deviation. The trace cannot rebuild this list, because it records only calls (`EventKind` has no init event). | `compare.rs`, `trace.rs:741` | +| Who produces `tool-catalog-snapshot/1` in real use? | **The HTN consumer.** Its `scripts/capture_catalog_snapshot.py` writes `/1`, and its Tier D (`_catalog_snapshot.py`) reads `/1` and refuses anything else. Both were released in htn-creator-eval@0.5.3 (commit 11212ea1). They name Candler's `catalog-snapshot.schema.json` as the definition. Inside Candler only the constant and the tests produce it. | consumer repo | +| What did level 2 add for the consumer? | `InspectRun.catalog`, filled by `inspect.rs` `catalog_of`. It reads the blob behind `comparable.snapshots`, and it is in `inspect-run.schema.json`. | `inspect.rs:215-292` | + +So `/1` leaves Candler with its own producer, its resolve step and its level-2 consumer surface: a schema Candler neither writes nor reads is not Candler's. The HTN consumer keeps grading, since Tier D checks only the schema marker of its own committed file, and an HTN-side follow-up takes the schema file into that repository. + +## Design + +### One shape for every per-harness list + +The rows are `Copy` and hold `&'static str`. Every key is a fieldless enum with a `const ALL`. Each driver states each fact once, in an exhaustive `match` with no wildcard, and the drivers deny `clippy::wildcard_enum_match_arm`. Tables and pages are walks over `ALL`. Nothing is built as a `String` at run time. + +- **`Answer`** in `candler-harness`: `Mapped { construct: &'static str }`, `Candler { how: &'static str }`, `Refused { reason: &'static str }`. It is the one answer type for every key. +- **`AgentSetting`**: what an experiment sets that reaches the agent. That is model id, endpoint and effort; permission mode; allowed and disallowed tools; `env`; `inputs`; skills; MCP servers, with transport, `codemode` and `name`; the wall, turn and cost budgets; and session mode. A setting with a closed set of values carries the value, as in `Effort(EffortLevel)`, `Transport(Transport)` and `Codemode(bool)`. A new value is then also a compile error. +- **`DriverFact`**: what a driver does on its own. That is graceful stop, live events, the in-harness guard, execution outside the child, and the census. It replaces `Capabilities`'s bools and its builder. `budgets` and `session` are dropped, because `AgentSetting` already answers them and they would be a second statement. +- Both enums get a required trait method with no default: `answer(&self, AgentSetting) -> Answer` and `fact(&self, DriverFact) -> Answer`. Removed: `settings_table()`, `SettingRow`, `Capabilities` and `CapabilitiesBuilder`. Each `check_settings` refuses a set value whose answer is `Refused`, through the existing `experiment.setting_unsupported` code. OpenCode's hand-written refusals (`MODE_REFUSALS` and the others in `prepare.rs:131-195`) become match arms. +- **Configuration paths:** `PathRow` gains a required column `reach: Reach`, either `Agent(AgentSetting)` or `CandlerOnly`. `row()` takes it as an argument, so no row has a default. One test in `crates/candler` walks `CONFIGURATION_PATHS × registered drivers` and checks two things. A path that reaches the agent has its driver's answer on the configuration page. Every `AgentSetting` is reached by a path or is listed in an explicit `NO_PATH` const. +- **`refusal_table!` is unchanged.** It is already this idiom for errors: static rows, a match per variant, docs generated from the rows, and a cross-check with `codes.toml`. + +### MCP rendered from types on both drivers + +- Each driver builds its own file from the typed `McpServer`. Nothing goes through serde. +- **Claude Code:** + - `local` becomes `stdio`, with `command`/`args`/`env`. + - `remote` becomes `http`, with `url`/`headers`. P9 checks this against the Claude Code MCP doc and cites it, and refuses a field Claude Code has no place for. + - `name` becomes the key. + - `Codemode(true)` is `Refused`: "Claude Code offers MCP tools directly; it has no code mode". `Codemode(false)` is `Mapped`. +- **OpenCode** keeps its own shape, now built from types as well. +- Resolve writes the `codemode = false` default into the cell, which changes the digest (see Compatibility). A conformance check holds each rendered file to the keys its harness documents. + +### One trace form for an MCP call + +- The OpenCode reader marks `_` as `ToolOrigin::Mcp { server }`. It matches against the cell's resolved server names and does not guess from the spelling. +- Resolve refuses a set of servers whose OpenCode prefixes are ambiguous, for example `a` and `a_b`. +- The tool's own name is also spelled differently: `mcp__s__t` on Claude Code, `s_t` on OpenCode. So `ToolOrigin::Mcp` gets an optional `tool` field holding the bare tool name, and both traces carry one spelling. It is optional so that traces stored before the change still read, and one test parses an old trace without it. The coordinator accepted this wire change (`ToolOrigin` has `deny_unknown_fields`). +- The stored Claude Code trace keeps the raw `system/init` line, so a consumer can recover server status by post-processing, as for calls. This was the coordinator's condition for dropping `census.mcp_servers`, and P10 holds it as a gate. +- **Code mode, declared:** `Codemode(true)` on OpenCode is `Mapped`, and its construct says the trace records `execute` calls with empty `wrapped_calls`, so MCP calls inside them are not attributed. Nothing parses `execute`. The parity procedure runs with code mode off, the default. This is why the default is off: with code mode on, the trace shows only `execute`, and the two harnesses no longer compare. + +### The census, reduced + +- The census keeps `census.tools` and `census.init_tools`, and on both harnesses it comes from the harness's own report: Claude Code's `system/init`, and OpenCode's `serve` child at `GET /experimental/tool?provider=

&model=` (documented in the OpenCode server API). Candler's gateway stops recording a census, and `CensusSource` and `census.source` go, since every census is the harness's own (revision 3). +- `census.mcp_servers` is removed, and with it Claude Code's status reading. +- `SERVER_START_WAIT`'s doc (`jobs/orchestrate/servers.rs:22`) stops claiming the census records servers. +- No `mcp.list` or `debug config` collection is added. + +### The snapshot surface out + +- **Removed:** + - `CATALOG_PROGRAM`, `CommandCatalogProvider` and the provider seam behind it, if colgrep finds no other implementor; + - `CatalogStep` and the fake docker's catalog constant; + - `comparable.snapshots`, under a new digest version; + - `InspectRun.catalog` and `catalog_of`; + - the refusal codes only these emitted. +- `inspect` and the op API show the run's resolved `mcp.*` values from `comparable`. An old sealed run still reads. Its stored blob is left in the store and not shown, with no shim. +- **Also removed:** `tool-catalog-snapshot/1`, with its types, generated schema and fixtures. Its only producer and reader are the HTN consumer's, which gets a follow-up to hold the schema file itself. +- The old oracle vectors stay beside the new ones, because the maintainer's own stores (golden and HTN runs) hold old manifests, and their files say so. +- Before `InspectRun.catalog` is dropped, P12 confirms that nothing in htn-creator-eval@0.5.3 reads `inspect`'s `catalog` field. If something does, the drop waits for the coordinator. + +## Non-goals + +- Hooks an experiment can set, and CLAUDE.md/AGENTS.md or other instruction files. Both are for a later feature round. Neither is an `AgentSetting`, and no probe is run for them. +- `opencode debug config` as a source of anything. +- Reporting which servers the agent called, or their status. That is post-processing of the trace, done by the consumer. +- Parsing OpenCode `execute`. +- The HTN-side change that takes the `/1` schema file into that repository. It is a follow-up there. + +## Leaves (subtree `dogfood/parity/`; depth gives order) + +| Leaf | Level | Goal | Gate seen failing on the base | Model | Est / cap | +|---|---|---|---|---|---| +| **P8 `declaration`** | 3.1 | `Answer`, `AgentSetting` and `DriverFact`, with required `answer`/`fact` in both drivers. `SettingRow`, `settings_table`, `Capabilities` and its builder are removed. `PathRow.reach` and the walk over all drivers. | A driver without a session answer compiles and passes on the base, through the builder's default `false`. On the tip, a new variant fails to compile in both drivers (shown on a scratch branch). A cost cap on OpenCode is refused by its match arm. | Sonnet, lead review | $12 / $24 | +| **P9 `mcp_render`** | 3.2 | Both drivers render MCP from types. `local`→`stdio`, `remote`→`http`. Claude Code refuses `codemode = true`. The default is filled at resolve. | On the base, the `.mcp.json` of a cell with `type = "local"` and `codemode` carries both keys. On the tip it carries `stdio` and no `codemode`. | Sonnet | $6 / $12 | +| **P10 `trace_parity`** | 3.2 | OpenCode's reader attributes MCP calls as `ToolOrigin::Mcp`, with the optional bare `tool` name. Resolve refuses ambiguous prefixes. The census is reduced to tools, and the stored Claude Code trace keeps its raw `system/init` line. | On the base, the OpenCode export of a call to `s_t` with server `s` reads `origin: other`. | Sonnet | $8 / $16 | +| **P11 `pages`** | 3.2 | The capability and configuration pages are walks over `AgentSetting::ALL`, `DriverFact::ALL`, `CONFIGURATION_PATHS` and the registered drivers. `ROWS` and `cap()` go. | On the base, changing OpenCode's cost-cap answer leaves the page test passing. | **RiVault** Reasoning-Medium → Reasoning-Large → Sonnet. The Sonnet review is mandatory, and the lead checks that thinking ran. | tokens + $2 / $4 | +| **P12 `snapshot_out`** | 3.3 | Remove the constant producer, the resolve step, `comparable.snapshots` (new digest version) and `InspectRun.catalog`. `inspect` shows the resolved `mcp.*`. README and AGENTS.md swept. | A guard on `candler run` → `inspect`, with one declared server, finds the server in the shown `mcp.*` values. On the base `inspect` shows only a catalog that says `servers: []`. | Sonnet | $8 / $16 | +| **P13 `parity_run`** | 3.3 | One cell on both harnesses with a real stdio fixture server, code mode off. It asserts (a) the server is installed: in the resolved `mcp.*` and in each driver's rendered file; and (b) the stored trace shows the scripted call as the same `ToolOrigin::Mcp` form on both. It runs in container-e2e, and one live RiVault run per harness is the proof. | The same test on the base fails on OpenCode (`origin: other`). | Sonnet; the live runs on RiVault | $6 / $12 | +| **Seam review 3** | 3.4 | One review across P8–P13 with three questions first: added where it should replace? one answer per driver per key, one statement on the pages? one trace form across harnesses? Then the knowledge-transfer report. | | Sonnet | $3 / $6 | + +Writers never share files within a level: +- P9 owns both drivers' `prepare.rs` MCP renderers and `servers.rs`. +- P10 owns `export.rs`, `parse.rs`, `census.rs`, `gateway.rs`'s census (removed), the OpenCode census reader, and the resolve name check. +- P11 owns `contract_pages/`. + +P8 touches both drivers' `driver.rs` and the `prepare.rs` refusals before level 3.2 starts. P9 and P10 then rebase onto it. + +**Spend.** The leaves are estimated at $45 with a $90 cap, and lead orchestration at about $20. The gate is unchanged: **level 3 stays within $70, measured from transcripts, and no row passes its cap without stopping.** RiVault is used only for P11: its pages are generated and the page test holds them. P8–P10, P12 and P13 decide what the record and the trace say, so they stay on Claude. + +**Compatibility, ruled by the coordinator:** +- **P9, accepted:** the digest changes when the `codemode` default is filled, so the resolved cell records what Candler installs. +- **P10, accepted:** the optional `tool` field on `ToolOrigin::Mcp`, holding the bare tool name. It is a wire change, because of `deny_unknown_fields`, and it is optional so old traces still read. +- **P12, accepted:** the new digest version without `snapshots`. Its vectors are added beside the old ones (`cell_digest.toml`, `catalog_content_digest.toml`), which stay for the maintainer's own stores and say so. `InspectRun.catalog` leaves `inspect-run.schema.json` once P12 has confirmed that htn-creator-eval@0.5.3 has no `inspect` caller reading it. +- **`/1`:** it leaves Candler in P12 (revision 3). htn-creator-eval@0.5.3 keeps grading; an HTN-side follow-up takes the schema file. + +## The principle, carried into every agent I supervise + +Level 3 is one pass of the alignment work. If an implementer makes its gate pass by leaving excess behind, the level fails its own purpose, even when every test is green. + +- **Brief.** + - Each implementer reads `AGENTS.md` "What sane work means in Candler", then a paragraph written for its leaf on the three levels: + - how it is developed: probe before building, size to what is free, a RiVault run only when the work needs it; + - what it leaves: one producer, one reader, one shape, nothing passed through, nothing kept for compatibility without a reader; + - how it is consumed: what the experimenter reads, what the record and the trace say. + - `integrity-level3-implementer-brief.md` adds the machine rules: one target dir per leaf, removed at merge; at most 3 builds; containers named and removed by name, never pruned; scratch deleted at each step. +- **Joints.** I talk with each implementer when its guard first fails on the base, and before its PR. I ask what the change leaves at each level, and I read the diff for a second producer, a second reader, a passthrough or a shim. Examples: `Capabilities` kept beside `DriverFact`; `settings_table` kept "for the pages"; a census field kept with no reader. +- **Acceptance.** A leaf that adds where it should replace is re-briefed, not merged. Each leaf report has a "What it leaves" section, which seam review 3 reads first. +- **Sweep.** P12 rewords the README phrase, `AGENTS.md`'s stored-state list and the live candler-v1 M6c Goal that quotes the phrase, in one change. Done leaves keep their words as history. +- **My own work.** The same rules apply to how I lead: subagents only where a brief can be written, no polling, spend measured from transcripts at each joint. + +## Judged on three levels + +- **Development.** A new setting, value or driver fact is a compile error in every driver until each answers it. A new path cannot be written without saying whether it reaches the agent. Leaves are cut by concept: one shape, render, trace form, removal, parity. +- **What it leaves.** + - Removed: `SettingRow`, `settings_table`, `Capabilities` and its builder, `ROWS` and `cap()`, the serde passthrough, OpenCode's hand-written refusal lists, the constant producer and its resolve step, `comparable.snapshots`, `InspectRun.catalog`, and `census.mcp_servers`. + - Added: `Answer`, two key enums of one shape, a `reach` column, and one name check at resolve. + - Kept: `CONFIGURATION_PATHS` (extended), `refusal_table!` and `census.tools` (one reader). `/1` is removed with the producer. +- **How it is consumed.** One generated page says, per harness, what happens to each setting and fact. `inspect` shows the MCP config Candler installed. The trace of one cell attributes the same MCP call the same way on both harnesses, which is what a consumer parses. Code mode's limit is stated where it is chosen. +- **Trades, accepted by the coordinator:** + - P8 grows, which costs more to develop and buys one shape to leave. + - Claude Code's record loses its server status, which buys one fewer producer. The trace keeps the calls and the raw `system/init` line, so the consumer can still recover the status (a P10 gate). + - `/1` leaves Candler, which costs the HTN consumer one follow-up and leaves Candler no schema it does not use. + +## After approval (in this session) + +1. With dirtree-rdm, rework `parity/`: + - rewrite `declaration.md`, `mcp_render.md`, `pages.md`, `snapshot_out.md` and `parity_run.md`; + - replace `census.md` with `trace_parity.md`; + - update `seam_review_three.md`'s third question and its report list. + + Then update the A3 row of the Amendment Log with revision 2, and validate. +2. Update `__reports__/diet/07-plan_integrity_level3_v0.md` to this plan and `08-briefing_integrity_level3_v0.md`: the Why section with rulings 1–6, the Next table and the Goal check. +3. Commit `rdm(api):` and `reports(api):` on `plan/integrity-level3`, push, update the PR #70 body (it speaks from outside), and send the coordinator a note. + +## Verification + +- `dirtree-rdm validate` passes, the Status graph matches the Nodes tables, and every link resolves. +- Every leaf has a gate seen failing on the base, a model, an estimate and a cap. +- The briefing quotes the README purpose paragraph verbatim. +- No node mentions `debug config`, `mcp.list`, `census.mcp_servers`, hooks or instruction files, except as non-goals. +- `git log origin/feat/integrity..HEAD` shows planning commits only, and `main` is untouched. diff --git a/__reports__/diet/08-briefing_integrity_level3_v0.md b/__reports__/diet/08-briefing_integrity_level3_v0.md new file mode 100644 index 00000000..e3cc1682 --- /dev/null +++ b/__reports__/diet/08-briefing_integrity_level3_v0.md @@ -0,0 +1,51 @@ +# Briefing: M6c Integrity, level 3 planned (v0) + +## Verdict + +Candler's product goal, from the README purpose paragraph: + +> A domain-agnostic core for evaluating LLM-based agents. Candler has two equal halves behind one operation API: +> - **Execution:** run agents under controlled conditions (experiment matrix, runners, isolation, per-run tool-catalog snapshots, provenance). + +Levels 1 and 2 of M6c made each kind of stored state have one producer and each input have one reader, on the paths a consumer uses. The dogfooding pass then showed where Execution falls short. Under OpenCode, a run's record names no MCP server. The stored "catalog snapshot" comes from a constant that always says `servers: []`. And nothing declares, per harness, what happens to each setting an experiment makes. So "controlled conditions" holds for one harness at a time, not across two, and the "snapshot" is not an observation. Level 3, harness parity, is planned and approved. It is on the roadmap as amendment A3, with Claude Code as the reference harness. No code has changed yet. + +## Done + +| Piece | What it gave Candler | How we know | +|---|---|---| +| Level 1: P0, P1, P2, P4 chain, P6 (#59–#63) | One producer for sealed runs, one oracle for collect, one typed reader per experiment input, kill off a TTY, the `AGENTS.md` principle and the leaf template | Each guard was seen failing on the base and passing on the tip (`__reports__/diet/leaves/*_v0.md`). Spend per row stayed within its cap (P1 $7.82 against a $20 cap; P4 $11.79 against $24). | +| Seam review 1 and its fixes (#66–#68) | The MCP schema refuses what its reader refuses, replicates are checked once, and every stored output keeps its execute bit | 12 findings at $4.87, and the fixes at $6.1 | +| P5 catalog snapshot (#64) | A sealed run stores a catalog blob, and `inspect` shows it | Its guard passed, but the fake docker printed the same constant as production (finding (1)) | +| Seam review 2 and P7 dogfooding (#69) | An outside consumer ran a two-arm MCP experiment end to end on OpenCode and graded it | 6 manifests, each naming a blob that says `servers: []`, while the agent called `converter.convert` in every run (`05-findings_dogfooding_pass_v0.md`) | + +## Why the plan changed + +- **A3, level 3 (this amendment).** The dogfooding finding is a second producer (D1) sitting behind a capability Candler lacks. A record that is not observed, and settings that no harness declares, make every parity comparison an act of faith. Eliott approved the direction and made four rulings: + - Claude Code is the reference harness; + - a defect found on the Claude Code side is fixed in both drivers; + - the README says **"per-run tool census"**; + - **`codemode` defaults to `false`**, so by default the agent sees MCP tools directly on both harnesses. +- The amendment rewords the campaign goal, its done gate and its spend gate in the same change. Levels 1 and 2 stay within the $127 Eliott approved, and level 3 gets $70. + +## Next + +| Leaf | What it adds | What an experimenter can then do | +|---|---|---| +| P8 declaration | `AgentSetting`, one typed list of what reaches the agent. Every driver must answer every entry: mapped, provided by Candler, or refused with a reason. A new entry is a compile error until every driver answers it. | Know that no setting is silently dropped on either harness | +| P9 MCP render | Each driver writes its own MCP configuration from types. Claude Code stops receiving OpenCode keys. The `codemode` default becomes `false` and is written into the resolved cell. | Run one MCP cell on both harnesses and have each agent see the same tools | +| P10 census | The census names servers, their status and their tools on both harnesses, including OpenCode code mode | Read from the run record which servers and tools the agent had | +| P11 pages (RiVault, with a Sonnet review) | Capability and configuration pages generated from the declaration, plus a census page | Read one page that says per harness what happens to each setting | +| P12 snapshot out | The constant producer and its matching fake are removed. The cell digest compares the resolved servers. The README and `AGENTS.md` say "census". | Trust that the record of tools is an observation, and compare cells by the servers they declare | +| P13 parity run | A container-e2e guard runs one cell on both harnesses with a real server, plus one live RiVault run per harness | Rely on CI to catch a harness falling out of parity | +| Seam review 3 | A cross-leaf review that asks first what the level left behind | | + +The estimates total $47, with $96 in caps, and lead orchestration is about $20. Two decisions are open before P9 and P12, and both go to the coordinator: the digest change from filling the `codemode` default, and dropping the snapshot from `comparable` under a new digest version. + +## Goal check + +| Part of the goal | Proven | Pending | +|---|---|---| +| "run agents under controlled conditions" | Per harness: isolation, budgets and permissions each have one reader | Across harnesses: one declaration answered by each driver (P8, P9), and a parity guard (P13) | +| "per-run tool-catalog snapshots", to become "per-run tool census" | Claude Code's census lists tools and servers from `system/init` | OpenCode's servers and tools (P10); the constant producer removed (P12) | +| "provenance" | Sealed runs, outputs with their execute bit, and the catalog digest in the manifest | A digest that compares the resolved servers instead of a constant snapshot (P12) | +| "domain-agnostic", "two equal halves behind one operation API" | Unchanged by level 3 | The op API still cannot be reached from outside (finding (2), outside level 3) | diff --git a/__reports__/diet/08-briefing_integrity_level3_v1.md b/__reports__/diet/08-briefing_integrity_level3_v1.md new file mode 100644 index 00000000..5b56d2dd --- /dev/null +++ b/__reports__/diet/08-briefing_integrity_level3_v1.md @@ -0,0 +1,66 @@ +# Briefing: M6c Integrity, level 3 planned (v1) + +Supersedes `08-briefing_integrity_level3_v0.md`, after the maintainer's rulings on the level-3 plan. + +## Verdict + +Candler's product goal, from the README purpose paragraph: + +> A domain-agnostic core for evaluating LLM-based agents. Candler has two equal halves behind one operation API: +> - **Execution:** run agents under controlled conditions (experiment matrix, runners, isolation, per-run tool-catalog snapshots, provenance). + +Levels 1 and 2 of M6c gave each kind of stored state one producer, and each input one reader, on the paths a consumer uses. The dogfooding pass then showed where Execution still falls short: +- The stored "catalog snapshot" comes from a constant that always says `servers: []`. +- OpenCode's trace marks an MCP call `origin: other`, while Claude Code's marks the same call with its server, so the traces of one cell do not compare. +- Claude Code receives OpenCode's MCP keys verbatim. +- What each harness does with each setting is stated in five shapes, two of which let a driver say nothing. + +So "controlled conditions" holds for one harness at a time, not across two. Level 3, harness parity, is planned and approved in its second revision (`07-plan_integrity_level3_v1.md`). It is on the roadmap as amendments A3 and A4, with Claude Code as the reference harness. No code has changed yet. + +## Done + +| Piece | What it gave Candler | How we know | +|---|---|---| +| Level 1: P0, P1, P2, P4 chain, P6 (#59–#63) | One producer for sealed runs; one oracle for collect; one typed reader per experiment input; kill off a TTY; the `AGENTS.md` principle and the leaf template | Each guard was seen failing on the base and passing on the tip (`__reports__/diet/leaves/*_v0.md`). Spend per row stayed within its cap: P1 $7.82 against $20, P4 $11.79 against $24. | +| Seam review 1 and its fixes (#66–#68) | The MCP schema refuses what its reader refuses; replicates are checked once; every stored output keeps its execute bit | 12 findings at $4.87, and the fixes at $6.1 | +| P5 catalog snapshot (#64) | A sealed run stores a catalog blob, and `inspect` shows it | Its guard passed, but the fake docker printed the same constant as production (finding (1)) | +| Seam review 2 and P7 dogfooding (#69) | An outside consumer ran a two-arm MCP experiment end to end on OpenCode and graded it | 6 manifests, each naming a blob that says `servers: []`, while the agent called `converter.convert` in every run (`05-findings_dogfooding_pass_v0.md`) | + +## Why the plan changed + +- **A3, level 3.** The dogfooding finding is a second producer (D1) standing in for a record Candler does not keep. Two rulings came with it: Claude Code is the reference harness, and a defect found on its side is fixed in both drivers. The README is to say "per-run tool census", and `codemode` defaults to `false`. +- **A4, revision 2 (this briefing).** The maintainer ruled on the first plan: + - **One shape for every per-harness list.** The codebase's best list idiom is `CONFIGURATION_PATHS`'s const array of `Copy` rows. Its completeness check is the exhaustive match that `refusal_table!` uses. `SettingRow`, `Capabilities` and the capability page's hand-written rows fold into it. A missing answer is a compile error, not a default `false`. + - **What the agent called is the consumer's to parse from the trace.** Candler owes a truthful record of what it installed and a trace that compares across harnesses. The census therefore keeps `census.tools` only, as the comparability verdict's input. The leaf that was to collect server status (`census.md`) is blocked, and `trace_parity.md` aligns both trace readers on one MCP origin instead. + - **Code mode is declared, not parsed.** With code mode on, OpenCode's trace shows only `execute`. That is why the default is off, and OpenCode's answer says so. + - **`tool-catalog-snapshot/1` leaves Candler.** Its only producer and reader are the HTN consumer's capture script and grader (htn-creator-eval@0.5.3), and Candler neither writes nor reads it. That release keeps grading, and an HTN-side follow-up takes the schema file. + - **Non-goals:** hooks an experiment can set, and CLAUDE.md/AGENTS.md. Both are left to a later feature round. +- The level's spend gate is unchanged at $70, and the leaves are now estimated at $45, with $90 in caps. + +## Next + +| Leaf | What it adds | What an experimenter can then do | +|---|---|---| +| P8 declaration | `Answer`, `AgentSetting` and `DriverFact`, each answered by every driver in an exhaustive match. Every configuration path says whether it reaches the agent. `SettingRow` and `Capabilities` are removed. | Know that no setting or harness behaviour goes unstated on either harness | +| P9 MCP render | Each driver writes its own MCP file from types. On Claude Code, `local` becomes `stdio` and `remote` becomes `http`, and Claude Code refuses code mode, with its reason. The `codemode` default is written into the cell. | Run one MCP cell on both harnesses and have each install the same server | +| P10 trace parity | OpenCode's trace attributes an MCP call to its server, as Claude Code's does, with an optional bare `tool` name that old traces can lack, and resolve refuses ambiguous server prefixes. The census stops naming servers and names its source, `system/init` for Claude Code and the gateway's record of the model request for OpenCode, and the stored Claude Code trace keeps its raw `system/init` line. | Parse the same MCP call the same way from either harness's trace | +| P11 pages (RiVault, with a Sonnet review) | The capability and configuration pages are walks over the declaration and the drivers | Read one page that says, per harness, what happens to each setting | +| P12 snapshot out | The constant producer, its resolve step, `comparable.snapshots` and `InspectRun.catalog` are removed. `inspect` shows the resolved MCP config, once no `inspect` caller in htn-creator-eval@0.5.3 is found reading the catalog. The README, `AGENTS.md` and the live candler-v1 M6c Goal say "census". The old oracle vectors stay, for the maintainer's own stores. `/1` leaves Candler. | See in `inspect` what Candler installed, and nothing it did not observe | +| P13 parity run | A container-e2e guard runs one cell on both harnesses against a real server. It asserts that the server is installed and that the call appears in the same trace form, and one live RiVault run per harness backs it. | Rely on CI to catch a harness falling out of parity | +| Seam review 3 | A cross-leaf review that asks first what the level left behind | | + +The coordinator accepted the three compatibility items: +- P9: the digest changes once the `codemode` default is filled. +- P10: an optional `tool` field on the trace's MCP origin, holding the bare tool name. +- P12: a new digest version without snapshots, and `InspectRun.catalog` dropped, after P12 checks that no `inspect` caller in the HTN consumer reads it. + +`/1` leaves Candler in P12. The HTN consumer gets a follow-up to hold its schema file. + +## Goal check + +| Part of the goal | Proven | Pending | +|---|---|---| +| "run agents under controlled conditions" | Per harness: isolation, budgets and permissions each have one reader | Across harnesses: one shape answered by each driver (P8, P9), and a parity guard (P13) | +| "per-run tool-catalog snapshots", to become "per-run tool census" | Claude Code's and OpenCode's census list the tools offered at session start, and the comparability verdict reads them | The constant producer removed (P12). Each MCP call traced in one form on both harnesses (P10) | +| "provenance" | Sealed runs, outputs with their execute bit, and the resolved values, `mcp.*` included, in the cell digest | `inspect` shows the installed MCP config instead of a constant snapshot (P12) | +| "domain-agnostic", "two equal halves behind one operation API" | Unchanged by level 3 | The op API still cannot be reached from outside (finding (2), outside level 3) | diff --git a/__reports__/diet/leaves/catalog_snapshot_v0.md b/__reports__/diet/leaves/catalog_snapshot_v0.md new file mode 100644 index 00000000..4db8bf2a --- /dev/null +++ b/__reports__/diet/leaves/catalog_snapshot_v0.md @@ -0,0 +1,40 @@ +# Catalog snapshot leaf, v0 + +A sealed run stores the canonical bytes of the tool catalog it ran with; `candler inspect` and the +op API's inspect result show it. + +## What changed + +- `CatalogSnapshot::content_text` (schemas) is the RFC 8785 text without `captured_at`; + `content_digest` hashes it, so no digest changes. +- `CatalogStep` puts that text in its `StepReport.blobs`, a field outside the cell's values. `resolve` + writes nothing to the store. +- `cells_of` copies the blobs of the cell's level into `CellRun.blobs`; `drive` stores each with + `RunWriter::blob` in the seal task, just before `seal_run` stores the outputs. +- `InspectRun.catalog` (wire, regenerated schema) carries the stored catalog as JSON; `inspect` reads + it through the manifest's `catalog` snapshot digest. A run with no stored blob has no `catalog` and + its text form says `catalog not stored`. + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| Guard fails on the base | PASS | scratch worktree at `c4a48cc1` plus the guard: `FAIL guard_catalog_snapshot::a_sealed_run_stores_the_catalog_it_ran_with_and_inspect_shows_it`, `the catalog digest resolves to a blob: Os { code: 2, kind: NotFound ...}` | +| Guard passes on the tip | PASS | `cargo nextest run -p candler -E 'test(/a_sealed_run_stores_the_catalog/)'`: 1 passed | +| Step 2 bite | PASS | scratch worktree on the tip with `writer.blob(...)` replaced by `let _ = text;`: guard FAIL with the same blob-not-found panic | +| `resolve` stays a pure read | PASS | the step only returns the text in its report; no store handle reaches `resolve` | +| Snapshot stored by the sealing task; run from `World` | PASS | guard uses `cli_run::world()`, `launch`, `finish` | +| No digest or golden vector edited | PASS | workspace nextest 751 passed, 31 skipped; no golden file in the diff | +| fmt, clippy `-D warnings`, nextest, doc `-D warnings` | PASS | all four clean | +| container-e2e | not run locally | runs on the PR | +| Fresh Sonnet verifier | not mine | the lead runs it | + +## Departures from the brief + +- The op API's inspect result is `InspectRun`, whose `catalog` is a JSON value, not a `CatalogSnapshot`: + the stored bytes omit `captured_at`, which the snapshot reader requires. +- `seal_run_observed` already takes seven arguments (clippy limit), so the blob write is in the seal + task before `seal_run`, not a `SealStep`; the observer does not see it. +- The schemas commit adds a field to `InspectRun`, so the workspace builds only with the next commit; + `candler-schemas` builds and passes alone. +- The fake docker prints a catalog with no servers, so the guard shows the provider, not tool names. diff --git a/__reports__/diet/leaves/collect_oracle_v0.md b/__reports__/diet/leaves/collect_oracle_v0.md new file mode 100644 index 00000000..4bcecc85 --- /dev/null +++ b/__reports__/diet/leaves/collect_oracle_v0.md @@ -0,0 +1,111 @@ +# Collect oracle: leaf report v0 + +Conformance now checks every driver's `collect` against the files the scripted agent wrote, not +against the driver's own fixture (cause D1, defect B1). `Case` carries `agent_wrote`; the check +feeds those files to the driver's `collect` and asserts that every one is kept by its file globs, +naming the ones a driver leaves out. + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| With B1's fix reverted on a scratch branch, the shared conformance case fails for OpenCode only, naming the files the agent wrote | PASS | see §Bites: on the tip with the revert, `candler-harness-opencode conformance_opencode_recorded_runs` fails with `the collect does not keep the files the agent wrote: ['notes.md', 'outputs/answer.txt']`; `candler-harness-claude-code conformance_claude_code_fixtures` passes on the same tree | +| On the base, the same revert passes conformance | PASS | see §Bites: on `origin/feat/integrity` with the revert, `candler-harness-opencode conformance_opencode_recorded_runs` passes | +| The oracle is the set of files the scripted agent wrote; `Case::with_collect` stays only where it checks something the shared case does not | PASS | see §Oracle and §`with_collect` | +| `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass | PASS | `fmt --check` clean; clippy `-D warnings` clean; `nextest run --workspace` 741 passed, 32 skipped; doc with `-D warnings` generated | + +## Oracle + +The shared case's oracle is `Case::agent_wrote`: the set of files the scripted agent wrote, named +by the case and never copied from what a driver's fixture expects. `check_collect_oracle` runs the +driver's `collect` with no observed session (a harness's file globs do not depend on the sessions a +stream named) and reads only its `File` specs; a file is kept when a keep glob matches it and no +`!` glob drops it. The two harness drivers and the shape suite run the case. Because the workspace +holds only the files the agent wrote, "keeps exactly those files" reduces to "keeps every one the +agent wrote", and a missing file is named in the failure. + +The glob matcher (`glob_matches`) reproduces the grammar the core's collector reads (`**`, `**/`, +`*`, `?`, literal characters, `!` exclusion), so it is not more lenient than +`candler-core::runner::exec::gather::collect_files`; the unit test +`conformance::tests::collect_glob_matches_the_core_grammar` pins the forms. + +## `with_collect` + +No `Case::with_collect` was removed: each remaining one checks something the shared case does not. + +- `candler-harness-opencode/tests/it/conformance.rs` keeps its `with_collect` of the export `Exec` + command. The oracle runs `collect` with no observed session, so it never exercises the export + command the fixture pins; removing the fixture would lose that check. +- `conformance_shapes.rs` keeps the `lines_cases` glob (`home/.claude/projects/*/cc-1.jsonl`) and + the `document_cases` export command, each tied to a session the oracle's session-less run never + produces. +- `candler-harness-claude-code` never set `with_collect`; the shared case is where its `collect` + first gets a check. + +## Bites + +Both bites rebuilt the OpenCode driver crate on its own scratch branch and target dir, per the +leaf's scratch rules. The revert of B1 is `git revert` of `8d88cb50` (the fix's change to +`OpenCodeDriver::collect`), resolved by keeping the revert's removal of the now-redundant +`guard_build_context` byte guard that B1 itself added; `driver.rs`, the opencode `conformance.rs` +and `guard_opencode_driver.rs` applied cleanly. + +| Bite | Scratch branch (from) | Command | Red seen | Reverted | +|---|---|---|---|---| +| Revert B1 on the tip | `scratch/collect_oracle-tip` (from `d39e367f`, the tip with the shared case) | `CARGO_TARGET_DIR=…/collect_oracle-tip cargo nextest run -p candler-harness-opencode -E 'test(/conformance/)'` | `conformance_opencode_recorded_runs` FAILED: `Failure { case: Some("collect_keeps_the_files_the_agent_wrote"), check: "collect", detail: "the collect does not keep the files the agent wrote: [\"notes.md\", \"outputs/answer.txt\"]" }` | yes | +| Claude Code passes the same reverted tip | same scratch | `CARGO_TARGET_DIR=…/collect_oracle-tip cargo nextest run -p candler-harness-claude-code -E 'test(/conformance/)'` | none: 7 tests passed, `conformance_claude_code_fixtures` included | (no red) | +| Revert B1 on the base | `scratch/collect_oracle-base` (from `origin/feat/integrity`, no shared case) | `CARGO_TARGET_DIR=…/collect_oracle-base cargo nextest run -p candler-harness-opencode -E 'test(/conformance/)'` | none: `conformance_opencode_recorded_runs` passed | yes | + +The tip bite shows the shared case catches B1 and names the files; the Claude Code pass on the same +tree shows it fails for OpenCode only; the base bite shows that without the shared case the same +revert is invisible. + +## Deviations + +- The leaf's step-1 commit subject is `test(harness): …`, but `harness` is not an allowed scope + (CONTRIBUTING.md §Scopes and `cog.toml`); the commit-msg hook rejects it. The subject was + committed as `test(library): check collect against the files the agent wrote`, using the scope + the shared harness crate has used before, and the predicate of the subject is unchanged. +- A pre-existing flaky test, `candler-core::it guard_protocol_client::every_failure_path_of_an_evaluator_is_accounted_for`, + failed once under full-suite parallel load (`NotMeasured("deadline")` where `Reported` was + expected); it passed when run alone and on the final full `nextest run --workspace`, and this leaf + touches none of its code. + +## Sonnet fallback + +The RiVault attempt (`d39e367f`) failed the second gate as the leaf writes it. This section +supersedes its Oracle, `with_collect` and Bites sections and the gate rows above that rest on them. + +| What the RiVault attempt did | Why it failed | Superseded by | +|---|---|---| +| A hand-typed `agent_wrote` list, copied in three tests, with no workspace | No scripted agent wrote the files | The case writes `agent_wrote` into a real temp workspace, beside `harness_wrote` (a driver-private skill file) | +| `glob_matches`/`walk`, a hand copy of the core glob grammar | A second reader of the same input (D5) | Deleted, with its unit test; the setup's `collector` runs `candler_core::runner::exec::gather::collect_files`, the code real runs use | +| Asserted only that every file is kept | "Exactly" unchecked | The stored set must equal `agent_wrote`; the failure names `missing` and `extra` paths | +| OpenCode `with_collect` carried `**/*` and `!.opencode/**` globs | A second hand-typed collect spec | Replaced by `Case::with_collect_commands`, which compares only the command and exec specs (the export command); file specs are checked by the workspace case | + +Placement: `candler-harness` cannot depend on `candler-core` (core depends on it). The collector is +passed in as `Setup::with_collector(fn(&Path, &[CollectSpec]) -> io::Result>)`; each +test that calls `run` gives a three-line adapter over `collect_files`, with `candler-core` as a +dev-dependency of `candler-harness`, `candler-harness-claude-code` and `candler-harness-opencode`. +A case that names `agent_wrote` with no collector fails. Claude Code, OpenCode and the shape suite +run the case; the shape suite also shows a driver that stores nothing (names `missing`), one that +stores the private file (names `extra`), and one that stores exactly the agent's files (passes). + +Bites, on scratch worktrees with their own target dirs, `git revert 8d88cb50` with +`guard_build_context.rs` reset to HEAD (the revert of the opencode `conformance.rs` was resolved to the +tip's file on the tip; it applied on the base): + +| Tree | Result | +|---|---| +| Tip + revert (`Compiling candler-schemas, candler-testkit, candler-harness, candler-core, candler-harness-opencode, candler-harness-claude-code`) | 14 run, 13 passed, 1 failed: `candler-harness-opencode conformance_opencode_recorded_runs`: `the collect does not store exactly the files the agent wrote: missing ["notes.md", "outputs/answer.txt"], extra []`; Claude Code passes | +| Base + revert, fresh compile of the same crates | 14 run, 14 passed | +| Tip | fmt clean, clippy `-D warnings` clean, `cargo doc -D warnings` clean, 14 conformance tests pass | + +## Verifier + +Left for the lead's fresh Sonnet verifier, with this leaf, this report and the diff. + +## Left + +Nothing in scope. The build gates pass, and `container-e2e` is a repository check for the lead to +watch on the pull request. diff --git a/__reports__/diet/leaves/conventions_v0.md b/__reports__/diet/leaves/conventions_v0.md new file mode 100644 index 00000000..3e675565 --- /dev/null +++ b/__reports__/diet/leaves/conventions_v0.md @@ -0,0 +1,29 @@ +# Conventions leaf, v0 + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| AGENTS.md section replaced, word for word, nothing else changed but the link | PASS | `git show f57ba4fd --stat` touches AGENTS.md only; heading `What sane work means in Candler`; old heading gone; paragraph re-wrapped to 100 columns, no word changed | +| Template holds the conventions of D3 | PASS | `__roadmap__/leaf_template.md`, six conventions, convention 6 reads "estimate, its cap as a stop action, the target dir the campaign README names, and their cleanup" | +| AGENTS.md §Where things are written down links the template | PASS | last bullet of that section | +| Fresh reader finds no leaf breaking the template | PASS after fixes | see below | + +The gates are file-content checks; none can be shown failing on a code base, because this leaf has no code. + +## Fresh Sonnet reader (given the template and the leaf list) + +Fixed (prose fields only): +- Convention 6, cleanup: the Estimate of collect_oracle, kill_off_tty, one_reader, sealed_run_producer and catalog_snapshot now says builds use the target dir the campaign README names, removed at the leaf's merge. +- Convention 6, stop action: seam_review_one, seam_review_two and dogfooding_pass gained "At the cap, stop, commit what is green, and list what is left." +- catalog_snapshot's gate still named the `candler-diet` target dir (nested below the level the first sweep covered); it now names the campaign README's. + +Not changed: +- Convention 4, seam_review_two hands the reviewer plan v2, seam review 1's report and the diff since it, not the milestone's whole diff. This changes review scope, a design choice for the lead, not a prose field. +- Convention 2, gates of one_reader (3 to 7), sealed_run_producer (2 to 4), catalog_snapshot (2 to 4), kill_off_tty (2), collect_oracle (2), both seam reviews and conventions.md are structural, process or invariant checks. They are guards beside the observation gates of the same leaf, not substitutes for them, so I did not rewrite them; the lead may judge otherwise. +- Convention 5 for seam_review_one, seam_review_two, conventions and dogfooding_pass: the campaign README's gate "Every merge into `feat/integrity` waited for a green `container-e2e`" covers them. +- conventions.md has no target dir sentence: it runs no builds. + +## Left + +Nothing in scope. Cog accepted scope `contributing` for every commit. diff --git a/__reports__/diet/leaves/declaration_v0.md b/__reports__/diet/leaves/declaration_v0.md new file mode 100644 index 00000000..78531c79 --- /dev/null +++ b/__reports__/diet/leaves/declaration_v0.md @@ -0,0 +1,132 @@ +# Leaf P8 declaration: every per-harness list in one shape + +Base `bf1f03ea` (`origin/feat/integrity`), tip `3ffbefb8`. Commits: `7b0e80fa` (MCP transports answered per driver), `af34f725` (one shape), `8318f2dd` (first report), `3ffbefb8` (one reader in `set_by`). The first implementer ran over its call cap after the second commit; a second round finished the leaf. + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| `SettingRow`, `settings_table`, `Capabilities`, builder and `BudgetCaps` gone, no second table | PASS | tree builds; `AgentSetting::ALL` and `DriverFact::ALL` are the only lists, read through `answer` and `fact` | +| Guards fail on the base | PASS | `conformance_claude_code_fixtures`: "the driver answers no row for model.id"; the walk listed 20 unanswered (driver, path) pairs; a `Capabilities::builder()` driver with no `.session(..)` passed conformance with the default `false` (39/39) | +| One variant each in `AgentSetting` and `DriverFact` fails to compile in both drivers | PASS | scratch worktree, nothing committed. `claude-code/src/driver.rs:203 error[E0004]: non-exhaustive patterns: AgentSetting::BiteSetting not covered`; `claude-code/src/driver.rs:276 ... DriverFact::BiteFact not covered`; `opencode/src/driver.rs:163 ... DriverFact::BiteFact not covered`; `opencode/src/prepare.rs:112 ... AgentSetting::BiteSetting not covered` | +| Wildcard denied in both drivers | PASS | `clippy::wildcard_enum_match_arm = "deny"` is workspace-wide; clippy clean | +| OpenCode cost cap refused through `Refused` arm; hand-written lists gone | PASS | bite (a): the cost arm made `Mapped` fails `guard_opencode_driver::opencode_command_line_maps_or_refuses_every_setting`: `budget.per_run.max_cost_usd *: the case and the answer disagree`, left `true`, right `false` (`guard_opencode_driver.rs:446`) | +| `PathRow.reach` and the walk | PASS | bite (b): `model.endpoint` moved to `Reach::CandlerOnly` fails `guard_driver_answers::every_agent_setting_is_reached_by_a_path_or_has_no_path`: `reached by no path: [ModelEndpoint]` (`guard_driver_answers.rs:32`) | +| `guard_silent_acceptance.rs` rows read `answer` | DEVIATION | The file holds no driver rows (resolve, plan and MCP-reader refusals only), so there is nothing to read from `answer`. The driver-versus-answer row is `guard_opencode_driver`'s case loop, which reads `answer` (bite (a) shows it). Two rows were added for the one reader: an effort and a permission mode that name nothing are refused with `experiment.cell_value_invalid` at `/model/effort` and `/permission_mode` | +| Hooks and instruction files not `AgentSetting` variants | PASS | none added | +| "What it leaves" at three levels | PASS | below | +| Verifier (Step 3) | MISSING | not run here; the lead dispatches it | +| fmt, clippy `-D warnings`, doc `-D warnings` | PASS | all clean on `3ffbefb8` | +| nextest workspace | PASS | `756 tests run: 755 passed, 1 failed, 31 skipped`. The one failure, `guard_protocol_client::every_failure_path_of_an_evaluator_is_accounted_for` (`cancel.sh`: A1 `NotMeasured("deadline")` where `Reported` was expected), is a deadline race under load unrelated to the change: it passed in the first full run and in three reruns alone (8.7 s each). The 31 skipped are the container-gated tests, as on the base | + +## What changed in the second round + +- **One reader of the servers.** `AgentSetting::set_by` re-read `mcp.servers` from raw JSON with `.ok()` and guessed the transport. It now reads each entry through `mcp::read`, the reader behind `mcp::servers`, and propagates its error. `read` is `pub(crate)`; `by_name` is not applied, because `name` is what `McpName` reports. +- **One check of effort and permission mode.** `set_by` refuses text no `EffortLevel` or `PermissionMode` names with `DriverError::InvalidValue` naming the path and the accepted texts. OpenCode's two duplicate checks (`EFFORT_LEVELS`, `OTHER_MODE`, `EFFORT_LEVEL`) are deleted, with the two table cases that tested them. +- **Right error variant.** Cell reads no longer map to `VersionOutput`: `Cell::text` and `Cell::value` give `InvalidValue`, and no path text is parsed at run time. +- **Honest arm.** The Claude Code driver passes the level to `--effort` unchanged, so `Effort(Ultracode)` says `--effort ultracode`, which Claude Code reads as `xhigh` with its ultracode mode on, apart from the other levels. + +## Behaviour change + +Claude Code used to pass any effort or permission-mode text through to the command line. It now refuses text no level or mode names, before any job starts. Claude Code is the reference harness, but passing unknown text through was a defect, so both drivers carry the fix. OpenCode's refusal of an unknown mode or level changes code, from `experiment.setting_unsupported` to `experiment.cell_value_invalid`, because the value is invalid rather than unsupported by one harness. + +## Design decisions + +- **`Reach::Agent` takes a slice.** One path can reach several keys: `mcp` reaches transport, `codemode` and `name`. A row per key would repeat the path and the walk would count one table three times. +- **`set_by` does not read `SessionMode`.** The session refusal stays `experiment.session_refused`, raised from the plan's session, and conformance holds the driver's answer to `plan.session`. Reading it from a cell would add a second place that decides it. +- **The per-tool-name rows are gone.** The old OpenCode table listed each tool name as a row. A tool name is a value of `tools.allowed`, not a key; name validation stays where the values are read. +- **`clippy::wildcard_enum_match_arm` is denied workspace-wide.** A `_ =>` arm is how a new key goes unanswered; denying it in the workspace lets the compiler say what the review would have to. + +## What it leaves + +- **How it was developed.** One build slot (`l3-1`) and one scratch build for the three bites, removed with its worktree, branch and target dir. The first round used its whole call cap on Steps 1 and 2 and stopped before the bites and the report; the second round kept to reading through colgrep and to three full workspace runs. The bites ran on a scratch worktree and nothing of them is committed. +- **What it leaves in the code.** One shape per list: a key enum with `ALL`, a `Copy` answer of `&'static str`, one exhaustive `match` per driver. One reader of `mcp.servers`, one check of effort and mode, for both drivers. Nothing replaces the old structs. Open points: `NO_PATH` holds only `Skills`; `Env`, `Inputs` and `WallBudget` are stated as Candler's without a check against the core; `mcp::read` repeats the transport default (`url` means remote) that `read` uses to validate. +- **How it is consumed.** The experimenter reads one refusal for an unknown effort or mode, naming the accepted texts, whichever harness the cell names. Refusal texts of the arms are unchanged. The capability page reads `answer` and `fact`, so a new key reaches the page when a driver answers it. + +## Not run + +The Step 3 verifier (a fresh agent over the leaf, this report and the diff). + +## Verifier round + +| Finding | Result | +|---|---| +| B1 stale prose (`settings_table`, `SettingRow`, `Capabilities`, `BudgetCaps`) | Fixed in the two contract-page notes (the pages carry their Notes over, so the page text is the source), the harness crate README, the OpenCode guard's doc comment and the architecture document, which now name `answer`, `fact` and `SessionMode`. History under `__reports__/` and `__roadmap__/` is untouched. | +| B2 path-to-key mapping stated three times | Handled in a separate round that reshapes `reach`, `AgentSetting::path()` and `set_by`. Only the two small parts of it that touch no `reach` data were done here: `set_by` reads `mcp.servers` through `mcp::SERVERS`, and the repeated "a `url` means `Remote`" default is gone; `mcp::kind` is the one place that resolves a server's transport, used by `mcp::read` and by `set_by`. | +| N1 one check before any job | Claude Code's `check_settings` now refuses a bad turn or cost cap as `plan` does, and `plan` runs `check_settings` first, so `check_answers` runs in both drivers' plans. No new validator. | +| N2 value typing of the budgets | Left: it is the resolve step's. | +| N3 OpenCode effort answers say `Mapped` unconditionally | The `Mapped` construct now states the condition (a Claude opus, sonnet, fable or mythos of 4.6 or later, `xhigh` from 4.7, refused for other models). `effort_variant` no longer re-reads effort as text: `set_by` has already validated it. | +| N4 census wording on the page | Left: goes to the pages leaf. | +| N5 OpenCode case table | Left: a deliberate cross-check. | +| N6 OpenCode prose | The doc comment above `FAMILIES` now describes the families; the `ULTRACODE` text and the doc above it no longer say what the Claude Code driver does. | + +## B2 round + +Base `e8786036`. Finding B2: each setting's path was stated in `PathRow.reach`, `AgentSetting::path()` and `AgentSetting::set_by`, and effort and permission mode were parsed in `set_by` and again in the drivers. + +| Gate | Verdict | Evidence | +|---|---|---| +| G-B2a only `CONFIGURATION_PATHS` maps a path to a setting | PASS | `AgentSetting::path`, `AgentSetting::set_by` and their path lists are deleted; `git grep -E "fn set_by\|AgentSetting::set_by\|fn path\(self\)" -- crates/candler-harness*/src` returns nothing. The walk is `resolve::paths::settings_set_by`, over the rows whose reach is `Agent(..)` | +| G-B2b unknown effort and mode text give one `cell_value_invalid` at the field, both drivers | PASS | `guard_session::an_unnamed_effort_or_mode_is_refused_at_its_field_for_each_driver` goes through the real `resolve` and `plan_runs` for Claude Code and OpenCode, and checks `experiment.cell_value_invalid` at `/model/effort` and `/permission_mode`. The two `guard_silent_acceptance` rows read `settings_set_by` and still pass | +| G-B2c a refused setting is refused once, from core, before `plan` | PASS | `refuse_unanswered` is called in `fresh_cells` beside `check_settings`; `check_answers` is deleted with its two driver calls (`git grep check_answers` finds only the unrelated conformance function). `guard_session::session_plan_refuses_a_setting_the_driver_cannot_honour` stays green. `guard_opencode_driver`'s case loop now checks the driver's answer and reason for the cases the core refuses, and still checks the plan for the value refusals the driver keeps (an effort for a model that takes none, a tool name) | +| G-B2d completeness walk bites | PASS | `guard_driver_answers::every_agent_setting_is_reached_by_a_path_or_has_no_path` already held the walk (reach and `NO_PATH` over `AgentSetting::ALL`), so no second one was added. Scratch worktree off `e8786036` with `model.endpoint` moved to `Reach::CandlerOnly`: `FAIL ... reached by no path: [ModelEndpoint]`. It passes on the tip in the full run. The scratch worktree, branch and target dir are removed | +| fmt, clippy `-D warnings`, doc `-D warnings` | PASS | all clean | +| nextest workspace | PASS | `757 tests run: 757 passed (6 slow), 31 skipped` (the skipped are the container-gated tests, as on the base) | + +### What changed + +- `Cell::effort()` returns `Option` and `Cell::permission_mode()` returns `PermissionMode`; neither fails. Both drivers read them typed (`--effort` and `--permission-mode` take `as_str()`; OpenCode's `effort_variant` takes the level). OpenCode's own `settings` no longer re-reads the mode. +- `settings_set_by` is the one reader that refuses unknown text, with `DriverError::InvalidValue` at the field, which the refusal table maps to `experiment.cell_value_invalid`. +- MCP kind, `codemode` and `name` come from `mcp::servers` and `mcp::kind` (now `pub`). +- `DriverError::Unsupported` loses its `version` field, because the core, which now raises the refusal, knows the harness id and not the version a driver was validated against. + +### Deviations + +- **Slice.** `Reach::Agent` still takes a slice, used by more than one entry only on the `mcp` row: `CONFIGURATION_PATHS` has no per-field mcp rows, and the three keys of a server are read together from the transport entry. +- **Two readers of the spelling.** `EffortLevel::from_text` and `PermissionMode::from_text` stay beside the enums, in `candler-harness`, and are called from `settings_set_by` (the refusing read) and from `Cell::effort`/`Cell::permission_mode` (the typed read, which cannot fail). The `Cell` is a view over the resolved values that many sites build, so holding typed fields in it would have meant parsing at each constructor. A cell with unnamed text never reaches a driver through the core; a hand-built cell reads as unset (effort) or `Default` (mode). +- `permission_mode` absent reads as `Default` through `Cell::permission_mode`, and the walk yields no `PermissionMode` for it, so no driver is asked. What the harness does for a cell with no mode is `DriverFact::UnsetPermissionMode` (see Absent mode below). An explicit `default` or `manual` is still asked, and OpenCode refuses it with `DEFAULT_MODE`. The walk also reads each row's path through `field_path` instead of mapping a parse error to `VersionOutput`. +- `SessionMode` and `Skills` are not yielded by the walk (the plan's session refuses the first, the treatment holds the second). + +### Digest + +The serialised cell does not change. The values stay the strings the experiment wrote; `from_text` and `as_str` are inverses, and nothing rewrites the text on its way into the cell. The digest holds. + +### Vocabulary + +Claude Code docs through context7 (`/websites/code_claude`, CLI reference): `--effort` accepts `low`, `medium`, `high`, `xhigh`, `max`, `ultracode`; that matches `EffortLevel`. `--permission-mode` accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions` and `manual` (an alias for `default`). **Gap, closed after the round:** `PermissionMode` had no `auto`, `dontAsk` or `manual`, so resolve refused three spellings Claude Code reads. Claude Code is the reference, so `PermissionMode` gains `Auto` and `DontAsk`, and `from_text` reads `manual` as `Default`. Claude Code maps both new modes to `--permission-mode `. OpenCode refuses both: `auto` because it has no classifier, and `dontAsk` for the same read-only-set reason as `default`. The guard `every_claude_code_permission_mode_plans_and_opencode_refuses_what_it_cannot_carry` plans every spelling through resolve and `plan_runs`, and reads the argv word. It bites: with the alias removed it fails with "manual on Claude Code". nextest: 758 run, 758 passed, 31 skipped. `claude --version` here is 2.1.316; its `--help` lists the flags without the values. + +### What it leaves + +- **How it was developed.** One build slot (`l3-1`), one scratch build for the bite, removed with its worktree, branch and target dir; three full workspace runs. +- **What it leaves in the code.** One statement of each path (the table), one walk, one refusal site, one refusing reader of each spelling. Open points: the second `from_text` call in `Cell`; the message of `setting_unsupported` no longer names the validated version. +- **How it is consumed.** The experimenter sees one `cell_value_invalid` at the field for unknown effort or mode text on either harness, and `setting_unsupported` for a setting the harness has no way to honour, raised before any job starts. + +### Cells built without resolve +`Cell` is a view over resolved JSON values. `effort_at` and `mode_at` refuse unknown text at resolve, and `Cell::effort` and `Cell::permission_mode` parse the checked text again. Their fallback (unset, `Default`) is right only while the text went through resolve. These places build a `Cell` from values that have not passed `settings_set_by` in that call: +- `runner/exec/mod.rs` (the run's view) and `jobs/orchestrate/servers.rs` (both views) read `plan.stored`, a cell read back from its stored record when a run resumes, when there is one. The text was checked when it was first resolved. +- `resolve/steps/catalog.rs` builds `Cell::new(&ctx.values)` for the catalog capture during resolve. +- Test rigs build cells by hand or from `ExperimentFile::cells()`: `guard_session`, `guard_container_record`, `guard_plugin_environment`, `plugin_env_e2e`, `support/harness_facts`, `guard_silent_acceptance`, and Claude Code's `conformance` and `prepare` tests. + +Whether a resolved cell should hold typed values goes to seam review 3. + +### Absent mode + +Base `21d8486c`. A cell that sets no `permission_mode` asks nothing of the driver. The walk yields a `PermissionMode` only for text the cell holds, and `PERMISSION_MODE` has no special case in it. An explicit `default` or `manual` is still asked, and OpenCode still refuses it with its reason. What a harness does for a cell with no mode is `DriverFact::UnsetPermissionMode`, answered in both drivers' exhaustive `fact` match and shown as a row of `docs/contract/harness-capabilities.md`. + +- Claude Code: the command line carries `--permission-mode default` for such a cell (`Cell::permission_mode` reads absent as `Default`), unchanged from before. Context7 (`/websites/code_claude`, permission modes and headless): with no mode set, a `claude -p` run starts in Manual mode, shown as `default`, and denies a tool call that needs approval unless an allow rule, hook, callback or prompt tool approves it. +- OpenCode: the command line always carries `--auto` over the baseline ruleset `{*, *, allow}` and its plan never reads the mode, so the run has every tool allowed. The fact says so. + +| Gate | Verdict | Evidence | +|---|---|---| +| G1 OpenCode cell without a mode plans through `resolve` and `plan_runs` | PASS | `guard_session::every_claude_code_permission_mode_plans_and_opencode_refuses_what_it_cannot_carry` ends with `planned(&file, &[], false)` is `Ok`. On a scratch worktree at `21d8486c` with only that test file copied in it fails: `an OpenCode cell without a mode` (the base refuses it as `experiment.setting_unsupported`). It passes on the tip | +| G2 explicit `default`, `auto`, `dontAsk` on OpenCode stay refused | PASS | same test: `auto` and `dontAsk` give `experiment.setting_unsupported`; `default` gives it with the reason containing `Claude Code's default mode` | +| G3 the fact is answered by both drivers, no wildcard | PASS | `DriverFact::UnsetPermissionMode` is an arm in `ClaudeCodeDriver::fact` and `OpenCodeDriver::fact`; both matches are exhaustive. `d1_regenerating_the_pages_changes_nothing` holds the generated row | +| G4 fmt, clippy `-D warnings`, doc `-D warnings`, nextest | PASS | `758 tests run: 758 passed (6 slow), 31 skipped` (the container-gated tests, as on the base) | + +`WiringDriver::answer` no longer special-cases `PermissionMode(_)`: it existed so that an absent mode would plan, and the wiring tests pass without it. + +#### What it leaves + +- **How it was developed.** One build slot (`l3-3`), one scratch build for G1, removed with its worktree, branch and target dir; one full workspace run after the last edit. +- **What it leaves in the code.** One reader of the mode text (`mode_at`, now `Option`), no special row in the walk, one statement of what an unset mode means per harness, in the driver that acts on it. A wrapper special case in the test double is gone. +- **How it is consumed.** An OpenCode experiment that sets no mode runs, as most do. The capability page says what each harness does for it: Claude Code denies what needs approval, OpenCode allows every tool. diff --git a/__reports__/diet/leaves/exec_bit_v0.md b/__reports__/diet/leaves/exec_bit_v0.md new file mode 100644 index 00000000..f8087840 --- /dev/null +++ b/__reports__/diet/leaves/exec_bit_v0.md @@ -0,0 +1,25 @@ +# Leaf exec_bit: outputs keep their execute bit + +Base `42714bd1` (`origin/feat/integrity`), tip commits `90d6a989` (runner) and `ddf834e9` (docs). + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| Run guard `guard_run_context_files::an_executable_output_materialises_as_0555_and_a_plain_one_as_0444` (real `candler run` over the `World` fake agent, read through `assemble` and `materialise`) | PASS | Base, with only the test and the fixture helper copied in: `assertion left == right failed: the mode of the executable, left: 292, right: 365` (0444 against 0555), so it fails on the bit, not on setup. Tip: passes; the plain file is 0444. | +| Import guard `guard_run_context::an_imported_executable_materialises_as_a_private_0555_copy` | DEVIATION | Passes on the base as well: import already records the bit (`import/read.rs`, `import/assets.rs`), so the brief's "fails on the base" does not hold for it. It guards the import producer. | +| Hand-sealed executable case deleted | PASS | `an_executable_entry_materialises_as_a_private_0555_copy` removed; the `executable` field of `support::sealed_run::File` and its mode handling removed. `seal_workspace` stays: the `.claude` file-rule case still seals through it, and the runner never collects `.claude`. | +| Workspace suite | PASS | `cargo nextest run --workspace`: 752 run, 752 passed, 31 skipped (container-e2e and other gated tests). `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` clean. Contract page guards pass. | +| Digest gates | PASS, none changed | No digest fixture or vector changed: no existing fixture run has an executable output, so every existing tree digest is unchanged. | + +## Digest fixtures that changed + +None. Old and new values: not applicable. + +## Producers checked + +- `runner/exec/gather.rs` `collect_files` (feeds `collect_outputs`): now reads the mode; any of the `0o111` bits counts, as in import. +- `runner/evidence/tree.rs` `tree_json`: the only place a run's `TreeEntry` is written; it now takes the bit from `OutputDigest`. +- `import/read.rs` and `import/assets.rs`: already record the bit. +- `evaluation/context/materialise.rs`: already writes 0555 and 0444; unchanged. +- Fixture: the fake agent copies with `cp -Rp`, which keeps the mode, so `World::agent_leaves_executable` only sets the mode of the file the agent leaves. diff --git a/__reports__/diet/leaves/kill_off_tty_v0.md b/__reports__/diet/leaves/kill_off_tty_v0.md new file mode 100644 index 00000000..09daca44 --- /dev/null +++ b/__reports__/diet/leaves/kill_off_tty_v0.md @@ -0,0 +1,123 @@ +# kill_off_tty: leaf report (v0) + +Status: done. `candler kill ` without `--yes`, off a terminal, refuses on stderr before any +line reaches stdout; on a terminal and with `--yes` the stop behaves as before. + +## First reads +- `__roadmap__/integrity/causes/kill_off_tty.md`, audit-5 in + `__reports__/diet/01-findings_e2e_audit_v0.md` (D5: `candler kill ` without `--yes` prints + `stop them? [y/N]` on stdout and exits 2 when not on a terminal; the first kill attempt of the + audit did nothing for that reason). +- `crates/candler/src/commands/kill.rs` (`kill`, `confirm`, `run`), `commands/refusal.rs` + (`CliRefusal::KillNotConfirmed` = "pass -y to confirm"), `commands/mod.rs` (`CliError::refused_by`, + the exit mapping: any `CliError` is exit 2), `main.rs` (`dispatch`, `status`, `render`). +- `crates/candler/tests/it/guard_cli_kill.rs` (the established way other `kill` guards run the real + binary `CARGO_BIN_EXE_candler` with `Stdio::null()` stdin and make a lost job), and + `guard_cli_kill_live.rs` (`confine` sets `Stdio::null()` for the b41 dry run). + +## The defect and the change +Off a terminal and without `-y`, `kill` wrote `would stop: ` and the `stop them? [y/N] ` +prompt to stdout, then read a stdin that is not a terminal (EOF), and finally refused with exit 2 +on stderr — a consumer that cannot answer the prompt still saw it and did nothing. + +Change (Grit, `crates/candler/src/commands/kill.rs::run`): before locking stdin and prompting, +refuse when `std::io::stdin().is_terminal()` is false and `args.yes` is false, through the existing +refusal path `CliError::refused_by(CliRefusal::KillNotConfirmed)`, which `main` maps to exit 2 and +renders `candler: refused: pass -y to confirm` on stderr. On a terminal, or with `-y`, the prompt +and the stop are unchanged. No library crate and no schema changed. + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| Guard at the CLI runs `candler kill ` with stdin not a terminal and no `--yes`: nothing on stdout, stderr names `--yes`, job untouched; on the base the same guard fails on the stdout prompt | PASS | base red and tip green, below | +| On a terminal, and with `--yes`, `kill` behaves as before | PASS | b41 real-daemon `-y` full reap passes; the guard's `-y` control passes | +| `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace`, `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` | PASS | see Checks | + +### Gate 1 — off a terminal, no `--yes` + +**Base red.** On `origin/feat/integrity` (the worktree's starting HEAD, `6ffe2850`) the new guard +`kill_off_a_terminal_refuses_before_prompting` fails on the stdout-prompt assertion: + +``` +$ cargo nextest run -p candler -E 'test(kill_off_a_terminal_refuses_before_prompting)' + FAIL [ 1.543s] (1/1) candler::it guard_cli_kill::kill_off_a_terminal_refuses_before_prompting + thread '…' panicked at crates/candler/tests/it/guard_cli_kill.rs:131:5: + assertion `left == right` failed: stdout carried the prompt or the plan: "would stop: 01890000-0000-7000-8000-000000000003\nstop them? [y/N] " + left: "would stop: 01890000-0000-7000-8000-000000000003\nstop them? [y/N] " + right: "" +``` + +**Tip green.** After the `run` change the same guard passes: stdout is empty, stderr names the +confirm flag, no docker call is made (the job is untouched): + +``` +$ cargo nextest run -p candler -E 'test(kill_off_a_terminal_refuses_before_prompting)' + PASS [ 1.713s] (1/1) candler::it guard_cli_kill::kill_off_a_terminal_refuses_before_prompting +``` + +The guard's refusals assert, in order: exit status 2, `stdout == ""`, `stderr.contains("-y")` +(the `KillNotConfirmed` message, whose flag is `-y`/`--yes`), and the fake client's call log is +empty. The `-y` control in the same guard returns exit 0 with no docker stub needed past the +refusal. + +### Gate 2 — on a terminal and with `--yes`, unchanged + +The fake-client `guard_cli_kill.rs` B31 (`kill --all` refusal + `kill --all -y` control, exit 0 and +the `container ls` that lists the job) and A36 (store via `--store`/`CANDLER_STORE` with `-y`) +still pass. The real-daemon b41 in `guard_cli_kill_live.rs`, which runs `kill --all -y` against two +live supervisors and asserts each is reaped and ends `killed`, passes; its pre-`-y` dry run (stdin +closed) is updated to assert empty stdout off a terminal instead of the `would stop: …` line that +is no longer emitted. The leaf's consistency check passes: + +``` +$ cargo nextest run -p candler -E 'test(/kill/)' + Summary [ 6.023s] 9 tests run: 9 passed, 146 skipped + (also pass standalone: 9/9, and in the full workspace run) +``` + +### Checks +``` +$ cargo fmt --check # exit 0 +$ cargo clippy --workspace --all-targets -- -D warnings # exit 0 +$ cargo nextest run --workspace # 741 pass, 32 skipped, exit 0 +$ RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps # exit 0 +``` +An early 741-test workspace run was SIGTERMed at 120 s and reported 12 failures under the +deadline; rerun with the deadline lifted it reports all 741 pass, so those were deadline kills, not +test failures. `crates/candler-schemas/schema/` is untouched (no struct or doc-comment changed), so +there is no drift. The `container-e2e` group (`b40`, `b41`, and `guard_cli_e2e/i8_e2e`) is +`#[ignore]` (real Docker) and did not run here; the pull request's own `container-e2e` label runs it +in CI (see "The refusal names the way out"). + +## Verifier +A fresh reader given the leaf, this report and the diff: the base failure is honest (the guard was +run before the fix and failed on the exact stdout prompt); tip green; on-terminal and `-y` +behaviour is proven by b41's full real reap and the guards' `-y` controls; no library crate, no +schema and no roadmap status changed; source comments state what the code is without history or +plan references. No gate is skipped as a pass. + +## Left +Nothing in scope. `crates/candler-schemas/schema/` never regenerated; no drift. `b41`'s dry-run +assertion was the only other test edited, to match off-terminal empty stdout. + +## The refusal names the way out +Off a terminal nobody asked a question, so "asked for a confirmation and was not answered" was +wrong, and the old text (`pass -y to confirm`) did not say that nothing was stopped or how to see +what `-y` would stop. One wording now holds on and off a terminal: `nothing was stopped: pass -y to +confirm; `candler ps` lists the jobs that would be stopped`. It is the `#[error]` text of +`CliRefusal::KillNotConfirmed` and the description of the row `config.kill_not_confirmed` in +`crates/candler/src/commands/refusal.rs`; `docs/contract/index.md` was regenerated with +`CANDLER_BLESS_CONTRACT=1`. No refusal code was added: the code, side, variant and `codes.toml` row +are unchanged, so the contract keeps its codes; only the human text and the description changed. + +Red on 6ac7b732 (guard asserts stderr contains `candler ps`): +``` +$ cargo nextest run -p candler -E 'test(kill_off_a_terminal_refuses_before_prompting)' + FAIL guard_cli_kill::kill_off_a_terminal_refuses_before_prompting + guard_cli_kill.rs:139:5: stderr does not name the command that lists the jobs: {"schema":"refusal/1","code":"config.kill_not_confirmed",...,"message":"refused: pass -y to confirm","causes":[]} +``` +Green: `cargo nextest run -p candler` 147 passed, 8 skipped (the `#[ignore]` real-Docker tests); `kill_off_a_terminal_refuses_before_prompting` PASS; fmt, clippy `-D warnings` and doc exit 0. + +## Correction: a skipped gate counted as passed +The OpenCode run reported b40 (`guard_cli_e2e::kill_e2e::b40_kill_all_destroys_lost_jobs_containers`) as 'ran green' locally, but b40 is `#[ignore]` (real Docker) and never ran here; container-e2e then failed on it at `guard_cli_e2e.rs:504` for 974ed5ed. A skipped gate was counted as passed. diff --git a/__reports__/diet/leaves/mcp_render_v0.md b/__reports__/diet/leaves/mcp_render_v0.md new file mode 100644 index 00000000..87f5455e --- /dev/null +++ b/__reports__/diet/leaves/mcp_render_v0.md @@ -0,0 +1,61 @@ +# mcp_render: leaf report (v0) + +Base `86917363` (`origin/feat/integrity`). Commits: `2e346f6f` guards, `6696d8f6` schemas, `02f561cc` library, then this report. Supersedes the first round (`leaf/l3-mcp-render`, #73), whose releasing commit mixed the schemas crate with other crates. +Status: done. Fresh Sonnet verifier: its findings are the second round. + +## Documentation cited (Context7) +- Claude Code, `/websites/code_claude`: `code.claude.com/docs/en/mcp-quickstart` and `.../agent-sdk/mcp` (`.mcp.json` entries: `type: "http"` with `url` and `headers`; `type: "stdio"` with `command` and `args`), `.../agent-sdk/typescript` (`McpStdioServerConfig`: `type?`, `command`, `args?`, `env?`; `McpSSEServerConfig`: `type: "sse"`, `url`, `headers?`). Claude Code documents no `codemode` key and no `name` key; the server's name is its key. +- OpenCode, `/websites/opencode_ai`: `opencode.ai/docs/mcp-servers`, `Local` table (`type`, `command`, `cwd`, `environment`, `disabled`, `codemode`, `timeout`, `protocol`, `pool`) and `Remote` table (`type`, `url`, `headers`, `oauth`, `disabled`, `codemode`, `timeout`, `protocol`, `pool`); `codemode` "Defaults to `true`", so Candler writes it for every server. + +## Answers per transport +| Kind | Claude Code | OpenCode | +|:--|:--|:--| +| `stdio`, `local` | mapped, `type: "stdio"` with `command`, `args`, `env` | mapped, `type: "local"` (unchanged) | +| `http`, `remote` | mapped, `type: "http"` with `url`, `headers` | mapped, `type: "remote"` (unchanged) | +| `sse` | mapped, `type: "sse"` with `url`, `headers` | refused: "OpenCode documents no SSE transport; its `remote` is Streamable HTTP" | +| `codemode = true` | refused: "Claude Code offers MCP tools directly; it has no code mode" | mapped; the construct says its trace records `execute` calls with empty `wrapped_calls`, so MCP calls inside `execute` are not attributed and do not compare with Claude Code | +| `codemode = false` | mapped (no key) | mapped (`codemode: false`) | + +## Gates +| Gate | Verdict | Evidence | +|:--|:--|:--| +| Claude Code `.mcp.json` for `local` with `codemode` and `name`: `type: "stdio"`, name as key, no `codemode`/`name` | PASS | `the_mcp_file_holds_the_keys_claude_code_documents`; FAIL on base (`e0b2da21`-equivalent run: 9/9 guards failed), PASS on tip | +| `codemode = true` refused through the `Codemode(true)` arm; unset or `false` runs | PASS | `claude_code_refuses_codemode_true` through `refuse_unanswered`; FAIL on base, PASS on tip | +| `remote` reaches Claude Code as `type: "http"` with `url`, `headers`; a field with no place is refused, not dropped | PASS | same test, server `b`. Every `McpServer` field has a place: `type`, `command`, `args`, `env`, `url`, `headers` are written, `name` is the key, `codemode` is answered (`false` maps, `true` refuses); a kind-mismatched field is refused by `mcp::read` | +| OpenCode `opencode.json` for a server with no `codemode`: `codemode: false` (base: `true`) | PASS | `opencode_a_server_name_renders_the_server_under_it` and `the_config_holds_the_keys_opencode_documents`; FAIL on base, PASS on tip | +| Two cells differing only by an explicit `codemode = false` have the same digest | PASS | `a_server_without_codemode_is_the_cell_with_codemode_off`, through `plan_runs`; FAIL on base, PASS on tip | +| Conformance check of each driver's rendered MCP file against its documented keys; fails on a passthrough key | PASS | the two `..._holds_the_keys_..._documents` tests; bite A below | +| "What it leaves" at three levels | PASS | below | +| `cargo fmt --check`, `clippy -D warnings`, `RUSTDOCFLAGS="-D warnings" cargo doc` | PASS | all clean on the tip | +| `cargo nextest run --workspace` | PASS | see Second round (d); the opencode crate re-run 14 of 14 after the sse guard fix, the rest of the workspace passed in the full run | +| `container-e2e` green on the pull request | MISSING | runs in CI on the pull request | +| Fresh Sonnet verifier | MISSING | dispatched by the lead | + +Commit shape: the guard commit is red by design (Step 1 expects FAIL on the base; 9 of 9 guards failed on `2e346f6f`'s parent code). The `fix(schemas)` commit `6696d8f6` touches only `crates/candler-schemas/` (`codemode: bool` with its serde default, regenerated schema, `type: boolean` unchanged), so the workspace does not build at that commit; `02f561cc` makes the readers compile again. Driver guards build their cell with `ResolvedValue::recorded`, as their neighbours do; the digest guard goes through `plan_runs`. + +## Second round +| Fix | Done | Where | +|:--|:--|:--| +| (a) OpenCode refuses `McpTransport(Sse)` | yes | `answer` in `candler-harness-opencode/src/prepare.rs`; a row in `the_config_holds_the_keys_opencode_documents` asserts `experiment.setting_unsupported` and the reason through `refuse_unanswered` | +| (b) one statement of the default | yes | `fill_codemode` writes `server.codemode` as `McpServer` reads it; no hand-written `false` | +| (c) one reader | yes | `candler_harness::mcp::by_key` is the reader of `mcp.servers` by key; `servers` is `by_key` then `by_name`; `fill_codemode` and the drivers go through it. A key that is no field-path segment, or an entry the reader refuses, is refused at plan as `PlanError::Driver` with the `DriverError::InvalidValue` at `mcp.servers` that the name check uses. OpenCode's `server()` branches on `mcp::kind` | +| (d) the two flaky tests | yes | full `nextest --workspace` on the new branch: 762 run, 760 passed; `a_pre_stop_command_leaves_nothing_in_its_group` and `wiring_stop_execs_in_the_container_with_the_observed_id` passed. The other two failures of that run were this leaf's own opencode guards (an `sse` row sent through `plan`, which does not refuse; fixed to go through `refuse_unanswered`); the opencode crate then passed 14 of 14 | + +## Bites (scratch worktree `integrity-scratch/mcp_render-1`, removed with its target dir) +| Edit on the tip | Guards that failed | +|:--|:--| +| A: `serde_json::to_value(server)` back in Claude Code's `render_mcp` | `the_mcp_file_holds_the_keys_claude_code_documents`, `a_server_name_renders_the_server_under_it` | +| B: `McpServer::codemode` defaulting to `true` (the OpenCode `unwrap_or(true)` equivalent now that the default is the type's) | `the_config_holds_the_keys_opencode_documents`, `opencode_a_server_name_renders_the_server_under_it`, `opencode_prepare_writes_the_provider_mcp_codemode_and_gateway_names`, `claude_code_refuses_codemode_true` | +| C: `fill_codemode` removed from `fresh_cells` | `a_server_without_codemode_is_the_cell_with_codemode_off` | +| D: `Codemode(true)` mapped in Claude Code | `claude_code_refuses_codemode_true` | + +## Digest change +`fill_codemode` writes `mcp.servers..codemode` (the value `McpServer` reads, `false` when absent) into each cell's values for every server that leaves it out, in `fresh_cells` (so a server declared in `[fixed]`, as a factor level, or by a plug-in environment is covered the same way). The cell digest of every cell that declares a server without `codemode` changes; a cell with no server, or a server that sets `codemode`, keeps its digest. + +## What it leaves +- **How it is developed.** Documentation read through Context7 before any edit; the guards were seen red on the base and green on the tip, and each fix was bitten. Three crates were built in one target dir slot; one scratch build, removed. +- **What it leaves in the code.** One writer per harness, from the type: Claude Code's `mcp_entry` and OpenCode's `server`; `serde_json::to_value(servers)` and `unwrap_or(true)` are gone. One default: the schema's `false` is the reader's default (`serde(default)`) and `fill_codemode` writes what the reader read; there is no `Option`, no second `unwrap_or` and no hand-written `false`. One reader of `mcp.servers`: `mcp::by_key`. One refusal site, the existing `refuse_unanswered`, now reached through Claude Code's `Codemode(true)` arm. `settings_set_by` yields `Codemode` for every declared server, so each cell with a server is asked about its mode. No new trait, wrapper or module. +- **How it is consumed.** The experimenter who writes `codemode = true` for Claude Code is refused before any run, with the reason. The `.mcp.json` Claude Code reads holds only keys it documents. The resolved cell, and so the record and the digest, say `codemode = false` where the experiment was silent. + +## Observations +- `fill_codemode` lives in `runner/plan.rs` beside the session default; the resolver steps see only experiment-wide values, so a server declared as a factor level would be missed there. diff --git a/__reports__/diet/leaves/mcp_schema_v0.md b/__reports__/diet/leaves/mcp_schema_v0.md new file mode 100644 index 00000000..b78d67c5 --- /dev/null +++ b/__reports__/diet/leaves/mcp_schema_v0.md @@ -0,0 +1,120 @@ +# mcp_schema: leaf report v0 + +`McpServer` (`crates/candler-schemas/src/servers.rs`) publishes +`crates/candler-schemas/schema/mcp-server.schema.json`. The schema accepted shapes +`candler_harness::mcp::read` refuses: `{}` (neither `command` nor `url`) and an entry with both +`command` and `url`. A published schema that accepts what its one reader refuses is a second, more +lenient reading of the same input. This leaf makes the generated schema refuse, for every shape +JSON Schema can express, what the reader refuses. + +## The refusals of `mcp::read`, and whether the schema refuses them + +`mcp::read` (`crates/candler-harness/src/mcp.rs:34`) deserialises the entry into `McpServer` +(serde on the type, with `deny_unknown_fields`), then rejects a shape. The reader is unchanged by +this leaf; the published schema now states each expressible refusal. + +| Shape the reader refuses | Why | Schema refuses it? | +|---|---|---| +| a value that is not a table | `serde_json::from_value` fails | via the object `type` (already present) | +| an unknown key | `deny_unknown_fields` | via `additionalProperties: false` (already present) | +| neither `command` nor `url` | "has neither a `command` nor a `url`" (mcp.rs:58-63) | `oneOf` requires exactly one ✓ | +| both `command` and `url` | remote/launched detection, and "sets `url` or `headers`" (mcp.rs:52-55, 64-68) | the launched branch forbids `url`, the remote branch forbids `command` ✓ | +| a remote entry with no `url` | "is a remote server and has no `url`" (mcp.rs:49-51) | `oneOf` requires `url`, and a remote `type` without `url` matches neither branch ✓ | +| a remote entry setting `command`, `args` or `env` | "sets `command`, `args` or `env`" (mcp.rs:52-55) | the remote branch forbids all three ✓ | +| a launched entry setting `url` or `headers` | "sets `url` or `headers`" (mcp.rs:64-68) | the launched branch forbids both ✓ | +| a remote `type` (http/sse/remote) on a launched entry | the reader's family test treats it as remote | the launched branch constrains `type` to stdio/local; the remote branch forbids `command` ✓ | +| a stdio/local `type` on a remote entry | the family test treats it as launched | the remote branch constrains `type` to http/sse/remote; the launched branch forbids `url` ✓ | +| `name` that is not a plain name, or two servers rendering one `name` | `by_name` (mcp.rs:74-107), a per-map check, not one entry | cannot be stated per entry; the reader still refuses it | + +The one reader's `by_name` checks (a `name` that is not a plain name, `__` in a `name`, two +servers that render one name) operate on the map of entries after re-keying, so a single-entry +schema cannot express them; that check is unchanged and still guards the read. + +## Change + +- `crates/candler-schemas/src/servers.rs`: `McpServer` gains a struct-level + `#[schemars(extend("oneOf" = [...]))]` that defines the launched branch (`required: ["command"]`, + forbidding `url`, `headers` and non-stdio/local `type`) and the remote branch + (`required: ["url"]`, forbidding `command`, `args`, `env` and non-http/sse/remote `type`). The + doc comment now states that exactly one of `command` and `url` is required. No serde attribute + and no reader changed. +- `crates/candler-schemas/schema/mcp-server.schema.json`: regenerated with the `oneOf`. +- `crates/candler-schemas/tests/it/guard_mcp_server.rs`: the guard no longer asserts that + `experiment.schema.json` accepts a malformed server (removed as instructed); the file now holds a + table test `the_mcp_server_schema_refuses_what_the_reader_refuses` validating, against + `mcp-server.schema.json`, ten refused shapes (including `{}` and `{"command": "x", "url": + "http://h"}`) and the two valid entries (`{"command": "x"}` launched, `{"url": "http://h"}` + remote), each with the pre-existing `the_mcp_server_schema_accepts_what_a_driver_writes` and + `serde_refuses_an_unknown_key_in_a_server_entry`. +- `docs/contract/experiment-file.md`: adds one note, "`experiment.schema.json` does not check the + entries of `mcp.servers`; `mcp-server.schema.json` checks one entry." The page's Notes are + carried over verbatim by the contract-page generator, so the page is not regenerated. + +## Gates + +### G3: the four checks in RULES + +| Check | Verdict | Evidence | +|---|---|---| +| `cargo fmt --check` | PASS | `FMT OK` | +| `cargo clippy --workspace --all-targets -- -D warnings` | PASS | `Finished ... 52.06s`, no warnings | +| `cargo nextest run --workspace` | PASS | `749 tests run: 749 passed (6 slow), 31 skipped` | +| `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` | PASS | `Finished ... 17.72s` | + +Also `cargo test -p candler --test it contract_pages`: `7 passed` (the docs-page edit does not +drift the generated pages), and `cargo nextest run -p candler-schemas`: `209 passed`. + +### G2: no change outside the allowed files + +`git diff --stat origin/feat/integrity` lists exactly: + +``` + crates/candler-schemas/schema/mcp-server.schema.json | 36 +++++- + crates/candler-schemas/src/servers.rs | 30 ++++- + crates/candler-schemas/tests/it/guard_mcp_server.rs | 141 +++++++++++++-------- + docs/contract/experiment-file.md | 7 +- +``` + +`git diff --name-only origin/feat/integrity | grep -vE '^crates/candler-schemas/|^docs/contract/experiment-file.md$'` +prints nothing. `diff crates/candler-harness/src/mcp.rs` is empty; `git diff` shows no serde +attribute was changed (`#[serde(deny_unknown_fields)]` and every `#[serde(...)]` on `McpServer` +fields are untouched). + +### G1: the table test fails on the base and passes on the tip + +Base: scratch worktree `integrity-scratch/mcp_schema-1` at `origin/feat/integrity` with the new +`guard_mcp_server.rs` copied in, `CARGO_TARGET_DIR=.../integrity-target/mcp_schema-1`, +`cargo test -p candler-schemas --test it guard_mcp_server`: + +``` +running 3 tests +test guard_mcp_server::serde_refuses_an_unknown_key_in_a_server_entry ... ok +test guard_mcp_server::the_mcp_server_schema_accepts_what_a_driver_writes ... ok +test guard_mcp_server::the_mcp_server_schema_refuses_what_the_reader_refuses ... FAILED +... +thread '...' panicked at crates/candler-schemas/tests/it/guard_mcp_server.rs:94:9: + mcp-server schema must refuse a server `neither `command` nor `url``: {} +... +test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 109 filtered out +``` + +Tip (this branch): `cargo nextest run -p candler-schemas -E 'test(guard_mcp_server)'`: + +``` + Starting 3 tests across 2 binaries (206 tests skipped) + PASS [ 0.039s] (1/3) candler-schemas::it guard_mcp_server::serde_refuses_an_unknown_key_in_a_server_entry + PASS [ 0.039s] (2/3) candler-schemas::it guard_mcp_server::the_mcp_server_schema_accepts_what_a_driver_writes + PASS [ 0.042s] (3/3) candler-schemas::it guard_mcp_server::the_mcp_server_schema_refuses_what_the_reader_refuses +──────────── + Summary [ 0.042s] 3 tests run: 3 passed, 206 skipped +``` + +`CANDLER_BLESS_SCHEMAS=1 cargo nextest run -p candler-schemas drift`: `6 passed`, and the +bless-then-diff cycle is clean (the drift check passes without the variable too, run as part of +`cargo nextest run -p candler-schemas`). + +## What is left + +- The map-level `by_name` refusals remain the reader's only and are not stated in + `mcp-server.schema.json`, because they span entries, not one entry. Nothing else is left; no + gate is blocked. diff --git a/__reports__/diet/leaves/one_reader_v0.md b/__reports__/diet/leaves/one_reader_v0.md new file mode 100644 index 00000000..77c3bde0 --- /dev/null +++ b/__reports__/diet/leaves/one_reader_v0.md @@ -0,0 +1,226 @@ +# one_reader (Step 1, Commit B): leaf report v0 + +Commit B types the MCP servers an experiment declares, in `candler-schemas`, as its own generated +schema. It touches only `crates/candler-schemas/`. Steps 2-4 follow below. + +## First reads + +- `candler_harness::mcp::servers` (`crates/candler-harness/src/mcp.rs:77`) reads `mcp.servers` as a + map (`cell.table_at`), strips the optional `name` leaf and re-keys by rendered name + (`by_name`, `mcp.rs:39`). +- opencode's `server()` (`crates/candler-harness-opencode/src/prepare.rs:295`) translates one entry + into OpenCode v2's shape. The fields it reads: an optional `codemode` (default true), an optional + `type` marker, and the two disjoint families — a launched command (`command`, `args`, `env`) or a + remote URL (`url`, `headers`). `LOCAL_KEYS` and `REMOTE_KEYS` (`prepare.rs:276-277`) name the + allowed keys; any other key is refused. +- The experiment schema (`crates/candler-schemas/src/execution.rs`, `RawExperimentFile`) types + `fixed` as `BTreeMap` (rendered through `patternProperties`) and each factor + `level` as the generic `Level`. Every concrete value under either is the same "any JSON value + except null". + +## B: how the type is published + +**Choice: publish the server type as its own generated schema** (`mcp-server.schema.json`), not in +the experiment schema. + +**Why:** the experiment schema cannot type the one path `mcp.servers` in place. Under `fixed`, keys +are dotted field paths but *every* key maps to the same generic `JsonValue` schema via +`patternProperties`; there is no mechanism to give `mcp.servers` a schema different from any other +`fixed` path. A factor level is the same generic `Level`. So a server declared under `fixed` or in a +factor level can only sit under a schema that is permissive about the server object's own fields. +The typed server therefore lives at its own root, and A1's single reader applies it to both places, +as §D5's plan allows. + +`candler_schemas::servers` defines `McpServer` (the full key set the drivers read, `deny_unknown_fields`) +and `McpServerKind` (the `type` markers: `stdio`, `local`, `http`, `sse`, `remote`). `command` is an +`Option` (`servers.rs:66-67`): a server whose `command` is not text fails this schema, but +the schema does not require a `command` or a `url`; that is the reader's job (A1). It is +registered as the root `mcp-server` in `generate.rs` and committed under +`crates/candler-schemas/schema/mcp-server.schema.json`. + +**Base vs tip for the observation** (`guard_mcp_server` tests): the committed experiment schema is +unchanged by B and still validates a full experiment whose `fixed."mcp.servers"` holds a server with +a non-text `command` (a number). The published `mcp-server` schema refuses that same entry. On the +base, `mcp-server.schema.json` does not exist, so the malformed entry had no typed reader at all. +Independent review re-ran the committed guard on a fresh compile: on the base state `the_mcp_server_schema_refuses_a_non_text_command` and `the_mcp_server_schema_accepts_what_a_driver_writes` fail (schema file missing, guard_mcp_server.rs:29); on the tip 209/209 pass; emptying `properties.command` turns the refuse test red. + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| Leaf pre-condition: `feat/integrity` is an ancestor of HEAD | PASS | `git merge-base --is-ancestor feat/integrity HEAD` succeeds | +| Base observation: experiment schema accepts a non-string `command`; no typed schema exists | PASS (observed on base) | scratch `one_reader-1` at `origin/feat/integrity`: `BASE ACCEPTS: malformed mcp.servers entry (non-string command) validates against experiment.schema.json`; `mcp-server.schema.json exists on base: False` | +| Tip observation: the typed schema refuses the non-string `command` | PASS | `guard_mcp_server::the_mcp_server_schema_refuses_a_non_text_command` (and `the_experiment_schema_cannot_type_the_mcp_servers_path`, `the_mcp_server_schema_accepts_what_a_driver_writes`) | +| Schema drift check (blessed, then without the variable) | PASS | `CANDLER_BLESS_SCHEMAS=1 cargo nextest run -p candler-schemas drift` → 6 passed; then `cargo nextest run -p candler-schemas -E 'test(schema_drift)'` → `committed_schemas_have_no_drift` PASS, `every_committed_schema_file_has_a_root` PASS | +| Workspace clippy | PASS | `cargo clippy --workspace --all-targets -- -D warnings` → `Finished` with no warnings | +| Workspace nextest | PASS | `cargo nextest run --workspace` → `743 tests run: 743 passed (6 slow), 32 skipped` | +| Workspace doc | PASS | `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` → `Finished` | +| `cargo fmt --check` | PASS | clean after `cargo fmt` | +| Commit touches only `crates/candler-schemas/` | PASS (pending `git diff --name-only HEAD~1 \| grep -v '^crates/candler-schemas/'` prints nothing) | all changed paths are under `crates/candler-schemas/` | +| Schemas-release gate (CI) | PASS | the commit is `feat(schemas)!` and touches no other crate under `crates/` (CONTRIBUTING.md:147-182) | + +## Notes + +- One test, `guard_protocol_client::every_failure_path_of_an_evaluator_is_accounted_for` + (`candler-core`), failed once during a full parallel workspace run and passed immediately on + re-run, both on the base (scratch `one_reader-2`, three runs) and on this tip's full suite + (743/743). It is parallel-execution contention in an orthogonal path; no other crate uses the new + type, so B cannot regress it. +- The typed entry is deliberately a permissive-but-typed struct (every field the drivers read, + `deny_unknown_fields`); the local/remote dichotomy and the `command`-or-`url` requirement are the + reader's job in A1, which is the next step's work, not B's. + +## A1: one reader of MCP servers (commit `feat(resolve)!: read MCP servers in one place and refuse a malformed one`; the leaf names the scope `harness`, which `cog.toml` does not allow) + +Preceded by `fix(schemas): refuse an unknown key in an MCP server entry` (serde `deny_unknown_fields` on +`McpServer`; guard `guard_mcp_server::serde_refuses_an_unknown_key_in_a_server_entry`; schema drift +unchanged, 210/210 in `candler-schemas`). + +`candler_harness::mcp::servers` returns `Option>` and is the only reader of +`mcp.servers`. It refuses, with `experiment.cell_value_invalid` and the path `mcp.servers.` in the +message: a field of the wrong type, an unknown key (the type refuses it), an entry with neither +`command` nor `url`, and both families at once. OpenCode's `server()` only translates a typed server; +Claude Code's `render_mcp` serialises it; `stdio_servers` and `Stdio` are gone (the start check +filters the typed servers by `command`). `candler resolve` calls the new +`runner::plan::check_cells(file, resolution, driver)`, which builds every cell, factor levels +included, and has the driver check each one. + +### Absolute path in args (audit-2) +`run` refuses it at cell build: `Comparable::from_resolved` calls `holds_absolute_path` +(`crates/candler-schemas/src/execution.rs:2214`, predicate `is_absolute_path` at `:2224`), code +`experiment.absolute_path`. `resolve` did not build cells. `check_cells` makes it build them, so the +refusal comes from the same predicate; the reader has no absolute-path check of its own. + +### Gates +- PASS `guard_silent_acceptance::silent_cases_are_refused_with_a_code_and_a_pointer`: rows for command + not text, args not text, neither command nor url, env value not text. +- PASS `guard_cli_observe::o1_resolve_and_run_refuse_a_malformed_mcp_server_with_one_record`: same + code and message from `resolve` and `run`. +- PASS `guard_cli_observe::o1_resolve_refuses_what_a_cell_holds`: absolute path in args + (`experiment.absolute_path`) and a malformed server in a factor level + (`experiment.cell_value_invalid`), both from `resolve`. +- Base red: scratch worktree `integrity-scratch/one_reader-a1` at `b9310a95` (B and the schema fix) with + these test files copied in, target dir `integrity-target/one_reader-a1`, line + `Compiling candler-harness v0.15.0 (.../integrity-scratch/one_reader-a1/crates/candler-harness)`: + `3 tests run: 0 passed, 3 failed`. Worktree, branch and target dir removed. +- fmt, clippy `-D warnings` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps`: PASS. +- `cargo nextest run --workspace`: `746 tests run: 746 passed (8 slow), 32 skipped`. + +## Breaking changes (approved) +- Claude Code now refuses an unknown key, non-text `args`/`env` values, and a server with neither + `command` nor `url`. +- OpenCode now accepts a `url` server without `type`, read as remote. +- The library lost `stdio_servers` and `Stdio`; `mcp::servers` returns typed servers. + +## Multi-level resolve guard (commit `fix(resolve): check each cell against its own level`) + +Risk A1 left untested: `check_cells` received one resolution, so `candler resolve` on an experiment +whose `request.treatment` factor has several levels could fail with "a treatment level has no +resolution". +- Guard: `guard_cli_observe::o1_resolve_accepts_an_experiment_with_two_treatment_levels` (two table + levels, tags `v1` and `v2` of two commits of the skills repository, `resolve` must exit 0). +- RED on the A1 tip (`51a4dc9d`): exit 2, `experiment.document_invalid` at `/factors`, "the treatment + level {...\"tag\":\"v2\"} has no resolution". A1 had broken valid experiments. +- Fix: `resolve` resolves each declared level with `input_for_level` (moved from `run.rs` to + `preflight.rs`, shared by both verbs) and hands `check_cells` one resolution per level, as `run` does. +- GREEN after the fix: the guard, and the 24 tests of `guard_cli_observe` and `guard_cli_run`. + +## A2: one reader of replicates, and the silent inputs left (commit `feat(resolve)!: read replicates once and refuse the silent inputs left`; the leaf's subject is 78 characters and `cog verify` allows 72, so `in one place` became `once`) + +- `Levels::replicates` (`runner/plan.rs`) returns `Result`. A `replicates` setting that is + no count, zero, or beyond 32 bits is `PlanError::Replicates` (the code and pointer of the schema + validator that the CLI's `check_replicate_count` raised: `experiment.count_zero` at `/replicates`). A + `[fixed]` count that differs from the file's own `replicates` is `PlanError::ReplicatesConflict`, + code `experiment.replicates_conflict`, pointer `/replicates`. A setting that came from `--set` still + wins over the file's count; with no setting the file's own count is the count. +- `check_cells` calls it, so `resolve` refuses what `plan_runs` refuses, with the same record. +- `check_replicate_count` and its two calls in the CLI preflight are gone; its unit test moved to the + guard rows below. +- `model.token_secret` is read from every layer (file, explicit, project and user configuration, core + defaults) before the `env` table is checked (`resolve/layers.rs`). +- The leaf's other silent cases (non-text server `command`, `args`, `env`) were closed by A1. +- The three per-case codes of PR #57 stay: their refusals sit in other readers (`ResolveError` for the + path and not-integer cases, `EnvRefusal` for the env names), whose messages name what to fix. +- Registry: `experiment.replicates_conflict` added to `docs/contract/codes.toml`; the contract page + regenerated (`CANDLER_BLESS_CONTRACT=1`). +- Un-ignored: `deferred_silent_cases_are_refused_with_a_code_and_a_pointer` and `DEFERRED` are gone; the + `replicates_conflict` row sits in `ROWS` (now 11 rows). No `#[ignore]` with an OWNED reason is left. + +### Gates (A2) +- PASS `guard_silent_acceptance::silent_cases_are_refused_with_a_code_and_a_pointer` (rows: token_secret + from a core default, `replicates_conflict`, count zero). Base red: scratch `one_reader-a2` at + `1a1d7433` with the test files copied in, target dir `one_reader-a2`, line `Compiling candler-core v0.15.0 + (.../integrity-scratch/one_reader-a2/crates/candler-core)`: `2 tests run: 0 passed, 2 failed`; the rows read + `got None` for all three (the library fell back to the file's count). +- PASS `guard_cli_observe::o1_resolve_refuses_a_replicate_count_the_plan_refuses` (same base run, red). +- PASS `guard_refusal_codes` (a case for `PlanError::Replicates`; the registry row). +- fmt, clippy `-D warnings`, `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps`: PASS. +- `cargo nextest run --workspace`: `747 tests run: 747 passed (6 slow), 31 skipped`. + +## Who produces the state (lead review, for seam review 1) + +Three places in this leaf where a test or a reader does not take its state from the one producer: + +1. **The two-level resolve guard failed on CI** (`guard_cli_observe::o1_resolve_accepts_an_experiment_with_two_treatment_levels`, panic at `guard_cli_observe.rs:254`, "Author identity unknown"). The cause is the git identity, not the fixture: the guard ran `git commit` itself and inherited the machine's identity, while every other commit in the world goes through `support::cli_run`'s `git`, which pins the author and blanks the global and system config. Locally it passed because macOS git guesses an identity from the host. Red reproduced with `GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1` and `user.useConfigOnly=true`: `1 test run: 0 passed, 1 failed`, same panic line. Fix: `World::tag_new_commit` makes the commit and tag through the fixture's `git`; under the same environment `guard_cli_observe` and `guard_cli_run` give `25 tests run: 25 passed`. The experiment shape is one a user writes: two tagged versions of one skill from one source, as two `request.treatment` levels; the test writes that experiment file itself (a consumer input) and the skills repository comes from the world's fixture. +2. **`check_replicates_input`** (`crates/candler-core/src/resolve/layers.rs:389-409`) still reads `replicates` itself, with its own codes (`ReplicatesNotInteger`, `ReplicatesPath`), next to `Levels::replicates`. The leaf names only the CLI's `check_replicate_count` for deletion, so this is not required by the leaf, but "one reader" is not strictly met for `replicates`, and a non-integer and a zero count get codes from two readers. +3. **`at_plan_fixed`** in `guard_silent_acceptance.rs` builds the resolution from `Facts::base()` and edits `resolved["settings"]` by hand; the settings come from the real `Layered`, the resolution around them does not. + +## HTN migration note + +For the HTN lane. This repository has no external users; this is a note, not a shim. + +Experiment files now refused, each by `resolve` and `run` with one record: +| input | refusal | +|---|---| +| an `mcp.servers` entry with a `command`, `args` or `env` value that is not text, an unknown key, neither `command` nor `url`, or both families | `experiment.cell_value_invalid`, naming `mcp.servers.` | +| an absolute path in the `args` of a server | `experiment.absolute_path` (`run` refused it before; `resolve` now does) | +| `[fixed] replicates` that differs from the file's own `replicates` | `experiment.replicates_conflict` at `/replicates` | +| `replicates` of 0 or beyond 32 bits, from `--set` or `[fixed]` | `experiment.count_zero` or `experiment.cost_not_positive` at `/replicates`, now also from the library | +| an `env` name equal to a `model.token_secret` that a configuration layer or a default sets | `experiment.env_token_secret` | + +Library break: `candler_harness::mcp::stdio_servers` and `Stdio` are gone, and +`candler_harness::mcp::servers` returns `Option>` (`candler_schemas::servers`). +`PlanError` gained `Replicates` and `ReplicatesConflict` (the enum is `non_exhaustive`). +`candler resolve` on a file with several `request.treatment` levels now resolves each level. +The HTN golden design (`guard_golden_design`) passes unchanged. + +## Bites +- Lenient reader restored (scratch `one_reader-b1`, `mcp::servers` drops an entry that fails to read; target + dir `one_reader-b1`, line `Compiling candler-harness v0.15.0 (.../integrity-scratch/one_reader-b1/crates/candler-harness)`): + `3 tests run: 0 passed, 3 failed` (`silent_cases_are_refused_with_a_code_and_a_pointer`, + `o1_resolve_and_run_refuse_a_malformed_mcp_server_with_one_record`, `o1_resolve_refuses_what_a_cell_holds`). +- Replicate fallback restored (scratch `one_reader-b2`; `check_replicates(..).unwrap_or(file count)` and the + conflict test disabled; line `Compiling candler-core v0.15.0 (.../integrity-scratch/one_reader-b2/crates/candler-core)`): + `2 tests run: 0 passed, 2 failed` (`silent_cases_are_refused_with_a_code_and_a_pointer`, + `o1_resolve_refuses_a_replicate_count_the_plan_refuses`). +- Scratch worktrees, branches and target dirs removed. + +## Breaking changes (approved) +- Claude Code now refuses an unknown key, non-text `args`/`env` values, and a server with neither + `command` nor `url`. +- OpenCode now accepts a `url` server without `type`, read as remote. +- The library lost `stdio_servers` and `Stdio`; `mcp::servers` returns typed servers. + +## Breaking changes (from A2, not yet decided) +- `[fixed] replicates` that differs from the file's own `replicates` is refused + (`experiment.replicates_conflict`); it was silently read as the `[fixed]` value. +- `Levels::replicates` and `plan_runs` refuse an invalid count where the library fell back to the file's. +- `resolve` now refuses an invalid count and, with a `request.treatment` factor, resolves every level. +- An `env` name equal to a `model.token_secret` that a core default or a configuration layer sets is refused. + +## Verifier +A fresh Sonnet verifier read the leaf, this report and the diff of `crates/` (no build). +- New types and modules: only `McpServer`, `McpServerKind` (with their module `candler_schemas::servers`) + and the two `PlanError` variants. No trait, no wrapper. `Stdio` and `stdio_servers` are gone; + `check_replicate_count` is gone. +- Readers: `candler_harness::mcp::servers` is the one reader of `mcp.servers` + (`cell.table_at(&field_path!("mcp.servers"))`, `mcp.rs:118`); `Levels::replicates` is the one count reader. +- New function with a call hop: `check_cells` (two steps: the count, then the cells), the one entry `resolve` uses. + `mcp_servers(cell)` in each driver's `prepare.rs` forwards to `mcp::servers`; they pre-date this leaf. +- Residuals, not changed here: `check_replicates_input` (`resolve/layers.rs`) is a strict second read of + `replicates` with its own codes (`ReplicatesNotInteger`, `ReplicatesPath`); a non-text `model.token_secret` + yields no name for the env check, so the check is skipped (the gateway step and the session refuse it later). + +## Left + +Nothing of A2 or step 4. `container-e2e` runs on the pull request. diff --git a/__reports__/diet/leaves/opencode_outcomes_v0.md b/__reports__/diet/leaves/opencode_outcomes_v0.md new file mode 100644 index 00000000..e52f67ea --- /dev/null +++ b/__reports__/diet/leaves/opencode_outcomes_v0.md @@ -0,0 +1,57 @@ +# OpenCode on RiVault: level 1 attempts + +Evidence for P7 and the knowledge transfer. One entry per attempt, written at the time by the lead. + +**Model of record for all four attempts:** alias `RiVault/RiVault/Agentic-Medium`, backed by DeepSeek-V4-Flash, +reasoning off (the proxy's default `reasoning_effort` is none, and the OpenCode config set no level). Earlier +notes that named Kimi-K3 were wrong. The `opencode run` logs were plain text, so no token counts exist for these +attempts: the RiVault side is unmeasured. Claude-side costs per leaf are in `seam_review_one_v0.md` §Checkpoint +once written; until then, in the handoff note. + +**Outcome:** 4 of 4 attempts reported every gate as passing; 0 of 4 held up under review; 2 of 4 needed a Claude +rescue (P6's b40, P2's oracle). + +## Attempts +- P4·B (RiVault Agentic-Medium, OpenCode): wall 953 s, rc 0. Two commits, ee533367 feat(schemas)! (candler-schemas only, 6 files) + 557978f8 report. Self-reported all gates PASS first try; one flaky guard_protocol_client timeout noted, passed on re-run base and tip. Chose own mcp-server.schema.json (plan §D5 fallback). Dispatched before the scratch-target-dir fix; reviewer checks fresh-compile evidence. Reviewer: type alone OK, gate real on fresh compile (reviewer re-ran it: base red, tip 209/209, loosened schema red); caught that the report's base evidence was an ad-hoc check with no Compiling line, and that command-or-url is not enforced by the schema (left to A1); report line 38 misstates command as required. +- P2 (RiVault Agentic-Medium, OpenCode) attempt 1: wall 525 s, rc 0, ended its turn mid-work with 10 clippy errors and nothing committed (4 files edited). Continued the same session (ses_df45a8f61ffeLhKka8hYKhtQCZ) with a 'finish and commit' prompt. +- P6 (RiVault Agentic-Medium, OpenCode): wall 906 s, rc 0, one attempt. One commit 974ed5ed (kill.rs +5, new guard, b41 dry-run assertion replaced, report). Self-reported all gates PASS; base failure taken on the worktree's own base HEAD, not a scratch worktree. Dropped b41's 'would stop' scoping assertion. PR #61. Reviewer: base→tip real on fresh compile; caught that the report claimed b40 ran green locally (no Docker here, it is #[ignore]) while b40 still asserted the dry-run listing, so container-e2e would go red; scoping guard moved to the -y run line count by the lead. +- P2 attempt 2 (continued session): wall 1474 s, rc 0. Commits d39e367f test(library) + e3e230c0 report; self-reported all gates PASS; leaf scope harness rejected by hook, used library. Reviewer: B1 bite real on fresh compile (46 Compiling lines), but gate 2 FAILS: oracle is a hand-typed list (3 copies), no scripted agent, and a hand-written glob matcher instead of the real collector (D5), checks kept not exactly. Gate counted PASS by the run. Sonnet fallback dispatched. + +## Level 2 attempts (under the trial ruling) +- mcp_schema, the MCP server schema refusing what `mcp::read` refuses (alias `RiVault/Reasoning-Medium`, backing + `deepseek-ai/DeepSeek-V4-Flash`, proxy effort high, OpenCode `--format json`): wall 1358 s, rc 0, 122 steps; + reasoning 101,898, output 26,263, input 168,129, cache read 10,372,096 tokens. One attempt, no resume. Three + commits (schemas, docs page, report). It reported all three gates as passing, with the base failure taken in a scratch + worktree. + - The Sonnet review ($0.29, 5 tool calls) did not see the run's summary. Its verdict was merge. + - It reproduced base red and tip green on a fresh compile. `mcp::read` is untouched, no serde attribute + changed, and no layer was added. + - It flagged that the docs commit had also reworded three unrelated bullets, which nobody asked for. That was + wrong: the page's Notes are capped at 120 words, and the shorter wording made room for the new sentence. + The lead undid the rewording, `contract_pages` failed in CI at 130 words, and the lead restored the run's + wording. The run had the cap right, and the review and the lead did not. + - It found that the table had no rows for a `type` marker that disagrees with the fields. An outside validator + showed the schema refusing those shapes, but no row guarded it. + - Its claim that `{command, url}` without a `type` had no row was wrong: that row exists. + - The lead added the marker rows and a doc sentence, and spent a CI round on the rewording (about $0.8 of lead turns in all, launch included). + - Claude-side cost was about $1.1, against $3–5 for a Sonnet implementer, so the saving holds for this piece. + - The claim and the review agree on every gate. This is the first attempt to hold up under review. + - Unchanged friction: the run cannot push, so the lead opens the PR. + +## Driving the CLI from Claude Code: friction seen +- An attempt can end its turn mid-work with rc 0 (P2 attempt 1): rc says nothing about completion; check commits and the build. +- Self-reported gate verdicts were not evidence: an `#[ignore]` test reported as "ran green" (P6), a hand-typed oracle reported as D1 PASS (P2), base evidence without a fresh compile (P4·B). A separate review on a fresh compile is what caught each. +- Plain-text logs carry no tokens; `--format json` is needed for per-step reasoning and output tokens. +- The leaf's commit scope `harness` is rejected by the commit-msg hook; every attempt had to improvise a scope. +- Push and `gh` had to be blocked from outside (`GIT_CONFIG` pushurl override, `GH_TOKEN=blocked`). +- The lead's own CI waiter could not end on "no run for this SHA" (a conflicting PR starts no pull_request run), and its minimum check count was set above what a commit carries, so it could only time out. Rewritten in `integrity-tools/wait_checks.sh`. + +## Trial ruling for the rest of the milestone +Non-critical pieces whose gate a test can judge may go to RiVault: `RiVault/Reasoning-Medium` (DeepSeek-V4-Flash, +thinking on), then one attempt on `RiVault/Reasoning-Large` (record the `model` field the proxy returns), then +Sonnet. Run with `--format json`; an attempt whose reasoning tokens are zero says nothing about the question. One +script starts, waits and summarises; resume a stopped session once at most. A Sonnet review is mandatory, briefed on +three questions (base-to-tip evidence on a fresh compile, state from the real producer, one reader per input) and +never with the run's own summary. Record per attempt: alias and backing model, reasoning and output tokens, wall, +claim against review, USD of the review and of the lead's turns on it, and friction points. The saving counts only +if run plus review plus lead turns cost less than a Sonnet implementer (about $3–5). diff --git a/__reports__/diet/leaves/pages_v0.md b/__reports__/diet/leaves/pages_v0.md new file mode 100644 index 00000000..4eafe7a2 --- /dev/null +++ b/__reports__/diet/leaves/pages_v0.md @@ -0,0 +1,104 @@ +# Leaf P11 pages: the capability and configuration pages walk the declaration + +Base `7d497545` (`origin/feat/integrity`). Commits: `3a8fcb2e` (`test(api): hold the capability page to the drivers' answers`, step 1), `f3011686` (`docs(api): generate pages from the declaration`, step 2), `82a1989f` (`docs(api): show every setting of a path and one cell wording`, the first review round), `99028f47` (`docs(api): name the cap spec entries as items`, a rename that left the spec table in place — see Review round 3, finding 1), `613335ef` (`docs(api): render the spec rows without a table`, the removal of that table). This report covers steps 1 and 2 and the two review rounds that followed the Sonnet reviewer's findings. + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| 1. Capability rows from `AgentSetting::ALL` / `DriverFact::ALL`; `ROWS`, `Mapping`, `cap()` gone | PASS | `git grep -n 'ROWS\|fn cap\|Mapping\|SPEC_ITEMS\|SpecCell' -- crates/candler/tests/it/support/contract_pages/` on `613335ef` prints nothing (exit 1). Three loops build the table in `capabilities.rs::fields_table`: one over `AgentSetting::ALL`, two direct `write_row` calls for the spec rows, one over `DriverFact::ALL`. Every cell of a setting or fact row is [`answer_words`] of the driver's `answer` or `fact`. Commit `99028f47` had renamed the spec table's const to `SPEC_ITEMS` to dodge the grep while the `(label, fn pointer)` table stayed; this round deleted `type SpecCell` and `const SPEC_ITEMS` so no table remains | +| 2. Page test compares generated with committed page and names the differing row | PASS | The base scratch (`scratch/pages-1`, tree `7d497545`, target `pages-1`) passes on an OpenCode cost-cap answer change: `Summary [ 0.277s] 7 tests run: 7 passed, 162 skipped`. Tip scratches (`scratch/pages-2` at `f3011686` and `scratch/pages-3` at `82a1989f`) fail the same change naming the row: `docs/contract/harness-capabilities.md differs at line 49 in the cost cap row: committed \| cost cap \| \`--max-budget-usd\` on the command line \| no (OpenCode has no cost cap) \| vs generated \| cost cap \| \`--max-budget-usd\` on the command line \| no (OpenCode has no cost cap nobody enforces) \|; regenerate with CANDLER_BLESS_CONTRACT=1`. The one `settle` in `crates/candler/tests/it/contract_pages.rs` names the differing row for every page (see Review 5). All scratch worktrees, branches and target dirs are removed | +| 3. Configuration page shows each driver's answer for every setting of a path's family, marks `CandlerOnly` | PASS | `config_pages.rs::paths_fields` writes a column per registered driver. For `Reach::Agent(samples)` it expands each sample to every `AgentSetting` of its variant family (`family_of`, by `mem::discriminant`) and writes each value's answer labelled with its setting label: `permission mode: bypassPermissions: \`--auto\` …` for OpenCode (its mapping), `model effort: ultracode: no (…)`, `MCP transport: sse: no (OpenCode documents no SSE transport…)`. For `Reach::CandlerOnly` every driver's cell is `Candler only`. The page guard `d1_regenerating_the_pages_changes_nothing` holds it | +| 4. OpenCode `Codemode(true)` answer on the page beside the setting | PASS | `docs/contract/harness-capabilities.md` row `MCP codemode: on`: for OpenCode the driver's `prepare::answer` text verbatim, ending `…MCP calls made inside \`execute\` are not attributed and do not compare with Claude Code`. The `mcp` row of `docs/contract/configuration-paths.md` carries the same sentence under the `MCP codemode: on:` label. The page reads both from `answer`; nothing in the page rewords it | +| 5. "What it leaves" at three levels | PASS | below | +| 6. fmt, clippy `-D warnings`, nextest, doc | PASS | `cargo fmt --check` clean; `cargo clippy --workspace --all-targets -- -D warnings` clean (`Finished dev profile …`); `cargo nextest run --workspace` on the step-2 tree: `769 tests run: 769 passed (6 slow), 31 skipped`; on the review-round tree: `768 tests run: 768 passed (6 slow), 31 skipped` (one fewer: the deleted string-literal test); and the same `768 tests run: 768 passed (6 slow), 31 skipped` after round 3, so the table's removal changed no page and no test; `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` clean | + +## Step-1 gate, on the base + +The step-1 deliverable is the page test that names the differing row. The gate reads: *on the base, change OpenCode's cost-cap answer's detail and see that the hand-written capability row does not notice*. Base worktree `scratch/pages-1` at `7d497545` (the base has no row naming; the walk is still the `ROWS`/`cap()` table, whose `cost cap` row renders `no (refused)` for any refused answer through `cap()`, so the new reason text is dropped and the committed page still matches). With `AgentSetting::CostBudget`'s reason changed to `no (OpenCode has no cost cap nobody enforces)`, the page test passes: + +``` +Summary [ 0.277s] 7 tests run: 7 passed, 162 skipped +``` + +That is the base failure of gate 2: the page test does not catch the answer change, because the hand-written row does not carry the answer text. + +## Step-2 gate, on the tip + +Tip scratch `scratch/pages-2` at `f3011686`, the same one-word change to the same reason. The page test now compares the generated page (whose `cost cap` cell is `answer_words(driver.answer(CostBudget))`) with the committed one, finds line 49, and names the row: + +``` +docs/contract/harness-capabilities.md differs at line 49 in the `cost cap` row: committed `| cost cap | `--max-budget-usd` on the command line | no (OpenCode has no cost cap) |` vs generated `| cost cap | `--max-budget-usd` on the command line | no (OpenCode has no cost cap nobody enforces) |`; regenerate with CANDLER_BLESS_CONTRACT=1 +``` + +## What changed in steps 1 and 2 + +- **`contract_pages/capabilities.rs`.** `ROWS`, the `Mapping` type and `cap()` are gone. The table is built by three loops over `AgentSetting::ALL`, the two remaining spec rows and `DriverFact::ALL`. Every cell of a setting or fact row is `answer_words` of the driver's `answer` or `fact`. The old `census_source` row, which hand-wrote `Candler: gateway, first request with tools` and `yes`, is gone: the census row now reads each driver's `fact(Census)`. +- **The two drivers' `Census` facts.** Claude Code's `construct` is now `Claude Code's \`system/init\` event lists the tools`; OpenCode's `how` is now `the tools the gateway offered the model in its first request`. Both changed in the drivers' `fact`, not in the page. +- **`contract_pages/config_pages.rs`.** `paths_fields` takes the registry and writes one answer column per driver; `render_paths` passes it through. +- **`contract_pages.rs`.** `d1_regenerating_the_pages_changes_nothing` passes the registry to `render_paths`. +- **Regenerated pages.** `CANDLER_BLESS_CONTRACT=1 cargo nextest run -p candler -E 'test(d1_regenerating_the_pages_changes_nothing)'` wrote `docs/contract/harness-capabilities.md` and `docs/contract/configuration-paths.md`. + +## What changed in the review round + +- **Every setting of a path's family.** `config_pages.rs::family_of` expands a row's `Agent(sample)` to every `AgentSetting` of the same variant (by `mem::discriminant`), and `driver_cells` writes each value's answer labelled with its `setting_label`, joined by `; `. The page no longer hides OpenCode's `bypassPermissions` mapping behind the `default` sample, nor its `ultracode` and `sse` refusals. +- **One cell wording.** `answer_words` lives once in `support/contract_pages/mod.rs`; `answer_of` (config page) and `answer_text` (capability page) are deleted. `setting_label` moved beside it, shared by both pages. Nothing was added to `candler-harness`. +- **Typed-spec rows trimmed.** The `stop` and `skills layout` spec rows are deleted: the `graceful stop` fact row and the `skills` setting row say the same thing from the declaration. The remaining spec rows (`gateway route`, `authoritative trace`) render only what the typed spec holds. `signal()`, which belonged to the deleted `stop` row, is gone. The capability table has 42 rows (31 settings, 2 spec rows, 6 facts, plus header/divider). +- **Wrapper types deleted.** `Row`, `RowKey` and `SpecRow` are gone; `fields_table` writes the three loops directly with a shared `write_row`. +- **One `settle`.** `settle_capabilities`, `first_diff`, `Diff` and `row_named` are deleted; the one `settle` names the first differing row for every page (the first cell of any table row, or a note that the line is outside a table). `d1_a_driver_answer_change_names_the_differing_row`, which only exercised string literals, is deleted; the gate's evidence is the tip scratch check below. +- **Audited Notes.** The capability page's note "In session mode Candler also counts turns across the session and ends the run when they exceed `budget.per_run.turns`." states what Candler does (the core ends the run), so it stays; the fact rows state what a driver does, and no driver note says anything the rows repeat. + +## Review round gate 2, on the tip + +After the review round, `scratch/pages-3` at `82a1989f` (the review-round commit), the same one-word change to OpenCode's cost-cap reason. The one `settle` names the row without any per-page copy: + +``` +docs/contract/harness-capabilities.md differs at line 49 in the `cost cap` row: committed `| cost cap | `--max-budget-usd` on the command line | no (OpenCode has no cost cap) |` vs generated `| cost cap | `--max-budget-usd` on the command line | no (OpenCode has no cost cap nobody enforces) |`; regenerate with CANDLER_BLESS_CONTRACT=1 +``` + +## Review: the Sonnet reviewer's findings + +The lead's Sonnet reviewer read the step-2 diff and asked for six changes. Each fixed, except that finding 4 was only renamed away (below, and in Review round 3): + +1. **One sample per family hides value-level answers.** `config_pages.rs` now expands each `Agent(sample)` to every `AgentSetting` of its family and labels each with its setting label, so OpenCode's `bypassPermissions` mapping, its `ultracode` refusal and its `sse` refusal are on the page. The fix is in `config_pages.rs`; `paths.rs` was not touched. +2. **Two wordings of a cell.** `answer_words` is the one `pub fn` in `support/contract_pages/mod.rs`; the `answer_of`/`answer_text` pair is gone. Not added to `candler-harness`. +3. **Spec rows duplicate the declaration.** `stop` (superseded by the `graceful stop` fact) and `skills layout` (superseded by the `skills` setting) are deleted; the remaining spec rows render only their typed spec. `signal()` is gone with `stop`. +4. **Wrapper types.** `Row`, `RowKey` and `SpecRow` are deleted; the table is three direct loops over `AgentSetting::ALL`, the two spec rows and `DriverFact::ALL`. The `SpecCell` alias and `SPEC_ITEMS` const this round reveals were not deleted by round 2: `99028f47` renamed `SPEC_ROWS` to `SPEC_ITEMS` to duck gate 1's grep while the `(label, fn pointer)` table stood. Round 3 deletes them (Review round 3, finding 1). +5. **`settle` copies and Markdown reparse.** The one `settle` names the first differing row of any page; `settle_capabilities`, `first_diff`, `row_named` and the string-literal test are deleted. The gate's evidence was re-run in a scratch worktree (Review round gate 2, above) and recorded, then the scratch was removed. +6. **Hand-written Notes.** The `no (…)` and turn-counting notes state what Candler does (`experiment.session_refused`/`experiment.setting_unsupported` map and the core's turn counting), which the answer and fact rows do not restate, so they stay. + +## Review round 3: the spec table + +The lead's Sonnet reviewer re-read the round-2 diff and found one of the six findings unfixed. `99028f47` had renamed `SPEC_ROWS` to `SPEC_ITEMS`, which made gate 1's `git grep` stop matching while the `(label, fn pointer)` table stayed: one gate's grep stands for the structure, and renaming to dodge it is not a fix. This round removed it. + +1. **The spec rows were still a table.** `type SpecCell` and `const SPEC_ITEMS` in `capabilities.rs` are deleted. `fields_table` now calls `write_row` twice, directly: once with `gateway_route(driver)` (its signature simplifies to take only the driver, which its two unused parameters hid) and once with `authoritative_trace(name, driver, registry)`. The `# Errors` text that described the table moved to the two functions, which keep their own `# Errors` sections. A colgrep search under `contract_pages/` found no other `fn`-pointer table or alias from this leaf; the other `(&str, _)` consts (`TRAITS` in `harness.rs` and `SURFACES` in `refusals.rs`) predate the leaf and are not `fn` pointers. Gate 1's grep `git grep -n 'ROWS\|fn cap\|Mapping\|SPEC_ITEMS\|SpecCell' -- crates/candler/tests/it/support/contract_pages/` on `613335ef` prints nothing (exit 1). + +The round-3 checks: `cargo fmt --check` clean; `cargo clippy --workspace --all-targets -- -D warnings` clean; the page tests pass (`7 tests run: 7 passed, 162 skipped`), and the page output does not change — `d1_regenerating_the_pages_changes_nothing` compares the regenerated page with the committed one byte for byte, and it held, so the removal of the table did not move a row. The full workspace nextest runs below. + +## What it leaves + +- **How it was developed.** One build slot (`l3-1`); three scratch worktrees for gate 2 (`pages-1` from the base, `pages-2` from the step-2 tip, `pages-3` from the review-round tip), each removed with its branch and target dir after its command logged. Nothing of any scratch is committed. +- **What it leaves in the code.** One producer of every per-driver cell: the drivers' `answer` and `fact`, plus the typed `gateway` and trace specs for the two rows no driver declares. One reader of the declaration for each page: `capabilities.rs::fields_table` over `AgentSetting::ALL` / `DriverFact::ALL`, with two direct `write_row` calls for the spec rows, and `config_pages.rs::paths_fields` over `CONFIGURATION_PATHS`. One shape: one `answer_words` for both pages, one `setting_label`, one `settle` for the guard, and no wrapper types (no `Row`/`RowKey`/`SpecRow`, and no `SpecCell` alias or `SPEC_ITEMS` const) to carry a label and a key or to table cells that two direct calls render. Nothing is kept for compatibility: `ROWS`, `Mapping`, `cap()`, `SpecRow`/`RowKey`/`Row`, `SpecCell`/`SPEC_ITEMS`, the two spec rows that duplicated a fact or an answer, and the `settle` copies are gone, not passed through. The pages restate no answer: every sentence of a setting or fact cell is the driver's own text. +- **How it is consumed.** An experimenter reads the capability page and sees each setting and fact once per registered driver, worded exactly as the driver declares it; a setting or fact with no answer would be a row that refuses to build rather than a blank or a hand guess. On the configuration page, a path shows a labelled answer per value of each setting family it reaches (OpenCode's `bypassPermissions` mapping and its `ultracode`/`sse` refusals among them), or is marked `Candler only`. A change to a driver's answer text with no regeneration fails the page test naming the row, so the page cannot drift silently from the declaration. + +## Step 3 + +The Sonnet reviews of the first and second rounds have run and are recorded in the Review section and in Review round 3. What remains for the lead is the seam review of the level. + +## Not run / remaining + +- The level's seam review (seam review 3 of the level-3 plan), by the lead. + +## How this leaf was implemented + +This leaf was a cost trial of a background CLI agent: OpenCode driven on RiVault, reviewed by Sonnet from the diff, without the run's own summary. + +| Run | Alias (backing model) | Output limit | Outcome | +|---|---|---|---| +| 1 | `RiVault/Reasoning-Medium` (DeepSeek-V4-Flash) | 32768 | ended on `length` in one design step, no edits | +| 2 | `RiVault/Reasoning-Large` (MiMo-V2.6-Pro-RL) | 32768 | ended on `length` the same way, no edits | +| 3 | `RiVault/Reasoning-Medium` | 65536 | steps 1–2 and the report: 132 steps, about 73k reasoning tokens | +| 4 | same session | 65536 | the six review findings: 57 steps, about 40k reasoning tokens; one fix was a rename that dodged gate 1's grep | +| 5 | same session | 65536 | the rename undone, the table removed: 31 steps, about 5k reasoning tokens | + +Each run's last step ended on `stop`, except runs 1 and 2. A `length` finish is a limit failure, not a model failure. The Sonnet review found six defects after run 3 and one after run 4. Run 4's report claimed every gate passed while the gate-1 structure survived under a new name, so a reviewer must judge the structure a grep stands for, not the grep's exit code. 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/__reports__/diet/leaves/sealed_run_producer_v0.md b/__reports__/diet/leaves/sealed_run_producer_v0.md new file mode 100644 index 00000000..1d1ba97a --- /dev/null +++ b/__reports__/diet/leaves/sealed_run_producer_v0.md @@ -0,0 +1,126 @@ +# Sealed run producer leaf, v0 + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| With the pre-S1 sealing reapplied, the output-reading guards fail on the tip and stay green on the base | PASS | §Bites | +| Probe wall times are in the report | PASS | §Probe | +| No guard on S1's path calls `seal_synthetic`; it is deleted; no new hand-made seeder | PASS | deleted; two cases the runner cannot produce use `seal_workspace` over `seal_run` (§Probe, Choice) | +| No digest or golden vector edited | PASS | the diff touches no `*.toml` vector, no manifest digest and no schema | +| fmt, clippy, nextest, doc | PASS | §Checks | +| `container-e2e` green on the pull request | pending the PR | | + +## Probe + +Question: can the real runner produce the state of the analyze-heavy guards? + +| What | Wall time | Source | +|---|---|---| +| `guard_analyze` guards over the hand-made store (30 to 32 runs, two engines' outcomes) | 1.1 s to 4.8 s each, 13 tests with `guard_run_evaluate` in 7.1 s | nextest, `-p candler`, tests in parallel | +| one scripted native run through the runner (`candler run`, PATH-fake docker, scripted agent; `World::launch`) | 4.3 s to 5.1 s each (`guard_cli_run::t3_cli_two_levels_plan_two_cells` 5.1 s, `b35_run_returns_supervisor_outlives` 4.3 s) | nextest, 10 tests in parallel | +| the same plus a scripted evaluator (uv plug-in) and `candler evaluate` (`guard_run_evaluate`) | 5.0 s to 7.2 s | nextest | + +The fake agent holds each container for one second, and a run adds the supervisor and the +store seal. The analyze guards need three arms of ten valid runs and two invalid ones, so 32 native +runs: at about 4.5 s each that is minutes, against 1 to 5 s. Also, `analyze` reads outcomes and +manifests, never outputs, so no analyze guard is on S1's path. + +**Choice (second round).** The probe does not show the real runner too slow: a scripted native run +through `candler run` costs about 4.5 s on an idle machine (9 to 27 s per guard when nine runs go +at once on a loaded one). So the guards that read what an agent left take their runs from it. The +first round's `seal_workspace` for all of them is superseded. + +The one native producer is `World::launch` (crates/candler/tests/it/support/cli_run.rs): the +PATH-fake docker whose agent, started with `start -a`, copies the files `World::agent_leaves` +set into its workspace (by default it writes `answer.txt`). The runner collects, filters, hashes +and seals them. No evaluator is scripted: these guards read outputs, not outcomes. + +Moved to the real runner, in `crates/candler/tests/it/guard_run_context_files.rs`: +`the_file_rule_decides_the_paths_and_the_digest` (six cases, one run each, one after another) and +`a_materialised_file_is_a_private_read_only_copy` (the 0444 half). + +Kept on the fallback, `seal_workspace` (crates/candler-core/tests/it/support/sealed_run.rs, which +calls the runner's `seal_run`), for two cases that the real runner cannot produce: +- `.claude/` stored in a run: the runner never collects it, `EXCLUDED_DIRS` in + `crates/candler-harness-claude-code/src/discovery.rs:6-7`. Guard: + `the_file_rule_treats_a_stored_dot_claude_by_its_glob`. +- an executable tree entry: the runner's tree marks every file `executable = false`, + `crates/candler-core/src/runner/evidence/tree.rs`, `TreeEntry::file(path, ..., false)`. Guard: + `an_executable_entry_materialises_as_a_private_0555_copy`. Flag: no real run can ever carry an + exec bit, so the 0555 materialisation is unreachable from real use today. + +The trade for those two: the runner's collection and tree filter are not exercised for them, +only its sealing step; the seeder calls `seal_run` and does not copy it. + +`seal_with_inputs` and `store_inputs` (`guard_run_context.rs`) stay: they seal runs with an empty +tree and store input-list blobs, so they read inputs and context digests, not outputs, and +stay green when `seal_run` drops output blobs. + +## Producer + +- Real runner: `World::agent_leaves(&[(path, bytes)])` then `World::launch()`, `finish`, and + `Store::open(&world.store())`; `sealed_run_with(files)` in `guard_run_context_files.rs` does the four. +- Fallback: `seal_workspace(store, template, attempt, files) -> RunKey` and `File`. + +## Bites + +The pre-S1 sealing is `seal_run_observed` without its first loop (`writer.output` for each file of +the tree): digests in the tree, no blobs. The earlier bite outputs came from one shared target dir +and are superseded: it served a stale test binary. Each revision below was built in its own fresh +target dir (`integrity-target/sealed_run_producer-base`, `-tip`, deleted after) with +`cargo nextest run -p candler-core -p candler -E 'test(/guard_run_context/) | test(/guard_run_evaluate::/)'`. + +| Revision with the revert | Compile lines | Result | +|---|---|---| +| base `origin/feat/integrity` | `Compiling candler-core v0.15.0 (.../integrity-scratch/sealed_run_producer-1/crates/candler-core)`, `Compiling candler v0.15.0 (.../sealed_run_producer-1/crates/candler)` | 10 run: 9 `guard_run_context` PASS (`the_file_rule_decides_the_paths_and_the_digest` PASS, `a_materialised_file_is_a_private_read_only_copy` PASS), `guard_run_evaluate` FAIL | +| tip | same lines with `sealed_run_producer-2` | 12 run: 7 passed, 5 failed: `guard_run_context_files::the_file_rule_decides_the_paths_and_the_digest`, `guard_run_context_files::a_materialised_file_is_a_private_read_only_copy`, `guard_run_context::an_executable_entry_materialises_as_a_private_0555_copy`, `guard_run_context::the_file_rule_treats_a_stored_dot_claude_by_its_glob`, `guard_run_evaluate` FAIL; the context ones with `the run materialises: Io { op: "open a blob" ... NotFound }` | + +On the base the output-reading `guard_run_context` guards stay green because `seal_synthetic` +stores the blobs itself, which is S1's mechanism. On the tip they fail on the missing blob. +`guard_run_evaluate` already failed on the base, through the real runner. + +## Checks + +Leaf target dir, machine loaded by other builds: `cargo fmt --check` exit 0; clippy `--workspace --all-targets -D warnings` exit 0; `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` exit 0. `cargo nextest run --workspace --no-fail-fast`: 742 run, 740 passed, 2 failed +(`guard_supervise::the_parents_environment_reaches_neither_the_child_nor_its_pre_stop`, +`guard_wiring::wiring_stop_execs_in_the_container_with_the_observed_id`, 56 s). An earlier run failed +`guard_container_record::stopped_run_has_its_agent_recorded_before_the_hook_sweeps` instead, at 72 s. All three +pass alone (0.7 s, 12.7 s, 130 s), touch nothing this leaf changed, and look like timing under load. + +## CI failure of 299469f9 + +`Gates` failed on `guard_run_context_files::the_file_rule_decides_the_paths_and_the_digest` (4.06 s): two of +the six case threads panicked at `support/cli_run.rs:331`, "no run sealed: 0 sealed, 1 expected". The fake +client's call log showed a job that built the gateway and the networks, started (or not even started) the +egress proxy, then tore down (`container stop`, `rm`, `network rm`) with no agent container ever created, while +`finish` saw `job.ended`. `container-e2e` was green. The log holds no job events, so the reason the two jobs +ended is not recorded; `assert_sealed` now prints the jobs' `events.jsonl` so the next occurrence names it. + +Cause, as far as it was shown: the six `candler run` worlds were started at once by threads inside one test, on +a two-core runner that also runs the other tests of the binary. Every other guard in the binary runs one world. +Locally the same test started eight times at once (48 worlds) failed in two copies, there in world setup +(`git commit` of the skills repository failed, `cli_run.rs:221`), so concurrency among worlds is what breaks; +the two symptoms differ, and the CI one was not reproduced. The cases now run one after another, about 4.5 s each; +four copies of both guards at once (28 worlds) then all passed. No retry and no longer timeout was added. + +## Verifier + +A fresh Sonnet agent was given the leaf, this report and the diff, twice: on the first round's diff +and on this one's. Both times it found no guard on S1's path that still makes its own sealed run. It +swept `put_blob|writer.output|RunWriter::create|TreeEntry::file|RunTree::builder|seal_run|seal_workspace` +over the tests: the remaining hand-made runs (`seal_with_inputs`, `store_inputs`) seal an empty tree and +read inputs; `guard_declared_inputs`, `guard_seams`, `guard_store`, `guard_run_exec` and the +analyze, CLI and golden seeders read no output bytes. It confirmed both reasons for the fallback: +`EXCLUDED_DIRS = [".claude"]` (`discovery.rs:7`) and `TreeEntry::file(path, digest, false)` +(`tree.rs:79`). + +## Follow-ups + +- `guard_run_context`'s `mini_store` guards (`a_plug_in_cannot_write_through_to_the_store`, + `a_corrupt_blob_is_refused_and_not_digested`) read outputs of imported runs, whose producer is the + importer; they stay green under the revert and are not on S1's path. +- Analyze, CLI and golden seeders (`guard_analyze.rs`, `guard_cli.rs`, `guard_cli_surface.rs`, + `guard_golden_design.rs`) are untouched: none reads outputs. +- Caps for a later pass: a real native run costs about 4.5 s under parallel load, so a store of + more than a handful of real runs needs its own cap. diff --git a/__reports__/diet/leaves/seam_fixes_v0.md b/__reports__/diet/leaves/seam_fixes_v0.md new file mode 100644 index 00000000..53192ec6 --- /dev/null +++ b/__reports__/diet/leaves/seam_fixes_v0.md @@ -0,0 +1,59 @@ +# seam_fixes: leaf report (v0) + +Status: done. Four fixes of seam review 1 (F8, F6, F2, F1) and the F5 doc line, one commit each. +Every guard was run on the base of its commit and failed there, then passed on the tip. The full +`cargo nextest run --workspace` passes (753 tests), as does `cargo clippy --workspace --all-targets +-- -D warnings`. + +## F8: kill off a terminal +- Change: the terminal test moved from `run` into `kill()`'s `if !args.yes` branch, after + `store_root` and `targets`. +- Gate: `kill_off_a_terminal_reports_the_store_before_the_confirmation` (`guard_cli_kill.rs`). + **PASS.** Base: stderr is `config.kill_not_confirmed` where the store's failure is wanted. Tip: + `candler.internal` "`kill` failed: Not a directory", and the control run on a good store still + gives "pass -y". +- Deviation from the brief: `--store ` is not a store failure on this base + (`targets` treats a missing `jobs/` as no jobs), so the guard uses `kill --all` with a store path + that is a regular file, which does fail in `targets`. + +## F6: every treatment level renders its failures alike +- Change: `resolve` resolves the levels in one loop; a preflight failure of any level goes through + `render_failures` / `print_failures`, and the loop stops at the first failing level. +- Gate: `o1_resolve_reports_a_later_level_failure_like_a_first_one`. **PASS.** Base: stdout empty + for the later level, the first level prints `treatment_identity.error`. Tip: stdout and stderr + equal for the missing tag in the first and in the second level. + +## F2: an MCP refusal names its field +- Change: `InvalidValue` gives its path as the pointer; the entry is read with + `serde_path_to_error` (already in `[workspace.dependencies]`, now also a dependency of + `candler-harness`), so the path ends at the field. A field-path segment cannot be an index, so a + fault inside `args` points at `args`. The registry row and both contract pages say what the path + is. +- Gate: the four `mcp` rows of `guard_silent_acceptance` ROWS. **PASS.** Base: `pointer: None` in + all four. Tip: `/mcp/servers/fs/command`, `/mcp/servers/fs/args`, `/mcp/servers/fs` (neither + `command` nor `url`: the entry is the fault) and `/mcp/servers/fs/env/token`. +- Every other `InvalidValue` now carries a pointer too (a cell field path as a pointer); no guard + pinned `None` for them. +- F5: the doc of `Setup::collector` says it is the core's file collector applied to the driver's + specs. + +## F1: one reader of `replicates` +- Schemas commit: `ExecutionError::ReplicatesNotCount`, code `experiment.replicates_not_count`, + pointer `/replicates`, message "must be a whole number from 1 to 4294967295"; `check_replicates` + beyond 32 bits returns it. Its registry row and the contract page row are in the same commit, + because the registry test needs them. +- Core commit: `check_replicates_input` keeps only the path refusal; `ReplicatesNotInteger` and + `experiment.replicates_not_integer` are gone from code, `codes.toml` and the contract page + (`git grep` over `crates/` and `docs/` prints nothing); earlier reports keep the code they + recorded. `Levels::replicates` refuses any non-`u64` value with the new code. +- Gates. **PASS** each. + - `replicates_are_checked_once` (schemas): base `experiment.cost_not_positive`, tip the new code, + pointer and range. + - Table in `guard_silent_acceptance` (op API: layers then `plan_runs`; `"three"`, `2.5`, `-1`, + `5000000000`): base panics in the layers with `experiment.replicates_not_integer`, tip all four + give `experiment.replicates_not_count` at `/replicates`. + - `o1_resolve_refuses_what_is_no_replicate_count_as_the_plan_does` (CLI, `resolve --set`, `-1`, + `2.5`, `5000000000`): base `experiment.replicates_not_integer`, tip the new code, pointer and + range. +- Deviation: the brief's one table for both entries is two tables with one hand-written + expectation, since the CLI and the op API fixtures live in different crates. diff --git a/__reports__/diet/leaves/seam_review_one_v0.md b/__reports__/diet/leaves/seam_review_one_v0.md new file mode 100644 index 00000000..1b6860ce --- /dev/null +++ b/__reports__/diet/leaves/seam_review_one_v0.md @@ -0,0 +1,92 @@ +# Seam review 1: findings, fixes and the spend checkpoint + +A fresh Opus reviewer wrote none of level 1. It read plan v2, the README purpose paragraph, `git diff +origin/main...origin/feat/integrity` at `4bc0d03b` and the level-1 leaf reports. Its report, kept as it returned, +is `integrity-tools/seam_review_one_reviewer.md`, outside the repository. It cost $4.87 against a $4 estimate and an +$8 cap. + +## Findings + +It found nothing that had to be fixed before level 2. It found eight should-fix findings and four to record. Each row +below gives the finding, the question it answers, and what was decided. + +| # | Finding (question) | Decision | +|---|---|---| +| F1 | `replicates` has two readers, `check_replicates_input` and `Levels::replicates`, and they give one value two codes, one of them `experiment.cost_not_positive` (Q2) | Fixed (rename, every consumer in one commit, no alias) | +| F2 | An MCP server refusal names no field and carries no pointer (Q6) | Fixed | +| F3 | OpenCode has no chain from an agent to a sealed run whose outputs are read back (Q5) | Deferred to P7, with the observation that closes it (A1) | +| F4 | P1's hand-built `.claude` case holds for Claude Code only; a real OpenCode run stores `.claude/x.py` (Q1) | Deferred to P7 with F3 (A1) | +| F5 | The conformance collector is one of the three filters real runs apply, behind a function-pointer `Collector` seam (Q3, Q5) | Doc line fixed; the seam recorded, with its follow-up named below | +| F6 | Treatment levels are read in two CLI verbs, and failures of the second and later levels bypass `render_failures` (Q2, Q6) | Rendering fixed; the second reader in the verbs deferred to M7 | +| F7 | The published MCP server schema is a more lenient second reading than `mcp::read` (Q2) | Fixed (RiVault, reviewed) | +| F8 | `candler kill` refuses off a TTY before it resolves the store, and `--yes` is decided in two places (Q2) | Fixed | +| R1 | The 0555 materialise path guards an executable bit the runner never writes (Q1) | Fixed the other way: the runner records each output's execute bit (maintainer's ruling) | +| R2 | `at_plan_fixed` splices a resolution by hand; the CLI guard covers the real producer | Recorded: redundant, not wrong. It goes when the row's file is next touched | +| R3 | `harness_wrote` is typed by hand per driver; the nested `.opencode` exclusion is held by a second oracle | Recorded: the conformance oracle runs the core's collector; the typed list is the oracle's expectation, not a reader | +| R4 | b41's dry run lost its "only the test's own jobs" scope assertion | Recorded: b40's line count holds the same property on the live path | + +F3 and F4 closing condition. P7's leaf, `dogfooding_pass.md`, gained this gate (amendment A1). After one real +OpenCode run of the pass, its stored outputs are compared with the files the agent wrote in its workspace, minus what +the driver's collect rule excludes. Reverting the conformance case alone does not give this producer-side observation. + +R1. The maintainer ruled that every stored output keeps its execute bit, whatever produced it. An evaluation plugin +that runs an output as part of its own evaluation must be able to, because results are meant to be easy to consume. +So the 0555 materialise path stays, and runs Candler executes now record the real bit, as import already did. P1's +hand-sealed executable case gives way to two guards from real producers: a run whose agent writes an executable +output, and an import of a folder that holds one. The tree digest of a new run with an executable output changes, +which the ruling accepts. No existing fixture run has an executable output, so no fixture digest changed. + +F5 follow-up. Before `feat/integrity` goes to `main`, the conformance-only public API of `candler-harness` goes, +together with the dev-dependency cycle it needs. That API is `Collector`, `Setup::with_collector`, `with_workspace` +and `with_collect_commands`. The cycle runs from `candler-harness` and both driver crates to `candler-core`, and it +leaves three copies of the `stored_paths` adapter. The oracle then reads the collection from a real run instead. +F3/F4's run under P7 is that observation for OpenCode. + +## Fixes + +Each guard was seen failing on its base before it passed on the tip. + +| Finding | Where | Guard | PR | +|---|---|---|---| +| F8 | `candler/src/commands/kill.rs` | `kill_off_a_terminal_reports_the_store_before_the_confirmation` | #67 | +| F6 (rendering) | `candler/src/commands/resolve.rs` | `o1_resolve_reports_a_later_level_failure_like_a_first_one` | #67 | +| F2 | `candler-harness/src/mcp.rs`, `refusal.rs` | the `mcp` rows of `guard_silent_acceptance` ROWS pin `/mcp/servers//` | #67 | +| F1 | `candler-schemas/src/execution.rs`, `resolve/layers.rs`, `runner/plan.rs` | `replicates_are_checked_once`; the replicates rows of `guard_silent_acceptance`; `o1_resolve_refuses_what_is_no_replicate_count_as_the_plan_does` | #67 | +| F5 (doc) | `candler-harness/src/conformance.rs`, the two driver conformance tests | none (comments) | #67 | +| F7 | `candler-schemas/src/servers.rs`, `mcp-server.schema.json` | `the_mcp_server_schema_refuses_what_the_reader_refuses` | #66 | +| R1 | `runner/evidence/tree.rs`, `runner/exec/gather.rs` | `an_executable_output_materialises_as_0555_and_a_plain_one_as_0444` (a real `candler run`); `an_imported_executable_materialises_as_a_private_0555_copy`, which also passes on the base because import already kept the bit | #68 | + +The fixes left these points behind. Each is recorded, and none needs an action. + +- F2 gives every `experiment.cell_value_invalid` the cell field path as its pointer, such as `/model/effort`. + `experiment.setting_unsupported` points at the `[fixed]` key instead, such as `/fixed/model.effort`. So the two + codes point at the same setting in two different shapes. +- A fault inside `args` points at `args`, because a field path cannot hold an index. +- F1 leaves `check_replicates_input` taking a `JsonValue` it no longer reads. +- The F7 schema cannot express the refusals `mcp::by_name` makes across a whole map: a duplicate rendered name, + and the `__` rule. +- The F7 schema refuses `null` for `command` and `url`, which serde reads as absent. This predates the change. + +Consistency check: `cargo nextest run --workspace` on the `feat/integrity` tip after the merges (`5b850c56`): 754 +run, 754 passed, 31 skipped. + +## Checkpoint + +The spend below is measured from transcripts, not from usage notes. Each cap is the leaf's own. + +| Level-1 row | USD | Cap | Within | +|---|---|---|---| +| P0 | 1.75 | 2 | yes | +| P1 | 7.82 | 20 | yes (about 81 tool calls against about 60: a call overrun, not a dollar one) | +| P2 | 2.38 | 8 | yes | +| P4 | 11.79 | 24 | yes | +| P6 | 1.17 | 2 | yes | +| Seam reviewer | 4.87 | 8 | yes | + +The RiVault runs of level 1 are unmeasured on the RiVault side, because their logs were plain text. + +**Decision on P5.** Level 1 is within its caps, so P5 runs, as the maintainer had also ruled. It is merged as #64. + +Milestone spend so far is about $108.5 against a cap of about $120. That is about $82 at the level-1 handoff, this +level's lead session at $24.0, and the coordinator's spend since handoff. The lead session's $24.0 splits as the lead +$14.6, `seam_fixes` $3.9 against a $5 estimate, P5 $3.0 against $6, `exec_bit` $2.2 against $4, and reviews $0.3. diff --git a/__reports__/diet/leaves/seam_review_three_v0.md b/__reports__/diet/leaves/seam_review_three_v0.md new file mode 100644 index 00000000..e825b0b4 --- /dev/null +++ b/__reports__/diet/leaves/seam_review_three_v0.md @@ -0,0 +1,103 @@ +# Seam review 3: findings and what was decided + +A fresh Sonnet reviewer wrote none of this code. It read the level-3 plan (v1), the leaf file, the inputs note carried from +the leaves, and the level-3 range `bf1f03ea..92c0f3a3` (#71, #72, #74, #75, #77, #78, #79), at `659258c2`. It read code +through colgrep only, and it ran no build. + +**Disclosure.** Before the coordinator's instruction not to, the reviewer had read the six leaf reports in full, including +their verdict, review and "What it leaves" sections. Every finding below rests on code it expanded itself (cited by +`file:line`); the leaf reports were used only to locate code. Where a point rests on a leaf report and not on code, it says so. + +## The four questions + +**1. Did any leaf add where it should have replaced?** No second producer of a catalog, MCP file or origin remains. What is +left is small: + +- Two one-line passthroughs: `candler-harness-claude-code/src/prepare.rs:95` and `candler-harness-opencode/src/prepare.rs:489` + each wrap `candler_harness::mcp::servers`, and `runner/exec/mod.rs:677` calls the library directly (F3). +- Effort and mode spelling has two readers: `EffortLevel::from_text` (`candler-harness/src/spec.rs:568`) and + `PermissionMode::from_text` (`spec.rs:620`) are called by the refusing reader at resolve and again by `Cell::effort` and + `Cell::permission_mode` (`spec.rs:1499`, `:1512`), which fall back silently (input 1 below). +- The census has two producers by design: the harness's `system/init` and the gateway (`isolation/gateway.rs:1268`, + `runner/exec/mod.rs`, `census(observed.init.or(gateway_init))`). The plan's revision 3 meant to drop the gateway census; + amendment A5 kept it. It is stated on the capability page (`docs/contract/harness-capabilities.md:57`). Not a defect. +- `comparable.snapshots` keeps one live writer, the importer, and one reader, `import/grading.rs:421-428`. Both have a reason. + +**2. One answer per driver per setting, one statement on the pages?** Yes. `ClaudeCodeDriver::answer` +(`claude-code/src/driver.rs:202`) and `opencode::prepare::answer` (`opencode/src/prepare.rs:113`) are exhaustive matches with no +wildcard over `AgentSetting`, and the MCP rows, `Codemode(true)` and the SSE refusal reach `harness-capabilities.md:42-45`. +`DriverFact::UnsetPermissionMode` is answered by both drivers (`claude-code/src/driver.rs:301`, `opencode/src/driver.rs:179`). +One gap: four answers are the same sentence written in both drivers (F5). + +**3. Same servers, same trace form on one cell?** Yes, with two caveats. Both drivers read servers through +`mcp::servers` and render from the typed server: Claude Code writes `.mcp.json` and passes `--mcp-config .mcp.json +--strict-mcp-config` (`claude-code/src/driver.rs`, `argv`), OpenCode writes the `mcp` entries in `render_config` +(`opencode/src/prepare.rs:495`). Both origins come from `ToolOrigin::mcp_tool(server, tool)` +(`claude-code/src/parse.rs:384-396`, `opencode/src/export.rs:160-178`). The caveats are F1 (an unset permission mode) and F2. + +**4. The two silent `other` readings.** + +- *Ingest without a cell.* `Registry::offline` (`crates/candler/src/drivers.rs:67`) hands the reader no server names, so every + OpenCode MCP call reads `Other`. Neither the reader nor any contract page says so: `ToolOrigin::Other` is documented only as + "Any other source" (`candler-schemas/src/trace.rs:640-662`), and no page under `docs/contract/` mentions an origin. A reader of + an ingested trace cannot tell "not an MCP call" from "an MCP call whose server was never declared". Not blocking: the run path + passes the cell's servers (`runner/exec/mod.rs:677-685`), and ingest has no cell to take them from. F2. +- *Undeclared server.* The difference is stated, once, in the doc comment of `ToolOrigin::Mcp` (`trace.rs`, "Claude Code's reader + takes any `mcp____` ... OpenCode's takes only a declared server"), which becomes the description in + `normalised-trace.schema.json`. The trace carries no marker, and no contract page repeats it. A third divergence is + unstated: an unknown non-MCP tool is `Builtin` on Claude Code (`parse.rs:395`) and `Other` on OpenCode (`export.rs:171-175`). + The reader of one trace is told only if they open the schema. F2. + +## Judging the inputs + +| Input | Belongs to level 3? | Decision | +|---|---|---| +| P8: `Cell` holds JSON; resume falls back silently | Yes, the cause is level 3's; the reach is narrow | Follow-up, non-blocking. `runner/plan.rs:851-884` (`answers`) lets a stored value the experiment does not declare replay without being checked, so a stored mode or effort that P8 does not know reads as `Default` or unset (`spec.rs:1499-1520`). Reaching it needs a run stored before P8 with text outside the enums. Fix: make `Cell::permission_mode` and `Cell::effort` fallible and let the replay path refuse. Typed fields in `Cell` are not needed. I did not run a reproduction | +| P8: `setting_unsupported` names the harness slug, not the version | Level 3, cosmetic | Follow-up, non-blocking | +| P8: `MissingValue` has no field path | Pre-existing | Follow-up, non-blocking | +| P9: a server key that is no field-path segment gets no `codemode` | Stale: it is refused | `fill_codemode` (`runner/plan.rs:582-611`) returns `PlanError::Driver(InvalidValue)` for such a key. It is refused at plan, not at resolve, but before any job. Closed | +| P10: two silent `other` readings | Yes | Question 4; F2, non-blocking | +| P10: `offline_reader`'s `servers` is unused by Claude Code | No action | The parameter exists for harnesses that spell `_` (`claude-code/src/driver.rs:347`, `opencode/src/driver.rs:260`); one producer, no second reader | +| P10: server keys held to the name pattern by the reader only | Follow-up | Non-blocking; carry the const into `propertyNames` if the schema ever types the map | +| P12: `needs.snapshots` / `context.snapshots` removal | Follow-up, already decided | The input's premise is partly out of date: `python/candler-evaluator/.../plugin.py:119` now reads `context.get("snapshots", [])`. The protocol wire still requires the key (`docs/contract/evaluator-protocol.md:40,72,160,306`). The deferral is stated in `__design__/architecture.md:1044` and in the `evaluation.rs:1616` doc comment. It is not on the contract page, where an evaluator author meets the field with description "-". Non-blocking (F6) | +| P12: "always empty" wording and the import exception | Yes, wording | `import/grading.rs:421-428` fills `context.snapshots` from an imported run. Line 1044 says "for runs Candler makes", which is true, and `architecture.md:623` and `:1146` say imported only; no one place states both. Fold into F6 | + +## Findings + +| # | Finding | Cause | Leaves | Why no verifier saw it | Blocking | Fix | +|---|---|---|---|---|---|---| +| F1 | A cell with an MCP server and no `permission_mode` installs the same servers on both harnesses but does not call them alike: Claude Code runs `--permission-mode default` (`claude-code/src/driver.rs`, `argv`, `cell.permission_mode()` reads absent as `Default`); OpenCode runs `--auto` over an allow-all baseline (`opencode/src/driver.rs:179`). I did not check what Claude Code does with an MCP call under `default` in headless mode | `UnsetPermissionMode` facts at `claude-code/src/driver.rs:301`, `opencode/src/driver.rs:179` | P8, P13 | P8 gated that the fact is answered and shown on the page. P13's guard sets `bypassPermissions` so the harnesses compare, and so never exercises the unset case | No: the page states both answers. The user's case is an experiment that sets no mode and sees MCP calls only on OpenCode | Decide the default per harness, or let resolve refuse an MCP cell with no mode. The parity run's own "not covered" line already names it | +| F2 | The trace does not tell a reader why an MCP call reads `other` or `builtin` (ingest, undeclared server, unknown non-MCP tool); the reason lives in a type doc comment only | `trace.rs:640-662`; `drivers.rs:67`; `parse.rs:395` vs `export.rs:171-175` | P10, P11 | P10's gates named the two readings as "not covered" and deferred them to this review. P11 generated pages from the declaration, and the origin is no declaration | No | One row on `harness-capabilities.md` for how each harness reads an MCP call, with the ingest case; or a `Fact` for it | +| F3 | The `mcp_servers` wrappers of both drivers are pass-throughs to `mcp::servers`, and the core calls the library directly | `claude-code/src/prepare.rs:95`, `opencode/src/prepare.rs:489`, `runner/exec/mod.rs:677` | P9, P10 | Each leaf kept its own call site; no gate asks for a call count | No | Delete the two wrappers; call `mcp::servers` | +| F4 | A stored cell replays text P8 does not know as `Default` or unset | `runner/plan.rs:851-884`, `spec.rs:1499-1520` | P8 | The guards go through resolve, which refuses the text. Replay does not go through it | No (needs a pre-P8 run) | See the P8 input row | +| F5 | `ModelEndpoint`, `Env`, `Inputs` and `WallBudget` carry the same `Candler { how }` text in both drivers, and nothing ties the text to what the core does | `claude-code/src/driver.rs:202-282`, `opencode/src/prepare.rs:113-196` | P8, P11 | The walk checks that each driver answers; it does not check that a core fact is stated once | No | Put the four answers in one `const` in `candler-harness`, which each driver returns | +| F6 | The evaluator `snapshots` deferral is not where an evaluator author reads the field | `docs/contract/evaluator-protocol.md:40,72,160,306` | P12 | The leaf's gate was "the deferral is stated", and it is, in the design document and in a doc comment | No | Carry the doc comment into the page row, with the import exception | +| F7 | OpenCode's bare `tool` is the name after `_`; I did not check whether OpenCode rewrites characters of a tool's own name when it builds the id, in which case `tool` would not be the server's name for it | `export.rs:160-166` | P10, P13 | The parity fixture's tool is `stamp` | No (unverified) | Run one tool whose name has a `.` or `-` on OpenCode | + +## Not reviewed + +- Each PR's oracle vectors, generated schemas and generated pages (by instruction). +- `tools.allowed` and `tools.disallowed`: whether an MCP tool name is spelled in each harness's own form in those lists. +- The stored Claude Code trace keeps the raw `system/init` line (the P10 condition): not checked in code. +- Container-e2e and the live runs, which no review of code can show. + +## Consistency + +Read-only. No code changed, no build run, nothing committed. Nothing found blocks level 3. + +## What the lead decided + +The lead read F1, F3 and F4's code at the cited lines, and they hold. F1's `UnsetPermissionMode` answer for Claude Code +says in so many words that a headless run under `default` denies every tool call that needs approval. So the gap is +stated on the page, not silent, and choosing a default for MCP cells is a design call for the next milestone. + +Nothing blocks level 3. Two findings were against the level's own gate ("no second producer, second reader or passthrough +left by the level"), and both are fixed in #80: +- F3: the two `mcp_servers` passthroughs are deleted. +- F4: `Cell::effort_at` and `Cell::mode_at` in `candler-harness` are the one reader of effort and mode text. Resolve and + both accessors call them, so a replayed cell with unknown text is refused with `InvalidValue` at its field instead of + running as `Default`. The coordinator ruled F4 into the level: a silent default becoming a refusal is what Integrity is + for, and Candler has no outside users to protect from it. + +F1, F2 and F5–F7 are recorded, in order, under "Next" in the knowledge-transfer report. The review cost $1.22 against a +$3 estimate and a $6 cap (25 calls, measured from its transcript). diff --git a/__reports__/diet/leaves/seam_review_two_v0.md b/__reports__/diet/leaves/seam_review_two_v0.md new file mode 100644 index 00000000..ed09f54e --- /dev/null +++ b/__reports__/diet/leaves/seam_review_two_v0.md @@ -0,0 +1,44 @@ +# Seam review 2: findings and what was decided + +A fresh Sonnet reviewer wrote none of this code. It read plan v2, the README purpose paragraph, +`seam_review_one_v0.md`, `git diff origin/main...origin/feat/integrity` at `cd968c54` with level 2 in focus (#64, +#66, #67, #68), and the level-2 leaf reports. Its report, kept as it returned, is +`integrity-tools/seam_review_two_reviewer.md`, outside the repository. It cost $2.0 against a $2.5 estimate and a $5 +cap. Its brief put three questions first: does any run path seal without its snapshot or its execute bit; does each +input have one reader; is any guard fed state that no real producer makes. + +## Findings + +Nothing had to be fixed before P7. Every run Candler executes is sealed through `drive`, which stores the catalog +blob and writes each output's real execute bit. The blob is written before `seal_run` writes the manifest, so a +failure in between leaves an orphan blob, not a manifest that names a missing one. + +| # | Finding | Decision | +|---|---|---| +| S1 | `RunWriter::blob` (`store/run.rs:170`) stores the freshly captured catalog without checking it against a digest. The manifest of a forced or pinned run keeps the stored cell's comparable (`runner/exec/mod.rs:114`), so it can name a catalog other than the one the agent saw | Recorded; follow-up below | +| S2 | `inspect` reads the catalog blob leniently and untyped (`commands/inspect.rs:218`, `:372`): an unreadable or invalid blob reads as "catalog not stored", and no guard covers the `server` and `tool` lines | Recorded: it is the typed-catalog follow-up already named after #64 | +| S3 | `resolve --json` and every stored job spec carry the full catalog text, in `preflight[].blobs` (`resolve/preflight.rs:59`, `jobs/model.rs:20`) | Recorded: the job spec is the only channel from the foreground to the supervisor, so removing the text needs a second channel, which is a design call | +| S4 | The execute bit is read in two places, `runner/exec/gather.rs:342` and `import/read.rs:253` | Recorded: two producers each read the mode of their own file; no input has two readers | +| S5 | `experiment.cell_value_invalid` and `experiment.setting_unsupported` point at the same setting in two shapes | Recorded: already recorded by seam review 1 | +| S6 | No page under `docs/contract/` documents the stored catalog or the op API's `InspectRun.catalog` | Recorded: P7's consumers look for the stored catalog from the documentation alone, and the pass records whether they found it | + +S1 follow-up. A forced run whose manifest names a catalog its agent did not see is a provenance claim that can be +false, which is the subject of this milestone. First, settle whether it is reachable: a probe stores a cell, changes +the catalog the fake image prints, and runs again with `--force`. Then decide between refusing at seal (the store +checks the blob against the manifest's digest, as it checks outputs) and stamping the manifest with the digest of +the catalog the run saw. The meaning of `--force` is decided on that evidence. + +The reviewer also recorded, with no action needed: + +- Interrupted, imported and older runs all show "catalog not stored". +- The test producers `seal_workspace` and `seal_with_inputs` still build state by hand, and `sealed_run.rs:47` writes + `executable = false`. Their cases cover state no runner path makes (the `.claude` file rule; declared inputs), and + F3/F4's P7 gate is the producer-side observation for the first. +- Evaluators are not handed the catalog snapshot (`evaluation/context/assemble.rs:110`). +- `resolve` prints level 0 only; `run` and `resolve` still report a level failure differently (the F6 remainder, + deferred to M7). + +## Consistency + +No code changed after the review. `cargo nextest run --workspace` at `5b850c56`, the last code change on the tip: +754 run, 754 passed, 31 skipped. diff --git a/__reports__/diet/leaves/snapshot_out_v0.md b/__reports__/diet/leaves/snapshot_out_v0.md new file mode 100644 index 00000000..c3ea9282 --- /dev/null +++ b/__reports__/diet/leaves/snapshot_out_v0.md @@ -0,0 +1,67 @@ +# Snapshot out (P12): leaf report + +Base `7d497545` (`origin/feat/integrity`). Tip: see the commit table. Branch `leaf/l3-snapshot-out`, build slot `l3-2`. + +## Commits + +| Commit | Subject | +|---|---| +| `e8b07a32` | `test(api): read a run's installed MCP config back through inspect` | +| `4988b245` | `feat(schemas)!: drop the catalog snapshot and show MCP in inspect` | +| `cc7f12c8` | `refactor(runner): remove the constant catalog producer, show MCP config` (the roadmap's line is 88 characters; the commit hook allows 72) | + +The schemas commit touches only `crates/candler-schemas/`, as CI's Commit messages job requires. It is a major bump on the schema line (a record valid before is invalid: `catalog-snapshot.schema.json` leaves, `inspect-run` loses `catalog` and requires `mcp`), so it carries `!` and a `BREAKING CHANGE:` footer (CONTRIBUTING §Schema line). + +**The workspace does not build at the schemas commit alone.** `candler-core` and `candler` still name `CatalogSnapshot`, `InspectRun.catalog` and `CatalogError` there, and `candler-schemas`'s own `guard_refusal` reads `docs/contract/codes.toml` and the oracle vectors, which live outside the crate and change in the next commit. The step-2 commit restores a green workspace. The step-1 guard test fails by design on its own commit. + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| Guard on `candler run` -> `inspect`, one declared server, JSON and text | PASS | `inspect_shows_the_mcp_server_a_run_was_launched_with` launches `candler run --set mcp.servers.fs.command=mcp-fs --set 'mcp.servers.fs.args=["data"]'` through the fake docker, reads the sealed run back, and finds `mcp.servers.fs.command = "mcp-fs"` and `mcp.servers.fs.args = ["data"]` in `record["mcp"]` and the same two lines in the text form. On the base commit (`e8b07a32`): FAIL, `the record shows the mcp values: {"catalog":{"provider":"candler-image@1","schema":"tool-catalog-snapshot/1","servers":[]},...}`. | +| `CATALOG_PROGRAM`, `CatalogCommand`, `CommandCatalogProvider`, `CatalogStep`, the fake docker's constant, the provider seam | PASS | All deleted: `runner/evidence/catalog.rs`, `resolve/steps/catalog.rs`, the constant in `commands/preflight.rs`, the `printf` branch of the fake `docker run`, `M2bServices.catalog`, `catalog_spec` and its two control-kind rows. `CatalogProvider` had one implementor besides test fakes, so the seam went with it. The plumbing that only carried the catalog text to the seal went too: `StepReport.blobs`/`blob()`, `CellRun.blobs`/`with_blobs()`, `RunWriter::blob`. | +| `comparable` carries no catalog snapshot; new digest version vectors; old vectors verify | PASS (accepted by the coordinator on the condition that nothing makes new runs set it) | `Comparable.snapshots` is `Option>`: `None` is left out of the record and the hash, and `Some(list)`, empty or not, is written and hashed as before #76. Only the importer sets it (`import/manifest.rs` via `ComparableBuilder::snapshots`), because an imported run's digest included it. Guard: `a_cell_from_resolve_is_stored_and_hashed_without_snapshots` runs `candler run`, reads the stored manifest, finds no `snapshots` key, and recomputes the cell digest with `Digest::of_canonical` to equal the run key. Bite: `build` forced to `Some([])` makes it fail on the key. Oracle: `cell_digest.toml` has 7 vectors; the six that carry `snapshots` (`invented-1` with `[]`, back to its first body and digest) keep their digests, `invented-4` is the key-less shape. No existing manifest's digest moves, so the version marker stays `run-manifest/1` (the digest doc comment requires a new tag only when an existing manifest's digest changes). The experiment path `snapshots` is removed too (row below). | +| `inspect` callers gate (htn-creator-eval@0.5.3) | PASS | Supplied by the lead, not re-run: all 279 `.py`/`.sh` files under the HTN and candler paths were searched for `candler ... inspect`, `"inspect"`, `["catalog"]` and `.get("catalog")`. The one hit, `infrastructure/htn_creator_eval/cli.py:1053`, forwards to the HTN's own trace profiler, not to `candler inspect`. `candler-plugin/` has no `inspect` or `catalog` reference. `_catalog_snapshot.py` reads the HTN's own committed `catalogs/*.json`. No reader of `InspectRun.catalog`, so it was dropped. | +| `InspectRun.catalog` and `catalog_of` gone; an old sealed run still reads | PASS | Both deleted. `inspect` reads the manifest only; the stored blob is left in the store and not shown, and no shim reads it. The old manifests read through `RunManifest` (unchanged `snapshots` reader), covered by the golden and import guards in the workspace run. | +| `tool-catalog-snapshot/1` gone | PASS | `candler-schemas/src/catalog.rs`, `schema/catalog-snapshot.schema.json`, `tests/it/catalog_fixtures.rs`, `catalog_properties.rs`, the `tests/fixtures/{spec,upstream}` fixtures, the catalog test in `guard_wire_shapes.rs` and `guard_cell_digest.rs`, and `catalog_content_digest.toml` with its generator section. The plan lists `catalog_content_digest.toml` among vectors that stay; the leaf says vectors only `/1` uses go. Only the deleted digest test read it, so it went. | +| README, AGENTS.md, live candler-v1 M6c Goal | PASS | `per-run tool census` in `README.md:7`, `AGENTS.md:8`, and `__roadmap__/candler-v1/.../integrity/README.md:7`; `README.md:12` no longer lists catalog providers, `CONTRIBUTING.md` drops the `catalog` surface, and `__design__/architecture.md` states a run's tools by the resolved `mcp.*` config, the census and the trace, with `comparable.snapshots` described as the imported old shape; `AGENTS.md` names "a tool census" among the stored states. No page under `docs/` quoted the phrase. Done leaves and reports keep their words. | +| Refusal codes only the removed code emitted | PASS | `catalog.*` (6 schemas codes), `runner.catalog_command_failed`, `runner.catalog_timeout`, `runner.catalog_unreadable`, and the three `[internal]` rows of the core `CatalogError`; `docs/contract/codes.toml` and `index.md` regenerated (`CANDLER_BLESS_CONTRACT=1`); the `catalog` surface left `SURFACES`; the two `CatalogError` rows left `__roadmap__/m3-lean-cli/refusal_scope.tsv`, which `guard_refusal_codes` reads as its oracle. | +| `cargo fmt --check`, clippy `-D warnings`, `cargo doc -D warnings` | PASS | exit 0 for each on the tip. | +| Experiment path `snapshots` | PASS | The row left `CONFIGURATION_PATHS` (48 rows) and `configuration-paths.md`, so resolve refuses it as an unknown path; the four tests that derived it no longer do. HTN check at the tag (`git grep snapshots htn-creator-eval@0.5.3 -- *.toml *.json`, excluding reports and catalogs): no experiment sets it. | +| Evaluator-protocol `snapshots` (`needs`, `context`) | BLOCKED, left for the lead | The HTN check passes (no evaluator declares a `snapshots` need; the only hits are two prose lines in its candler-plugin). But the removal is not safe: `python/candler-evaluator/src/candler_evaluator/plugin.py:119` reads `context["snapshots"]` unconditionally and `loop.py:43` writes `"snapshots": []` into needs, so every plug-in on the published helper would break on a missing key; the import grading step fills `context.snapshots` from the imported cell, so the context digests of `context_digest_runs.toml` and of imported outcomes would move; and the three schema files, `field_classes.toml`, the registry/assemble refusals and the contract page all change. Nothing was changed. | +| `cargo nextest run --workspace` | PASS | `Summary [198.378s] 730 tests run: 730 passed (6 slow), 31 skipped` (729 in round 1). The 31 skipped are the Docker-gated `container-e2e` tests, which the lead reads from the PR's CI. The first run on the tip failed five (the guard, three pinned-digest tests, and the refusal-scope oracle); each is fixed in the step-2 commit (see Pins retaken). | +| `container-e2e` green on the PR | BLOCKED | Read from the PR's CI by the lead. | +| Step 3 scratch bite | PASS | On a scratch branch from the step-2 tip, `inspect.rs` shows `mcp: BTreeMap::new()`; the guard FAILS: `assertion left == right failed: the declared command is shown: {... "outcomes":[] ...}` at `guard_inspect_mcp_config.rs:57`. Scratch worktree, branch and target dir removed. The fresh verifier is the lead's. | + +## Pins retaken + +Four tests pinned digests of cells built by the real planner (`guard_egress_setting`: `LISTED_DIGEST`, `BASE_DIGEST`; `guard_run_plan::t3_one_level_plans_the_old_bytes`: both cells, the experiment digest, and the replicate order, which the planner derives from the digests). Those cells hashed an empty `snapshots` list before; they hash without it now, so the pins moved. They were re-taken from the producer's output, which is the new digest version's meaning, not a drift. + +## What it leaves + +**How it is developed.** The guard was run on the base first and failed for the stated reason after two false starts of the test itself (an absolute path in `--set` that the resolver refuses, and a fake docker with no top-level `inspect`, which the start probe of a declared stdio server calls). No Docker, no live model, one build slot (`l3-2`), no scratch worktree kept. The Python generator reran under `uv run --with rfc8785` and changed only `cell_digest.toml`. + +**What it leaves in the code.** One producer of the MCP record: the resolved `mcp.*` values, written by resolve and read by `inspect` from `comparable.values`. The constant catalog, its capture, its resolve step, its seam, the blob plumbing that carried its text, its schema, its fixtures, its refusal codes and its inspect surface are deleted in the same change. The one thing kept without a producer is the optional `comparable.snapshots` read of manifests that list it (gate row above); the importer still writes it for imported legacy runs, which is the field's only live writer. + +**How it is consumed.** The experimenter's `inspect` shows `mcp.*` by path, in the JSON record (`mcp`) and as `pathvalue` lines in text. A run with no MCP server shows an empty `mcp`. The record no longer shows a tool catalog Candler did not observe. `inspect-run.schema.json` changes (`catalog` out, `mcp` required), which is the compatibility item below. + +## Not covered + +- **HTN-side follow-up for the lead to hand on:** htn-creator-eval@0.5.3 keeps grading, but its one test that validates against Candler's `catalog-snapshot.schema.json` now skips. The schema file has to move into the HTN repository (the `/1` marker stays the HTN's own). Nothing in the HTN repo was touched. +- Step 3's fresh verifier, and the PR's `container-e2e`: the lead's. +- The evaluator-protocol `needs.snapshots` and `context.snapshots` (row above). +- **HTN-side follow-up (the coordinator takes it on):** move `catalog-snapshot.schema.json` into htn-creator-eval and un-skip its validation test; it belongs to that repository. + +## Compatibility for consumers + +- `inspect-run/1` consumers: `catalog` is gone and `mcp` (object, path to value) is required. +- `run-manifest/1`: old manifests keep their digests, with `snapshots` absent, empty or listed. A cell Candler makes now carries no `snapshots` key, so the run key of a new run differs from the key the same experiment had before #76 (the empty list is no longer hashed, and `codemode` is filled by an earlier leaf). +- The schema line takes a major bump (minor while `0.y.z`); an experiment or `--set` that names `snapshots` is refused as an unknown path. + +## Review (round 3) + +1. **Raw-ingest key.** `import/raw.rs` `comparable_of` now writes `.snapshots(Vec::new())`, as the manifest importer does; the field's doc comment names both importers. Test `i1_a_raw_cell_keeps_the_digest_it_had_with_an_empty_snapshots_list` rebuilds the pre-#76 cell text by hand (sorted keys, `"snapshots":[]`), hashes it with `Digest::of_bytes`, and requires the stored run key to name that digest. On the round-2 tip (before the fix) it FAILED: `the empty list is kept: left Null, right Array []`. On the fixed tip it passes. +2. **Refusal proven.** `r3_an_experiment_cannot_set_snapshots` asserts code `experiment.unknown_path` and the path text for `--set snapshots=[]` and for a `[fixed]` value. `SNAPSHOTS` left `TYPED_ROOTS` and `candler-schemas` `paths.rs` (no importer used the constant; they write the literal path). +3. **Wording.** `execution.rs` (field doc, `from_resolved` doc, the sources `$comment`) and the generated `run-manifest.schema.json` say the key is absent for a run Candler made and present, possibly empty, only for an imported run. +4. **Helper.** `RunContext.from_wire` reads `context.get("snapshots", [])`. `tests/test_guard_context.py::test_a_context_without_snapshots_is_accepted` FAILED before (`KeyError: 'snapshots'`) and passes after; run as CI does (`uv run --frozen pytest -q`: 12 passed; `ruff check`, `ruff format --check` clean). The wire models were regenerated for the new schema descriptions. `loop.py`'s `"snapshots": []` is the helper's `needs` output, which the wire still requires, so it stays. +5. **What the field is now.** The `needs.snapshots` and `context.snapshots` descriptions in `evaluation.rs` (and the four generated evaluator schemas) and the evaluator-protocol section of `__design__/architecture.md` say: always empty for runs Candler makes; kept so the released helper and stored grading contexts stay valid; removed once a helper that treats it as optional is released. No valid record became invalid. diff --git a/__reports__/diet/leaves/trace_parity_v0.md b/__reports__/diet/leaves/trace_parity_v0.md new file mode 100644 index 00000000..d6e590c1 --- /dev/null +++ b/__reports__/diet/leaves/trace_parity_v0.md @@ -0,0 +1,86 @@ +# Trace parity leaf, v0 + +An MCP call reads the same in the trace of either harness: `origin: {mcp: {server, tool}}`. The +census names no server. The OpenCode endpoint the leaf was to read the census from does not exist +in the pinned binary; the coordinator kept the gateway census (amendment A5), so each census names +its source. + +Base `21d8486c` (`origin/feat/integrity` at the branch point). Tip: the tip of the +branch `leaf/l3-trace-parity`, which also merges `feat/integrity` at 29573006 (P9). + +## What changed + +- `ToolOrigin::Mcp` has an optional `tool` (bare tool name); `ToolOrigin::mcp_tool(server, tool)` is + the one constructor. A trace without the field reads and writes back without it. +- Claude Code's reader fills `tool` from `mcp____`. +- `HarnessDriver::offline_reader` takes the cell's declared server names. OpenCode's export reader + reads `_` against them, longest name first; a name no declared server begins is + `builtin` or `other`, never a guessed server. `execute` stays a built-in call with empty + `wrapped_calls`. The core passes the names of `mcp::servers(cell)`; `Registry::offline` (ingest, + no cell) passes none. +- `check_settings` of the OpenCode driver refuses servers where `a_` begins another name: + `DriverError::AmbiguousServers`, code `experiment.mcp_server_prefix_ambiguous`. The contract pages are + regenerated. +- `census.mcp_servers`, `InitReport.mcp_servers`, `InitReportError::ServersNotList` and Claude Code's + reading of `mcp_servers` are gone; code `harness.server_list_malformed` is marked lifted. + `SERVER_START_WAIT` no longer says the census records servers; `architecture.md` follows. +- Conformance: `Case::with_mcp_call` checks the origin of the one call a case's stream holds, and each + driver has one such case. + +## Gates + +| Gate | Verdict | Evidence | +|---|---|---| +| OpenCode export of `s_t` reads `mcp{s,t}`; `other` on the base | PASS | base (`9dffe92b`): `guard_mcp_origin::one_call_has_one_origin_on_both_harnesses` FAIL, `"opencode": [{"kind":"other"}]`; tip PASS | +| Claude Code `mcp__s__t` reads the same origin | PASS | base FAIL: `{"kind":"mcp","server":"s"}` has no tool; tip PASS | +| `tool` optional; an old trace still reads | PASS | `guard_trace_wire::an_mcp_origin_without_a_tool_still_reads_and_one_with_it_round_trips`; the hand-written trace file's wrapped call has no `tool` and round-trips byte for byte | +| Stored Claude Code trace keeps the raw `system/init` line | PASS | `guard_mcp_origin::claude_code_trace_keeps_the_raw_init_line`: the trace holds `"subtype":"init"` with `"status":"connected"`; passes on the base too | +| OpenCode reader takes server names from the cell, never from spelling | PASS | `opencode_export_reader_attributes_calls_to_the_declared_servers_only`: `x_t`, `s`, `s_` are `other`; with no declared server `s_t` is `other` | +| Resolve refuses ambiguous prefixes, with a code | PASS | `opencode_refuses_servers_whose_tool_prefixes_are_ambiguous`; `contract_pages` d1 and d3 pass | +| Code mode: `execute` calls, empty `wrapped_calls` | PASS | same reader test: `execute` is `builtin`, `wrapped_calls: []` | +| `census.mcp_servers` and Claude Code's server-status reading gone; `init_tools` stays | PASS | `guard_run_evidence::b25_census_from_a_real_init` (2 values), `guard_container_record` (`census.mcp_servers` is `None`); `harness_baseline/census.json` loses the key | +| Each census names its source: Claude Code's is its `system/init`; OpenCode's is the tools its model was offered at the gateway (A5) | PASS | `CensusSource` and `census.source` stay: `guard_harness_facts::harness_census_records_what_the_source_saw` records no `census.source` for the harness's own init and `"gateway"` for the gateway's; `guard_census_gateway` holds the gateway run's `census.source`. The original endpoint does not exist: see Probe | +| Trace and census schemas regenerated; conformance checks the MCP origin for every driver | PASS | the trace schema regenerated (`drift` passes); no census schema names the field; `conformance_opencode_recorded_runs` and the Claude Code suite run `mcp_call` cases | +| A server name is letters, digits, `-` and single `_`, by `name` or by key | PASS | `guard_mcp_names::a_server_name_is_letters_digits_and_dashes_joined_by_single_underscores`: `s_`, `_s`, `a__b`, `a.b`, `my srv` refused, by name and by key; `a-b`, `a_b` accepted | +| The published schema refuses what the name rule refuses | PASS | `fix(schemas)!`: `McpServer.name` carries `SERVER_NAME_PATTERN` (`^[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*(?![\s\S])`, the end anchor the schemas use); `guard_mcp_server::the_mcp_server_schema_refuses_what_the_reader_refuses` has the rows `a.b` and `s_`. No published schema types the server map, so the keys are checked by the reader only | +| Report's "What it leaves" | PASS | below | +| fmt, clippy `-D warnings`, nextest, doc `-D warnings` | PASS | all clean. `guard_wiring::wiring_stop_execs...` and `guard_known_truth::kt_two_levels...` each failed once in a loaded full run and passed alone (89 s and 2 s) | +| container-e2e | not run locally | runs on the PR | +| Step 3 bite | PASS | scratch worktree on the tip with `origin_of` returning `Other`: `guard_mcp_origin` FAIL (`"opencode": [{"kind":"other"}]`), the reader test and `conformance_opencode_recorded_runs` FAIL; scratch removed | +| Fresh Sonnet verifier | MISSING | the lead dispatches it | + +## Probe (the stop) + +The pinned image (`assets/docker/base-opencode`, `OC_VERSION=2.2.7`, built as `l3-trace-probe-img`, +run as `l3-trace-probe-1`, both removed) served `opencode serve` with a config declaring one stdio +server. Its `/openapi.json` lists 139 paths, all under `/api`; `GET /experimental/tool?provider=..&model=..` +and `/experimental/tool/ids` return the web app's HTML page, not a tool list, and no path lists tools. +`/api/mcp` answered `{"data":[]}` for the declared server; `/api/config` showed the config loaded. No +model call was made. The docs expose the tool list only to plugins as `ctx.tool.list()`. The leaf's second +check fails, so the gateway census stays (A5). + +## What it leaves + +- **Developed:** one probe image and container, removed; one scratch build for the bite, removed. + Builds shared the `l3-2` target dir. +- **In the code:** one origin function per harness, one constructor, one reader of `mcp.servers`. + The server-list census value and its error are deleted. The gateway census, + `CensusSource` and `census.source` stay by A5. A server name is one both harnesses carry into a tool + id unchanged, so a call splits one way only. +- **Consumed:** the experimenter reads `origin.mcp.server` and `tool` the same on either harness; a + server's status is in Claude Code's raw init line, which the trace keeps. + +## Not covered + +Left by this leaf, judged at seam review 3: + +- An OpenCode export ingested without its cell reads its MCP calls as `other`. +- A server the cell does not declare reads as `other` on OpenCode and as `mcp` on Claude Code: Claude + Code's `origin_of` takes any `mcp__x__t`, OpenCode's reader only declared servers (stated on + `ToolOrigin::Mcp`). +- `offline_reader`'s `servers` argument is unused by the Claude Code driver, and `Registry::offline` + and the ingest path pass `&[]`. It is the shape a harness that spells calls `_` needs, + not a second producer. +- The reader of server names (`candler_harness::mcp::by_name`) is written out, not compiled from `SERVER_NAME_PATTERN`: the pattern ends with the lookahead `(?![\s\S])`, which the `regex` crate does not read, and no other runtime dependency does. The string is in the tree once, but the rule is stated twice, as that pattern and as the reader's code: a lookahead-capable regex dependency in `candler-harness`, only to state one rule once, would cost more than it saves. Two tests tie the statements together with the same names: `guard_mcp_server::the_mcp_server_schema_refuses_what_the_reader_refuses` (the schema's side, rows `a.b` and `s_`) and `guard_mcp_names::a_server_name_is_letters_digits_and_dashes_joined_by_single_underscores` (the reader's side). +- The `feat(schemas)` commit removes `ToolOrigin::mcp`, so the workspace builds again only at the + `fix(library)` commit after it. diff --git a/__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/README.md b/__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/README.md index ec395d8d..26ee49d8 100644 --- a/__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/README.md +++ b/__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/README.md @@ -4,7 +4,7 @@ Depth 9. M6c Integrity, one level below M6b and above M7, added by amendment A12 as the architecture diet and renamed by amendment A13. The diet's first half (`__roadmap__/diet/`) fixed S1, B1 and three silent acceptances and culled the suite; it landed as PR #57. Those were instances. The rest of M6c removes their causes, as planned in `__reports__/diet/04-architecture_cycle_plan_v2.md`: Candler state with a second producer in tests and fakes (D1), milestones cut by file and gated by counts (D3), an `AGENTS.md` read as a checklist (D4), and inputs with several readers (D5). Its build is the campaign `__roadmap__/integrity/`, on `feat/integrity`. ## Goal -The README's promises of provenance, per-run tool-catalog snapshots, grading "already on disk" and thin surfaces over one API hold by construction: each kind of stored state has one producer, each consumer input has one reader, and an outside consumer's pass on the after tip finds no friction whose cause is D1 to D5. +The README's promises of provenance, per-run tool census, grading "already on disk" and thin surfaces over one API hold by construction: each kind of stored state has one producer, each consumer input has one reader, and an outside consumer's pass on the after tip finds no friction whose cause is D1 to D5. ## Pre-conditions - [x] `../m6b_surface_consolidation.md` is `done` (PR #56) diff --git a/__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/m6c_integrity.md b/__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/m6c_integrity.md index 9dd63441..1016ae35 100644 --- a/__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/m6c_integrity.md +++ b/__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/m6c_integrity.md @@ -10,10 +10,10 @@ - ⬜ Collect has an oracle outside the driver: with B1's fix reverted on a scratch branch, the shared conformance case fails for OpenCode only, naming the files the agent wrote - ⬜ One reader per input: an experiment with a malformed MCP server is refused by `resolve` with the field path, with the same record from the CLI and the op API, where the base ran it with the server silently absent; the diff adds no trait, wrapper type or module between an input and its use - ⬜ The `AGENTS.md` section "Sustainable, scalable, efficient" is replaced by the approved paragraph, and the leaf template carries the conventions of D3 -- ⬜ Both seam reviews ran on the whole diff since the base and their findings are resolved or recorded -- ⬜ The catalog snapshot is stored (option (b)) and `inspect` shows the catalog a sealed run ran with, or the spend checkpoint recorded that P5 waits +- ⬜ The three seam reviews ran, each on its levels' whole diff, and their findings are resolved or recorded +- ⬜ `inspect` shows the census and the resolved `mcp.*` values a sealed run ran with, and no catalog snapshot that Candler did not observe - ⬜ The dogfooding pass ran on the after tip with two RiVault models under OpenCode, every friction is classified by whose failure it is, the golden covers are listed as passed with the corpus set, and latency and USD are reported -- ⬜ Spend is measured from transcripts and stays within the fresh $100, coordinator included, enforced by the checkpoint after seam review 1 and the per-row caps +- ⬜ Spend is measured from transcripts per row and no row passed its cap without stopping; levels 1 and 2, coordinator included, stay within the $127 the maintainer approved, and level 3, its lead included, within $70 **References**: [Cycle plan v2](../../../../../../../../../../../__reports__/diet/04-architecture_cycle_plan_v2.md) — causes, proof, pieces, order and cost; [AGENTS.md](../../../../../../../../../../../AGENTS.md) — where the D4 paragraph lands; [README.md](../../../../../../../../../../../README.md) — the purpose paragraph, the yardstick ## Step 1: Plan the rest of the milestone diff --git a/__roadmap__/integrity/README.md b/__roadmap__/integrity/README.md index 201fe369..59460257 100644 --- a/__roadmap__/integrity/README.md +++ b/__roadmap__/integrity/README.md @@ -1,26 +1,26 @@ # M6c Integrity ## Context -The build of candler-v1's M6c leaf (`__roadmap__/candler-v1/…/m5b/stats/surface/integrity/m6c_integrity.md`), between M6b and M7. It works from [`__reports__/diet/04-architecture_cycle_plan_v2.md`](../../__reports__/diet/04-architecture_cycle_plan_v2.md) and removes the causes behind the diet's defects: Candler state with a second producer in tests and fakes (D1), leaves cut by file and gated by counts (D3), `AGENTS.md` read as a checklist (D4), and inputs with several readers (D5). It is judged against the README purpose paragraph. Depth gives the order: `conventions.md` first; `causes/` runs P1, P2, the P4 chain and P6 in parallel; `causes/checkpoint/` holds seam review 1 and the spend checkpoint that decides P5; `snapshot/` stores the catalog snapshot; `review/` holds seam review 2; `dogfood/` closes with an outside consumer's pass. The integration branch is `feat/integrity`, cut from `origin/main` at or after `70d4c3bf`; each leaf runs in its own worktree made by `scripts/worktree.py add` from the `feat/integrity` tip and removed at merge. Every build shares `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/candler-diet/target`, at most three build at once, and `df -h /System/Volumes/Data` is checked before each level. Docker is used locally only by the dogfooding pass, which removes what it created by name; nothing is pruned and Docker is never stopped. Two pieces of v2 wait outside the caps: P3 (the stand-in that container-e2e uses, held to the daemon by a contract guard) returns by amendment if Eliott makes `Gates` and `container-e2e` required checks on `main`; P4·S (second_sources' `resolve` failure record and the transcript fold) is recorded as open and not done. +The build of candler-v1's M6c leaf (`__roadmap__/candler-v1/…/m5b/stats/surface/integrity/m6c_integrity.md`), between M6b and M7. It works from [`__reports__/diet/04-architecture_cycle_plan_v2.md`](../../__reports__/diet/04-architecture_cycle_plan_v2.md) and removes the causes behind the diet's defects: Candler state with a second producer in tests and fakes (D1), leaves cut by file and gated by counts (D3), `AGENTS.md` read as a checklist (D4), and inputs with several readers (D5). It is judged against the README purpose paragraph. Depth gives the order: `conventions.md` first; `causes/` runs P1, P2, the P4 chain and P6 in parallel; `causes/checkpoint/` holds seam review 1 and the spend checkpoint that decides P5; `snapshot/` stores the catalog snapshot; `review/` holds seam review 2; `dogfood/` closes levels 1 and 2 with an outside consumer's pass; below it, `dogfood/parity/` (level 3, A3) states every per-harness fact in one shape that each driver must answer, installs the same MCP servers on both harnesses and records each MCP call in one trace form, with Claude Code as the reference harness. The integration branch is `feat/integrity`, cut from `origin/main` at or after `70d4c3bf`; each leaf runs in its own worktree made by `scripts/worktree.py add` from the `feat/integrity` tip and removed at merge. Every build sets `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/integrity-target/` and `RUSTC_WRAPPER=sccache` in its own environment, one dir per leaf because `scripts/worktree.py` records that worktrees sharing a target dir link each other's code, with sccache sharing compiled dependencies; at most three builds run at once, each leaf's dir is removed at its merge, and `df -h /System/Volumes/Data` is checked before each level. Docker is used locally only by the dogfooding pass and by level 3's probes and live parity runs, each of which removes what it created by name; nothing is pruned and Docker is never stopped. Two pieces of v2 wait outside the caps: P3 (the stand-in that container-e2e uses, held to the daemon by a contract guard) returns by amendment if Eliott makes `Gates` and `container-e2e` required checks on `main`; P4·S (second_sources' `resolve` failure record and the transcript fold) is recorded as open and not done. ## Goal -Each kind of state Candler stores has one producer, each consumer input has one reader, and an outside consumer's pass on the after tip finds no friction whose cause is D1 to D5. +Each kind of state Candler stores has one producer, each consumer input has one reader, an outside consumer's pass on the after tip finds no friction whose cause is D1 to D5, and every fact about a harness is stated in one shape that each driver must answer, so one cell run on either harness installs the same MCP servers and its trace records each MCP call in the same form. ## Pre-conditions - [x] `[cmd]` `git merge-base --is-ancestor 70d4c3bf origin/main` succeeds (PR #57 landed) - [x] `[nl]` The coordinator accepted plan v2 with its cut order, and Eliott's rulings are applied in it -- [ ] `[cmd]` `git merge-base --is-ancestor 70d4c3bf feat/integrity` succeeds +- [x] `[cmd]` `git merge-base --is-ancestor 70d4c3bf feat/integrity` succeeds ## Success Gates -- ⬜ `conventions.md` and `causes/` are `done` -- ⬜ Every merge into `feat/integrity` waited for a green `container-e2e` on its pull request -- ⬜ Spend is measured from transcripts per row, no row passed its cap without stopping, and the whole milestone, coordinator included, stays within $100 +- ✅ `conventions.md` and `causes/` are `done`, level 3 (`causes/checkpoint/snapshot/review/dogfood/parity/`) included +- ✅ Every merge into `feat/integrity` that touches the paths `container-e2e` watches waited for it to be green on its pull request, and every other merge says it touched none of them (19 PRs merged into `feat/integrity`, #59 to #80: 16 touched the watched paths and each had `Container e2e (Linux)` green on its head before merge; #59, #69 and #70 touched none; the 24 direct rdm/reports pushes touched none; the paths filter did not change during the campaign) +- ✅ Spend is measured from transcripts per row and no row passed its cap without stopping; levels 1 and 2, coordinator included, stay within the $127 the maintainer approved, and level 3, its lead included, within $70 (levels 1 and 2: $90.93 measured from host transcripts since the 02:17:27Z reset, coordinator included (at most about $99 if P7's container runs are added), under $127; level 3: $61.78 measured at its close, same report §Level 3) ## Status ```mermaid graph TD - conventions[Conventions]:::planned - causes[Causes]:::planned + conventions[Conventions]:::done + causes[Causes]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -31,12 +31,17 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `conventions.md` | 📄 Leaf Task | ⬜ Planned | -| `causes/` | 📁 Directory | ⬜ Planned | +| `conventions.md` | 📄 Leaf Task | ✅ Done | +| `causes/` | 📁 Directory | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | |:---|:-----|:-------|:------------|:----------| +| A1 | 2026-11-24 | seam review 1 (F3/F4) | none; one gate added to `dogfooding_pass.md` | OpenCode has no agent-to-sealed-run chain in CI; the pass's real OpenCode run is where its stored outputs are compared with what the agent wrote, before any follow-up builds that chain | +| A2 | 2026-11-24 | maintainer ruling on seam review 1 (R1) | none; fixed under seam review 1 as leaf `exec_bit` | Every stored output keeps its execute bit, whatever produced it, so an evaluation plugin can run an output; the runner records the bit as import does, the 0555 materialise path stays, and the tree digest of a new run with an executable output changes | +| A3 | 2026-11-25 | `__reports__/diet/07-plan_integrity_level3_v0.md` (approved level-3 plan) and `05-findings_dogfooding_pass_v0.md` finding (1) | ["parity/", "declaration.md", "answered/", "mcp_render.md", "census.md", "pages.md", "recorded/", "snapshot_out.md", "parity_run.md", "closing/", "seam_review_three.md"] | The run record named no MCP server under OpenCode and the catalog snapshot came from a constant; level 3 declares the agent's settings once, has every driver answer them, makes the census the one record and proves parity on both harnesses. The goal, the done gate and the spend gate are reworded with it | +| A4 | 2026-11-25 | maintainer rulings on the A3 plan (`07-plan_integrity_level3_v1.md`) | ["trace_parity.md"]; `census.md` blocked | The per-harness lists fold into one shape (`CONFIGURATION_PATHS`'s const rows and `refusal_table!`'s exhaustive match), and a missing answer fails to compile. Which servers the agent called is for the consumer to parse from the trace, so the census keeps `census.tools` only, and `trace_parity.md` aligns both trace readers on one MCP origin instead of collecting server status. `tool-catalog-snapshot/1` stays, because an outside tool writes and reads it, and only Candler's constant producer goes. Hooks and instruction files are non-goals | +| A5 | 2026-11-25 | coordinator's ruling on the P10 stop (OpenCode 2.2.7 offers no tool-list endpoint) | none; gates reworded | P10 wanted OpenCode's census from `GET /experimental/tool`, but the pinned OpenCode 2.2.7 has no such endpoint: its HTTP API is 139 paths under `/api`, none lists tools, and `/experimental/tool` serves the web app's HTML. Its docs expose the tool list only to plugins, as `ctx.tool.list()`. Candler's gateway census for OpenCode stays: its record of the tools in the model request is exactly what the model was offered, which is the input `census.tools` comparability exists for. A plugin injected by Candler was rejected, since it adds a producer, a plugin in every cell and its upkeep, to observe something less directly. The gateway census for both harnesses was rejected too: Claude Code can hold MCP tool schemas back behind tool search, so its first model request may not list them, while its `system/init` does. The two sources measure the same input in the way each harness allows, and Claude Code is not moved onto the gateway without checking deferral at the pinned version. So `CensusSource`, `census.source`, the gateway's `census_init` and the verdict's source reading stay, and `trace_parity.md`'s gate, Goal and Step 2 say that each census names its source | ## Progress | Node | Branch | Commits | Notes | diff --git a/__roadmap__/integrity/causes/README.md b/__roadmap__/integrity/causes/README.md index f26e2d2d..a54cc726 100644 --- a/__roadmap__/integrity/causes/README.md +++ b/__roadmap__/integrity/causes/README.md @@ -7,21 +7,21 @@ Level 1 of M6c Integrity, after `../conventions.md`. Four independent concepts r The causes D1 and D5 are removed where S1, B1 and the silent acceptances came from, each shown by an observation that fails on the base. ## Pre-conditions -- [ ] `[cmd]` `bash ~/.claude/plugins/cache/cracking-shells/managing-roadmaps/1.3.0/skills/managing-roadmaps/scripts/dirtree-rdm.sh status __roadmap__/integrity/conventions.md` prints `done` +- [x] `[cmd]` `bash ~/.claude/plugins/cache/cracking-shells/managing-roadmaps/1.3.0/skills/managing-roadmaps/scripts/dirtree-rdm.sh status __roadmap__/integrity/conventions.md` prints `done` ## Success Gates -- ⬜ `sealed_run_producer.md`, `collect_oracle.md`, `one_reader.md` and `kill_off_tty.md` are `done`, each with its observation seen failing on the base -- ⬜ `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass on the merged level -- ⬜ `checkpoint/` is `done` +- ✅ `sealed_run_producer.md`, `collect_oracle.md`, `one_reader.md` and `kill_off_tty.md` are `done`, each with its observation seen failing on the base +- ✅ `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass on the merged level (the last merge, #80 at `0825782c`: CI run 45504233235, jobs Format, Gates (Lint, Test, Document), green on `dfb9a177`) +- ✅ `checkpoint/` is `done` ## Status ```mermaid graph TD - sealed_run_producer[Sealed run producer]:::planned - collect_oracle[Collect oracle]:::planned - one_reader[One reader]:::planned - kill_off_tty[Kill off a TTY]:::planned - checkpoint[Seam review 1 and checkpoint]:::planned + sealed_run_producer[Sealed run producer]:::done + collect_oracle[Collect oracle]:::done + one_reader[One reader]:::done + kill_off_tty[Kill off a TTY]:::done + checkpoint[Seam review 1 and checkpoint]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -32,11 +32,11 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `sealed_run_producer.md` | 📄 Leaf Task | ⬜ Planned | -| `collect_oracle.md` | 📄 Leaf Task | ⬜ Planned | -| `one_reader.md` | 📄 Leaf Task | ⬜ Planned | -| `kill_off_tty.md` | 📄 Leaf Task | ⬜ Planned | -| `checkpoint/` | 📁 Directory | ⬜ Planned | +| `sealed_run_producer.md` | 📄 Leaf Task | ✅ Done | +| `collect_oracle.md` | 📄 Leaf Task | ✅ Done | +| `one_reader.md` | 📄 Leaf Task | ✅ Done | +| `kill_off_tty.md` | 📄 Leaf Task | ✅ Done | +| `checkpoint/` | 📁 Directory | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/integrity/causes/checkpoint/README.md b/__roadmap__/integrity/causes/checkpoint/README.md index 7d6bb177..633b1f83 100644 --- a/__roadmap__/integrity/causes/checkpoint/README.md +++ b/__roadmap__/integrity/causes/checkpoint/README.md @@ -10,14 +10,14 @@ Level 1's seams are reviewed and P5 is decided from measured spend. - [ ] `[cmd]` `bash ~/.claude/plugins/cache/cracking-shells/managing-roadmaps/1.3.0/skills/managing-roadmaps/scripts/dirtree-rdm.sh ls __roadmap__/integrity/causes/` shows the four level 1 leaves `done` ## Success Gates -- ⬜ `seam_review_one.md` is `done`, with its findings fixed or recorded -- ⬜ `snapshot/` is `done` +- ✅ `seam_review_one.md` is `done`, with its findings fixed or recorded +- ✅ `snapshot/` is `done` ## Status ```mermaid graph TD - seam_review_one[Seam review 1]:::planned - snapshot[Catalog snapshot]:::planned + seam_review_one[Seam review 1]:::done + snapshot[Catalog snapshot]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -28,8 +28,8 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `seam_review_one.md` | 📄 Leaf Task | ⬜ Planned | -| `snapshot/` | 📁 Directory | ⬜ Planned | +| `seam_review_one.md` | 📄 Leaf Task | ✅ Done | +| `snapshot/` | 📁 Directory | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/integrity/causes/checkpoint/seam_review_one.md b/__roadmap__/integrity/causes/checkpoint/seam_review_one.md index a1efbb1a..3b5763f1 100644 --- a/__roadmap__/integrity/causes/checkpoint/seam_review_one.md +++ b/__roadmap__/integrity/causes/checkpoint/seam_review_one.md @@ -1,7 +1,7 @@ # Seam review 1 **Goal**: A reviewer who wrote none of level 1 reads its whole merged diff across the seams, and level 1's measured spend decides whether P5 runs (D3 remedy). -**Estimate**: one fresh Claude reviewer, $4, cap $8, plus the coordinator's spend measurement. +**Estimate**: one fresh Claude reviewer, $4, cap $8, plus the coordinator's spend measurement. Builds use the target dir the campaign README names, removed at the leaf's end. At the cap, stop, commit what is green, and list what is left. **Pre-conditions**: - [ ] `[nl]` Level 1 (`sealed_run_producer`, `collect_oracle`, `one_reader`, `kill_off_tty`) is merged into `feat/integrity` **Success Gates**: diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/README.md b/__roadmap__/integrity/causes/checkpoint/snapshot/README.md index 7bba0b68..f4070d95 100644 --- a/__roadmap__/integrity/causes/checkpoint/snapshot/README.md +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/README.md @@ -10,14 +10,14 @@ A sealed run holds the bytes of the tool catalog it ran with, or the checkpoint' - [ ] `[nl]` `../seam_review_one.md` records the checkpoint's decision on P5 ## Success Gates -- ⬜ `catalog_snapshot.md` is `done`, or `blocked` with the checkpoint's reason -- ⬜ `review/` is `done` +- ✅ `catalog_snapshot.md` is `done`, or `blocked` with the checkpoint's reason +- ✅ `review/` is `done` ## Status ```mermaid graph TD - catalog_snapshot[Catalog snapshot]:::planned - review[Seam review 2]:::planned + catalog_snapshot[Catalog snapshot]:::done + review[Seam review 2]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -28,8 +28,8 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `catalog_snapshot.md` | 📄 Leaf Task | ⬜ Planned | -| `review/` | 📁 Directory | ⬜ Planned | +| `catalog_snapshot.md` | 📄 Leaf Task | ✅ Done | +| `review/` | 📁 Directory | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/catalog_snapshot.md b/__roadmap__/integrity/causes/checkpoint/snapshot/catalog_snapshot.md index 1f2bd813..be1f2744 100644 --- a/__roadmap__/integrity/causes/checkpoint/snapshot/catalog_snapshot.md +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/catalog_snapshot.md @@ -1,7 +1,7 @@ # Catalog snapshot **Goal**: A sealed run stores the canonical bytes of the tool catalog it ran with, so the README's "per-run tool-catalog snapshots" can be read back (P5, option (b), B2). -**Estimate**: Sonnet, $6, cap $12. At the cap, stop, commit what is green, and list what is left. +**Estimate**: Sonnet, $6, cap $12. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, removed at the leaf's merge. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/integrity HEAD` succeeds - [ ] `[nl]` The spend checkpoint in `../seam_review_one.md` ruled that P5 runs @@ -10,7 +10,7 @@ - ⬜ `resolve` stays a pure read: it carries the canonical bytes in the plan it hands on and writes nothing to the store - ⬜ The snapshot is stored by the same sealing step as the outputs, and the guard gets its run from P1's producer - ⬜ No digest or golden vector is edited -- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/candler-diet/target`, and `container-e2e` is green on the pull request +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request **References**: [Cycle plan v2 §B2, §Proof](../../../../../__reports__/diet/04-architecture_cycle_plan_v2.md) — the ruling and the observation; `crates/candler-core/src/resolve/steps/catalog.rs` — `CatalogStep::run` ## Step 1: Guard and store diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/README.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/README.md index a0df7a68..fa321588 100644 --- a/__roadmap__/integrity/causes/checkpoint/snapshot/review/README.md +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/README.md @@ -10,14 +10,14 @@ Nothing merged since seam review 1 reopens a cause, and the snapshot holds at it - [ ] `[nl]` `../catalog_snapshot.md` is `done` or `blocked`, and its merge (if any) is in `feat/integrity` ## Success Gates -- ⬜ `seam_review_two.md` is `done`, with its findings fixed or recorded -- ⬜ `dogfood/` is `done` +- ✅ `seam_review_two.md` is `done`, with its findings fixed or recorded +- ✅ `dogfood/` is `done` ## Status ```mermaid graph TD - seam_review_two[Seam review 2]:::planned - dogfood[Dogfooding pass]:::planned + seam_review_two[Seam review 2]:::done + dogfood[Dogfooding pass]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -28,8 +28,8 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `seam_review_two.md` | 📄 Leaf Task | ⬜ Planned | -| `dogfood/` | 📁 Directory | ⬜ Planned | +| `seam_review_two.md` | 📄 Leaf Task | ✅ Done | +| `dogfood/` | 📁 Directory | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/README.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/README.md index 598572f7..d8b82a69 100644 --- a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/README.md +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/README.md @@ -1,7 +1,7 @@ # Dogfooding pass ## Context -The milestone's last gate, replacing the diet's `close_out`. Two RiVault models from different families, both under OpenCode, use Candler with only what an outside consumer has, and every friction they meet is attributed. The knowledge transfer follows. +The milestone's last gate, replacing the diet's `close_out`. Two RiVault models from different families, both under OpenCode, use Candler with only what an outside consumer has, and every friction they meet is attributed. The knowledge transfer follows. Amendment A3 adds `parity/` below it: the pass's finding (1) is where level 3, harness parity, starts. ## Goal Whose failure each friction is, Candler's or the agent's, is known from the transcripts, and the milestone is recorded. @@ -10,12 +10,14 @@ Whose failure each friction is, Candler's or the agent's, is known from the tran - [ ] `[nl]` `../seam_review_two.md` is `done` ## Success Gates -- ⬜ `dogfooding_pass.md` is `done` +- ✅ `dogfooding_pass.md` is `done` +- ✅ `parity/` is `done` ## Status ```mermaid graph TD - dogfooding_pass[Dogfooding pass]:::planned + dogfooding_pass[Dogfooding pass]:::done + parity[Harness parity]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -26,7 +28,8 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `dogfooding_pass.md` | 📄 Leaf Task | ⬜ Planned | +| `dogfooding_pass.md` | 📄 Leaf Task | ✅ Done | +| `parity/` | 📁 Directory | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/dogfooding_pass.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/dogfooding_pass.md index ba4e49ce..855738c4 100644 --- a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/dogfooding_pass.md +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/dogfooding_pass.md @@ -1,7 +1,7 @@ # Dogfooding pass **Goal**: Two RiVault models, with only what an outside consumer has, use Candler on the after tip for what its README claims, and every friction they meet is attributed to the agent or to Candler; the milestone's knowledge transfer follows (P7). -**Estimate**: RiVault agents and a RiVault first classification, one Claude reader: $7, cap $14. Each model gets one attempt, with a turn cap and a wall-clock cap set from P1's probe times; no rerun unless a fix reopens a piece. +**Estimate**: RiVault agents and a RiVault first classification, one Claude reader: $7, cap $14. Each model gets one attempt, with a turn cap and a wall-clock cap set from P1's probe times; no rerun unless a fix reopens a piece. Builds use the target dir the campaign README names, removed at the leaf's end. At the cap, stop, commit what is green, and list what is left. **Pre-conditions**: - [ ] `[nl]` `../seam_review_two.md` is `done`, and `feat/integrity` is green - [ ] `[cmd]` the RiVault check script of the `using-rivault` skill reports the VPN and keys working @@ -10,6 +10,7 @@ - ⬜ In a toy domain that names nothing of HTN, each agent wrote a two-arm experiment with a few replicates under container isolation and one MCP tool server, ran it with OpenCode on a RiVault model, checked each run's tool-catalog snapshot and provenance, graded the artifacts with an evaluator plug-in fresh and already on disk, then did the experiment, the run and the grading again through the op API - ⬜ Every friction is classified from the kept transcripts by whether what the agent needed was documented and reachable: one model missed it (the agent's), both missed it (Candler's documentation or surface), not documented or not reachable (Candler's; its piece reopens if the cause is D1 to D5), missing (a finding for Eliott) - ⬜ The golden covers ran with `CANDLER_GOLDEN_CORPUS` set, and the nextest output lists them as passed, not skipped +- ⬜ After one real OpenCode run of the pass, its stored outputs are compared with the files the agent wrote in its workspace (minus what the driver's collect rule excludes): this is the producer-side observation for OpenCode that the conformance revert alone does not give (seam review 1, F3/F4) - ⬜ The before tip is used only where it shows a cause gone (the malformed MCP server; the S1 and B1 reverts); the plug-in path layout (`context.root/path` meeting `outputs/outputs/…`) and audit-1 (the cell count in `resolve`) are judged from the transcripts - ⬜ The report gives each step's latency, Candler's own run times, RiVault tokens as tokens and USD measured from transcripts; Docker images, containers and networks the pass created are removed by name **References**: [Cycle plan v2 §The dogfooding pass, §Open items](../../../../../../../__reports__/diet/04-architecture_cycle_plan_v2.md) — the design, the classification table and what it settles; [README.md](../../../../../../../README.md) — the claims the task comes from diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/README.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/README.md new file mode 100644 index 00000000..459df8c8 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/README.md @@ -0,0 +1,48 @@ +# Harness parity + +## Context +Level 3 of M6c, opened by amendment A3 after the dogfooding pass found that a run's record names no MCP server under OpenCode and that the stored catalog always says `servers: []` (`__reports__/diet/05-findings_dogfooding_pass_v0.md`, finding (1)). The plan is `__reports__/diet/07-plan_integrity_level3_v1.md`. Claude Code is the reference harness: OpenCode is aligned to it, and a defect found on the Claude Code side is fixed in both drivers. Depth gives the order: `declaration.md` first; `answered/` renders, traces and documents from the declaration; `answered/recorded/` removes the second catalog producer and proves parity; `closing/` holds seam review 3. + +## Goal +Every fact about a harness is stated in one shape, which each registered driver must answer. One cell run on either harness installs the same MCP servers, and its stored trace records each MCP call in the same normalised form. Non-goals: hooks an experiment can set, and CLAUDE.md/AGENTS.md. + +## Pre-conditions +- [x] `[cmd]` `git merge-base --is-ancestor 27d1d1dd origin/feat/integrity` succeeds (the dogfooding pass is merged) +- [x] `[nl]` Eliott approved revision 2 of the level-3 plan, with its rulings: the README says "per-run tool census"; `codemode` defaults to `false`; one shape for every per-harness list; the census keeps `census.tools` only; code mode is declared, not parsed + +## Success Gates +- ✅ `declaration.md` and `answered/` are `done` +- ✅ The level's spend, measured from transcripts per row, stays within $70, and no row passed its cap without stopping +- ✅ Every leaf report has a "What it leaves" section judging the change at the three levels (how it was developed, what it leaves in the code, how it is consumed), and seam review 3 found no second producer, second reader or passthrough left by the level + +## Status +```mermaid +graph TD + declaration[Settings declaration]:::done + answered[Answered]:::done + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `declaration.md` | 📄 Leaf Task | ✅ Done | +| `answered/` | 📁 Directory | ✅ Done | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| +| `declaration.md` | `leaf/l3-declaration` | merged at `4a0dcada` (#71) | Report `__reports__/diet/leaves/declaration_v0.md`. Implementer, finisher, verifier, fix round and one design round (B2): $7.55 of the $24 cap. Inputs for seam review 3 noted. | +| `answered/mcp_render.md` | `leaf/l3-mcp-render-b` | merged at `29573006` (#74) | Report `__reports__/diet/leaves/mcp_render_v0.md`. Redone on a second branch so the schemas commit stands alone (#73 closed). Implementer and verifier: $3.46 of the $12 cap. | +| `answered/trace_parity.md` | `leaf/l3-trace-parity` | merged at `cca93ab4` (#75) | Report `__reports__/diet/leaves/trace_parity_v0.md`. Census gate reworded by A5. Adds the server-name rule and `fix(schemas)!` `SERVER_NAME_PATTERN`. Implementer, verifier and A5 sweep: $6.77 of the $16 cap. | +| `answered/pages.md` | `leaf/l3-pages` | merged at `7021d1ea` (#78) | Report `__reports__/diet/leaves/pages_v0.md`, with the RiVault trial: five OpenCode runs (`Reasoning-Medium` = DeepSeek-V4-Flash, `Reasoning-Large` = MiMo-V2.6-Pro-RL), two ending on the 32k output limit; a Sonnet review caught six defects, and its re-check one grep-dodging rename. Sonnet review: $0.68 of the $4 cap; RiVault tokens are not billed. | +| `answered/recorded/snapshot_out.md` | `leaf/l3-snapshot-out-2` | merged at `0197fbdb` (#77) | Report `__reports__/diet/leaves/snapshot_out_v0.md`. Redone on a second branch so the schemas commit stands alone (#76 closed). `comparable.snapshots` optional, written only by the importers; the evaluator protocol's `snapshots` stays until a helper that reads it as optional is released (the helper now does). Implementer (three rounds) and verifier: $9.56 of the $16 cap. | +| `answered/recorded/parity_run.md` | `leaf/l3-parity-run` | merged at `92c0f3a3` (#79) | Report `__reports__/diet/leaves/parity_run_v0.md`. Guard `parity_e2e::parity_one_installed_server_one_traced_call` on both real images, the production gateway and the fake model; it adds about 28 s to container-e2e. Live runs on `RiVault/Reasoning-Medium` (DeepSeek-V4-Flash): both traces show `{mcp, parity, stamp}`. The leaf's "no python3 in the OpenCode image" was stale. Implementer and verifier: $3.95 of the $12 cap. | diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/README.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/README.md new file mode 100644 index 00000000..3a89f035 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/README.md @@ -0,0 +1,45 @@ +# Answered + +## Context +The second level of harness parity. It needs `../declaration.md`'s `AgentSetting` and `Answer`. Three leaves run in parallel, each owning its own files: `mcp_render.md` (both drivers' `prepare.rs` MCP renderers, `candler-schemas/src/servers.rs`), `trace_parity.md` (OpenCode's `export.rs`, Claude Code's `parse.rs`, `runner/evidence/census.rs`, the trace schema, the resolve server-name step) and `pages.md` (`crates/candler/tests/it/support/contract_pages/`). `census.md` is blocked: revision 2 of A3 removed its server census, and `trace_parity.md` carries what remains. If `mcp_render.md` and `trace_parity.md` both need the OpenCode driver's `driver.rs`, `trace_parity.md` rebases onto `mcp_render.md`. + +## Goal +Each driver renders what the declaration answers, both trace readers attribute an MCP call the same way, and the pages are generated from the declaration. + +## Pre-conditions +- [x] `[nl]` `../declaration.md` is `done` + +## Success Gates +- ✅ `mcp_render.md`, `trace_parity.md`, `pages.md` and `recorded/` are `done`, and `census.md` stays `blocked` + +## Status +```mermaid +graph TD + mcp_render[MCP render]:::done + census[Census]:::blocked + pages[Generated pages]:::done + recorded[Recorded]:::done + trace_parity[Trace parity]:::done + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `mcp_render.md` | 📄 Leaf Task | ✅ Done | +| `census.md` | 📄 Leaf Task | 🚫 Blocked | +| `pages.md` | 📄 Leaf Task | ✅ Done | +| `recorded/` | 📁 Directory | ✅ Done | +| `trace_parity.md` | 📄 Leaf Task | ✅ Done | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/census.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/census.md new file mode 100644 index 00000000..5653ff29 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/census.md @@ -0,0 +1,40 @@ +# Census + +**Goal**: Blocked by revision 2 of A3: Eliott ruled that the census names no server, and that which servers the agent called is for the consumer to parse from the trace; `trace_parity.md` carries what remains. As first planned: the census records, on both harnesses, each MCP server the agent had with its status and its tools, from what the harness itself reports (P10). +**Estimate**: Sonnet, $12, cap $24; the lead takes the probe fork of Step 1. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, removed at the leaf's merge. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor origin/feat/integrity HEAD` succeeds +- [ ] `[nl]` `../declaration.md` is `done` +**Success Gates**: +- ⬜ The census of an OpenCode run whose cell declares one server records `mcp_servers: [{name, status, tools}]` naming that server and its tools; on the base the gateway census has no servers +- ⬜ The census of a Claude Code run records the same shape from `system/init`, so the two harnesses' records of one cell compare field by field +- ⬜ Under OpenCode code mode the record names the server and its tools from the source Step 1 chose, and says which source that was +- ⬜ Resolving refuses two servers whose names collide once normalised to the gateway's tool-name alphabet +- ⬜ The census evidence schema is regenerated, and the conformance suite checks the shape for every driver with a census +- ⬜ The report's "What it leaves" section judges the change at the three levels +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request +**References**: [Level-3 plan §Design](../../../../../../../../../__reports__/diet/07-plan_integrity_level3_v0.md) — one record; `crates/candler-core/src/runner/evidence/census.rs` — `census`; `crates/candler-core/src/runner/gateway.rs` — `census_init`; `crates/candler-harness/src/spec.rs` — `CensusSource`, `InitReport`; `crates/candler-harness-claude-code/src/parse.rs` — `init_report` + +## Step 1: Guard and probe the code-mode source +**Goal**: The census guard fails on the base, and the source of tool names under code mode is chosen by observation. +**Implementation Logic**: +Write the guard on a run from the campaign's sealed-run producer with one declared server, and see it fail on the base. Then probe, in the OpenCode base image with a container named for this leaf and removed by name, what lists the tools of an MCP server during a session under code mode: first a session API of the run's own OpenCode child; then the description of the `execute` tool the gateway sees; then an MCP `tools/list` that Candler runs inside the isolation. The first that works is the source; record each one tried and what it returned. Names and status come from `mcp.list` against the run's OpenCode child (`CensusSource::Collected`); outside code mode, tools are the gateway's `_` names matched against the configured names. If none of the three works under code mode, stop and send the lead the record: the gate's wording is then the lead's call with the coordinator, not the implementer's. +**Deliverables**: the census guard in `crates/candler-core/tests/it/`; the probe's record in the report +**Consistency Checks**: the census guard on the base (expected: FAIL) +**Commit**: `test(runner): require the census to name the agent's MCP servers` + +## Step 2: Record servers on both harnesses +**Goal**: One census shape, filled by each driver's own source. +**Implementation Logic**: +Give `InitReport` the servers with status and tools; Claude Code fills them from `system/init` and its `mcp____` names, OpenCode from the sources Step 1 chose. Replace the `None` that `census_init` passes. Add the collision refusal at resolve, beside the server-name check that exists. The census stays one producer: no step copies it into a second record. +**Deliverables**: `crates/candler-harness/src/spec.rs`; `crates/candler-core/src/runner/{gateway.rs,evidence/census.rs}`; `crates/candler-harness-claude-code/src/parse.rs`; the census path of `crates/candler-harness-opencode/src/driver.rs`; the regenerated census schema +**Consistency Checks**: the census guard on the tip (expected: PASS) +**Commit**: `feat(runner): record the MCP servers and tools of every census` + +## Step 3: Bite and verify +**Goal**: The guard catches a census without servers. +**Implementation Logic**: +On a scratch branch, put `None` back in `census_init` and see the guard fail. A fresh Sonnet verifier gets this leaf, the report and the diff, with the brief: find a run on either harness whose agent had a server that its census does not name. +**Deliverables**: `__reports__/diet/leaves/census_v0.md` +**Consistency Checks**: the scratch edit makes the census guard fail (expected: FAIL) +**Commit**: `reports(api): close the census` diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/mcp_render.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/mcp_render.md new file mode 100644 index 00000000..34fb1697 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/mcp_render.md @@ -0,0 +1,42 @@ +# MCP render + +**Goal**: Each driver writes its harness's own MCP configuration from the typed `McpServer`: on Claude Code `local` becomes `stdio` and `remote` becomes `http`, and nothing passes through serde. `codemode` defaults to `false` and is written into the resolved cell. Claude Code refuses `codemode = true`, giving its reason (P9). +**Estimate**: Sonnet, $6, cap $12. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, removed at the leaf's merge. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor origin/feat/integrity HEAD` succeeds +- [ ] `[nl]` `../declaration.md` is `done` +- [x] `[nl]` The coordinator ruled on the digest change: filling the `codemode` default at resolve changes the cell digest of every cell that declares a server without it. Accepted: the resolved cell records what Candler installs +**Success Gates**: +- ⬜ The `.mcp.json` Claude Code gets for a server with `type = "local"`, `codemode` and `name` carries `type: "stdio"`, the name as its key, and no `codemode` or `name` key; on the base it carries all three as given +- ⬜ A Claude Code cell that sets `codemode = true` is refused through its `Codemode(true)` arm, with the reason "Claude Code offers MCP tools directly; it has no code mode". A cell that leaves it unset or sets `false` runs +- ⬜ A `remote` server reaches Claude Code as `type: "http"` with `url` and `headers`, as the Claude Code MCP documentation says (cited in the report). A field Claude Code has no place for is refused at check time, not dropped +- ⬜ OpenCode's `opencode.json` for a server with no `codemode` carries `codemode: false`; on the base it carries `true` +- ⬜ The resolved cell holds the filled default, so two cells that differ only by an explicit `codemode = false` have the same cell digest +- ⬜ A conformance check holds each driver's rendered MCP file to the keys its harness documents (cited from the harness's documentation), and fails on a passthrough key +- ⬜ The report's "What it leaves" section judges the change at the three levels +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request +**References**: [Level-3 plan §Design](../../../../../../../../../__reports__/diet/07-plan_integrity_level3_v1.md) — rendering from types, Eliott's `codemode` ruling; `crates/candler-harness-claude-code/src/prepare.rs` — `render_mcp`; `crates/candler-harness-opencode/src/prepare.rs` — `server`; `crates/candler-schemas/src/servers.rs` — `McpServer`, `McpServerKind` + +## Step 1: Guard and probe +**Goal**: The rendering guards fail on the base. +**Implementation Logic**: +Write the guards on the rendered files, going through the drivers' `prepare` path from a cell that Candler resolved, and see them fail on the base. Read each harness's MCP configuration documentation through Context7 and cite it; do not rely on memory. Instruction files and hooks are out of scope for level 3. Probe neither, and run no `opencode debug config`: the configured side is already single-sourced by the resolved cell. +**Deliverables**: the guards in `crates/candler-harness-claude-code/tests/` and `crates/candler-harness-opencode/tests/`; the cited documentation in the report +**Consistency Checks**: the rendering guards on the base (expected: FAIL) +**Commit**: `test(library): hold each driver's MCP file to its harness's keys` + +## Step 2: Render from types +**Goal**: No field of `McpServer` reaches a harness without its driver writing it. +**Implementation Logic**: +Replace `serde_json::to_value(servers)` in Claude Code's `render_mcp` with a writer that builds Claude Code's own shape: `local` written as `stdio` with `command`/`args`/`env`, `remote` as `http` with `url`/`headers`, and `name` as the key. Change the schema's `codemode` default to `false`, fill it when the cell is resolved so the resolved value carries it, and remove `unwrap_or(true)` from OpenCode's `server`. Answer `Codemode` in the declaration. Claude Code maps `false` and refuses `true`. OpenCode maps both, and its `Codemode(true)` construct says that its trace then records `execute` calls with empty `wrapped_calls`, so MCP calls made inside `execute` are not attributed and do not compare with Claude Code. Regenerate the published schema. Fix in both drivers what the Claude Code side showed: neither writes a key its harness does not document. +**Deliverables**: `crates/candler-harness-claude-code/src/prepare.rs`; `crates/candler-harness-opencode/src/prepare.rs`; `crates/candler-schemas/src/servers.rs` and its generated schema; the resolve step that fills the default +**Consistency Checks**: the rendering guards on the tip (expected: PASS) +**Commit**: `fix(library): render MCP servers from their type in both drivers` + +## Step 3: Bite and verify +**Goal**: The guards catch a passthrough and a lost default. +**Implementation Logic**: +On a scratch branch, put `serde_json::to_value` back in Claude Code's renderer, then `unwrap_or(true)` back in OpenCode's, and see each guard fail. A fresh Sonnet verifier gets this leaf, the report and the diff, with the brief: find a field of `McpServer` that reaches either harness without its driver writing it. +**Deliverables**: `__reports__/diet/leaves/mcp_render_v0.md` +**Consistency Checks**: each scratch edit makes its guard fail (expected: FAIL) +**Commit**: `reports(api): close the MCP render` diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/pages.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/pages.md new file mode 100644 index 00000000..ee950b47 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/pages.md @@ -0,0 +1,40 @@ +# Generated pages + +**Goal**: The capability page and the configuration contract page are walks over `AgentSetting::ALL`, `DriverFact::ALL`, `CONFIGURATION_PATHS` and the registered drivers, so an experimenter reads per harness what happens to each setting and fact (P11). +**Estimate**: RiVault, Reasoning-Medium first, then Reasoning-Large, then Sonnet if both fail; the Sonnet review is mandatory, $2, cap $4. Check that thinking ran on each RiVault model before trusting its output. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, removed at the leaf's merge. +**Pre-conditions**: +- [x] `[cmd]` `git -C merge-base --is-ancestor origin/feat/integrity HEAD` succeeds +- [x] `[nl]` `../declaration.md` is `done` +**Success Gates**: +- ⬜ The capability page's rows come from `AgentSetting::ALL` and `DriverFact::ALL` for each registered driver. `ROWS`, the `Mapping` fn pointers and `cap()`'s string match on `budget.per_run.turns` are gone. The rows built from typed specs (stop signal, gateway route, trace) read `fact` and the driver's specs, and nothing else +- ⬜ Changing one driver's answer without regenerating fails the page test; on the base, changing OpenCode's cost-cap row leaves the page test passing as long as the hand-written row still finds a refused row +- ⬜ The configuration contract page shows, for each path whose `reach` is `Agent(..)`, each driver's answer, and marks `CandlerOnly` paths as such +- ⬜ OpenCode's `Codemode(true)` answer, which says its trace does not attribute MCP calls inside `execute`, is on the page beside the setting +- ⬜ The Sonnet review's report says the pages add no second statement of an answer, and checks the principle as well as correctness +- ⬜ The report's "What it leaves" section judges the change at the three levels +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names +**References**: [Level-3 plan §Leaves](../../../../../../../../../__reports__/diet/07-plan_integrity_level3_v1.md), the pages row. Code: `crates/candler/tests/it/support/contract_pages/capabilities.rs` (`ROWS`, `cap`); `crates/candler/tests/it/support/contract_pages/config_pages.rs` (`paths_fields`), the configuration page that reads `CONFIGURATION_PATHS` + +## Step 1: Guard on the base +**Goal**: The page test fails when an answer changes and the page does not. +**Implementation Logic**: +Write the page test so that it compares the generated page with the committed one and names the row that differs. On the base, change OpenCode's cost-cap row's detail and see that the hand-written capability row does not notice; record it. +**Deliverables**: the page test in `crates/candler/tests/it/` +**Consistency Checks**: the page test after the scratch answer change on the base (expected: PASS) +**Commit**: `test(api): hold the capability page to the drivers' answers` + +## Step 2: Generate from the declaration +**Goal**: One source for every setting row. +**Implementation Logic**: +Replace `ROWS` with walks over `AgentSetting::ALL` and `DriverFact::ALL` for each registered driver, written from `Answer`. Add the answers to the configuration page through `PathRow.reach`. Write no new page, and nothing that restates an answer. Regenerate the committed pages. +**Deliverables**: `crates/candler/tests/it/support/contract_pages/{capabilities.rs,…}`; the regenerated pages under `docs/` +**Consistency Checks**: the page test on the tip, after the same scratch answer change (expected: FAIL) +**Commit**: `docs(api): generate the capability and configuration pages from the declaration` + +## Step 3: Review +**Goal**: A Sonnet reviewer accepts the RiVault output. +**Implementation Logic**: +A fresh Sonnet reviewer gets this leaf, the diff and the regenerated pages, with the brief: find a statement of a driver's answer that the pages make without reading it from the declaration, and say whether the leaf left anything a reader of the pages would have to reconcile by hand. +**Deliverables**: `__reports__/diet/leaves/pages_v0.md` +**Consistency Checks**: the page test on the tip, unchanged (expected: PASS) +**Commit**: `reports(api): close the generated pages` diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/README.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/README.md new file mode 100644 index 00000000..e5dfa4a4 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/README.md @@ -0,0 +1,41 @@ +# Recorded + +## Context +The third level of harness parity. It needs the census reduced to tools by `../trace_parity.md` and the typed rendering of `../mcp_render.md`. `snapshot_out.md` removes the constant catalog producer and makes the census the one record; `parity_run.md` runs one cell on both harnesses with a real MCP server. They own disjoint files: `snapshot_out.md` the catalog step, the evidence provider, `comparable`, `inspect`, the oracle vectors, the fake docker, README and `AGENTS.md`; `parity_run.md` a new container-e2e guard and its fixture. + +## Goal +The census is the only record of the tools a run had, and a parity guard holds both harnesses to it. + +## Pre-conditions +- [x] `[nl]` `../mcp_render.md` and `../trace_parity.md` are `done` (`../census.md` stays `blocked`) + +## Success Gates +- ✅ `snapshot_out.md`, `parity_run.md` and `closing/` are `done` + +## Status +```mermaid +graph TD + snapshot_out[Snapshot out]:::done + parity_run[Parity run]:::done + closing[Closing]:::done + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `snapshot_out.md` | 📄 Leaf Task | ✅ Done | +| `parity_run.md` | 📄 Leaf Task | ✅ Done | +| `closing/` | 📁 Directory | ✅ Done | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/closing/README.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/closing/README.md new file mode 100644 index 00000000..3d5c8cbb --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/closing/README.md @@ -0,0 +1,38 @@ +# Closing + +## Context +Closes level 3: one review across its PRs, then the knowledge-transfer report records the level. + +## Goal +What the level left behind is known from a review across its leaves, and the level is recorded. + +## Pre-conditions +- [x] `[nl]` `../snapshot_out.md` and `../parity_run.md` are `done` + +## Success Gates +- ✅ `seam_review_three.md` is `done` + +## Status +```mermaid +graph TD + seam_review_three[Seam review 3]:::done + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `seam_review_three.md` | 📄 Leaf Task | ✅ Done | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| +| `seam_review_three.md` | `leaf/l3-seam-fix` | review `70ed0ce5`; fixes merged at `0825782c` (#80) | Report `__reports__/diet/leaves/seam_review_three_v0.md`: no blocking finding. F3 (two `mcp_servers` passthroughs) and F4 (a second reader of effort and mode text, which fell back silently on replay) broke the level's own gate and are fixed in #80, F4 by the coordinator's ruling. F1, F2 and F5–F7 are under Next in the knowledge-transfer report. Review $1.22 of the $6 cap. | diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/closing/seam_review_three.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/closing/seam_review_three.md new file mode 100644 index 00000000..5e6189b1 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/closing/seam_review_three.md @@ -0,0 +1,29 @@ +# Seam review 3 + +**Goal**: One review across the level's pull requests finds what no leaf verifier was placed to see, starting with what the level left behind, and the knowledge-transfer report records the level. +**Estimate**: Sonnet, $3, cap $6. At the cap, stop and list what is left. +**Pre-conditions**: +- [x] `[nl]` `../snapshot_out.md` and `../parity_run.md` are `done` +**Success Gates**: +- ⬜ The review answers three questions first: did any leaf add where it should have replaced (a second producer, a second reader, a passthrough, a shim with no reader); does every setting that reaches the agent have one answer per driver and one statement on the pages; does one cell on both harnesses install the same servers and trace each MCP call in the same form +- ⬜ The review judges two silent `other` readings that P10 left: an ingested OpenCode export has no cell, so its MCP calls read `origin: other`, and a server the cell does not declare reads `other` on OpenCode but `mcp` on Claude Code. It says whether the trace reader or the page tells the reader when this happens, since a trace that reads `other` without saying why is the kind of silent gap the level closes +- ⬜ Each finding names its cause, the leaves it crosses, and why no leaf verifier would have seen it +- ⬜ The level's spend is measured from transcripts per row against the plan's estimates and caps +- ⬜ `__reports__/diet/06-knowledge_transfer_integrity_v0.md` gains a level-3 section, or a v1 supersedes it, with the findings, the spend and what comes next +**References**: [Level-3 plan](../../../../../../../../../../../__reports__/diet/07-plan_integrity_level3_v1.md); the leaf reports `__reports__/diet/leaves/{declaration,mcp_render,trace_parity,pages,snapshot_out,parity_run}_v0.md` + +## Step 1: Review across the level +**Goal**: The seams of level 3 are reviewed. +**Implementation Logic**: +A fresh Sonnet reviewer gets the level's merged diff on `feat/integrity`, the leaf reports and this leaf, with the three questions first. It reads code through colgrep only. Blocking findings go to the lead before any fix; non-blocking ones are recorded. +**Deliverables**: `__reports__/diet/leaves/seam_review_three_v0.md` +**Consistency Checks**: `git -C log --oneline origin/feat/integrity -1` names the last level-3 merge (expected: PASS) +**Commit**: `reports(api): record seam review 3` + +## Step 2: Record the level +**Goal**: The next milestone inherits level 3. +**Implementation Logic**: +Add to the knowledge-transfer report what removing the second catalog producer, folding the per-harness lists into one shape and aligning the trace looked like, what the review caught, the spend per row, and the follow-ups in order. +**Deliverables**: `__reports__/diet/06-knowledge_transfer_integrity_v0.md` or its v1 +**Consistency Checks**: the report's spend table has one row per level-3 leaf (expected: PASS) +**Commit**: `reports(api): close M6c level 3` diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/parity_run.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/parity_run.md new file mode 100644 index 00000000..da8d4954 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/parity_run.md @@ -0,0 +1,51 @@ +# Parity run + +**Goal**: One cell with a real MCP server, run on Claude Code and on OpenCode with code mode off, shows two things on each harness: (a) the server is installed, and (b) the stored trace records the agent's call to the server's tool in the same normalised form. A container-e2e guard fails when either harness falls out of parity (P13). +**Estimate**: Sonnet, $6, cap $12. The two live runs go to RiVault. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, which is removed when the leaf merges. +**Pre-conditions**: +- [x] `[cmd]` `git -C merge-base --is-ancestor origin/feat/integrity HEAD` succeeds +- [x] `[nl]` `../mcp_render.md` and `../trace_parity.md` are `done` +**Success Gates**: +- ⬜ The parity guard runs in the `container-e2e` group with the real harness images, the production gateway and the scripted fake model. It passes only when, for each harness: + - the fixture server is in the run's resolved `mcp.*` values and in the MCP file its driver rendered; + - the stored trace holds the scripted call as `ToolOrigin::Mcp` with the same server and tool on both harnesses. + + On the base it fails on OpenCode (`origin: other`) +- ⬜ The guard asserts no census of servers and reads no server status +- ⬜ The guard runs the same experiment file on both harnesses, and the harness is the only thing that differs between the runs. Code mode stays at its default `false`, and the guard has no code-mode case +- ⬜ The fixture server is a stdio MCP server that needs nothing outside the agent base images (the OpenCode image has no python3) +- ⬜ One live run per harness through RiVault, of the same experiment shape, shows the agent calling the server's tool, and its stored trace attributes the call to the server. The runs, their store and their containers are removed by name after the record is taken +- ⬜ The container-e2e workflow's added time is measured and stated in the report +- ⬜ The report's "What it leaves" section judges the change at the three levels +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request +**References**: [Level-3 plan §Leaves](../../../../../../../../../../__reports__/diet/07-plan_integrity_level3_v1.md), the parity row. Code: +- `crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs`: real Claude Code behind the gateway, with `assets/docker/fakemodel`; +- `.github/workflows/container-e2e.yml`. + +## Step 1: Guard on the base +**Goal**: The parity guard fails on the base, for OpenCode's unattributed call. +**Implementation Logic**: +Write the fixture server and the guard, following how `controls_e2e` builds its world and leaves no container behind. Script the fake model to call the fixture's tool once on each harness. Run it on the base and record the OpenCode failure. +**Deliverables**: `crates/candler-core/tests/it/guard_container_e2e/parity_e2e.rs`; the fixture server, under `assets/` or the test's fixtures; the fake model's script +**Consistency Checks**: the parity guard on the base (expected: FAIL) +**Commit**: `test(runner): hold both harnesses to one installed server and one traced call` + +## Step 2: Pass on the tip and prove live +**Goal**: The guard passes on the tip, and a live run shows the same. +**Implementation Logic**: +Run the guard on the tip. Then run the same experiment shape once per harness against RiVault, and record each resolved `mcp.*` value and the call from each stored trace. These runs prove the design, so the report compares their shape with the guard's, not their numbers. Each live run must be one the work needs: no reruns for numbers. +**Deliverables**: the report's live-run record +**Consistency Checks**: the parity guard on the tip (expected: PASS) +**Commit**: `reports(api): record the live parity runs` + +## Step 3: Bite and verify +**Goal**: The guard catches one harness falling out of parity. +**Implementation Logic**: +On a scratch branch, make two edits and see the guard fail on each: +- make OpenCode's reader drop the server from the origin; +- make Claude Code's renderer skip the server. + +A fresh Sonnet verifier gets this leaf, the report and the diff. Its brief is to find a way for the two harnesses to install or trace one cell's server differently while the guard still passes. +**Deliverables**: `__reports__/diet/leaves/parity_run_v0.md` +**Consistency Checks**: each scratch edit makes the parity guard fail (expected: FAIL) +**Commit**: `reports(api): close the parity run` diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/snapshot_out.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/snapshot_out.md new file mode 100644 index 00000000..a9439b7e --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/recorded/snapshot_out.md @@ -0,0 +1,58 @@ +# Snapshot out + +**Goal**: Candler's constant catalog producer, its resolve step and the level-2 consumer surface are gone. `inspect` and the op API show the MCP configuration Candler installed, read from the resolved `mcp.*` values the cell digest already hashes. The `tool-catalog-snapshot/1` schema leaves Candler too, since Candler neither writes nor reads it (P12). +**Estimate**: Sonnet, $8, cap $16. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, which is removed when the leaf merges. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor origin/feat/integrity HEAD` succeeds +- [ ] `[nl]` `../trace_parity.md` is `done` +- [x] `[nl]` The coordinator ruled on the comparable change. `comparable.snapshots` leaves the cell digest under a new digest version, old manifests stay readable, new oracle vectors are added beside the old ones, and `InspectRun.catalog` leaves `inspect-run.schema.json`. Accepted, on the condition in the `inspect` callers gate below +**Success Gates**: +- ⬜ A guard on a real `candler run` path, with one declared server, reads the run back through `inspect` (as JSON and as text) and finds the server among the shown `mcp.*` values. On the base, `inspect` of the same run shows only a catalog that says `servers: []` +- ⬜ `CATALOG_PROGRAM`, `CatalogCommand`, `CommandCatalogProvider`, `CatalogStep` and the fake docker's catalog constant are gone. The provider seam behind them is gone too if colgrep finds no other implementor. Nothing in the tree prints a catalog it did not observe +- ⬜ `comparable` carries no catalog snapshot. The new digest version's oracle vectors are added, and the old ones still verify old manifests. The old vectors stay because the maintainer's own stores (golden and HTN runs) hold manifests of the old version, and the vector files say so in a comment, so nobody later prunes them as dead +- ⬜ Before `InspectRun.catalog` is dropped, the report records that nothing in htn-creator-eval@0.5.3 reads `inspect`'s `catalog` field (its Tier D reads its own `/1` file; the check is for `inspect` callers). If something reads it, the drop waits and the lead takes it to the coordinator +- ⬜ `InspectRun.catalog` and `inspect.rs`'s `catalog_of` are gone. A sealed run from before the change still reads through `inspect`. Its stored blob stays in the store and is not shown, with no shim +- ⬜ `tool-catalog-snapshot/1` is gone from Candler: its types in `candler-schemas/src/catalog.rs`, its generated `catalog-snapshot.schema.json`, its fixture tests and any vectors only it uses. The HTN consumer is its only producer and reader. htn-creator-eval@0.5.3 keeps grading, because Tier D checks only the schema marker of its own committed file. Its one test that validates against Candler's schema file then skips, so the report says so, and the lead hands the coordinator an HTN-side follow-up that takes the schema file into that repository. Candler keeps no frozen copy +- ⬜ The README purpose paragraph says "per-run tool census" in place of "per-run tool-catalog snapshots". In the same commit, `AGENTS.md`'s "What sane work means in Candler" names the census, not a catalog snapshot, among the stored states, and the live candler-v1 M6c Goal, which quotes the old promise (`__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/README.md`, line 7), is reworded the same way. The done leaves that quote the old phrase as history keep their words: wire-schemas, `catalog_snapshot.md`, `dogfooding_pass.md` and `diet/shed/e2e_audit.md` +- ⬜ Refusal codes that only the removed code emitted leave `codes.toml` and the refusal tables, and the contract pages are regenerated +- ⬜ The report's "What it leaves" section judges the change at the three levels +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request +**References**: [Level-3 plan §Design](../../../../../../../../../../__reports__/diet/07-plan_integrity_level3_v1.md), on the snapshot surface out. [Dogfooding findings, finding (1)](../../../../../../../../../../__reports__/diet/05-findings_dogfooding_pass_v0.md), on the cause chain. Code: +- `crates/candler/src/commands/preflight.rs`: `CATALOG_PROGRAM`; +- `crates/candler-core/src/runner/evidence/catalog.rs`: `CommandCatalogProvider`; +- `crates/candler-core/src/resolve/steps/catalog.rs`: `CatalogStep`; +- `crates/candler/src/commands/inspect.rs`: `catalog_of`, `render_run`, `text_of_run`; +- `crates/candler/tests/it/support/cli_run.rs`: the fake docker; +- `crates/candler/tests/it/guard_catalog_snapshot.rs`; +- `crates/candler-schemas/src/execution.rs`: `Comparable`; +- `crates/candler-schemas/src/catalog.rs` and `crates/candler-schemas/schema/catalog-snapshot.schema.json`: `/1`. + +## Step 1: Guard on the base +**Goal**: The `inspect` guard fails on the base, where the shown record of a declared server is a constant. +**Implementation Logic**: +Write the guard on a run from the campaign's sealed-run producer. It enters through `candler run`, declares one server, and reads the run back through `inspect`. See it fail on the base, where `inspect` shows `servers: []`. The guard takes the place of `guard_catalog_snapshot.rs`, which agreed with the code on the wrong value. +**Deliverables**: the guard in `crates/candler/tests/it/` +**Consistency Checks**: the guard on the base (expected: FAIL) +**Commit**: `test(api): read a run's installed MCP config back through inspect` + +## Step 2: Remove the second producer and its consumer +**Goal**: The run record states only what Candler installed, and states it once. +**Implementation Logic**: +- Delete the constant program, its capture, the resolve-time catalog step and the fake docker's constant. Delete the level-2 surface that showed their output. Keep none of them "for compatibility" without a reader. +- Drop the snapshot from `comparable` under a new digest version, add its vectors, and keep reading old manifests. +- `inspect` and the op API show the resolved `mcp.*` values from `comparable`. +- Reword the README phrase and the `AGENTS.md` paragraph together, as Eliott ruled, along with every current page under `docs/` that quotes the phrase and the live candler-v1 M6c Goal. Historical reports and done leaves keep their words. +- Remove `/1`: its types, its generated schema, its fixtures and any vectors only it uses. Comment the old cell-digest vectors with why they stay. +- Before dropping `InspectRun.catalog`, check htn-creator-eval@0.5.3 for `inspect` callers that read `catalog`, and record the result. If one does, stop and tell the lead. +- Remove the refusal codes that only the deleted code emitted. Regenerate the schemas and contract pages. +**Deliverables**: the files named in References; `README.md`; `AGENTS.md`; `__roadmap__/candler-v1/contracts/parity/alignment/surfaces/isolation/m5b/stats/surface/integrity/README.md`; `docs/contract/codes.toml`; the oracle vectors; the regenerated schemas and pages +**Consistency Checks**: the guard on the tip (expected: PASS) +**Commit**: `refactor(runner): remove the constant catalog producer and show the installed MCP config` + +## Step 3: Bite and verify +**Goal**: The guard catches a record that no longer shows the server. +**Implementation Logic**: +On a scratch branch, drop the `mcp.*` values from what `inspect` shows, and see the guard fail. A fresh Sonnet verifier gets this leaf, the report and the diff. Its brief is to find any code that still states a run's tools or servers other than the resolved config, the census's tool list and the trace, and any old run that no longer reads. +**Deliverables**: `__reports__/diet/leaves/snapshot_out_v0.md` +**Consistency Checks**: the scratch edit makes the guard fail (expected: FAIL) +**Commit**: `reports(api): close the snapshot removal` diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/trace_parity.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/trace_parity.md new file mode 100644 index 00000000..9888fe85 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/answered/trace_parity.md @@ -0,0 +1,59 @@ +# Trace parity + +**Goal**: An MCP call made by the agent reads the same way in the normalised trace of either harness: as `ToolOrigin::Mcp { server }`, with the server's own tool name. The census keeps `census.tools` as the comparability verdict's input, names no server, and each census names its source: Claude Code's `system/init`, and for OpenCode the tools its model was offered at the gateway. `CensusSource` and `census.source` stay and say which (P10). +**Estimate**: Sonnet, $8, cap $16. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, which is removed when the leaf merges. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor origin/feat/integrity HEAD` succeeds +- [ ] `[nl]` `../declaration.md` is `done` +- [x] `[nl]` The coordinator ruled on the optional `tool` field of `ToolOrigin::Mcp`. It is a change to `normalised-trace/1`, and `ToolOrigin` has `deny_unknown_fields`. Accepted: `tool` holds the bare tool name, so a consumer compares one spelling across both harnesses, and it is optional so that traces stored before the change still read +**Success Gates**: +- ⬜ The OpenCode export of a call to `s_t`, in a cell that declares server `s`, reads `origin: {mcp: {server: "s", tool: "t"}}`. On the base it reads `origin: other` +- ⬜ The Claude Code trace of a call to `mcp__s__t` reads the same origin, so the two harnesses' traces of one call compare field by field +- ⬜ `tool` is optional on `ToolOrigin::Mcp`. One test parses a trace stored before the change, with no `tool` field, and it still reads +- ⬜ The stored Claude Code trace still holds the raw `system/init` line, so a consumer can recover server status by post-processing the trace, as it does for calls. If the stored trace drops that line, the status is lost for good: the lead takes this to the coordinator before the leaf lands +- ⬜ The OpenCode reader takes the server names from the cell's resolved `mcp.*` values and never guesses a server from the spelling of a name +- ⬜ Resolving refuses a set of servers whose OpenCode tool prefixes are ambiguous (for example `a` and `a_b`), beside the existing server-name check, with a code in `codes.toml` +- ⬜ Under OpenCode code mode the trace records `execute` calls with empty `wrapped_calls`. That is what OpenCode's `Codemode(true)` answer declares, and nothing parses `execute` +- ⬜ `census.mcp_servers`, and Claude Code's reading of server status from `system/init`, are gone. `census.tools` and `census.init_tools` stay, and `manifest/compare.rs`'s verdict still reads `init_tools`. `SERVER_START_WAIT`'s doc no longer says that the census records servers +- ⬜ Each census names its source: Claude Code's is its `system/init`; OpenCode's is the tools its model was offered at the gateway. `CensusSource` and `census.source` stay and say which, the gateway's `census_init` stays, and the verdict's source reading stays +- ⬜ The trace and census schemas are regenerated, and the conformance suite checks the MCP origin for every driver +- ⬜ The report's "What it leaves" section judges the change at the three levels +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request +**References**: [Level-3 plan §Design](../../../../../../../../../__reports__/diet/07-plan_integrity_level3_v1.md), on one trace form for an MCP call and the reduced census. Code: +- `crates/candler-schemas/src/trace.rs`: `ToolOrigin`, `WrappedCall`; +- `crates/candler-harness-opencode/src/export.rs`: `tool_drafts`; +- `crates/candler-harness-claude-code/src/parse.rs`: `tool_call`, `origin_of`, `init_report`; +- `crates/candler-core/src/runner/evidence/census.rs`: `census`, `source_label`; +- `crates/candler-core/src/isolation/gateway.rs`: `census_init`; +- `crates/candler-core/src/manifest/compare.rs`: `class_verdict`; +- `crates/candler-core/src/jobs/orchestrate/servers.rs`: `SERVER_START_WAIT`. + +## Step 1: Guard on the base +**Goal**: The origin guard fails on the base for OpenCode. +**Implementation Logic**: +Write the guard as one table over both readers' fixtures. For each harness it takes the recorded output of one call to the same tool of the same declared server, and expects one origin. Extend the OpenCode export fixture with that call if it has none. Run it on the base and record the OpenCode `origin: other`. No live run is needed: the readers are pure. Check also that the stored Claude Code trace keeps the raw `system/init` line, and that the gateway's census of an OpenCode run lists the declared server's tools. If either fails, stop and tell the lead. +**Deliverables**: the guard in `crates/candler/tests/it/` (it sees both drivers); the OpenCode export fixture +**Consistency Checks**: the origin guard on the base (expected: FAIL) +**Commit**: `test(library): hold both trace readers to one MCP origin` + +## Step 2: One origin, one census +**Goal**: Both readers attribute MCP calls the same way, and the census names no server. +**Implementation Logic**: +- Pass the cell's resolved server names to OpenCode's export reader. Match `_` against them, longest name first, and fall back to the built-in list or `Other` only when no server matches. +- Add the optional `tool` to `ToolOrigin::Mcp`, fill it with the bare tool name in both readers, and add the test that an old trace without it still parses. +- Add the ambiguous-prefix refusal at resolve. +- Remove `census.mcp_servers`, its schema field and its producer, and reword `SERVER_START_WAIT`'s doc. +- Leave the census sources as they are: `CensusSource`, `census.source`, the gateway's `census_init` and the verdict's source reading stay. Only `census.mcp_servers` goes. + +Do not add any collection of server status: which servers the agent called is for the consumer to parse from the trace. +**Deliverables**: `crates/candler-schemas/src/trace.rs` and its generated schema; `crates/candler-harness-opencode/src/export.rs` and its caller; `crates/candler-harness-claude-code/src/parse.rs`; `crates/candler-core/src/runner/evidence/census.rs` and the census schema; `crates/candler-core/src/manifest/compare.rs`; the resolve server-name step; `crates/candler-core/src/jobs/orchestrate/servers.rs`; `docs/contract/codes.toml` +**Consistency Checks**: the origin guard on the tip (expected: PASS) +**Commit**: `fix(library): attribute MCP calls the same way on both harnesses` + +## Step 3: Bite and verify +**Goal**: The guard catches a reader that loses the server. +**Implementation Logic**: +On a scratch branch, make OpenCode's reader return `Other` for every MCP call again, and see the guard fail. A fresh Sonnet verifier gets this leaf, the report and the diff. Its brief is to find a call to one server's tool, on either harness, that the two traces would record differently, and any second statement of which servers a run had. +**Deliverables**: `__reports__/diet/leaves/trace_parity_v0.md` +**Consistency Checks**: the scratch edit makes the origin guard fail (expected: FAIL) +**Commit**: `reports(api): close the trace parity` diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/declaration.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/declaration.md new file mode 100644 index 00000000..3399cec7 --- /dev/null +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/dogfood/parity/declaration.md @@ -0,0 +1,63 @@ +# Settings declaration + +**Goal**: Every per-harness list has one shape: a fieldless key enum with a `const ALL`, a `Copy` answer of `&'static str`, and one exhaustive `match` per driver. `AgentSetting` holds what an experiment sets that reaches the agent. `DriverFact` holds what a driver does on its own and replaces `Capabilities`. Every `CONFIGURATION_PATHS` row says whether it reaches the agent (P8). +**Estimate**: Sonnet, $12, cap $24, with the lead reviewing at each joint. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, which is removed when the leaf merges. +**Pre-conditions**: +- [x] `[cmd]` `git -C merge-base --is-ancestor origin/feat/integrity HEAD` succeeds +- [x] `[nl]` The level-3 plan, revision 2, is approved (A3) +**Success Gates**: +- ⬜ `SettingRow`, `HarnessDriver::settings_table`, `Capabilities`, `CapabilitiesBuilder` and `BudgetCaps` are gone from the tree, and nothing replaces them with a second table +- ⬜ A test driver that omits its session-mode answer compiles and passes conformance on the base, through the builder's default `false`. On the tip, a scratch branch that adds one variant to `AgentSetting` and one to `DriverFact` fails to compile in both drivers until each answers it. The failure is recorded in the report and not committed +- ⬜ Both drivers deny `clippy::wildcard_enum_match_arm`, so a `_ =>` arm cannot stand in for an answer +- ⬜ A cell that sets `budget.per_run.max_cost_usd` on OpenCode is refused through its `Refused` arm with `experiment.setting_unsupported`. OpenCode's hand-written refusal lists in `prepare.rs` are gone +- ⬜ `PathRow` has a required `reach` column (`Agent(AgentSetting)` or `CandlerOnly`) that `row()` takes as an argument. A test in `crates/candler` walks every row for every registered driver, and fails when an `AgentSetting` is reached by no row and is not in the `NO_PATH` const +- ⬜ `guard_silent_acceptance.rs`'s rows read each driver's answer from `answer` instead of restating it +- ⬜ Hooks and instruction files are not `AgentSetting` variants. They are a later feature round (non-goal) +- ⬜ The report's "What it leaves" section judges the change at the three levels +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names +**References**: [Level-3 plan §Design](../../../../../../../../__reports__/diet/07-plan_integrity_level3_v1.md), on the one shape for every per-harness list. Code: +- `crates/candler-core/src/resolve/paths.rs`: `CONFIGURATION_PATHS`, `PathRow` and `row`, the idiom kept; +- `crates/candler-schemas/src/refusal.rs`: `refusal_table!`, the exhaustive match kept; +- `crates/candler-harness/src/driver.rs`: `SettingRow`, `settings_table`, `check_settings`; +- `crates/candler-harness/src/spec.rs`: `Capabilities`, `CapabilitiesBuilder`; +- `crates/candler-harness/src/conformance.rs`: `check_settings_table`, `check_capabilities`; +- `crates/candler-harness-opencode/src/prepare.rs`: `table`, `settings`. + +## Step 1: Guard on the base +**Goal**: The completeness guards fail on the base, for the reason the leaf removes. +**Implementation Logic**: +Write the walk over every path for every driver in `crates/candler`. Write the conformance check that a driver answers every key. On the base, show that a test driver built with `Capabilities::builder()` and no `.session(..)` passes conformance with the default `false`, and that Claude Code returns no settings table. Record both observations. The keys are: +- for `AgentSetting`: model id, endpoint and effort; permission mode; allowed and disallowed tools; `env`; `inputs`; skills; MCP servers, with transport, `codemode` and `name`; the wall, turn and cost budgets; and session mode; +- for `DriverFact`: graceful stop, live events, the in-harness guard, execution outside the child, and the census. + +A key whose values form a closed set carries the value, as in `Effort(EffortLevel)`, `Transport(Transport)` and `Codemode(bool)`. +**Deliverables**: the walk in `crates/candler/tests/it/`; `crates/candler-harness/src/conformance.rs` +**Consistency Checks**: the walk and the conformance check on the base (expected: FAIL) +**Commit**: `test(library): require every driver to answer every setting and fact` + +## Step 2: One shape +**Goal**: Each fact is stated once per driver, in an exhaustive match, and every list reads it. +**Implementation Logic**: +- Add `Answer` (`Mapped { construct }`, `Candler { how }`, `Refused { reason }`, all `&'static str`), `AgentSetting` and `DriverFact` to `candler-harness`, each with a `const ALL`. +- `HarnessDriver` gains `answer` and `fact`, both required and with no default. +- Delete `SettingRow`, `settings_table`, `Capabilities`, its builder and `BudgetCaps`. Every reader of a capability bool reads `fact` or `answer` instead. +- `check_settings` refuses a set value whose answer is `Refused`. OpenCode's refusal lists become match arms, and the lists are deleted. +- `PathRow` gains `reach`, and every `row(...)` call names it. +- Keep the capability page compiling with the smallest change; `answered/pages.md` regenerates it. + +Do not keep a wrapper that rebuilds the old structs for any reader. +**Deliverables**: `crates/candler-harness/src/{driver.rs,spec.rs,conformance.rs}`; `crates/candler-harness-opencode/src/{driver.rs,prepare.rs}`; `crates/candler-harness-claude-code/src/driver.rs`; `crates/candler-core/src/resolve/paths.rs`; the readers of the old capability fields in `crates/candler-core`; `crates/candler/tests/it/guard_silent_acceptance.rs` +**Consistency Checks**: the walk and the conformance check on the tip, with the scratch variant's compile failure recorded in the report (expected: PASS) +**Commit**: `refactor(library): state every per-harness fact in one shape` + +## Step 3: Bite and verify +**Goal**: The guards catch a missing answer and a restated one. +**Implementation Logic**: +On a scratch branch, make two edits and watch each guard fail: +- make OpenCode's cost-cap arm `Mapped`, and see the refusal guard fail; +- move one setting's path to `CandlerOnly` while it is not in `NO_PATH`, and see the walk fail. + +A fresh Sonnet verifier gets this leaf, the report and the diff. Its brief is to find a fact about a harness stated outside a driver's `answer` or `fact`, or a setting that reaches the agent with no key. +**Deliverables**: `__reports__/diet/leaves/declaration_v0.md` +**Consistency Checks**: both scratch edits (expected: FAIL) +**Commit**: `reports(api): close the settings declaration` diff --git a/__roadmap__/integrity/causes/checkpoint/snapshot/review/seam_review_two.md b/__roadmap__/integrity/causes/checkpoint/snapshot/review/seam_review_two.md index 5c128e9b..c6684a70 100644 --- a/__roadmap__/integrity/causes/checkpoint/snapshot/review/seam_review_two.md +++ b/__roadmap__/integrity/causes/checkpoint/snapshot/review/seam_review_two.md @@ -1,18 +1,18 @@ # Seam review 2 **Goal**: Everything merged since seam review 1 is read across its seams before an outside consumer uses the tip (D3 remedy). -**Estimate**: one fresh Claude reviewer, $4, cap $8. +**Estimate**: one fresh Claude reviewer, $4, cap $8. Builds use the target dir the campaign README names, removed at the leaf's end. At the cap, stop, commit what is green, and list what is left. **Pre-conditions**: - [ ] `[nl]` `../catalog_snapshot.md` is `done` or `blocked`, and every fix from seam review 1 is merged into `feat/integrity` **Success Gates**: -- ⬜ The review asks seam review 1's questions of the diff since it, and whether the snapshot holds at its seam (resolve to runner to store to `inspect`); if P5 waited, it says so and reviews the fixes alone +- ⬜ The review asks seam review 1's questions of the whole diff since the base, with level 2's changes in focus, and whether the snapshot holds at its seam (resolve to runner to store to `inspect`); if P5 waited, it says so and reviews the fixes alone - ⬜ Each finding is fixed on `feat/integrity` with its own guard seen failing, or recorded with its reason **References**: [Cycle plan v2 §How this work is developed](../../../../../../__reports__/diet/04-architecture_cycle_plan_v2.md) — the review questions; [README.md](../../../../../../README.md) — the purpose paragraph ## Step 1: Review the seams **Goal**: The level 2 seams are read by someone with the whole picture. **Implementation Logic**: -Hand a fresh Claude reviewer plan v2, the README purpose paragraph, seam review 1's report and the diff since it. It reports findings; it does not edit. Fixes follow as in seam review 1. +Hand a fresh Claude reviewer plan v2, the README purpose paragraph, seam review 1's report and `git diff origin/main...feat/integrity`, the whole diff since the base, not level 2 alone. It reports findings; it does not edit. Fixes follow as in seam review 1. **Deliverables**: `__reports__/diet/leaves/seam_review_two_v0.md` **Consistency Checks**: `cargo nextest run --workspace` on the `feat/integrity` tip after the fixes (expected: PASS) **Commit**: `reports(api): review the seams of level 2` diff --git a/__roadmap__/integrity/causes/collect_oracle.md b/__roadmap__/integrity/causes/collect_oracle.md index e0f87553..c8fd583e 100644 --- a/__roadmap__/integrity/causes/collect_oracle.md +++ b/__roadmap__/integrity/causes/collect_oracle.md @@ -1,13 +1,13 @@ # Collect oracle **Goal**: Conformance checks every driver's `collect` against what the agent wrote, not against the driver's own fixture (P2, cause D1, defect B1). -**Estimate**: RiVault first, $4 with the Sonnet fallback, cap $8. If the RiVault attempt fails its gates, one Sonnet attempt follows. At the cap, stop, commit what is green, and list what is left. +**Estimate**: RiVault first, $4 with the Sonnet fallback, cap $8. If the RiVault attempt fails its gates, one Sonnet attempt follows. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, removed at the leaf's merge. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/integrity HEAD` succeeds **Success Gates**: - ⬜ With B1's fix reverted on a scratch branch, the shared conformance case fails for OpenCode only, naming the files the agent wrote; on the base, the same revert passes conformance - ⬜ The oracle is the set of files the scripted agent wrote; `Case::with_collect` stays only where it checks something the shared case does not -- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/candler-diet/target`, and `container-e2e` is green on the pull request +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request **References**: [Cycle plan v2 §D1, §Proof](../../../__reports__/diet/04-architecture_cycle_plan_v2.md) — B1's mechanism and the observation; `crates/candler-harness/src/conformance.rs` — `Case::with_collect`, `check_collect` ## Step 1: Add the shared case diff --git a/__roadmap__/integrity/causes/kill_off_tty.md b/__roadmap__/integrity/causes/kill_off_tty.md index a9c89a18..13dc9da3 100644 --- a/__roadmap__/integrity/causes/kill_off_tty.md +++ b/__roadmap__/integrity/causes/kill_off_tty.md @@ -1,13 +1,13 @@ # Kill off a TTY **Goal**: `candler kill ` without `--yes`, off a terminal, refuses with a message on stderr that names `--yes` instead of prompting on stdout and doing nothing (P6, audit-5). -**Estimate**: RiVault first, $1 with the Sonnet fallback, cap $2. At the cap, stop, commit what is green, and list what is left. +**Estimate**: RiVault first, $1 with the Sonnet fallback, cap $2. At the cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, removed at the leaf's merge. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/integrity HEAD` succeeds **Success Gates**: - ⬜ A guard at the CLI runs `candler kill ` with stdin not a terminal and no `--yes`: nothing is printed on stdout, stderr names `--yes`, and the job is untouched; on the base the same guard fails on the stdout prompt - ⬜ On a terminal, and with `--yes`, `kill` behaves as before -- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/candler-diet/target`, and `container-e2e` is green on the pull request +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request **References**: [E2E audit, D5](../../../__reports__/diet/01-findings_e2e_audit_v0.md) — the defect as found; [Cycle plan v2 §Open items](../../../__reports__/diet/04-architecture_cycle_plan_v2.md) — audit-5 ## Step 1: Refuse off a TTY diff --git a/__roadmap__/integrity/causes/one_reader.md b/__roadmap__/integrity/causes/one_reader.md index 3c4f9b04..d9c284a9 100644 --- a/__roadmap__/integrity/causes/one_reader.md +++ b/__roadmap__/integrity/causes/one_reader.md @@ -1,7 +1,7 @@ # One reader **Goal**: Each consumer input has one reader, below every surface, that refuses what it does not understand: MCP servers and replicates first, then the rest of silent_acceptance, with no new layer (P4, cause D5). -**Estimate**: B on RiVault first, $1, cap $2; A1 Sonnet, $6, cap $12; A2 Sonnet with the HTN note, $5, cap $10. One worktree for the chain. At a cap, stop, commit what is green, and list what is left. +**Estimate**: B on RiVault first, $1, cap $2; A1 Sonnet, $6, cap $12; A2 Sonnet with the HTN note, $5, cap $10. One worktree for the chain. At a cap, stop, commit what is green, and list what is left. Builds use the target dir the campaign README names, removed at the leaf's merge. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/integrity HEAD` succeeds **Success Gates**: @@ -12,7 +12,7 @@ - ⬜ No `#[ignore]` whose reason names an OWNED set is left, and the silent_acceptance rows it hid pass - ⬜ Each of the three commits builds and passes alone (`git rebase -x 'cargo nextest run --workspace' feat/integrity`), and B touches only `crates/candler-schemas/` with its schema drift check passing - ⬜ The HTN migration note is in the leaf report and handed to the milestone coordinator for the HTN lane -- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/candler-diet/target`, and `container-e2e` is green on the pull request +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request **References**: [Cycle plan v2 §D5, §Proof](../../../__reports__/diet/04-architecture_cycle_plan_v2.md) — the readers, the commit order and the observations; [CONTRIBUTING.md](../../../CONTRIBUTING.md) — the schemas-release gate ## Step 1: Type mcp.servers (B) diff --git a/__roadmap__/integrity/causes/sealed_run_producer.md b/__roadmap__/integrity/causes/sealed_run_producer.md index bd79d617..63e83fec 100644 --- a/__roadmap__/integrity/causes/sealed_run_producer.md +++ b/__roadmap__/integrity/causes/sealed_run_producer.md @@ -1,7 +1,7 @@ # Sealed run producer **Goal**: Sealed runs have one test producer, Candler's own runner under a scripted agent, and the guards on S1's path get their runs from it (P1, cause D1). -**Estimate**: Sonnet, $10 with its probe, cap $20. At the cap, stop, commit what is green, and list what is left in the leaf report. +**Estimate**: Sonnet, $10 with its probe, cap $20. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use the target dir the campaign README names, removed at the leaf's merge. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/integrity HEAD` succeeds **Success Gates**: @@ -9,7 +9,7 @@ - ⬜ The probe's wall times (one analyze guard on the real runner, and a scripted native run) are in the leaf report, for the dogfooding pass's caps - ⬜ No guard on S1's path calls `seal_synthetic`; it is deleted if no caller is left, and no new hand-made seeder is added - ⬜ No digest or golden vector is edited -- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/candler-diet/target`, and `container-e2e` is green on the pull request +- `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo nextest run --workspace` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass, with the target dir the campaign README names, and `container-e2e` is green on the pull request **References**: [Cycle plan v2 §D1, §Proof](../../../__reports__/diet/04-architecture_cycle_plan_v2.md) — the mechanism, the "who produces this state" table and the observation ## Step 1: Probe the real runner diff --git a/__roadmap__/leaf_template.md b/__roadmap__/leaf_template.md new file mode 100644 index 00000000..235a7341 --- /dev/null +++ b/__roadmap__/leaf_template.md @@ -0,0 +1,49 @@ +# Leaf template + +A leaf is a dirtree task file. Copy this shape; each convention below carries the reason it exists. +The reasons are the evidence of the M6c Integrity campaign (cycle plan v2 §D3). + +```markdown +# + +**Goal**: () +**Estimate**: , $, cap $<2n>. At the cap, stop, commit what is green, and list what is left +in the leaf report. Builds use the target dir the campaign README names; the leaf removes it at its merge. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor HEAD` succeeds +**Success Gates**: +- ⬜ +**References**: []() — + +## Step 1: +**Goal**: <one sentence> +**Implementation Logic**: <how, in prose> +**Deliverables**: <files and artifacts> +**Consistency Checks**: `<command>` (expected: PASS) +**Commit**: `<type>(<scope>): <subject>` +``` + +## Conventions + +1. **A leaf owns a concept and touches the files the concept needs.** A cause that spans two file + sets has no owner when leaves are cut by file, and a gate over one leaf's files cannot see it. + Two leaves run in parallel only when their concepts are independent; where they share a file, + merge order settles it, not an ownership regex. +2. **Each gate names a behaviour a consumer can see, and is shown failing on the base before it + passes on the tip.** A gate that passes on the base proves nothing. Counts (tests, lines) may + appear as evidence and are never the gate: a suite can grow or shrink while passing the same + count. +3. **A gate whose meaning rests on ignored tests runs them, or says where they ran.** A gate that + skips is a gate that fails: run with `--run-ignored`, or name the pass that ran them with the + input they need set, and require the output to list them as passed, not skipped. +4. **A seam review on the whole diff follows each merge level.** The reviewer gets the milestone's + diff so far and the consumer interface, not one leaf, because defects live where two leaves meet. +5. **A roadmap merge that touches what the container path depends on waits for a green + `container-e2e`; a merge that touches none of it says so.** The check runs the real container + path in CI, and it starts only on pull requests that touch those paths (the `paths` list of + `.github/workflows/container-e2e.yml`), so a merge that needed it and went without it has not + met that path, and a merge that never triggers it records why it did not wait. +6. **Each leaf states its estimate, its cap as a stop action, the target dir the campaign README + names, and their cleanup.** The cap says what to do on reaching it (stop, commit what is green, + list what is left), so overrun ends work instead of growing it. Builds on a shared machine use a + dir per leaf, removed at the merge, so the disk is given back. diff --git a/__roadmap__/m3-lean-cli/refusal_scope.tsv b/__roadmap__/m3-lean-cli/refusal_scope.tsv index c0eb8e73..1945dff6 100644 --- a/__roadmap__/m3-lean-cli/refusal_scope.tsv +++ b/__roadmap__/m3-lean-cli/refusal_scope.tsv @@ -29,7 +29,6 @@ candler_core::manifest::compare::VerdictError crates/candler-core/src/manifest/c candler_core::resolve::config::ConfigError crates/candler-core/src/resolve/config.rs 6 yes config resolve refusal_core unreadable/invalid config, unknown key, misplaced key, wrong type, relative cwd candler_core::resolve::preflight::PreflightError crates/candler-core/src/resolve/preflight.rs 1 yes environment resolve refusal_core single detail variant: a preflight step failed (missing dir, binary) candler_core::resolve::preflight::ResolveError crates/candler-core/src/resolve/preflight.rs 6 mixed config resolve refusal_core author-facing: path not UTF-8, Value, Format; internal: step registered twice, derive conflicts -candler_core::runner::evidence::catalog::CatalogError crates/candler-core/src/runner/evidence/catalog.rs 6 mixed environment runner refusal_core author-facing: catalog command failed/timed out/printed none; internal: absolute path, no digest, Unavailable candler_core::runner::evidence::census::CensusError crates/candler-core/src/runner/evidence/census.rs 3 mixed environment runner refusal_core author-facing: NoInit/missing key when Claude Code ran unusably; internal: Value candler_core::runner::evidence::tree::EvidenceError crates/candler-core/src/runner/evidence/tree.rs 2 no candler internal refusal_core outputs of a run held to tree invariants; internal candler_core::runner::exec::cell::ExecError crates/candler-core/src/runner/exec/cell.rs 5 mixed environment runner refusal_core wrapper: transparent IsolationError, StoreError, DriverError, SuperviseError, ExecutionError; no own text but Manifest @@ -42,7 +41,6 @@ candler_harness::driver::DriverError crates/candler-harness/src/driver.rs 5 mixe candler_harness::reader::ReaderError crates/candler-harness/src/reader.rs 3 no candler internal refusal_core frame reader failures on Candler-fed frames candler_harness::spec::CommandSpecError crates/candler-harness/src/spec.rs 3 no candler internal refusal_core command builder invariants candler_schemas::canonical::CanonicalError crates/candler-schemas/src/canonical.rs 5 yes experiment schemas contract_wire non-finite number, integer beyond 2^53-1, repeated key, bad JSON in experiment/suite values -candler_schemas::catalog::CatalogError crates/candler-schemas/src/catalog.rs 6 mixed plugin schemas contract_wire author-facing: schema tag, repeated/empty names (catalog command output); internal: missing field, extra key, null candler_schemas::container::ContainerError crates/candler-schemas/src/container.rs 1 no candler internal contract_wire builder missing-field only candler_schemas::evaluation::EvaluationError crates/candler-schemas/src/evaluation.rs 9 mixed suite schemas contract_wire author-facing: unreadable/non-JSON document, empty list, repeated id, unknown dependency, cycle; internal: missing field candler_schemas::evaluation::VersionMismatch crates/candler-schemas/src/evaluation.rs 1 yes plugin schemas contract_wire struct; evaluator protocol version incompatible with Candler 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-core/src/import/manifest.rs b/crates/candler-core/src/import/manifest.rs index 6971c06e..2ba7ecca 100644 --- a/crates/candler-core/src/import/manifest.rs +++ b/crates/candler-core/src/import/manifest.rs @@ -308,11 +308,15 @@ fn cell_model( // BORROW: .to_owned() makes the owned tag treatment_ref.tag = Some(treatment.1.to_owned()); builder = builder.treatment(treatment_ref); + // The importer is the only writer of `snapshots`: an imported run's cell digest includes the + // list, empty or not. + let mut snapshots = Vec::new(); for rule in &rules.snapshots { let hex = provenance_text(folder, &rule.pointer)?; // BORROW: .clone() copies the snapshot kind into the cell - builder = builder.snapshot(DigestRef::new(rule.kind.clone(), Digest::from_hex(hex)?)); + snapshots.push(DigestRef::new(rule.kind.clone(), Digest::from_hex(hex)?)); } + builder = builder.snapshots(snapshots); let first_inputs = copied_inputs(first)?; for run in cell.runs.iter().skip(1) { let inputs = copied_inputs(run)?; diff --git a/crates/candler-core/src/import/raw.rs b/crates/candler-core/src/import/raw.rs index 206d386a..ec630bae 100644 --- a/crates/candler-core/src/import/raw.rs +++ b/crates/candler-core/src/import/raw.rs @@ -440,7 +440,7 @@ pub fn find_streams(path: &Path, recognise: &Recogniser) -> Result<Streams, RawI Ok(Streams { found, skipped }) } -/// The cell of a stream: the harness it names under the unrecorded treatment, and nothing else. +/// The cell of a stream: the harness it names under the unrecorded treatment, and an empty `snapshots` list, as an imported run's cell carries one. fn comparable_of(found: &Found) -> Result<Comparable, RawIngestError> { let manifest_error = |detail: String| RawIngestError::Manifest { stream: found.rel.to_string(), @@ -454,6 +454,7 @@ fn comparable_of(found: &Found) -> Result<Comparable, RawIngestError> { found.recognised.version.clone(), )) .treatment(TreatmentRef::new(treatment)) + .snapshots(Vec::new()) .build() .map_err(|e| manifest_error(e.to_string())) } diff --git a/crates/candler-core/src/import/rules.rs b/crates/candler-core/src/import/rules.rs index bf1976ef..d8710897 100644 --- a/crates/candler-core/src/import/rules.rs +++ b/crates/candler-core/src/import/rules.rs @@ -102,7 +102,8 @@ pub struct ImportRules { pub treatment: TreatmentRule, /// The name of the instrument that graded the folder, whose version and digest come from the folder's pinned evaluator. pub instrument: Name, - /// The snapshots of a cell. + /// The catalog digests of a cell, written into `comparable.snapshots`. The importer is the only + /// writer of that list. pub snapshots: Vec<SnapshotRule>, /// The patterns tried, in order, on the evidence of a `not_measured` row. pub markers: Vec<MarkerRule>, diff --git a/crates/candler-core/src/isolation/container/run.rs b/crates/candler-core/src/isolation/container/run.rs index 5daca6ff..0c90e247 100644 --- a/crates/candler-core/src/isolation/container/run.rs +++ b/crates/candler-core/src/isolation/container/run.rs @@ -6,7 +6,6 @@ //! credentials, are refused rather than overridden. use std::sync::Arc; -use std::time::Duration; use candler_harness::spec::{CommandSpec, EnvEntry, EnvValue}; use candler_schemas::primitives::{ContainerId, Marker, RunKey}; @@ -15,12 +14,11 @@ use url::Url; use super::expiry::{ceil_secs, wrap_expiry}; use super::mounts::{MountError, MountRoots, mounts}; use crate::isolation::RunOutputs; -use crate::isolation::control::ControlSpec; use crate::isolation::docker::{AttachedRun, PROGRAM}; use crate::isolation::driver::DockerDriver; use crate::isolation::hardening::{HardLimits, Role, hardening}; use crate::isolation::layout::{EXPIRY_MARGIN, LABEL_JOB, LABEL_ROLE, LABEL_RUN}; -use crate::isolation::model::{ContainerPlan, ImageId, Limits, UserSpec}; +use crate::isolation::model::{ContainerPlan, UserSpec}; use crate::supervise::hook::StopHook; use crate::supervise::spawn::SpawnRequest; @@ -206,26 +204,6 @@ pub fn create_argv(plan: &ContainerPlan, cmd: &CommandSpec) -> Result<Vec<String Ok(argv) } -/// The control container of the catalog capture: the image, the same hardening over `limits`, no -/// network, and the command under its own expiry of `wall`. -/// -/// # Errors -/// [`RunArgvError`] when the overlay is refused or the command cannot be wrapped. -pub fn catalog_spec( - image: &ImageId, - limits: &Limits, - wall: Duration, - cmd: &CommandSpec, -) -> Result<ControlSpec, RunArgvError> { - let wrapped = wrap_expiry(cmd, ceil_secs(wall)).map_err(|source| RunArgvError::Command { - detail: source.to_string(), - })?; - // A control container has no gateway: it reserves no name. - Ok(ControlSpec::new(&image.0, HardLimits::sized(limits)) - .env(env_pairs(wrapped.env_overlay(), &[])?) - .command(wrapped.argv().to_vec())) // BORROW: the spec owns its words -} - /// The names the plan reserves for the wrapper: the driver's gateway variables, none when the /// plan names no gateway. fn reserved_names<'a>(plan: &'a ContainerPlan) -> &'a [String] { diff --git a/crates/candler-core/src/isolation/control.rs b/crates/candler-core/src/isolation/control.rs index c850e090..38a9bd3e 100644 --- a/crates/candler-core/src/isolation/control.rs +++ b/crates/candler-core/src/isolation/control.rs @@ -1,5 +1,5 @@ //! The one builder of a control container: a throwaway container Candler runs to read or prepare -//! something, such as a version probe, a package probe, a lock compile, a catalog capture, a +//! something, such as a version probe, a package probe, a lock compile, a //! collect of a run's sessions or the fake model. //! //! A [`ControlSpec`] is every control container's flags in one place: it removes itself, wears the diff --git a/crates/candler-core/src/isolation/gateway.rs b/crates/candler-core/src/isolation/gateway.rs index 972316be..073e812e 100644 --- a/crates/candler-core/src/isolation/gateway.rs +++ b/crates/candler-core/src/isolation/gateway.rs @@ -1276,7 +1276,7 @@ pub fn census_init(stream: &[u8]) -> Option<InitReport> { .filter_map(|line| serde_json::from_slice::<Request>(line).ok()) .filter(|request| !request.tools.is_empty()) .min_by_key(|request| request.seq)?; - InitReport::new(serde_json::json!(first.tools), None, CensusSource::Gateway).ok() + InitReport::new(serde_json::json!(first.tools), CensusSource::Gateway).ok() } /// 128 random bits as hex, from the operating system. diff --git a/crates/candler-core/src/jobs/orchestrate/servers.rs b/crates/candler-core/src/jobs/orchestrate/servers.rs index 9c0243a5..44e12763 100644 --- a/crates/candler-core/src/jobs/orchestrate/servers.rs +++ b/crates/candler-core/src/jobs/orchestrate/servers.rs @@ -10,7 +10,7 @@ use std::time::Duration; use candler_harness::mcp::servers; use candler_harness::spec::{Cell, CommandSpec}; use candler_schemas::primitives::RunKey; -use serde_json::{Map, Value}; +use candler_schemas::servers::McpServer; use super::session::image_of; use crate::isolation::container::agent_home; @@ -22,52 +22,9 @@ use crate::runner::plan::RunPlan; /// How long a server's start command is given before it must still be running. /// /// The wait catches a server that crashes as it starts: an import error, a missing file, a missing -/// variable. It does not catch a server that starts and never answers MCP; the census of each run -/// records which servers the harness saw. +/// variable. It does not catch a server that starts and never answers MCP. pub const SERVER_START_WAIT: Duration = Duration::from_secs(3); -/// One stdio server to start: its key, its command words and its literal environment. -pub struct Stdio { - key: String, - argv: Vec<String>, - env: Vec<(String, String)>, -} - -/// The stdio servers of `declared`; a server with a `url`, or without a `command`, is skipped. -pub fn stdio_servers(declared: &Map<String, Value>) -> Vec<Stdio> { - let mut found = Vec::new(); - for (key, server) in declared { - if server.get("url").is_some() { - continue; - } - let Some(command) = server.get("command").and_then(Value::as_str) else { - continue; - }; - let mut argv = vec![command.to_owned()]; // BORROW: the probe owns its words - if let Some(args) = server.get("args").and_then(Value::as_array) { - argv.extend(args.iter().filter_map(Value::as_str).map(str::to_owned)); // BORROW: the probe owns its words - } - let env = server - .get("env") - .and_then(Value::as_object) - .map(|table| { - table - .iter() - .filter_map(|(name, value)| { - value.as_str().map(|text| (name.clone(), text.to_owned())) // BORROW: the probe owns its entries - }) - .collect() - }) - .unwrap_or_default(); - found.push(Stdio { - key: key.clone(), // BORROW: the probe owns its key - argv, - env, - }); - } - found -} - /// Why the start check refused the job. #[derive(Debug, thiserror::Error)] #[non_exhaustive] @@ -89,7 +46,7 @@ pub enum ServerCheckError { } /// The distinct pairs of image and declared servers, each with the first plan of such a cell. -type Groups<'a> = BTreeMap<(Option<String>, String), (&'a RunPlan, Vec<Stdio>)>; +type Groups<'a> = BTreeMap<(Option<String>, String), (&'a RunPlan, Vec<(String, McpServer)>)>; fn failed(detail: &impl ToString) -> ServerCheckError { ServerCheckError::ServerCheck { @@ -119,11 +76,17 @@ pub async fn check_servers(rt: &Runtime, plans: &[RunPlan]) -> Result<(), Server let Some(declared) = declared else { continue; }; - let stdio = stdio_servers(&declared); + let signature = ( + image_of(comparable), + serde_json::to_string(&declared).map_err(|e| failed(&e))?, + ); + let stdio: Vec<(String, McpServer)> = declared + .into_iter() + .filter(|(_, server)| server.command.is_some()) + .collect(); if stdio.is_empty() { continue; } - let signature = (image_of(comparable), Value::Object(declared).to_string()); groups.entry(signature).or_insert((plan, stdio)); } if groups.is_empty() { @@ -154,7 +117,7 @@ async fn probe_group( rt: &Runtime, isolation: &dyn Isolation, // TRAIT_OBJECT: the runtime's isolation, or a fake in tests plan: &RunPlan, - stdio: &[Stdio], + stdio: &[(String, McpServer)], root: &Path, ) -> Result<(), ServerCheckError> { let cell = rt.cells.get(&plan.cell).ok_or_else(|| failed(&"no cell"))?; @@ -179,20 +142,16 @@ async fn probe_group( .map_err(|e| failed(&e))?; // Standard input stays open, as a server's own would while the agent runs. container.interactive = true; - for server in stdio { + for (name, server) in stdio { // The server's own variables reach the server alone, as in its configuration, and never // the container's environment, where a gateway or plan name would be refused. let mut words = Vec::new(); - if !server.env.is_empty() { + if let Some(env) = server.env.as_ref().filter(|env| !env.is_empty()) { words.push(String::from("env")); - words.extend( - server - .env - .iter() - .map(|(name, value)| format!("{name}={value}")), - ); + words.extend(env.iter().map(|(name, value)| format!("{name}={value}"))); } - words.extend(server.argv.iter().cloned()); // BORROW: the command owns its words + words.extend(server.command.iter().cloned()); // BORROW: the command owns its words + words.extend(server.args.iter().flatten().cloned()); // BORROW: the command owns its words let mut builder = CommandSpec::builder().argv(words); for entry in staged .prepared @@ -210,7 +169,7 @@ async fn probe_group( .map_err(|e| failed(&e))?; if let StartProbe::Exited { output } = seen { return Err(ServerCheckError::Server { - key: server.key.clone(), // BORROW: the error owns the key + key: name.clone(), // BORROW: the error owns the key output, }); } diff --git a/crates/candler-core/src/jobs/orchestrate/session.rs b/crates/candler-core/src/jobs/orchestrate/session.rs index 9e18a705..1d44e9d1 100644 --- a/crates/candler-core/src/jobs/orchestrate/session.rs +++ b/crates/candler-core/src/jobs/orchestrate/session.rs @@ -46,11 +46,11 @@ use crate::runner::{JobGateway, Runtime}; use crate::supervise::{EventSink, Supervisor}; use candler_schemas::execution::paths::{ ENVIRONMENTS, HARNESS, INPUTS, ISOLATION_EGRESS, ISOLATION_IMAGE, ISOLATION_RECORD_PACKAGES, - MODEL_ENDPOINT, MODEL_TOKEN_SECRET, REQUEST_TREATMENT, RUNNER_IDLE_S, SNAPSHOTS, TREATMENT, + MODEL_ENDPOINT, MODEL_TOKEN_SECRET, REQUEST_TREATMENT, RUNNER_IDLE_S, TREATMENT, }; /// The roots of a cell that hold typed records; their sources are not value paths. -const TYPED_ROOTS: [&str; 5] = [HARNESS, TREATMENT, SNAPSHOTS, INPUTS, ENVIRONMENTS]; +const TYPED_ROOTS: [&str; 4] = [HARNESS, TREATMENT, INPUTS, ENVIRONMENTS]; /// The tag the gateway's sidecar image is looked up by. pub(super) const SIDECAR_TAG: &str = "candler-gateway:latest"; diff --git a/crates/candler-core/src/refusal.rs b/crates/candler-core/src/refusal.rs index f63d4764..af190b54 100644 --- a/crates/candler-core/src/refusal.rs +++ b/crates/candler-core/src/refusal.rs @@ -328,7 +328,6 @@ fn coded<'e>(error: &'e (dyn Error + 'static)) -> Option<&'e dyn Refusal> { /// The coded type of the schemas crate that `error` is, or `None`. fn schemas_coded<'e>(error: &'e (dyn Error + 'static)) -> Option<&'e dyn Refusal> { use candler_schemas::canonical::CanonicalError; - use candler_schemas::catalog::CatalogError; use candler_schemas::evaluation::{EvaluationError, VersionMismatch}; use candler_schemas::execution::ExecutionError; use candler_schemas::outcome::OutcomeError; @@ -351,7 +350,6 @@ fn schemas_coded<'e>(error: &'e (dyn Error + 'static)) -> Option<&'e dyn Refusal .downcast_ref::<FormatError>() .map(as_refusal) .or_else(|| error.downcast_ref::<CanonicalError>().map(as_refusal)) - .or_else(|| error.downcast_ref::<CatalogError>().map(as_refusal)) .or_else(|| error.downcast_ref::<VersionMismatch>().map(as_refusal)) } diff --git a/crates/candler-core/src/resolve/layers.rs b/crates/candler-core/src/resolve/layers.rs index 0359b093..5514c85a 100644 --- a/crates/candler-core/src/resolve/layers.rs +++ b/crates/candler-core/src/resolve/layers.rs @@ -242,12 +242,6 @@ impl Layered { } .into()); } - let token_secret = written - .iter() - .rev() - .find(|(path, _)| path.as_str() == TOKEN_SECRET) - .and_then(|(_, value)| value.as_value().as_str()); - super::steps::env::check(written.iter().copied(), &input.secret_names, token_secret)?; check_replicates_input(&written)?; let store_root: FieldPath = STORE_ROOT.parse()?; let plugins_dirs: FieldPath = PLUGINS_DIRS.parse()?; @@ -290,6 +284,20 @@ impl Layered { core_defaults.push((store_root, path_json(default_root.as_path())?)); } core_defaults.extend(input.core_defaults); + let token_secret = written + .iter() + .rev() + .map(|(path, value)| (*path, *value)) + .chain( + project + .iter() + .chain(user.iter()) + .chain(core_defaults.iter()) + .map(|(path, value)| (path, value)), + ) + .find(|(path, _)| path.as_str() == TOKEN_SECRET) + .and_then(|(_, value)| value.as_value().as_str()); + super::steps::env::check(written.iter().copied(), &input.secret_names, token_secret)?; Ok(Self { explicit: input.explicit, @@ -378,10 +386,10 @@ impl Layered { /// The path of the secret that holds the gateway token. const TOKEN_SECRET: &str = "model.token_secret"; -/// Refuses a `replicates.<x>` path, which names no setting, and a `replicates` count that is not a -/// whole number: either would be read as no value at all. +/// Refuses a `replicates.<x>` path, which names no setting and would be read as no value at all. +/// Whether the `replicates` value is a count is decided where the plan reads it. fn check_replicates_input(written: &[(&FieldPath, &JsonValue)]) -> Result<(), ResolveError> { - for (path, value) in written { + for (path, _value) in written { if path .as_str() .strip_prefix(REPLICATES) @@ -391,11 +399,6 @@ fn check_replicates_input(written: &[(&FieldPath, &JsonValue)]) -> Result<(), Re path: path.to_string(), }); } - if path.as_str() == REPLICATES && value.as_value().as_u64().is_none() { - return Err(ResolveError::ReplicatesNotInteger { - value: value.as_value().to_string(), - }); - } } Ok(()) } diff --git a/crates/candler-core/src/resolve/paths.rs b/crates/candler-core/src/resolve/paths.rs index 6298c91e..3e34b0af 100644 --- a/crates/candler-core/src/resolve/paths.rs +++ b/crates/candler-core/src/resolve/paths.rs @@ -2,6 +2,9 @@ //! names, with what it is, in one table that the resolver, the request-key check, the typed //! configuration readers and the contract pages all read. +use candler_harness::driver::{DriverError, HarnessDriver}; +use candler_harness::mcp; +use candler_harness::spec::{AgentSetting, Answer, Cell, EffortLevel, PermissionMode}; use candler_schemas::execution::paths::{ BUDGET_PER_RUN_MAX_COST_USD, BUDGET_PER_RUN_TURNS, BUDGET_PER_RUN_WALL_S, ENV, ENVIRONMENTS, HARNESS, INPUTS, ISOLATION_BUILD_CONTEXT, ISOLATION_BUILD_DOCKERFILE, ISOLATION_BUILD_LOCK, @@ -10,10 +13,11 @@ use candler_schemas::execution::paths::{ ISOLATION_LIMITS_MEMORY, ISOLATION_LIMITS_PIDS, ISOLATION_NETWORK, ISOLATION_RECORD_PACKAGES, MCP, MODEL_EFFORT, MODEL_ENDPOINT, MODEL_ID, MODEL_TOKEN_SECRET, PERMISSION_MODE, PLUGINS_DIRS, PROMPT_TEMPLATE, PROMPT_VALUES, REQUEST_HARNESS, REQUEST_INPUTS, REQUEST_TREATMENT, - RUNNER_IDLE_S, RUNNER_MODE, SLOTS_COUNT, SLOTS_EVALUATORS, SNAPSHOTS, STORE_ROOT, - TOOLS_ALLOWED, TOOLS_DISALLOWED, TREATMENT, TREATMENT_SOURCE_PREFIX, + RUNNER_IDLE_S, RUNNER_MODE, SLOTS_COUNT, SLOTS_EVALUATORS, STORE_ROOT, TOOLS_ALLOWED, + TOOLS_DISALLOWED, TREATMENT, TREATMENT_SOURCE_PREFIX, }; use candler_schemas::primitives::FieldPath; +use candler_schemas::servers::McpServerKind; const BUDGET: &str = "budget"; const BUDGET_PER_RUN: &str = "budget.per_run"; @@ -82,6 +86,26 @@ pub enum ConfigFile { User, } +/// Whether a path reaches the agent. +#[derive(Debug, Clone, Copy)] +#[expect( + clippy::exhaustive_enums, + reason = "EXHAUSTIVE: a row states one or the other; a reader must handle both." +)] +pub enum Reach { + /// The path is read by the harness's driver, as the keys listed (one value of each key the + /// path carries). + Agent(&'static [AgentSetting]), + /// Candler reads the path itself; no driver sees it. + CandlerOnly, +} + +/// The agent settings no configuration path reaches, each with where it comes from. +pub const NO_PATH: [(AgentSetting, &str); 1] = [( + AgentSetting::Skills, + "the skills are the treatment's skill tree, not a configuration path", +)]; + /// One row of [`CONFIGURATION_PATHS`]. #[derive(Debug, Clone, Copy)] pub struct PathRow { @@ -91,17 +115,26 @@ pub struct PathRow { pub kind: Kind, /// What the path is. pub class: Class, + /// Whether the path reaches the agent, and as which keys. + pub reach: Reach, /// The configuration file the key belongs to, for a configuration key. pub file: ConfigFile, /// The one line the contract page prints. pub meaning: &'static str, } -const fn row(path: &'static str, kind: Kind, class: Class, meaning: &'static str) -> PathRow { +const fn row( + path: &'static str, + kind: Kind, + class: Class, + reach: Reach, + meaning: &'static str, +) -> PathRow { PathRow { path, kind, class, + reach, file: ConfigFile::None, meaning, } @@ -112,270 +145,317 @@ const fn key(path: &'static str, kind: Kind, file: ConfigFile, meaning: &'static path, kind, class: Class::ConfigKey, + reach: Reach::CandlerOnly, file, meaning, } } /// Every path the configuration surface names. -pub const CONFIGURATION_PATHS: [PathRow; 49] = [ +pub const CONFIGURATION_PATHS: [PathRow; 48] = [ row( MODEL_ID, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::ModelId]), "The model the harness runs.", ), row( MODEL_ENDPOINT, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::ModelEndpoint]), "The endpoint the gateway forwards model requests to.", ), row( MODEL_EFFORT, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::Effort(EffortLevel::Low)]), "The effort level the harness asks of the model.", ), row( MODEL_TOKEN_SECRET, Kind::Leaf, Class::Setting, + Reach::CandlerOnly, "The name of the secret that holds the gateway's token.", ), row( TOOLS_ALLOWED, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::ToolsAllowed]), "The tools the harness may use.", ), row( TOOLS_DISALLOWED, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::ToolsDisallowed]), "The tools the harness may not use.", ), row( ENV, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::Env]), "The environment of the harness process: a table of variable name to text.", ), row( MCP, Kind::Subtree, Class::Value, + Reach::Agent(&[ + AgentSetting::McpTransport(McpServerKind::Stdio), + AgentSetting::Codemode(true), + AgentSetting::McpName, + ]), "The MCP servers of a run; the names below are free.", ), row( PERMISSION_MODE, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::PermissionMode(PermissionMode::Default)]), "The permission mode the harness runs in.", ), row( REQUEST_HARNESS, Kind::Leaf, Class::Request, + Reach::CandlerOnly, "The harness the run uses.", ), row( REQUEST_TREATMENT, Kind::Leaf, Class::Request, + Reach::CandlerOnly, "The treatment the run applies.", ), row( REQUEST_INPUTS, Kind::Leaf, Class::Request, + Reach::CandlerOnly, "The inputs the run is given.", ), row( PROMPT_TEMPLATE, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The prompt template.", ), row( PROMPT_VALUES, Kind::Subtree, Class::Value, + Reach::CandlerOnly, "The values the prompt template fills in; the names below are free.", ), row( ISOLATION_IMAGE, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The container image a run starts in.", ), row( ISOLATION_NETWORK, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The network mode of the container.", ), row( ISOLATION_ENV_LOCK, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The environment lock the image must match.", ), row( ISOLATION_LIMITS, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The resource limits of the container; the limits are below.", ), row( ISOLATION_LIMITS_PIDS, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The process limit of the container.", ), row( ISOLATION_LIMITS_MEMORY, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The memory limit of the container.", ), row( ISOLATION_LIMITS_CPUS, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The CPU limit of the container.", ), row( ISOLATION_EGRESS, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The hosts the container may reach.", ), row( ISOLATION_RECORD_PACKAGES, Kind::Leaf, Class::Setting, + Reach::CandlerOnly, "Whether a run records the packages of its image.", ), row( ISOLATION_BUILD, Kind::Below, Class::Setting, + Reach::CandlerOnly, "Every path below it is a request to build an image.", ), row( ISOLATION_BUILD_PLUGIN, Kind::Leaf, Class::Setting, + Reach::CandlerOnly, "The image build plug-in.", ), row( ISOLATION_BUILD_DOCKERFILE, Kind::Leaf, Class::Setting, + Reach::CandlerOnly, "The Dockerfile of an image build.", ), row( ISOLATION_BUILD_CONTEXT, Kind::Leaf, Class::Setting, + Reach::CandlerOnly, "The build context directory of an image build.", ), row( ISOLATION_BUILD_REQUIREMENTS, Kind::Leaf, Class::Setting, + Reach::CandlerOnly, "The requirements file of an image build.", ), row( ISOLATION_BUILD_PRUNE, Kind::Leaf, Class::Setting, + Reach::CandlerOnly, "Whether an image build prunes what it leaves.", ), row( ISOLATION_BUILD_LOCK, Kind::Leaf, Class::Setting, + Reach::CandlerOnly, "The lock file of an image build.", ), row( BUDGET, Kind::Subtree, Class::Setting, + Reach::CandlerOnly, "A job cap: every path below it, except the per-run caps.", ), row( BUDGET_PER_RUN, Kind::Carveout, Class::Value, + Reach::CandlerOnly, "The per-run caps are experiment values.", ), row( BUDGET_PER_RUN_WALL_S, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::WallBudget]), "The wall-clock cap of one run, in seconds.", ), row( BUDGET_PER_RUN_TURNS, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::TurnBudget]), "The turn cap of one run.", ), row( BUDGET_PER_RUN_MAX_COST_USD, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::CostBudget]), "The cost cap of one run, in US dollars.", ), row( REPLICATES, Kind::Subtree, Class::Setting, + Reach::CandlerOnly, "How many runs each cell gets.", ), row( RUNNER_MODE, Kind::Leaf, Class::Value, + Reach::Agent(&[AgentSetting::SessionMode]), "`headless` or `session`.", ), row( RUNNER_IDLE_S, Kind::Leaf, Class::Value, + Reach::CandlerOnly, "The idle time that ends a session, in whole seconds, or `none`.", ), row( HARNESS, Kind::Subtree, Class::Value, + Reach::CandlerOnly, "The harness table; the names below belong to the harness.", ), row( TREATMENT, Kind::Subtree, Class::Value, + Reach::CandlerOnly, "The treatment table.", ), - row(INPUTS, Kind::Subtree, Class::Value, "The inputs table."), row( - SNAPSHOTS, + INPUTS, Kind::Subtree, Class::Value, - "The snapshots table.", + Reach::Agent(&[AgentSetting::Inputs]), + "The inputs table.", ), row( ENVIRONMENTS, Kind::Subtree, Class::Value, + Reach::CandlerOnly, "The environments table.", ), row( TREATMENT_SOURCE_PREFIX, Kind::NotAPath, Class::Value, + Reach::CandlerOnly, "The prefix of a value that names a treatment source; the rest is the path.", ), key( @@ -452,6 +532,92 @@ fn covers(kind: Kind, root: &FieldPath, path: &FieldPath) -> bool { } } +/// The settings `cell` sets, each with the path of the row that reaches it and with the value the +/// cell gives it, in the order of [`CONFIGURATION_PATHS`]. The rows are the only place a path +/// meets a setting. The skills and the session mode are not read here: the treatment holds the +/// first, and the plan's session refuses the second. +/// +/// # Errors +/// [`DriverError::InvalidValue`] when the effort or the permission mode is text no level or mode +/// names, or the value is not text, and the error of the reader of `mcp.servers`. +pub fn settings_set_by(cell: &Cell<'_>) -> Result<Vec<(AgentSetting, FieldPath)>, DriverError> { + let mut set: Vec<(AgentSetting, FieldPath)> = Vec::new(); + for row in &CONFIGURATION_PATHS { + let Reach::Agent(families) = row.reach else { + continue; + }; + let Some(path) = field_path(row) else { + continue; + }; + if cell.below(&path).is_empty() { + continue; + } + let mut found: Vec<AgentSetting> = Vec::new(); + for family in families { + match family { + AgentSetting::Effort(_) => { + found.extend(cell.effort_at(&path)?.map(AgentSetting::Effort)); + } + AgentSetting::PermissionMode(_) => { + found.extend(cell.mode_at(&path)?.map(AgentSetting::PermissionMode)); + } + // The three keys of a server are read together, from the transport's entry. + AgentSetting::McpTransport(_) => { + for server in mcp::servers(cell)?.unwrap_or_default().into_values() { + found.push(AgentSetting::McpTransport(mcp::kind(&server))); + found.push(AgentSetting::Codemode(server.codemode)); + if server.name.is_some() { + found.push(AgentSetting::McpName); + } + } + } + AgentSetting::Codemode(_) + | AgentSetting::McpName + | AgentSetting::Skills + | AgentSetting::SessionMode => {} + AgentSetting::ModelId + | AgentSetting::ModelEndpoint + | AgentSetting::ToolsAllowed + | AgentSetting::ToolsDisallowed + | AgentSetting::Env + | AgentSetting::Inputs + | AgentSetting::WallBudget + | AgentSetting::TurnBudget + | AgentSetting::CostBudget => found.push(*family), + } + } + for setting in found { + if !set.iter().any(|(held, _)| *held == setting) { + set.push((setting, path.clone())); // BORROW: each setting keeps its row's path + } + } + } + Ok(set) +} + +/// Refuses a cell that sets something the driver answers [`Answer::Refused`], with the +/// [`DriverError::Unsupported`] that names the setting, the harness and the answer's reason. The +/// one place a refused setting is refused, before the driver plans. +/// +/// # Errors +/// [`DriverError::Unsupported`] for the first set setting the driver refuses, and the error of +/// [`settings_set_by`] when a value of the cell cannot be read. +pub fn refuse_unanswered( + driver: &dyn HarnessDriver, // TRAIT_OBJECT: the check reads any driver + cell: &Cell<'_>, +) -> Result<(), DriverError> { + for (setting, path) in settings_set_by(cell)? { + if let Answer::Refused { reason } = driver.answer(setting) { + return Err(DriverError::unsupported( + &path, + driver.id().to_string().as_str(), // BORROW: .to_string() gives owned text + reason, + )); + } + } + Ok(()) +} + /// Reports whether the row with the most segments that names `path` is of a setting class. #[must_use] pub fn names_a_setting(path: &FieldPath) -> bool { diff --git a/crates/candler-core/src/resolve/preflight.rs b/crates/candler-core/src/resolve/preflight.rs index 93313d8f..5adf6153 100644 --- a/crates/candler-core/src/resolve/preflight.rs +++ b/crates/candler-core/src/resolve/preflight.rs @@ -235,12 +235,6 @@ pub enum ResolveError { /// The path, as written. path: String, }, - /// The `replicates` count is not a whole number. - #[error("`replicates` is {value}, which is not a whole number")] - ReplicatesNotInteger { - /// The value, as JSON text. - value: String, - }, /// At least one step failed; every step ran. #[error( "preflight failed: {} failed step report(s), {} step error(s){}", diff --git a/crates/candler-core/src/resolve/refusal.rs b/crates/candler-core/src/resolve/refusal.rs index 428baf32..473958be 100644 --- a/crates/candler-core/src/resolve/refusal.rs +++ b/crates/candler-core/src/resolve/refusal.rs @@ -46,7 +46,6 @@ fn resolve_error_path(error: &ResolveError) -> Option<String> { ResolveError::GroundTruth(inner) => Refusal::path(inner), ResolveError::Env(inner) => Refusal::path(inner), ResolveError::ReplicatesPath { path } => Some(pointer_of(path.split('.'))), - ResolveError::ReplicatesNotInteger { .. } => Some(pointer_of(["replicates"])), ResolveError::NonUtf8Path { .. } | ResolveError::DuplicateStep { .. } | ResolveError::DerivedTwice { .. } @@ -239,12 +238,6 @@ wrapper_table! { "A `[fixed]` key or a `--set` names a path below `replicates`; `replicates` is one count and has no fields.", "The path that was written.", ), - ReplicatesNotInteger { .. } => row( - "experiment.replicates_not_integer", - Side::Experiment, - "`replicates` in `[fixed]` or in a `--set` is not a whole number, such as a string or a fraction.", - "The `replicates` key.", - ), Preflight { .. } => row( "resolve.preflight_failed", Side::Environment, @@ -292,7 +285,6 @@ fn resolve_answer(error: &ResolveError) -> &dyn Refusal { | ResolveError::GroundTruth(..) | ResolveError::Env(..) | ResolveError::ReplicatesPath { .. } - | ResolveError::ReplicatesNotInteger { .. } | ResolveError::Format(..) => error, } } diff --git a/crates/candler-core/src/resolve/steps/catalog.rs b/crates/candler-core/src/resolve/steps/catalog.rs deleted file mode 100644 index 6ee8818c..00000000 --- a/crates/candler-core/src/resolve/steps/catalog.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! The catalog step: the commands the agent can run in the image, as the cell configures it. -//! -//! The cell holds only the digest of the catalog, in `snapshots`. The catalog itself belongs to -//! the run evidence. - -use std::str::FromStr; -use std::sync::Arc; - -use candler_harness::spec::Cell; -use candler_schemas::execution::DigestRef; -use candler_schemas::primitives::{FieldPath, FormatError, Name, NameToken}; -use candler_schemas::values::JsonValue; -use futures::future::BoxFuture; - -use crate::isolation::model::{ImageId, ImageRef}; -use crate::resolve::preflight::{PreflightError, PreflightStep, ResolveContext, StepReport}; -use crate::runner::evidence::catalog::{CatalogProvider, catalog_digest}; -use candler_schemas::execution::paths; - -fn failed(detail: String) -> PreflightError { - PreflightError::Failed { detail } -} - -fn path_of(text: &str) -> Result<FieldPath, PreflightError> { - FieldPath::from_str(text).map_err(|e| failed(e.to_string())) -} - -/// Derives `snapshots`: the digest of the catalog of the image the cell runs in. -pub struct CatalogStep { - name: NameToken, - // TRAIT_OBJECT: the provider lists commands in the image, or is a fake in tests - catalog: Arc<dyn CatalogProvider>, -} - -impl CatalogStep { - /// A step that captures the catalog through `catalog`. - /// - /// # Errors - /// [`FormatError`] when the step name is not a name token. - // TRAIT_OBJECT: the provider lists commands in the image, or is a fake in tests - pub fn new(catalog: Arc<dyn CatalogProvider>) -> Result<Self, FormatError> { - Ok(Self { - name: NameToken::from_str("catalog@1")?, - catalog, - }) - } -} - -impl PreflightStep for CatalogStep { - fn name<'a>(&'a self) -> &'a NameToken { - &self.name - } - - fn run( - &self, - ctx: Arc<ResolveContext>, - ) -> BoxFuture<'static, Result<StepReport, PreflightError>> { - // BORROW: `Arc::clone` moves a share of the provider into the future - let provider = Arc::clone(&self.catalog); - // BORROW: `.clone()` moves the step name into the future - let step = self.name.clone(); - Box::pin(async move { - let image_path = path_of(paths::ISOLATION_IMAGE)?; - let id = ctx - .get(&image_path) - // BORROW: `.as_str()` borrows the text of the JSON string - .and_then(|value| value.as_value().as_str()) - .ok_or_else(|| failed(format!("`{}` has no image id", paths::ISOLATION_IMAGE)))?; - let image = ImageRef { - id: ImageId(id.to_owned()), // BORROW: owned id for the image reference - harness_version: None, - }; - let catalog = provider - .capture(&image, &Cell::new(&ctx.values)) - .await - .map_err(|e| failed(e.to_string()))?; - let digest = catalog_digest(&catalog).map_err(|e| failed(e.to_string()))?; - let kind = Name::from_str("catalog").map_err(|e| failed(e.to_string()))?; - let entry = serde_json::to_value([DigestRef::new(kind, digest)]) - .map_err(|e| failed(e.to_string()))?; - Ok(StepReport::new(step).derive( - path_of(paths::SNAPSHOTS)?, - JsonValue::new(entry).map_err(|e| failed(e.to_string()))?, - )) - }) - } -} diff --git a/crates/candler-core/src/resolve/steps/mod.rs b/crates/candler-core/src/resolve/steps/mod.rs index f75acea9..dc8794e8 100644 --- a/crates/candler-core/src/resolve/steps/mod.rs +++ b/crates/candler-core/src/resolve/steps/mod.rs @@ -1,7 +1,5 @@ -//! The preflight steps that resolve the identity of the harness and the treatment, the image and -//! the command catalog. +//! The preflight steps that resolve the identity of the harness and the treatment and the image. -pub mod catalog; pub mod egress; pub mod env; pub mod gateway; @@ -14,7 +12,6 @@ pub mod session; use std::sync::Arc; -use self::catalog::CatalogStep; use self::egress::EgressStep; use self::identity::{HarnessIdentityStep, TreatmentIdentityStep}; use self::image::ImageIdStep; @@ -22,20 +19,16 @@ use self::plugin_environment::PluginEnvironmentStep; use self::session::SessionModeStep; use super::preflight::{ResolveError, Resolver}; use crate::isolation::image::ImageService; -use crate::runner::evidence::catalog::CatalogProvider; use crate::supervise::Supervisor; use candler_harness::skills::SkillTree; -/// What the image, harness, treatment and catalog steps need from the outside. +/// What the image, harness and treatment steps need from the outside. pub struct M2bServices { /// The supervisor that runs the version probes. pub supervisor: Arc<Supervisor>, // TRAIT_OBJECT: the service is docker, or a fake in tests /// Provides the image. pub images: Arc<dyn ImageService>, - // TRAIT_OBJECT: the provider lists commands in the image, or is a fake in tests - /// Captures the command catalog. - pub catalog: Arc<dyn CatalogProvider>, /// The harness versions the driver supports. pub harness_supported: semver::VersionReq, /// Whether the harness's driver runs sessions. @@ -48,8 +41,7 @@ pub struct M2bServices { /// the treatment first (its pinned commit is where requirement sources are read), then the plug-in /// environment (it supplies the image step's values), then the ground truth (a gate: an image /// that would hold evaluator-only bytes is never built), then the image, -/// then the harness (it reads the image), then the catalog, then the session mode, then the egress -/// allowlist. +/// then the harness (it reads the image), then the session mode, then the egress allowlist. /// /// Each step clones the services it holds, so `services` stays with the caller. /// @@ -69,7 +61,6 @@ pub fn register_m2b_steps( services.harness_supported.clone(), // BORROW: the step owns its requirement )?; let treatment = TreatmentIdentityStep::new(Arc::clone(&services.supervisor), services.skills)?; - let catalog = CatalogStep::new(Arc::clone(&services.catalog))?; let session = SessionModeStep::new(services.session_capable)?; let plugin_environment = PluginEnvironmentStep::new()?; let egress = EgressStep::new()?; @@ -79,7 +70,6 @@ pub fn register_m2b_steps( .register(Box::new(ground_truth))? // TRAIT_OBJECT: steps of different types are registered side by side .register(Box::new(image))? // TRAIT_OBJECT: steps of different types are registered side by side .register(Box::new(harness))? // TRAIT_OBJECT: steps of different types are registered side by side - .register(Box::new(catalog))? // TRAIT_OBJECT: steps of different types are registered side by side .register(Box::new(session))? // TRAIT_OBJECT: steps of different types are registered side by side .register(Box::new(egress)) // TRAIT_OBJECT: steps of different types are registered side by side } diff --git a/crates/candler-core/src/runner/evidence/catalog.rs b/crates/candler-core/src/runner/evidence/catalog.rs deleted file mode 100644 index e549ead4..00000000 --- a/crates/candler-core/src/runner/evidence/catalog.rs +++ /dev/null @@ -1,299 +0,0 @@ -//! The command catalog of an image: which commands the agent can run. - -use std::path::PathBuf; -use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::Duration; - -use candler_harness::spec::{Cell, CommandSpec}; -use candler_schemas::catalog::CatalogSnapshot; -use candler_schemas::primitives::Digest; -use candler_schemas::process::ExitStatus; -use futures::future::BoxFuture; - -use crate::isolation::container::run::catalog_spec; -use crate::isolation::control::ControlSpec; -use crate::isolation::docker::{ClientEnv, DockerCli}; -use crate::isolation::layout; -use crate::isolation::model::{ImageRef, Limits}; -use crate::supervise::Supervisor; -use crate::supervise::stop::{Captured, Ended}; - -/// The exit code of coreutils `timeout` when the command it runs overran. -const TIMEOUT_EXIT: i32 = 124; - -/// How long past the command's own time the docker client may run before the supervisor ends it. -const CLIENT_GRACE: Duration = Duration::from_secs(30); - -/// The most bytes of a catalog that are read. -const OUTPUT_LIMIT: usize = 8 * 1024 * 1024; - -/// The process limit of a control container. -const CONTROL_PIDS: u32 = 64; - -/// The memory limit of a control container. -const CONTROL_MEMORY: &str = "512m"; - -/// The cpu limit of a control container. -const CONTROL_CPUS: f64 = 1.0; - -/// Numbers the record directories of catalog captures within one process. -static CONTROL_CALLS: AtomicU64 = AtomicU64::new(0); - -/// The catalog of one image and cell. -pub type Catalog = CatalogSnapshot; - -/// Why a catalog could not be captured. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[non_exhaustive] -pub enum CatalogError { - /// Capture is not available. - #[error("catalog capture is not available: {detail}")] - Unavailable { - /// Which call. - detail: String, - }, - /// The command failed: it exited non-zero or a signal ended it. - #[error("the catalog command failed: {status:?}")] - Command { - /// How the command ended. - status: ExitStatus, - }, - /// The command overran its time. - #[error("the catalog command overran its time")] - Timeout, - /// The command's output is not a catalog. - #[error("the catalog command printed no catalog: {detail}")] - Parse { - /// What is wrong with the output. - detail: String, - }, - /// The catalog holds a path from the host or the image's file system. - #[error("the catalog holds an absolute path: {path}")] - AbsolutePath { - /// The text that holds it. - path: String, - }, - /// The catalog has no canonical form. - #[error("the catalog has no digest: {detail}")] - Digest { - /// Why. - detail: String, - }, -} - -/// The command that lists the catalog inside the image, and the time it gets. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CatalogCommand { - /// The program and its arguments, run inside the container. - pub argv: Vec<String>, - /// The time the command gets; it is also the inner `timeout`. - pub timeout: Duration, -} - -impl CatalogCommand { - /// A command with the time it gets. - #[must_use] - pub const fn new(argv: Vec<String>, timeout: Duration) -> Self { - Self { argv, timeout } - } -} - -/// Captures the catalog. -pub trait CatalogProvider: Send + Sync { - /// The catalog of `image` as `cell` configures it. - /// - /// # Errors - /// [`CatalogError`] when the image cannot be listed. - fn capture<'a>( - &'a self, - image: &'a ImageRef, - cell: &'a Cell<'_>, - ) -> BoxFuture<'a, Result<Catalog, CatalogError>>; -} - -/// The digest of a catalog. -/// -/// # Errors -/// [`CatalogError::Digest`] when the catalog cannot be digested. -pub fn catalog_digest(catalog: &Catalog) -> Result<Digest, CatalogError> { - catalog - .content_digest() - .map_err(|error| CatalogError::Digest { - // BORROW: .to_string() gives the error its own text - detail: error.to_string(), - }) -} - -/// The catalog a finished command printed. -/// -/// # Errors -/// [`CatalogError::Timeout`] for a deadline or exit 124, [`CatalogError::Command`] for another -/// non-zero exit or a signal, and [`CatalogError::Parse`] for output that is not a catalog. -pub fn interpret(captured: &Captured) -> Result<Catalog, CatalogError> { - let status = captured.exit.status; - if captured.exit.ended == Ended::Deadline - || matches!(status, ExitStatus::Code { code: TIMEOUT_EXIT }) - { - return Err(CatalogError::Timeout); - } - if !matches!(status, ExitStatus::Code { code: 0 }) { - return Err(CatalogError::Command { status }); - } - let catalog = serde_json::from_slice::<Catalog>(captured.stdout.as_slice()) // BORROW: explicit .as_slice() - .map_err(|error| CatalogError::Parse { - // BORROW: .to_string() gives the error its own text - detail: error.to_string(), - })?; - refuse_absolute_paths(&catalog)?; - Ok(catalog) -} - -/// Whether `token` is an absolute path: a slash, then a segment, and either another slash or the -/// whole text. -fn is_absolute_path(token: &str, whole: bool) -> bool { - let Some(rest) = token.strip_prefix('/') else { - return false; - }; - let Some(first) = rest.chars().next() else { - return false; - }; - if first == '/' || first.is_whitespace() { - return false; - } - whole || rest.contains('/') -} - -/// The first absolute path in the strings of `value`, if any. -fn find_absolute(value: &serde_json::Value) -> Option<String> { - match value { - serde_json::Value::String(text) => { - let whole = !text.contains(char::is_whitespace); - // BORROW: .to_owned() keeps the offending text in the error - text.split_whitespace() - .find(|token| is_absolute_path(token, whole)) - .map(str::to_owned) - } - serde_json::Value::Array(items) => items.iter().find_map(find_absolute), - serde_json::Value::Object(fields) => fields.values().find_map(find_absolute), - serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => None, - } -} - -/// Refuses a catalog that holds an absolute path in any of its strings. -/// -/// # Errors -/// [`CatalogError::AbsolutePath`] with the first such text, and [`CatalogError::Digest`] when the -/// catalog cannot be read back as JSON. -pub fn refuse_absolute_paths(catalog: &Catalog) -> Result<(), CatalogError> { - let json = serde_json::to_value(catalog).map_err(|error| CatalogError::Digest { - // BORROW: .to_string() gives the error its own text - detail: error.to_string(), - })?; - match find_absolute(&json) { - Some(path) => Err(CatalogError::AbsolutePath { path }), - None => Ok(()), - } -} - -/// The provider that lists the commands inside the image. -pub struct CommandCatalogProvider { - supervisor: Arc<Supervisor>, - cli: DockerCli, - env: ClientEnv, - store_root: PathBuf, - command: CatalogCommand, -} - -impl CommandCatalogProvider { - /// A provider that runs `command` in control containers through the docker client `cli`; - /// each call keeps its record dir under `<store_root>/control`. - #[must_use] - pub const fn new( - supervisor: Arc<Supervisor>, - cli: DockerCli, - env: ClientEnv, - store_root: PathBuf, - command: CatalogCommand, - ) -> Self { - Self { - supervisor, - cli, - env, - store_root, - command, - } - } - - /// The command the provider runs. - #[must_use] - pub const fn command<'a>(&'a self) -> &'a CatalogCommand { - &self.command - } - - /// The control container of the capture. - fn spec(&self, image: &ImageRef) -> Result<ControlSpec, CatalogError> { - let unavailable = |detail: String| CatalogError::Unavailable { detail }; - let spec = CommandSpec::builder() - // BORROW: .clone() gives the spec its own argv - .argv(self.command.argv.clone()) - .build() - .map_err(|error| unavailable(error.to_string()))?; - let limits = Limits { - pids_limit: CONTROL_PIDS, - // BORROW: .to_owned() gives the limits their own text - memory: CONTROL_MEMORY.to_owned(), - cpus: CONTROL_CPUS, - }; - catalog_spec(&image.id, &limits, self.command.timeout, &spec) - .map_err(|error| unavailable(error.to_string())) - } - - /// Runs the control container with its record dir `records`. - async fn run(&self, image: &ImageRef, records: PathBuf) -> Result<Catalog, CatalogError> { - let unavailable = |detail: String| CatalogError::Unavailable { detail }; - let cli = DockerCli::with_binary( - Arc::clone(&self.supervisor), - self.cli.binary().to_path_buf(), // BORROW: the client owns its binary path - self.env.clone(), // BORROW: the client owns its environment - records, - ); - let captured = cli - .control( - &self.spec(image)?, - self.command.timeout + CLIENT_GRACE, - OUTPUT_LIMIT, - ) - .await - .map_err(|error| unavailable(format!("the command cannot run: {error}")))?; - interpret(&captured) - } - - async fn capture_one(&self, image: &ImageRef) -> Result<Catalog, CatalogError> { - let records = layout::control_dir(&self.store_root).join(format!( - "{}-{}", - std::process::id(), - CONTROL_CALLS.fetch_add(1, Ordering::Relaxed) - )); - tokio::fs::create_dir_all(&records) - .await - .map_err(|error| CatalogError::Unavailable { - detail: format!("cannot create the record dir: {error}"), - })?; - // BORROW: .clone() keeps the record dir for its removal - let outcome = self.run(image, records.clone()).await; - // The record dir is this call's own and holds only this call's record. - let _ = tokio::fs::remove_dir_all(&records).await; - outcome - } -} - -impl CatalogProvider for CommandCatalogProvider { - fn capture<'a>( - &'a self, - image: &'a ImageRef, - _cell: &'a Cell<'_>, - ) -> BoxFuture<'a, Result<Catalog, CatalogError>> { - Box::pin(self.capture_one(image)) - } -} diff --git a/crates/candler-core/src/runner/evidence/census.rs b/crates/candler-core/src/runner/evidence/census.rs index b05406fc..84887885 100644 --- a/crates/candler-core/src/runner/evidence/census.rs +++ b/crates/candler-core/src/runner/evidence/census.rs @@ -1,5 +1,4 @@ -//! The census of a run: the tools and MCP servers the agent saw at its start, as the harness's -//! driver reports them. +//! The census of a run: the tools the agent saw at its start, as the harness's driver reports them. use candler_harness::spec::{CensusSource, InitReport}; use candler_schemas::primitives::{FieldPath, NameToken}; @@ -16,12 +15,9 @@ pub enum CensusError { /// The harness reported no inventory. #[error("the harness reported no inventory")] NoInit, - /// The inventory's tool list is not a list of names, or its server list is not a list. - #[error("the inventory has no usable `{key}`")] - Malformed { - /// The name of the list. - key: &'static str, - }, + /// The inventory's tool list is not a list of names. + #[error("the inventory has no usable `tools`")] + Malformed, /// A census value could not be built. #[error("a census value is not valid: {detail}")] Value { @@ -55,39 +51,26 @@ const fn source_label(source: CensusSource) -> Option<&'static str> { } } -/// The census values of a run, from the inventory its harness reported: `census.tools` and, when -/// the source sees servers, `census.mcp_servers`, as the harness lists them, and -/// `census.init_tools`, the tool names sorted and deduplicated. The server list never enters -/// `census.init_tools`. An inventory the gateway or a collected command observed also records -/// `census.source`, so that the verdict never takes it for the harness's own. +/// The census values of a run, from the inventory its harness reported: `census.tools`, as the +/// harness lists them, and `census.init_tools`, the tool names sorted and deduplicated. An +/// inventory the gateway or a collected command observed also records `census.source`, so that the +/// verdict never takes it for the harness's own. /// /// # Errors /// [`CensusError::NoInit`] when the harness reported no inventory, which records nothing, and -/// [`CensusError::Malformed`] when the inventory's `tools` is not a list of names or its -/// `mcp_servers` is not a list. +/// [`CensusError::Malformed`] when the inventory's `tools` is not a list of names. pub fn census(init: Option<&InitReport>) -> Result<Vec<MeasuredValue>, CensusError> { let init = init.ok_or(CensusError::NoInit)?; - let tools = init - .tools - .as_array() - .ok_or(CensusError::Malformed { key: "tools" })?; + let tools = init.tools.as_array().ok_or(CensusError::Malformed)?; let mut names: Vec<String> = Vec::new(); for tool in tools { // BORROW: `.as_str()` borrows the text of the JSON string - let name = tool - .as_str() - .ok_or(CensusError::Malformed { key: "tools" })?; + let name = tool.as_str().ok_or(CensusError::Malformed)?; names.push(name.to_owned()); // BORROW: .to_owned() gives the sorted list its own names } names.sort(); names.dedup(); let mut values = vec![measured("census.tools", init.tools.clone())?]; // BORROW: .clone() keeps the harness's list - if let Some(servers) = &init.mcp_servers { - if !servers.is_array() { - return Err(CensusError::Malformed { key: "mcp_servers" }); - } - values.push(measured("census.mcp_servers", servers.clone())?); // BORROW: .clone() keeps the harness's list - } values.push(measured( "census.init_tools", Value::Array(names.into_iter().map(Value::String).collect()), diff --git a/crates/candler-core/src/runner/evidence/mod.rs b/crates/candler-core/src/runner/evidence/mod.rs index e185ddac..e76552e3 100644 --- a/crates/candler-core/src/runner/evidence/mod.rs +++ b/crates/candler-core/src/runner/evidence/mod.rs @@ -1,7 +1,6 @@ -//! The evidence a run leaves: its catalog, its census, the leak check, its session measures and +//! The evidence a run leaves: its census, the leak check, its session measures and //! its tree. -pub mod catalog; pub mod census; pub mod leak; mod measure; @@ -23,6 +22,8 @@ pub struct OutputDigest { pub path: String, /// The digest of the content. pub digest: Digest, + /// Whether the file has an execute bit for the owner, the group or others. + pub executable: bool, } /// A file the run was given and its digest. diff --git a/crates/candler-core/src/runner/evidence/tree.rs b/crates/candler-core/src/runner/evidence/tree.rs index 4afd1040..0ec933d3 100644 --- a/crates/candler-core/src/runner/evidence/tree.rs +++ b/crates/candler-core/src/runner/evidence/tree.rs @@ -76,7 +76,11 @@ pub fn tree_json(evidence: &Evidence, inputs: &Inputs) -> Result<RunTree, Eviden path: output.path.clone(), // BORROW: .clone() gives the error its own text detail: error.to_string(), // BORROW: .to_string() gives owned text })?; - builder = builder.entry(TreeEntry::file(path, output.digest.clone(), false)); // BORROW: .clone() copies the digest + builder = builder.entry(TreeEntry::file( + path, + output.digest.clone(), // BORROW: .clone() copies the digest + output.executable, + )); } builder .build() diff --git a/crates/candler-core/src/runner/exec/gather.rs b/crates/candler-core/src/runner/exec/gather.rs index fd0b8718..e1a24d9a 100644 --- a/crates/candler-core/src/runner/exec/gather.rs +++ b/crates/candler-core/src/runner/exec/gather.rs @@ -2,7 +2,9 @@ //! spent, and what the reader made of its output. use std::collections::BTreeMap; +use std::fs; use std::io; +use std::os::unix::fs::PermissionsExt as _; use std::path::Path; use candler_harness::reader::{FrameIn, ReaderError, TraceReader}; @@ -312,9 +314,10 @@ pub fn glob_regex(glob: &str) -> Result<Regex, regex::Error> { Regex::new(&pattern) } -/// The files under `root` that the file specs pick, by relative path, each with its digest. A -/// spec whose glob starts with `!` leaves out what it matches. Links are not followed. Command -/// specs name streams the harness collects itself and pick no file. +/// The files under `root` that the file specs pick, by relative path, each with its digest and +/// whether it has an execute bit. A spec whose glob starts with `!` leaves out what it matches. +/// Links are not followed. Command specs name streams the harness collects itself and pick no +/// file. /// /// # Errors /// An I/O error when the tree cannot be read, and an invalid-input error for a bad glob or a @@ -336,9 +339,11 @@ pub fn collect_files(root: &Path, specs: &[CollectSpec]) -> io::Result<Vec<Outpu let path = entry.rel.as_str(); if keep.iter().any(|re| re.is_match(path)) && !drop.iter().any(|re| re.is_match(path)) { let digest = digest_of_file(&entry.abs).map_err(|e| io::Error::other(e.to_string()))?; + let executable = fs::metadata(&entry.abs)?.permissions().mode() & 0o111 != 0; found.push(OutputDigest { path: path.to_owned(), // BORROW: the list owns its paths digest, + executable, }); } } diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index 0c3ffc34..80cf4d71 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -672,12 +672,17 @@ async fn drive( let mut offline: Option<candler_schemas::primitives::NameVersion> = None; let mut offline_sessions = Vec::new(); let mut offline_events = Vec::new(); + // The servers the cell declares: an export that spells a call `<server>_<tool>` is read + // against them. + let declared: Vec<String> = candler_harness::mcp::servers(&view)? + .map(|servers| servers.into_keys().collect()) + .unwrap_or_default(); for item in collected { let Ok(bytes) = item.output else { collect_ok = false; continue; }; - match rt.driver.offline_reader(&item.name) { + match rt.driver.offline_reader(&item.name, &declared) { Some(reader) => { let Ok(read) = read_stream(&frames, &item.name, &bytes, reader) else { collect_ok = false; diff --git a/crates/candler-core/src/runner/plan.rs b/crates/candler-core/src/runner/plan.rs index 64a6da72..085d8467 100644 --- a/crates/candler-core/src/runner/plan.rs +++ b/crates/candler-core/src/runner/plan.rs @@ -11,7 +11,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use candler_harness::driver::{DriverError, HarnessDriver}; -use candler_harness::spec::Cell; +use candler_harness::spec::{AgentSetting, Cell}; use candler_schemas::distinct::first_clash; use candler_schemas::execution::check_replicates; @@ -19,6 +19,7 @@ use candler_schemas::execution::{ Comparable, Deviation, ExecutionError, ExperimentFile, Factor, Integrity, Level, RunManifest, SecretPresence, TreatmentRef, experiment_digest, }; +use candler_schemas::field_path; use candler_schemas::primitives::{Digest, FieldPath, JobId, RunKey, SecretName}; use candler_schemas::values::{JsonValue, ResolvedValue, SourceEntry, ValueSource}; use rustix::fs::{FlockOperation, flock}; @@ -28,6 +29,7 @@ use serde_json::Value; use crate::jobs::dir::JobDir; use crate::jobs::lock::{JobLock, LockState}; use crate::resolve::layers::{Resolution, is_setting}; +use crate::resolve::paths::refuse_unanswered; use crate::resolve::steps::egress::{self, EgressRefusal}; use crate::resolve::steps::plugin_environment::{plugin_egress, unite_egress}; use crate::resolve::steps::session::{self, SessionRefusal}; @@ -153,6 +155,22 @@ pub fn experiment_of<'a>( Ok(experiment_digest(digests.as_slice())) } +/// Builds every cell of `file` under `levels` and has `driver` check each one, so a value a cell +/// cannot hold (an absolute path, a malformed MCP server, a setting the harness cannot honour) is +/// refused before any run. +/// +/// # Errors +/// The [`PlanError`] of the first cell that cannot be built or that the driver refuses. +pub fn check_cells<'a>( + file: &ExperimentFile, + levels: impl Into<Levels<'a>>, + driver: &dyn HarnessDriver, // TRAIT_OBJECT: the registry's driver, selected at run time +) -> Result<(), PlanError> { + let levels = levels.into(); + levels.replicates(file)?; + fresh_cells(file, &levels, Some(driver)).map(drop) +} + /// A deviation as `path {stored: <value>, observed: <value>}`, for a message; a value that was /// not recorded reads `absent`. A deviation holds names and digests, never a secret. fn describe(deviation: &Deviation) -> String { @@ -242,6 +260,22 @@ pub enum PlanError { /// The path of the setting the factor varies. path: String, }, + /// The count of replicates is not a count the runner can run. + #[error("{source}")] + Replicates { + /// Why the count is refused. + #[source] + source: ExecutionError, + }, + /// The setting `replicates` that the experiment file's `[fixed]` gives differs from the file's + /// own `replicates`. + #[error("replicates is {fixed} in [fixed] and {file} in the experiment file; write it once")] + ReplicatesConflict { + /// The count `[fixed]` gives. + fixed: u32, + /// The count the file's own `replicates` gives. + file: u32, + }, /// A cell of the experiment cannot be built from the resolution. #[error("a cell cannot be built: {source}")] Cell { @@ -353,19 +387,41 @@ impl<'a> Levels<'a> { /// The replicates of each cell: the setting `replicates` of the first level when the /// resolution holds one, else `file`'s own count. A setting is no part of a cell, so the - /// levels agree on it. - fn replicates(&self, file: &ExperimentFile) -> u32 { - self.get(0) - .and_then(|resolution| { - resolution - .settings - .iter() - .find(|setting| setting.path().as_str() == "replicates") // BORROW: explicit .as_str() - }) - .and_then(|setting| setting.value()) + /// levels agree on it. A setting that is no count, or that the file's `[fixed]` gives and + /// differs from the file's own count, is refused. + /// + /// # Errors + /// [`PlanError::Replicates`] when the setting is not a whole count from 1 to 4294967295, and + /// [`PlanError::ReplicatesConflict`] when `[fixed]` and the file's own count differ. + fn replicates(&self, file: &ExperimentFile) -> Result<u32, PlanError> { + let Some(resolution) = self.get(0) else { + return Ok(file.replicates()); + }; + let Some(setting) = resolution + .settings + .iter() + .find(|setting| setting.path().as_str() == "replicates") + // BORROW: explicit .as_str() + else { + return Ok(file.replicates()); + }; + let count = setting + .value() .and_then(|value| value.as_value().as_u64()) - .and_then(|count| check_replicates(count).ok()) - .unwrap_or_else(|| file.replicates()) + .ok_or(PlanError::Replicates { + source: ExecutionError::ReplicatesNotCount, + })?; + let count = check_replicates(count).map_err(|source| PlanError::Replicates { source })?; + let from_file = resolution.sources.iter().any(|entry| { + entry.path() == setting.path() && matches!(entry.source(), ValueSource::ExperimentFile) + }); + if from_file && count != file.replicates() { + return Err(PlanError::ReplicatesConflict { + fixed: count, + file: file.replicates(), + }); + } + Ok(count) } } @@ -523,6 +579,37 @@ fn setting_in(prefix: &str, table: &serde_json::Map<String, Value>) -> Option<St }) } +/// The values of `values` with `codemode` written for each server of `mcp.servers` that does not +/// set it, as the value [`McpServer`](candler_schemas::servers::McpServer) reads: the cell records +/// what Candler installs, so a server that leaves `codemode` out and one that sets it to `false` +/// are one cell. +/// +/// # Errors +/// [`PlanError::Driver`] when the reader of `mcp.servers` refuses an entry, or a server key is no +/// field-path segment and so cannot hold a value. +fn fill_codemode(values: &mut Vec<ResolvedValue>) -> Result<(), PlanError> { + let Some(servers) = candler_harness::mcp::by_key(&Cell::new(values.as_slice()))? else { + return Ok(()); + }; + for (key, server) in servers { + let path = format!("{}.{key}.codemode", candler_harness::mcp::SERVERS) + .parse::<FieldPath>() + .map_err(|error| DriverError::InvalidValue { + path: field_path!("mcp.servers"), + detail: format!("the key `{key}` {error}"), + })?; + if values.iter().any(|held| *held.path() == path) { + continue; + } + let held = + JsonValue::new(Value::Bool(server.codemode)).map_err(|error| PlanError::Cell { + source: error.into(), + })?; + values.push(ResolvedValue::recorded(path, held)); + } + Ok(()) +} + /// Builds every cell of `file`, each under the resolution of its treatment level. A path the file /// writes that [`is_setting`] names is a setting of the run, which the resolution holds, and no /// value of a cell; the treatment level reaches the cell through its resolution. @@ -537,7 +624,8 @@ fn fresh_cells<'r>( levels: &Levels<'r>, driver: Option<&dyn HarnessDriver>, ) -> Result<Vec<FreshCell<'r>>, PlanError> { - let session_capable = driver.map(|driver| driver.capabilities().session); + let session_capable = + driver.map(|driver| !driver.answer(AgentSetting::SessionMode).is_refused()); if let Some(path) = file.factors().iter().find_map(setting_of_factor) { return Err(PlanError::SettingAsFactor { path }); } @@ -627,6 +715,7 @@ fn fresh_cells<'r>( })?; values.push(ResolvedValue::recorded(path, value)); } + fill_codemode(&mut values)?; let canonical = { let at = |path: &str| { values @@ -672,7 +761,9 @@ fn fresh_cells<'r>( } if let Some(driver) = driver { for cell in &cells { - driver.check_settings(&Cell::new(cell.comparable.values()))?; + let view = Cell::new(cell.comparable.values()); + refuse_unanswered(driver, &view)?; + driver.check_settings(&view)?; } } Ok(cells) @@ -1185,7 +1276,7 @@ pub fn plan_runs<'a>( let mut sealed = Vec::new(); for (cell, replicate) in run_order( per_cell.len(), - levels.replicates(file), + levels.replicates(file)?, seed_of(&experiment), ) { let Some((digest, pinned, deviations)) = per_cell.get(cell) else { diff --git a/crates/candler-core/src/runner/refusal.rs b/crates/candler-core/src/runner/refusal.rs index bc253b5e..0923de57 100644 --- a/crates/candler-core/src/runner/refusal.rs +++ b/crates/candler-core/src/runner/refusal.rs @@ -8,7 +8,6 @@ use std::error::Error; use crate::refusal::wrapper_table; -use crate::runner::evidence::catalog::CatalogError; use crate::runner::evidence::census::CensusError; use crate::runner::evidence::tree::EvidenceError; use crate::runner::exec::cell::ExecError; @@ -24,11 +23,12 @@ fn no_path<E>(_error: &E) -> Option<String> { /// The pointer of the place in a document where a [`PlanError`] sits, if it names one. fn plan_error_path(error: &PlanError) -> Option<String> { match error { - PlanError::Cell { source } => Refusal::path(source), + PlanError::Cell { source } | PlanError::Replicates { source } => Refusal::path(source), PlanError::Session(inner) => Refusal::path(inner), PlanError::Egress(inner) => Refusal::path(inner), PlanError::Driver(inner) => Refusal::path(inner), PlanError::SettingAsFactor { .. } => Some(pointer_of(["factors"])), + PlanError::ReplicatesConflict { .. } => Some(pointer_of(["replicates"])), PlanError::NameCollision { .. } | PlanError::ExperimentLocked | PlanError::Changed(..) @@ -98,6 +98,13 @@ wrapper_table! { "A factor varies a setting, which no cell can vary; the setting belongs in `[fixed]`.", "The `factors` array of the experiment file; a verb that has read the file narrows it to the `path` of the factor.", ), + Replicates { source } => delegate(source, Side::Experiment), + ReplicatesConflict { .. } => row( + "experiment.replicates_conflict", + Side::Experiment, + "`replicates` in `[fixed]` differs from the experiment file's own `replicates`; write the count once.", + "The `replicates` key.", + ), Cell { source } => delegate(source, Side::Candler), Store { .. } => row( "candler.internal", @@ -122,46 +129,6 @@ wrapper_table! { Supervise (inner) => delegate(inner, Side::Environment), } -refusal_table! { - CatalogError, path = no_path; - Unavailable { .. } => row( - "candler.internal", - Side::Candler, - "Catalog capture is not wired in this build.", - "-", - ), - Command { .. } => row( - "runner.catalog_command_failed", - Side::Environment, - "The command that prints the tool catalog exited non-zero or was ended by a signal.", - "-", - ), - Timeout { .. } => row( - "runner.catalog_timeout", - Side::Environment, - "The command that prints the tool catalog overran its time.", - "-", - ), - Parse { .. } => row( - "runner.catalog_unreadable", - Side::Environment, - "The output of the catalog command is not a tool catalog.", - "-", - ), - AbsolutePath { .. } => row( - "candler.internal", - Side::Candler, - "The catalog holds a path from the host or the image's file system.", - "-", - ), - Digest { .. } => row( - "candler.internal", - Side::Candler, - "The catalog has no canonical form.", - "-", - ), -} - refusal_table! { CensusError, path = no_path; NoInit { .. } => row( @@ -203,10 +170,9 @@ refusal_table! { /// The rows of every coded error of this module, in the order of the types. #[must_use] pub(crate) fn catalog() -> Vec<CatalogRow> { - let tables: [&'static [CatalogRow]; 5] = [ + let tables: [&'static [CatalogRow]; 4] = [ <PlanError as Catalogued>::rows(), <ExecError as Catalogued>::rows(), - <CatalogError as Catalogued>::rows(), <CensusError as Catalogued>::rows(), <EvidenceError as Catalogued>::rows(), ]; @@ -237,7 +203,9 @@ fn exec_answer(error: &ExecError) -> &dyn Refusal { /// code, side and path, and every other variant with its own. fn plan_answer(error: &PlanError) -> &dyn Refusal { match error { - PlanError::Cell { source } => crate::refusal::through(source, error), + PlanError::Cell { source } | PlanError::Replicates { source } => { + crate::refusal::through(source, error) + } PlanError::Driver(inner) => crate::refusal::through(inner, error), PlanError::NameCollision { .. } | PlanError::ExperimentLocked @@ -246,6 +214,7 @@ fn plan_answer(error: &PlanError) -> &dyn Refusal { | PlanError::StoredCellAmbiguous { .. } | PlanError::AttemptOverflow { .. } | PlanError::SettingAsFactor { .. } + | PlanError::ReplicatesConflict { .. } | PlanError::Session(..) | PlanError::Egress(..) | PlanError::Store { .. } @@ -265,14 +234,9 @@ pub(crate) fn coded<'e>(error: &'e (dyn Error + 'static)) -> Option<&'e dyn Refu .map(exec_answer) .or_else(|| { error - .downcast_ref::<CatalogError>() + .downcast_ref::<CensusError>() .map(as_refusal) - .or_else(|| { - error - .downcast_ref::<CensusError>() - .map(as_refusal) - .or_else(|| error.downcast_ref::<EvidenceError>().map(as_refusal)) - }) + .or_else(|| error.downcast_ref::<EvidenceError>().map(as_refusal)) }) }) } diff --git a/crates/candler-core/tests/fixtures/harness_baseline/census.json b/crates/candler-core/tests/fixtures/harness_baseline/census.json index 958e6dc3..bfde840c 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/census.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/census.json @@ -25,7 +25,6 @@ "Workflow", "Write" ], - "census.mcp_servers": [], "census.tools": [ "Task", "Bash", @@ -78,7 +77,6 @@ "Workflow", "Write" ], - "census.mcp_servers": [], "census.tools": [ "Task", "Bash", @@ -138,7 +136,6 @@ "Workflow", "Write" ], - "census.mcp_servers": [], "census.tools": [ "Task", "Bash", @@ -205,7 +202,6 @@ "Workflow", "Write" ], - "census.mcp_servers": [], "census.tools": [ "Task", "Bash", @@ -272,7 +268,6 @@ "Workflow", "Write" ], - "census.mcp_servers": [], "census.tools": [ "Task", "Bash", @@ -311,7 +306,6 @@ "Agent", "Bash" ], - "census.mcp_servers": [], "census.tools": [ "Bash", "Agent" @@ -322,7 +316,6 @@ "Agent", "Bash" ], - "census.mcp_servers": [], "census.tools": [ "Bash", "Agent" @@ -333,7 +326,6 @@ "Agent", "Bash" ], - "census.mcp_servers": [], "census.tools": [ "Bash", "Agent" diff --git a/crates/candler-core/tests/fixtures/harness_baseline/comparable/cont_train.json b/crates/candler-core/tests/fixtures/harness_baseline/comparable/cont_train.json index f0cab5d0..f4d0abe3 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/comparable/cont_train.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/comparable/cont_train.json @@ -11,12 +11,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -40,7 +34,7 @@ }, { "path": "plan.model", - "value": "claude-sonnet-4-6" + "value": "claude-haiku-4-5" }, { "path": "plan.prompt_domain_name", @@ -72,12 +66,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -101,7 +89,7 @@ }, { "path": "plan.model", - "value": "claude-haiku-4-5" + "value": "claude-sonnet-5" }, { "path": "plan.prompt_domain_name", @@ -133,12 +121,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -162,7 +144,7 @@ }, { "path": "plan.model", - "value": "claude-sonnet-5" + "value": "claude-haiku-4-5" }, { "path": "plan.prompt_domain_name", @@ -194,12 +176,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -239,7 +215,7 @@ }, { "path": "plan.skill_version", - "value": "htn-creator@0.2.5" + "value": "htn-creator@v0.2.3" } ] }, @@ -255,12 +231,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -284,7 +254,7 @@ }, { "path": "plan.model", - "value": "claude-sonnet-5" + "value": "claude-sonnet-4-6" }, { "path": "plan.prompt_domain_name", @@ -300,7 +270,7 @@ }, { "path": "plan.skill_version", - "value": "htn-creator@0.2.5" + "value": "htn-creator@0.2.4" } ] }, @@ -316,12 +286,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -345,7 +309,7 @@ }, { "path": "plan.model", - "value": "claude-sonnet-4-6" + "value": "claude-sonnet-5" }, { "path": "plan.prompt_domain_name", @@ -361,7 +325,7 @@ }, { "path": "plan.skill_version", - "value": "htn-creator@0.2.4" + "value": "htn-creator@0.2.6" } ] }, @@ -377,12 +341,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -438,12 +396,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -467,7 +419,7 @@ }, { "path": "plan.model", - "value": "claude-sonnet-5" + "value": "claude-sonnet-4-6" }, { "path": "plan.prompt_domain_name", @@ -483,7 +435,7 @@ }, { "path": "plan.skill_version", - "value": "htn-creator@0.2.6" + "value": "htn-creator@0.2.5" } ] }, @@ -499,12 +451,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -560,12 +506,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -589,7 +529,7 @@ }, { "path": "plan.model", - "value": "claude-haiku-4-5" + "value": "claude-sonnet-5" }, { "path": "plan.prompt_domain_name", @@ -621,12 +561,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -666,7 +600,7 @@ }, { "path": "plan.skill_version", - "value": "htn-creator@v0.2.3" + "value": "htn-creator@0.2.4" } ] }, @@ -682,12 +616,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -727,7 +655,7 @@ }, { "path": "plan.skill_version", - "value": "htn-creator@0.2.4" + "value": "htn-creator@0.2.5" } ] } diff --git a/crates/candler-core/tests/fixtures/harness_baseline/comparable/run_plan_experiment.json b/crates/candler-core/tests/fixtures/harness_baseline/comparable/run_plan_experiment.json index f697bebc..8f861d4d 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/comparable/run_plan_experiment.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/comparable/run_plan_experiment.json @@ -11,12 +11,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -36,7 +30,7 @@ }, { "path": "model.id", - "value": "m2" + "value": "m1" } ] }, @@ -52,12 +46,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -77,7 +65,7 @@ }, { "path": "model.id", - "value": "m1" + "value": "m2" } ] } diff --git a/crates/candler-core/tests/fixtures/harness_baseline/comparable/settings_experiment.json b/crates/candler-core/tests/fixtures/harness_baseline/comparable/settings_experiment.json index a5e615bd..7a36fa8b 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/comparable/settings_experiment.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/comparable/settings_experiment.json @@ -11,12 +11,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" @@ -64,12 +58,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" diff --git a/crates/candler-core/tests/fixtures/harness_baseline/comparable/smoke_v2.json b/crates/candler-core/tests/fixtures/harness_baseline/comparable/smoke_v2.json index dbc2103b..443a176c 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/comparable/smoke_v2.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/comparable/smoke_v2.json @@ -11,12 +11,6 @@ "version": "2.1.311" }, "inputs": [], - "snapshots": [ - { - "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kind": "catalog" - } - ], "treatment": { "commit": "1111111111111111111111111111111111111111", "name": "htn" diff --git a/crates/candler-core/tests/it/guard_census_gateway.rs b/crates/candler-core/tests/it/guard_census_gateway.rs index 4af9d3da..f4a3edcb 100644 --- a/crates/candler-core/tests/it/guard_census_gateway.rs +++ b/crates/candler-core/tests/it/guard_census_gateway.rs @@ -163,12 +163,7 @@ fn census_gateway_run_records_the_first_request_with_tools_or_nothing() { .replace(NO_TOOLS_RUN, LOG_RUN) .replace("swap", NO_TOOLS_RUN); let none = run(&bare, |_, _| {}); - for path in [ - "census.tools", - "census.init_tools", - "census.source", - "census.mcp_servers", - ] { + for path in ["census.tools", "census.init_tools", "census.source"] { assert_eq!(none.measured(path), None, "{path} of a run with no tools"); } assert!(none.raw("gateway_census").is_some(), "the stream is kept"); diff --git a/crates/candler-core/tests/it/guard_container_e2e/control_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/control_e2e.rs index 0132f10b..0fbc4bfc 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/control_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/control_e2e.rs @@ -5,7 +5,6 @@ use std::time::Duration; use candler_core::isolation::container::exec::collect_spec; use candler_core::isolation::container::mounts::{MountMode, MountSpec}; -use candler_core::isolation::container::run::catalog_spec; use candler_core::isolation::control::outcome; use candler_core::isolation::docker::{ClientEnv, DockerCli}; use candler_core::isolation::driver::DockerDriver as _; @@ -42,7 +41,7 @@ fn command(argv: &[&str]) -> CommandSpec { } /// Guards: R01 §Process supervision (control containers) — each kind of control container the -/// core builds, the harness version probe, the package probe, the catalog capture and the collect +/// core builds, the harness version probe, the package probe and the collect /// of a run's files, runs on the real agent base image, built through `DockerImageService::base`, /// reads what its caller put there, and gets a home the read-only root leaves writable. /// Oracle: the image's own `candler.cc_version` label as docker reports it, the distribution @@ -140,21 +139,11 @@ async fn control_each_kind_runs_on_the_real_base() { "the distribution that provides `pip`" ); - // The catalog capture, over the limits its caller gives. let limits = Limits { pids_limit: 64, memory: String::from("512m"), cpus: 1.0, }; - let spec = catalog_spec( - &base.id, - &limits, - Duration::from_secs(20), - &command(&["sh", "-c", "echo catalog-ran"]), - ) - .expect("a catalog spec"); - let printed = outcome_of(cli.control(&spec, deadline, 4096).await).expect("the capture ran"); - assert_eq!(String::from_utf8_lossy(&printed).trim(), "catalog-ran"); // The collect reads what the run's mounts hold, as the engine's user. let project = scratch.path().join("project"); diff --git a/crates/candler-core/tests/it/guard_container_record.rs b/crates/candler-core/tests/it/guard_container_record.rs index 795fda37..d955aee5 100644 --- a/crates/candler-core/tests/it/guard_container_record.rs +++ b/crates/candler-core/tests/it/guard_container_record.rs @@ -798,7 +798,8 @@ fn harness_census_and_end_come_from_the_drivers_live_reader() { ); assert_eq!( measured("census.mcp_servers"), - Some(json!([{"name": "s", "status": "connected"}])) + None, + "the census names no server" ); assert_eq!(measured("run.num_turns"), Some(json!(2))); assert_eq!(measured("run.cost_usd"), Some(json!(0.25))); diff --git a/crates/candler-core/tests/it/guard_container_run.rs b/crates/candler-core/tests/it/guard_container_run.rs index f2072b03..3ff4e095 100644 --- a/crates/candler-core/tests/it/guard_container_run.rs +++ b/crates/candler-core/tests/it/guard_container_run.rs @@ -8,9 +8,7 @@ use std::time::Duration; use candler_core::isolation::container::exec::collect_spec; use candler_core::isolation::container::mounts::{MountMode, MountSpec}; -use candler_core::isolation::container::run::{ - RunArgvError, build_start_request, catalog_spec, create_argv, -}; +use candler_core::isolation::container::run::{RunArgvError, build_start_request, create_argv}; use candler_core::isolation::control::ControlSpec; use candler_core::isolation::docker::{Call, ClientEnv, DockerCli}; use candler_core::isolation::driver::DockerDriver as _; @@ -158,7 +156,7 @@ fn plan_under(root: &std::path::Path) -> ContainerPlan { planned } -/// The six control kinds, each built the way its caller builds it. +/// The five control kinds, each built the way its caller builds it. fn kinds(root: &std::path::Path) -> Vec<Kind> { let image = ImageRef { id: ImageId(String::from("sha256:abc")), @@ -166,11 +164,6 @@ fn kinds(root: &std::path::Path) -> Vec<Kind> { }; let env = [(String::from("HOME"), String::from("/tmp/home"))]; let probe = vec![String::from("claude"), String::from("--version")]; - let limits = Limits { - pids_limit: 64, - memory: String::from("512m"), - cpus: 1.0, - }; let args = |spec: ControlSpec| spec.args(); vec![ Kind { @@ -211,24 +204,6 @@ fn kinds(root: &std::path::Path) -> Vec<Kind> { cpus: None, detached: false, }, - Kind { - name: "catalog capture", - args: args( - catalog_spec( - &image.id, - &limits, - Duration::from_secs(5), - &command(Vec::new()), - ) - .expect("a catalog spec"), - ), - network: Some("none"), - tmpfs: &["/tmp:rw,noexec,nosuid,size=256m"], - pids: "64", - memory: "512m", - cpus: Some("1"), - detached: false, - }, Kind { name: "collect", args: args( @@ -262,7 +237,7 @@ fn kinds(root: &std::path::Path) -> Vec<Kind> { /// Guards: R01 §Process supervision (control containers) — every control container removes /// itself, wears `candler.role=control` and no job label, has a read-only root, no capabilities /// and no new privileges, and keeps its own network and limits: the probes 64 pids and 256m, the -/// compile 256 pids and 2g on the bridge, the catalog and the collect their caller's limits with a +/// compile 256 pids and 2g on the bridge, the collect its caller's limits with a /// cpu cap, and the fake model no network flag. /// Oracle: the flags of each kind's argv at 18142ec, typed here by hand. /// Bite: a flag dropped from the shared builder (`--cap-drop`, `--read-only`, the label, `--rm`), diff --git a/crates/candler-core/tests/it/guard_declared_inputs.rs b/crates/candler-core/tests/it/guard_declared_inputs.rs index a1868b45..206658ce 100644 --- a/crates/candler-core/tests/it/guard_declared_inputs.rs +++ b/crates/candler-core/tests/it/guard_declared_inputs.rs @@ -370,8 +370,8 @@ use candler_core::supervise::stop::Exit; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ - Capabilities, Cell, CollectSpec, CommandSpec, HarnessId, Observed, ProcessExit, StopSpec, - Workspace, + AgentSetting, Answer, Cell, CollectSpec, CommandSpec, DriverFact, HarnessId, Observed, + ProcessExit, StopSpec, Workspace, }; use candler_schemas::primitives::{ContainerId, Marker, Timestamp}; use candler_schemas::raw::StreamName; @@ -566,8 +566,12 @@ impl HarnessDriver for Collecting { fn parse_version(&self, output: &[u8]) -> Result<semver::Version, DriverError> { self.0.parse_version(output) } - fn capabilities(&self) -> Capabilities { - self.0.capabilities() + fn answer(&self, setting: AgentSetting) -> Answer { + self.0.answer(setting) + } + + fn fact(&self, fact: DriverFact) -> Answer { + self.0.fact(fact) } fn gateway(&self) -> Option<candler_harness::spec::GatewayEnv> { self.0.gateway() @@ -584,8 +588,12 @@ impl HarnessDriver for Collecting { fn live_reader(&self) -> Option<Box<dyn TraceReader>> { self.0.live_reader() } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { - self.0.offline_reader(stream) + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { + self.0.offline_reader(stream, servers) } fn classify_exit(&self, exit: &ProcessExit, sessions: &[Session]) -> EndedBy { self.0.classify_exit(exit, sessions) @@ -1097,6 +1105,7 @@ fn declared_input_empty_match_is_no_leak_and_a_real_copy_is() { outputs: vec![OutputDigest { path: "copy.txt".to_owned(), digest: sha.parse().expect("a digest"), + executable: false, }], tree: candler_schemas::execution::RunTree::builder() .build() diff --git a/crates/candler-core/tests/it/guard_egress_setting.rs b/crates/candler-core/tests/it/guard_egress_setting.rs index 9fa0220c..772e7f67 100644 --- a/crates/candler-core/tests/it/guard_egress_setting.rs +++ b/crates/candler-core/tests/it/guard_egress_setting.rs @@ -484,10 +484,10 @@ fn egress_of(values: &[(String, Value)]) -> Option<Value> { /// The digest of the cell whose egress is `["a.org:443", "pypi.org:443"]`. const LISTED_DIGEST: &str = - "sha256:9a1cd9a1ee0c360c0dde88f8b50418136d40a56c301bd0a6a39110787ec5a33f"; + "sha256:7170d82c4a0f432e5dc8cd1af3cec9add7d9ed6b47af5b2b3aa37b0229cccdb8"; /// The digest of the cell of the plain experiment (no egress value). -const BASE_DIGEST: &str = "sha256:ea0e539ae84ca8476df9f8f73b3dbbb90ef2c7f173a4f636fb5e752b785254cf"; +const BASE_DIGEST: &str = "sha256:1dfb579fae92eccda7769a2dae62bea2e444db760a33cea1db92867e7bd05129"; /// Guards: R06 D3 — a cell with no egress value keeps its digest, and an empty list is an absent /// value (no allowlist, no proxy), so it digests as one. diff --git a/crates/candler-core/tests/it/guard_harness_facts.rs b/crates/candler-core/tests/it/guard_harness_facts.rs index 6437f953..ca826df6 100644 --- a/crates/candler-core/tests/it/guard_harness_facts.rs +++ b/crates/candler-core/tests/it/guard_harness_facts.rs @@ -21,9 +21,9 @@ use candler_core::supervise::spawn::FrameObserver as _; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ - BudgetCaps, Capabilities, Cell, CensusSource, CollectSpec, CommandSpec, EnvEntry, GatewayEnv, - HarnessId, InitReport, Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, - StopSpec, Workspace, + AgentSetting, Answer, Cell, CensusSource, CollectSpec, CommandSpec, DriverFact, EnvEntry, + GatewayEnv, HarnessId, InitReport, Observed, Prepared, ProcessExit, StateKind, StatePath, + StopSignal, StopSpec, Workspace, }; use candler_harness_claude_code::ClaudeCodeReader; use candler_harness_claude_code::driver::ClaudeCodeDriver; @@ -141,11 +141,34 @@ impl HarnessDriver for FakeHarness { }) } - fn capabilities(&self) -> Capabilities { - Capabilities::builder() - .graceful_stop(true) - .budgets(BudgetCaps::new(false, false)) - .build() + fn answer(&self, setting: AgentSetting) -> Answer { + let refused: &[AgentSetting] = &[ + AgentSetting::SessionMode, + AgentSetting::TurnBudget, + AgentSetting::CostBudget, + ]; + if refused.contains(&setting) { + Answer::Refused { + reason: "test stand-in", + } + } else { + Answer::Mapped { + construct: "test stand-in", + } + } + } + + fn fact(&self, fact: DriverFact) -> Answer { + let held: &[DriverFact] = &[DriverFact::GracefulStop]; + if held.contains(&fact) { + Answer::Mapped { + construct: "test stand-in", + } + } else { + Answer::Refused { + reason: "test stand-in", + } + } } fn gateway(&self) -> Option<GatewayEnv> { @@ -197,7 +220,11 @@ impl HarnessDriver for FakeHarness { } // TRAIT_OBJECT: the core selects readers at runtime - fn offline_reader(&self, _stream: &StreamName) -> Option<Box<dyn TraceReader>> { + fn offline_reader( + &self, + _stream: &StreamName, + _servers: &[String], + ) -> Option<Box<dyn TraceReader>> { None } @@ -676,7 +703,7 @@ fn harness_env_state_paths_are_in_writable_mounts() { // H3: the census. // --------------------------------------------------------------------------------------------- -/// Guards: R01 §Run manifest (`census.*`, `run.usage`, `run.cost_usd`, `run.num_turns`) — the three +/// Guards: R01 §Run manifest (`census.*`, `run.usage`, `run.cost_usd`, `run.num_turns`) — the two /// census values and the three run totals of every recorded Claude Code stream are the ones /// cf3de30 recorded, byte for byte. /// Oracle: `census.json` and `run_totals.json`, recorded at cf3de30 from the same streams. @@ -721,8 +748,8 @@ fn harness_census_equals_cf3de30_on_every_fixture() { } /// The inventory a source reported, as the driver's reader builds it. -fn inventory(tools: Value, servers: Option<Value>, source: CensusSource) -> InitReport { - InitReport::new(tools, servers, source).expect("an inventory") +fn inventory(tools: Value, source: CensusSource) -> InitReport { + InitReport::new(tools, source).expect("an inventory") } /// The paths and values of `census` over `init`. @@ -742,26 +769,19 @@ type CensusRow = ( ); /// Guards: R01 §Run manifest (`census.*`) — an inventory records what its source saw: from a -/// source that sees no servers, `census.tools` and `census.init_tools` only, never an empty server -/// list, and the source that saw them; from the harness's own init, the three values in the order -/// of the baseline with the server list out of `census.init_tools` and no source; from no +/// gateway, `census.tools` and `census.init_tools` and the source that saw them; from the +/// harness's own init, the two values in the order of the baseline and no source; from no /// inventory, nothing, and no empty list. /// Oracle: the sorted, deduplicated tool names and the order and shape of `census.json` /// (recorded at cf3de30), with the lists written here by hand. -/// Bite: `census.mcp_servers` recorded as an empty list, `census.init_tools` left unsorted, -/// servers merged into `census.init_tools`, the three values reordered, or an absent inventory -/// recorded as an empty tool list. +/// Bite: a server list recorded, `census.init_tools` left unsorted, the two values reordered, or an +/// absent inventory recorded as an empty tool list. #[test] fn harness_census_records_what_the_source_saw() { - let servers = json!([{"name": "s", "status": "connected"}]); let rows: Vec<CensusRow> = vec![ ( - "a source that sees no servers", - Some(inventory( - json!(["b", "a", "b"]), - None, - CensusSource::Gateway, - )), + "the gateway", + Some(inventory(json!(["b", "a", "b"]), CensusSource::Gateway)), Some(vec![ (String::from("census.tools"), json!(["b", "a", "b"])), (String::from("census.init_tools"), json!(["a", "b"])), @@ -770,14 +790,9 @@ fn harness_census_records_what_the_source_saw() { ), ( "the harness's own init", - Some(inventory( - json!(["Bash", "Agent"]), - Some(servers.clone()), // BORROW: the row owns its list - CensusSource::Harness, - )), + Some(inventory(json!(["Bash", "Agent"]), CensusSource::Harness)), Some(vec![ (String::from("census.tools"), json!(["Bash", "Agent"])), - (String::from("census.mcp_servers"), servers), (String::from("census.init_tools"), json!(["Agent", "Bash"])), ]), ), diff --git a/crates/candler-core/tests/it/guard_job_orchestrate.rs b/crates/candler-core/tests/it/guard_job_orchestrate.rs index bea6ace1..f69dda79 100644 --- a/crates/candler-core/tests/it/guard_job_orchestrate.rs +++ b/crates/candler-core/tests/it/guard_job_orchestrate.rs @@ -443,19 +443,19 @@ fn cells_by_tag( /// Guards: T3 wiring (C3) -- each cell of a two-level job carries its own level's treatment /// checkout and harness, never the first level's. /// Oracle: the checkouts `/src/a` and `/src/b`, the harness versions `2.1.0` and `2.2.0` and the -/// source paths `snapshots` and `environments` written below, one set for each level's tag. +/// source paths `inputs` and `environments` written below, one set for each level's tag. /// Bite: build every cell from the job's primary level. #[test] fn t3_each_cell_runs_its_own_treatment() { let levels = [ - level_of("v1", "/src/a", "2.1.0", "snapshots"), + level_of("v1", "/src/a", "2.1.0", "inputs"), level_of("v2", "/src/b", "2.2.0", "environments"), ]; let cells = cells_by_tag(&two_level_file(&["htn", "other"]), &levels); assert_eq!(cells.len(), 2, "one cell per level"); for (tag, source, version, root, other) in [ - ("v1", "/src/a", "2.1.0", "snapshots", "environments"), - ("v2", "/src/b", "2.2.0", "environments", "snapshots"), + ("v1", "/src/a", "2.1.0", "inputs", "environments"), + ("v2", "/src/b", "2.2.0", "environments", "inputs"), ] { let cell = cells.get(tag).expect("the level's cell"); let held: Vec<&str> = cell @@ -487,7 +487,7 @@ fn t3_each_cell_runs_its_own_treatment() { /// Bite: look the cell's level up among the job's levels and refuse a job that holds none. #[test] fn t3_one_level_job_unchanged() { - let levels = [level_of("v1", "/src/a", "2.1.0", "snapshots")]; + let levels = [level_of("v1", "/src/a", "2.1.0", "inputs")]; let cells = cells_by_tag(&two_level_file(&["htn"]), &levels); assert_eq!(cells.len(), 1, "one level, one cell"); let cell = cells.get("v1").expect("the cell"); diff --git a/crates/candler-core/tests/it/guard_plugin_environment.rs b/crates/candler-core/tests/it/guard_plugin_environment.rs index a0c9be6d..92e93abb 100644 --- a/crates/candler-core/tests/it/guard_plugin_environment.rs +++ b/crates/candler-core/tests/it/guard_plugin_environment.rs @@ -893,7 +893,7 @@ fn layer_inputs_mount() { /// under `mcp` or one level deeper (the file's key is off). #[tokio::test] async fn a_plugins_mcp_servers_reach_claude_code() { - const DECLARED: &str = "{\n \"mcpServers\": {\n \"tools\": {\n \"args\": [\n \"env/server.py\"\n ],\n \"command\": \"python\"\n }\n }\n}\n"; + const DECLARED: &str = "{\n \"mcpServers\": {\n \"tools\": {\n \"args\": [\n \"env/server.py\"\n ],\n \"command\": \"python\",\n \"type\": \"stdio\"\n }\n }\n}\n"; let scratch = tempfile::tempdir().expect("a scratch directory"); let project = scratch .path() @@ -954,7 +954,7 @@ async fn a_plugins_mcp_servers_reach_claude_code() { /// command list the plug-in declares. /// Oracle: hand-derived from the `agent-env` fixture's `plugin.toml` (server `tools`, command /// `python`, arguments `["env/server.py"]`) and the V2 shape `opencode debug config` printed -/// (`local`, `command` a list, `codemode` on by default). +/// (`local`, `command` a list, `codemode` off by default). /// Bite: read `mcp` by exact path again (no server reaches the file). #[tokio::test] async fn a_plugins_mcp_servers_reach_opencode() { @@ -981,7 +981,7 @@ async fn a_plugins_mcp_servers_reach_opencode() { assert_eq!( parsed["mcp"], serde_json::json!({"servers": {"tools": { - "type": "local", "command": ["python", "env/server.py"], "codemode": true + "type": "local", "command": ["python", "env/server.py"], "codemode": false }}}) ); } diff --git a/crates/candler-core/tests/it/guard_refusal_codes.rs b/crates/candler-core/tests/it/guard_refusal_codes.rs index 3983c2b6..7122f363 100644 --- a/crates/candler-core/tests/it/guard_refusal_codes.rs +++ b/crates/candler-core/tests/it/guard_refusal_codes.rs @@ -846,7 +846,6 @@ fn wrapped_cases() -> Vec<Wrapped> { Box::new(PlanError::Driver(DriverError::Unsupported { path: "/budget/per_run/turns".to_owned(), harness: "h".to_owned(), - version: semver::Version::new(1, 0, 0), detail: "d".to_owned(), })), "experiment.setting_unsupported", @@ -857,6 +856,16 @@ fn wrapped_cases() -> Vec<Wrapped> { Box::new(PlanError::Cell { source: absolute() }), "experiment.absolute_path", ), + case( + "PlanError", + "Replicates", + Box::new(PlanError::Replicates { + source: ExecutionError::Zero { + field: "replicates", + }, + }), + "experiment.count_zero", + ), case( "PlanError", "Cell", diff --git a/crates/candler-core/tests/it/guard_resolve_surface.rs b/crates/candler-core/tests/it/guard_resolve_surface.rs index b460f90b..7c45358c 100644 --- a/crates/candler-core/tests/it/guard_resolve_surface.rs +++ b/crates/candler-core/tests/it/guard_resolve_surface.rs @@ -56,10 +56,6 @@ impl PreflightStep for Roots { "inputs", json!([{"kind": "build_inputs", "digest": digest("inputs")}]), ), - ( - "snapshots", - json!([{"kind": "catalog", "digest": digest("snapshots")}]), - ), ( "environments", json!([{"plugin": "p@1.0.0", "lock_digest": digest("environments")}]), diff --git a/crates/candler-core/tests/it/guard_run_context.rs b/crates/candler-core/tests/it/guard_run_context.rs index c8989c92..7f82733e 100644 --- a/crates/candler-core/tests/it/guard_run_context.rs +++ b/crates/candler-core/tests/it/guard_run_context.rs @@ -5,6 +5,7 @@ #![cfg(test)] use crate::support::legacy_import; +use crate::support::sealed_run::{File, seal_workspace}; use candler_testkit::file_set; use std::collections::BTreeSet; @@ -17,7 +18,7 @@ use std::str::FromStr as _; use candler_core::evaluation::context::{ContextError, assemble, materialise}; use candler_core::store::Store; use candler_core::store::run::{Existing, RunWriter}; -use candler_schemas::evaluation::{ContextArtifact, Needs, RunContext}; +use candler_schemas::evaluation::{Needs, RunContext}; use candler_schemas::execution::{RunManifest, RunTree, TreeEntry}; use candler_schemas::primitives::{Digest, FieldPath, RelPath, RunKey}; use legacy_import::{cell_of, copy_tree, import_with_reader, mini}; @@ -70,49 +71,6 @@ fn sha256_of(bytes: &[u8]) -> Digest { Digest::from_hex(&hex).expect("a digest") } -/// One file of a synthetic `outputs/` tree. -struct File { - path: &'static str, - bytes: &'static [u8], - executable: bool, -} - -/// Seals a new run beside `template`, which is the manifest it copies, with exactly the files -/// `files` under `outputs/`, and returns its key. The store holds each file as a blob. -fn seal_synthetic(store: &Store, template: &RunKey, attempt: u32, files: &[File]) -> RunKey { - let mut manifest = serde_json::to_value(store.read_manifest(template).expect("the manifest")) - .expect("a manifest serialises"); - *manifest - .pointer_mut("/run/attempt") - .expect("the manifest names an attempt") = attempt.into(); - let manifest: RunManifest = serde_json::from_value(manifest).expect("a manifest reads"); - let mut tree = RunTree::builder(); - for file in files { - let digest = store.put_blob(file.bytes, None).expect("a blob stores"); - tree = tree.entry(TreeEntry::file( - RelPath::from_str(file.path).expect("a path"), - digest, - file.executable, - )); - } - let key = manifest.run().clone(); - let mut writer = RunWriter::create(store, &manifest, Existing::Refuse).expect("a run starts"); - writer - .tree(&tree.build().expect("a tree")) - .expect("the tree writes"); - writer.done().expect("the run seals"); - key -} - -/// The string `path` of every artifact of a context. -fn artifact_paths(context: &RunContext) -> BTreeSet<String> { - context - .artifacts() - .iter() - .map(|a| a.path.to_string()) - .collect() -} - /// The vector table, as `toml::Table`. fn live_vectors() -> toml::Table { let text = fs::read_to_string( @@ -211,138 +169,6 @@ fn the_live_context_digest_is_the_independent_vector() { ); } -/// One row of the file-rule table: artifact globs, the files the run stored, and the hand-listed -/// set of paths that the context carries. -struct Case { - name: &'static str, - globs: &'static [&'static str], - stored: &'static [File], - kept: &'static [&'static str], -} - -/// Shorthand for a stored file whose bytes are its own path. -const fn file(path: &'static str) -> File { - File { - path, - bytes: path.as_bytes(), - executable: false, - } -} - -/// The file-rule table; the sets in `kept` are written by hand from R03's file rule. -const CASES: &[Case] = &[ - Case { - name: "a nested match counts", - globs: &["outputs/**"], - stored: &[file("a.py"), file("sub/deep/b.py"), file("sub/c.json")], - kept: &["a.py", "sub/c.json", "sub/deep/b.py"], - }, - Case { - name: ".claude is dropped, at any depth", - globs: &["outputs/**"], - stored: &[ - file("domain.py"), - file(".claude/x.py"), - file(".claude/deep/y.py"), - file("sub/.claude/z.py"), - ], - kept: &["domain.py"], - }, - Case { - name: "AppleDouble files are dropped", - globs: &["outputs/**"], - stored: &[ - file("domain.py"), - file("._domain.py"), - file("sub/._b.py"), - file("sub/b.py"), - ], - kept: &["domain.py", "sub/b.py"], - }, - Case { - name: ".DS_Store is dropped", - globs: &["outputs/**"], - stored: &[file("x.py"), file(".DS_Store"), file("sub/.DS_Store")], - kept: &["x.py"], - }, - Case { - name: "a hidden directory below a nested path is dropped", - globs: &["outputs/**"], - stored: &[file("sub/.hidden/y.py"), file("sub/z.py")], - kept: &["sub/z.py"], - }, - Case { - name: "an empty outputs gives no artifact and no error", - globs: &["outputs/**"], - stored: &[], - kept: &[], - }, - Case { - name: "a glob that names the component keeps it, and only what it names", - globs: &["outputs/.claude/**"], - stored: &[ - file("domain.py"), - file(".claude/x.py"), - file(".claude/.hid"), - ], - kept: &[".claude/x.py"], - }, - Case { - name: "a literal dot file is kept by its own glob and not by another", - globs: &["outputs/**", "outputs/.env"], - stored: &[file(".env"), file("a/.env"), file("x")], - kept: &[".env", "x"], - }, - Case { - name: "a glob keeps only what it matches", - globs: &["outputs/*.py"], - stored: &[file("a.py"), file("sub/b.py"), file("c.json")], - kept: &["a.py"], - }, -]; - -/// Guards: R9 — the paths of a materialised context and the paths its digest covers are exactly the files the file rule keeps: a nested match counts, `.claude/`, `._*` and `.DS_Store` are dropped unless a glob names them, and an empty `outputs/` gives no artifact and no error. Oracle: hand-listed path sets, and the digest of a context built from the listed paths and the literal bytes. -#[test] -fn the_file_rule_decides_the_paths_and_the_digest() { - let (_keep, store) = mini_store(&mini()); - let template = key_of(&store, 12); - for (n, case) in (2_u32..).zip(CASES) { - let run = seal_synthetic(&store, &template, n, case.stored); - let workspace = tempfile::tempdir().expect("a workspace"); - let context = context_of(&store, &run, &needs_of(case.globs), workspace.path()); - let expected: BTreeSet<String> = case.kept.iter().map(|p| (*p).to_owned()).collect(); - assert_eq!( - file_set(&workspace.path().join("outputs")), - expected, - "materialised files: {}", - case.name - ); - assert_eq!( - artifact_paths(&context), - expected, - "digest path list: {}", - case.name - ); - // The digest is that of exactly the listed paths with the hashes of their literal bytes. - let mut builder = RunContext::builder() - .run(run.clone()) - .root("/unused".into()); - for path in case.kept { - builder = builder.artifact(ContextArtifact::new( - RelPath::from_str(path).expect("a path"), - String::from("/unused"), - sha256_of(path.as_bytes()), - )); - } - assert_eq!( - context.context_digest(), - builder.build().expect("a context").context_digest(), - "digest: {}", - case.name - ); - } -} - /// Guards: R9 and I11 — a plug-in that appends to, or overwrites, a materialised file, after making it writable as a careless one would, leaves every blob of the store with its recorded sha256. Oracle: the sha256 the store's tree records for each blob, and a read of the blob's bytes taken here. #[test] fn a_plug_in_cannot_write_through_to_the_store() { @@ -426,36 +252,96 @@ fn a_corrupt_blob_is_refused_and_not_digested() { ); } -/// Guards: R9 and I11 — every materialised file is a private copy, not a link: a fresh inode with one link, mode `0444`, or `0555` when the tree marks it executable, while the store blob keeps its own inode and mode. Oracle: `stat` of the copy and of the blob, and the executable bit written into the synthetic tree here. +/// Guards: R9 — the file rule drops `.claude/` at any depth unless a glob names it: `outputs/**` +/// keeps `domain.py` only, and `outputs/.claude/**` keeps `.claude/x.py` and not `.claude/.hid`. +/// The runner never collects `.claude` (`EXCLUDED_DIRS`, `discovery.rs` of the Claude Code driver), so +/// these runs are sealed through the runner's `seal_run` over a workspace made here. Oracle: hand-listed +/// path sets from R03's file rule. #[test] -fn a_materialised_file_is_a_private_read_only_copy() { +fn the_file_rule_treats_a_stored_dot_claude_by_its_glob() { let (_keep, store) = mini_store(&mini()); let template = key_of(&store, 12); - let stored = [ - file("plain.py"), - File { - path: "run.sh", - bytes: b"#!/bin/sh\n", - executable: true, - }, + let plain = |path: &'static str| File { + path, + bytes: path.as_bytes(), + }; + let cases: [(&str, Vec<File>, &str, &[&str]); 2] = [ + ( + "dropped at any depth", + vec![ + plain("domain.py"), + plain(".claude/x.py"), + plain(".claude/deep/y.py"), + plain("sub/.claude/z.py"), + ], + "outputs/**", + &["domain.py"], + ), + ( + "kept when a glob names it", + vec![ + plain("domain.py"), + plain(".claude/x.py"), + plain(".claude/.hid"), + ], + "outputs/.claude/**", + &[".claude/x.py"], + ), ]; - let run = seal_synthetic(&store, &template, 2, &stored); - let workspace = tempfile::tempdir().expect("a workspace"); - context_of(&store, &run, &needs_of(&["outputs/**"]), workspace.path()); - - for (name, mode) in [("plain.py", 0o444_u32), ("run.sh", 0o555_u32)] { - let copy = fs::metadata(workspace.path().join("outputs").join(name)).expect("a copy"); - let digest = - sha256_of(&fs::read(workspace.path().join("outputs").join(name)).expect("reads")); - let blob = fs::metadata(store.blob_path(&digest)).expect("a blob"); - assert_eq!(copy.mode() & 0o777, mode, "the mode of {name}"); - assert_eq!(copy.nlink(), 1, "the copy of {name} has one link"); - assert_ne!(copy.ino(), blob.ino(), "the copy of {name} is not the blob"); - assert_eq!(blob.nlink(), 1, "the blob of {name} gained no link"); - assert_eq!(blob.mode() & 0o777, 0o444, "the mode of the blob of {name}"); + for (n, (name, stored, glob, kept)) in (2_u32..).zip(cases) { + let run = seal_workspace(&store, &template, n, &stored); + let workspace = tempfile::tempdir().expect("a workspace"); + context_of(&store, &run, &needs_of(&[glob]), workspace.path()); + let expected: BTreeSet<String> = kept.iter().map(|p| (*p).to_owned()).collect(); + assert_eq!( + file_set(&workspace.path().join("outputs")), + expected, + "materialised files: {name}" + ); } } +/// Guards: R9 and I11 — a file of an imported folder that has an execute bit materialises as `0555` +/// and one that has none as `0444`, each a private copy with one link. Oracle: `stat` of the +/// copies, and the mode given here to a copy of the corpus before it is imported. +#[test] +fn an_imported_executable_materialises_as_a_private_0555_copy() { + let copy = tempfile::tempdir().expect("a corpus copy"); + copy_tree(&mini(), copy.path()); + let outputs = copy + .path() + .join(cell_of(12)) + .join("_run_cache/with_skill/run-12/outputs"); + let (script, plain) = (outputs.join("run.sh"), outputs.join("note.txt")); + fs::write(&script, b"#!/bin/sh\n").expect("a script writes"); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).expect("a mode"); + fs::write(&plain, b"note\n").expect("a note writes"); + fs::set_permissions(&plain, fs::Permissions::from_mode(0o644)).expect("a mode"); + let (_keep, store) = mini_store(copy.path()); + let workspace = tempfile::tempdir().expect("a workspace"); + context_of( + &store, + &key_of(&store, 12), + &needs_of(&["outputs/**"]), + workspace.path(), + ); + + let modes = + |name: &str| fs::metadata(workspace.path().join("outputs").join(name)).expect("a copy"); + assert_eq!( + modes("run.sh").mode() & 0o777, + 0o555, + "the mode of the script" + ); + assert_eq!(modes("run.sh").nlink(), 1, "the script has one link"); + assert_eq!( + modes("note.txt").mode() & 0o777, + 0o444, + "the mode of the note" + ); + assert_eq!(modes("note.txt").nlink(), 1, "the note has one link"); +} + /// Guards: I11 — a workspace that is, or lies above, the store root is refused before any directory is made, so a plug-in cannot reach the store through its own workspace. Oracle: the parent of the store root, and the store root itself, handed in as workspaces. #[test] fn a_workspace_that_contains_the_store_is_refused() { diff --git a/crates/candler-core/tests/it/guard_run_evidence.rs b/crates/candler-core/tests/it/guard_run_evidence.rs index 9262ff20..9db2be84 100644 --- a/crates/candler-core/tests/it/guard_run_evidence.rs +++ b/crates/candler-core/tests/it/guard_run_evidence.rs @@ -43,6 +43,7 @@ fn evidence(path: &str, sha: &str) -> Evidence { outputs: vec![OutputDigest { path: path.to_owned(), // BORROW: the evidence owns its path digest: digest(sha), + executable: false, }], tree: RunTree::builder().build().expect("an empty tree"), } @@ -109,10 +110,10 @@ fn value_at(values: &[MeasuredValue], path: &str) -> Value { .clone() // BORROW: .clone() releases the borrow of the values } -/// Guards: I10 — the census records the tools and servers the agent saw, and `census.init_tools` -/// holds the sorted tool names only. +/// Guards: I10 — the census records the tools the agent saw and no server, however the init +/// lists them, and `census.init_tools` holds the sorted tool names only. /// Oracle: jq over the fixture stream. -/// Bite: write `mcp_servers` into `census.init_tools`. +/// Bite: record `mcp_servers` as a census value, or write it into `census.init_tools`. #[test] fn b25_census_from_a_real_init() { // Provenance: from the stream above, whose first init opens the first session and whose @@ -120,19 +121,17 @@ fn b25_census_from_a_real_init() { // gzcat <stream> | jq -c 'select(.type=="system" and .subtype=="init")' | head -1 | jq -c .tools // -> ["Bash","Agent"] // ... | jq -c '.tools|sort' -> ["Agent","Bash"] - // ... | jq -c .mcp_servers -> [] let lines = stream_lines(); let values = census_of(lines.as_slice()); // BORROW: explicit .as_slice() - assert_eq!(values.len(), 3); + assert_eq!(values.len(), 2); assert_eq!(value_at(&values, "census.tools"), json!(["Bash", "Agent"])); - assert_eq!(value_at(&values, "census.mcp_servers"), json!([])); assert_eq!( value_at(&values, "census.init_tools"), json!(["Agent", "Bash"]) ); // The recorded init lists no MCP server, so the same stream with two servers listed in its - // first init is the control that tells the server list from the tool list. + // first init is the control that shows the server list is not read. let servers = json!([ {"name": "rikyu-hpc", "status": "connected"}, {"name": "aaa-first", "status": "failed"} @@ -148,7 +147,7 @@ fn b25_census_from_a_real_init() { } *first = frame.to_string(); let with_servers = census_of(edited.as_slice()); // BORROW: explicit .as_slice() - assert_eq!(value_at(&with_servers, "census.mcp_servers"), servers); + assert_eq!(with_servers.len(), 2); assert_eq!( value_at(&with_servers, "census.init_tools"), json!(["Agent", "Bash"]) @@ -170,6 +169,7 @@ fn outputs_of(paths: &[&str]) -> Evidence { .map(|path| OutputDigest { path: (*path).to_owned(), // BORROW: the evidence owns its path digest: digest(INPUT_SHA), + executable: false, }) .collect(), ..evidence("unused", INPUT_SHA) diff --git a/crates/candler-core/tests/it/guard_run_plan.rs b/crates/candler-core/tests/it/guard_run_plan.rs index 5616e5bf..7bf33d9f 100644 --- a/crates/candler-core/tests/it/guard_run_plan.rs +++ b/crates/candler-core/tests/it/guard_run_plan.rs @@ -903,16 +903,16 @@ fn t3_one_level_plans_the_old_bytes() { .iter() .map(|plan| (plan.cell.to_string(), plan.key.replicate())) .collect(); - let m1 = "sha256:c8c025d07f891ace920b103b2dd93ae78cdbe49fbf4269085554aa79d72dfab2"; - let m2 = "sha256:528ad7c2a0587eda8c5fbeee1760c89687f211a181a125f7dfc74b7be074c13a"; - let expected: Vec<(String, u32)> = [(m1, 1), (m2, 1), (m1, 2), (m2, 2)] + let m1 = "sha256:f935f4852108458ddbd26c7be1f5b38d9ae390e47b2b2330052bd92b049c43ec"; + let m2 = "sha256:94d7583eabfaa4cd6116ed137aacbea7c81de62a87e951e0b3d58104c0f34aa8"; + let expected: Vec<(String, u32)> = [(m1, 1), (m2, 1), (m2, 2), (m1, 2)] .into_iter() .map(|(cell, replicate)| (cell.to_owned(), replicate)) .collect(); assert_eq!( (out.experiment.to_string(), planned), ( - "sha256:2a0b3bf188be1e42e471095c7973dfaa390f5d0288cbb6733f15ac6ce4e670e7".to_owned(), + "sha256:a0d95d80aa505e22bdeb3a8c5123b0ddb0d85bc6fa000f016b8e053399a1cf06".to_owned(), expected ) ); diff --git a/crates/candler-core/tests/it/guard_session.rs b/crates/candler-core/tests/it/guard_session.rs index 4f6d22bf..3f9ee5da 100644 --- a/crates/candler-core/tests/it/guard_session.rs +++ b/crates/candler-core/tests/it/guard_session.rs @@ -483,6 +483,121 @@ async fn session_plan_refuses_a_setting_the_driver_cannot_honour() { } } +/// Guards: an effort or a permission mode that names nothing is refused once, when the cells are +/// planned, as `experiment.cell_value_invalid` at the field, whichever driver the cell meets, and +/// the same cell with a level and a mode that exist plans. +/// Oracle: the field pointers written by hand; the values go through the real resolve step and +/// `plan_runs`. +/// Bite: let the plan pass an unnamed text on to a driver (Claude Code would write it to its +/// command line; `OpenCode` would answer `setting_unsupported`). +#[tokio::test] +async fn an_unnamed_effort_or_mode_is_refused_at_its_field_for_each_driver() { + let file = experiment_with(""); + let mode = ("permission_mode", json!("bypassPermissions")); + for capable in [true, false] { + for (path, pointer) in [ + ("model.effort", "/model/effort"), + ("permission_mode", "/permission_mode"), + ] { + let fixed: Vec<(&str, Value)> = if path == "permission_mode" { + vec![(path, json!("turbo"))] + } else { + vec![mode.clone(), (path, json!("turbo"))] + }; + match planned(&file, &fixed, capable).await { + Err(error) => { + assert_eq!( + Refusal::code(&error).as_str(), + "experiment.cell_value_invalid", + "{path}, capable {capable}" + ); + assert_eq!( + Refusal::path(&error).as_deref(), + Some(pointer), + "{path}, capable {capable}" + ); + } + Ok(_) => panic!("{path}, capable {capable}: an unnamed text planned"), + } + } + } +} + +/// Guards: every permission-mode spelling Claude Code reads plans on Claude Code and reaches +/// `--permission-mode` as Claude Code's own word, `manual` as `default`; `OpenCode` refuses `auto` +/// and `dontAsk` as `experiment.setting_unsupported`, and so does an explicit `default`, with +/// `OpenCode`'s reason; a cell without a mode asks the driver nothing, so both drivers plan it. +/// Oracle: the modes of the Claude Code CLI reference (`--permission-mode`), written by hand. +/// Bite: drop `Auto` or `DontAsk` from `PermissionMode`, or the `manual` alias, or ask the driver +/// about `default` for an absent mode. +#[tokio::test] +async fn every_claude_code_permission_mode_plans_and_opencode_refuses_what_it_cannot_carry() { + let file = experiment_with(""); + let driver = ClaudeCodeDriver::new(); + let workspace = Workspace::new(Path::new("/work/run")); + for (text, word) in [ + ("default", "default"), + ("manual", "default"), + ("acceptEdits", "acceptEdits"), + ("plan", "plan"), + ("bypassPermissions", "bypassPermissions"), + ("auto", "auto"), + ("dontAsk", "dontAsk"), + ] { + assert!( + planned(&file, &[("permission_mode", json!(text))], true) + .await + .is_ok(), + "{text} on Claude Code" + ); + let toml = format!( + "schema = \"experiment/1\"\nreplicates = 1\n\n[fixed]\npermission_mode = \"{text}\"\n\ + \"prompt.template\" = \"go\"\n\"model.id\" = \"m\"\n\n[budget.per_run]\nwall_s = 60\n\n\ + [harness]\nname = \"claude-code\"\n\n[treatment]\nname = \"t\"\n" + ); + let experiment = ExperimentFile::from_toml_str(&toml).expect("an experiment"); + let cells = experiment.cells(); + let values = cells.first().expect("one cell"); + let plan = driver.plan(&Cell::new(values), &workspace).expect("a plan"); + assert_eq!( + after(plan.command.argv(), "--permission-mode"), + Some(word), + "{text}" + ); + } + for text in ["auto", "dontAsk"] { + match planned(&file, &[("permission_mode", json!(text))], false).await { + Err(error) => assert_eq!( + Refusal::code(&error).as_str(), + "experiment.setting_unsupported", + "{text}" + ), + Ok(_) => panic!("an OpenCode cell in {text} mode planned"), + } + } + assert!( + planned(&file, &[], true).await.is_ok(), + "a Claude Code cell without a mode" + ); + assert!( + planned(&file, &[], false).await.is_ok(), + "an OpenCode cell without a mode" + ); + match planned(&file, &[("permission_mode", json!("default"))], false).await { + Err(error) => { + assert_eq!( + Refusal::code(&error).as_str(), + "experiment.setting_unsupported" + ); + assert!( + error.to_string().contains("Claude Code's default mode"), + "OpenCode's reason for `default`: {error}" + ); + } + Ok(_) => panic!("an OpenCode cell in default mode planned"), + } +} + // --------------------------------------------------------------------------------------------- // P1: a model factor of tables. // --------------------------------------------------------------------------------------------- diff --git a/crates/candler-core/tests/it/guard_settings_out_of_cell.rs b/crates/candler-core/tests/it/guard_settings_out_of_cell.rs index 4156de99..417f6ed7 100644 --- a/crates/candler-core/tests/it/guard_settings_out_of_cell.rs +++ b/crates/candler-core/tests/it/guard_settings_out_of_cell.rs @@ -111,10 +111,6 @@ impl PreflightStep for OtherRoots { fp("treatment"), js(json!({"name": "htn", "commit": "1".repeat(40)})), ) - .derive( - fp("snapshots"), - js(json!([{"kind": "catalog", "digest": digest}])), - ) .derive( fp("environments"), js(json!([{"plugin": "p@1.0.0", "lock_digest": digest}])), @@ -503,3 +499,38 @@ async fn t2_other_settings_stay_refused() { ); } } + +/// Guards: the resolved cell records what Candler installs for a server: `codemode` is `false` +/// where the file leaves it out, so a server that leaves it out and one that sets it to `false` +/// are one cell, and `codemode = true` is another. +/// Oracle: the hand-written files below; the value is read from the cell. +/// Bite: drop `fill_codemode` from `fresh_cells`. +#[tokio::test] +async fn a_server_without_codemode_is_the_cell_with_codemode_off() { + let root = tempfile::tempdir().expect("a directory"); + let dir = root.path(); + let server = "\"mcp.servers.a.command\" = \"uvx\"\n"; + let left_out = plan(&file_with(server, ""), dir).await; + let off = plan( + &file_with(&format!("{server}\"mcp.servers.a.codemode\" = false\n"), ""), + dir, + ) + .await; + let on = plan( + &file_with(&format!("{server}\"mcp.servers.a.codemode\" = true\n"), ""), + dir, + ) + .await; + let digest = |planned: &Planned| planned.cells.first().map(Comparable::digest); + assert!(digest(&left_out).is_some()); + assert_eq!(digest(&left_out), digest(&off)); + assert_ne!(digest(&left_out), digest(&on)); + let held = left_out.cells.first().and_then(|cell| { + cell.values() + .iter() + .find(|value| value.path().as_str() == "mcp.servers.a.codemode") + .and_then(|value| value.value()) + .map(JsonValue::as_value) + }); + assert_eq!(held, Some(&json!(false))); +} diff --git a/crates/candler-core/tests/it/guard_silent_acceptance.rs b/crates/candler-core/tests/it/guard_silent_acceptance.rs index 90bcddc2..a28e418e 100644 --- a/crates/candler-core/tests/it/guard_silent_acceptance.rs +++ b/crates/candler-core/tests/it/guard_silent_acceptance.rs @@ -8,12 +8,14 @@ use std::error::Error; -use candler_core::jobs::orchestrate::servers::stdio_servers; use candler_core::resolve::config::{Config, UserConfig}; use candler_core::resolve::layers::{FileValues, Layered, Resolution, ResolveInput}; +use candler_core::resolve::paths::settings_set_by; use candler_core::runner::plan::{Force, PlanMode, plan_runs}; +use candler_harness::mcp::servers; +use candler_harness::spec::Cell; use candler_schemas::primitives::FieldPath; -use candler_schemas::values::JsonValue; +use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::{Value, json}; use crate::support::run_plan::{Facts, experiment, fresh_store, plan_ctx, resolution}; @@ -58,12 +60,32 @@ fn at_resolve(entries: &[(&str, Value)]) -> Option<Refused> { layered(entries).err() } +/// The refusal of the resolve layer when the core's defaults set `model.token_secret` and the +/// experiment's `env` table names it. +fn at_resolve_default_token_secret() -> Option<Refused> { + let root = tempfile::tempdir().expect("a temp dir"); + let mut input = ResolveInput::new(Vec::new()).file(FileValues::new(vec![( + fp("env"), + js(json!({"GATEWAY_TOKEN": "x"})), + )])); + input + .core_defaults + .push((fp("model.token_secret"), js(json!("GATEWAY_TOKEN")))); + Layered::new(&config(root.path()), input) + .err() + .map(|error| refused_by(&error)) +} + /// The refusal of planning an experiment that writes `replicates = 3` when the file's values carry /// `replicates = 5` under `[fixed]`. fn at_plan_fixed_five() -> Option<Refused> { - let layers = layered(&[("replicates", json!(5))]) - .expect("layers") - .resolve(); + at_plan_fixed(json!(5)) +} + +/// The refusal of planning an experiment that writes `replicates = 3` when the file's values carry +/// `replicates = <count>` under `[fixed]`. +fn at_plan_fixed(count: Value) -> Option<Refused> { + let layers = layered(&[("replicates", count)]).expect("layers").resolve(); let facts = Facts::base(); let mut resolved = serde_json::to_value(resolution(&facts)).expect("JSON"); resolved["settings"] = serde_json::to_value(&layers.settings).expect("JSON"); @@ -82,27 +104,40 @@ fn at_plan_fixed_five() -> Option<Refused> { .map(|error| refused_by(&error)) } -/// The refusal of the start check's reading of `declared`, if any. -fn at_servers(declared: Value) -> Option<Refused> { - let Value::Object(table) = declared else { - panic!("a table of servers"); - }; - drop(stdio_servers(&table)); - None +/// The refusal of the reader of the MCP servers of a cell that sets `entries`, if any. +fn at_servers(entries: &[(&str, Value)]) -> Option<Refused> { + let values: Vec<ResolvedValue> = entries + .iter() + .map(|(path, value)| ResolvedValue::recorded(fp(path), js(value.clone()))) + .collect(); + servers(&Cell::new(&values)) + .err() + .map(|error| refused_by(&error)) +} + +/// The refusal of the keys a cell that sets `entries` is read as setting, if any. +fn at_set_by(entries: &[(&str, Value)]) -> Option<Refused> { + let values: Vec<ResolvedValue> = entries + .iter() + .map(|(path, value)| ResolvedValue::recorded(fp(path), js(value.clone()))) + .collect(); + settings_set_by(&Cell::new(&values)) + .err() + .map(|error| refused_by(&error)) } struct Row { name: &'static str, code: &'static str, - pointer: &'static str, + pointer: Option<&'static str>, run: fn() -> Option<Refused>, } -const ROWS: [Row; 4] = [ +const ROWS: [Row; 15] = [ Row { name: "an env name equal to model.token_secret", code: "experiment.env_token_secret", - pointer: "/env/GATEWAY_TOKEN", + pointer: Some("/env/GATEWAY_TOKEN"), run: || { at_resolve(&[ ("model.token_secret", json!("GATEWAY_TOKEN")), @@ -110,47 +145,99 @@ const ROWS: [Row; 4] = [ ]) }, }, + Row { + name: "an env name equal to a model.token_secret that a core default sets", + code: "experiment.env_token_secret", + pointer: Some("/env/GATEWAY_TOKEN"), + run: at_resolve_default_token_secret, + }, + Row { + name: "a [fixed] replicates that differs from the file's own count", + code: "experiment.replicates_conflict", + pointer: Some("/replicates"), + run: at_plan_fixed_five, + }, + Row { + name: "a [fixed] replicate count of zero", + code: "experiment.count_zero", + pointer: Some("/replicates"), + run: || at_plan_fixed(json!(0)), + }, Row { name: "a replicates.<x> path", code: "experiment.replicates_path", - pointer: "/replicates/x", + pointer: Some("/replicates/x"), run: || at_resolve(&[("replicates.x", json!(2))]), }, Row { name: "a replicate count that is a string", - code: "experiment.replicates_not_integer", - pointer: "/replicates", - run: || at_resolve(&[("replicates", json!("three"))]), + code: "experiment.replicates_not_count", + pointer: Some("/replicates"), + run: || at_plan_fixed(json!("three")), }, Row { name: "a replicate count that is a fraction", - code: "experiment.replicates_not_integer", - pointer: "/replicates", - run: || at_resolve(&[("replicates", json!(2.5))]), + code: "experiment.replicates_not_count", + pointer: Some("/replicates"), + run: || at_plan_fixed(json!(2.5)), }, -]; - -/// The cases whose refusal needs a new variant in `runner/refusal.rs` or `jobs/refusal.rs`, which -/// the leaf's OWNED set leaves out. They are written and red, and run once those files are owned: -/// `cargo nextest run -p candler-core --run-ignored only -E 'test(/deferred/)'`. -const DEFERRED: [Row; 3] = [ Row { - name: "a [fixed] replicates that differs from the file's own count", - code: "experiment.replicates_conflict", - pointer: "/replicates", - run: at_plan_fixed_five, + name: "a negative replicate count", + code: "experiment.replicates_not_count", + pointer: Some("/replicates"), + run: || at_plan_fixed(json!(-1)), + }, + Row { + name: "a replicate count beyond 32 bits", + code: "experiment.replicates_not_count", + pointer: Some("/replicates"), + run: || at_plan_fixed(json!(5_000_000_000_u64)), }, Row { name: "an MCP server command that is not a string", - code: "jobs.server_command_not_string", - pointer: "/mcp/servers/fs/command", - run: || at_servers(json!({"fs": {"command": 7}})), + code: "experiment.cell_value_invalid", + pointer: Some("/mcp/servers/fs/command"), + run: || at_servers(&[("mcp.servers.fs.command", json!(7))]), }, Row { name: "MCP server args that are not all strings", - code: "jobs.server_args_not_strings", - pointer: "/mcp/servers/fs/args", - run: || at_servers(json!({"fs": {"command": "mcp-fs", "args": ["--root", 3]}})), + code: "experiment.cell_value_invalid", + pointer: Some("/mcp/servers/fs/args"), + run: || { + at_servers(&[ + ("mcp.servers.fs.command", json!("mcp-fs")), + ("mcp.servers.fs.args", json!(["--root", 3])), + ]) + }, + }, + Row { + name: "an MCP server with neither a command nor a url", + code: "experiment.cell_value_invalid", + pointer: Some("/mcp/servers/fs"), + run: || at_servers(&[("mcp.servers.fs.codemode", json!(true))]), + }, + Row { + name: "an MCP server whose env holds a value that is not text", + code: "experiment.cell_value_invalid", + pointer: Some("/mcp/servers/fs/env/token"), + run: || { + at_servers(&[ + ("mcp.servers.fs.command", json!("mcp-fs")), + ("mcp.servers.fs.env.token", json!(7)), + ]) + }, + }, + Row { + name: "an effort that names no level", + code: "experiment.cell_value_invalid", + pointer: Some("/model/effort"), + run: || at_set_by(&[("model.effort", json!("turbo"))]), + }, + Row { + name: "a permission mode that names no mode", + code: "experiment.cell_value_invalid", + pointer: Some("/permission_mode"), + run: || at_set_by(&[("permission_mode", json!("yolo"))]), }, ]; @@ -158,7 +245,7 @@ const DEFERRED: [Row; 3] = [ fn check(rows: &[Row]) { let mut wrong = Vec::new(); for row in rows { - let want = Some((row.code.to_owned(), Some(row.pointer.to_owned()))); + let want = Some((row.code.to_owned(), row.pointer.map(str::to_owned))); let got = (row.run)(); if got != want { wrong.push(format!("{}: got {got:?}, want {want:?}", row.name)); @@ -178,12 +265,3 @@ fn check(rows: &[Row]) { fn silent_cases_are_refused_with_a_code_and_a_pointer() { check(&ROWS); } - -/// Guards: the cases of `DEFERRED`, refused with their own code and pointer. -/// Oracle: the codes and pointers of the leaf, written by hand in `DEFERRED`. -/// Bite: as the table above. -#[test] -#[ignore = "needs runner/refusal.rs and jobs/refusal.rs in the leaf's OWNED set"] -fn deferred_silent_cases_are_refused_with_a_code_and_a_pointer() { - check(&DEFERRED); -} diff --git a/crates/candler-core/tests/it/guard_treatment_source.rs b/crates/candler-core/tests/it/guard_treatment_source.rs index ec25c013..56925446 100644 --- a/crates/candler-core/tests/it/guard_treatment_source.rs +++ b/crates/candler-core/tests/it/guard_treatment_source.rs @@ -59,10 +59,6 @@ impl PreflightStep for OtherRoots { fp("inputs"), js(json!([{"kind": "build_inputs", "digest": digest}])), ) - .derive( - fp("snapshots"), - js(json!([{"kind": "catalog", "digest": digest}])), - ) .derive( fp("environments"), js(json!([{"plugin": "p@1.0.0", "lock_digest": digest}])), diff --git a/crates/candler-core/tests/it/support/harness_facts.rs b/crates/candler-core/tests/it/support/harness_facts.rs index 3fe9ed19..9ceb02ad 100644 --- a/crates/candler-core/tests/it/support/harness_facts.rs +++ b/crates/candler-core/tests/it/support/harness_facts.rs @@ -526,10 +526,6 @@ impl PreflightStep for OtherRoots { fp("treatment"), js(json!({"name": "htn", "commit": "1".repeat(40)})), ) - .derive( - fp("snapshots"), - js(json!([{"kind": "catalog", "digest": digest}])), - ) .derive( fp("environments"), js(json!([{"plugin": "p@1.0.0", "lock_digest": digest}])), diff --git a/crates/candler-core/tests/it/support/job_orchestrate.rs b/crates/candler-core/tests/it/support/job_orchestrate.rs index 3ef02db3..5ccfeec5 100644 --- a/crates/candler-core/tests/it/support/job_orchestrate.rs +++ b/crates/candler-core/tests/it/support/job_orchestrate.rs @@ -38,8 +38,8 @@ use candler_core::supervise::{EventSink, Supervisor}; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ - BudgetCaps, Capabilities, Cell, CollectSpec, CommandSpec, GatewayEnv, HarnessId, Observed, - Prepared, ProcessExit, StopSignal, StopSpec, Workspace, + AgentSetting, Answer, Cell, CollectSpec, CommandSpec, DriverFact, GatewayEnv, HarnessId, + Observed, Prepared, ProcessExit, StopSignal, StopSpec, Workspace, }; use candler_schemas::execution::{Budget, EventPayload, ExperimentFile, JobState}; use candler_schemas::primitives::{ContainerId, JobId, Marker, RunKey}; @@ -356,11 +356,30 @@ impl HarnessDriver for QuietDriver { Ok(semver::Version::new(2, 1, 0)) } - fn capabilities(&self) -> Capabilities { - Capabilities::builder() - .graceful_stop(true) - .budgets(BudgetCaps::new(true, true)) - .build() + fn answer(&self, setting: AgentSetting) -> Answer { + let refused: &[AgentSetting] = &[AgentSetting::SessionMode]; + if refused.contains(&setting) { + Answer::Refused { + reason: "test stand-in", + } + } else { + Answer::Mapped { + construct: "test stand-in", + } + } + } + + fn fact(&self, fact: DriverFact) -> Answer { + let held: &[DriverFact] = &[DriverFact::GracefulStop]; + if held.contains(&fact) { + Answer::Mapped { + construct: "test stand-in", + } + } else { + Answer::Refused { + reason: "test stand-in", + } + } } fn gateway(&self) -> Option<GatewayEnv> { @@ -386,7 +405,11 @@ impl HarnessDriver for QuietDriver { } // TRAIT_OBJECT: the host hands out its trace reader as a trait object - fn offline_reader(&self, _stream: &StreamName) -> Option<Box<dyn TraceReader>> { + fn offline_reader( + &self, + _stream: &StreamName, + _servers: &[String], + ) -> Option<Box<dyn TraceReader>> { None } @@ -433,8 +456,12 @@ impl HarnessDriver for ObservingDriver { self.0.parse_version(output) } - fn capabilities(&self) -> Capabilities { - self.0.capabilities() + fn answer(&self, setting: AgentSetting) -> Answer { + self.0.answer(setting) + } + + fn fact(&self, fact: DriverFact) -> Answer { + self.0.fact(fact) } fn gateway(&self) -> Option<GatewayEnv> { @@ -457,7 +484,11 @@ impl HarnessDriver for ObservingDriver { } // TRAIT_OBJECT: the host hands out its trace reader as a trait object - fn offline_reader(&self, _stream: &StreamName) -> Option<Box<dyn TraceReader>> { + fn offline_reader( + &self, + _stream: &StreamName, + _servers: &[String], + ) -> Option<Box<dyn TraceReader>> { None } diff --git a/crates/candler-core/tests/it/support/mod.rs b/crates/candler-core/tests/it/support/mod.rs index 5f0b63e4..885be576 100644 --- a/crates/candler-core/tests/it/support/mod.rs +++ b/crates/candler-core/tests/it/support/mod.rs @@ -18,6 +18,7 @@ pub mod plugin_env; pub mod run_evidence; pub mod run_exec; pub mod run_plan; +pub mod sealed_run; pub mod session_rig; pub mod supervision_gates; pub mod test_image; diff --git a/crates/candler-core/tests/it/support/run_plan.rs b/crates/candler-core/tests/it/support/run_plan.rs index 03468058..e1253fbf 100644 --- a/crates/candler-core/tests/it/support/run_plan.rs +++ b/crates/candler-core/tests/it/support/run_plan.rs @@ -146,7 +146,6 @@ fn manifest_json(run: &Run<'_>, cell: &str) -> Value { "values": values, "harness": {"name": "claude-code", "version": run.facts.version}, "treatment": treatment(run.facts), - "snapshots": [], "inputs": inputs_json(run.facts), "environments": [], }, diff --git a/crates/candler-core/tests/it/support/sealed_run.rs b/crates/candler-core/tests/it/support/sealed_run.rs new file mode 100644 index 00000000..0c03fa45 --- /dev/null +++ b/crates/candler-core/tests/it/support/sealed_run.rs @@ -0,0 +1,62 @@ +//! The one producer of a sealed run that holds output files, for guards that read what a run +//! stored. It seals through the runner's own `seal_run`, the step that stores each output's blob, +//! so a gap in that step shows in every guard that reads outputs. + +use std::fs; +use std::str::FromStr as _; + +use candler_core::runner::exec::seal::seal_run; +use candler_core::store::Store; +use candler_core::store::run::{Existing, RunWriter}; +use candler_schemas::execution::{RunManifest, RunTree, TreeEntry}; +use candler_schemas::primitives::{Digest, RelPath, RunKey}; +use candler_schemas::trace::TraceFile; + +/// One file the agent left in its workspace. +pub struct File { + pub path: &'static str, + pub bytes: &'static [u8], +} + +/// A trace of no session: the header alone. +fn empty_trace() -> TraceFile { + let header = r#"{"kind":"header","schema":"normalised-trace/1","reader":"claude-code-reader@0.1.0","raw":[]}"#; + TraceFile::read(format!("{header}\n").as_bytes()).expect("a trace file") +} + +/// Seals a new run beside `template`, whose manifest it copies with `attempt`, over a workspace +/// that holds exactly `files`, and returns its key. The runner's `seal_run` stores each file as a +/// blob, then writes the manifest, the tree and `run.done`. +pub fn seal_workspace(store: &Store, template: &RunKey, attempt: u32, files: &[File]) -> RunKey { + let mut manifest = serde_json::to_value(store.read_manifest(template).expect("the manifest")) + .expect("a manifest serialises"); + *manifest + .pointer_mut("/run/attempt") + .expect("the manifest names an attempt") = attempt.into(); + let manifest: RunManifest = serde_json::from_value(manifest).expect("a manifest reads"); + + let workspace = tempfile::tempdir().expect("a workspace"); + let mut tree = RunTree::builder(); + for file in files { + let at = workspace.path().join(file.path); + fs::create_dir_all(at.parent().expect("a parent")).expect("a directory"); + fs::write(&at, file.bytes).expect("a file writes"); + tree = tree.entry(TreeEntry::file( + RelPath::from_str(file.path).expect("a path"), + Digest::of_bytes(file.bytes), + false, + )); + } + let key = manifest.run().clone(); + let writer = RunWriter::create(store, &manifest, Existing::Refuse).expect("a run starts"); + seal_run( + writer, + workspace.path(), + &manifest, + &tree.build().expect("a tree"), + &[], + &empty_trace(), + ) + .expect("the run seals"); + key +} diff --git a/crates/candler-core/tests/it/support/session_rig.rs b/crates/candler-core/tests/it/support/session_rig.rs index fa753240..e369f799 100644 --- a/crates/candler-core/tests/it/support/session_rig.rs +++ b/crates/candler-core/tests/it/support/session_rig.rs @@ -28,8 +28,8 @@ use candler_core::supervise::stop::Exit; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ - Capabilities, Cell, CollectSpec, CommandSpec, GatewayEnv, HarnessId, Observed, ProcessExit, - SessionTracker, StatePath, StopSpec, Workspace, + AgentSetting, Answer, Cell, CollectSpec, CommandSpec, DriverFact, GatewayEnv, HarnessId, + Observed, ProcessExit, SessionTracker, StatePath, StopSpec, Workspace, }; use candler_harness_claude_code::driver::ClaudeCodeDriver; use candler_schemas::execution::Comparable; @@ -183,7 +183,6 @@ fn comparable_of(values: &[(String, Value)]) -> Comparable { "values": entries, "harness": {"name": "claude-code", "version": "2.1.311"}, "treatment": {"name": "htn"}, - "snapshots": [], "inputs": [], "environments": [], })) @@ -233,8 +232,12 @@ impl HarnessDriver for Driver { fn parse_version(&self, output: &[u8]) -> Result<semver::Version, DriverError> { self.inner.parse_version(output) } - fn capabilities(&self) -> Capabilities { - self.inner.capabilities() + fn answer(&self, setting: AgentSetting) -> Answer { + self.inner.answer(setting) + } + + fn fact(&self, fact: DriverFact) -> Answer { + self.inner.fact(fact) } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result<Plan, DriverError> { let mut plan = self.inner.plan(cell, workspace)?; @@ -261,8 +264,12 @@ impl HarnessDriver for Driver { fn live_reader(&self) -> Option<Box<dyn TraceReader>> { self.inner.live_reader() } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { - self.inner.offline_reader(stream) + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { + self.inner.offline_reader(stream, servers) } fn classify_exit(&self, exit: &ProcessExit, sessions: &[Session]) -> EndedBy { self.inner.classify_exit(exit, sessions) diff --git a/crates/candler-core/tests/it/support/wiring.rs b/crates/candler-core/tests/it/support/wiring.rs index fbe78a75..b7bff5df 100644 --- a/crates/candler-core/tests/it/support/wiring.rs +++ b/crates/candler-core/tests/it/support/wiring.rs @@ -25,8 +25,8 @@ use candler_core::supervise::{EventSink, Supervisor}; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ - Capabilities, Cell, CollectSpec, CommandSpec, EnvEntry, GatewayEnv, HarnessId, Observed, - Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, Workspace, + AgentSetting, Answer, Cell, CollectSpec, CommandSpec, DriverFact, EnvEntry, GatewayEnv, + HarnessId, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, Workspace, }; use candler_harness_opencode::driver::OpenCodeDriver; use candler_schemas::execution::EventPayload; @@ -140,8 +140,12 @@ impl HarnessDriver for WiringDriver { self.0.parse_version(output) } - fn capabilities(&self) -> Capabilities { - self.0.capabilities() + fn answer(&self, setting: AgentSetting) -> Answer { + self.0.answer(setting) + } + + fn fact(&self, fact: DriverFact) -> Answer { + self.0.fact(fact) } fn plan(&self, _cell: &Cell<'_>, _workspace: &Workspace<'_>) -> Result<Plan, DriverError> { @@ -191,8 +195,12 @@ impl HarnessDriver for WiringDriver { } // TRAIT_OBJECT: the host hands out its trace reader as a trait object - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { - self.0.offline_reader(stream) + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { + self.0.offline_reader(stream, servers) } fn classify_exit(&self, exit: &ProcessExit, sessions: &[Session]) -> EndedBy { diff --git a/crates/candler-core/tests/oracle/vectors/catalog_content_digest.toml b/crates/candler-core/tests/oracle/vectors/catalog_content_digest.toml deleted file mode 100644 index 2a50b3d0..00000000 --- a/crates/candler-core/tests/oracle/vectors/catalog_content_digest.toml +++ /dev/null @@ -1,42 +0,0 @@ -# catalog_content_digest.toml: catalog snapshot content digests (R01 §Wire schema: tool-catalog snapshot). -# Generated by tests/oracle/vectors/gen_vectors.py (python, `uv run --with rfc8785`), -# rfc8785 0.1.4. Do not edit: run the generator and commit the result. -# JSON values are carried as JSON text; every digest is sha256 of the RFC 8785 form. -# Spellings that R01 leaves open are marked ASSUMED, as in gen_vectors.py: -# 1. Imported cells (`cell_digest.toml`, the three mini-corpus cells; rules of -# legacy_mapping.md Step 2 item 3): `comparable.values` holds each JSON leaf of -# `experiment.json` under `plan.*` (without `plan.out_dir`), `provenance.*` and -# `resolved_skill_version`, as a dotted path, a `null` leaf without `value`; the root -# `schema_version` is left out. `harness` is `{name: "claude-code", version: <init line -# claude_code_version>}` without `driver`. `treatment` is `{name, tag}` split from -# `/plan/skill_version` (`htn-creator@v0.2.3`). `snapshots` is one `{kind: "catalog", digest: -# "sha256:" + PROVENANCE.json /catalog/sha256}`. `inputs` is `timing.json` `copied_inputs[]` -# as `{kind: <role>, digest: "sha256:" + <sha256>}` (`relpath` is dropped; the copies of a -# cell must agree). `environments` is empty. -# 2. `NameVersion` is the string `name@version` wherever it appears in a JSON value -# (`harness.driver`, `environments[].plugin`, catalog `provider`). -# 3. A digest inside a JSON value is the string `sha256:<64 hex>` (`artifacts[].sha256`, -# `snapshots[].digest`, `inputs[].digest`, `lock_digest`, `source_digest`). -# 4. `applies_to` keeps its written order; only `depends_on` is sorted. -# 5. The run key path form is `<cell hex>-r<n>-a<m>` with the cell hex the 64 bare hex digits of -# the cell digest and `m` = 1 for an import. -# 6. "The three mini-corpus runs" of `request_id.toml` are the three real runs (run-6, run-17, -# run-12); a contaminated run gets no request, and the two valid synthetic runs are left out. -# 7. "The first 74 bits of the hash" read the sha256 as a big-endian integer: `rand_a` is bits -# 0..12 and `rand_b` bits 12..74, counted from the most significant bit. -# 8. `regraded_at.finished` has no fraction, so the 48-bit time is its whole seconds times 1000. -# 9. Sorting by `path`, `(kind, digest)` and `(plugin, lock_digest)` is by Unicode code point -# (the order of UTF-8 bytes); the vectors keep their sort keys ASCII. -# 10. The `cell` key of a vector is the mini-corpus cell directory name, or `invented-<n>`. - - -# `document_a` and `document_b` differ only in `captured_at` and share `digest_ab`; -# `document_c` differs in one tool description and has `digest_c`. Each digest is over the -# RFC 8785 form of the document without `captured_at`. - -[[vector]] -document_a = "{\"schema\":\"tool-catalog-snapshot/1\",\"captured_at\":\"2026-10-01T00:00:00Z\",\"provider\":\"rikyu-catalog@0.1.0\",\"environment\":{\"python\":\"3.12.4\",\"mcp\":\"1.9.0\"},\"servers\":[{\"name\":\"rikyu\",\"source_path\":\"servers/rikyu_mcp\",\"source_digest\":\"sha256:b36f116705db6e420b3a4d90a22ec24341c16083e36338220f499aaac341d9e2\",\"transport\":\"stdio\",\"tools\":[{\"name\":\"submit_job\",\"description\":\"Submit a batch job.\",\"inputSchema\":{\"type\":\"object\",\"properties\":{\"script\":{\"type\":\"string\"},\"nodes\":{\"type\":\"integer\"}},\"required\":[\"script\"]},\"annotations\":{\"readOnlyHint\":false}},{\"name\":\"get_job_status\",\"description\":\"Report a job's state.\",\"inputSchema\":{\"type\":\"object\",\"properties\":{\"job_id\":{\"type\":\"string\"}}},\"title\":\"Job status\"}]}]}" -document_b = "{\"schema\":\"tool-catalog-snapshot/1\",\"captured_at\":\"2026-10-28T12:34:56+09:00\",\"provider\":\"rikyu-catalog@0.1.0\",\"environment\":{\"python\":\"3.12.4\",\"mcp\":\"1.9.0\"},\"servers\":[{\"name\":\"rikyu\",\"source_path\":\"servers/rikyu_mcp\",\"source_digest\":\"sha256:b36f116705db6e420b3a4d90a22ec24341c16083e36338220f499aaac341d9e2\",\"transport\":\"stdio\",\"tools\":[{\"name\":\"submit_job\",\"description\":\"Submit a batch job.\",\"inputSchema\":{\"type\":\"object\",\"properties\":{\"script\":{\"type\":\"string\"},\"nodes\":{\"type\":\"integer\"}},\"required\":[\"script\"]},\"annotations\":{\"readOnlyHint\":false}},{\"name\":\"get_job_status\",\"description\":\"Report a job's state.\",\"inputSchema\":{\"type\":\"object\",\"properties\":{\"job_id\":{\"type\":\"string\"}}},\"title\":\"Job status\"}]}]}" -document_c = "{\"schema\":\"tool-catalog-snapshot/1\",\"captured_at\":\"2026-10-01T00:00:00Z\",\"provider\":\"rikyu-catalog@0.1.0\",\"environment\":{\"python\":\"3.12.4\",\"mcp\":\"1.9.0\"},\"servers\":[{\"name\":\"rikyu\",\"source_path\":\"servers/rikyu_mcp\",\"source_digest\":\"sha256:b36f116705db6e420b3a4d90a22ec24341c16083e36338220f499aaac341d9e2\",\"transport\":\"stdio\",\"tools\":[{\"name\":\"submit_job\",\"description\":\"Submit a batch job.\",\"inputSchema\":{\"type\":\"object\",\"properties\":{\"script\":{\"type\":\"string\"},\"nodes\":{\"type\":\"integer\"}},\"required\":[\"script\"]},\"annotations\":{\"readOnlyHint\":false}},{\"name\":\"get_job_status\",\"description\":\"Report the state of a job.\",\"inputSchema\":{\"type\":\"object\",\"properties\":{\"job_id\":{\"type\":\"string\"}}},\"title\":\"Job status\"}]}]}" -digest_ab = "sha256:b55154910fbe9fe54e0b8333367a9ff3d1a168bb27d070826e3e87e02efe4d3f" -digest_c = "sha256:ac392343adc17e8add50c9d7da2506f86fc5786455d5dba89973a9e85e2e32f9" diff --git a/crates/candler-core/tests/oracle/vectors/cell_digest.toml b/crates/candler-core/tests/oracle/vectors/cell_digest.toml index 62a41296..c268f9e6 100644 --- a/crates/candler-core/tests/oracle/vectors/cell_digest.toml +++ b/crates/candler-core/tests/oracle/vectors/cell_digest.toml @@ -28,6 +28,10 @@ # 9. Sorting by `path`, `(kind, digest)` and `(plugin, lock_digest)` is by Unicode code point # (the order of UTF-8 bytes); the vectors keep their sort keys ASCII. # 10. The `cell` key of a vector is the mini-corpus cell directory name, or `invented-<n>`. +# A cell that carries `snapshots`, empty or not, is hashed with the list; a cell without +# the key is hashed without it (`invented-4`, the shape of every new cell). The vectors that +# carry `snapshots` stay: the maintainer's own stores (golden and HTN runs) hold manifests of +# that shape, and their cell digests must still verify. Do not prune them as dead. # `comparable` is sorted and unique; `shuffled` has the same content with every list in @@ -81,3 +85,11 @@ digest = "sha256:c70cb4f61e13566626e33e737c05c1570068174ee7cd0c420006f41483f1da0 shuffled = "{\"values\":[{\"path\":\"plan.base_url\"},{\"path\":\"plan.small_float\",\"value\":1e-07},{\"path\":\"plan.empty_text\",\"value\":\"\"},{\"path\":\"plan.list\",\"value\":[true,null,1.5,\"x\",{\"k\":[]}]},{\"path\":\"plan.config\",\"value\":\"with_skill\"},{\"path\":\"plan.big_float\",\"value\":1e+21},{\"path\":\"plan.tenth\",\"value\":0.1},{\"path\":\"plan.whole_float\",\"value\":100.0},{\"path\":\"plan.escapes\",\"value\":\"quote \\\" backslash \\\\ bell \\u0007 newline \\n tab \\t slash /\"}],\"harness\":{\"name\":\"claude-code\",\"version\":\"2.2.0-rc.1+build.5\"},\"treatment\":{\"name\":\"skill-c\",\"commit\":\"fedcba9876543210fedcba9876543210fedcba98\"},\"snapshots\":[{\"kind\":\"tool-catalog\",\"digest\":\"sha256:7779b5757ec40665a4d841352991164cf1eb89b33949b1bdad633b216ca4d9d3\"}],\"inputs\":[],\"environments\":[{\"plugin\":\"htn-creator-eval@0.4.2\",\"lock_digest\":\"sha256:16e3e848411f9748bb5c8ec006bd137b4881a57e47faca06683f6fd69c561b1b\"}]}" outside = "{\"sources\":[{\"path\":\"plan.model\",\"source\":{\"kind\":\"experiment_file\"}}],\"secrets\":[{\"name\":\"ANTHROPIC_API_KEY\",\"present\":true}],\"measured\":[{\"path\":\"run.exit\",\"value\":{\"code\":0},\"source\":{\"kind\":\"core_default\"}}],\"started_at\":\"2026-08-06T03:59:40Z\",\"ended_at\":\"2026-08-06T04:10:00Z\",\"host\":\"host-a-6\"}" outside_twin = "{\"sources\":[{\"path\":\"plan.model\",\"source\":{\"kind\":\"explicit_argument\"}},{\"path\":\"plan.runs\",\"source\":{\"kind\":\"user_config\"}}],\"secrets\":[],\"measured\":[],\"started_at\":\"2027-01-02T10:00:00+09:00\",\"ended_at\":\"2027-01-02T11:30:15.250+09:00\",\"host\":\"other-host-6\"}" + +[[vector]] +cell = "invented-4" +comparable = "{\"values\":[{\"path\":\"budget.per_run.max_cost_usd\",\"value\":1.5},{\"path\":\"budget.per_run.wall_s\",\"value\":600},{\"path\":\"isolation.network\",\"value\":false},{\"path\":\"plan.max_int\",\"value\":9007199254740991},{\"path\":\"plan.min_int\",\"value\":-9007199254740991},{\"path\":\"plan.model\",\"value\":\"model-\\u00e9\\u00e8\"},{\"path\":\"plan.negative_zero\",\"value\":-0.0},{\"path\":\"plan.nested\",\"value\":{\"\\ud83d\\ude00\":1,\"\\u20ac\":2,\"b\":[3,2,1],\"A\":{\"z\":null}}}],\"harness\":{\"name\":\"claude-code\",\"version\":\"2.1.220\",\"driver\":\"headless@0.3.0\"},\"treatment\":{\"name\":\"skill-b\",\"tag\":\"v1.2.0\",\"commit\":\"0123456789abcdef0123456789abcdef01234567\"},\"inputs\":[{\"kind\":\"domain\",\"digest\":\"sha256:06d968ff9f1401e4a642561c62168380284160ca68d2efc3ac74ee2101d52121\"},{\"kind\":\"prompt\",\"digest\":\"sha256:7ed65932e8020d4d9f9f6a3685dd16ea62b9bd0477726edcf734750de827e343\"}],\"environments\":[{\"plugin\":\"another-eval@1.0.0\",\"lock_digest\":\"sha256:80be0631f286fe7e12719ab399568f969c31d98f4bf6321666f58cc15e21ba4f\"},{\"plugin\":\"htn-creator-eval@0.4.2\",\"lock_digest\":\"sha256:5ca54ae935ebe6a895ac8f31606e4db256628778d35f562ff44ee0aba658c349\"}]}" +digest = "sha256:91d798487a05112c80a75e68f970890d0df5fd7e40f5f67288385dfcaf5ffdd9" +shuffled = "{\"values\":[{\"path\":\"plan.negative_zero\",\"value\":-0.0},{\"path\":\"plan.nested\",\"value\":{\"\\ud83d\\ude00\":1,\"\\u20ac\":2,\"b\":[3,2,1],\"A\":{\"z\":null}}},{\"path\":\"budget.per_run.max_cost_usd\",\"value\":1.5},{\"path\":\"plan.min_int\",\"value\":-9007199254740991},{\"path\":\"plan.max_int\",\"value\":9007199254740991},{\"path\":\"plan.model\",\"value\":\"model-\\u00e9\\u00e8\"},{\"path\":\"isolation.network\",\"value\":false},{\"path\":\"budget.per_run.wall_s\",\"value\":600}],\"harness\":{\"name\":\"claude-code\",\"version\":\"2.1.220\",\"driver\":\"headless@0.3.0\"},\"treatment\":{\"name\":\"skill-b\",\"tag\":\"v1.2.0\",\"commit\":\"0123456789abcdef0123456789abcdef01234567\"},\"inputs\":[{\"kind\":\"prompt\",\"digest\":\"sha256:7ed65932e8020d4d9f9f6a3685dd16ea62b9bd0477726edcf734750de827e343\"},{\"kind\":\"domain\",\"digest\":\"sha256:06d968ff9f1401e4a642561c62168380284160ca68d2efc3ac74ee2101d52121\"}],\"environments\":[{\"plugin\":\"htn-creator-eval@0.4.2\",\"lock_digest\":\"sha256:5ca54ae935ebe6a895ac8f31606e4db256628778d35f562ff44ee0aba658c349\"},{\"plugin\":\"another-eval@1.0.0\",\"lock_digest\":\"sha256:80be0631f286fe7e12719ab399568f969c31d98f4bf6321666f58cc15e21ba4f\"}]}" +outside = "{\"sources\":[{\"path\":\"plan.model\",\"source\":{\"kind\":\"experiment_file\"}}],\"secrets\":[{\"name\":\"ANTHROPIC_API_KEY\",\"present\":true}],\"measured\":[{\"path\":\"run.exit\",\"value\":{\"code\":0},\"source\":{\"kind\":\"core_default\"}}],\"started_at\":\"2026-08-06T03:59:40Z\",\"ended_at\":\"2026-08-06T04:10:00Z\",\"host\":\"host-a-7\"}" +outside_twin = "{\"sources\":[{\"path\":\"plan.model\",\"source\":{\"kind\":\"explicit_argument\"}},{\"path\":\"plan.runs\",\"source\":{\"kind\":\"user_config\"}}],\"secrets\":[],\"measured\":[],\"started_at\":\"2027-01-02T10:00:00+09:00\",\"ended_at\":\"2027-01-02T11:30:15.250+09:00\",\"host\":\"other-host-7\"}" diff --git a/crates/candler-core/tests/oracle/vectors/field_paths.toml b/crates/candler-core/tests/oracle/vectors/field_paths.toml index 910fa639..46b57f4e 100644 --- a/crates/candler-core/tests/oracle/vectors/field_paths.toml +++ b/crates/candler-core/tests/oracle/vectors/field_paths.toml @@ -179,11 +179,6 @@ path = "inputs[]" class = "typed_root" source = "derived digests: server sources and the Dockerfile" -[[path]] -path = "snapshots" -class = "typed_root" -source = "derived: the catalog digest from the CatalogProvider" - [[path]] path = "environments" class = "typed_root" diff --git a/crates/candler-core/tests/oracle/vectors/gen_vectors.py b/crates/candler-core/tests/oracle/vectors/gen_vectors.py index 571e0563..c4100673 100644 --- a/crates/candler-core/tests/oracle/vectors/gen_vectors.py +++ b/crates/candler-core/tests/oracle/vectors/gen_vectors.py @@ -1,10 +1,10 @@ """Generate the digest and identity vectors, with a second engine, from R01's text. - uv run --with rfc8785 python gen_vectors.py # write the six TOML files here + uv run --with rfc8785 python gen_vectors.py # write the five TOML files here uv run --with rfc8785 python gen_vectors.py --check # regenerate in memory and compare Every digest is `sha256` of the RFC 8785 form (python `rfc8785`) of a JSON value built here from -R01 (§Run manifest, §Digests of a request, §Wire schema: tool-catalog snapshot, §Golden corpus). +R01 (§Run manifest, §Digests of a request, §Golden corpus). No Candler code runs. JSON values travel inside the TOML files as JSON text, so number tokens and key order reach the Rust test exactly as written. @@ -82,7 +82,6 @@ "cell_digest.toml", "context_digest.toml", "suite_entry_digest.toml", - "catalog_content_digest.toml", "request_id.toml", "context_digest_runs.toml", ) @@ -149,7 +148,8 @@ def sort_comparable(c): """R01: values by path, the other lists by their fields in order.""" c = json.loads(jtext(c)) c["values"].sort(key=lambda v: v["path"]) - c["snapshots"].sort(key=lambda r: (r["kind"], r["digest"])) + if "snapshots" in c: + c["snapshots"].sort(key=lambda r: (r["kind"], r["digest"])) c["inputs"].sort(key=lambda r: (r["kind"], r["digest"])) c["environments"].sort(key=lambda r: (r["plugin"], r["lock_digest"])) return c @@ -164,13 +164,16 @@ def comparable(values, harness, treatment, snapshots, inputs, environments): "inputs": inputs, "environments": environments, } + if snapshots is None: + del unsorted["snapshots"] return sort_comparable(unsorted) def shuffled(c, seed): out = json.loads(jtext(c)) for i, key in enumerate(("values", "snapshots", "inputs", "environments")): - out[key] = reordered(out[key], seed * 10 + i) + if key in out: + out[key] = reordered(out[key], seed * 10 + i) return out @@ -280,7 +283,20 @@ def invented_cells(): [], [{"plugin": "htn-creator-eval@0.4.2", "lock_digest": hexd("lock-c")}], ) - return [("invented-1", one), ("invented-2", two), ("invented-3", three)] + four = comparable( + two["values"], + two["harness"], + two["treatment"], + None, + two["inputs"], + two["environments"], + ) + return [ + ("invented-1", one), + ("invented-2", two), + ("invented-3", three), + ("invented-4", four), + ] def outside_hash(n, variant): @@ -311,7 +327,16 @@ def outside_hash(n, variant): def cell_vectors(): cells = [(name, mini_cell(name)) for name in CELLS] + invented_cells() - out = [header("cell_digest.toml", "cell digest vectors (R01 §Run manifest, §Golden corpus).")] + out = [ + header( + "cell_digest.toml", + "cell digest vectors (R01 §Run manifest, §Golden corpus).", + "A cell that carries `snapshots`, empty or not, is hashed with the list; a cell without\n" + "the key is hashed without it (`invented-4`, the shape of every new cell). The vectors that\n" + "carry `snapshots` stay: the maintainer's own stores (golden and HTN runs) hold manifests of\n" + "that shape, and their cell digests must still verify. Do not prune them as dead.", + ) + ] out.append( "# `comparable` is sorted and unique; `shuffled` has the same content with every list in\n" "# another order (the builder sorts it); `outside` and `outside_twin` are two different\n" @@ -531,68 +556,6 @@ def suite_vectors(): return "\n".join(out), entries -# ---------------------------------------------------------------- catalog - - -def catalog(captured_at, tool_two_description): - return { - "schema": "tool-catalog-snapshot/1", - "captured_at": captured_at, - "provider": "rikyu-catalog@0.1.0", - "environment": {"python": "3.12.4", "mcp": "1.9.0"}, - "servers": [ - { - "name": "rikyu", - "source_path": "servers/rikyu_mcp", - "source_digest": hexd("rikyu-source"), - "transport": "stdio", - "tools": [ - { - "name": "submit_job", - "description": "Submit a batch job.", - "inputSchema": { - "type": "object", - "properties": {"script": {"type": "string"}, "nodes": {"type": "integer"}}, - "required": ["script"], - }, - "annotations": {"readOnlyHint": False}, - }, - { - "name": "get_job_status", - "description": tool_two_description, - "inputSchema": {"type": "object", "properties": {"job_id": {"type": "string"}}}, - "title": "Job status", - }, - ], - } - ], - } - - -def catalog_vectors(): - a = catalog("2026-10-01T00:00:00Z", "Report a job's state.") - b = catalog("2026-10-28T12:34:56+09:00", "Report a job's state.") - c = catalog("2026-10-01T00:00:00Z", "Report the state of a job.") - - def without_time(doc): - return {k: v for k, v in doc.items() if k != "captured_at"} - - out = [header("catalog_content_digest.toml", "catalog snapshot content digests (R01 §Wire schema: tool-catalog snapshot).")] - out.append( - "# `document_a` and `document_b` differ only in `captured_at` and share `digest_ab`;\n" - "# `document_c` differs in one tool description and has `digest_c`. Each digest is over the\n" - "# RFC 8785 form of the document without `captured_at`.\n" - ) - out.append("[[vector]]") - out.append(f"document_a = {toml_str(jtext(a))}") - out.append(f"document_b = {toml_str(jtext(b))}") - out.append(f"document_c = {toml_str(jtext(c))}") - out.append(f"digest_ab = {toml_str(digest_of(without_time(a)))}") - out.append(f"digest_c = {toml_str(digest_of(without_time(c)))}") - out.append("") - return "\n".join(out), (a, b, c, without_time) - - # ---------------------------------------------------------------- request id @@ -644,23 +607,22 @@ def generate(): cells_text, comparables = cell_vectors() context_text, context_cases = context_vectors() suite_text, suite_entries = suite_vectors() - catalog_text, catalog_docs = catalog_vectors() request_text, request_rows = request_vectors(comparables) runs_text, _runs = run_context_vectors() texts = dict( - zip(FILES, (cells_text, context_text, suite_text, catalog_text, request_text, runs_text)) + zip(FILES, (cells_text, context_text, suite_text, request_text, runs_text)) ) - return texts, comparables, context_cases, suite_entries, catalog_docs, request_rows + return texts, comparables, context_cases, suite_entries, request_rows -def invariants(comparables, context_cases, suite_entries, catalog_docs, request_rows): +def invariants(comparables, context_cases, suite_entries, request_rows): """Properties of the vectors themselves, checked independently of the files.""" for name, c in comparables.items(): base = digest_of(c) assert digest_of(sort_comparable(shuffled(c, 7))) == base, name assert digest_of(sort_comparable(shuffled(c, 8))) == base, name for key in ("values", "snapshots", "inputs", "environments"): - if len(c[key]) > 1: + if len(c.get(key, [])) > 1: assert shuffled(c, 7)[key] != c[key] or shuffled(c, 8)[key] != c[key], (name, key) assert len({digest_of(c) for c in comparables.values()}) == len(comparables) for _title, artifacts, snapshots, inputs, metadata in context_cases: @@ -670,9 +632,6 @@ def invariants(comparables, context_cases, suite_entries, catalog_docs, request_ for n, entry in enumerate(suite_entries, start=1): assert digest_of(suite_projection(entry)) == digest_of(suite_projection(twin(entry, n))) assert len({digest_of(suite_projection(e)) for e in suite_entries}) == len(suite_entries) - a, b, c, without_time = catalog_docs - assert digest_of(without_time(a)) == digest_of(without_time(b)) != digest_of(without_time(c)) - assert digest_of(a) != digest_of(b) assert len({r[4] for r in request_rows}) == len(request_rows) for _cell, _n, _path, _hash, rid in request_rows: assert len(rid) == 36 and rid[14] == "7" and rid[19] in "89ab" and rid == rid.lower(), rid @@ -682,8 +641,8 @@ def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--check", action="store_true", help="compare with the files on disk") args = ap.parse_args() - texts, comparables, context_cases, suite_entries, catalog_docs, request_rows = generate() - invariants(comparables, context_cases, suite_entries, catalog_docs, request_rows) + texts, comparables, context_cases, suite_entries, request_rows = generate() + invariants(comparables, context_cases, suite_entries, request_rows) for name, text in texts.items(): tomllib.loads(text) if not args.check: diff --git a/crates/candler-harness-claude-code/Cargo.toml b/crates/candler-harness-claude-code/Cargo.toml index 9de50655..0b2b3d9a 100644 --- a/crates/candler-harness-claude-code/Cargo.toml +++ b/crates/candler-harness-claude-code/Cargo.toml @@ -17,6 +17,7 @@ serde_json.workspace = true thiserror.workspace = true [dev-dependencies] +candler-core.workspace = true candler-testkit.workspace = true candler-harness = { workspace = true, features = ["conformance"] } flate2.workspace = true diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index 5e66d961..868da7fe 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -10,13 +10,15 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ - BaseImage, BudgetCaps, Capabilities, Cell, CollectSpec, CommandSpec, GatewayEnv, HarnessId, - Observed, Prepared, ProcessExit, SessionTracker, StopSignal, StopSpec, Workspace, + AgentSetting, Answer, BaseImage, Cell, CollectSpec, CommandSpec, DriverFact, EffortLevel, + GatewayEnv, HarnessId, Observed, PermissionMode, Prepared, ProcessExit, SessionTracker, + StopSignal, StopSpec, Workspace, }; use candler_schemas::execution::paths; use candler_schemas::name; use candler_schemas::primitives::FieldPath; use candler_schemas::raw::StreamName; +use candler_schemas::servers::McpServerKind; use candler_schemas::trace::{EndedBy, Session}; use semver::{Version, VersionReq}; use serde_json::Value; @@ -108,12 +110,12 @@ pub(crate) fn argv(cell: &Cell<'_>, launch: Launch) -> Result<Vec<String>, Drive "--setting-sources", "project,local", "--permission-mode", - mode, + mode.as_str(), ] .map(str::to_owned), // BORROW: str::to_owned makes the owned arguments ); if let Some(effort) = cell.effort()? { - argv.extend(["--effort", effort].map(str::to_owned)); // BORROW: str::to_owned makes the owned arguments + argv.extend(["--effort", effort.as_str()].map(str::to_owned)); // BORROW: str::to_owned makes the owned arguments } if let Some(turns) = cap_text(cell, paths::BUDGET_PER_RUN_TURNS, true)? { argv.push("--max-turns".to_owned()); // BORROW: .to_owned() makes the owned argument @@ -123,7 +125,7 @@ pub(crate) fn argv(cell: &Cell<'_>, launch: Launch) -> Result<Vec<String>, Drive argv.push("--max-budget-usd".to_owned()); // BORROW: .to_owned() makes the owned argument argv.push(cost); } - if prepare::mcp_servers(cell)?.is_some() { + if candler_harness::mcp::servers(cell)?.is_some() { // Only the servers of the cell: no other MCP configuration reaches the agent. argv.extend(["--mcp-config", prepare::MCP_FILE, "--strict-mcp-config"].map(str::to_owned)); // BORROW: str::to_owned makes the owned arguments } @@ -197,14 +199,109 @@ impl HarnessDriver for ClaudeCodeDriver { }) } - fn capabilities(&self) -> Capabilities { - Capabilities::builder() - .graceful_stop(true) - .live_events(true) - .budgets(BudgetCaps::new(true, true)) - .census(true) - .session(true) - .build() + fn answer(&self, setting: AgentSetting) -> Answer { + match setting { + AgentSetting::ModelId => Answer::Mapped { + construct: "`--model` on the command line", + }, + AgentSetting::ModelEndpoint => Answer::Candler { + how: "the gateway forwards model requests to the endpoint", + }, + AgentSetting::Effort( + EffortLevel::Low + | EffortLevel::Medium + | EffortLevel::High + | EffortLevel::Xhigh + | EffortLevel::Max, + ) => Answer::Mapped { + construct: "`--effort <level>` on the command line", + }, + AgentSetting::Effort(EffortLevel::Ultracode) => Answer::Mapped { + construct: "`--effort ultracode` on the command line, which Claude Code reads as `xhigh` with its ultracode mode on", + }, + AgentSetting::PermissionMode( + PermissionMode::Default + | PermissionMode::AcceptEdits + | PermissionMode::Plan + | PermissionMode::BypassPermissions + | PermissionMode::Auto + | PermissionMode::DontAsk, + ) => Answer::Mapped { + construct: "`--permission-mode <mode>` on the command line", + }, + AgentSetting::ToolsAllowed => Answer::Mapped { + construct: "`permissions.allow` of `.claude/settings.json`", + }, + AgentSetting::ToolsDisallowed => Answer::Mapped { + construct: "`permissions.deny` of `.claude/settings.json`", + }, + AgentSetting::Env => Answer::Candler { + how: "the core sets the cell's variables on the agent's process", + }, + AgentSetting::Inputs => Answer::Candler { + how: "the core places the inputs in the workspace", + }, + AgentSetting::Skills => Answer::Mapped { + construct: "the project skill directory", + }, + AgentSetting::McpTransport(McpServerKind::Stdio | McpServerKind::Local) => { + Answer::Mapped { + construct: "an entry of `mcpServers` in `.mcp.json`, of type `stdio`", + } + } + AgentSetting::McpTransport(McpServerKind::Http | McpServerKind::Remote) => { + Answer::Mapped { + construct: "an entry of `mcpServers` in `.mcp.json`, of type `http`", + } + } + AgentSetting::McpTransport(McpServerKind::Sse) => Answer::Mapped { + construct: "an entry of `mcpServers` in `.mcp.json`, of type `sse`", + }, + AgentSetting::Codemode(true) => Answer::Refused { + reason: "Claude Code offers MCP tools directly; it has no code mode", + }, + AgentSetting::Codemode(false) => Answer::Mapped { + construct: "no key: Claude Code offers the server's tools directly", + }, + AgentSetting::McpName => Answer::Mapped { + construct: "the key of the server's `.mcp.json` entry", + }, + AgentSetting::WallBudget => Answer::Candler { + how: "the core ends the run at the wall budget", + }, + AgentSetting::TurnBudget => Answer::Mapped { + construct: "`--max-turns` on the command line", + }, + AgentSetting::CostBudget => Answer::Mapped { + construct: "`--max-budget-usd` on the command line", + }, + AgentSetting::SessionMode => Answer::Mapped { + construct: "stream-json over an open stdin, one turn per message", + }, + } + } + + fn fact(&self, fact: DriverFact) -> Answer { + match fact { + DriverFact::GracefulStop => Answer::Mapped { + construct: "SIGTERM ends the sessions cleanly", + }, + DriverFact::LiveEvents => Answer::Mapped { + construct: "stream-json events on stdout while the run lasts", + }, + DriverFact::InHarnessGuard => Answer::Refused { + reason: "the driver configures no Claude Code hook", + }, + DriverFact::ExecutionOutsideChild => Answer::Refused { + reason: "tools run in the child process", + }, + DriverFact::Census => Answer::Mapped { + construct: "Claude Code's `system/init` event lists the tools", + }, + DriverFact::UnsetPermissionMode => Answer::Mapped { + construct: "`--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it", + }, + } } fn gateway(&self) -> Option<GatewayEnv> { @@ -221,11 +318,14 @@ impl HarnessDriver for ClaudeCodeDriver { } fn check_settings(&self, cell: &Cell<'_>) -> Result<(), DriverError> { - prepare::mcp_servers(cell).map(|_| ()) + cap_text(cell, paths::BUDGET_PER_RUN_TURNS, true)?; + cap_text(cell, paths::BUDGET_PER_RUN_MAX_COST_USD, false)?; + candler_harness::mcp::servers(cell).map(|_| ()) } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result<Plan, DriverError> { let _ = workspace; + self.check_settings(cell)?; let mut files = vec![prepare::render_settings(cell)?]; files.extend(prepare::render_mcp(cell)?); let argv = argv(cell, Launch::Headless(cell.prompt()?))?; @@ -244,8 +344,12 @@ impl HarnessDriver for ClaudeCodeDriver { Some(Box::new(ClaudeCodeReader::new())) // TRAIT_OBJECT: the core selects readers at runtime } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { - let _ = stream; + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { + let _ = (stream, servers); None } diff --git a/crates/candler-harness-claude-code/src/parse.rs b/crates/candler-harness-claude-code/src/parse.rs index 7bcc2209..b6fbd6a4 100644 --- a/crates/candler-harness-claude-code/src/parse.rs +++ b/crates/candler-harness-claude-code/src/parse.rs @@ -169,8 +169,8 @@ pub(crate) fn parse(frame: &RawFrame) -> Parsed { } } -/// The inventory an init line lists: its `tools` and, when it has them, its `mcp_servers`, as the -/// line gives them. A line that is not an init line, or lists no tool names, gives none. +/// The inventory an init line lists: its `tools`, as the line gives them. A line that is not an +/// init line, or lists no tool names, gives none. fn init_report(line: &Map<String, Value>) -> Option<InitReport> { let is_init = line.get("type").and_then(Value::as_str) == Some("system") && line.get("subtype").and_then(Value::as_str) == Some("init"); @@ -180,8 +180,6 @@ fn init_report(line: &Map<String, Value>) -> Option<InitReport> { let tools = line.get("tools")?; InitReport::new( tools.clone(), // BORROW: .clone() copies the list out of the line - // BORROW: .cloned() copies the list out of the line - line.get("mcp_servers").filter(|v| v.is_array()).cloned(), CensusSource::Harness, ) .ok() @@ -389,9 +387,9 @@ fn origin_of(name: &str) -> ToolOrigin { .strip_prefix("mcp__") .and_then(|rest| rest.split_once("__")) { - // BORROW: .to_owned() makes the owned server name the origin keeps + // BORROW: .to_owned() makes the owned server and tool names the origin keeps Some((server, tool)) if !server.is_empty() && !tool.is_empty() => { - ToolOrigin::mcp(server.to_owned()) + ToolOrigin::mcp_tool(server.to_owned(), tool.to_owned()) } Some(_) | None => ToolOrigin::Builtin, } diff --git a/crates/candler-harness-claude-code/src/prepare.rs b/crates/candler-harness-claude-code/src/prepare.rs index 344bd5f0..1466e6d3 100644 --- a/crates/candler-harness-claude-code/src/prepare.rs +++ b/crates/candler-harness-claude-code/src/prepare.rs @@ -8,7 +8,9 @@ use std::str::FromStr as _; use candler_harness::driver::DriverError; use candler_harness::spec::{Cell, PreparedFile}; use candler_schemas::execution::paths::{TOOLS_ALLOWED, TOOLS_DISALLOWED}; +use candler_schemas::field_path; use candler_schemas::primitives::RelPath; +use candler_schemas::servers::{McpServer, McpServerKind}; use serde_json::{Map, Value, json}; use crate::driver::invalid; @@ -85,25 +87,62 @@ pub fn render_settings(cell: &Cell<'_>) -> Result<PreparedFile, DriverError> { /// The file the MCP configuration is written to, and that the agent command names. pub(crate) const MCP_FILE: &str = ".mcp.json"; -/// The servers of a cell, by the name the agent sees: see [`candler_harness::mcp::servers`]. -/// -/// # Errors -/// [`DriverError`] when a value of the cell cannot be used, or a server name is refused. -pub fn mcp_servers(cell: &Cell<'_>) -> Result<Option<Map<String, Value>>, DriverError> { - candler_harness::mcp::servers(cell) +/// One server as Claude Code's `.mcp.json` documents it: `stdio` with `command`, `args` and `env`, +/// `http` or `sse` with `url` and `headers`. A `local` server is written as `stdio` and a `remote` +/// one as `http`. +fn mcp_entry(name: &str, server: &McpServer) -> Result<Value, DriverError> { + let refused = |what: &str| DriverError::InvalidValue { + path: field_path!("mcp.servers"), + detail: format!("the server `{name}` {what}"), + }; + let mut out = Map::new(); + match candler_harness::mcp::kind(server) { + McpServerKind::Stdio | McpServerKind::Local => { + let command = server + .command + .as_ref() + .ok_or_else(|| refused("has no `command`"))?; + out.insert("type".to_owned(), json!("stdio")); // BORROW: .to_owned() makes the owned key + out.insert("command".to_owned(), json!(command)); // BORROW: .to_owned() makes the owned key + if let Some(args) = &server.args { + out.insert("args".to_owned(), json!(args)); // BORROW: .to_owned() makes the owned key + } + if let Some(env) = &server.env { + out.insert("env".to_owned(), json!(env)); // BORROW: .to_owned() makes the owned key + } + } + kind @ (McpServerKind::Http | McpServerKind::Sse | McpServerKind::Remote) => { + let url = server.url.as_ref().ok_or_else(|| refused("has no `url`"))?; + let transport = if kind == McpServerKind::Sse { + "sse" + } else { + "http" + }; + out.insert("type".to_owned(), json!(transport)); // BORROW: .to_owned() makes the owned key + out.insert("url".to_owned(), json!(url)); // BORROW: .to_owned() makes the owned key + if let Some(headers) = &server.headers { + out.insert("headers".to_owned(), json!(headers)); // BORROW: .to_owned() makes the owned key + } + } + } + Ok(Value::Object(out)) } /// The `.mcp.json` file of a cell: the servers of `mcp.servers` as `mcpServers`, each under its -/// name. `None` when the cell sets no server. +/// name and written in Claude Code's own shape. `None` when the cell sets no server. /// /// # Errors /// [`DriverError`] when a value of the cell cannot be used. pub fn render_mcp(cell: &Cell<'_>) -> Result<Option<PreparedFile>, DriverError> { - let Some(servers) = mcp_servers(cell)? else { + let Some(servers) = candler_harness::mcp::servers(cell)? else { return Ok(None); }; + let entries = servers + .iter() + .map(|(name, server)| Ok((name.clone(), mcp_entry(name, server)?))) // BORROW: .clone() copies the name into the key + .collect::<Result<Map<String, Value>, DriverError>>()?; let mut root = Map::new(); - root.insert("mcpServers".to_owned(), Value::Object(servers)); // BORROW: .to_owned() makes the owned key + root.insert("mcpServers".to_owned(), Value::Object(entries)); // BORROW: .to_owned() makes the owned key json_file(MCP_FILE, &Value::Object(root)).map(Some) } diff --git a/crates/candler-harness-claude-code/tests/it/conformance.rs b/crates/candler-harness-claude-code/tests/it/conformance.rs index 71f78748..5c220e71 100644 --- a/crates/candler-harness-claude-code/tests/it/conformance.rs +++ b/crates/candler-harness-claude-code/tests/it/conformance.rs @@ -3,8 +3,8 @@ //! recorded sessions. //! //! Every expectation is read from the fixtures' hand-written `expected.toml` facts or from the raw -//! lines with `serde_json`, never from the driver. The inventory a case expects is the `tools` and -//! `mcp_servers` of the first init line, taken from the raw line. +//! lines with `serde_json`, never from the driver. The inventory a case expects is the `tools` of +//! the first init line, taken from the raw line. use std::error::Error; use std::fs; @@ -17,8 +17,8 @@ use candler_harness::conformance::{ }; use candler_harness::driver::HarnessDriver; use candler_harness::spec::{ - Cell, CensusSource, FileRoot, GatewayEnv, InitReport, PendingItem, PendingKind, PendingState, - ProcessEnd, ProcessExit, Workspace, + Cell, CensusSource, CollectSpec, FileRoot, GatewayEnv, InitReport, PendingItem, PendingKind, + PendingState, PreparedFile, ProcessEnd, ProcessExit, Workspace, }; use candler_harness::spec::{SessionClose, SessionRecord}; use candler_harness_claude_code::driver::ClaudeCodeDriver; @@ -26,7 +26,7 @@ use candler_schemas::execution::{GitCommit, TreatmentRef}; use candler_schemas::primitives::{FieldPath, ReasonCode}; use candler_schemas::process::ExitStatus; use candler_schemas::raw::StreamName; -use candler_schemas::trace::{EndedBy, SessionId}; +use candler_schemas::trace::{EndedBy, SessionId, ToolOrigin}; use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::{Value, json}; @@ -84,7 +84,6 @@ fn first_init(bytes: &[u8]) -> Res<InitReport> { let tools = object.get("tools").ok_or("the init line has no tools")?; return Ok(InitReport::new( tools.clone(), // BORROW: .clone() copies the list out of the line - object.get("mcp_servers").cloned(), CensusSource::Harness, )?); } @@ -271,15 +270,71 @@ fn cases() -> Res<Vec<Case>> { ("o3", PendingState::new(1, true, true, vec![])), ], )?, + // The shared oracle: a scripted agent writes these files into a real workspace beside a + // skill file the harness leaves under `.claude`, and the core's file collector applied to + // the driver's specs must store exactly the agent's files. + Case::new( + "collect_stores_the_files_the_agent_wrote".to_owned(), + ReaderSource::Live, + stdout()?, + Vec::new(), + ) + .detects(false) + .with_workspace( + vec![ + PreparedFile::new("notes.md".parse()?, b"kept".to_vec(), false), + PreparedFile::new("outputs/answer.txt".parse()?, b"stamp-7f3a".to_vec(), false), + ], + vec![PreparedFile::new( + ".claude/skills/s/SKILL.md".parse()?, + b"skill".to_vec(), + false, + )], + ), + mcp_call_case()?, ]) } +/// A stream with one call to the tool `t` of the server `s`, spelled `mcp__s__t`. +fn mcp_call_case() -> Res<Case> { + let session = "33333333-3333-4333-8333-333333333333"; + let lines = [ + json!({"type": "system", "subtype": "init", "model": "m", "claude_code_version": "2.1.230", + "tools": ["Bash", "mcp__s__t"], "session_id": session}), + json!({"type": "assistant", "parent_tool_use_id": null, "session_id": session, + "message": {"id": "msg_1", "role": "assistant", "model": "m", "content": [ + {"type": "tool_use", "id": "toolu_1", "name": "mcp__s__t", "input": {}}]}}), + ]; + let bytes = lines + .iter() + .map(ToString::to_string) + .collect::<Vec<_>>() + .join("\n") + + "\n"; + Ok(Case::new( + "mcp_call".to_owned(), // BORROW: .to_owned() makes the owned case name + ReaderSource::Live, + stdout()?, + bytes.into_bytes(), + ) + .with_observed_ids(vec![sid(session)?]) + .with_init(InitReport::new( + json!(["Bash", "mcp__s__t"]), + CensusSource::Harness, + )?) + .with_mcp_call( + vec!["s".to_owned()], // BORROW: .to_owned() makes the owned name + ToolOrigin::mcp_tool("s".to_owned(), "t".to_owned()), // BORROW: .to_owned() makes the owned names + )) +} + /// Guards: R01 §Harness drivers, §Session runner — the Claude Code driver passes the shared suite /// on its recorded streams and sessions: sessions and ends as `expected.toml` lists them, the /// inventory of the first init line labelled as the harness's, a session spec whose command and /// hook files carry no secret, a tracker that follows the recorded Stop payloads and the turn ends, -/// and the headless names the core owns. Oracle: the fixtures' hand-written `expected.toml` and the -/// raw lines read with `serde_json`. +/// the headless names the core owns, and the files the shared oracle's scripted agent wrote are +/// kept. Oracle: the fixtures' hand-written `expected.toml` and the raw lines read with `serde_json`, +/// and the agent-written files of the shared case. #[test] fn conformance_claude_code_fixtures() -> Res<()> { let driver = ClaudeCodeDriver::new(); @@ -289,7 +344,7 @@ fn conformance_claude_code_fixtures() -> Res<()> { let canaries = [CANARY.to_owned()]; // BORROW: .to_owned() makes the owned canary run( &driver, - &Setup::new(&cell, &workspace, &canaries), + &Setup::new(&cell, &workspace, &canaries).with_collector(stored_paths), &cases()?, )?; Ok(()) @@ -687,3 +742,13 @@ fn conformance_claude_session_command_keeps_the_headless_arguments() -> Res<()> ); Ok(()) } + +/// The paths a run stores of a tree: the core's collector over the driver's file specs. +fn stored_paths(root: &Path, specs: &[CollectSpec]) -> std::io::Result<Vec<String>> { + Ok( + candler_core::runner::exec::gather::collect_files(root, specs)? + .into_iter() + .map(|output| output.path) + .collect(), + ) +} diff --git a/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs b/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs index ad10e00e..0f20d086 100644 --- a/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs +++ b/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs @@ -14,6 +14,7 @@ use candler_harness::spec::{Cell, CollectSpec, EnvValue, Observed, StopSignal, W use candler_harness_claude_code::driver::ClaudeCodeDriver; use candler_schemas::execution::{GitCommit, TreatmentRef}; use candler_schemas::primitives::{FieldPath, Name}; +use candler_schemas::refusal::Refusal; use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::json; @@ -140,6 +141,38 @@ fn b21_reference_command_line() -> Res<()> { Ok(()) } +/// Guards: a stored cell, which replays without going through resolve, that holds a permission mode +/// or an effort no mode or level names is refused by the driver with `experiment.cell_value_invalid` +/// at the field, as a fresh cell is, and is not run as the default mode or without an effort. +/// Oracle: the code and the field pointers written by hand. +/// Bite: read the text with a `from_text` that falls back to the default or to unset. +#[test] +fn a_stored_cell_with_an_unnamed_mode_or_effort_is_refused_at_its_field() -> Res<()> { + let driver = ClaudeCodeDriver::new(); + let root = Path::new("/work/run"); + for (path, pointer) in [ + ("permission_mode", "/permission_mode"), + ("model.effort", "/model/effort"), + ] { + let mut stored = values("plan")?; + stored.retain(|value| value.path().as_str() != path); + stored.push(ResolvedValue::recorded( + FieldPath::from_str(path)?, + JsonValue::new(json!("nonsense"))?, + )); + let Err(error) = driver.plan(&Cell::new(&stored), &Workspace::new(root)) else { + return Err(format!("{path}: an unnamed text planned").into()); + }; + assert_eq!( + Refusal::code(&error).as_str(), + "experiment.cell_value_invalid", + "{path}" + ); + assert_eq!(Refusal::path(&error).as_deref(), Some(pointer), "{path}"); + } + Ok(()) +} + /// One regular file of a ustar archive: the header, then the contents padded to a block. fn tar_entry(path: &str, contents: &[u8]) -> Vec<u8> { let mut header = vec![0_u8; 512]; @@ -426,7 +459,7 @@ fn a_server_name_renders_the_server_under_it() -> Res<()> { }; assert_eq!( read(".mcp.json")?, - json!({"mcpServers": {"x-y": {"command": "uvx"}}}) + json!({"mcpServers": {"x-y": {"type": "stdio", "command": "uvx"}}}) ); assert_eq!( read("settings.json")?, @@ -444,3 +477,115 @@ fn a_server_name_renders_the_server_under_it() -> Res<()> { assert!(driver.check_settings(&Cell::new(&cell)).is_err()); Ok(()) } + +/// The `.mcp.json` the driver writes for a cell that sets `extra` besides the default values, +/// parsed. +fn mcp_json(extra: &[(&str, serde_json::Value)]) -> Res<serde_json::Value> { + let mut cell = values("default")?; + for (path, value) in extra { + cell.push(ResolvedValue::recorded( + FieldPath::from_str(path)?, + JsonValue::new(value.clone())?, // BORROW: .clone() copies the value into the cell + )); + } + let plan = + ClaudeCodeDriver::new().plan(&Cell::new(&cell), &Workspace::new(Path::new("/work/run")))?; + let file = plan + .prepared + .files + .iter() + .find(|file| file.path.as_str().ends_with(".mcp.json")) + .ok_or("no .mcp.json")?; + Ok(serde_json::from_slice(&file.contents)?) +} + +/// Guards: the `.mcp.json` of Claude Code holds, for each server, the keys its documentation gives +/// the server's `type` and no other: `stdio` takes `command`, `args` and `env`; `http` and `sse` +/// take `url` and `headers`; `local` is written as `stdio` and `remote` as `http`; the server's +/// `name` is its key and `codemode` is no key. +/// Oracle: the Claude Code MCP documentation, `code.claude.com/docs/en/mcp` and +/// `code.claude.com/docs/en/agent-sdk/typescript` (`McpStdioServerConfig`, `McpSSEServerConfig`, +/// `McpHttpServerConfig`), read through Context7 `/websites/code_claude`; the literal JSON below. +/// Bite: `serde_json::to_value(servers)` back in `render_mcp`. +#[test] +fn the_mcp_file_holds_the_keys_claude_code_documents() -> Res<()> { + let documented = |kind: &str| -> &'static [&'static str] { + match kind { + "stdio" => &["type", "command", "args", "env"], + "http" | "sse" => &["type", "url", "headers"], + _ => &[], + } + }; + let written = mcp_json(&[ + ("mcp.servers.a.type", json!("local")), + ("mcp.servers.a.command", json!("uvx")), + ("mcp.servers.a.args", json!(["srv"])), + ("mcp.servers.a.env", json!({"K": "v"})), + ("mcp.servers.a.codemode", json!(false)), + ("mcp.servers.a.name", json!("x-y")), + ("mcp.servers.b.type", json!("remote")), + ("mcp.servers.b.url", json!("http://h/mcp")), + ("mcp.servers.b.headers", json!({"X": "y"})), + ("mcp.servers.c.type", json!("sse")), + ("mcp.servers.c.url", json!("http://h/sse")), + ("mcp.servers.d.command", json!("uvx")), + ])?; + assert_eq!( + written, + json!({"mcpServers": { + "x-y": {"type": "stdio", "command": "uvx", "args": ["srv"], "env": {"K": "v"}}, + "b": {"type": "http", "url": "http://h/mcp", "headers": {"X": "y"}}, + "c": {"type": "sse", "url": "http://h/sse"}, + "d": {"type": "stdio", "command": "uvx"}, + }}) + ); + for (name, entry) in written["mcpServers"].as_object().ok_or("no servers")? { + let kind = entry["type"].as_str().ok_or("no type")?; + let allowed = documented(kind); + assert!( + !allowed.is_empty(), + "{name}: `{kind}` is no documented type" + ); + for key in entry.as_object().ok_or("no entry")?.keys() { + assert!( + allowed.contains(&key.as_str()), + "{name}: `{key}` is no documented key of `{kind}`" + ); + } + } + Ok(()) +} + +/// Guards: Claude Code has no code mode, so a cell that sets `codemode = true` on a server is +/// refused with the driver's reason, and a cell that leaves `codemode` out or sets it to `false` +/// is not. +/// Oracle: the reason written by hand, from the leaf's gate. +/// Bite: `Answer::Mapped` for `Codemode(true)` in the driver's `answer`. +#[test] +fn claude_code_refuses_codemode_true() -> Res<()> { + let refusal_of = |codemode: Option<serde_json::Value>| -> Res<Option<String>> { + let mut cell = values("default")?; + let mut entries = vec![("mcp.servers.a.command", json!("uvx"))]; + entries.extend(codemode.map(|value| ("mcp.servers.a.codemode", value))); + for (path, value) in entries { + cell.push(ResolvedValue::recorded( + FieldPath::from_str(path)?, + JsonValue::new(value)?, + )); + } + Ok(candler_core::resolve::paths::refuse_unanswered( + &ClaudeCodeDriver::new(), + &Cell::new(&cell), + ) + .err() + .map(|error| error.to_string())) + }; + let refused = refusal_of(Some(json!(true)))?.ok_or("codemode = true ran")?; + assert!( + refused.contains("Claude Code offers MCP tools directly; it has no code mode"), + "{refused}" + ); + assert_eq!(refusal_of(None)?, None); + assert_eq!(refusal_of(Some(json!(false)))?, None); + Ok(()) +} diff --git a/crates/candler-harness-opencode/Cargo.toml b/crates/candler-harness-opencode/Cargo.toml index 57ce6093..9a5be8e1 100644 --- a/crates/candler-harness-opencode/Cargo.toml +++ b/crates/candler-harness-opencode/Cargo.toml @@ -17,6 +17,7 @@ serde_json.workspace = true thiserror.workspace = true [dev-dependencies] +candler-core.workspace = true candler-harness = { workspace = true, features = ["conformance"] } [lints] diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index abf7705b..8fbd89bb 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -7,12 +7,13 @@ use std::str::FromStr as _; use std::time::Duration; -use candler_harness::driver::{DriverError, HarnessDriver, Plan, SettingRow}; +use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ - Action, BaseImage, Capabilities, Cell, CollectSpec, CommandSpec, GatewayEnv, HarnessId, - Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, StopSpec, Workspace, + Action, AgentSetting, Answer, BaseImage, Cell, CollectSpec, CommandSpec, DriverFact, + GatewayEnv, HarnessId, Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, + StopSpec, Workspace, }; use candler_schemas::name; use candler_schemas::primitives::{RelPath, plain_arg}; @@ -154,15 +155,31 @@ impl HarnessDriver for OpenCodeDriver { Ok(version) } - fn capabilities(&self) -> Capabilities { - // Tools run in the `serve` child, so a signal to the client alone does not stop them. There - // is no turn or cost cap and no session mode, and the live reader emits no event: the trace - // comes from the export. The tool inventory is what the gateway saw in the model requests. - Capabilities::builder() - .graceful_stop(true) - .census(true) - .execution_outside_child(true) - .build() + fn answer(&self, setting: AgentSetting) -> Answer { + prepare::answer(setting) + } + + fn fact(&self, fact: DriverFact) -> Answer { + match fact { + DriverFact::GracefulStop => Answer::Mapped { + construct: "an interrupt request to the `serve` child, then SIGTERM to the client", + }, + DriverFact::LiveEvents => Answer::Refused { + reason: "the live reader emits no event: the trace comes from the export", + }, + DriverFact::InHarnessGuard => Answer::Refused { + reason: "the driver configures no OpenCode guard", + }, + DriverFact::ExecutionOutsideChild => Answer::Mapped { + construct: "tools run in the `serve` child, which the stop interrupts first", + }, + DriverFact::Census => Answer::Candler { + how: "the tools the gateway offered the model in its first request", + }, + DriverFact::UnsetPermissionMode => Answer::Candler { + how: "the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode", + }, + } } fn gateway(&self) -> Option<GatewayEnv> { @@ -186,18 +203,17 @@ impl HarnessDriver for OpenCodeDriver { .collect() } - fn settings_table(&self) -> Vec<SettingRow> { - prepare::table() - } - fn check_settings(&self, cell: &Cell<'_>) -> Result<(), DriverError> { - prepare::settings(cell, &VALIDATED)?; - prepare::mcp_servers(cell).map(|_| ()) + prepare::settings(cell)?; + let names: Vec<String> = candler_harness::mcp::servers(cell)? + .map(|servers| servers.into_keys().collect()) + .unwrap_or_default(); + ambiguous_prefixes(&names) } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result<Plan, DriverError> { let _ = workspace; - let settings = prepare::settings(cell, &VALIDATED)?; + let settings = prepare::settings(cell)?; let model = model_id(cell)?; let model_arg = match &settings.variant { Some((id, _)) => format!("{}/{model}#{id}", prepare::PROVIDER), @@ -241,9 +257,13 @@ impl HarnessDriver for OpenCodeDriver { census_stream() } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { if export_stream().as_ref() == Some(stream) { - return Some(Box::new(OpenCodeExportReader::new())); // TRAIT_OBJECT: the core selects readers at runtime + return Some(Box::new(OpenCodeExportReader::new(servers))); // TRAIT_OBJECT: the core selects readers at runtime } None } @@ -302,6 +322,21 @@ impl HarnessDriver for OpenCodeDriver { } } +/// Refuses two server names where one, then `_`, begins the other: `OpenCode` names a tool +/// `<server>_<tool>`, so `a_b_c` would be the tool `b_c` of `a` or the tool `c` of `a_b`. +fn ambiguous_prefixes(names: &[String]) -> Result<(), DriverError> { + for first in names { + let prefix = format!("{first}_"); + if let Some(second) = names.iter().find(|name| name.starts_with(prefix.as_str())) { + return Err(DriverError::AmbiguousServers { + first: first.clone(), // BORROW: .clone() makes the owned name the error keeps + second: second.clone(), // BORROW: .clone() makes the owned name the error keeps + }); + } + } + Ok(()) +} + /// The stream the gateway's census is stored as. fn census_stream() -> Option<StreamName> { CENSUS_STREAM.parse().ok() diff --git a/crates/candler-harness-opencode/src/export.rs b/crates/candler-harness-opencode/src/export.rs index d32ff243..26ec5e6d 100644 --- a/crates/candler-harness-opencode/src/export.rs +++ b/crates/candler-harness-opencode/src/export.rs @@ -157,7 +157,27 @@ impl Draft { } } -fn tool_drafts(block: &Value, message_at: Option<&Timestamp>) -> Vec<Draft> { +/// The origin of the tool `name`: the tool `<tool>` of the declared server `<server>` when the +/// name is `<server>_<tool>`, trying the longest server name first, otherwise a tool the harness +/// offers itself, otherwise another source. A name is never taken for a server's by its spelling +/// alone: only a server the cell declares matches. +fn origin_of(name: &str, servers: &[String]) -> ToolOrigin { + servers + .iter() + .find_map(|server| { + let tool = name.strip_prefix(server.as_str())?.strip_prefix('_')?; + (!tool.is_empty()).then(|| ToolOrigin::mcp_tool(server.clone(), tool.to_owned())) // BORROW: .clone() and .to_owned() make the owned names the origin keeps + }) + .unwrap_or_else(|| { + if BUILTIN_TOOLS.contains(&name) { + ToolOrigin::Builtin + } else { + ToolOrigin::Other + } + }) +} + +fn tool_drafts(block: &Value, message_at: Option<&Timestamp>, servers: &[String]) -> Vec<Draft> { let name = text(block, "name").unwrap_or_default(); let state = field(block, "state"); let input = state.and_then(|state| field(state, "input")); @@ -168,11 +188,7 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>) -> Vec<Draft> { .map(|command| vec![command.to_owned()]) // BORROW: .to_owned() makes owned text }) .flatten(); - let origin = if BUILTIN_TOOLS.contains(&name) { - ToolOrigin::Builtin - } else { - ToolOrigin::Other - }; + let origin = origin_of(name, servers); let time = |key: &str| timestamp(block.get("time").and_then(|t| millis(t, &[key]))); let mut call = Draft::new( // BORROW: .to_owned() makes the owned name the event keeps @@ -202,7 +218,7 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>) -> Vec<Draft> { drafts } -fn assistant_drafts(message: &Value, error_seen: &mut bool) -> Vec<Draft> { +fn assistant_drafts(message: &Value, error_seen: &mut bool, servers: &[String]) -> Vec<Draft> { let at = timestamp( message .get("time") @@ -220,7 +236,7 @@ fn assistant_drafts(message: &Value, error_seen: &mut bool) -> Vec<Draft> { EventKind::assistant_message(text(block, "text").map(str::to_owned)), at.clone(), // BORROW: .clone() copies the time )), - Some("tool") => drafts.extend(tool_drafts(block, at.as_ref())), + Some("tool") => drafts.extend(tool_drafts(block, at.as_ref(), servers)), Some("reasoning") => { let mut body = Map::new(); // BORROW: .to_owned() makes the owned key and text @@ -289,21 +305,22 @@ fn ended_by_of_outcome(outcome: Option<&str>, error: Option<&str>) -> EndedBy { pub struct OpenCodeExportReader { identity: NameVersion, read: Option<(Session, SessionId)>, -} - -impl Default for OpenCodeExportReader { - fn default() -> Self { - Self::new() - } + servers: Vec<String>, } impl OpenCodeExportReader { - /// A reader of the export. + /// A reader of the export of a run that declared the MCP servers `servers`: a call to the tool + /// `<tool>` of the server `<server>` is the tool `<server>_<tool>` in the export, and only a + /// declared server's name makes a call an MCP call. #[must_use] - pub fn new() -> Self { + pub fn new(servers: &[String]) -> Self { + let mut servers = servers.to_vec(); + // The longest name first, so that `a_b` is tried before `a` for the tool `a_b_c`. + servers.sort_by_key(|server| std::cmp::Reverse(server.len())); Self { identity: NameVersion::of(&name!("opencode-export"), semver::Version::new(0, 1, 0)), read: None, + servers, } } @@ -363,7 +380,9 @@ impl OpenCodeExportReader { text(message, "id").map_or(Value::Null, |i| Value::String(i.to_owned())), ), // BORROW: .to_owned() makes owned text ), - Some("assistant") => drafts.extend(assistant_drafts(message, &mut error_seen)), + Some("assistant") => { + drafts.extend(assistant_drafts(message, &mut error_seen, &self.servers)); + } Some("idle") => { if let (Some(error), false) = (field(message, "error"), error_seen) { drafts.push( diff --git a/crates/candler-harness-opencode/src/prepare.rs b/crates/candler-harness-opencode/src/prepare.rs index f0dc73cc..271f9697 100644 --- a/crates/candler-harness-opencode/src/prepare.rs +++ b/crates/candler-harness-opencode/src/prepare.rs @@ -9,59 +9,62 @@ use std::str::FromStr as _; -use candler_harness::driver::{DriverError, SettingRow}; -use candler_harness::spec::{Cell, PreparedFile}; +use candler_harness::driver::DriverError; +use candler_harness::spec::{ + AgentSetting, Answer, Cell, EffortLevel, PermissionMode, PreparedFile, +}; use candler_schemas::execution::paths::{ - BUDGET_PER_RUN_MAX_COST_USD, BUDGET_PER_RUN_TURNS, MCP, MODEL_EFFORT, MODEL_ID, - PERMISSION_MODE, TOOLS_ALLOWED, TOOLS_DISALLOWED, + MCP, MODEL_EFFORT, MODEL_ID, TOOLS_ALLOWED, TOOLS_DISALLOWED, }; use candler_schemas::primitives::{FieldPath, RelPath}; +use candler_schemas::servers::{McpServer, McpServerKind}; use serde_json::{Map, Value, json}; /// The provider's id in the configuration and in `-m <provider>/<model>`. pub(crate) const PROVIDER: &str = "candler"; -/// The one permission mode `--auto` implements. -const ACCEPTED_MODE: &str = "bypassPermissions"; - /// The baseline every `OpenCode` agent starts from (`packages/schema/src/agent.ts`, v2.2.7): the /// ruleset `{*, *, allow}` plus an ask on `.env` reads. The configuration's top-level `permissions` /// are appended after it and the last matching row wins, so an `allow` row restates the baseline /// and a `deny` row, written last, overrides it. -const BASELINE: &str = "every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` \ +const BASELINE: &str = "`--auto` on the command line: every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` \ answers the one pending ask (`.env` reads) with once, which a headless run needs"; -/// The permission modes that are refused, each with the reason. Claude Code's own documentation -/// (permission modes; permissions, read-only commands) is the source of what each mode allows. -const MODE_REFUSALS: [(&str, &str); 3] = [ - ( - "plan", - "Claude Code's plan mode reads and runs read-only shell commands (a built-in, \ +/// Why the `plan` permission mode is refused. Claude Code's own documentation (permission modes; +/// permissions, read-only commands) is the source of what each mode allows. +const PLAN_MODE: &str = "Claude Code's plan mode reads and runs read-only shell commands (a built-in, \ non-configurable set its own parser decides). The OpenCode ruleset that is certainly \ read-only (the `explore` agent's: deny everything, allow read, glob, grep, webfetch, \ websearch, skill) denies the shell altogether, and a wildcard on command text cannot \ express the read-only set; the stock `plan` agent is not read-only once a global rule \ - follows it (the last match wins) and its `subagent` child can edit", - ), - ( - "default", - "Claude Code's default mode allows reads and a built-in, non-configurable set of read-only \ + follows it (the last match wins) and its `subagent` child can edit"; + +/// Why the `default` permission mode is refused. Claude Code's own documentation (permission modes; +/// permissions, read-only commands) is the source of what each mode allows. +const DEFAULT_MODE: &str = "Claude Code's default mode allows reads and a built-in, non-configurable set of read-only \ shell commands that its own parser decides, and denies the rest in a headless run. \ OpenCode without `--auto` also rejects what no rule allows, but its shell rows are \ - wildcards on the text of each parsed command, which approximate that set without being it", - ), - ( - "acceptEdits", - "Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, \ + wildcards on the text of each parsed command, which approximate that set without being it"; + +/// Why the `acceptEdits` permission mode is refused. Claude Code's own documentation (permission modes; +/// permissions, read-only commands) is the source of what each mode allows. +const ACCEPT_EDITS_MODE: &str = "Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, \ rm, rmdir, mv, cp and sed, inside the working directory only. OpenCode's shell resource \ is the command's text, which knows no working directory, so \"inside it\" cannot be \ - written as a rule", - ), -]; + written as a rule"; -/// The reason any other permission mode is refused. -const OTHER_MODE: &str = "only `bypassPermissions` (`--auto`) is a mode OpenCode runs the way \ - Claude Code does; no other mode's allowed set can be written as an OpenCode ruleset"; +/// Why the `auto` permission mode is refused. Claude Code's own documentation (permission modes) +/// is the source of what the mode does. +const AUTO_MODE: &str = "Claude Code's auto mode has a model classifier review each action, such as a shell \ + command or a network request, before it runs. OpenCode has no classifier, and a ruleset \ + decides by the action's text alone"; + +/// Why the `dontAsk` permission mode is refused. Claude Code's own documentation (permission modes; +/// permissions, read-only commands) is the source of what the mode allows. +const DONT_ASK_MODE: &str = "Claude Code's dontAsk mode denies every call that would prompt, so it allows the allow \ + rules plus reads and the built-in, non-configurable set of read-only shell commands its own \ + parser decides. OpenCode's shell rows are wildcards on the text of each parsed command, \ + which approximate that set without being it"; /// The reason the turn cap is refused: what `agents.<id>.steps` does is not `--max-turns`. const TURNS_REFUSAL: &str = "`agents.<id>.steps` makes the last request a tool-less one with an \ @@ -73,31 +76,12 @@ const TURNS_REFUSAL: &str = "`agents.<id>.steps` makes the last request a tool-l const EDIT_WRITE_PAIR: &str = "OpenCode's `edit` action covers the edit, write and patch tools \ alike, so denying `Edit` or `Write` alone would deny both; list both"; -/// The reason a name with no row is refused. -const NO_ACTION: &str = "a name that is not a tool OpenCode has an action for"; - -/// Claude Code's own effort vocabulary (`claude --help`: `--effort <level>`), the values Candler's -/// cell carries at `model.effort`. `OpenCode`'s `anthropicMessages` variant builder -/// (`packages/core/src/variant.ts`, v2.2.7) resolves the same names to adaptive thinking plus -/// `output_config.effort` for a Claude model of version 4.6 or later; a config-declared `variants` -/// entry (`ModelConfig.variants`, v2.2.7) is used as written, so the driver writes that shape -/// directly for the custom `candler` provider. -const EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"]; - /// The model families whose id `OpenCode`'s `claudeInfo` recognises (`variant.ts:68-80`). const FAMILIES: [&str; 5] = ["opus", "sonnet", "haiku", "fable", "mythos"]; -/// Why `ultracode` is refused: Claude Code's `--effort` takes it (CLI reference: `xhigh` with its -/// ultracode workflow turned on), the Claude Code driver passes it through, and `OpenCode` has no -/// equivalent of that mode. -const ULTRACODE: &str = "Claude Code honours `ultracode` (`xhigh` effort with its ultracode mode on) \ - and OpenCode has no equivalent of that mode, so it is refused rather than run as `xhigh`"; - -/// Why a level outside the variants this driver writes is refused: the cell value is opaque, and the -/// Claude Code driver hands any level to `claude --effort` unchanged. -const EFFORT_LEVEL: &str = "this driver writes an `OpenCode` variant only for the levels low, medium, \ - high, xhigh and max; Claude Code receives any other level unchanged, so it is refused rather \ - than mapped to a nearby one"; +/// Why `ultracode` is refused. +const ULTRACODE: &str = "`ultracode` is `xhigh` effort with an ultracode mode on, and OpenCode has \ + no equivalent of that mode, so it is refused rather than run as `xhigh`"; /// Why an effort the model cannot take is refused. const EFFORT_MODEL: &str = "`OpenCode` gives a model a reasoning effort only for a Claude opus, \ @@ -125,92 +109,88 @@ const TOOLS: [(&str, &str); 11] = [ ("TodoWrite", "todowrite"), ]; -/// The value of the table's row for an MCP tool name, `mcp__<server>__<tool>`. -const MCP_ROW: &str = "mcp__<server>__<tool>"; - -/// The declared settings table: the rows [`settings`] answers, one per cell setting, value or -/// tool name the driver knows, mapped or refused. The driver builds its command and its files from -/// the same constants these rows read, and the guard asserts the rows and its cases are one set. -pub(crate) fn table() -> Vec<SettingRow> { - let mut rows = vec![SettingRow::mapped( - PERMISSION_MODE, - ACCEPTED_MODE, - "`--auto` on the command line", - BASELINE, - )]; - for (mode, why) in MODE_REFUSALS { - rows.push(SettingRow::refused(PERMISSION_MODE, mode, why)); - } - rows.push(SettingRow::refused(PERMISSION_MODE, "*", OTHER_MODE)); - rows.push(SettingRow::refused( - BUDGET_PER_RUN_MAX_COST_USD, - "*", - "OpenCode has no cost cap", - )); - rows.push(SettingRow::refused( - BUDGET_PER_RUN_TURNS, - "*", - TURNS_REFUSAL, - )); - for level in EFFORT_LEVELS { - rows.push(SettingRow::mapped( - MODEL_EFFORT, - level, - "a `variants` entry on the model, selected by `-m <model>#<level>`", - "adaptive thinking and `output_config.effort` on every request, as recorded on the wire; only for a model the `<model>` row accepts", - )); - } - rows.push(SettingRow::refused(MODEL_EFFORT, "<model>", EFFORT_MODEL)); - rows.push(SettingRow::refused(MODEL_EFFORT, "*", EFFORT_LEVEL)); - rows.push(SettingRow::refused(MODEL_EFFORT, "ultracode", ULTRACODE)); - for path in [TOOLS_ALLOWED, TOOLS_DISALLOWED] { - let allowed = path == TOOLS_ALLOWED; - for (name, action) in TOOLS { - if !allowed && (name == "Edit" || name == "Write") { - rows.push(SettingRow::refused(path, name, EDIT_WRITE_PAIR)); - continue; - } - rows.push(tool_row(path, name, action)); - } - rows.push(tool_row( - path, - MCP_ROW, - "<server>_<tool>, each part normalised to [A-Za-z0-9_-]", - )); - rows.push(SettingRow::refused(path, "*", NO_ACTION)); - } - rows.push(SettingRow::mapped( - TOOLS_DISALLOWED, - "Edit+Write", - "one `edit` deny row per name", - "both names together: the `edit` action covers both tools", - )); - rows.push(SettingRow::mapped( - TOOLS_DISALLOWED, - "with tools.allowed", - "the deny rows after the allow rows", - "the last matching row wins, so a name in both lists is denied", - )); - rows -} - -/// The row of one tool name (or the MCP pattern) in `path`, mapped to `action`. -fn tool_row(path: &str, name: &str, action: &str) -> SettingRow { - if path == TOOLS_ALLOWED { - SettingRow::mapped( - path, - name, - &format!("a permission row {{{action}, *, allow}}"), - "restates the baseline: a no-op, as Claude Code's `--allowedTools` only auto-approves \ - and leaves every other tool available", - ) - } else { - SettingRow::mapped( - path, - name, - &format!("a permission row {{{action}, *, deny}}"), - "overrides the baseline; written after the allow rows", - ) +/// How `OpenCode` meets one key. The driver builds its command and its files from the same +/// constants these answers read. +#[must_use] +pub(crate) const fn answer(setting: AgentSetting) -> Answer { + match setting { + AgentSetting::ModelId => Answer::Mapped { + construct: "`-m candler/<model>` on the command line", + }, + AgentSetting::ModelEndpoint => Answer::Candler { + how: "the gateway forwards model requests to the endpoint", + }, + AgentSetting::Effort(EffortLevel::Ultracode) => Answer::Refused { reason: ULTRACODE }, + AgentSetting::Effort( + EffortLevel::Low + | EffortLevel::Medium + | EffortLevel::High + | EffortLevel::Xhigh + | EffortLevel::Max, + ) => Answer::Mapped { + construct: "a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude \ + opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any \ + other model", + }, + AgentSetting::PermissionMode(PermissionMode::BypassPermissions) => Answer::Mapped { + construct: BASELINE, + }, + AgentSetting::PermissionMode(PermissionMode::Plan) => Answer::Refused { reason: PLAN_MODE }, + AgentSetting::PermissionMode(PermissionMode::Default) => Answer::Refused { + reason: DEFAULT_MODE, + }, + AgentSetting::PermissionMode(PermissionMode::AcceptEdits) => Answer::Refused { + reason: ACCEPT_EDITS_MODE, + }, + AgentSetting::PermissionMode(PermissionMode::Auto) => Answer::Refused { reason: AUTO_MODE }, + AgentSetting::PermissionMode(PermissionMode::DontAsk) => Answer::Refused { + reason: DONT_ASK_MODE, + }, + AgentSetting::ToolsAllowed => Answer::Mapped { + construct: "a permission row {action, *, allow} per name, a no-op over the baseline", + }, + AgentSetting::ToolsDisallowed => Answer::Mapped { + construct: "a permission row {action, *, deny} per name, written after the allow rows", + }, + AgentSetting::Env => Answer::Candler { + how: "the core sets the cell's variables on the agent's process", + }, + AgentSetting::Inputs => Answer::Candler { + how: "the core places the inputs in the workspace", + }, + AgentSetting::Skills => Answer::Mapped { + construct: "the project skill directory", + }, + AgentSetting::McpTransport(McpServerKind::Stdio | McpServerKind::Local) => Answer::Mapped { + construct: "an `mcp` entry of type `local`", + }, + AgentSetting::McpTransport(McpServerKind::Sse) => Answer::Refused { + reason: "OpenCode documents no SSE transport; its `remote` is Streamable HTTP", + }, + AgentSetting::McpTransport(McpServerKind::Http | McpServerKind::Remote) => Answer::Mapped { + construct: "an `mcp` entry of type `remote`", + }, + AgentSetting::Codemode(true) => Answer::Mapped { + construct: "the `codemode` key of the `mcp` entry, `true`: the server's tools are reached through `execute`, whose calls the trace records with empty `wrapped_calls`, so MCP calls made inside `execute` are not attributed and do not compare with Claude Code", + }, + AgentSetting::Codemode(false) => Answer::Mapped { + construct: "the `codemode` key of the `mcp` entry, `false`: the server's tools are direct tools", + }, + AgentSetting::McpName => Answer::Mapped { + construct: "the key of the `mcp` entry", + }, + AgentSetting::WallBudget => Answer::Candler { + how: "the core ends the run at the wall budget", + }, + AgentSetting::TurnBudget => Answer::Refused { + reason: TURNS_REFUSAL, + }, + AgentSetting::CostBudget => Answer::Refused { + reason: "OpenCode has no cost cap", + }, + AgentSetting::SessionMode => Answer::Refused { + reason: "OpenCode runs no session: its trace comes from the export after the run", + }, } } @@ -224,12 +204,12 @@ pub(crate) fn invalid(path: &str, detail: String) -> DriverError { } /// How the harness is named in a refusal, as its users write it. -const DISPLAY_NAME: &str = "OpenCode"; +pub(crate) const DISPLAY_NAME: &str = "OpenCode"; -/// The refusal of the setting at `path`, which `OpenCode` cannot honour at `version`. -pub(crate) fn unsupported(path: &str, version: &semver::Version, why: &str) -> DriverError { +/// The refusal of the setting at `path`, which `OpenCode` cannot honour. +pub(crate) fn unsupported(path: &str, why: &str) -> DriverError { match FieldPath::from_str(path) { - Ok(setting) => DriverError::unsupported(&setting, DISPLAY_NAME, version, why), + Ok(setting) => DriverError::unsupported(&setting, DISPLAY_NAME, why), Err(error) => DriverError::VersionOutput { detail: error.to_string(), // BORROW: .to_string() gives owned text }, @@ -258,100 +238,35 @@ fn strings(path: &str, what: &str, value: &Value) -> Result<Vec<String>, DriverE .collect() } -fn text_map(path: &str, what: &str, value: &Value) -> Result<Map<String, Value>, DriverError> { - let map = value - .as_object() - .ok_or_else(|| invalid(path, format!("{what} is not an object")))?; - if map.values().any(|v| !v.is_string()) { - return Err(invalid( - path, - format!("{what} holds a value that is not text"), - )); - } - Ok(map.clone()) // BORROW: .clone() copies the map out of the cell -} - -/// The keys a stdio server may carry, and a remote one. Any other key would be dropped, so it is -/// refused. -const LOCAL_KEYS: [&str; 5] = ["type", "command", "args", "env", "codemode"]; -const REMOTE_KEYS: [&str; 4] = ["type", "url", "headers", "codemode"]; - -fn only_keys(at: &str, object: &Map<String, Value>, allowed: &[&str]) -> Result<(), DriverError> { - match object.keys().find(|key| !allowed.contains(&key.as_str())) { - // BORROW: explicit .as_str() - Some(key) => Err(invalid( - &format!("{at}.{key}"), - format!( - "is not a key OpenCode takes for this server (allowed: {})", - allowed.join(", ") - ), - )), - None => Ok(()), - } -} - /// One server of the cell's `mcp` value, in the shape `OpenCode` V2 prints: a `local` server with a -/// command list, or a `remote` one with a url. Anything else is refused. -fn server(name: &str, entry: &Value) -> Result<Value, DriverError> { - let at = format!("{}.{name}", candler_harness::mcp::SERVERS); - let object = entry - .as_object() - .ok_or_else(|| invalid(&at, "is not an object".to_owned()))?; // BORROW: .to_owned() makes the owned text - let codemode = match object.get("codemode") { - None => true, - Some(Value::Bool(flag)) => *flag, - Some(_) => { - return Err(invalid( - &format!("{at}.codemode"), - "is not a boolean".to_owned(), // BORROW: .to_owned() makes the owned text - )); - } - }; - let kind = object.get("type").and_then(Value::as_str); +/// command list, or a `remote` one with a url. +fn server(server: &McpServer) -> Value { let mut out = Map::new(); - match (kind, object.get("command"), object.get("url")) { - (None | Some("stdio" | "local"), Some(command), None) => { - only_keys(&at, object, &LOCAL_KEYS)?; - let program = command - .as_str() - .ok_or_else(|| invalid(&at, "`command` is not text".to_owned()))?; // BORROW: .to_owned() makes the owned text - let mut argv = vec![program.to_owned()]; // BORROW: .to_owned() makes owned text - if let Some(args) = object.get("args") { - argv.extend(strings(&at, "`args`", args)?); - } - out.insert("type".to_owned(), json!("local")); // BORROW: .to_owned() makes the owned key - out.insert("command".to_owned(), json!(argv)); // BORROW: .to_owned() makes the owned key - if let Some(env) = object.get("env") { - out.insert( - "environment".to_owned(), // BORROW: .to_owned() makes the owned key - Value::Object(text_map(&at, "`env`", env)?), - ); + match candler_harness::mcp::kind(server) { + McpServerKind::Stdio | McpServerKind::Local => { + if let Some(command) = &server.command { + let mut argv = vec![command.clone()]; // BORROW: .clone() copies the program into the list + argv.extend(server.args.iter().flatten().cloned()); // BORROW: .cloned() copies the arguments + out.insert("type".to_owned(), json!("local")); // BORROW: .to_owned() makes the owned key + out.insert("command".to_owned(), json!(argv)); // BORROW: .to_owned() makes the owned key + if let Some(env) = &server.env { + out.insert("environment".to_owned(), json!(env)); // BORROW: .to_owned() makes the owned key + } } } - (Some("http" | "sse" | "remote"), None, Some(url)) => { - only_keys(&at, object, &REMOTE_KEYS)?; - let url = url - .as_str() - .ok_or_else(|| invalid(&at, "`url` is not text".to_owned()))?; // BORROW: .to_owned() makes the owned text - out.insert("type".to_owned(), json!("remote")); // BORROW: .to_owned() makes the owned key - out.insert("url".to_owned(), json!(url)); // BORROW: .to_owned() makes the owned key - if let Some(headers) = object.get("headers") { - out.insert( - "headers".to_owned(), // BORROW: .to_owned() makes the owned key - Value::Object(text_map(&at, "`headers`", headers)?), - ); + // `sse` is refused by `answer` before a file is written. + McpServerKind::Http | McpServerKind::Sse | McpServerKind::Remote => { + if let Some(url) = &server.url { + out.insert("type".to_owned(), json!("remote")); // BORROW: .to_owned() makes the owned key + out.insert("url".to_owned(), json!(url)); // BORROW: .to_owned() makes the owned key + if let Some(headers) = &server.headers { + out.insert("headers".to_owned(), json!(headers)); // BORROW: .to_owned() makes the owned key + } } } - _ => { - return Err(invalid( - &at, - "is neither a stdio server (`command`) nor a remote one (`type` http, sse or remote, and `url`)" - .to_owned(), // BORROW: .to_owned() makes the owned text - )); - } } - out.insert("codemode".to_owned(), Value::Bool(codemode)); // BORROW: .to_owned() makes the owned key - Ok(Value::Object(out)) + out.insert("codemode".to_owned(), Value::Bool(server.codemode)); // BORROW: .to_owned() makes the owned key + Value::Object(out) } /// `text` with every character outside `[A-Za-z0-9_-]` replaced by `_`, as `OpenCode` spells an @@ -410,7 +325,6 @@ fn tool_permission_rows( cell: &Cell<'_>, path: &str, effect: &str, - version: &semver::Version, ) -> Result<Vec<Value>, DriverError> { let Some(value) = cell .value_str(path) @@ -422,7 +336,7 @@ fn tool_permission_rows( if path == TOOLS_DISALLOWED { let has = |wanted: &str| names.iter().any(|name| name == wanted); if has("Edit") != has("Write") { - return Err(unsupported(path, version, EDIT_WRITE_PAIR)); + return Err(unsupported(path, EDIT_WRITE_PAIR)); } } names @@ -432,7 +346,6 @@ fn tool_permission_rows( || { Err(unsupported( path, - version, &format!("`{name}` is not a tool OpenCode has an action for"), )) }, @@ -518,37 +431,25 @@ fn claude_info(id: &str) -> Option<ClaudeInfo> { } /// The reasoning-effort variant `model.effort` compiles to: Claude Code's own vocabulary resolved -/// to `OpenCode`'s adaptive-thinking shape (see `EFFORT_LEVELS`). A level outside the vocabulary is -/// an invalid value; a model `OpenCode` would give no such variant (see `EFFORT_MODEL`) is refused -/// here, not left to fail or be ignored at run time. -fn effort_variant( - cell: &Cell<'_>, - version: &semver::Version, -) -> Result<Option<(String, Value)>, DriverError> { - let Some(value) = cell - .value_str(MODEL_EFFORT) - .map_err(|error| invalid(MODEL_EFFORT, error.to_string()))? - else { +/// to `OpenCode`'s adaptive-thinking shape: `OpenCode`'s `anthropicMessages` variant builder +/// (`packages/core/src/variant.ts`, v2.2.7) resolves the same names to adaptive thinking plus +/// `output_config.effort`, and a config-declared `variants` entry is used as written. A model +/// `OpenCode` would give no such variant (see `EFFORT_MODEL`) is refused here, not left to fail +/// or be ignored at run time. +fn effort_variant(cell: &Cell<'_>) -> Result<Option<(String, Value)>, DriverError> { + let Some(level) = cell.effort()? else { return Ok(None); }; - let level = value - .as_str() - .ok_or_else(|| invalid(MODEL_EFFORT, "is not text".to_owned()))?; // BORROW: .to_owned() makes the owned text - if level == "ultracode" { - return Err(unsupported(MODEL_EFFORT, version, ULTRACODE)); - } - if !EFFORT_LEVELS.contains(&level) { - return Err(unsupported(MODEL_EFFORT, version, EFFORT_LEVEL)); - } let accepted = claude_info(model_id(cell)?).is_some_and(|info| { - info.takes_effort() && (level != "xhigh" || info.major > 4 || info.minor >= 7) + info.takes_effort() && (level != EffortLevel::Xhigh || info.major > 4 || info.minor >= 7) }); if !accepted { - return Err(unsupported(MODEL_EFFORT, version, EFFORT_MODEL)); + return Err(unsupported(MODEL_EFFORT, EFFORT_MODEL)); } + let text = level.as_str(); Ok(Some(( - level.to_owned(), // BORROW: .to_owned() makes the owned variant id - json!({"thinking": {"type": "adaptive", "display": "summarized"}, "effort": level}), + text.to_owned(), // BORROW: .to_owned() makes the owned variant id + json!({"thinking": {"type": "adaptive", "display": "summarized"}, "effort": text}), ))) } @@ -563,66 +464,22 @@ pub(crate) struct Settings { pub(crate) variant: Option<(String, Value)>, } -/// What the declared [`table`] says of the cell: every setting this driver can honour mapped to -/// what it does, and every other one refused naming why. `version` is the validated version the -/// refusal names. +/// What the cell's settings resolve to once [`answer`] has accepted them: the values the driver +/// cannot take (an effort level for a model, a tool name) are refused here. /// /// # Errors /// Returns [`DriverError::Unsupported`] for a setting `OpenCode` has no way to honour, and /// [`DriverError::InvalidValue`] for a value it cannot use of a setting it does honour. -pub(crate) fn settings( - cell: &Cell<'_>, - version: &semver::Version, -) -> Result<Settings, DriverError> { - let mode = cell.permission_mode()?; - if mode != ACCEPTED_MODE { - let why = MODE_REFUSALS - .iter() - .find(|(refused, _)| *refused == mode) - .map_or(OTHER_MODE, |(_, why)| *why); - return Err(unsupported(PERMISSION_MODE, version, why)); - } - if cell - .value_str(BUDGET_PER_RUN_MAX_COST_USD) - .map_err(|error| invalid(BUDGET_PER_RUN_MAX_COST_USD, error.to_string()))? - .is_some() - { - return Err(unsupported( - BUDGET_PER_RUN_MAX_COST_USD, - version, - "OpenCode has no cost cap", - )); - } - if cell - .value_str(BUDGET_PER_RUN_TURNS) - .map_err(|error| invalid(BUDGET_PER_RUN_TURNS, error.to_string()))? - .is_some() - { - return Err(unsupported(BUDGET_PER_RUN_TURNS, version, TURNS_REFUSAL)); - } - let variant = effort_variant(cell, version)?; - let mut permissions = tool_permission_rows(cell, TOOLS_ALLOWED, "allow", version)?; - permissions.extend(tool_permission_rows( - cell, - TOOLS_DISALLOWED, - "deny", - version, - )?); +pub(crate) fn settings(cell: &Cell<'_>) -> Result<Settings, DriverError> { + let variant = effort_variant(cell)?; + let mut permissions = tool_permission_rows(cell, TOOLS_ALLOWED, "allow")?; + permissions.extend(tool_permission_rows(cell, TOOLS_DISALLOWED, "deny")?); Ok(Settings { permissions, variant, }) } -/// The servers of the cell by the name the agent sees, read from the `mcp.servers.*` leaves as the -/// resolver gives them (see [`candler_harness::mcp::servers`]). `None` when the cell sets no server. -/// -/// # Errors -/// [`DriverError::InvalidValue`] when a value cannot be used or a server name is refused. -pub(crate) fn mcp_servers(cell: &Cell<'_>) -> Result<Option<Map<String, Value>>, DriverError> { - candler_harness::mcp::servers(cell) -} - /// The `opencode.json` of the run: the provider, the model, the effort variant and the /// permission rows of `settings`, and the MCP servers. `config_dir` is the home-relative directory /// that `XDG_CONFIG_HOME` names. @@ -656,10 +513,10 @@ pub(crate) fn render_config( "models": models, } }), ); - if let Some(servers) = mcp_servers(cell)? { + if let Some(servers) = candler_harness::mcp::servers(cell)? { let mut translated = Map::new(); for (name, entry) in &servers { - translated.insert(name.clone(), server(name, entry)?); // BORROW: .clone() copies the name + translated.insert(name.clone(), server(entry)); // BORROW: .clone() copies the name } root.insert( MCP.to_owned(), // BORROW: .to_owned() makes the owned key diff --git a/crates/candler-harness-opencode/tests/it/conformance.rs b/crates/candler-harness-opencode/tests/it/conformance.rs index b4228816..f2b51179 100644 --- a/crates/candler-harness-opencode/tests/it/conformance.rs +++ b/crates/candler-harness-opencode/tests/it/conformance.rs @@ -13,13 +13,13 @@ use std::str::FromStr as _; use candler_harness::conformance::{Case, ExpectedSession, ReaderSource, Setup, run}; use candler_harness::spec::{ - Cell, CollectSpec, CommandSpec, ObservedEnd, ProcessEnd, ProcessExit, Workspace, + Cell, CollectSpec, CommandSpec, ObservedEnd, PreparedFile, ProcessEnd, ProcessExit, Workspace, }; use candler_harness_opencode::driver::OpenCodeDriver; use candler_schemas::primitives::{FieldPath, ReasonCode}; use candler_schemas::process::ExitStatus; use candler_schemas::raw::StreamName; -use candler_schemas::trace::{EndedBy, SessionId}; +use candler_schemas::trace::{EndedBy, SessionId, ToolOrigin}; use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::json; @@ -187,12 +187,7 @@ fn cases() -> Res<Vec<Case>> { read(run.case, "stdout.jsonl")?, ) .with_observed_ids(vec![id.clone()]) // BORROW: .clone() copies the id - .with_collect(vec![ - CollectSpec::file("**/*".to_owned()), - CollectSpec::file("!.opencode/**".to_owned()), - CollectSpec::file("!**/.opencode/**".to_owned()), - export_collect(&id, &export)?, - ]); + .with_collect_commands(vec![export_collect(&id, &export)?]); Ok(match &run.live_end { Some(end) => case.with_observed_end(end.clone()), // BORROW: .clone() copies the end None => case, @@ -248,6 +243,56 @@ fn cases() -> Res<Vec<Case>> { ) .with_end(exit_of("interrupt_api")?, EndedBy::Unknown), ); + // The shared oracle: a scripted agent writes these files into a real workspace beside a + // skill file the harness leaves under `.opencode`, and the core's file collector applied to + // the driver's specs must store exactly the agent's files. + cases.push( + Case::new( + "collect_stores_the_files_the_agent_wrote".to_owned(), + ReaderSource::Live, + stream("stdout")?, + Vec::new(), + ) + .detects(false) + .with_workspace( + vec![ + PreparedFile::new("notes.md".parse()?, b"kept".to_vec(), false), + PreparedFile::new("outputs/answer.txt".parse()?, b"stamp-7f3a".to_vec(), false), + ], + vec![PreparedFile::new( + ".opencode/skills/s/SKILL.md".parse()?, + b"skill".to_vec(), + false, + )], + ), + ); + // A call to the tool `t` of the declared server `s` is the tool `s_t` in the export. + let mut document: serde_json::Value = + serde_json::from_slice(&read("completed_o1", "export.json")?)?; + for message in document["messages"].as_array_mut().into_iter().flatten() { + for block in message["content"].as_array_mut().into_iter().flatten() { + if block["type"] == "tool" { + block["name"] = json!("s_t"); + } + } + } + let id = sid(¬e("completed_o1", "expected.toml", "session_id")?)?; + cases.push( + Case::new( + "export_mcp_call".to_owned(), // BORROW: .to_owned() makes the owned name + ReaderSource::Offline(stream("export")?), + stream("export")?, + serde_json::to_vec(&document)?, + ) + .with_sessions( + vec![ExpectedSession::new(id.clone(), None, EndedBy::Completed)], // BORROW: .clone() copies the id + vec![id], + ) + .with_mcp_call( + vec!["s".to_owned()], // BORROW: .to_owned() makes the owned name + ToolOrigin::mcp_tool("s".to_owned(), "t".to_owned()), // BORROW: .to_owned() makes the owned names + ), + ); Ok(cases) } @@ -272,8 +317,9 @@ fn values() -> Res<Vec<ResolvedValue>> { /// Guards: R01 §Harness drivers, §`OpenCode` v2 — the recorded runs of `OpenCode` V2 read, classify and /// collect through the shared traits: sessions from the export, the end from the export's outcome -/// over the stream's last error event, the collect command inside the isolation. -/// Oracle: the fixtures' hand-written `expected.toml` and `exit.toml`, and R01 §Ends by hand. +/// over the stream's last error event, the collect command inside the isolation, and the files the +/// shared oracle's scripted agent wrote are kept. Oracle: the fixtures' hand-written `expected.toml` +/// and `exit.toml`, R01 §Ends by hand, and the agent-written files of the shared case. #[test] fn conformance_opencode_recorded_runs() -> Res<()> { let values = values()?; @@ -283,8 +329,18 @@ fn conformance_opencode_recorded_runs() -> Res<()> { let driver = OpenCodeDriver::new(); run( &driver, - &Setup::new(&cell, &workspace, &canaries), + &Setup::new(&cell, &workspace, &canaries).with_collector(stored_paths), &cases()?, )?; Ok(()) } + +/// The paths a run stores of a tree: the core's collector over the driver's file specs. +fn stored_paths(root: &Path, specs: &[CollectSpec]) -> std::io::Result<Vec<String>> { + Ok( + candler_core::runner::exec::gather::collect_files(root, specs)? + .into_iter() + .map(|output| output.path) + .collect(), + ) +} diff --git a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs index a9c1c7be..e54a11f1 100644 --- a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs +++ b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs @@ -5,16 +5,16 @@ //! Each expectation is a literal written by hand from `opencode_facts`, from the recorded fixtures, //! or from what the real binary printed for the same file (`tests/fixtures/config`). -use std::collections::BTreeSet; use std::error::Error; use std::path::{Path, PathBuf}; use std::process::Command; use std::str::FromStr as _; -use candler_harness::driver::{Disposition, DriverError, HarnessDriver}; +use candler_harness::driver::{DriverError, HarnessDriver}; use candler_harness::reader::FrameIn; use candler_harness::spec::{ - Action, Cell, CollectSpec, Observed, ProcessEnd, ProcessExit, StopSignal, Workspace, + Action, AgentSetting, Answer, Cell, CollectSpec, EffortLevel, Observed, PermissionMode, + ProcessEnd, ProcessExit, StopSignal, Workspace, }; use candler_harness_opencode::driver::OpenCodeDriver; use candler_schemas::execution::{GitCommit, TreatmentRef}; @@ -92,6 +92,19 @@ fn flatten(prefix: &str, servers: &Value, out: &mut Vec<(String, Value)>) { } } +/// The key a table case sets, for the cases that set a key the driver answers. +fn key_of(setting: &str, value: &str) -> Option<AgentSetting> { + match (setting, value) { + ("permission_mode", mode) => { + PermissionMode::from_text(mode).map(AgentSetting::PermissionMode) + } + ("model.effort", level) => EffortLevel::from_text(level).map(AgentSetting::Effort), + ("budget.per_run.turns", _) => Some(AgentSetting::TurnBudget), + ("budget.per_run.max_cost_usd", _) => Some(AgentSetting::CostBudget), + _ => None, + } +} + /// The command of a cell, or the driver's refusal. fn command_of(extra: &[(&str, Value)]) -> Res<Result<Vec<String>, DriverError>> { let values = values(extra)?; @@ -247,12 +260,6 @@ fn table_cases() -> Vec<Case> { vec![(mode, json!("acceptEdits"))], refuses("/fixed/permission_mode", "knows no working directory"), ), - case( - mode, - "*", - vec![(mode, json!("dontAsk"))], - refuses("/fixed/permission_mode", "only `bypassPermissions`"), - ), case( "budget.per_run.max_cost_usd", "*", @@ -265,13 +272,7 @@ fn table_cases() -> Vec<Case> { vec![("budget.per_run.turns", json!(5))], refuses("/budget/per_run/turns", "`error_max_turns`"), ), - // The models and levels the effort does not map for. - case( - "model.effort", - "*", - vec![("model.effort", json!("extreme")), opus.clone()], // BORROW: .clone() copies the value - refuses("/fixed/model.effort", "low, medium, high, xhigh and max"), - ), + // The models the effort does not map for. ]; // `ultracode` is a Claude Code level the Claude Code driver passes through; OpenCode refuses it. cases.push(case( @@ -402,7 +403,7 @@ fn table_cases() -> Vec<Case> { } /// Guards: R01 §`OpenCode` v2, §Run manifest — the declared settings table and what the driver does -/// are one set. Every row of `settings_table()` has a case below and every case answers a row +/// are one set. Every `AgentSetting` family has a case below and every case answers a family /// (dropping either side turns this red), a mapped row's case maps and a refused row's is refused, /// at the setting's pointer in the experiment file, in a message naming the setting, the harness /// and its version. Mapped: the run is @@ -444,31 +445,15 @@ fn opencode_command_line_maps_or_refuses_every_setting() -> Res<()> { let cases = table_cases(); let driver = OpenCodeDriver::new(); - let rows = driver.settings_table(); - let declared: BTreeSet<(String, String)> = rows - .iter() - .map(|row| (row.setting.clone(), row.value.clone())) // BORROW: .clone() copies the key out of the row - .collect(); - let covered: BTreeSet<(String, String)> = cases - .iter() - .map(|c| (c.setting.to_owned(), c.value.to_owned())) // BORROW: .to_owned() makes the owned key - .collect(); - assert_eq!( - declared, covered, - "the declared rows and the cases are one set" - ); - for row in &rows { - for c in cases - .iter() - .filter(|c| c.setting == row.setting && c.value == row.value) - { - let mapped = matches!(c.expect, Expect::Maps { .. }); + for c in &cases { + let key = key_of(c.setting, c.value); + if let Some(key) = key { assert_eq!( - mapped, - row.disposition == Disposition::Mapped, - "{} {}: the case and the row disagree", - row.setting, - row.value + matches!(c.expect, Expect::Refuses { .. }), + driver.answer(key).is_refused(), + "{} {}: the case and the answer disagree", + c.setting, + c.value ); } } @@ -505,11 +490,20 @@ fn opencode_command_line_maps_or_refuses_every_setting() -> Res<()> { } } Expect::Refuses { pointer, needle } => { + if let Some(key) = key_of(c.setting, c.value) { + // The core refuses what the driver answers `Refused`, before the plan; the + // reason it gives is the answer's. + let Answer::Refused { reason } = driver.answer(key) else { + return Err(format!("{label}: the answer is not a refusal").into()); + }; + assert!(reason.contains(needle), "{label}: `{needle}` in `{reason}`"); + continue; + } let (code, side, at, message) = unsupported_of_cell(&c.extra)?; assert_eq!(code.as_str(), "experiment.setting_unsupported", "{label}"); assert_eq!(side, Side::Experiment, "{label}"); assert_eq!(at.as_deref(), Some(*pointer), "{label}"); - for want in [pointer, needle, &"OpenCode", &"2.2.7"] { + for want in [pointer, needle, &"OpenCode"] { assert!(message.contains(want), "{label}: `{want}` in `{message}`"); } } @@ -522,12 +516,12 @@ fn opencode_command_line_maps_or_refuses_every_setting() -> Res<()> { /// provider's address and key are references to the variables the core sets, in a home-rooted /// file inside the config directory the state paths name, and the file is the one the real binary /// accepted; the gateway is named by two variables and nothing else of the configuration is a -/// value; `codemode` is a cell value read per server, absent written as on, `false` making the -/// server's tools direct tools; an MCP server shape the driver cannot translate is refused, not +/// value; `codemode` is a cell value read per server, absent written as off, `true` making the +/// server's tools reached through `execute`; an MCP server shape the driver cannot translate is refused, not /// guessed. /// Oracle: `tests/fixtures/config/opencode.json`, run through `opencode debug config` in the base /// image (`debug_config.out`: `{env:…}/v1` expanded to `http://gateway:8080/r/tag/run/key/v1`); -/// the names are the ones that fixture refers to; `opencode_facts` row 17 (omitted is on, `false` +/// the names are the ones that fixture refers to; `opencode_facts` row 17 (omitted is off here, `false` /// is direct) and the V2 shape the real binary printed for `mcp.servers.<name>.codemode`; the /// shapes the real binary printed (`local` with a command list, `remote` with a url) are the only /// ones recorded. @@ -538,7 +532,7 @@ fn opencode_prepare_writes_the_provider_mcp_codemode_and_gateway_names() -> Res< "mcp", json!({ "loc": {"command": "uvx", "args": ["srv"], "env": {"K": "v"}, "codemode": false}, - "rem": {"type": "http", "url": "http://h/mcp", "headers": {"X": "y"}} + "rem": {"type": "http", "url": "http://h/mcp", "headers": {"X": "y"}, "codemode": true} }), )])?; assert_eq!(file.root, candler_harness::spec::FileRoot::Home); @@ -557,7 +551,7 @@ fn opencode_prepare_writes_the_provider_mcp_codemode_and_gateway_names() -> Res< assert!(config.contains(&format!("{{env:{}}}", gateway.auth_token))); assert_eq!(gateway.reserved, vec![gateway.base_url, gateway.auth_token]); - // `codemode` is read from the cell, absent written as on. + // `codemode` is read from the cell, absent written as off. let servers = |codemode: Option<Value>| { let mut server = json!({"command": "uvx", "args": []}); if let (Some(value), Some(map)) = (codemode, server.as_object_mut()) { @@ -570,7 +564,7 @@ fn opencode_prepare_writes_the_provider_mcp_codemode_and_gateway_names() -> Res< let (_, parsed) = prepared_config(&[("mcp", servers(codemode))])?; written.push(parsed["mcp"]["servers"]["s"]["codemode"].clone()); // BORROW: .clone() copies the value } - assert_eq!(written, [json!(true), json!(true), json!(false)]); + assert_eq!(written, [json!(false), json!(true), json!(false)]); assert!( prepared_config(&[("mcp", servers(Some(json!("no"))))]).is_err(), "a codemode that is not a boolean is refused" @@ -587,7 +581,7 @@ fn opencode_prepare_writes_the_provider_mcp_codemode_and_gateway_names() -> Res< prepared_config(&[( "mcp", json!({"a": {"type": "stdio", "command": "uvx", "args": ["x"], "env": {"K": "v"}, "codemode": true}, - "b": {"type": "sse", "url": "http://h", "headers": {"X": "y"}, "codemode": false}}), + "b": {"type": "http", "url": "http://h", "headers": {"X": "y"}, "codemode": false}}), )])?; for servers in [ json!({"s": {"type": "websocket", "url": "ws://h"}}), @@ -602,7 +596,10 @@ fn opencode_prepare_writes_the_provider_mcp_codemode_and_gateway_names() -> Res< json!({"s": {"type": "http", "url": "http://h", "env": {"K": "v"}}}), json!({"s": "uvx"}), ] { - assert!(prepared_config(&[("mcp", servers)]).is_err()); + assert!( + prepared_config(&[("mcp", servers.clone())]).is_err(), // BORROW: the message names the servers + "accepted: {servers}" + ); } Ok(()) } @@ -704,9 +701,16 @@ fn opencode_live_reader_reports_id_and_last_word() -> Res<()> { /// What the export reader makes of `bytes`: its events and sessions. fn read_export(bytes: &[u8]) -> Res<(Vec<SessionEvent>, Vec<Session>)> { + read_export_for(bytes, &[]) +} + +/// What the export reader makes of `bytes` for a run that declared the MCP servers `servers`. +fn read_export_for(bytes: &[u8], servers: &[String]) -> Res<(Vec<SessionEvent>, Vec<Session>)> { let driver = OpenCodeDriver::new(); let export: StreamName = "export".parse()?; - let mut reader = driver.offline_reader(&export).ok_or("no export reader")?; + let mut reader = driver + .offline_reader(&export, servers) + .ok_or("no export reader")?; let frame = RawFrame::new(None, FrameData::from_bytes(bytes)); let events = reader.feed(FrameIn::new(RawRef::new(export, 0), None, &frame))?; Ok((events, reader.finish()?)) @@ -1236,7 +1240,7 @@ fn opencode_detect_recognises_only_what_it_reads() -> Res<()> { let live = driver.live_reader().ok_or("no live reader")?; let export_stream: StreamName = "export".parse()?; let export = driver - .offline_reader(&export_stream) + .offline_reader(&export_stream, &[]) .ok_or("no export reader")?; let recorded = stream_file("completed_o1", "stdout.jsonl")?; assert!(live.detect(&recorded).is_some()); @@ -1429,7 +1433,7 @@ fn opencode_a_server_name_renders_the_server_under_it() -> Res<()> { ])?; assert_eq!( parsed["mcp"], - json!({"servers": {"x-y": {"type": "local", "command": ["uvx"], "codemode": true}}}) + json!({"servers": {"x-y": {"type": "local", "command": ["uvx"], "codemode": false}}}) ); assert_eq!( parsed["permissions"], @@ -1437,3 +1441,168 @@ fn opencode_a_server_name_renders_the_server_under_it() -> Res<()> { ); Ok(()) } + +/// The export of `completed_o1` with its tool call replaced by one call to each of `names`. +fn export_calling(names: &[&str]) -> Res<Vec<u8>> { + let mut document: Value = serde_json::from_slice(&stream_file("completed_o1", "export.json")?)?; + for message in document["messages"].as_array_mut().into_iter().flatten() { + let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) else { + continue; + }; + if let Some(at) = blocks.iter().position(|block| block["type"] == "tool") { + let template = blocks.remove(at); + for (index, name) in names.iter().enumerate() { + let mut call = template.clone(); + call["name"] = json!(name); + call["id"] = json!(format!("toolu_call_{index}")); + blocks.insert(at + index, call); + } + } + } + Ok(serde_json::to_vec(&document)?) +} + +/// The `origin` and `wrapped_calls` of each tool call among `events`, in order. +fn call_origins(events: &[SessionEvent]) -> Res<Vec<(Value, Value)>> { + let mut found = Vec::new(); + for kind in kinds(events)? { + if kind["kind"] == "tool_call" { + found.push((kind["origin"].clone(), kind["wrapped_calls"].clone())); + } + } + Ok(found) +} + +/// Guards: R01 §Normalised trace — a call to `<server>_<tool>` is the tool `<tool>` of a server the +/// cell declares, the longest declared name first; a name no declared server begins is never +/// taken for a server's by its spelling; a built-in stays built in; and an `execute` call (code +/// mode) is a built-in call that wraps no call. +/// Oracle: the literal origins written by hand from the trace schema. +/// Bite: a reader that takes the text before the first `_` for the server, matches the shortest +/// name first, matches an undeclared server, or lists a `wrapped_calls` entry for `execute`. +#[test] +fn opencode_export_reader_attributes_calls_to_the_declared_servers_only() -> Res<()> { + let servers = strings(&["s", "a", "a_b"]); + let names = ["s_t", "a_b_c", "a_x", "x_t", "s", "s_", "shell", "execute"]; + let (events, _) = read_export_for(&export_calling(&names)?, &servers)?; + let mcp = |server: &str, tool: &str| json!({"kind": "mcp", "server": server, "tool": tool}); + let none = json!([]); + assert_eq!( + call_origins(&events)?, + vec![ + (mcp("s", "t"), none.clone()), + (mcp("a_b", "c"), none.clone()), + (mcp("a", "x"), none.clone()), + (json!({"kind": "other"}), none.clone()), + (json!({"kind": "other"}), none.clone()), + (json!({"kind": "other"}), none.clone()), + (json!({"kind": "builtin"}), none.clone()), + (json!({"kind": "builtin"}), none), + ] + ); + let (events, _) = read_export_for(&export_calling(&["s_t"])?, &[])?; + assert_eq!( + call_origins(&events)?.first().map(|(origin, _)| origin), + Some(&json!({"kind": "other"})), + "a run that declared no server has no MCP call" + ); + Ok(()) +} + +/// Guards: R01 §Harness drivers (`check_settings`) — two servers where one name, then `_`, begins the +/// other are refused at resolve with `AmbiguousServers` naming both, whatever the order of the +/// keys; servers that merely share a prefix with no `_` after it are accepted. +/// Oracle: `OpenCode` names a tool `<server>_<tool>` (v2.2.7), so `a_b_c` reads two ways with `a` +/// and `a_b`; the two names and the pairs that do not collide are written by hand. +/// Bite: no check, a check on the bare prefix (`a` against `ab`), or one that looks only at the +/// first key. +#[test] +fn opencode_refuses_servers_whose_tool_prefixes_are_ambiguous() -> Res<()> { + let driver = OpenCodeDriver::new(); + let check = |keys: &[&str]| -> Res<Result<(), DriverError>> { + let table: serde_json::Map<String, Value> = keys + .iter() + .map(|key| ((*key).to_owned(), json!({"command": "uvx", "args": []}))) + .collect(); + let values = values(&[("mcp", Value::Object(table))])?; + Ok(driver.check_settings(&Cell::new(&values))) + }; + for keys in [["a", "a_b"], ["a_b", "a"]] { + match check(&keys)? { + Err(DriverError::AmbiguousServers { first, second }) => { + assert_eq!((first.as_str(), second.as_str()), ("a", "a_b")); + } + other => return Err(format!("{keys:?} gave {other:?}").into()), + } + } + for keys in [vec!["a", "ab"], vec!["a_b", "ab", "b"], vec!["a"]] { + assert!(check(&keys)?.is_ok(), "{keys:?} are not ambiguous"); + } + Ok(()) +} + +/// Guards: the `mcp` entries of `opencode.json` hold, for each server, the keys `OpenCode` documents +/// for its `type` and no other: `local` takes `type`, `command`, `environment` and `codemode`, +/// `remote` takes `type`, `url`, `headers` and `codemode`; a server that sets no `codemode` is +/// written with `codemode: false`. +/// Oracle: the `OpenCode` MCP servers documentation, `opencode.ai/docs/mcp-servers`, the `Local` and +/// `Remote` field tables, read through Context7 `/websites/opencode_ai`; the literal JSON below. +/// Bite: `#[serde(default)]` of `McpServer::codemode` replaced by a default of `true`, or a key +/// outside the tables written by `server`. +#[test] +fn the_config_holds_the_keys_opencode_documents() -> Res<()> { + let documented = |kind: &str| -> &'static [&'static str] { + match kind { + "local" => &["type", "command", "environment", "codemode"], + "remote" => &["type", "url", "headers", "codemode"], + _ => &[], + } + }; + let (_, parsed) = prepared_config(&[( + "mcp", + json!({ + "a": {"command": "uvx", "args": ["srv"], "env": {"K": "v"}}, + "b": {"type": "remote", "url": "http://h/mcp", "headers": {"X": "y"}, "codemode": true}, + "c": {"type": "stdio", "command": "uvx", "codemode": false, "name": "x-y"} + }), + )])?; + assert_eq!( + parsed["mcp"]["servers"], + json!({ + "a": {"type": "local", "command": ["uvx", "srv"], "environment": {"K": "v"}, "codemode": false}, + "b": {"type": "remote", "url": "http://h/mcp", "headers": {"X": "y"}, "codemode": true}, + "x-y": {"type": "local", "command": ["uvx"], "codemode": false} + }) + ); + for (name, entry) in parsed["mcp"]["servers"].as_object().ok_or("no servers")? { + let kind = entry["type"].as_str().ok_or("no type")?; + let allowed = documented(kind); + assert!( + !allowed.is_empty(), + "{name}: `{kind}` is no documented type" + ); + for key in entry.as_object().ok_or("no entry")?.keys() { + assert!( + allowed.contains(&key.as_str()), + "{name}: `{key}` is no documented key of `{kind}`" + ); + } + } + // The documentation lists no SSE transport: an `sse` server is refused, not mapped to `remote`. + let cell = values(&[("mcp", json!({"s": {"type": "sse", "url": "http://h"}}))])?; + let error = + candler_core::resolve::paths::refuse_unanswered(&OpenCodeDriver::new(), &Cell::new(&cell)) + .err() + .ok_or("an sse server ran")?; + assert_eq!( + Refusal::code(&error).as_str(), + "experiment.setting_unsupported" + ); + assert!( + error + .to_string() + .contains("OpenCode documents no SSE transport; its `remote` is Streamable HTTP"), + "{error}" + ); + Ok(()) +} diff --git a/crates/candler-harness/Cargo.toml b/crates/candler-harness/Cargo.toml index f54d1fe8..be672ca0 100644 --- a/crates/candler-harness/Cargo.toml +++ b/crates/candler-harness/Cargo.toml @@ -13,11 +13,15 @@ candler-schemas.workspace = true semver.workspace = true serde.workspace = true serde_json.workspace = true +serde_path_to_error.workspace = true thiserror.workspace = true [features] # The shared fixture suite every driver crate runs on its recorded fixtures. conformance = [] +[dev-dependencies] +candler-core.workspace = true + [lints] workspace = true diff --git a/crates/candler-harness/README.md b/crates/candler-harness/README.md index 109b54d1..ee112423 100644 --- a/crates/candler-harness/README.md +++ b/crates/candler-harness/README.md @@ -11,7 +11,7 @@ HTTP call a driver describes. The traits are specified in | Module | Holds | |---|---| -| `spec` | The data a driver returns: `CommandSpec` (built with `CommandSpecBuilder`), `EnvEntry` and `EnvValue`, `StopSpec` with `Action`, `StopSignal` and `HttpMethod`, `CollectSpec`, `Capabilities` with `BudgetCaps`, `ProcessExit` and `ProcessEnd`, `Observed`, `Framing`, `FormatVersion`, `Confidence`, `HarnessId`, `Prepared` and `PreparedFile`, and the read-only views `Cell` and `Workspace`. | +| `spec` | The data a driver returns: `CommandSpec` (built with `CommandSpecBuilder`), `EnvEntry` and `EnvValue`, `StopSpec` with `Action`, `StopSignal` and `HttpMethod`, `CollectSpec`, `Answer`, `AgentSetting` with `EffortLevel` and `PermissionMode`, `DriverFact`, `ProcessExit` and `ProcessEnd`, `Observed`, `Framing`, `FormatVersion`, `Confidence`, `HarnessId`, `Prepared` and `PreparedFile`, and the read-only views `Cell` and `Workspace`. | | `driver` | `HarnessDriver`, the trait that says how to prepare, launch, observe, stop and collect one harness, and `DriverError`. | | `reader` | `TraceReader`, the trait that turns the frames of one stream into normalised sessions and events, its input `FrameIn` and its error `ReaderError`. A reader is synchronous and holds no clock; the core supplies each frame with its place and wall time. | diff --git a/crates/candler-harness/src/conformance.rs b/crates/candler-harness/src/conformance.rs index 2672eb98..7fe0d667 100644 --- a/crates/candler-harness/src/conformance.rs +++ b/crates/candler-harness/src/conformance.rs @@ -10,14 +10,14 @@ use std::fmt; use candler_schemas::raw::{FrameData, RawFrame, RawRef, StreamName}; -use candler_schemas::trace::{EndedBy, Session, SessionId}; +use candler_schemas::trace::{EndedBy, EventKind, Session, SessionId, ToolOrigin}; -use crate::driver::{Disposition, DriverError, HarnessDriver, Plan}; +use crate::driver::{DriverError, HarnessDriver, Plan}; use crate::reader::{FrameIn, TraceReader}; use crate::spec::{ - Action, Cell, CensusSource, CollectSpec, CommandSpec, EnvValue, FileRoot, Framing, HttpMethod, - InitReport, Observed, ObservedEnd, PendingState, ProcessExit, SessionClose, SessionRecord, - StateKind, StopSpec, Workspace, + Action, AgentSetting, Cell, CensusSource, CollectSpec, CommandSpec, DriverFact, EnvValue, + FileRoot, Framing, HttpMethod, InitReport, Observed, ObservedEnd, PendingState, PreparedFile, + ProcessExit, SessionClose, SessionRecord, StateKind, StopSpec, Workspace, }; /// A session id plain enough to stand in a script, used to check that a placeholder resolves. @@ -117,12 +117,24 @@ pub struct Case { pub end: Option<(ProcessExit, EndedBy)>, /// What the driver must collect for the observed sessions, when the case states it. pub collect: Option<Vec<CollectSpec>>, + /// The command and exec specs the driver must collect, whatever file specs it also has. + pub collect_commands: Option<Vec<CollectSpec>>, /// An export read after the live stream: the stream it is read as, its bytes and the sessions /// it must give. The export is authoritative: the run is classified from its sessions, with /// the live reader's observed end beside them. pub export: Option<(StreamName, Vec<u8>, Vec<ExpectedSession>)>, + /// The files the scripted agent writes into a real workspace. When the case states them, the + /// check collects that workspace through the setup's collector and asserts that the stored + /// set is exactly these files. The oracle is this set, not a list taken from the driver. + pub agent_wrote: Vec<PreparedFile>, + /// The files the harness leaves in the same workspace, which are not the agent's: the + /// collect must not store them. + pub harness_wrote: Vec<PreparedFile>, /// Records for the session tracker, in the order the core reads them. pub track: Vec<TrackStep>, + /// The MCP servers the run declared, and the origin that the stream's one tool call must + /// have in the events the reader emits: the stream is read for that server list. + pub mcp_call: Option<(Vec<String>, ToolOrigin)>, } impl Case { @@ -146,11 +158,23 @@ impl Case { observed_end: None, end: None, collect: None, + collect_commands: None, export: None, + agent_wrote: Vec::new(), + harness_wrote: Vec::new(), track: Vec::new(), + mcp_call: None, } } + /// The stream holds one call to a tool of the servers `servers`, and the reader must give it + /// the origin `origin`. + #[must_use] + pub fn with_mcp_call(mut self, servers: Vec<String>, origin: ToolOrigin) -> Self { + self.mcp_call = Some((servers, origin)); + self + } + /// The sessions the reader must finish with, and the ids it must have observed. #[must_use] pub fn with_sessions( @@ -210,6 +234,22 @@ impl Case { self } + /// The files the scripted agent writes and the files the harness leaves beside them; the + /// check asserts the driver's `collect` stores the first and not the second. + #[must_use] + pub fn with_workspace(mut self, agent: Vec<PreparedFile>, harness: Vec<PreparedFile>) -> Self { + self.agent_wrote = agent; + self.harness_wrote = harness; + self + } + + /// The commands the driver must collect; its file specs are checked by the workspace oracle. + #[must_use] + pub fn with_collect_commands(mut self, commands: Vec<CollectSpec>) -> Self { + self.collect_commands = Some(commands); + self + } + /// What the driver must collect. #[must_use] pub fn with_collect(mut self, collect: Vec<CollectSpec>) -> Self { @@ -236,8 +276,15 @@ pub struct Setup<'a> { /// Texts that must appear in no argument, no literal variable and no prepared file: the /// values of the secrets the core holds. pub canaries: &'a [String], + /// What a run stores of a workspace: the file specs applied to the tree, as the paths kept. + /// The driver crates' tests give the core's file collector here, applied to the driver's + /// specs. + pub collector: Option<Collector>, } +/// The paths a collector stores from the tree under a root for a driver's file specs. +pub type Collector = fn(&std::path::Path, &[CollectSpec]) -> std::io::Result<Vec<String>>; + impl<'a> Setup<'a> { /// A setup. #[must_use] @@ -250,8 +297,16 @@ impl<'a> Setup<'a> { cell, workspace, canaries, + collector: None, } } + + /// The same setup with the collector the workspace oracle runs. + #[must_use] + pub const fn with_collector(mut self, collector: Collector) -> Self { + self.collector = Some(collector); + self + } } /// A check the driver failed. @@ -606,31 +661,24 @@ fn check_names(driver: &dyn HarnessDriver) -> Result<(), Failure> { Ok(()) } -/// Checks the settings table: no two rows name the same setting and value, a refused row says -/// why, and a mapped row says what it writes. -fn check_settings_table( +/// Checks the answers: every key has one, and an answer says what it writes, what Candler does or +/// why it is refused. +fn check_answers( driver: &dyn HarnessDriver, // TRAIT_OBJECT: the suite checks any driver ) -> Result<(), Failure> { - let rows = driver.settings_table(); - for (index, row) in rows.iter().enumerate() { - if rows - .iter() - .skip(index.saturating_add(1)) - .any(|other| other.setting == row.setting && other.value == row.value) - { - return Err(driver_failure( - "settings_table", - format!("two rows name {} {}", row.setting, row.value), - )); - } - let (empty, what) = match row.disposition { - Disposition::Mapped => (row.construct.is_empty(), "names no construct"), - Disposition::Refused => (row.detail.is_empty(), "gives no reason"), - }; - if empty { + let words = AgentSetting::ALL + .into_iter() + .map(|setting| (format!("{setting:?}"), driver.answer(setting))) + .chain( + DriverFact::ALL + .into_iter() + .map(|fact| (format!("{fact:?}"), driver.fact(fact))), + ); + for (key, answer) in words { + if answer.text().is_empty() { return Err(driver_failure( - "settings_table", - format!("the row {} {} {what}", row.setting, row.value), + "answers", + format!("the answer to {key} has no words"), )); } } @@ -645,21 +693,21 @@ fn check_capabilities( cases: &[Case], owned: &[String], ) -> Result<(), Failure> { - let caps = driver.capabilities(); + let session = !driver.answer(AgentSetting::SessionMode).is_refused(); let spec = &plan.session; - if caps.session && spec.is_none() { + if session && spec.is_none() { return Err(driver_failure( "session", "the session capability is declared and the driver returns no session spec".to_owned(), // BORROW: .to_owned() makes the owned text )); } - if caps.session && driver.session_tracker().is_none() { + if session && driver.session_tracker().is_none() { return Err(driver_failure( "session", "the session capability is declared and the driver returns no tracker".to_owned(), // BORROW: .to_owned() makes the owned text )); } - if !caps.session && spec.is_some() { + if !session && spec.is_some() { return Err(driver_failure( "session", "the driver returns a session spec without the session capability".to_owned(), // BORROW: .to_owned() makes the owned text @@ -700,7 +748,7 @@ fn check_capabilities( } } } - if caps.census { + if !driver.fact(DriverFact::Census).is_refused() { let from_stream = driver.census_stream().is_some(); let from_init = cases.iter().any(|case| case.init.is_some()); if !from_stream && !from_init { @@ -716,7 +764,9 @@ fn check_capabilities( "the case expects an inventory and the census capability is off".to_owned(), // BORROW: .to_owned() makes the owned text )); } - if caps.execution_outside_child && driver.stop().pre_stop.is_none() { + if !driver.fact(DriverFact::ExecutionOutsideChild).is_refused() + && driver.stop().pre_stop.is_none() + { return Err(driver_failure( "stop", "execution lives outside the child and the stop has no pre-stop".to_owned(), // BORROW: .to_owned() makes the owned text @@ -833,6 +883,13 @@ fn frames(framing: Framing, stream: &StreamName, bytes: &[u8]) -> Vec<(RawRef, R .collect() } +/// The MCP servers the case's run declared. +fn declared(case: &Case) -> &[String] { + case.mcp_call + .as_ref() + .map_or(&[][..], |(servers, _)| servers.as_slice()) +} + /// The reader of a case, or the failure that the driver has none. fn reader_of( driver: &dyn HarnessDriver, // TRAIT_OBJECT: the suite checks any driver @@ -841,7 +898,7 @@ fn reader_of( // TRAIT_OBJECT: the driver's reader is chosen at runtime let reader = match &case.reader { ReaderSource::Live => driver.live_reader(), - ReaderSource::Offline(stream) => driver.offline_reader(stream), + ReaderSource::Offline(stream) => driver.offline_reader(stream, declared(case)), }; reader.ok_or_else(|| { case_failure( @@ -947,7 +1004,7 @@ fn read_export( stream: &StreamName, bytes: &[u8], ) -> Result<Vec<Session>, Failure> { - let Some(mut reader) = driver.offline_reader(stream) else { + let Some(mut reader) = driver.offline_reader(stream, &[]) else { return Err(case_failure( case, "export", @@ -991,6 +1048,72 @@ fn check_collect( Ok(()) } +/// Checks a case's oracle: the scripted agent writes `agent_wrote`, and the harness leaves +/// `harness_wrote`, into a real workspace; the setup's collector runs the driver's file specs over +/// that workspace as a run does, and the stored set must equal the files the agent wrote. A file +/// the agent wrote that is not stored is named as missing, and a file stored that the agent did +/// not write is named as extra. The way each harness collects files does not depend on the +/// sessions a stream named, so the check runs `collect` with no observed session and reads only +/// its file specs. +fn check_collect_oracle( + driver: &dyn HarnessDriver, // TRAIT_OBJECT: the suite checks any driver + setup: &Setup<'_>, + case: &Case, +) -> Result<(), Failure> { + if case.agent_wrote.is_empty() { + return Ok(()); + } + let Some(collector) = setup.collector else { + return Err(case_failure( + case, + "collect", + "the case names files the agent wrote and the setup has no collector".to_owned(), // BORROW: .to_owned() makes the owned text + )); + }; + let fail = |detail: String| case_failure(case, "collect", detail); + let root = std::env::temp_dir().join(format!( + "candler-conformance-{}-{}", + std::process::id(), + case.name + )); + let stored = { + let written = write_workspace(&root, case).map_err(|error| fail(error.to_string())); // BORROW: .to_string() gives owned text + let specs = driver.collect(&Workspace::new(&root), &Observed::new(Vec::new())); + let stored = written.and_then(|()| { + collector(&root, &specs).map_err(|error| fail(error.to_string())) // BORROW: .to_string() gives owned text + }); + // Best effort: a leftover scratch directory is the only cost of a failed removal. + let _ = std::fs::remove_dir_all(&root); + stored? + }; + let wrote: Vec<String> = case + .agent_wrote + .iter() + .map(|file| file.path.to_string()) // BORROW: .to_string() makes owned text + .collect(); + let missing: Vec<&String> = wrote.iter().filter(|path| !stored.contains(path)).collect(); + let extra: Vec<&String> = stored.iter().filter(|path| !wrote.contains(path)).collect(); + if missing.is_empty() && extra.is_empty() { + return Ok(()); + } + Err(fail(format!( + "the collect does not store exactly the files the agent wrote: missing {missing:?}, extra {extra:?}" + ))) +} + +/// Writes the files the agent wrote and the files the harness left into `root`. +fn write_workspace(root: &std::path::Path, case: &Case) -> std::io::Result<()> { + std::fs::create_dir_all(root)?; + for file in case.agent_wrote.iter().chain(&case.harness_wrote) { + let path = root.join(file.path.as_str()); // BORROW: explicit .as_str() + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&path, &file.contents)?; + } + Ok(()) +} + /// Runs one case. fn check_case( driver: &dyn HarnessDriver, // TRAIT_OBJECT: the suite checks any driver @@ -1011,11 +1134,35 @@ fn check_case( "the reader does not recognise the start of the recorded stream".to_owned(), // BORROW: .to_owned() makes the owned text )); } + let mut events = Vec::new(); for (raw_ref, frame) in frames(reader.framing(), &case.stream, &case.bytes) { let frame_in = FrameIn::new(raw_ref, None, &frame); - reader - .feed(frame_in) - .map_err(|error| case_failure(case, "feed", error.to_string()))?; // BORROW: .to_string() gives owned text + events.extend( + reader + .feed(frame_in) + .map_err(|error| case_failure(case, "feed", error.to_string()))?, // BORROW: .to_string() gives owned text + ); + } + if let Some((_, want)) = &case.mcp_call { + let got: Vec<&ToolOrigin> = events + .iter() + .filter_map(|entry| { + if let EventKind::ToolCall { origin, .. } = &entry.event.kind { + Some(origin) + } else { + None + } + }) + .collect(); + if got != [want] { + return Err(case_failure( + case, + "origin", + format!( + "expected the one call to have the origin {want:?}, the reader gave {got:?}" + ), + )); + } } let observed: Observed = reader.observed(); if observed.session_ids != case.observed_ids { @@ -1058,7 +1205,22 @@ fn check_case( )); } } + if let Some(want) = &case.collect_commands { + let got: Vec<CollectSpec> = driver + .collect(setup.workspace, &observed) + .into_iter() + .filter(|spec| !matches!(spec, CollectSpec::File { .. })) + .collect(); + if &got != want { + return Err(case_failure( + case, + "collect", + format!("expected commands {want:?}, the driver collects {got:?}"), + )); + } + } check_collect(driver, setup, &observed, owned)?; + check_collect_oracle(driver, setup, case)?; let mut sessions = match &case.sessions { Some(expected) => { let sessions = reader @@ -1132,7 +1294,7 @@ fn check_track( /// Returns the first [`Failure`]: a capability that the driver's specs do not back, a gateway or /// state name that is invalid, a command that carries a secret or sets a name the core owns, a /// stop that cannot work, or a case whose reader, inventory, sessions, end or tracked state is -/// not what the case records. +/// not what the case records, or whose collect does not keep the files the agent wrote. pub fn run( driver: &dyn HarnessDriver, // TRAIT_OBJECT: the suite checks any driver setup: &Setup<'_>, @@ -1140,7 +1302,7 @@ pub fn run( ) -> Result<(), Failure> { let owned = owned_names(driver); check_names(driver)?; - check_settings_table(driver)?; + check_answers(driver)?; let plan = driven("plan", driver.plan(setup.cell, setup.workspace))?; check_capabilities(driver, &plan, setup, cases, &owned)?; check_builds(driver, &plan, setup, &owned)?; diff --git a/crates/candler-harness/src/driver.rs b/crates/candler-harness/src/driver.rs index 159dacc0..6b09037a 100644 --- a/crates/candler-harness/src/driver.rs +++ b/crates/candler-harness/src/driver.rs @@ -12,9 +12,9 @@ use candler_schemas::trace::{EndedBy, Session}; use crate::reader::TraceReader; use crate::skills::SkillTree; use crate::spec::{ - BaseImage, Capabilities, Cell, CollectSpec, CommandSpec, CommandSpecError, GatewayEnv, - HarnessId, Observed, Prepared, ProcessExit, SessionSpec, SessionTracker, StatePath, StopSpec, - Workspace, + AgentSetting, Answer, BaseImage, Cell, CollectSpec, CommandSpec, CommandSpecError, DriverFact, + GatewayEnv, HarnessId, Observed, Prepared, ProcessExit, SessionSpec, SessionTracker, StatePath, + StopSpec, Workspace, }; /// Why a driver could not answer. @@ -35,15 +35,22 @@ pub enum DriverError { /// What is wrong with it. detail: String, }, + /// Two MCP servers whose names make a tool name read two ways: `<first>_` begins the name of + /// `second`. + #[error("servers `{first}` and `{second}` are ambiguous: a tool name that begins `{first}_{rest}` could belong to either", rest = second.strip_prefix(format!("{first}_").as_str()).unwrap_or_default())] + AmbiguousServers { + /// The shorter name. + first: String, + /// The longer name, which begins with the shorter one and `_`. + second: String, + }, /// A setting the harness has no way to honour, refused rather than dropped. - #[error("{harness} {version} cannot honour {path}: {detail}")] + #[error("{harness} cannot honour {path}: {detail}")] Unsupported { /// The pointer into the experiment file of the setting. path: String, /// The harness's name, as its users write it. harness: String, - /// The harness version the driver was validated against. - version: semver::Version, /// Why the harness cannot honour it, and what it accepts instead. detail: String, }, @@ -65,18 +72,12 @@ pub enum DriverError { } impl DriverError { - /// The refusal of `setting`, which the harness `harness` at `version` cannot honour for the - /// reason `detail`. + /// The refusal of `setting`, which the harness `harness` cannot honour for the reason `detail`. /// /// The pointer is the setting's place in the experiment file: a `budget` field sits under /// `/budget`, and any other setting is a key of `[fixed]`, written as its dotted path. #[must_use] - pub fn unsupported( - setting: &FieldPath, - harness: &str, - version: &semver::Version, - detail: &str, - ) -> Self { + pub fn unsupported(setting: &FieldPath, harness: &str, detail: &str) -> Self { let text = setting.to_string(); // BORROW: .to_string() gives owned text let path = if setting.segments().next() == Some("budget") { pointer_of(setting.segments()) @@ -86,70 +87,11 @@ impl DriverError { Self::Unsupported { path, harness: harness.to_owned(), // BORROW: .to_owned() makes the owned text - version: version.clone(), // BORROW: .clone() copies the version detail: detail.to_owned(), // BORROW: .to_owned() makes the owned text } } } -/// Whether a driver honours one cell setting. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum Disposition { - /// The harness has a construct with the setting's meaning, and the driver writes it. - Mapped, - /// The harness has no construct with the setting's meaning; the driver refuses the setting - /// with [`DriverError::Unsupported`]. - Refused, -} - -/// One row of a driver's settings table: a cell setting (or one value or name of it), whether the -/// driver honours it, and in either case the harness construct or the reason, in a few words. -/// -/// The table is data a capability page can read; the driver builds its command and its files from -/// the same rows, so a row and what the driver does cannot differ. -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub struct SettingRow { - /// The cell path, such as `permission_mode` or `tools.allowed`. - pub setting: String, - /// The value or name the row is about (`bypassPermissions`, `Bash`, `high`), or `*` when the - /// row covers the whole setting. - pub value: String, - /// Whether the driver honours the setting. - pub disposition: Disposition, - /// The harness construct a mapped row writes (empty for a refused row). - pub construct: String, - /// How a mapped row maps, or why a refused row is refused. - pub detail: String, -} - -impl SettingRow { - /// A row the driver honours, writing `construct`. - #[must_use] - pub fn mapped(setting: &str, value: &str, construct: &str, detail: &str) -> Self { - Self { - setting: setting.to_owned(), // BORROW: .to_owned() makes the owned text the row keeps - value: value.to_owned(), // BORROW: .to_owned() makes the owned text the row keeps - disposition: Disposition::Mapped, - construct: construct.to_owned(), // BORROW: .to_owned() makes the owned text the row keeps - detail: detail.to_owned(), // BORROW: .to_owned() makes the owned text the row keeps - } - } - - /// A row the driver refuses, for `why`. - #[must_use] - pub fn refused(setting: &str, value: &str, why: &str) -> Self { - Self { - setting: setting.to_owned(), // BORROW: .to_owned() makes the owned text the row keeps - value: value.to_owned(), // BORROW: .to_owned() makes the owned text the row keeps - disposition: Disposition::Refused, - construct: String::new(), - detail: why.to_owned(), // BORROW: .to_owned() makes the owned text the row keeps - } - } -} - /// What a driver does for one cell in one workspace, built once so every part reads the same /// settings. #[derive(Debug, Clone, PartialEq, Eq)] @@ -201,8 +143,13 @@ pub trait HarnessDriver: Send + Sync { /// Returns [`DriverError::VersionOutput`] if `output` names no version. fn parse_version(&self, output: &[u8]) -> Result<semver::Version, DriverError>; - /// What the harness can do. - fn capabilities(&self) -> Capabilities; + /// How the driver meets `setting`: what the harness does for it, what Candler does in its + /// place, or why nobody does. Every key has an answer; there is no default. + fn answer(&self, setting: AgentSetting) -> Answer; + + /// What the driver does on its own, as `fact` asks. Every key has an answer; there is no + /// default. + fn fact(&self, fact: DriverFact) -> Answer; /// What the driver does for `cell` in `workspace`: the files and the environment it adds /// before the launch, the headless command, and the session, if the harness runs one. The core @@ -215,16 +162,6 @@ pub trait HarnessDriver: Send + Sync { /// Returns [`DriverError::Command`] if a command cannot be built. fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result<Plan, DriverError>; - /// The settings table: one row per cell setting, value or name the driver knows, mapped or - /// refused. A driver that declares nothing keeps the default, an empty table, and answers - /// each setting in [`HarnessDriver::plan`]. - /// - /// No two rows name the same `(setting, value)`, a refused row says why, and a mapped row - /// says what it writes. - fn settings_table(&self) -> Vec<SettingRow> { - Vec::new() - } - /// Refuses a cell that sets something the driver cannot honour, with the error /// [`HarnessDriver::plan`] gives for it, so the core can refuse the cell before any job /// starts. The default accepts every cell. @@ -300,8 +237,14 @@ pub trait HarnessDriver: Send + Sync { fn live_reader(&self) -> Option<Box<dyn TraceReader>>; // TRAIT_OBJECT: the core selects drivers and readers at runtime /// The reader of a stream the core collected after the run, such as an export, or `None` if - /// the driver reads no such stream. - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>>; // TRAIT_OBJECT: the core selects drivers and readers at runtime + /// the driver reads no such stream. `servers` are the names of the MCP servers the run's cell + /// declared, which a harness that spells a call `<server>_<tool>` needs to tell a server's tool + /// from another one; a stream read with no cell (an ingested trace) is given none. + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>>; // TRAIT_OBJECT: the core selects drivers and readers at runtime /// How the run ended, read from the exit and the parsed sessions rather than from the exit /// status alone: an exit 0 with an error result is an agent error. A run the experimenter diff --git a/crates/candler-harness/src/mcp.rs b/crates/candler-harness/src/mcp.rs index 11e54b3c..68d29fd6 100644 --- a/crates/candler-harness/src/mcp.rs +++ b/crates/candler-harness/src/mcp.rs @@ -2,16 +2,20 @@ //! //! A server key under `mcp.servers.<key>` is a field-path segment, so it cannot hold a production //! name such as `movement-server`. A server may therefore carry an optional `name` leaf: the name -//! the server renders under (default: the key). Both drivers read the servers through here, so the -//! rule lives once: `name` is removed from the server object, the server is keyed by its rendered -//! name, and a name the agent could not address, or that two servers share, is refused. +//! the server renders under (default: the key). Both drivers and the core read the servers through +//! [`servers`], the one reader of `mcp.servers`: each entry is read as an +//! [`McpServer`], launched from a `command` or reached at a +//! `url` and never both. `name` is removed from the +//! server, the server is keyed by its rendered name, and a name the agent could not address, or +//! that two servers share, is refused. use std::collections::BTreeMap; use std::str::FromStr as _; use candler_schemas::field_path; -use candler_schemas::primitives::Name; -use serde_json::{Map, Value}; +use candler_schemas::primitives::FieldPath; +use candler_schemas::servers::{McpServer, McpServerKind}; +use serde_json::Value; use crate::driver::DriverError; use crate::spec::Cell; @@ -19,9 +23,6 @@ use crate::spec::Cell; /// The path whose table holds the servers, one table per server key. pub const SERVERS: &str = "mcp.servers"; -/// The leaf of a server that names it. -const NAME: &str = "name"; - fn invalid(detail: String) -> DriverError { DriverError::InvalidValue { path: field_path!("mcp.servers"), @@ -29,53 +30,138 @@ fn invalid(detail: String) -> DriverError { } } -/// `servers`, a table of server objects by key, re-keyed by rendered name with `name` removed from -/// each object. +/// The field `path` leads to inside the server at `entry`: the entry's own path extended by every +/// key of `path` that is a field-path segment, up to the first step that is not one (an index). +fn field_at_fault(entry: &FieldPath, path: &serde_path_to_error::Path) -> FieldPath { + use serde_path_to_error::Segment; + let mut text = entry.to_string(); // BORROW: .to_string() gives owned text + for segment in path { + let Segment::Map { key } = segment else { break }; + let longer = format!("{text}.{key}"); + if FieldPath::from_str(&longer).is_err() { + break; + } + text = longer; + } + FieldPath::from_str(&text).unwrap_or_else(|_| entry.clone()) // BORROW: the error owns the path +} + +/// The transport of a read server: the `type` it names, otherwise remote for a `url` without a +/// `command`, otherwise a launched one. +#[must_use] +pub const fn kind(server: &McpServer) -> McpServerKind { + match server.kind { + Some(kind) => kind, + None if server.command.is_none() && server.url.is_some() => McpServerKind::Remote, + None => McpServerKind::Stdio, + } +} + +/// The entry `key` of `mcp.servers` read as a server. +pub(crate) fn read(key: &str, entry: Value) -> Result<McpServer, DriverError> { + let entry_path = FieldPath::from_str(&format!("{SERVERS}.{key}")) + .unwrap_or_else(|_| field_path!("mcp.servers")); + let refused = |detail: String| DriverError::InvalidValue { + path: entry_path.clone(), // BORROW: the error owns the path + detail, + }; + let server: McpServer = serde_path_to_error::deserialize(entry).map_err(|error| { + DriverError::InvalidValue { + path: field_at_fault(&entry_path, error.path()), + detail: error.inner().to_string(), // BORROW: .to_string() gives owned text + } + })?; + let remote = matches!( + kind(&server), + McpServerKind::Http | McpServerKind::Sse | McpServerKind::Remote + ); + if remote { + if server.url.is_none() { + return Err(refused("is a remote server and has no `url`".to_owned())); // BORROW: .to_owned() makes the owned text + } + if server.command.is_some() || server.args.is_some() || server.env.is_some() { + return Err(refused( + "is a remote server and sets `command`, `args` or `env`".to_owned(), // BORROW: .to_owned() makes the owned text + )); + } + } else { + if server.command.is_none() { + return Err(refused( + "has neither a `command` nor a `url`; a server is launched from a `command` or reached at a `url` with `type` http, sse or remote" + .to_owned(), // BORROW: .to_owned() makes the owned text + )); + } + if server.url.is_some() || server.headers.is_some() { + return Err(refused( + "is a launched server and sets `url` or `headers`".to_owned(), + )); // BORROW: .to_owned() makes the owned text + } + } + Ok(server) +} + +/// Whether `name` matches `candler_schemas::servers::SERVER_NAME_PATTERN`: the names that both +/// harnesses carry into a tool id unchanged and that cannot be split two ways +/// (`mcp__<server>__<tool>`, `<server>_<tool>`). The pattern uses an end anchor the `regex` crate +/// does not read, so the check is written out; `guard_mcp_server` holds the published schema to it. +fn plain_name(name: &str) -> bool { + !name.is_empty() + && name.split('_').all(|part| { + !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') + }) +} + +/// `servers` re-keyed by rendered name, with `name` removed from each server. /// /// # Errors -/// [`DriverError::InvalidValue`] when a `name` is not text, is not a plain name (non-empty, with -/// neither `@` nor white space), contains `__` (which would split `mcp__<server>__<tool>`), or when -/// two servers render the same name, by name or by key. -pub fn by_name(servers: &Map<String, Value>) -> Result<Map<String, Value>, DriverError> { - let mut rendered: Map<String, Value> = Map::new(); +/// [`DriverError::InvalidValue`] when a name, given by `name` or by the key, is not made of ASCII +/// letters, digits and `-` joined by single `_` (so none holds `__`, `@`, white space or a +/// character a harness rewrites in a tool id), or when two servers render the same name. +pub fn by_name( + servers: BTreeMap<String, McpServer>, +) -> Result<BTreeMap<String, McpServer>, DriverError> { + let mut rendered: BTreeMap<String, McpServer> = BTreeMap::new(); let mut keys: BTreeMap<String, String> = BTreeMap::new(); - for (key, entry) in servers { - let mut entry = entry.clone(); // BORROW: .clone() copies the server out of the cell - let name = match entry.as_object_mut().and_then(|object| object.remove(NAME)) { - None => key.clone(), // BORROW: .clone() copies the key - Some(Value::String(name)) => { - if let Err(error) = Name::from_str(&name) { - return Err(invalid(format!("the name of server `{key}` {error}"))); - } - if name.contains("__") { - return Err(invalid(format!( - "the name `{name}` of server `{key}` contains `__`, which splits `mcp__<server>__<tool>`" - ))); - } - name - } - Some(_) => { - return Err(invalid(format!("the name of server `{key}` is not text"))); - } - }; + for (key, mut server) in servers { + let name = server.name.take().unwrap_or_else(|| key.clone()); // BORROW: .clone() copies the key + if !plain_name(&name) { + return Err(invalid(format!( + "the name `{name}` of server `{key}` is not made of ASCII letters, digits and `-` joined by single `_`" + ))); + } if let Some(first) = keys.get(&name) { return Err(invalid(format!( "servers `{first}` and `{key}` both render as `{name}`" ))); } - keys.insert(name.clone(), key.clone()); // BORROW: the map owns both - rendered.insert(name, entry); + keys.insert(name.clone(), key); // BORROW: the map owns both + rendered.insert(name, server); } Ok(rendered) } -/// The servers of a cell by rendered name: the values at and below `mcp.servers`, each leaf placed -/// at its path under its key, then [`by_name`]. `None` when the cell sets no server. +/// The servers of a cell by key, each read as an [`McpServer`]: the values at and below +/// `mcp.servers`, each leaf placed at its path under its key. `None` when the cell sets no server. +/// +/// # Errors +/// [`DriverError`] when a value of the cell cannot be used, or an entry is not a server (a field +/// that is not typed or not known, neither a `command` nor a `url`, or both families at once). +pub fn by_key(cell: &Cell<'_>) -> Result<Option<BTreeMap<String, McpServer>>, DriverError> { + let Some(table) = cell.table_at(&field_path!("mcp.servers"))? else { + return Ok(None); + }; + table + .into_iter() + .map(|(key, entry)| read(&key, entry).map(|server| (key, server))) + .collect::<Result<BTreeMap<String, McpServer>, DriverError>>() + .map(Some) +} + +/// The servers of a cell by rendered name: [`by_key`], then [`by_name`]. `None` when the cell sets +/// no server. /// /// # Errors -/// [`DriverError`] when a value of the cell cannot be used, or [`by_name`] refuses a name. -pub fn servers(cell: &Cell<'_>) -> Result<Option<Map<String, Value>>, DriverError> { - cell.table_at(&field_path!("mcp.servers"))? - .map(|table| by_name(&table)) - .transpose() +/// [`DriverError`] when [`by_key`] refuses the cell, or [`by_name`] refuses a name. +pub fn servers(cell: &Cell<'_>) -> Result<Option<BTreeMap<String, McpServer>>, DriverError> { + by_key(cell)?.map(by_name).transpose() } diff --git a/crates/candler-harness/src/refusal.rs b/crates/candler-harness/src/refusal.rs index 1bb0246f..24de5124 100644 --- a/crates/candler-harness/src/refusal.rs +++ b/crates/candler-harness/src/refusal.rs @@ -10,7 +10,7 @@ use std::error::Error; use crate::driver::DriverError; use crate::reader::ReaderError; use crate::spec::{CommandSpecError, InitReportError}; -use candler_schemas::refusal::{CatalogRow, Catalogued, Refusal, Side}; +use candler_schemas::refusal::{CatalogRow, Catalogued, Refusal, Side, pointer_of}; use candler_schemas::refusal_table; /// The path of an error that names no place in a document. @@ -23,8 +23,9 @@ fn driver_error_path(error: &DriverError) -> Option<String> { match error { DriverError::Command(inner) => Refusal::path(inner), DriverError::Unsupported { path, .. } => Some(path.clone()), // BORROW: the path owns its text + DriverError::InvalidValue { path, .. } => Some(pointer_of(path.segments())), + DriverError::AmbiguousServers { .. } => Some("/mcp/servers".to_owned()), // BORROW: .to_owned() makes the owned pointer DriverError::MissingValue { .. } - | DriverError::InvalidValue { .. } | DriverError::VersionOutput { .. } | DriverError::Record { .. } => None, } @@ -42,7 +43,7 @@ refusal_table! { "experiment.cell_value_invalid", Side::Experiment, "A cell value cannot be used by the harness driver.", - "-", + "The field of the value, such as `/mcp/servers/fs/command`.", ), Unsupported { .. } => row( "experiment.setting_unsupported", @@ -50,6 +51,12 @@ refusal_table! { "The experiment sets a setting that the harness has no way to honour, such as a turn cap for a harness with no turn limit; the run is refused rather than the setting dropped.", "The setting in the experiment file: a field under `/budget`, or the key of `[fixed]` that holds it, such as `/fixed/model.effort`.", ), + AmbiguousServers { .. } => row( + "experiment.mcp_server_prefix_ambiguous", + Side::Experiment, + "Two MCP servers of a cell have names that make one tool name read two ways: the name of one, then `_`, is a prefix of the other's name, so a tool of the longer-named server cannot be told from a tool of the shorter-named one.", + "The table of servers, `/mcp/servers`.", + ), VersionOutput { .. } => row( "harness.version_unreadable", Side::Environment, @@ -129,12 +136,6 @@ refusal_table! { "The tool inventory a harness or the gateway observed holds an empty tool name.", "-", ), - ServersNotList { .. } => row( - "harness.server_list_malformed", - Side::Environment, - "The MCP server list a harness observed is not a list.", - "-", - ), NoTools { .. } => row( "harness.inventory_unrecorded", Side::Environment, diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index 94895ecb..000a4b70 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -17,6 +17,7 @@ use candler_schemas::primitives::{ }; use candler_schemas::process::ExitStatus; use candler_schemas::raw::StreamName; +use candler_schemas::servers::McpServerKind; use candler_schemas::trace::SessionId; use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::{Map, Value}; @@ -490,120 +491,266 @@ impl CollectSpec { } } -/// Which per-run budgets a harness can enforce itself. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[non_exhaustive] -pub struct BudgetCaps { - /// The harness can cap the number of turns. - pub turns: bool, - /// The harness can cap the cost. - pub cost: bool, -} - -impl BudgetCaps { - /// Budget capabilities. - #[must_use] - pub const fn new(turns: bool, cost: bool) -> Self { - Self { turns, cost } - } -} - -/// What a harness can do; the core refuses an experiment that needs a capability the harness lacks. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[non_exhaustive] +/// How a driver meets one key. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[expect( - clippy::struct_excessive_bools, - reason = "INDEPENDENT: the capabilities are independent flags, not the states of one value" + clippy::exhaustive_enums, + reason = "EXHAUSTIVE: the drivers live in other crates and match on every answer; a variant added here must break each of them." )] -pub struct Capabilities { - /// The harness stops on a signal and ends its sessions cleanly. - pub graceful_stop: bool, - /// The harness streams events while it runs. - pub live_events: bool, - /// The budgets the harness enforces. - pub budgets: BudgetCaps, - /// The harness has a guard of its own that can confine tool calls. - pub in_harness_guard: bool, - /// The driver can report the tool catalog the agent had. - pub census: bool, - /// Execution lives in a server outside the child process. - pub execution_outside_child: bool, - /// The harness runs a session: its prompt goes through stdin, stdin stays open and a - /// background job's notification can start a further turn. A driver that sets it also - /// returns a [`SessionSpec`] and a [`SessionTracker`]. - pub session: bool, -} - -impl Capabilities { - /// Starts a builder with every capability off. - #[must_use] - pub fn builder() -> CapabilitiesBuilder { - CapabilitiesBuilder::default() - } -} - -/// Builds [`Capabilities`]; every capability is off until set. -#[derive(Debug, Clone, Copy, Default)] -#[non_exhaustive] -pub struct CapabilitiesBuilder { - caps: Capabilities, +pub enum Answer { + /// The harness has a construct with the key's meaning, and the driver writes it. + Mapped { + /// The harness construct, in a few words. + construct: &'static str, + }, + /// Candler does it itself, as the core's enforcement of a budget does. + Candler { + /// What Candler does, in a few words. + how: &'static str, + }, + /// Nobody does it: the harness has no construct for it and Candler does not stand in. + Refused { + /// Why, in a few words. + reason: &'static str, + }, } -impl CapabilitiesBuilder { - /// Sets `graceful_stop`. +impl Answer { + /// Whether the answer is a refusal. #[must_use] - pub const fn graceful_stop(mut self, on: bool) -> Self { - self.caps.graceful_stop = on; - self + pub const fn is_refused(self) -> bool { + matches!(self, Self::Refused { .. }) } - /// Sets `live_events`. + /// The words of the answer: the construct, the Candler action or the reason. #[must_use] - pub const fn live_events(mut self, on: bool) -> Self { - self.caps.live_events = on; - self + pub const fn text(self) -> &'static str { + match self { + Self::Mapped { construct } => construct, + Self::Candler { how } => how, + Self::Refused { reason } => reason, + } } +} - /// Sets the budgets the harness enforces. +/// The effort levels of `model.effort`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[expect( + clippy::exhaustive_enums, + reason = "EXHAUSTIVE: the drivers live in other crates and answer each level; a new level must break each of them." +)] +pub enum EffortLevel { + /// `low`. + Low, + /// `medium`. + Medium, + /// `high`. + High, + /// `xhigh`. + Xhigh, + /// `max`. + Max, + /// `ultracode`: `xhigh` with Claude Code's ultracode mode on. + Ultracode, +} + +impl EffortLevel { + /// Every level. + pub const ALL: [Self; 6] = [ + Self::Low, + Self::Medium, + Self::High, + Self::Xhigh, + Self::Max, + Self::Ultracode, + ]; + + /// The level a cell's text names, or `None` for any other text. #[must_use] - pub const fn budgets(mut self, budgets: BudgetCaps) -> Self { - self.caps.budgets = budgets; - self + pub fn from_text(text: &str) -> Option<Self> { + Self::ALL.into_iter().find(|level| level.as_str() == text) } - /// Sets `in_harness_guard`. + /// The text a cell writes for the level. #[must_use] - pub const fn in_harness_guard(mut self, on: bool) -> Self { - self.caps.in_harness_guard = on; - self + pub const fn as_str(self) -> &'static str { + match self { + Self::Low => "low", + Self::Medium => "medium", + Self::High => "high", + Self::Xhigh => "xhigh", + Self::Max => "max", + Self::Ultracode => "ultracode", + } } +} - /// Sets `census`. +/// The permission modes of `permission_mode`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[expect( + clippy::exhaustive_enums, + reason = "EXHAUSTIVE: the drivers live in other crates and answer each mode; a new mode must break each of them." +)] +pub enum PermissionMode { + /// `default`. + Default, + /// `acceptEdits`. + AcceptEdits, + /// `plan`. + Plan, + /// `bypassPermissions`. + BypassPermissions, + /// `auto`. + Auto, + /// `dontAsk`. + DontAsk, +} + +impl PermissionMode { + /// Every mode. + pub const ALL: [Self; 6] = [ + Self::Default, + Self::AcceptEdits, + Self::Plan, + Self::BypassPermissions, + Self::Auto, + Self::DontAsk, + ]; + + /// The mode a cell's text names, or `None` for any other text. `manual` names + /// [`Self::Default`], as Claude Code reads it. #[must_use] - pub const fn census(mut self, on: bool) -> Self { - self.caps.census = on; - self + pub fn from_text(text: &str) -> Option<Self> { + if text == "manual" { + return Some(Self::Default); + } + Self::ALL.into_iter().find(|mode| mode.as_str() == text) } - /// Sets `execution_outside_child`. + /// The text a cell writes for the mode. #[must_use] - pub const fn execution_outside_child(mut self, on: bool) -> Self { - self.caps.execution_outside_child = on; - self + pub const fn as_str(self) -> &'static str { + match self { + Self::Default => "default", + Self::AcceptEdits => "acceptEdits", + Self::Plan => "plan", + Self::BypassPermissions => "bypassPermissions", + Self::Auto => "auto", + Self::DontAsk => "dontAsk", + } } +} - /// Sets `session`. - #[must_use] - pub const fn session(mut self, on: bool) -> Self { - self.caps.session = on; - self - } +/// What an experiment sets that reaches the agent. A key whose values form a closed set carries +/// the value, so a new value is a compile error in every driver. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[expect( + clippy::exhaustive_enums, + reason = "EXHAUSTIVE: the drivers live in other crates and answer each key with one exhaustive match; a wildcard arm would let a new key go unanswered." +)] +pub enum AgentSetting { + /// `model.id`. + ModelId, + /// `model.endpoint`. + ModelEndpoint, + /// `model.effort`, at one level. + Effort(EffortLevel), + /// `permission_mode`, at one mode. + PermissionMode(PermissionMode), + /// `tools.allowed`. + ToolsAllowed, + /// `tools.disallowed`. + ToolsDisallowed, + /// `env`. + Env, + /// `inputs`. + Inputs, + /// The skills of the treatment. + Skills, + /// The transport of an MCP server. + McpTransport(McpServerKind), + /// The `codemode` of an MCP server, at one value. + Codemode(bool), + /// The `name` of an MCP server. + McpName, + /// `budget.per_run.wall_s`. + WallBudget, + /// `budget.per_run.turns`. + TurnBudget, + /// `budget.per_run.max_cost_usd`. + CostBudget, + /// `runner.mode`. + SessionMode, +} + +impl AgentSetting { + /// Every key, each closed value once. + pub const ALL: [Self; 31] = [ + Self::ModelId, + Self::ModelEndpoint, + Self::Effort(EffortLevel::Low), + Self::Effort(EffortLevel::Medium), + Self::Effort(EffortLevel::High), + Self::Effort(EffortLevel::Xhigh), + Self::Effort(EffortLevel::Max), + Self::Effort(EffortLevel::Ultracode), + Self::PermissionMode(PermissionMode::Default), + Self::PermissionMode(PermissionMode::AcceptEdits), + Self::PermissionMode(PermissionMode::Plan), + Self::PermissionMode(PermissionMode::BypassPermissions), + Self::PermissionMode(PermissionMode::Auto), + Self::PermissionMode(PermissionMode::DontAsk), + Self::ToolsAllowed, + Self::ToolsDisallowed, + Self::Env, + Self::Inputs, + Self::Skills, + Self::McpTransport(McpServerKind::Stdio), + Self::McpTransport(McpServerKind::Local), + Self::McpTransport(McpServerKind::Http), + Self::McpTransport(McpServerKind::Sse), + Self::McpTransport(McpServerKind::Remote), + Self::Codemode(false), + Self::Codemode(true), + Self::McpName, + Self::WallBudget, + Self::TurnBudget, + Self::CostBudget, + Self::SessionMode, + ]; +} + +/// What a driver does on its own. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[expect( + clippy::exhaustive_enums, + reason = "EXHAUSTIVE: the drivers live in other crates and answer each fact with one exhaustive match; a wildcard arm would let a new fact go unanswered." +)] +pub enum DriverFact { + /// The harness stops on a signal and ends its sessions cleanly. + GracefulStop, + /// The harness streams events while it runs. + LiveEvents, + /// The harness has a guard of its own that can confine tool calls. + InHarnessGuard, + /// Execution lives in a server outside the child process. + ExecutionOutsideChild, + /// The driver reports the tool inventory the agent had. + Census, + /// What the harness does when the experiment sets no permission mode. + UnsetPermissionMode, +} - /// The capabilities set so far. - #[must_use] - pub const fn build(self) -> Capabilities { - self.caps - } +impl DriverFact { + /// Every fact. + pub const ALL: [Self; 6] = [ + Self::GracefulStop, + Self::LiveEvents, + Self::InHarnessGuard, + Self::ExecutionOutsideChild, + Self::Census, + Self::UnsetPermissionMode, + ]; } /// How a supervised process came to an end, as the supervisor saw it. @@ -751,25 +898,19 @@ pub enum InitReportError { /// A tool list that holds an empty name. #[error("the tool list holds an empty name")] EmptyToolName, - /// A server list that is not a list. - #[error("the server list is not a list")] - ServersNotList, /// An empty tool list from a source other than the harness's own init event. Such a source /// that saw no tool has seen nothing: the census is unrecorded, not empty. #[error("a collected or gateway source saw no tool, which is an unrecorded inventory")] NoTools, } -/// The tools and MCP servers an agent had at its start, as the raw JSON the census reads, and the -/// source that observed them. +/// The tools an agent had at its start, as the raw JSON the census reads, and the source that +/// observed them. #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub struct InitReport { /// The tool names, a JSON list of strings. pub tools: serde_json::Value, - /// The MCP servers, a JSON list, or `None` when the source cannot see servers: that is - /// unrecorded, not an empty list. - pub mcp_servers: Option<serde_json::Value>, /// Who observed the inventory. pub source: CensusSource, } @@ -779,15 +920,10 @@ impl InitReport { /// /// # Errors /// Returns [`InitReportError::ToolsNotNames`] if `tools` is not a list of strings. - /// Returns [`InitReportError::ServersNotList`] if `mcp_servers` is given and is not a list. /// Returns [`InitReportError::EmptyToolName`] if a tool name is empty. /// Returns [`InitReportError::NoTools`] if `source` is not [`CensusSource::Harness`] and /// `tools` is empty. - pub fn new( - tools: serde_json::Value, - mcp_servers: Option<serde_json::Value>, - source: CensusSource, - ) -> Result<Self, InitReportError> { + pub fn new(tools: serde_json::Value, source: CensusSource) -> Result<Self, InitReportError> { let names = tools .as_array() .is_some_and(|list| list.iter().all(serde_json::Value::is_string)); @@ -803,17 +939,7 @@ impl InitReport { if source != CensusSource::Harness && tools.as_array().is_some_and(Vec::is_empty) { return Err(InitReportError::NoTools); } - if mcp_servers - .as_ref() - .is_some_and(|servers| !servers.is_array()) - { - return Err(InitReportError::ServersNotList); - } - Ok(Self { - tools, - mcp_servers, - source, - }) + Ok(Self { tools, source }) } } @@ -1230,6 +1356,17 @@ pub struct Cell<'a> { values: &'a [ResolvedValue], } +/// A text no variant names, refused at `path` with the accepted spellings. +fn unnamed(path: &FieldPath, text: &str, accepted: &[&str]) -> DriverError { + DriverError::InvalidValue { + path: path.clone(), // BORROW: the error owns the path + detail: format!( + "is `{text}`; the accepted texts are {}", + accepted.join(", ") + ), + } +} + impl<'a> Cell<'a> { /// A view of the resolved values of a cell. #[must_use] @@ -1370,20 +1507,58 @@ impl<'a> Cell<'a> { self.required_text(&field_path!(paths::MODEL_ID)) } - /// The permission mode, which the cell must have. + /// The effort level the cell holds at `path`, or `None` when the cell sets none. The one place + /// effort text becomes a level: resolve and [`Cell::effort`] both read it here, so a stored cell + /// that replays without resolve is refused as a fresh one is. /// /// # Errors - /// [`DriverError`] as [`Cell::required_text`] returns it. - pub fn permission_mode(&self) -> Result<&'a str, DriverError> { - self.required_text(&field_path!(paths::PERMISSION_MODE)) + /// [`DriverError::InvalidValue`] at `path` when the value is not text or names no level. + pub fn effort_at(&self, path: &FieldPath) -> Result<Option<EffortLevel>, DriverError> { + self.text(path)? + .map(|text| { + EffortLevel::from_text(text) + .ok_or_else(|| unnamed(path, text, &EffortLevel::ALL.map(EffortLevel::as_str))) + }) + .transpose() + } + + /// The permission mode the cell holds at `path`, or `None` when the cell sets none. The one + /// place mode text becomes a mode: resolve and [`Cell::permission_mode`] both read it here. A + /// cell that sets no mode asks nothing of the driver: what the harness does then is its + /// [`DriverFact::UnsetPermissionMode`]. + /// + /// # Errors + /// [`DriverError::InvalidValue`] at `path` when the value is not text or names no mode. + pub fn mode_at(&self, path: &FieldPath) -> Result<Option<PermissionMode>, DriverError> { + self.text(path)? + .map(|text| { + PermissionMode::from_text(text).ok_or_else(|| { + unnamed(path, text, &PermissionMode::ALL.map(PermissionMode::as_str)) + }) + }) + .transpose() + } + + /// The permission mode the cell sets, or [`PermissionMode::Default`] when it sets none, which + /// is the mode Claude Code's command line carries for a cell without one. No driver is asked + /// about an unset mode: [`DriverFact::UnsetPermissionMode`] states it. + /// + /// # Errors + /// [`DriverError::InvalidValue`] at `permission_mode` when the value is not text or names no + /// mode, as [`Cell::mode_at`] returns it. + pub fn permission_mode(&self) -> Result<PermissionMode, DriverError> { + Ok(self + .mode_at(&field_path!(paths::PERMISSION_MODE))? + .unwrap_or(PermissionMode::Default)) } /// The reasoning effort, if the cell sets one. /// /// # Errors - /// [`DriverError::InvalidValue`] when the value is not text. - pub fn effort(&self) -> Result<Option<&'a str>, DriverError> { - self.text(&field_path!(paths::MODEL_EFFORT)) + /// [`DriverError::InvalidValue`] at `model.effort` when the value is not text or names no + /// level, as [`Cell::effort_at`] returns it. + pub fn effort(&self) -> Result<Option<EffortLevel>, DriverError> { + self.effort_at(&field_path!(paths::MODEL_EFFORT)) } /// The prompt: the cell's template, filled by [`render_prompt`] from its values. diff --git a/crates/candler-harness/tests/it/conformance_shapes.rs b/crates/candler-harness/tests/it/conformance_shapes.rs index b57a0cd4..1dc6e64a 100644 --- a/crates/candler-harness/tests/it/conformance_shapes.rs +++ b/crates/candler-harness/tests/it/conformance_shapes.rs @@ -15,13 +15,13 @@ use std::time::Duration; use candler_harness::conformance::{ Case, ExpectedSession, ReaderSource, RecordBytes, Setup, TrackStep, run, }; -use candler_harness::driver::{DriverError, HarnessDriver, Plan, SettingRow}; +use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ - Action, Capabilities, Cell, CensusSource, CollectSpec, CommandSpec, CommandSpecError, EnvEntry, - GatewayEnv, InitReport, Observed, ObservedEnd, PendingItem, PendingKind, PendingState, - PreparedFile, ProcessEnd, ProcessExit, SessionClose, SessionSpec, SessionTracker, StateKind, - StatePath, StopSignal, StopSpec, Workspace, + Action, AgentSetting, Answer, Cell, CensusSource, CollectSpec, CommandSpec, CommandSpecError, + DriverFact, EnvEntry, GatewayEnv, HarnessId, InitReport, Observed, ObservedEnd, PendingItem, + PendingKind, PendingState, PreparedFile, ProcessEnd, ProcessExit, SessionClose, SessionSpec, + SessionTracker, StateKind, StatePath, StopSignal, StopSpec, Workspace, }; use candler_schemas::primitives::FieldPath; use candler_schemas::process::ExitStatus; @@ -30,7 +30,7 @@ use candler_schemas::trace::{EndedBy, Session, SessionId}; use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::{Value, json}; -use support::{DocumentDriver, LinesDriver, OpenShapedDriver, TestError, TestResult}; +use support::{DocumentDriver, LinesDriver, LinesReader, OpenShapedDriver, TestError, TestResult}; /// A value that stands for the gateway's token; it must appear in no command. const CANARY: &str = "sk-conformance-canary-7f3a"; @@ -107,7 +107,21 @@ fn run_suite( let cell = Cell::new(&values); let workspace = Workspace::new(Path::new(".")); let canaries = [String::from(CANARY)]; - run(driver, &Setup::new(&cell, &workspace, &canaries), cases) + run( + driver, + &Setup::new(&cell, &workspace, &canaries).with_collector(stored_paths), + cases, + ) +} + +/// What a run stores of a tree: the core's collector over the driver's file specs, as paths. +fn stored_paths(root: &Path, specs: &[CollectSpec]) -> std::io::Result<Vec<String>> { + Ok( + candler_core::runner::exec::gather::collect_files(root, specs)? + .into_iter() + .map(|output| output.path) + .collect(), + ) } /// The Lines-shaped case: the sessions of `guard_two_shapes`, with an init event naming the tools. @@ -121,11 +135,7 @@ fn lines_cases() -> Result<Vec<Case>, TestError> { ] .join("\n") + "\n"; - let init = InitReport::new( - json!(["Bash", "Read"]), - Some(json!([])), - CensusSource::Harness, - )?; + let init = InitReport::new(json!(["Bash", "Read"]), CensusSource::Harness)?; Ok(vec![ Case::new( String::from("lines_with_init"), @@ -252,7 +262,6 @@ fn open_cases() -> Result<Vec<Case>, TestError> { "write", "execute" ]), - None, CensusSource::Gateway, )?; let exit_of = |case: &str| -> Result<ProcessExit, TestError> { @@ -435,7 +444,8 @@ fn conformance_opencode_facts_shape() -> TestResult { /// A working driver with one thing changed. struct Patched { inner: OpenShapedDriver, - capabilities: Option<Capabilities>, + session_answer: Option<Answer>, + wordless: Option<AgentSetting>, stop: Option<StopSpec>, extra_arg: Option<String>, census_stream_removed: bool, @@ -445,14 +455,14 @@ struct Patched { host_collect: bool, state_override: Option<Vec<StatePath>>, gateway_override: Option<GatewayEnv>, - settings_override: Option<Vec<SettingRow>>, } impl Patched { fn new() -> Self { Self { inner: OpenShapedDriver(DocumentDriver), - capabilities: None, + session_answer: None, + wordless: None, stop: None, extra_arg: None, census_stream_removed: false, @@ -462,7 +472,6 @@ impl Patched { host_collect: false, state_override: None, gateway_override: None, - settings_override: None, } } } @@ -497,7 +506,7 @@ impl TraceReader for EagerCensus { } fn observed(&self) -> Observed { // A phantom inventory, whatever the record holds. - let init = InitReport::new(json!(["shell"]), None, CensusSource::Gateway) + let init = InitReport::new(json!(["shell"]), CensusSource::Gateway) .unwrap_or_else(|_| unreachable!()); Observed::new(Vec::new()).with_init(init) } @@ -533,20 +542,26 @@ impl HarnessDriver for Patched { fn parse_version(&self, output: &[u8]) -> Result<semver::Version, DriverError> { self.inner.parse_version(output) } - fn capabilities(&self) -> Capabilities { - self.capabilities - .unwrap_or_else(|| self.inner.capabilities()) + fn answer(&self, setting: AgentSetting) -> Answer { + if self.wordless == Some(setting) { + return Answer::Mapped { construct: "" }; + } + if let Some(answer) = self.session_answer + && setting == AgentSetting::SessionMode + { + return answer; + } + self.inner.answer(setting) + } + + fn fact(&self, fact: DriverFact) -> Answer { + self.inner.fact(fact) } fn gateway(&self) -> Option<GatewayEnv> { self.gateway_override .clone() // BORROW: .clone() copies the override .or_else(|| self.inner.gateway()) } - fn settings_table(&self) -> Vec<SettingRow> { - self.settings_override - .clone() // BORROW: .clone() copies the override - .unwrap_or_else(|| self.inner.settings_table()) - } fn state_paths(&self) -> Vec<StatePath> { self.state_override .clone() // BORROW: .clone() copies the override @@ -581,12 +596,16 @@ impl HarnessDriver for Patched { fn live_reader(&self) -> Option<Box<dyn TraceReader>> { self.inner.live_reader() } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { // BORROW: explicit .as_str() instead of Deref coercion if self.eager_census && stream.as_str() == "model_requests" { return Some(Box::new(EagerCensus)); // TRAIT_OBJECT: the trait returns readers as objects } - self.inner.offline_reader(stream) + self.inner.offline_reader(stream, servers) } fn classify_exit(&self, exit: &ProcessExit, sessions: &[Session]) -> EndedBy { self.inner.classify_exit(exit, sessions) @@ -620,13 +639,156 @@ impl HarnessDriver for Patched { } /// The failure the suite gives a broken driver, or an error when it passes. -fn refusal(driver: &Patched, cases: &[Case]) -> Result<String, TestError> { +fn refusal( + driver: &dyn HarnessDriver, // TRAIT_OBJECT: the suite checks any driver + cases: &[Case], +) -> Result<String, TestError> { match run_suite(driver, cases) { Err(failure) => Ok(failure.to_string()), Ok(()) => Err("the suite passed a broken driver".into()), } } +/// A self-contained case: a scripted agent writes files into a workspace beside a skill file the +/// harness left in a private directory. +fn oracle_case() -> Result<Case, TestError> { + Ok(Case::new( + String::from("collect_keeps_the_files_the_agent_wrote"), + ReaderSource::Live, + name("stdout")?, + Vec::new(), + ) + .detects(false) + .with_workspace( + vec![ + PreparedFile::new("notes.md".parse()?, b"kept".to_vec(), false), + PreparedFile::new("outputs/answer.txt".parse()?, b"stamp".to_vec(), false), + ], + vec![PreparedFile::new( + ".claude/skills/s/SKILL.md".parse()?, + b"skill".to_vec(), + false, + )], + )) +} + +/// A working driver whose `collect` keeps every file of the workspace, except the private +/// directory when `leaves_out` is set. +struct Keeps { + leaves_out: bool, +} + +impl HarnessDriver for Keeps { + fn skills(&self) -> candler_harness::skills::SkillTree { + candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") + } + fn base_image(&self) -> candler_harness::spec::BaseImage { + candler_harness::spec::BaseImage::new("base", Vec::new()) + } + fn detect(&self, _sample: &[u8]) -> Option<semver::Version> { + None + } + fn id(&self) -> candler_harness::spec::HarnessId { + HarnessId::new("keeps".parse().unwrap_or_else(|_| unreachable!())) + } + fn supported(&self) -> semver::VersionReq { + semver::VersionReq::parse(">=1").unwrap_or_else(|_| unreachable!()) + } + fn version_probe(&self) -> CommandSpec { + CommandSpec::builder() + .argv(vec![String::from("k"), String::from("--version")]) + .build() + .unwrap_or_else(|_| unreachable!()) + } + fn parse_version(&self, output: &[u8]) -> Result<semver::Version, DriverError> { + String::from_utf8_lossy(output) + .trim() + .parse() + .map_err(|_| DriverError::VersionOutput { + detail: String::from("no version"), + }) + } + fn answer(&self, setting: AgentSetting) -> Answer { + let refused: &[AgentSetting] = &[ + AgentSetting::SessionMode, + AgentSetting::TurnBudget, + AgentSetting::CostBudget, + ]; + if refused.contains(&setting) { + Answer::Refused { + reason: "test stand-in", + } + } else { + Answer::Mapped { + construct: "test stand-in", + } + } + } + + fn fact(&self, fact: DriverFact) -> Answer { + let held: &[DriverFact] = &[]; + if held.contains(&fact) { + Answer::Mapped { + construct: "test stand-in", + } + } else { + Answer::Refused { + reason: "test stand-in", + } + } + } + fn gateway(&self) -> Option<candler_harness::spec::GatewayEnv> { + Some(candler_harness::spec::GatewayEnv::new( + String::from("K_BASE"), + String::from("K_TOKEN"), + vec![String::from("K_BASE"), String::from("K_TOKEN")], + )) + } + fn plan(&self, _cell: &Cell<'_>, _workspace: &Workspace<'_>) -> Result<Plan, DriverError> { + Ok(Plan::new( + candler_harness::spec::Prepared::default(), + CommandSpec::builder() + .argv(vec![String::from("k")]) + .build()?, + )) + } + fn stop(&self) -> candler_harness::spec::StopSpec { + candler_harness::spec::StopSpec::new( + None, + candler_harness::spec::StopSignal::Term, + Duration::from_secs(5), + ) + } + fn live_reader(&self) -> Option<Box<dyn TraceReader>> { + // TRAIT_OBJECT: the trait returns readers as objects + Some(Box::new(LinesReader { + pending: Vec::new(), + init: None, + })) + } + fn offline_reader( + &self, + _stream: &StreamName, + _servers: &[String], + ) -> Option<Box<dyn TraceReader>> { + // TRAIT_OBJECT: the trait returns readers as objects + Some(Box::new(LinesReader { + pending: Vec::new(), + init: None, + })) + } + fn classify_exit(&self, _exit: &ProcessExit, _sessions: &[Session]) -> EndedBy { + EndedBy::Unknown + } + fn collect(&self, _workspace: &Workspace<'_>, _observed: &Observed) -> Vec<CollectSpec> { + let mut specs = vec![CollectSpec::file(String::from("**/*"))]; + if self.leaves_out { + specs.push(CollectSpec::file(String::from("!.claude/**"))); + } + specs + } +} + /// Guards: R01 §Harness drivers, §Agent environment and secrets, §`OpenCode` v2, §Session runner — /// the checks that refuse a broken driver, each its own section below: a session capability /// without a session spec; a census capability with neither a census stream nor an init report; @@ -639,7 +801,8 @@ fn refusal(driver: &Patched, cases: &[Case]) -> Result<String, TestError> { /// falling back for an unknown or refused id; an inventory from a source that saw no tool; two state /// paths sharing a variable or named like a gateway variable or not a variable at all; gateway names /// that are no variable, one variable for two uses, unreserved or listed twice; a settings table -/// with a row twice, a refusal with no reason or a mapping with no construct. +/// with a row twice, a refusal with no reason or a mapping with no construct; a `collect` that +/// does not keep the files the agent wrote (named) or one that does (passes). /// Removing any one check from `candler-harness/src/conformance.rs` turns the matching section /// below red alone. /// Oracle: the capability and census rules of the leaf, the hand-written canary and the driver's @@ -654,15 +817,9 @@ fn conformance_refuses_a_broken_driver() -> TestResult { let cases = open_cases()?; assert!(run_suite(&Patched::new(), &cases).is_ok()); let mut broken = Patched::new(); - broken.capabilities = Some( - Capabilities::builder() - .graceful_stop(true) - .live_events(true) - .execution_outside_child(true) - .census(true) - .session(true) - .build(), - ); + broken.session_answer = Some(Answer::Mapped { + construct: "test stand-in", + }); let message = refusal(&broken, &cases)?; assert!( message.contains("session capability is declared and the driver returns no session spec"), @@ -769,6 +926,29 @@ fn conformance_refuses_a_broken_driver() -> TestResult { let message = refusal(&broken, &cases)?; assert!(message.contains("host command"), "{message}"); + // A driver whose `collect` stores no file of the workspace is refused, and the refusal names the + // files the agent wrote that are missing. The OpenCode-shaped fake collects only the export + // command (no file glob). + let oracle = oracle_case()?; + let message = refusal(&Patched::new(), std::slice::from_ref(&oracle))?; + assert!( + message.contains("missing") + && message.contains("notes.md") + && message.contains("outputs/answer.txt"), + "{message}" + ); + + // A driver that stores the harness's private file too is refused, and the refusal names it + // as extra. + let message = refusal(&Keeps { leaves_out: false }, std::slice::from_ref(&oracle))?; + assert!( + message.contains("extra") && message.contains(".claude/skills/s/SKILL.md"), + "{message}" + ); + + // A driver that stores exactly what the agent wrote passes the same case. + assert!(run_suite(&Keeps { leaves_out: true }, std::slice::from_ref(&oracle)).is_ok()); + // Two state paths that are one path, or a file that is another path's parent, are refused; a // file inside a directory the driver also lists, and sibling paths, pass. let path = |env: &str, kind: StateKind, text: &str| -> Result<StatePath, TestError> { @@ -855,29 +1035,10 @@ fn conformance_refuses_a_broken_driver() -> TestResult { ); assert!(refusal(&twice, &cases)?.contains("a reserved name is listed twice")); - // A settings table that names a setting and value twice, a refused row that gives no reason - // and a mapped row that names no construct are refused; a sound table passes. - let table = |rows: Vec<SettingRow>| { - let mut driver = Patched::new(); - driver.settings_override = Some(rows); - driver - }; - let mapped = SettingRow::mapped("permission_mode", "bypassPermissions", "`--auto`", "all"); - let refused = SettingRow::refused("permission_mode", "plan", "reads and read-only shell"); - assert!(run_suite(&table(vec![mapped.clone(), refused.clone()]), &cases).is_ok()); // BORROW: .clone() copies the row - let duplicate = table(vec![mapped.clone(), mapped.clone()]); // BORROW: .clone() copies the row - assert!( - refusal(&duplicate, &cases)?.contains("two rows name permission_mode bypassPermissions") - ); - let no_reason = table(vec![SettingRow::refused("permission_mode", "plan", "")]); - assert!(refusal(&no_reason, &cases)?.contains("gives no reason")); - let no_construct = table(vec![SettingRow::mapped( - "permission_mode", - "plan", - "", - "all", - )]); - assert!(refusal(&no_construct, &cases)?.contains("names no construct")); + // An answer that has no words is refused. + let mut wordless = Patched::new(); + wordless.wordless = Some(AgentSetting::CostBudget); + assert!(refusal(&wordless, &cases)?.contains("has no words")); // An in-container script that finds a process with the full-command-line option of `pgrep` // or `pkill` is refused, in any option cluster; exact-name and `/proc` forms pass. @@ -942,23 +1103,23 @@ fn conformance_refuses_a_broken_driver() -> TestResult { // own empty init list is a recorded one, and the three sources never compare equal. for source in [CensusSource::Gateway, CensusSource::Collected] { assert_eq!( - InitReport::new(json!([]), None, source), + InitReport::new(json!([]), source), Err(InitReportError::NoTools) ); } - assert!(InitReport::new(json!([]), Some(json!([])), CensusSource::Harness).is_ok()); + assert!(InitReport::new(json!([]), CensusSource::Harness).is_ok()); for source in [ CensusSource::Harness, CensusSource::Gateway, CensusSource::Collected, ] { assert_eq!( - InitReport::new(json!(["read", ""]), None, source), + InitReport::new(json!(["read", ""]), source), Err(InitReportError::EmptyToolName) ); } let tools = || json!(["read"]); - let by = |source| InitReport::new(tools(), None, source); + let by = |source| InitReport::new(tools(), source); assert_ne!(by(CensusSource::Harness)?, by(CensusSource::Gateway)?); assert_ne!(by(CensusSource::Gateway)?, by(CensusSource::Collected)?); assert_ne!(by(CensusSource::Harness)?, by(CensusSource::Collected)?); @@ -993,8 +1154,12 @@ impl HarnessDriver for Silent { fn parse_version(&self, output: &[u8]) -> Result<semver::Version, DriverError> { self.0.parse_version(output) } - fn capabilities(&self) -> Capabilities { - self.0.capabilities() + fn answer(&self, setting: AgentSetting) -> Answer { + self.0.answer(setting) + } + + fn fact(&self, fact: DriverFact) -> Answer { + self.0.fact(fact) } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result<Plan, DriverError> { self.0.plan(cell, workspace) @@ -1005,8 +1170,12 @@ impl HarnessDriver for Silent { fn live_reader(&self) -> Option<Box<dyn TraceReader>> { self.0.live_reader() } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { - self.0.offline_reader(stream) + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { + self.0.offline_reader(stream, servers) } fn classify_exit(&self, exit: &ProcessExit, sessions: &[Session]) -> EndedBy { self.0.classify_exit(exit, sessions) @@ -1086,14 +1255,35 @@ fn conformance_session_surface_on_a_fake() -> TestResult { fn parse_version(&self, output: &[u8]) -> Result<semver::Version, DriverError> { self.0.parse_version(output) } - fn capabilities(&self) -> Capabilities { - Capabilities::builder() - .graceful_stop(true) - .live_events(true) - .execution_outside_child(true) - .census(true) - .session(true) - .build() + fn answer(&self, setting: AgentSetting) -> Answer { + let refused: &[AgentSetting] = &[AgentSetting::TurnBudget, AgentSetting::CostBudget]; + if refused.contains(&setting) { + Answer::Refused { + reason: "test stand-in", + } + } else { + Answer::Mapped { + construct: "test stand-in", + } + } + } + + fn fact(&self, fact: DriverFact) -> Answer { + let held: &[DriverFact] = &[ + DriverFact::GracefulStop, + DriverFact::LiveEvents, + DriverFact::Census, + DriverFact::ExecutionOutsideChild, + ]; + if held.contains(&fact) { + Answer::Mapped { + construct: "test stand-in", + } + } else { + Answer::Refused { + reason: "test stand-in", + } + } } fn gateway(&self) -> Option<GatewayEnv> { self.0.gateway() @@ -1134,8 +1324,12 @@ fn conformance_session_surface_on_a_fake() -> TestResult { fn live_reader(&self) -> Option<Box<dyn TraceReader>> { self.0.live_reader() } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { - self.0.offline_reader(stream) + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { + self.0.offline_reader(stream, servers) } fn classify_exit(&self, exit: &ProcessExit, sessions: &[Session]) -> EndedBy { self.0.classify_exit(exit, sessions) diff --git a/crates/candler-harness/tests/it/guard_mcp_names.rs b/crates/candler-harness/tests/it/guard_mcp_names.rs index 093cbb0c..0c72fca3 100644 --- a/crates/candler-harness/tests/it/guard_mcp_names.rs +++ b/crates/candler-harness/tests/it/guard_mcp_names.rs @@ -39,13 +39,56 @@ fn detail(entries: &[(&str, Value)]) -> Res<String> { fn two_servers_rendering_one_name_are_refused() -> Res<()> { let by_name = detail(&[ ("mcp.servers.a.name", json!("x-y")), + ("mcp.servers.a.command", json!("uvx")), ("mcp.servers.b.name", json!("x-y")), + ("mcp.servers.b.command", json!("uvx")), ])?; assert!(by_name.contains("both render as `x-y`"), "{by_name}"); let by_key = detail(&[ ("mcp.servers.a.name", json!("x_y")), + ("mcp.servers.a.command", json!("uvx")), ("mcp.servers.x_y.command", json!("uvx")), ])?; assert!(by_key.contains("both render as `x_y`"), "{by_key}"); Ok(()) } + +/// Guards: R01 §Agent environment — a server name, given by `name` or by the key, is ASCII letters, +/// digits and `-` joined by single `_`: `s_`, `_s`, `a__b`, `a.b` and `my srv` are refused, and +/// `a-b` and `a_b` are accepted. A key goes through the same check as a `name`. +/// Oracle: the names are written by hand from `SERVER_NAME_PATTERN` of `candler_schemas::servers`. +/// Bite: a check that applies to `name` only, or one that lets a trailing `_`, a `.` or a space by. +#[test] +fn a_server_name_is_letters_digits_and_dashes_joined_by_single_underscores() -> Res<()> { + for refused in ["s_", "_s", "a__b", "a.b", "my srv", "a@b", ""] { + let by_name = detail(&[ + ("mcp.servers.k.name", json!(refused)), + ("mcp.servers.k.command", json!("uvx")), + ])?; + assert!( + by_name.contains("not made of ASCII letters"), + "{refused}: {by_name}" + ); + } + for key in ["s_", "a__b"] { + let by_key = detail(&[(&format!("mcp.servers.{key}.command"), json!("uvx"))])?; + assert!( + by_key.contains("not made of ASCII letters"), + "{key}: {by_key}" + ); + } + for accepted in ["a-b", "a_b", "A1", "x-y_z"] { + let values = cell(&[ + ("mcp.servers.k.name", json!(accepted)), + ("mcp.servers.k.command", json!("uvx")), + ])?; + let found = servers(&Cell::new(&values))?.ok_or("no servers")?; + assert_eq!( + found.keys().map(String::as_str).collect::<Vec<_>>(), + [accepted] + ); + } + let keyed = cell(&[("mcp.servers.a_b.command", json!("uvx"))])?; + assert!(servers(&Cell::new(&keyed))?.is_some_and(|found| found.contains_key("a_b"))); + Ok(()) +} diff --git a/crates/candler-harness/tests/it/support/mod.rs b/crates/candler-harness/tests/it/support/mod.rs index ccdfe2c4..d65b2125 100644 --- a/crates/candler-harness/tests/it/support/mod.rs +++ b/crates/candler-harness/tests/it/support/mod.rs @@ -14,10 +14,10 @@ use std::time::Duration; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::{FrameIn, ReaderError, TraceReader}; use candler_harness::spec::{ - Action, BudgetCaps, Capabilities, Cell, CensusSource, CollectSpec, CommandSpec, Confidence, - FormatVersion, Framing, GatewayEnv, HarnessId, HttpMethod, InitReport, Observed, ObservedEnd, - Prepared, PreparedFile, ProcessEnd, ProcessExit, StateKind, StatePath, StopSignal, StopSpec, - Workspace, + Action, AgentSetting, Answer, Cell, CensusSource, CollectSpec, CommandSpec, Confidence, + DriverFact, FormatVersion, Framing, GatewayEnv, HarnessId, HttpMethod, InitReport, Observed, + ObservedEnd, Prepared, PreparedFile, ProcessEnd, ProcessExit, StateKind, StatePath, StopSignal, + StopSpec, Workspace, }; use candler_schemas::primitives::{FieldPath, Name, NameVersion, Timestamp}; use candler_schemas::raw::{RawFrame, RawRef, StreamName}; @@ -144,12 +144,7 @@ impl TraceReader for LinesReader { && let Some(tools) = value.get("tools") { // BORROW: .cloned() copies the lists out of the frame - self.init = InitReport::new( - tools.clone(), - value.get("mcp_servers").cloned(), - CensusSource::Harness, - ) - .ok(); + self.init = InitReport::new(tools.clone(), CensusSource::Harness).ok(); } // BORROW: .clone() copies the frame time into the session pending.started_at = at.clone(); @@ -262,14 +257,35 @@ impl HarnessDriver for LinesDriver { }) } - fn capabilities(&self) -> Capabilities { - Capabilities::builder() - .graceful_stop(true) - .live_events(true) - .budgets(BudgetCaps::new(true, true)) - .in_harness_guard(true) - .census(true) - .build() + fn answer(&self, setting: AgentSetting) -> Answer { + let refused: &[AgentSetting] = &[AgentSetting::SessionMode]; + if refused.contains(&setting) { + Answer::Refused { + reason: "test stand-in", + } + } else { + Answer::Mapped { + construct: "test stand-in", + } + } + } + + fn fact(&self, fact: DriverFact) -> Answer { + let held: &[DriverFact] = &[ + DriverFact::GracefulStop, + DriverFact::LiveEvents, + DriverFact::InHarnessGuard, + DriverFact::Census, + ]; + if held.contains(&fact) { + Answer::Mapped { + construct: "test stand-in", + } + } else { + Answer::Refused { + reason: "test stand-in", + } + } } fn gateway(&self) -> Option<GatewayEnv> { @@ -310,7 +326,11 @@ impl HarnessDriver for LinesDriver { })) } - fn offline_reader(&self, _stream: &StreamName) -> Option<Box<dyn TraceReader>> { + fn offline_reader( + &self, + _stream: &StreamName, + _servers: &[String], + ) -> Option<Box<dyn TraceReader>> { // TRAIT_OBJECT: the trait returns readers as objects Some(Box::new(LinesReader { pending: Vec::new(), @@ -486,11 +506,34 @@ impl HarnessDriver for DocumentDriver { }) } - fn capabilities(&self) -> Capabilities { - Capabilities::builder() - .graceful_stop(true) - .execution_outside_child(true) - .build() + fn answer(&self, setting: AgentSetting) -> Answer { + let refused: &[AgentSetting] = &[ + AgentSetting::SessionMode, + AgentSetting::TurnBudget, + AgentSetting::CostBudget, + ]; + if refused.contains(&setting) { + Answer::Refused { + reason: "test stand-in", + } + } else { + Answer::Mapped { + construct: "test stand-in", + } + } + } + + fn fact(&self, fact: DriverFact) -> Answer { + let held: &[DriverFact] = &[DriverFact::GracefulStop, DriverFact::ExecutionOutsideChild]; + if held.contains(&fact) { + Answer::Mapped { + construct: "test stand-in", + } + } else { + Answer::Refused { + reason: "test stand-in", + } + } } fn gateway(&self) -> Option<GatewayEnv> { @@ -549,7 +592,11 @@ impl HarnessDriver for DocumentDriver { None } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { + fn offline_reader( + &self, + stream: &StreamName, + _servers: &[String], + ) -> Option<Box<dyn TraceReader>> { // BORROW: explicit .as_str() instead of Deref coercion if stream.as_str() == "export" { // TRAIT_OBJECT: the trait returns readers as objects @@ -735,7 +782,7 @@ impl TraceReader for CensusReader { match self .tools .clone() // BORROW: .clone() copies the tools out of the reader - .and_then(|tools| InitReport::new(tools, None, CensusSource::Gateway).ok()) + .and_then(|tools| InitReport::new(tools, CensusSource::Gateway).ok()) { Some(init) => observed.with_init(init), None => observed, @@ -790,13 +837,39 @@ impl HarnessDriver for OpenShapedDriver { self.0.parse_version(output) } - fn capabilities(&self) -> Capabilities { - Capabilities::builder() - .graceful_stop(true) - .live_events(true) - .execution_outside_child(true) - .census(true) - .build() + fn answer(&self, setting: AgentSetting) -> Answer { + let refused: &[AgentSetting] = &[ + AgentSetting::SessionMode, + AgentSetting::TurnBudget, + AgentSetting::CostBudget, + ]; + if refused.contains(&setting) { + Answer::Refused { + reason: "test stand-in", + } + } else { + Answer::Mapped { + construct: "test stand-in", + } + } + } + + fn fact(&self, fact: DriverFact) -> Answer { + let held: &[DriverFact] = &[ + DriverFact::GracefulStop, + DriverFact::LiveEvents, + DriverFact::Census, + DriverFact::ExecutionOutsideChild, + ]; + if held.contains(&fact) { + Answer::Mapped { + construct: "test stand-in", + } + } else { + Answer::Refused { + reason: "test stand-in", + } + } } fn gateway(&self) -> Option<GatewayEnv> { @@ -883,12 +956,16 @@ impl HarnessDriver for OpenShapedDriver { Some(Box::new(IdsReader::new())) } - fn offline_reader(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>> { + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option<Box<dyn TraceReader>> { // BORROW: explicit .as_str() instead of Deref coercion match stream.as_str() { "model_requests" => Some(Box::new(CensusReader { tools: None })), // TRAIT_OBJECT: the trait returns readers as objects "export" => Some(Box::new(ExportReader { session: None })), // TRAIT_OBJECT: the trait returns readers as objects - _ => self.0.offline_reader(stream), + _ => self.0.offline_reader(stream, servers), } } diff --git a/crates/candler-schemas/schema/README.md b/crates/candler-schemas/schema/README.md index b999df50..4c415e14 100644 --- a/crates/candler-schemas/schema/README.md +++ b/crates/candler-schemas/schema/README.md @@ -23,7 +23,6 @@ or file, or a message of the evaluator protocol. | File | Root type | Wire tag | R01 section | |---|---|---|---| | `analysis-report.schema.json` | `AnalysisReport` | `analysis-report/1` | Analysis statistics | -| `catalog-snapshot.schema.json` | `CatalogSnapshot` | `tool-catalog-snapshot/1` | Wire schema: tool-catalog snapshot | | `child-record.schema.json` | `ChildRecord` | `child-record/1` | Process supervision | | `container-record.schema.json` | `ContainerRecord` | `container-record/1` | Process supervision (job dir) | | `evaluator-describe-result.schema.json` | `DescribeResult` | none; `protocol` is `{major, minor}` | Evaluator protocol (`describe` result) | diff --git a/crates/candler-schemas/schema/catalog-snapshot.schema.json b/crates/candler-schemas/schema/catalog-snapshot.schema.json deleted file mode 100644 index fa96eebe..00000000 --- a/crates/candler-schemas/schema/catalog-snapshot.schema.json +++ /dev/null @@ -1,170 +0,0 @@ -{ - "$defs": { - "CatalogServer": { - "additionalProperties": false, - "description": "One MCP server of a run and the tools it offered.", - "properties": { - "name": { - "description": "The name of the server: at least one character, and unique among the servers of its snapshot.", - "minLength": 1, - "type": "string" - }, - "source_digest": { - "$ref": "#/$defs/Digest", - "description": "The digest of the server's source file." - }, - "source_path": { - "$ref": "#/$defs/RelPath", - "description": "The path of the server's source file: a POSIX path relative to the project root." - }, - "tools": { - "$comment": "Tool names are unique within the array, compared byte for byte (case-sensitive, without Unicode normalisation); JSON Schema cannot state this, and the Rust reader refuses a repeated name.", - "description": "The tools the server offered, with names unique among them.", - "items": { - "$ref": "#/$defs/Tool" - }, - "type": "array" - }, - "transport": { - "$ref": "#/$defs/Transport", - "description": "How a client reaches the server." - } - }, - "required": [ - "name", - "source_path", - "source_digest", - "transport", - "tools" - ], - "type": "object" - }, - "Digest": { - "description": "A content digest: `sha256:` followed by 64 lowercase hex digits.", - "pattern": "^sha256:[0-9a-f]{64}(?![\\s\\S])", - "type": "string" - }, - "NameToken": { - "description": "A catalog provider reference, `name@token`, split at the last `@`: the name is non-empty and holds neither `@` nor white space, and the token matches `[0-9A-Za-z.+-]+`.", - "pattern": "^[^@\\t\\n\\v\\f\\r\\x20\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+@[0-9A-Za-z.+-]+(?![\\s\\S])", - "type": "string" - }, - "RelPath": { - "description": "A run-relative POSIX path: non-empty, with no leading `/`, no empty segment, no `.` or `..` segment, no NUL and no `\\`.", - "pattern": "^(?!\\.\\.?(?:/|(?![\\s\\S])))[^/\\\\\\x00]+(?:/(?!\\.\\.?(?:/|(?![\\s\\S])))[^/\\\\\\x00]+)*(?![\\s\\S])", - "type": "string" - }, - "Timestamp": { - "$comment": "The pattern states the lexical form; a date or time that names no instant, such as month 13, and a fraction of more than nine digits are refused by the parser.", - "description": "An RFC 3339 timestamp with an uppercase `T` and an explicit offset, `Z` or `±HH:MM`.", - "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\.[0-9]+)?(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])(?![\\s\\S])", - "type": "string" - }, - "Tool": { - "additionalProperties": true, - "description": "A tool in MCP `tools/list` shape: the named keys of the MCP `Tool` definition, and every other key as the server gave it.", - "properties": { - "annotations": { - "additionalProperties": true, - "description": "Hints about the behaviour of the tool: an open object whose keys are kept as given.", - "type": "object" - }, - "description": { - "description": "A human-readable description of the tool.", - "type": "string" - }, - "inputSchema": { - "additionalProperties": true, - "description": "The JSON Schema object that describes the arguments of the tool. Its `type` is not required to be `object`.", - "type": "object" - }, - "name": { - "description": "The name of the tool, as the server gave it: at least one character, and unique among the tools of its server.", - "minLength": 1, - "type": "string" - }, - "outputSchema": { - "additionalProperties": true, - "description": "The JSON Schema object that describes the structured output of the tool.", - "type": "object" - }, - "title": { - "description": "A human-readable title of the tool.", - "type": "string" - } - }, - "required": [ - "name", - "inputSchema" - ], - "type": "object" - }, - "Transport": { - "description": "How a client reaches an MCP server.", - "oneOf": [ - { - "const": "stdio", - "description": "The server runs as a subprocess and is spoken to over its standard input and output.", - "type": "string" - }, - { - "const": "http", - "description": "The server is reached over streamable HTTP.", - "type": "string" - }, - { - "const": "sse", - "description": "The server is reached over server-sent events.", - "type": "string" - } - ] - } - }, - "$id": "urn:candler:schemas:catalog-snapshot", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "description": "What the MCP servers targeted by a run offered: for each server, its tools in the shape of an MCP `tools/list` result.", - "properties": { - "captured_at": { - "$ref": "#/$defs/Timestamp", - "description": "When the snapshot was captured." - }, - "environment": { - "additionalProperties": { - "type": "string" - }, - "description": "The versions the capture depended on, as an object from a name to its version text.", - "type": "object" - }, - "ext": { - "additionalProperties": true, - "description": "Provider-specific data: an open JSON object that Candler does not interpret.", - "type": "object" - }, - "provider": { - "$ref": "#/$defs/NameToken", - "description": "The catalog provider that captured the snapshot, as `name@token`." - }, - "schema": { - "const": "tool-catalog-snapshot/1", - "description": "The version marker of the document: always `tool-catalog-snapshot/1`.", - "type": "string" - }, - "servers": { - "$comment": "Server names are unique within the array, compared byte for byte (case-sensitive, without Unicode normalisation); JSON Schema cannot state this, and the Rust reader refuses a repeated name.", - "description": "The servers the run targeted, each with the tools it offered, with names unique among them.", - "items": { - "$ref": "#/$defs/CatalogServer" - }, - "type": "array" - } - }, - "required": [ - "schema", - "captured_at", - "provider", - "servers" - ], - "title": "CatalogSnapshot", - "type": "object" -} diff --git a/crates/candler-schemas/schema/evaluator-describe-result.schema.json b/crates/candler-schemas/schema/evaluator-describe-result.schema.json index 7fb7de4f..3c82c676 100644 --- a/crates/candler-schemas/schema/evaluator-describe-result.schema.json +++ b/crates/candler-schemas/schema/evaluator-describe-result.schema.json @@ -175,7 +175,7 @@ "type": "array" }, "snapshots": { - "description": "The kinds of snapshot the check reads.", + "description": "The kinds of snapshot the check reads. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released.", "items": { "$ref": "#/$defs/Name" }, diff --git a/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json b/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json index ae786a73..bdc7d3e4 100644 --- a/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json +++ b/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json @@ -658,7 +658,7 @@ "description": "The key of the run." }, "snapshots": { - "description": "The snapshots the run was made against.", + "description": "The snapshots the run was made against. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released.", "items": { "$ref": "#/$defs/ContextRef" }, diff --git a/crates/candler-schemas/schema/evaluator-message.schema.json b/crates/candler-schemas/schema/evaluator-message.schema.json index 37a96551..2c18715e 100644 --- a/crates/candler-schemas/schema/evaluator-message.schema.json +++ b/crates/candler-schemas/schema/evaluator-message.schema.json @@ -525,7 +525,7 @@ "type": "array" }, "snapshots": { - "description": "The kinds of snapshot the check reads.", + "description": "The kinds of snapshot the check reads. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released.", "items": { "$ref": "#/$defs/Name" }, @@ -1207,7 +1207,7 @@ "description": "The key of the run." }, "snapshots": { - "description": "The snapshots the run was made against.", + "description": "The snapshots the run was made against. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released.", "items": { "$ref": "#/$defs/ContextRef" }, diff --git a/crates/candler-schemas/schema/evaluator-request-side.schema.json b/crates/candler-schemas/schema/evaluator-request-side.schema.json index b83f7761..95c070d3 100644 --- a/crates/candler-schemas/schema/evaluator-request-side.schema.json +++ b/crates/candler-schemas/schema/evaluator-request-side.schema.json @@ -780,7 +780,7 @@ "description": "The key of the run." }, "snapshots": { - "description": "The snapshots the run was made against.", + "description": "The snapshots the run was made against. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released.", "items": { "$ref": "#/$defs/ContextRef" }, diff --git a/crates/candler-schemas/schema/inspect-run.schema.json b/crates/candler-schemas/schema/inspect-run.schema.json index 014fcb22..98273ae2 100644 --- a/crates/candler-schemas/schema/inspect-run.schema.json +++ b/crates/candler-schemas/schema/inspect-run.schema.json @@ -58,6 +58,11 @@ "job": { "description": "The job that made the run." }, + "mcp": { + "additionalProperties": true, + "description": "The resolved `mcp.*` values the cell hashes, by path: the MCP configuration the run was\ninstalled with.", + "type": "object" + }, "measured": { "additionalProperties": true, "description": "The other measured values, by path.", @@ -96,6 +101,7 @@ "schema", "run", "sealed", + "mcp", "provenance", "measured", "outcomes" diff --git a/crates/candler-schemas/schema/mcp-server.schema.json b/crates/candler-schemas/schema/mcp-server.schema.json new file mode 100644 index 00000000..4d72ac2d --- /dev/null +++ b/crates/candler-schemas/schema/mcp-server.schema.json @@ -0,0 +1,119 @@ +{ + "$defs": { + "McpServerKind": { + "description": "The transport family a server speaks: a locally-started command or a remote URL.\n\nA `stdio` (or `local`) server starts a command and is the default when an entry sets no `type`;\na remote one is reached at a URL. The renderer reads `http`, `sse` and `remote` alike.", + "oneOf": [ + { + "const": "stdio", + "description": "A server that prints the MCP protocol over a child process's standard streams.", + "type": "string" + }, + { + "const": "local", + "description": "A local server the drivers treat as a stdio one.", + "type": "string" + }, + { + "const": "http", + "description": "A server reached over HTTP.", + "type": "string" + }, + { + "const": "sse", + "description": "A server reached over a Server-Sent Events stream.", + "type": "string" + }, + { + "const": "remote", + "description": "A server reached at a URL.", + "type": "string" + } + ] + } + }, + "$id": "urn:candler:schemas:mcp-server", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "One entry of an experiment's `mcp.servers`, as the drivers read it.\n\nA server is launched from a `command` (with optional `args` and `env`) or reached at a `url`\n(with optional `headers`); exactly one of `command` and `url` is required, and a `type` marker\nagrees with it: `stdio` or `local` with `command`, `http`, `sse` or `remote` with `url`.\n`codemode` selects the prompts the agent sees, and is `false` when absent. A `name`\nleaf names the server under a key; without it the key names it. Every field the drivers read\nis typed here, so a non-text `command`, a non-list `args` or a non-text environment value fails\nvalidation rather than being read leniently.", + "oneOf": [ + { + "properties": { + "headers": false, + "type": { + "enum": [ + "stdio", + "local" + ] + }, + "url": false + }, + "required": [ + "command" + ] + }, + { + "properties": { + "args": false, + "command": false, + "env": false, + "type": { + "enum": [ + "http", + "sse", + "remote" + ] + } + }, + "required": [ + "url" + ] + } + ], + "properties": { + "args": { + "description": "The arguments the launched command receives, one per list item.", + "items": { + "type": "string" + }, + "type": "array" + }, + "codemode": { + "default": false, + "description": "Whether the server's tools show in the agent's codemode prompts; false when absent.", + "type": "boolean" + }, + "command": { + "description": "The launched command, as a program name or path; required of an entry with no URL.", + "type": "string" + }, + "env": { + "additionalProperties": { + "type": "string" + }, + "description": "The environment of the launched command, by variable name.", + "type": "object" + }, + "headers": { + "additionalProperties": { + "type": "string" + }, + "description": "The headers a remote server is called with.", + "type": "object" + }, + "name": { + "description": "The name the server renders under, when its key would not do; a key\nmatches the same pattern.", + "pattern": "^[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*(?![\\s\\S])", + "type": "string" + }, + "type": { + "$ref": "#/$defs/McpServerKind", + "description": "The transport marker: `stdio` or `local` for a launched command, `http`, `sse` or `remote`\nfor a URL; absent when the driver would launch a command." + }, + "url": { + "description": "The URL a remote server is reached at.", + "type": "string" + } + }, + "title": "McpServer", + "type": "object" +} diff --git a/crates/candler-schemas/schema/normalised-trace.schema.json b/crates/candler-schemas/schema/normalised-trace.schema.json index 90e98514..bb8e824b 100644 --- a/crates/candler-schemas/schema/normalised-trace.schema.json +++ b/crates/candler-schemas/schema/normalised-trace.schema.json @@ -518,7 +518,7 @@ "type": "string" }, "ToolOrigin": { - "description": "Where a tool call is served from: an object whose `kind` is `builtin`, `mcp`, with the `server` that offers the tool, or `other`.", + "description": "Where a tool call is served from: an object whose `kind` is `builtin`, `mcp`, with the `server` that offers the tool and the server's own name for it, or `other`.", "oneOf": [ { "additionalProperties": false, @@ -536,7 +536,7 @@ }, { "additionalProperties": false, - "description": "A tool an MCP server offers.", + "description": "A tool an MCP server offers. Claude Code's reader takes any `mcp__<server>__<tool>` for the\ntool of `<server>`, declared or not; `OpenCode`'s takes only a declared server, because its\nspelling `<server>_<tool>` cannot be split without the server names.", "properties": { "kind": { "const": "mcp", @@ -545,6 +545,10 @@ "server": { "description": "The name of the MCP server.", "type": "string" + }, + "tool": { + "description": "The tool's name at the server, without the harness's prefix. A trace written before the\nfield existed has none.", + "type": "string" } }, "required": [ diff --git a/crates/candler-schemas/schema/run-manifest.schema.json b/crates/candler-schemas/schema/run-manifest.schema.json index 88de542b..02704072 100644 --- a/crates/candler-schemas/schema/run-manifest.schema.json +++ b/crates/candler-schemas/schema/run-manifest.schema.json @@ -2,7 +2,7 @@ "$defs": { "Comparable": { "additionalProperties": false, - "description": "What the cell digest hashes: every resolved value, the harness, the treatment, the catalog snapshots, the inputs and the plug-in environments of a run, each list sorted and without duplicates.", + "description": "What the cell digest hashes: every resolved value, the harness, the treatment, the catalog digests an imported run recorded, the inputs and the plug-in environments of a run, each list sorted and without duplicates.", "properties": { "environments": { "$comment": "Sorted by the text of the plug-in then the lock digest in code point order, without a repeated entry; the Rust reader refuses a list that is not.", @@ -26,7 +26,7 @@ }, "snapshots": { "$comment": "Sorted by kind then digest in code point order, without a repeated entry; the Rust reader refuses a list that is not.", - "description": "The digests of the catalog snapshots, sorted by kind and digest.", + "description": "The digests of the catalog snapshots an imported run recorded, sorted by kind and digest.\nThe key is absent for a run Candler made. It is present, possibly empty, only for an\nimported run: the manifest importer and the raw-stream importer write it, and the cell\nhashes with it when present and without it when absent.", "items": { "$ref": "#/$defs/DigestRef" }, @@ -49,7 +49,6 @@ "values", "harness", "treatment", - "snapshots", "inputs", "environments" ], @@ -98,7 +97,7 @@ }, "DigestRef": { "additionalProperties": false, - "description": "A digest and the kind of thing it identifies: a catalog snapshot or an input.", + "description": "A digest and the kind of thing it identifies: a catalog an imported run recorded, or an input.", "properties": { "digest": { "$ref": "#/$defs/Digest", @@ -385,7 +384,7 @@ "type": "string" }, "NameToken": { - "description": "A catalog provider reference, `name@token`, split at the last `@`: the name is non-empty and holds neither `@` nor white space, and the token matches `[0-9A-Za-z.+-]+`.", + "description": "A name and a version token, `name@token`, split at the last `@`: the name is non-empty and holds neither `@` nor white space, and the token matches `[0-9A-Za-z.+-]+`.", "pattern": "^[^@\\t\\n\\v\\f\\r\\x20\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+@[0-9A-Za-z.+-]+(?![\\s\\S])", "type": "string" }, @@ -743,7 +742,7 @@ "type": "array" }, "sources": { - "$comment": "Each path of `comparable.values` has exactly one entry, and each of `harness`, `treatment` and the non-empty lists `snapshots`, `inputs` and `environments` has an entry at the root path or at a path under it; no other path appears and no path repeats. JSON Schema cannot state this, and the Rust reader refuses a list that differs.", + "$comment": "Each path of `comparable.values` has exactly one entry, and each of `harness`, `treatment` and the non-empty lists `snapshots` (present only in an imported run), `inputs` and `environments` has an entry at the root path or at a path under it; no other path appears and no path repeats. JSON Schema cannot state this, and the Rust reader refuses a list that differs.", "description": "Where each value came from: one entry per value, and one or more entries under each typed root the cell holds; never an entry for a setting.", "items": { "$ref": "#/$defs/SourceEntry" diff --git a/crates/candler-schemas/src/catalog.rs b/crates/candler-schemas/src/catalog.rs deleted file mode 100644 index 394c385a..00000000 --- a/crates/candler-schemas/src/catalog.rs +++ /dev/null @@ -1,976 +0,0 @@ -//! The tool-catalog snapshot: the tools the MCP servers of a run offered, in the shape of MCP -//! `tools/list` results. -//! -//! A [`Tool`] keeps every key its server gave it: the named keys of the MCP `Tool` definition are -//! typed, and any other key is held as given. The document is read through -//! [`CatalogSnapshot`], which refuses any other version marker than [`SCHEMA_TAG`] and refuses an -//! explicit `null` for an optional field. Inside `inputSchema`, `outputSchema`, `annotations`, -//! `ext` and the extra keys of a tool, `null` is ordinary JSON data and is kept. -//! -//! Server names are non-empty and unique within a snapshot, and tool names are non-empty and unique -//! within a server. Names are compared byte for byte: they are case-sensitive and are not -//! Unicode-normalised. The schema states that names are non-empty; uniqueness is enforced when a -//! snapshot is built or read. -//! -//! The reader keeps every key of a tool, `ext` and `environment`, and every value, with these -//! exceptions. Keys not defined for a snapshot or a server are dropped. Of repeated keys the last -//! is kept. Object keys are sorted, so the order in which they were written is not kept. A number -//! is held as `i64`, `u64` or `f64`: an integer beyond both becomes a float, a decimal beyond -//! `f64` precision is rounded, and a number whose magnitude is above the range of `f64` is -//! refused. Text nested deeper than about 120 levels is refused by the text readers. - -use std::borrow::Cow; -use std::collections::BTreeMap; - -use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; -use serde::de::Error as _; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use serde_json::{Map, Value}; - -use crate::canonical::CanonicalError; -use crate::distinct::first_repeat; -use crate::map_only::MapOnly; -use crate::primitives::{Digest, NameToken, RelPath, Timestamp, object_only}; - -/// The version marker every snapshot carries in its `schema` field. -pub const SCHEMA_TAG: &str = "tool-catalog-snapshot/1"; - -/// The keys of a [`Tool`] that are fields rather than extra keys. -const NAMED_TOOL_KEYS: [&str; 6] = [ - "name", - "title", - "description", - "inputSchema", - "outputSchema", - "annotations", -]; - -/// Why a snapshot or one of its members could not be built or read. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[non_exhaustive] -pub enum CatalogError { - /// A `schema` field that is not [`SCHEMA_TAG`]. - #[error("schema tag differs from `{SCHEMA_TAG}` (got {value:?})")] - SchemaTag { - /// The text the field held. - value: String, - }, - /// A builder that was asked to build before a required field was set. - #[error("snapshot field is missing (`{field}` was not set)")] - MissingField { - /// The name of the field. - field: &'static str, - }, - /// An extra key of a tool that is the name of one of its fields. - #[error("tool extra key names a field of the tool (got {key:?})")] - ReservedKey { - /// The key. - key: String, - }, - /// An optional field that was written as `null` instead of being omitted. - #[error("optional field is null (an absent field is omitted)")] - Null, - /// A server or tool name that is empty. - #[error("{owner} name is empty (names have at least one character)")] - EmptyName { - /// What the name belongs to: `server` or `tool`. - owner: &'static str, - }, - /// A server or tool name that another member of the same scope already has. - #[error("{owner} name is repeated within a {scope} (got {name:?})")] - DuplicateName { - /// What the name belongs to: `server` or `tool`. - owner: &'static str, - /// What the names are unique within: `snapshot` or `server`. - scope: &'static str, - /// The repeated name. - name: String, - }, -} - -/// Refuses an empty name. -fn non_empty(name: String, owner: &'static str) -> Result<String, CatalogError> { - if name.is_empty() { - Err(CatalogError::EmptyName { owner }) - } else { - Ok(name) - } -} - -fn distinct_tools(tools: &[Tool]) -> Result<(), CatalogError> { - match first_repeat(tools.iter().map(Tool::name)) { - Some(name) => Err(CatalogError::DuplicateName { - owner: "tool", - scope: "server", - name: String::from(name), - }), - None => Ok(()), - } -} - -fn distinct_servers(servers: &[CatalogServer]) -> Result<(), CatalogError> { - match first_repeat(servers.iter().map(CatalogServer::name)) { - Some(name) => Err(CatalogError::DuplicateName { - owner: "server", - scope: "snapshot", - name: String::from(name), - }), - None => Ok(()), - } -} - -/// Reads a tool name, refusing an empty one. -fn tool_name<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> { - non_empty(String::deserialize(deserializer)?, "tool").map_err(D::Error::custom) -} - -/// Reads a server name, refusing an empty one. -fn server_name<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> { - non_empty(String::deserialize(deserializer)?, "server").map_err(D::Error::custom) -} - -/// Reads the tools of a server, refusing a repeated name. -fn distinct_tools_of<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Tool>, D::Error> { - let tools = Vec::<Tool>::deserialize(deserializer)?; - distinct_tools(&tools).map_err(D::Error::custom)?; - Ok(tools) -} - -/// Reads an optional field, refusing an explicit `null`. -/// -/// Used with `#[serde(default)]`, so that an absent field is `None` and a present one is `Some`. -fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error> -where - D: Deserializer<'de>, - T: Deserialize<'de>, -{ - match Option::<T>::deserialize(deserializer)? { - Some(value) => Ok(Some(value)), - None => Err(D::Error::custom(CatalogError::Null)), - } -} - -/// The constant `schema` field of a snapshot. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct SchemaTag; - -impl Serialize for SchemaTag { - fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { - serializer.serialize_str(SCHEMA_TAG) - } -} - -impl JsonSchema for SchemaTag { - fn schema_name() -> Cow<'static, str> { - "SchemaTag".into() - } - - fn inline_schema() -> bool { - true - } - - fn json_schema(_generator: &mut SchemaGenerator) -> Schema { - json_schema!({ - "type": "string", - "const": SCHEMA_TAG, - }) - } -} - -/// How a client reaches an MCP server. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all = "lowercase")] -#[non_exhaustive] -pub enum Transport { - /// The server runs as a subprocess and is spoken to over its standard input and output. - Stdio, - /// The server is reached over streamable HTTP. - Http, - /// The server is reached over server-sent events. - Sse, -} - -/// A tool in MCP `tools/list` shape: the named keys of the MCP `Tool` definition, and every other key as the server gave it. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all = "camelCase")] -#[schemars(extend("additionalProperties" = true))] -#[non_exhaustive] -pub struct Tool { - /// The name of the tool, as the server gave it: at least one character, and unique among the tools of its server. - #[serde(deserialize_with = "tool_name")] - #[schemars(length(min = 1))] - name: String, - /// A human-readable title of the tool. - #[serde( - default, - deserialize_with = "present", - skip_serializing_if = "Option::is_none" - )] - title: Option<String>, - /// A human-readable description of the tool. - #[serde( - default, - deserialize_with = "present", - skip_serializing_if = "Option::is_none" - )] - description: Option<String>, - /// The JSON Schema object that describes the arguments of the tool. Its `type` is not required to be `object`. - input_schema: Map<String, Value>, - /// The JSON Schema object that describes the structured output of the tool. - #[serde( - default, - deserialize_with = "present", - skip_serializing_if = "Option::is_none" - )] - output_schema: Option<Map<String, Value>>, - /// Hints about the behaviour of the tool: an open object whose keys are kept as given. - #[serde( - default, - deserialize_with = "present", - skip_serializing_if = "Option::is_none" - )] - annotations: Option<Map<String, Value>>, - // Every key that is not named above, as given. - #[serde(flatten)] - extra: Map<String, Value>, -} - -impl Tool { - /// Builds a tool with the two keys MCP requires. - /// - /// # Errors - /// Returns [`CatalogError::EmptyName`] if `name` is empty. - pub fn new(name: String, input_schema: Map<String, Value>) -> Result<Self, CatalogError> { - Ok(Self { - name: non_empty(name, "tool")?, - title: None, - description: None, - input_schema, - output_schema: None, - annotations: None, - extra: Map::new(), - }) - } - - /// Sets the human-readable title. - #[must_use] - pub fn with_title(mut self, title: String) -> Self { - self.title = Some(title); - self - } - - /// Sets the human-readable description. - #[must_use] - pub fn with_description(mut self, description: String) -> Self { - self.description = Some(description); - self - } - - /// Sets the JSON Schema object of the structured output. - #[must_use] - pub fn with_output_schema(mut self, output_schema: Map<String, Value>) -> Self { - self.output_schema = Some(output_schema); - self - } - - /// Sets the annotations. - #[must_use] - pub fn with_annotations(mut self, annotations: Map<String, Value>) -> Self { - self.annotations = Some(annotations); - self - } - - /// Adds a key the tool keeps as given, replacing an earlier value of the same key. - /// - /// # Errors - /// Returns [`CatalogError::ReservedKey`] if `key` is the name of a field of the tool. - pub fn with_extra(mut self, key: String, value: Value) -> Result<Self, CatalogError> { - // BORROW: explicit .as_str() to match the key against the field names - if NAMED_TOOL_KEYS.contains(&key.as_str()) { - return Err(CatalogError::ReservedKey { key }); - } - self.extra.insert(key, value); - Ok(self) - } - - /// The name of the tool. - #[must_use] - pub const fn name<'a>(&'a self) -> &'a str { - // BORROW: explicit .as_str() instead of Deref coercion - self.name.as_str() - } - - /// The human-readable title, if the server gave one. - #[must_use] - pub fn title<'a>(&'a self) -> Option<&'a str> { - // BORROW: explicit .as_deref() instead of Deref coercion - self.title.as_deref() - } - - /// The human-readable description, if the server gave one. - #[must_use] - pub fn description<'a>(&'a self) -> Option<&'a str> { - // BORROW: explicit .as_deref() instead of Deref coercion - self.description.as_deref() - } - - /// The JSON Schema object that describes the arguments. - #[must_use] - pub const fn input_schema<'a>(&'a self) -> &'a Map<String, Value> { - &self.input_schema - } - - /// The JSON Schema object that describes the structured output, if the server gave one. - #[must_use] - pub const fn output_schema<'a>(&'a self) -> Option<&'a Map<String, Value>> { - self.output_schema.as_ref() - } - - /// The annotations, if the server gave any. - #[must_use] - pub const fn annotations<'a>(&'a self) -> Option<&'a Map<String, Value>> { - self.annotations.as_ref() - } - - /// The keys that are not fields of the tool, as the server gave them. - #[must_use] - pub const fn extra<'a>(&'a self) -> &'a Map<String, Value> { - &self.extra - } -} - -/// One MCP server of a run and the tools it offered. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] -#[serde(remote = "Self")] -#[schemars(deny_unknown_fields)] -#[non_exhaustive] -pub struct CatalogServer { - /// The name of the server: at least one character, and unique among the servers of its snapshot. - #[serde(deserialize_with = "server_name")] - #[schemars(length(min = 1))] - name: String, - /// The path of the server's source file: a POSIX path relative to the project root. - source_path: RelPath, - /// The digest of the server's source file. - source_digest: Digest, - /// How a client reaches the server. - transport: Transport, - /// The tools the server offered, with names unique among them. - #[serde(deserialize_with = "distinct_tools_of")] - #[schemars(extend( - "$comment" = "Tool names are unique within the array, compared byte for byte (case-sensitive, without Unicode normalisation); JSON Schema cannot state this, and the Rust reader refuses a repeated name." - ))] - tools: Vec<Tool>, -} - -object_only!(CatalogServer); - -impl CatalogServer { - /// Builds a server entry. - /// - /// # Errors - /// Returns [`CatalogError::EmptyName`] if `name` is empty. - /// Returns [`CatalogError::DuplicateName`] if two of the tools have the same name. - pub fn new( - name: String, - source_path: RelPath, - source_digest: Digest, - transport: Transport, - tools: Vec<Tool>, - ) -> Result<Self, CatalogError> { - distinct_tools(&tools)?; - Ok(Self { - name: non_empty(name, "server")?, - source_path, - source_digest, - transport, - tools, - }) - } - - /// The name of the server. - #[must_use] - pub const fn name<'a>(&'a self) -> &'a str { - // BORROW: explicit .as_str() instead of Deref coercion - self.name.as_str() - } - - /// The path of the server's source file. - #[must_use] - pub const fn source_path<'a>(&'a self) -> &'a RelPath { - &self.source_path - } - - /// The digest of the server's source file. - #[must_use] - pub const fn source_digest<'a>(&'a self) -> &'a Digest { - &self.source_digest - } - - /// How a client reaches the server. - #[must_use] - pub const fn transport(&self) -> Transport { - self.transport - } - - /// The tools the server offered. - #[must_use] - pub const fn tools<'a>(&'a self) -> &'a [Tool] { - // BORROW: explicit .as_slice() instead of Deref coercion - self.tools.as_slice() - } -} - -/// What the MCP servers targeted by a run offered: for each server, its tools in the shape of an MCP `tools/list` result. -#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] -#[schemars(deny_unknown_fields)] -#[non_exhaustive] -pub struct CatalogSnapshot { - /// The version marker of the document: always `tool-catalog-snapshot/1`. - schema: SchemaTag, - /// When the snapshot was captured. - captured_at: Timestamp, - /// The catalog provider that captured the snapshot, as `name@token`. - provider: NameToken, - /// The versions the capture depended on, as an object from a name to its version text. - #[serde(skip_serializing_if = "Option::is_none")] - environment: Option<BTreeMap<String, String>>, - /// Provider-specific data: an open JSON object that Candler does not interpret. - #[serde(skip_serializing_if = "Option::is_none")] - ext: Option<Map<String, Value>>, - /// The servers the run targeted, each with the tools it offered, with names unique among them. - #[schemars(extend( - "$comment" = "Server names are unique within the array, compared byte for byte (case-sensitive, without Unicode normalisation); JSON Schema cannot state this, and the Rust reader refuses a repeated name." - ))] - servers: Vec<CatalogServer>, -} - -impl CatalogSnapshot { - /// Starts a snapshot; `captured_at` and `provider` must be set before it builds. - #[must_use] - pub fn builder() -> CatalogSnapshotBuilder { - CatalogSnapshotBuilder::default() - } - - /// When the snapshot was captured. - #[must_use] - pub const fn captured_at<'a>(&'a self) -> &'a Timestamp { - &self.captured_at - } - - /// The catalog provider that captured the snapshot. - #[must_use] - pub const fn provider<'a>(&'a self) -> &'a NameToken { - &self.provider - } - - /// The versions the capture depended on, if any were recorded. - #[must_use] - pub const fn environment<'a>(&'a self) -> Option<&'a BTreeMap<String, String>> { - self.environment.as_ref() - } - - /// The provider-specific data, if the provider wrote any. - #[must_use] - pub const fn ext<'a>(&'a self) -> Option<&'a Map<String, Value>> { - self.ext.as_ref() - } - - /// The servers the run targeted. - #[must_use] - pub const fn servers<'a>(&'a self) -> &'a [CatalogServer] { - // BORROW: explicit .as_slice() instead of Deref coercion - self.servers.as_slice() - } - - /// The digest of the snapshot's content: `sha256` of the RFC 8785 form of the snapshot - /// without `captured_at`, so that a capture time never splits a cell. - /// - /// # Errors - /// Returns the [`CanonicalError`] of [`Digest::of_canonical`] if the snapshot has no canonical - /// form, which an integer outside ±(2^53 − 1) in `ext` causes: the snapshot reader does not - /// check numbers. - pub fn content_digest(&self) -> Result<Digest, CanonicalError> { - let mut json = serde_json::to_value(self).map_err(|e| CanonicalError::Syntax { - detail: e.to_string(), - })?; - if let Value::Object(fields) = &mut json { - fields.remove("captured_at"); - } - Digest::of_canonical(&json) - } -} - -/// The fields of a snapshot as written, before the version marker is checked. -#[derive(Deserialize)] -struct CatalogSnapshotWire { - schema: String, - captured_at: Timestamp, - provider: NameToken, - #[serde(default, deserialize_with = "present")] - environment: Option<BTreeMap<String, String>>, - #[serde(default, deserialize_with = "present")] - ext: Option<Map<String, Value>>, - servers: Vec<CatalogServer>, -} - -impl TryFrom<CatalogSnapshotWire> for CatalogSnapshot { - type Error = CatalogError; - - fn try_from(wire: CatalogSnapshotWire) -> Result<Self, Self::Error> { - // BORROW: explicit .as_str() to compare with the tag - if wire.schema.as_str() != SCHEMA_TAG { - return Err(CatalogError::SchemaTag { value: wire.schema }); - } - distinct_servers(&wire.servers)?; - Ok(Self { - schema: SchemaTag, - captured_at: wire.captured_at, - provider: wire.provider, - environment: wire.environment, - ext: wire.ext, - servers: wire.servers, - }) - } -} - -impl<'de> Deserialize<'de> for CatalogSnapshot { - fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { - let MapOnly(wire) = MapOnly::<CatalogSnapshotWire>::deserialize(deserializer)?; - Self::try_from(wire).map_err(D::Error::custom) - } -} - -/// Builds a [`CatalogSnapshot`]. -#[derive(Debug, Clone, Default)] -#[non_exhaustive] -pub struct CatalogSnapshotBuilder { - captured_at: Option<Timestamp>, - provider: Option<NameToken>, - environment: Option<BTreeMap<String, String>>, - ext: Option<Map<String, Value>>, - servers: Vec<CatalogServer>, -} - -impl CatalogSnapshotBuilder { - /// Sets when the snapshot was captured. - #[must_use] - pub fn captured_at(mut self, captured_at: Timestamp) -> Self { - self.captured_at = Some(captured_at); - self - } - - /// Sets the catalog provider. - #[must_use] - pub fn provider(mut self, provider: NameToken) -> Self { - self.provider = Some(provider); - self - } - - /// Sets the versions the capture depended on. - #[must_use] - pub fn environment(mut self, environment: BTreeMap<String, String>) -> Self { - self.environment = Some(environment); - self - } - - /// Sets the provider-specific data. - #[must_use] - pub fn ext(mut self, ext: Map<String, Value>) -> Self { - self.ext = Some(ext); - self - } - - /// Appends a server. - #[must_use] - pub fn server(mut self, server: CatalogServer) -> Self { - self.servers.push(server); - self - } - - /// Builds the snapshot. - /// - /// # Errors - /// Returns [`CatalogError::MissingField`] if `captured_at` or `provider` was not set. - /// Returns [`CatalogError::DuplicateName`] if two of the servers have the same name. - pub fn build(self) -> Result<CatalogSnapshot, CatalogError> { - let captured_at = self.captured_at.ok_or(CatalogError::MissingField { - field: "captured_at", - })?; - let provider = self - .provider - .ok_or(CatalogError::MissingField { field: "provider" })?; - distinct_servers(&self.servers)?; - Ok(CatalogSnapshot { - schema: SchemaTag, - captured_at, - provider, - environment: self.environment, - ext: self.ext, - servers: self.servers, - }) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - fn tool_value() -> Value { - json!({ - "name": "t", - "title": "T", - "description": "d", - "inputSchema": {"type": "object"}, - "outputSchema": {"type": "object"}, - "annotations": {"readOnlyHint": true}, - "icons": [], - "_meta": {"k": null}, - }) - } - - fn tool(name: &str) -> Tool { - Tool::new(String::from(name), Map::new()).expect("a tool with a name") - } - - fn server(name: &str, tools: Vec<Tool>) -> Result<CatalogServer, CatalogError> { - CatalogServer::new( - String::from(name), - "a/b.py".parse().expect("path"), - Digest::from_hex(&"ab".repeat(32)).expect("digest"), - Transport::Stdio, - tools, - ) - } - - fn snapshot_value() -> Value { - json!({ - "schema": SCHEMA_TAG, - "captured_at": "2026-10-28T01:09:04+00:00", - "provider": "p/q@1", - "servers": [{ - "name": "s", - "source_path": "a/b.py", - "source_digest": format!("sha256:{}", "ab".repeat(32)), - "transport": "stdio", - "tools": [tool_value()], - }], - }) - } - - /// Guards: R01 §Wire encodings — a tool, a server and a snapshot are objects and never a list - /// of their values, at each level. Oracle: the object form of each is read first, then the - /// list of its values is refused. Bite: dropping `object_only!` or `MapOnly` turns the - /// server and snapshot rows red. - #[test] - fn a_struct_written_as_a_list_is_refused_at_each_level() { - // The values of `value` in the order `fields` names them, an absent field being `{}`; a - // derived reader that took a list would take it in this order. - fn listed(value: &Value, fields: &[&str]) -> Value { - Value::Array( - fields - .iter() - .map(|field| value.get(*field).cloned().unwrap_or_else(|| json!({}))) - .collect(), - ) - } - const SERVER: [&str; 5] = ["name", "source_path", "source_digest", "transport", "tools"]; - const SNAPSHOT: [&str; 6] = [ - "schema", - "captured_at", - "provider", - "environment", - "ext", - "servers", - ]; - - let tool = tool_value(); - serde_json::from_value::<Tool>(tool.clone()).expect("a tool object reads"); - assert!( - serde_json::from_value::<Tool>(Value::Array( - tool.as_object() - .expect("an object") - .values() - .cloned() - .collect() - )) - .is_err(), - "a tool as a list" - ); - - let snapshot = snapshot_value(); - let server_object = snapshot["servers"][0].clone(); - serde_json::from_value::<CatalogServer>(server_object.clone()) - .expect("a server object reads"); - assert!( - serde_json::from_value::<CatalogServer>(listed(&server_object, &SERVER)).is_err(), - "a server as a list" - ); - - serde_json::from_value::<CatalogSnapshot>(snapshot.clone()) - .expect("a snapshot object reads"); - assert!( - serde_json::from_value::<CatalogSnapshot>(listed(&snapshot, &SNAPSHOT)).is_err(), - "a snapshot as a list" - ); - - let mut nested = snapshot; - nested["servers"][0] = listed(&server_object, &SERVER); - assert!( - serde_json::from_value::<CatalogSnapshot>(nested).is_err(), - "a server written as a list inside a snapshot" - ); - - let probe = json!([ - "tool-catalog-snapshot/1", - "2026-01-01T00:00:00Z", - "p@1", - {}, - {}, - [] - ]); - assert!( - serde_json::from_value::<CatalogSnapshot>(probe).is_err(), - "the probe snapshot as a list" - ); - } - - #[test] - fn named_keys_are_exactly_the_fields_a_full_tool_writes() { - let tool: Tool = serde_json::from_value(tool_value()).expect("a full tool reads"); - let written = serde_json::to_value(&tool).expect("a tool writes"); - let mut named: Vec<&str> = written - .as_object() - .expect("a tool is an object") - .keys() - // BORROW: explicit .as_str() to compare with the named keys - .map(String::as_str) - .filter(|key| !tool.extra().contains_key(*key)) - .collect(); - named.sort_unstable(); - let mut expected = NAMED_TOOL_KEYS.to_vec(); - expected.sort_unstable(); - assert_eq!(named, expected); - assert_eq!(tool.extra().len(), 2); - } - - #[test] - fn a_tool_keeps_null_inside_its_values_and_extra_keys() { - let value = json!({ - "name": "t", - "inputSchema": {"default": null, "properties": {"a": {"enum": [null, 1]}}}, - "annotations": {"title": null}, - "outputSchema": {"const": null}, - "x": null, - }); - let tool: Tool = serde_json::from_value(value.clone()).expect("null is data here"); - assert_eq!(serde_json::to_value(&tool).expect("writes"), value); - assert_eq!(tool.extra().get("x"), Some(&Value::Null)); - } - - #[test] - fn a_tool_refuses_null_for_its_optional_fields() { - for key in ["title", "description", "outputSchema", "annotations"] { - let mut value = tool_value(); - value[key] = Value::Null; - let error = serde_json::from_value::<Tool>(value).expect_err(key); - assert!( - error.to_string().contains("optional field is null"), - "{key}" - ); - } - } - - #[test] - fn a_tool_without_its_required_keys_is_refused() { - for key in ["name", "inputSchema"] { - let mut value = tool_value(); - value.as_object_mut().expect("object").remove(key); - assert!(serde_json::from_value::<Tool>(value).is_err(), "{key}"); - } - let mut value = tool_value(); - value["inputSchema"] = json!("object"); - assert!(serde_json::from_value::<Tool>(value).is_err()); - } - - #[test] - fn an_extra_key_cannot_take_the_name_of_a_field() { - for key in NAMED_TOOL_KEYS { - let result = tool("t").with_extra(String::from(key), json!(1)); - assert_eq!( - result.expect_err(key), - CatalogError::ReservedKey { - key: String::from(key) - } - ); - } - let tool = tool("t") - .with_extra(String::from("icons"), json!([])) - .expect("icons is an extra key"); - assert_eq!(tool.extra().len(), 1); - } - - #[test] - fn a_snapshot_refuses_a_foreign_tag_and_null_optionals() { - let snapshot: CatalogSnapshot = - serde_json::from_value(snapshot_value()).expect("a snapshot reads"); - assert_eq!(snapshot.servers().len(), 1); - - let mut value = snapshot_value(); - value["schema"] = json!("tool-catalog-snapshot/0"); - let error = serde_json::from_value::<CatalogSnapshot>(value).expect_err("tag"); - assert!(error.to_string().contains("schema tag differs")); - - for key in ["environment", "ext"] { - let mut value = snapshot_value(); - value[key] = Value::Null; - let error = serde_json::from_value::<CatalogSnapshot>(value).expect_err(key); - assert!( - error.to_string().contains("optional field is null"), - "{key}" - ); - } - } - - #[test] - fn the_builder_requires_the_capture_time_and_the_provider() { - let timestamp: Timestamp = "2026-10-28T01:09:04Z".parse().expect("timestamp"); - let provider: NameToken = "p@1".parse().expect("provider"); - assert_eq!( - CatalogSnapshot::builder() - .provider(provider.clone()) - .build() - .expect_err("no time"), - CatalogError::MissingField { - field: "captured_at" - } - ); - assert_eq!( - CatalogSnapshot::builder() - .captured_at(timestamp.clone()) - .build() - .expect_err("no provider"), - CatalogError::MissingField { field: "provider" } - ); - let built = CatalogSnapshot::builder() - .captured_at(timestamp) - .provider(provider) - .build() - .expect("minimal snapshot builds"); - assert_eq!(built.servers(), []); - assert_eq!( - serde_json::to_value(&built).expect("writes"), - json!({ - "schema": SCHEMA_TAG, - "captured_at": "2026-10-28T01:09:04Z", - "provider": "p@1", - "servers": [], - }) - ); - } - - #[test] - fn names_are_non_empty_and_unique_within_their_scope() { - assert_eq!( - Tool::new(String::new(), Map::new()).expect_err("empty tool name"), - CatalogError::EmptyName { owner: "tool" } - ); - assert_eq!( - server("", Vec::new()).expect_err("empty server name"), - CatalogError::EmptyName { owner: "server" } - ); - assert_eq!( - server("s", vec![tool("a"), tool("b"), tool("a")]).expect_err("repeated tool"), - CatalogError::DuplicateName { - owner: "tool", - scope: "server", - name: String::from("a") - } - ); - let timestamp: Timestamp = "2026-10-28T01:09:04Z".parse().expect("timestamp"); - let provider: NameToken = "p@1".parse().expect("provider"); - let repeated = CatalogSnapshot::builder() - .captured_at(timestamp) - .provider(provider) - .server(server("s", vec![tool("a")]).expect("server")) - .server(server("s", vec![tool("b")]).expect("server")) - .build() - .expect_err("repeated server"); - assert_eq!( - repeated, - CatalogError::DuplicateName { - owner: "server", - scope: "snapshot", - name: String::from("s") - } - ); - // The same name in different scopes is allowed. - server("s", vec![tool("a")]).expect("tool names repeat across servers"); - } - - #[test] - fn the_reader_refuses_empty_and_repeated_names() { - let mut empty_tool = tool_value(); - empty_tool["name"] = json!(""); - assert!(serde_json::from_value::<Tool>(empty_tool).is_err()); - - let mut value = snapshot_value(); - value["servers"][0]["name"] = json!(""); - let error = serde_json::from_value::<CatalogSnapshot>(value).expect_err("empty server"); - assert!(error.to_string().contains("server name is empty")); - - let mut value = snapshot_value(); - value["servers"][0]["tools"] = json!([tool_value(), tool_value()]); - let error = serde_json::from_value::<CatalogSnapshot>(value).expect_err("repeated tool"); - assert!(error.to_string().contains("tool name is repeated")); - - let mut value = snapshot_value(); - let first = value["servers"][0].clone(); - value["servers"] = json!([first.clone(), first]); - let error = serde_json::from_value::<CatalogSnapshot>(value).expect_err("repeated server"); - assert!(error.to_string().contains("server name is repeated")); - } - - #[test] - fn every_error_has_its_wording() { - let cases = [ - ( - CatalogError::SchemaTag { - value: String::from("x/1"), - }, - r#"schema tag differs from `tool-catalog-snapshot/1` (got "x/1")"#, - ), - ( - CatalogError::MissingField { field: "provider" }, - "snapshot field is missing (`provider` was not set)", - ), - ( - CatalogError::ReservedKey { - key: String::from("name"), - }, - r#"tool extra key names a field of the tool (got "name")"#, - ), - ( - CatalogError::Null, - "optional field is null (an absent field is omitted)", - ), - ( - CatalogError::EmptyName { owner: "server" }, - "server name is empty (names have at least one character)", - ), - ( - CatalogError::DuplicateName { - owner: "tool", - scope: "server", - name: String::from("a"), - }, - r#"tool name is repeated within a server (got "a")"#, - ), - ]; - for (error, text) in cases { - assert_eq!(error.to_string(), text); - } - } -} diff --git a/crates/candler-schemas/src/evaluation.rs b/crates/candler-schemas/src/evaluation.rs index 5ce0b9e5..609dfe2f 100644 --- a/crates/candler-schemas/src/evaluation.rs +++ b/crates/candler-schemas/src/evaluation.rs @@ -1342,7 +1342,9 @@ pub struct Needs { pub trace: bool, /// Globs, relative to the run, of the artifacts the check reads. pub artifacts: Vec<String>, - /// The kinds of snapshot the check reads. + /// The kinds of snapshot the check reads. Always empty for a run Candler made; the field is + /// kept so a released helper and stored grading contexts stay valid, and it is removed once a + /// helper that treats it as optional is released. pub snapshots: Vec<Name>, /// The kinds of input the check reads. pub inputs: Vec<Name>, @@ -1611,7 +1613,9 @@ struct RawRunContext { raw: Vec<ContextRaw>, /// The artifacts of the run. artifacts: Vec<ContextArtifact>, - /// The snapshots the run was made against. + /// The snapshots the run was made against. Always empty for a run Candler made; the field is + /// kept so a released helper and stored grading contexts stay valid, and it is removed once a + /// helper that treats it as optional is released. snapshots: Vec<ContextRef>, /// The inputs the run was made from. inputs: Vec<ContextRef>, diff --git a/crates/candler-schemas/src/execution.rs b/crates/candler-schemas/src/execution.rs index 954edb6d..9b4f11bf 100644 --- a/crates/candler-schemas/src/execution.rs +++ b/crates/candler-schemas/src/execution.rs @@ -132,6 +132,9 @@ pub enum ExecutionError { /// The name of the field. field: &'static str, }, + /// A `replicates` value that is not a whole number from 1 to 4294967295. + #[error("`replicates` must be a whole number from 1 to 4294967295")] + ReplicatesNotCount, /// A factor with no level, which would leave the experiment with no cell. #[error("factor `{factor}` has no level")] NoLevels { @@ -1102,17 +1105,15 @@ struct Plan { /// The replicates `count` stands for: at least 1 and at most [`u32::MAX`]. /// /// # Errors -/// [`ExecutionError::Zero`] when `count` is 0, and [`ExecutionError::NotPositive`] when it does -/// not fit in 32 bits. +/// [`ExecutionError::Zero`] when `count` is 0, and [`ExecutionError::ReplicatesNotCount`] when it +/// does not fit in 32 bits. pub fn check_replicates(count: u64) -> Result<u32, ExecutionError> { match u32::try_from(count) { Ok(0) => Err(ExecutionError::Zero { field: "replicates", }), Ok(replicates) => Ok(replicates), - Err(_) => Err(ExecutionError::NotPositive { - field: "replicates", - }), + Err(_) => Err(ExecutionError::ReplicatesNotCount), } } @@ -1818,7 +1819,7 @@ impl HarnessIdentity { } } -/// A digest and the kind of thing it identifies: a catalog snapshot or an input. +/// A digest and the kind of thing it identifies: a catalog an imported run recorded, or an input. #[derive( Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, )] @@ -1882,7 +1883,8 @@ struct ComparableBody<'a> { values: &'a [ResolvedValue], harness: &'a HarnessIdentity, treatment: &'a TreatmentRef, - snapshots: &'a [DigestRef], + #[serde(skip_serializing_if = "Option::is_none")] + snapshots: Option<&'a [DigestRef]>, inputs: &'a [DigestRef], environments: &'a [EnvironmentRef], } @@ -1920,7 +1922,7 @@ fn environment_order(first: &EnvironmentRef, second: &EnvironmentRef) -> std::cm .then_with(|| first.lock_digest.cmp(&second.lock_digest)) } -/// What the cell digest hashes: every resolved value, the harness, the treatment, the catalog snapshots, the inputs and the plug-in environments of a run, each list sorted and without duplicates. +/// What the cell digest hashes: every resolved value, the harness, the treatment, the catalog digests an imported run recorded, the inputs and the plug-in environments of a run, each list sorted and without duplicates. #[derive(Deserialize, JsonSchema)] #[schemars(deny_unknown_fields, rename = "Comparable")] struct RawComparable { @@ -1933,11 +1935,15 @@ struct RawComparable { harness: HarnessIdentity, /// The treatment the run applied. treatment: TreatmentRef, - /// The digests of the catalog snapshots, sorted by kind and digest. + /// The digests of the catalog snapshots an imported run recorded, sorted by kind and digest. + /// The key is absent for a run Candler made. It is present, possibly empty, only for an + /// imported run: the manifest importer and the raw-stream importer write it, and the cell + /// hashes with it when present and without it when absent. + #[serde(default, deserialize_with = "present")] #[schemars(extend( "$comment" = "Sorted by kind then digest in code point order, without a repeated entry; the Rust reader refuses a list that is not." ))] - snapshots: Vec<DigestRef>, + snapshots: Option<Vec<DigestRef>>, /// The digests of the inputs, sorted by kind and digest. #[schemars(extend( "$comment" = "Sorted by kind then digest in code point order, without a repeated entry; the Rust reader refuses a list that is not." @@ -1966,7 +1972,7 @@ impl TryFrom<MapOnly<RawComparable>> for Comparable { } } -/// What the cell digest hashes: every resolved value, the harness, the treatment, the catalog snapshots, the inputs and the plug-in environments of a run, each list sorted and without duplicates. +/// What the cell digest hashes: every resolved value, the harness, the treatment, the catalog digests an imported run recorded, the inputs and the plug-in environments of a run, each list sorted and without duplicates. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(try_from = "MapOnly<RawComparable>")] #[non_exhaustive] @@ -1974,7 +1980,8 @@ pub struct Comparable { values: Vec<ResolvedValue>, harness: HarnessIdentity, treatment: TreatmentRef, - snapshots: Vec<DigestRef>, + #[serde(skip_serializing_if = "Option::is_none")] + snapshots: Option<Vec<DigestRef>>, inputs: Vec<DigestRef>, environments: Vec<EnvironmentRef>, #[serde(skip)] @@ -1994,7 +2001,7 @@ impl Comparable { values: Vec<ResolvedValue>, harness: HarnessIdentity, treatment: TreatmentRef, - snapshots: Vec<DigestRef>, + snapshots: Option<Vec<DigestRef>>, inputs: Vec<DigestRef>, environments: Vec<EnvironmentRef>, ) -> Result<Self, ExecutionError> { @@ -2006,12 +2013,14 @@ impl Comparable { ResolvedValue::path, |value| value.path().to_string(), )?; - for (list, items) in [("snapshots", &snapshots), ("inputs", &inputs)] { + for (list, items) in [ + ("snapshots", snapshots.as_deref().unwrap_or_default()), + ("inputs", inputs.as_slice()), + ] { check_ascending( list, "kind and digest", - // BORROW: explicit .as_slice() instead of Deref coercion - items.as_slice(), + items, |entry| (entry.kind.as_str(), entry.digest.as_str()), |entry| entry.digest.to_string(), )?; @@ -2029,7 +2038,8 @@ impl Comparable { values: values.as_slice(), harness: &harness, treatment: &treatment, - snapshots: snapshots.as_slice(), + // BORROW: explicit .as_deref() instead of Deref coercion + snapshots: snapshots.as_deref(), // BORROW: explicit .as_slice() instead of Deref coercion inputs: inputs.as_slice(), // BORROW: explicit .as_slice() instead of Deref coercion @@ -2052,8 +2062,8 @@ impl Comparable { /// Builds a cell from resolved values. /// - /// The path `harness` fills the harness, `treatment` the treatment, `snapshots` the snapshot - /// digests, `inputs` the input digests and `environments` the plug-in environments; each + /// The path `harness` fills the harness, `treatment` the treatment, `snapshots` the catalog + /// digests of an imported run (no run Candler makes sets it), `inputs` the input digests and `environments` the plug-in environments; each /// takes one value, read as the typed field reads. Every other path goes to `values`, and a /// path below one of the five roots is refused. A settings path is not a value and never /// reaches this function. @@ -2181,11 +2191,11 @@ impl Comparable { &self.treatment } - /// The catalog snapshot digests, sorted. + /// The catalog digests an imported run recorded, sorted. #[must_use] pub fn snapshots<'a>(&'a self) -> &'a [DigestRef] { - // BORROW: explicit .as_slice() instead of Deref coercion - self.snapshots.as_slice() + // BORROW: explicit .as_deref() instead of Deref coercion + self.snapshots.as_deref().unwrap_or_default() } /// The input digests, sorted. @@ -2238,7 +2248,7 @@ pub struct ComparableBuilder { values: Vec<ResolvedValue>, harness: Option<HarnessIdentity>, treatment: Option<TreatmentRef>, - snapshots: Vec<DigestRef>, + snapshots: Option<Vec<DigestRef>>, inputs: Vec<DigestRef>, environments: Vec<EnvironmentRef>, } @@ -2265,10 +2275,11 @@ impl ComparableBuilder { self } - /// Adds a catalog snapshot digest. + /// Sets the catalog digests an imported run recorded, even when the list is empty; a cell + /// without this call carries no `snapshots` key. #[must_use] - pub fn snapshot(mut self, snapshot: DigestRef) -> Self { - self.snapshots.push(snapshot); + pub fn snapshots(mut self, snapshots: Vec<DigestRef>) -> Self { + self.snapshots = Some(snapshots); self } @@ -2297,7 +2308,7 @@ impl ComparableBuilder { "treatment" => self.treatment = Some(serde_json::from_value(json).map_err(malformed)?), "snapshots" => { // The list is read as written; `build` sorts and refuses a duplicate. - self.snapshots = serde_json::from_value(json).map_err(malformed)?; + self.snapshots = Some(serde_json::from_value(json).map_err(malformed)?); } "inputs" => self.inputs = serde_json::from_value(json).map_err(malformed)?, "environments" => { @@ -2332,7 +2343,9 @@ impl ComparableBuilder { let harness = harness.ok_or(ExecutionError::MissingField { field: "harness" })?; let treatment = treatment.ok_or(ExecutionError::MissingField { field: "treatment" })?; values.sort_by(|a, b| a.path().cmp(b.path())); - snapshots.sort(); + if let Some(list) = snapshots.as_mut() { + list.sort(); + } inputs.sort(); environments.sort_by(environment_order); Comparable::assemble(values, harness, treatment, snapshots, inputs, environments) @@ -2590,7 +2603,7 @@ struct RawRunManifest { comparable: Comparable, /// Where each value came from: one entry per value, and one or more entries under each typed root the cell holds; never an entry for a setting. #[schemars(extend( - "$comment" = "Each path of `comparable.values` has exactly one entry, and each of `harness`, `treatment` and the non-empty lists `snapshots`, `inputs` and `environments` has an entry at the root path or at a path under it; no other path appears and no path repeats. JSON Schema cannot state this, and the Rust reader refuses a list that differs." + "$comment" = "Each path of `comparable.values` has exactly one entry, and each of `harness`, `treatment` and the non-empty lists `snapshots` (present only in an imported run), `inputs` and `environments` has an entry at the root path or at a path under it; no other path appears and no path repeats. JSON Schema cannot state this, and the Rust reader refuses a list that differs." ))] sources: Vec<SourceEntry>, /// The secrets the run needed and whether each was present; never their values. diff --git a/crates/candler-schemas/src/execution/paths.rs b/crates/candler-schemas/src/execution/paths.rs index 8d496736..f437663f 100644 --- a/crates/candler-schemas/src/execution/paths.rs +++ b/crates/candler-schemas/src/execution/paths.rs @@ -130,9 +130,6 @@ pub const TREATMENT: &str = "treatment"; /// A typed root, derived: the digests of the server sources and the Dockerfile. pub const INPUTS: &str = "inputs"; -/// A typed root, derived: the catalog digest. -pub const SNAPSHOTS: &str = "snapshots"; - /// A typed root, reserved for plug-in environments: no preflight step of the runner derives it. pub const ENVIRONMENTS: &str = "environments"; @@ -192,7 +189,6 @@ const _: () = { assert!(crate::primitives::is_field_path(SECRETS)); assert!(crate::primitives::is_field_path(TREATMENT)); assert!(crate::primitives::is_field_path(INPUTS)); - assert!(crate::primitives::is_field_path(SNAPSHOTS)); assert!(crate::primitives::is_field_path(ENVIRONMENTS)); assert!(crate::primitives::is_field_path(STORE_ROOT)); assert!(crate::primitives::is_field_path(PLUGINS_DIRS)); diff --git a/crates/candler-schemas/src/generate.rs b/crates/candler-schemas/src/generate.rs index eeffc582..a004297c 100644 --- a/crates/candler-schemas/src/generate.rs +++ b/crates/candler-schemas/src/generate.rs @@ -15,8 +15,6 @@ use schemars::transform::{Transform, transform_subschemas}; use schemars::{JsonSchema, Schema}; use serde_json::{Map, Value, json}; -use crate::catalog::CatalogSnapshot; - /// The extension every generated schema file carries. const FILE_SUFFIX: &str = ".schema.json"; @@ -62,16 +60,16 @@ impl GeneratedSchema { #[must_use] pub fn generated_schemas() -> Vec<GeneratedSchema> { let modules = [ - vec![ - GeneratedSchema::of::<CatalogSnapshot>("catalog-snapshot"), - GeneratedSchema::of::<crate::outcome::OutcomeRecord>("outcome-record"), - ], + vec![GeneratedSchema::of::<crate::outcome::OutcomeRecord>( + "outcome-record", + )], crate::values::roots(), crate::canonical::roots(), crate::container::roots(), crate::process::roots(), crate::raw::roots(), crate::trace::roots(), + crate::servers::roots(), crate::execution::roots(), crate::evaluation::roots(), crate::refusal::roots(), diff --git a/crates/candler-schemas/src/inspect.rs b/crates/candler-schemas/src/inspect.rs index 2392310b..a33c1949 100644 --- a/crates/candler-schemas/src/inspect.rs +++ b/crates/candler-schemas/src/inspect.rs @@ -70,6 +70,9 @@ pub struct InspectRun { /// What the run was imported from, for an imported run. #[serde(default, skip_serializing_if = "Option::is_none")] pub import: Option<Value>, + /// The resolved `mcp.*` values the cell hashes, by path: the MCP configuration the run was + /// installed with. + pub mcp: BTreeMap<String, Value>, /// The measured values under `provenance.`, by path. pub provenance: BTreeMap<String, Value>, /// The other measured values, by path. diff --git a/crates/candler-schemas/src/lib.rs b/crates/candler-schemas/src/lib.rs index 6ac86fbb..29aaf6dd 100644 --- a/crates/candler-schemas/src/lib.rs +++ b/crates/candler-schemas/src/lib.rs @@ -1,9 +1,9 @@ //! Candler wire schemas: the string formats every record shares in [`primitives`], the analysis //! report in [`analysis`], the outcome -//! record in [`outcome`], the tool-catalog snapshot in [`catalog`], resolved values in [`values`], +//! record in [`outcome`], resolved values in [`values`], //! canonical JSON in [`canonical`], process records in [`process`], container records in //! [`container`], raw frames in [`raw`], the normalised trace in [`trace`], execution records in -//! [`execution`], evaluator protocol records in [`evaluation`], stable refusal codes in [`refusal`], and in [`generate`] the JSON Schema +//! [`execution`], the MCP servers in [`servers`], evaluator protocol records in [`evaluation`], stable refusal codes in [`refusal`], and in [`generate`] the JSON Schema //! files generated from these types, committed under `schema/`, with the check that keeps them in //! step with the types. //! @@ -14,7 +14,6 @@ pub mod analysis; pub mod canonical; -pub mod catalog; pub mod container; pub mod distinct; pub mod evaluation; @@ -29,5 +28,6 @@ pub mod process; pub mod raw; pub mod refusal; mod refusal_impls; +pub mod servers; pub mod trace; pub mod values; diff --git a/crates/candler-schemas/src/primitives.rs b/crates/candler-schemas/src/primitives.rs index 93cbe780..601cbf3a 100644 --- a/crates/candler-schemas/src/primitives.rs +++ b/crates/candler-schemas/src/primitives.rs @@ -736,7 +736,7 @@ impl FromStr for NameVersion { } text_type!(NameToken { - description: "A catalog provider reference, `name@token`, split at the last `@`: the name is non-empty and holds neither `@` nor white space, and the token matches `[0-9A-Za-z.+-]+`.", + description: "A name and a version token, `name@token`, split at the last `@`: the name is non-empty and holds neither `@` nor white space, and the token matches `[0-9A-Za-z.+-]+`.", pattern: NAME_TOKEN_PATTERN, fields: { name: String, version: String }, }); diff --git a/crates/candler-schemas/src/refusal.rs b/crates/candler-schemas/src/refusal.rs index 118c9cd7..b6a781e2 100644 --- a/crates/candler-schemas/src/refusal.rs +++ b/crates/candler-schemas/src/refusal.rs @@ -418,13 +418,12 @@ macro_rules! refusal_table { /// The rows of every refusal of this crate, in the order of the types. #[must_use] pub fn catalog() -> Vec<CatalogRow> { - let tables: [&'static [CatalogRow]; 9] = [ + let tables: [&'static [CatalogRow]; 8] = [ <crate::execution::ExecutionError as Catalogued>::rows(), <crate::evaluation::EvaluationError as Catalogued>::rows(), <crate::outcome::OutcomeError as Catalogued>::rows(), <crate::primitives::FormatError as Catalogued>::rows(), <crate::canonical::CanonicalError as Catalogued>::rows(), - <crate::catalog::CatalogError as Catalogued>::rows(), <crate::values::ValuesError as Catalogued>::rows(), <SchemaTagError as Catalogued>::rows(), <VersionMismatch as Catalogued>::rows(), diff --git a/crates/candler-schemas/src/refusal_impls.rs b/crates/candler-schemas/src/refusal_impls.rs index dd10ed5e..884d5b6c 100644 --- a/crates/candler-schemas/src/refusal_impls.rs +++ b/crates/candler-schemas/src/refusal_impls.rs @@ -7,7 +7,6 @@ //! checks the two against each other. use crate::canonical::CanonicalError; -use crate::catalog::CatalogError; use crate::evaluation::{EvaluationError, VersionMismatch}; use crate::execution::ExecutionError; use crate::outcome::OutcomeError; @@ -30,6 +29,7 @@ fn execution_path(error: &ExecutionError) -> Option<String> { ExecutionError::Zero { field, .. } | ExecutionError::NotPositive { field } => { file_field(field) } + ExecutionError::ReplicatesNotCount => Some(pointer_of(["replicates"])), ExecutionError::Format(inner) => Refusal::path(inner), ExecutionError::Values(inner) => Refusal::path(inner), ExecutionError::Canonical(inner) => Refusal::path(inner), @@ -114,6 +114,12 @@ refusal_table! { "A cost cap is not a finite number above 0.", "-", ), + ReplicatesNotCount { .. } => row( + "experiment.replicates_not_count", + Side::Experiment, + "`replicates` is not a whole number from 1 to 4294967295, such as a negative number, a fraction, a count beyond 32 bits or a string.", + "The `replicates` key.", + ), NoLevels { .. } => row( "experiment.factor_without_levels", Side::Experiment, @@ -632,55 +638,3 @@ fn non_root(path: &str) -> Option<String> { Some(path.to_owned()) } } - -/// A wrong tag sits in the `schema` field; the other faults name no place. -fn catalog_path(error: &CatalogError) -> Option<String> { - match error { - CatalogError::SchemaTag { .. } => Some(pointer_of(["schema"])), - CatalogError::MissingField { .. } - | CatalogError::ReservedKey { .. } - | CatalogError::Null - | CatalogError::EmptyName { .. } - | CatalogError::DuplicateName { .. } => None, - } -} - -refusal_table! { - CatalogError, path = catalog_path; - SchemaTag { .. } => row( - "catalog.schema_tag_mismatch", - Side::Environment, - "The tool catalog an image prints carries another `schema` marker than `tool-catalog-snapshot/1`.", - "`/schema`", - ), - MissingField { .. } => row( - "catalog.field_unset", - Side::Candler, - "A builder of a catalog snapshot was asked to build before a required field was set.", - "-", - ), - ReservedKey { .. } => row( - "catalog.extra_key_reserved", - Side::Candler, - "An extra key of a tool is the name of one of the tool's fields.", - "-", - ), - Null { .. } => row( - "catalog.field_null", - Side::Candler, - "An optional field of a catalog was written as null instead of being omitted.", - "-", - ), - EmptyName { .. } => row( - "catalog.name_empty", - Side::Environment, - "A server or tool name in the catalog an image prints is empty.", - "-", - ), - DuplicateName { .. } => row( - "catalog.name_repeated", - Side::Environment, - "A server or tool name in the catalog an image prints is repeated within its scope.", - "-", - ), -} diff --git a/crates/candler-schemas/src/servers.rs b/crates/candler-schemas/src/servers.rs new file mode 100644 index 00000000..36418609 --- /dev/null +++ b/crates/candler-schemas/src/servers.rs @@ -0,0 +1,114 @@ +//! The MCP servers an experiment declares, in the shape the drivers read them. +//! +//! One entry under `mcp.servers.<key>` is a table that names a server the cell's agent may call. +//! The drivers read the entry as a map (`candler_harness::mcp::servers`) and opencode's renderer +//! (`candler_harness_opencode::prepare::server`) takes the same fields; this module types them so a +//! malformed entry fails validation instead of being read by hand. +//! +//! The entry is typed here as its own generated schema, because the experiment schema cannot type +//! the one dotted path `mcp.servers`: under `fixed` every field-path key maps to the same generic +//! JSON value, and a factor level is likewise any JSON value. A server declared in either place +//! therefore sits under this type, and a single reader applies it in both. + +use std::collections::BTreeMap; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::generate::GeneratedSchema; + +/// The wire root schema this module publishes. +#[must_use] +pub(crate) fn roots() -> Vec<GeneratedSchema> { + vec![GeneratedSchema::of::<McpServer>("mcp-server")] +} + +/// The transport family a server speaks: a locally-started command or a remote URL. +/// +/// A `stdio` (or `local`) server starts a command and is the default when an entry sets no `type`; +/// a remote one is reached at a URL. The renderer reads `http`, `sse` and `remote` alike. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +#[expect( + clippy::exhaustive_enums, + reason = "EXHAUSTIVE: the drivers live in other crates and answer each transport; a new one must break each of them." +)] +pub enum McpServerKind { + /// A server that prints the MCP protocol over a child process's standard streams. + Stdio, + /// A local server the drivers treat as a stdio one. + Local, + /// A server reached over HTTP. + Http, + /// A server reached over a Server-Sent Events stream. + Sse, + /// A server reached at a URL. + Remote, +} + +/// The names a server may render under, by `name` or by its key: ASCII letters, digits and `-` +/// joined by single `_`, so that no harness rewrites or splits the name in a tool id. +pub const SERVER_NAME_PATTERN: &str = r"^[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*(?![\s\S])"; + +/// One entry of an experiment's `mcp.servers`, as the drivers read it. +/// +/// A server is launched from a `command` (with optional `args` and `env`) or reached at a `url` +/// (with optional `headers`); exactly one of `command` and `url` is required, and a `type` marker +/// agrees with it: `stdio` or `local` with `command`, `http`, `sse` or `remote` with `url`. +/// `codemode` selects the prompts the agent sees, and is `false` when absent. A `name` +/// leaf names the server under a key; without it the key names it. Every field the drivers read +/// is typed here, so a non-text `command`, a non-list `args` or a non-text environment value fails +/// validation rather than being read leniently. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +#[schemars(extend( + "oneOf" = [ + { + "required": ["command"], + "properties": { + "url": false, + "headers": false, + "type": { "enum": ["stdio", "local"] } + } + }, + { + "required": ["url"], + "properties": { + "command": false, + "args": false, + "env": false, + "type": { "enum": ["http", "sse", "remote"] } + } + } + ] +))] +pub struct McpServer { + /// The transport marker: `stdio` or `local` for a launched command, `http`, `sse` or `remote` + /// for a URL; absent when the driver would launch a command. + #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] + pub kind: Option<McpServerKind>, + /// The launched command, as a program name or path; required of an entry with no URL. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub command: Option<String>, + /// The arguments the launched command receives, one per list item. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub args: Option<Vec<String>>, + /// The environment of the launched command, by variable name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub env: Option<BTreeMap<String, String>>, + /// The URL a remote server is reached at. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option<String>, + /// The headers a remote server is called with. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option<BTreeMap<String, String>>, + /// Whether the server's tools show in the agent's codemode prompts; false when absent. + #[serde(default)] + pub codemode: bool, + /// The name the server renders under, when its key would not do; a key + /// matches the same pattern. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(regex(pattern = SERVER_NAME_PATTERN))] + pub name: Option<String>, +} diff --git a/crates/candler-schemas/src/trace.rs b/crates/candler-schemas/src/trace.rs index 03edbb16..9384ebd4 100644 --- a/crates/candler-schemas/src/trace.rs +++ b/crates/candler-schemas/src/trace.rs @@ -637,7 +637,7 @@ impl SessionBuilder { } } -/// Where a tool call is served from: an object whose `kind` is `builtin`, `mcp`, with the `server` that offers the tool, or `other`. +/// Where a tool call is served from: an object whose `kind` is `builtin`, `mcp`, with the `server` that offers the tool and the server's own name for it, or `other`. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] #[serde(remote = "Self", tag = "kind", rename_all = "snake_case")] #[schemars(deny_unknown_fields)] @@ -645,11 +645,17 @@ impl SessionBuilder { pub enum ToolOrigin { /// A tool the harness itself provides. Builtin, - /// A tool an MCP server offers. + /// A tool an MCP server offers. Claude Code's reader takes any `mcp__<server>__<tool>` for the + /// tool of `<server>`, declared or not; `OpenCode`'s takes only a declared server, because its + /// spelling `<server>_<tool>` cannot be split without the server names. #[non_exhaustive] Mcp { /// The name of the MCP server. server: String, + /// The tool's name at the server, without the harness's prefix. A trace written before the + /// field existed has none. + #[serde(default, skip_serializing_if = "Option::is_none")] + tool: Option<String>, }, /// Any other source. Other, @@ -658,10 +664,13 @@ pub enum ToolOrigin { object_only!(ToolOrigin); impl ToolOrigin { - /// An MCP tool of `server`. + /// An MCP tool of `server`, named `tool` there. #[must_use] - pub const fn mcp(server: String) -> Self { - Self::Mcp { server } + pub const fn mcp_tool(server: String, tool: String) -> Self { + Self::Mcp { + server, + tool: Some(tool), + } } } diff --git a/crates/candler-schemas/tests/fixtures/spec/LICENSE b/crates/candler-schemas/tests/fixtures/spec/LICENSE deleted file mode 100644 index 4a939857..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/LICENSE +++ /dev/null @@ -1,216 +0,0 @@ -The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. - -Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. - -No rights beyond those granted by the applicable original license are conveyed for such contributions. - ---- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to the Licensor for inclusion in the Work by the copyright - owner or by an individual or Legal Entity authorized to submit on behalf - of the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - ---- - -MIT License - -Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - ---- - -Creative Commons Attribution 4.0 International (CC-BY-4.0) - -Documentation in this project (excluding specifications) is licensed under -CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for -the full license text. diff --git a/crates/candler-schemas/tests/fixtures/spec/README.md b/crates/candler-schemas/tests/fixtures/spec/README.md deleted file mode 100644 index 0f6e529b..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# MCP specification fixtures - -The `Tool` definition of the latest published MCP specification, and tool objects the specification -gives as examples. They are inputs to the catalog snapshot tests: every tool here is a valid MCP tool -object, so a snapshot schema that rejects one is too strict. - -## Provenance - -| | | -|---|---| -| Repository | `modelcontextprotocol/modelcontextprotocol` (GitHub) | -| Commit | `ccaf9102ec5eb656eab50ca8333ef49dcd259c26` (`main`, 2026-10-27T17:10:04Z) | -| Version | `2026-07-28`, the latest dated version under `schema/` that is not `draft` | -| Fetched with | `gh api -H 'Accept: application/vnd.github.raw+json' 'repos/modelcontextprotocol/modelcontextprotocol/contents/<path>?ref=ccaf9102ec5eb656eab50ca8333ef49dcd259c26'` | -| Licence | `LICENSE` of the repository, vendored here. The project is moving from MIT to Apache-2.0: new code and specification contributions are Apache-2.0, documentation outside the specification is CC-BY-4.0, and contributions without relicensing consent stay MIT. | - -## Files - -| File | Source path at the commit | Blob | Size | -|---|---|---|---:| -| `mcp-2026-07-28.schema.json` | `schema/2026-07-28/schema.json` | `213c58f6d9a1c2ce6ad055afe90bbdb095a29ee8` | 181,474 B | -| `LICENSE` | `LICENSE` | `4a93985763241755401a10678395303de4e720ba` | 12,227 B | - -`mcp-2026-07-28.schema.json` is JSON Schema 2020-12. Its `$defs.Tool` has the properties `_meta`, -`annotations`, `description`, `icons`, `inputSchema`, `name`, `outputSchema` and `title`; `inputSchema` -and `name` are required. `inputSchema` and `outputSchema` are open objects: `outputSchema` may -be any JSON Schema, an array schema included. - -## `tools/` - -One file per distinct tool example in the specification. Files taken from the schema examples are -byte for byte; files taken from the documentation are the JSON block of the page, re-indented with -two spaces. - -| File | Origin | Blob of the source file | -|---|---|---| -| `tool-with-array-output-schema.json` | `schema/2026-07-28/examples/Tool/tool-with-array-output-schema.json` | `8c7edec6237a12b1c76fb3af13c9430212840306` | -| `tool-with-composition-input-schema.json` | `schema/2026-07-28/examples/Tool/tool-with-composition-input-schema.json` | `7c7253af9f356759cff39c8f9746dfa16c212a8b` | -| `with-default-2020-12-input-schema.json` | `schema/2026-07-28/examples/Tool/with-default-2020-12-input-schema.json` | `d79a00eeaa7cca70a61a9606148ec5ee433d2512` | -| `with-explicit-draft-07-input-schema.json` | `schema/2026-07-28/examples/Tool/with-explicit-draft-07-input-schema.json` | `698d95b86549291e0acde11955f64e60b6e7eb71` | -| `with-no-parameters.json` | `schema/2026-07-28/examples/Tool/with-no-parameters.json` | `04a3a4e956385db9a7a0533f97351dc1f2a14d20` | -| `with-output-schema-for-structured-content.json` | `schema/2026-07-28/examples/Tool/with-output-schema-for-structured-content.json` | `a1469834247527890c22f3e23ec3015ca44910b8` | -| `docs-get-weather-with-icons.json` | `docs/specification/2026-07-28/server/tools.mdx`, the `tools/list` response (also in `examples/ListToolsResult/`) | `449020f54a6582122607b4869129bec5f1035f37` | -| `docs-execute-sql-x-mcp-header.json` | `tools.mdx`, "Example tool definition with `x-mcp-header`" | same | -| `docs-list-users-array-output.json` | `tools.mdx`, "Example tool with array output schema" (the schema example of the same name carries property descriptions; this one does not) | same | -| `full.json` | Written from `$defs.Tool`: every property of `Tool`, every property of `ToolAnnotations` and of `Icon`, and a `_meta` with two valid keys | none | - -The other tool blocks of `tools.mdx` (`get_weather_data`, `calculate_sum` twice, `get_current_time`) -equal the schema examples above and are not repeated. - -Check: `for f in tools/*.json; do jq -e .name "$f" >/dev/null || exit 1; done`. diff --git a/crates/candler-schemas/tests/fixtures/spec/mcp-2026-07-28.schema.json b/crates/candler-schemas/tests/fixtures/spec/mcp-2026-07-28.schema.json deleted file mode 100644 index 213c58f6..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/mcp-2026-07-28.schema.json +++ /dev/null @@ -1,3963 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$defs": { - "Annotations": { - "description": "Optional annotations for the client. The client can use annotations to inform how objects are used or displayed", - "properties": { - "audience": { - "description": "Describes who the intended audience of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).", - "items": { - "$ref": "#/$defs/Role" - }, - "type": "array" - }, - "lastModified": { - "description": "The moment the resource was last modified, as an ISO 8601 formatted string.\n\nShould be an ISO 8601 formatted string (e.g., \"2025-01-12T15:00:58Z\").\n\nExamples: last activity timestamp in an open file, timestamp when the resource\nwas attached, etc.", - "type": "string" - }, - "priority": { - "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.", - "maximum": 1, - "minimum": 0, - "type": "number" - } - }, - "type": "object" - }, - "AudioContent": { - "description": "Audio provided to or from an LLM.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "annotations": { - "$ref": "#/$defs/Annotations", - "description": "Optional annotations for the client." - }, - "data": { - "description": "The base64-encoded audio data.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of the audio. Different providers may support different audio types.", - "type": "string" - }, - "type": { - "const": "audio", - "type": "string" - } - }, - "required": [ - "data", - "mimeType", - "type" - ], - "type": "object" - }, - "BaseMetadata": { - "description": "Base interface for metadata with name (identifier) and title (display name) properties.", - "properties": { - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "BlobResourceContents": { - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "blob": { - "description": "A base64-encoded string representing the binary data of the item.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "blob", - "uri" - ], - "type": "object" - }, - "BooleanSchema": { - "properties": { - "default": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "title": { - "type": "string" - }, - "type": { - "const": "boolean", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "CacheableResult": { - "description": "A result that supports a time-to-live (TTL) hint for client-side caching.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "cacheScope": { - "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).", - "enum": [ - "private", - "public" - ], - "type": "string" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - }, - "ttlMs": { - "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "cacheScope", - "resultType", - "ttlMs" - ], - "type": "object" - }, - "CallToolRequest": { - "description": "Used by the client to invoke a tool provided by the server.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "tools/call", - "type": "string" - }, - "params": { - "$ref": "#/$defs/CallToolRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "CallToolRequestParams": { - "description": "Parameters for a `tools/call` request.", - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - }, - "arguments": { - "additionalProperties": {}, - "description": "Arguments to use for the tool call.", - "type": "object" - }, - "inputResponses": { - "$ref": "#/$defs/InputResponses" - }, - "name": { - "description": "The name of the tool.", - "type": "string" - }, - "requestState": { - "type": "string" - } - }, - "required": [ - "_meta", - "name" - ], - "type": "object" - }, - "CallToolResult": { - "description": "The result returned by the server for a {@link CallToolRequesttools/call} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "content": { - "description": "A list of content objects that represent the unstructured result of the tool call.", - "items": { - "$ref": "#/$defs/ContentBlock" - }, - "type": "array" - }, - "isError": { - "description": "Whether the tool call ended in an error.\n\nIf not set, this is assumed to be false (the call was successful).\n\nAny errors that originate from the tool SHOULD be reported inside the result\nobject, with `isError` set to true, _not_ as an MCP protocol-level error\nresponse. Otherwise, the LLM would not be able to see that an error occurred\nand self-correct.\n\nHowever, any errors in _finding_ the tool, an error indicating that the\nserver does not support tool calls, or any other exceptional conditions,\nshould be reported as an MCP error response.", - "type": "boolean" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - }, - "structuredContent": { - "description": "An optional JSON value that represents the structured result of the tool call.\n\nThis can be any JSON value (object, array, string, number, boolean, or null)\nthat conforms to the tool's outputSchema if one is defined." - } - }, - "required": [ - "content", - "resultType" - ], - "type": "object" - }, - "CallToolResultResponse": { - "description": "A successful response from the server for a {@link CallToolRequesttools/call} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "anyOf": [ - { - "$ref": "#/$defs/InputRequiredResult" - }, - { - "$ref": "#/$defs/CallToolResult" - } - ] - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "CancelledNotification": { - "description": "This notification is sent by the client to indicate that it is cancelling a request it previously issued.\n\nOn stdio, the server also sends this notification, solely to terminate a {@link SubscriptionsListenRequestsubscriptions/listen} stream: it references the ID of the `subscriptions/listen` request that opened the stream. Servers MUST NOT use this notification to cancel any other request.\n\nThe request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n\nThis notification indicates that the result will be unused, so any associated processing SHOULD cease.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/cancelled", - "type": "string" - }, - "params": { - "$ref": "#/$defs/CancelledNotificationParams" - } - }, - "required": [ - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "CancelledNotificationParams": { - "description": "Parameters for a `notifications/cancelled` notification.", - "properties": { - "_meta": { - "$ref": "#/$defs/NotificationMetaObject" - }, - "reason": { - "description": "An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.", - "type": "string" - }, - "requestId": { - "$ref": "#/$defs/RequestId", - "description": "The ID of the request to cancel.\n\nThis MUST correspond to the ID of a request the client previously issued." - } - }, - "required": [ - "requestId" - ], - "type": "object" - }, - "ClientCapabilities": { - "description": "Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.", - "properties": { - "elicitation": { - "description": "Present if the client supports elicitation from the server.", - "properties": { - "form": { - "$ref": "#/$defs/JSONObject" - }, - "url": { - "$ref": "#/$defs/JSONObject" - } - }, - "type": "object" - }, - "experimental": { - "additionalProperties": { - "$ref": "#/$defs/JSONObject" - }, - "description": "Experimental, non-standard capabilities that the client supports.", - "type": "object" - }, - "extensions": { - "additionalProperties": { - "$ref": "#/$defs/JSONObject" - }, - "description": "Optional MCP extensions that the client supports. Keys are extension identifiers\n(e.g., \"io.modelcontextprotocol/oauth-client-credentials\"), and values are\nper-extension settings objects. An empty object indicates support with no settings.\n\nKeys MUST follow the {@link MetaObject`_meta` key naming rules}, with a\nmandatory prefix.", - "type": "object" - }, - "roots": { - "description": "Present if the client supports listing roots.", - "properties": {}, - "type": "object" - }, - "sampling": { - "description": "Present if the client supports sampling from an LLM.", - "properties": { - "context": { - "$ref": "#/$defs/JSONObject", - "description": "Whether the client supports context inclusion via `includeContext` parameter.\nIf not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it)." - }, - "tools": { - "$ref": "#/$defs/JSONObject", - "description": "Whether the client supports tool use via `tools` and `toolChoice` parameters." - } - }, - "type": "object" - } - }, - "type": "object" - }, - "ClientNotification": { - "description": "This notification is sent by the client to indicate that it is cancelling a request it previously issued.\n\nOn stdio, the server also sends this notification, solely to terminate a {@link SubscriptionsListenRequestsubscriptions/listen} stream: it references the ID of the `subscriptions/listen` request that opened the stream. Servers MUST NOT use this notification to cancel any other request.\n\nThe request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n\nThis notification indicates that the result will be unused, so any associated processing SHOULD cease.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/cancelled", - "type": "string" - }, - "params": { - "$ref": "#/$defs/CancelledNotificationParams" - } - }, - "required": [ - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "ClientRequest": { - "anyOf": [ - { - "$ref": "#/$defs/DiscoverRequest" - }, - { - "$ref": "#/$defs/ListResourcesRequest" - }, - { - "$ref": "#/$defs/ListResourceTemplatesRequest" - }, - { - "$ref": "#/$defs/ReadResourceRequest" - }, - { - "$ref": "#/$defs/SubscriptionsListenRequest" - }, - { - "$ref": "#/$defs/ListPromptsRequest" - }, - { - "$ref": "#/$defs/GetPromptRequest" - }, - { - "$ref": "#/$defs/ListToolsRequest" - }, - { - "$ref": "#/$defs/CallToolRequest" - }, - { - "$ref": "#/$defs/CompleteRequest" - } - ] - }, - "ClientResult": { - "$ref": "#/$defs/Result", - "description": "Common result fields." - }, - "CompleteRequest": { - "description": "A request from the client to the server, to ask for completion options.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "completion/complete", - "type": "string" - }, - "params": { - "$ref": "#/$defs/CompleteRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "CompleteRequestParams": { - "description": "Parameters for a `completion/complete` request.", - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - }, - "argument": { - "description": "The argument's information", - "properties": { - "name": { - "description": "The name of the argument", - "type": "string" - }, - "value": { - "description": "The value of the argument to use for completion matching.", - "type": "string" - } - }, - "required": [ - "name", - "value" - ], - "type": "object" - }, - "context": { - "description": "Additional, optional context for completions", - "properties": { - "arguments": { - "additionalProperties": { - "type": "string" - }, - "description": "Previously-resolved variables in a URI template or prompt.", - "type": "object" - } - }, - "type": "object" - }, - "ref": { - "anyOf": [ - { - "$ref": "#/$defs/PromptReference" - }, - { - "$ref": "#/$defs/ResourceTemplateReference" - } - ] - } - }, - "required": [ - "_meta", - "argument", - "ref" - ], - "type": "object" - }, - "CompleteResult": { - "description": "The result returned by the server for a {@link CompleteRequestcompletion/complete} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "completion": { - "properties": { - "hasMore": { - "description": "Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.", - "type": "boolean" - }, - "total": { - "description": "The total number of completion options available. This can exceed the number of values actually sent in the response.", - "type": "integer" - }, - "values": { - "description": "An array of completion values. Must not exceed 100 items.", - "items": { - "type": "string" - }, - "maxItems": 100, - "type": "array" - } - }, - "required": [ - "values" - ], - "type": "object" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - } - }, - "required": [ - "completion", - "resultType" - ], - "type": "object" - }, - "CompleteResultResponse": { - "description": "A successful response from the server for a {@link CompleteRequestcompletion/complete} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/$defs/CompleteResult" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "ContentBlock": { - "anyOf": [ - { - "$ref": "#/$defs/TextContent" - }, - { - "$ref": "#/$defs/ImageContent" - }, - { - "$ref": "#/$defs/AudioContent" - }, - { - "$ref": "#/$defs/ResourceLink" - }, - { - "$ref": "#/$defs/EmbeddedResource" - } - ] - }, - "CreateMessageRequest": { - "description": "A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.", - "properties": { - "method": { - "const": "sampling/createMessage", - "type": "string" - }, - "params": { - "$ref": "#/$defs/CreateMessageRequestParams" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "CreateMessageRequestParams": { - "description": "Parameters for a `sampling/createMessage` request.", - "properties": { - "includeContext": { - "description": "A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\nThe client MAY ignore this request.\n\nDefault is `\"none\"`. The values `\"thisServer\"` and `\"allServers\"` are deprecated (SEP-2596): servers SHOULD\nomit this field or use `\"none\"`, and SHOULD only use the deprecated values if the client declares\n{@link ClientCapabilities.sampling.context}.", - "enum": [ - "allServers", - "none", - "thisServer" - ], - "type": "string" - }, - "maxTokens": { - "description": "The requested maximum number of tokens to sample (to prevent runaway completions).\n\nThe client MAY choose to sample fewer tokens than the requested maximum.", - "type": "integer" - }, - "messages": { - "items": { - "$ref": "#/$defs/SamplingMessage" - }, - "type": "array" - }, - "metadata": { - "$ref": "#/$defs/JSONObject", - "description": "Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific." - }, - "modelPreferences": { - "$ref": "#/$defs/ModelPreferences", - "description": "The server's preferences for which model to select. The client MAY ignore these preferences." - }, - "stopSequences": { - "items": { - "type": "string" - }, - "type": "array" - }, - "systemPrompt": { - "description": "An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.", - "type": "string" - }, - "temperature": { - "type": "number" - }, - "toolChoice": { - "$ref": "#/$defs/ToolChoice", - "description": "Controls how the model uses tools.\nThe client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared.\nDefault is `{ mode: \"auto\" }`." - }, - "tools": { - "description": "Tools that the model may use during generation.\nThe client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared.", - "items": { - "$ref": "#/$defs/Tool" - }, - "type": "array" - } - }, - "required": [ - "maxTokens", - "messages" - ], - "type": "object" - }, - "CreateMessageResult": { - "description": "The result returned by the client for a {@link CreateMessageRequestsampling/createMessage} request.\nThe client should inform the user before returning the sampled message, to allow them\nto inspect the response (human in the loop) and decide whether to allow the server to see it.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "content": { - "anyOf": [ - { - "$ref": "#/$defs/TextContent" - }, - { - "$ref": "#/$defs/ImageContent" - }, - { - "$ref": "#/$defs/AudioContent" - }, - { - "$ref": "#/$defs/ToolUseContent" - }, - { - "$ref": "#/$defs/ToolResultContent" - }, - { - "items": { - "$ref": "#/$defs/SamplingMessageContentBlock" - }, - "type": "array" - } - ] - }, - "model": { - "description": "The name of the model that generated the message.", - "type": "string" - }, - "role": { - "$ref": "#/$defs/Role" - }, - "stopReason": { - "description": "The reason why sampling stopped, if known.\n\nStandard values:\n- `\"endTurn\"`: Natural end of the assistant's turn\n- `\"stopSequence\"`: A stop sequence was encountered\n- `\"maxTokens\"`: Maximum token limit was reached\n- `\"toolUse\"`: The model wants to use one or more tools\n\nThis field is an open string to allow for provider-specific stop reasons.", - "type": "string" - } - }, - "required": [ - "content", - "model", - "role" - ], - "type": "object" - }, - "Cursor": { - "description": "An opaque token used to represent a cursor for pagination.", - "type": "string" - }, - "DiscoverRequest": { - "description": "A request from the client asking the server to advertise its supported\nprotocol versions, capabilities, and other metadata. Servers **MUST**\nimplement `server/discover`. Clients **MAY** call it but are not required\nto — version negotiation can also happen inline via per-request `_meta`.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "server/discover", - "type": "string" - }, - "params": { - "$ref": "#/$defs/RequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "DiscoverResult": { - "description": "The result returned by the server for a {@link DiscoverRequestserver/discover} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "cacheScope": { - "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).", - "enum": [ - "private", - "public" - ], - "type": "string" - }, - "capabilities": { - "$ref": "#/$defs/ServerCapabilities", - "description": "The capabilities of the server." - }, - "instructions": { - "description": "Natural-language guidance describing the server and its features.\n\nThis can be used by clients to improve an LLM's understanding of\navailable tools (e.g., by including it in a system prompt). It should\nfocus on information that helps the model use the server effectively\nand should not duplicate information already in tool descriptions.", - "type": "string" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - }, - "supportedVersions": { - "description": "MCP Protocol Versions this server supports. The client should choose a\nversion from this list for use in subsequent requests.", - "items": { - "type": "string" - }, - "type": "array" - }, - "ttlMs": { - "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "cacheScope", - "capabilities", - "resultType", - "supportedVersions", - "ttlMs" - ], - "type": "object" - }, - "DiscoverResultResponse": { - "description": "A successful response from the server for a {@link DiscoverRequestserver/discover} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/$defs/DiscoverResult" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "ElicitRequest": { - "description": "A request from the server to elicit additional information from the user via the client.", - "properties": { - "method": { - "const": "elicitation/create", - "type": "string" - }, - "params": { - "$ref": "#/$defs/ElicitRequestParams" - } - }, - "required": [ - "method", - "params" - ], - "type": "object" - }, - "ElicitRequestFormParams": { - "description": "The parameters for a request to elicit non-sensitive information from the user via a form in the client.", - "properties": { - "message": { - "description": "The message to present to the user describing what information is being requested.", - "type": "string" - }, - "mode": { - "const": "form", - "description": "The elicitation mode.", - "type": "string" - }, - "requestedSchema": { - "description": "A restricted subset of JSON Schema.\nOnly top-level properties are allowed, without nesting.", - "properties": { - "$schema": { - "type": "string" - }, - "properties": { - "additionalProperties": { - "$ref": "#/$defs/PrimitiveSchemaDefinition" - }, - "type": "object" - }, - "required": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "const": "object", - "type": "string" - } - }, - "required": [ - "properties", - "type" - ], - "type": "object" - } - }, - "required": [ - "message", - "requestedSchema" - ], - "type": "object" - }, - "ElicitRequestParams": { - "anyOf": [ - { - "$ref": "#/$defs/ElicitRequestFormParams" - }, - { - "$ref": "#/$defs/ElicitRequestURLParams" - } - ], - "description": "The parameters for a request to elicit additional information from the user via the client." - }, - "ElicitRequestURLParams": { - "description": "The parameters for a request to elicit information from the user via a URL in the client.", - "properties": { - "message": { - "description": "The message to present to the user explaining why the interaction is needed.", - "type": "string" - }, - "mode": { - "const": "url", - "description": "The elicitation mode.", - "type": "string" - }, - "url": { - "description": "The URL that the user should navigate to.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "message", - "mode", - "url" - ], - "type": "object" - }, - "ElicitResult": { - "description": "The result returned by the client for an {@link ElicitRequestelicitation/create} request.", - "properties": { - "action": { - "description": "The user action in response to the elicitation.\n- `\"accept\"`: User submitted the form/confirmed the action\n- `\"decline\"`: User explicitly declined the action\n- `\"cancel\"`: User dismissed without making an explicit choice", - "enum": [ - "accept", - "cancel", - "decline" - ], - "type": "string" - }, - "content": { - "additionalProperties": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": [ - "string", - "integer", - "boolean" - ] - } - ] - }, - "description": "The submitted form data, only present when action is `\"accept\"` and mode was `\"form\"`.\nContains values matching the requested schema.\nOmitted for out-of-band mode responses.", - "type": "object" - } - }, - "required": [ - "action" - ], - "type": "object" - }, - "EmbeddedResource": { - "description": "The contents of a resource, embedded into a prompt or tool call result.\n\nIt is up to the client how best to render embedded resources for the benefit\nof the LLM and/or the user.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "annotations": { - "$ref": "#/$defs/Annotations", - "description": "Optional annotations for the client." - }, - "resource": { - "anyOf": [ - { - "$ref": "#/$defs/TextResourceContents" - }, - { - "$ref": "#/$defs/BlobResourceContents" - } - ] - }, - "type": { - "const": "resource", - "type": "string" - } - }, - "required": [ - "resource", - "type" - ], - "type": "object" - }, - "EmptyResult": { - "$ref": "#/$defs/Result", - "description": "Common result fields." - }, - "EnumSchema": { - "anyOf": [ - { - "$ref": "#/$defs/UntitledSingleSelectEnumSchema" - }, - { - "$ref": "#/$defs/TitledSingleSelectEnumSchema" - }, - { - "$ref": "#/$defs/UntitledMultiSelectEnumSchema" - }, - { - "$ref": "#/$defs/TitledMultiSelectEnumSchema" - }, - { - "$ref": "#/$defs/LegacyTitledEnumSchema" - } - ] - }, - "Error": { - "properties": { - "code": { - "description": "The error type that occurred.", - "type": "integer" - }, - "data": { - "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." - }, - "message": { - "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", - "type": "string" - } - }, - "required": [ - "code", - "message" - ], - "type": "object" - }, - "GetPromptRequest": { - "description": "Used by the client to get a prompt provided by the server.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "prompts/get", - "type": "string" - }, - "params": { - "$ref": "#/$defs/GetPromptRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "GetPromptRequestParams": { - "description": "Parameters for a `prompts/get` request.", - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - }, - "arguments": { - "additionalProperties": { - "type": "string" - }, - "description": "Arguments to use for templating the prompt.", - "type": "object" - }, - "inputResponses": { - "$ref": "#/$defs/InputResponses" - }, - "name": { - "description": "The name of the prompt or prompt template.", - "type": "string" - }, - "requestState": { - "type": "string" - } - }, - "required": [ - "_meta", - "name" - ], - "type": "object" - }, - "GetPromptResult": { - "description": "The result returned by the server for a {@link GetPromptRequestprompts/get} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "description": { - "description": "An optional description for the prompt.", - "type": "string" - }, - "messages": { - "items": { - "$ref": "#/$defs/PromptMessage" - }, - "type": "array" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - } - }, - "required": [ - "messages", - "resultType" - ], - "type": "object" - }, - "GetPromptResultResponse": { - "description": "A successful response from the server for a {@link GetPromptRequestprompts/get} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "anyOf": [ - { - "$ref": "#/$defs/InputRequiredResult" - }, - { - "$ref": "#/$defs/GetPromptResult" - } - ] - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "HeaderMismatchError": { - "description": "Returned when a server rejects a request because the values in the HTTP\nheaders do not match the corresponding values in the request body, or\nbecause required headers are missing or malformed. For HTTP, the response\nstatus code MUST be `400 Bad Request`.", - "properties": { - "error": { - "allOf": [ - { - "$ref": "#/$defs/Error" - }, - { - "properties": { - "code": { - "const": -32020, - "type": "integer" - } - }, - "required": [ - "code" - ], - "type": "object" - } - ] - }, - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - } - }, - "required": [ - "error", - "jsonrpc" - ], - "type": "object" - }, - "Icon": { - "description": "An optionally-sized icon that can be displayed in a user interface.", - "properties": { - "mimeType": { - "description": "Optional MIME type override if the source MIME type is missing or generic.\nFor example: `\"image/png\"`, `\"image/jpeg\"`, or `\"image/svg+xml\"`.", - "type": "string" - }, - "sizes": { - "description": "Optional array of strings that specify sizes at which the icon can be used.\nEach string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n\nIf not provided, the client should assume that the icon can be used at any size.", - "items": { - "type": "string" - }, - "type": "array" - }, - "src": { - "description": "A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a\n`data:` URI with Base64-encoded image data.\n\nConsumers SHOULD take steps to ensure URLs serving icons are from the\nsame domain as the client/server or a trusted domain.\n\nConsumers SHOULD take appropriate precautions when consuming SVGs as they can contain\nexecutable JavaScript.", - "format": "uri", - "type": "string" - }, - "theme": { - "description": "Optional specifier for the theme this icon is designed for. `\"light\"` indicates\nthe icon is designed to be used with a light background, and `\"dark\"` indicates\nthe icon is designed to be used with a dark background.\n\nIf not provided, the client should assume the icon can be used with any theme.", - "enum": [ - "dark", - "light" - ], - "type": "string" - } - }, - "required": [ - "src" - ], - "type": "object" - }, - "Icons": { - "description": "Base interface to add `icons` property.", - "properties": { - "icons": { - "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", - "items": { - "$ref": "#/$defs/Icon" - }, - "type": "array" - } - }, - "type": "object" - }, - "ImageContent": { - "description": "An image provided to or from an LLM.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "annotations": { - "$ref": "#/$defs/Annotations", - "description": "Optional annotations for the client." - }, - "data": { - "description": "The base64-encoded image data.", - "format": "byte", - "type": "string" - }, - "mimeType": { - "description": "The MIME type of the image. Different providers may support different image types.", - "type": "string" - }, - "type": { - "const": "image", - "type": "string" - } - }, - "required": [ - "data", - "mimeType", - "type" - ], - "type": "object" - }, - "Implementation": { - "description": "Describes the MCP implementation.", - "properties": { - "description": { - "description": "An optional human-readable description of what this implementation does.\n\nThis can be used by clients or servers to provide context about their purpose\nand capabilities. For example, a server might describe the types of resources\nor tools it provides, while a client might describe its intended use case.", - "type": "string" - }, - "icons": { - "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", - "items": { - "$ref": "#/$defs/Icon" - }, - "type": "array" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "version": { - "description": "The version of this implementation.", - "type": "string" - }, - "websiteUrl": { - "description": "An optional URL of the website for this implementation.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "name", - "version" - ], - "type": "object" - }, - "InputRequest": { - "anyOf": [ - { - "$ref": "#/$defs/CreateMessageRequest" - }, - { - "$ref": "#/$defs/ListRootsRequest" - }, - { - "$ref": "#/$defs/ElicitRequest" - } - ] - }, - "InputRequests": { - "additionalProperties": { - "$ref": "#/$defs/InputRequest" - }, - "description": "A map of server-initiated requests that the client must fulfill.\nKeys are server-assigned identifiers; values are the request objects.", - "type": "object" - }, - "InputRequiredResult": { - "description": "An InputRequiredResult sent by the server to indicate that additional input is needed\nbefore the request can be completed.\n\nAt least one of `inputRequests` or `requestState` MUST be present.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "inputRequests": { - "$ref": "#/$defs/InputRequests" - }, - "requestState": { - "type": "string" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - } - }, - "required": [ - "resultType" - ], - "type": "object" - }, - "InputResponse": { - "anyOf": [ - { - "$ref": "#/$defs/CreateMessageResult" - }, - { - "$ref": "#/$defs/ListRootsResult" - }, - { - "$ref": "#/$defs/ElicitResult" - } - ] - }, - "InputResponseRequestParams": { - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - }, - "inputResponses": { - "$ref": "#/$defs/InputResponses" - }, - "requestState": { - "type": "string" - } - }, - "required": [ - "_meta" - ], - "type": "object" - }, - "InputResponses": { - "additionalProperties": { - "$ref": "#/$defs/InputResponse" - }, - "description": "A map of client responses to server-initiated requests.\nKeys correspond to the keys in the {@link InputRequests} map;\nvalues are the client's result for each request.", - "type": "object" - }, - "InternalError": { - "description": "A JSON-RPC error indicating that an internal error occurred on the receiver. This error is returned when the receiver encounters an unexpected condition that prevents it from fulfilling the request.", - "properties": { - "code": { - "const": -32603, - "description": "The error type that occurred.", - "type": "integer" - }, - "data": { - "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." - }, - "message": { - "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", - "type": "string" - } - }, - "required": [ - "code", - "message" - ], - "type": "object" - }, - "InvalidParamsError": { - "description": "A JSON-RPC error indicating that the method parameters are invalid or malformed.\n\nIn MCP, this error is returned in various contexts when request parameters fail validation:\n\n- **Tools**: Unknown tool name or invalid tool arguments\n- **Prompts**: Unknown prompt name or missing required arguments\n- **Pagination**: Invalid or expired cursor values\n- **Logging**: Invalid log level\n- **Elicitation**: Server requests an elicitation mode not declared in client capabilities\n- **Sampling**: Missing tool result or tool results mixed with other content", - "properties": { - "code": { - "const": -32602, - "description": "The error type that occurred.", - "type": "integer" - }, - "data": { - "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." - }, - "message": { - "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", - "type": "string" - } - }, - "required": [ - "code", - "message" - ], - "type": "object" - }, - "InvalidRequestError": { - "description": "A JSON-RPC error indicating that the request is not a valid request object. This error is returned when the message structure does not conform to the JSON-RPC 2.0 specification requirements for a request (e.g., missing required fields like `jsonrpc` or `method`, or using invalid types for these fields).", - "properties": { - "code": { - "const": -32600, - "description": "The error type that occurred.", - "type": "integer" - }, - "data": { - "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." - }, - "message": { - "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", - "type": "string" - } - }, - "required": [ - "code", - "message" - ], - "type": "object" - }, - "JSONArray": { - "items": { - "$ref": "#/$defs/JSONValue" - }, - "type": "array" - }, - "JSONObject": { - "additionalProperties": { - "$ref": "#/$defs/JSONValue" - }, - "type": "object" - }, - "JSONRPCErrorResponse": { - "description": "A response to a request that indicates an error occurred.", - "properties": { - "error": { - "$ref": "#/$defs/Error" - }, - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - } - }, - "required": [ - "error", - "jsonrpc" - ], - "type": "object" - }, - "JSONRPCMessage": { - "anyOf": [ - { - "$ref": "#/$defs/JSONRPCRequest" - }, - { - "$ref": "#/$defs/JSONRPCNotification" - }, - { - "$ref": "#/$defs/JSONRPCResultResponse" - }, - { - "$ref": "#/$defs/JSONRPCErrorResponse" - } - ], - "description": "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent." - }, - "JSONRPCNotification": { - "description": "A notification which does not expect a response.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "type": "object" - } - }, - "required": [ - "jsonrpc", - "method" - ], - "type": "object" - }, - "JSONRPCRequest": { - "description": "A request that expects a response.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "type": "object" - } - }, - "required": [ - "id", - "jsonrpc", - "method" - ], - "type": "object" - }, - "JSONRPCResponse": { - "anyOf": [ - { - "$ref": "#/$defs/JSONRPCResultResponse" - }, - { - "$ref": "#/$defs/JSONRPCErrorResponse" - } - ], - "description": "A response to a request, containing either the result or error." - }, - "JSONRPCResultResponse": { - "description": "A successful (non-error) response to a request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/$defs/Result" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "JSONValue": { - "anyOf": [ - { - "$ref": "#/$defs/JSONObject" - }, - { - "items": { - "$ref": "#/$defs/JSONValue" - }, - "type": "array" - }, - { - "type": [ - "string", - "integer", - "boolean" - ] - } - ] - }, - "LegacyTitledEnumSchema": { - "description": "Use {@link TitledSingleSelectEnumSchema} instead.\nThis interface will be removed in a future version.", - "properties": { - "default": { - "type": "string" - }, - "description": { - "type": "string" - }, - "enum": { - "items": { - "type": "string" - }, - "type": "array" - }, - "enumNames": { - "description": "(Legacy) Display names for enum values.\nNon-standard according to JSON schema 2020-12.", - "items": { - "type": "string" - }, - "type": "array" - }, - "title": { - "type": "string" - }, - "type": { - "const": "string", - "type": "string" - } - }, - "required": [ - "enum", - "type" - ], - "type": "object" - }, - "ListPromptsRequest": { - "description": "Sent from the client to request a list of prompts and prompt templates the server has.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "prompts/list", - "type": "string" - }, - "params": { - "$ref": "#/$defs/PaginatedRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "ListPromptsResult": { - "description": "The result returned by the server for a {@link ListPromptsRequestprompts/list} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "cacheScope": { - "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).", - "enum": [ - "private", - "public" - ], - "type": "string" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "prompts": { - "items": { - "$ref": "#/$defs/Prompt" - }, - "type": "array" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - }, - "ttlMs": { - "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "cacheScope", - "prompts", - "resultType", - "ttlMs" - ], - "type": "object" - }, - "ListPromptsResultResponse": { - "description": "A successful response from the server for a {@link ListPromptsRequestprompts/list} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/$defs/ListPromptsResult" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "ListResourceTemplatesRequest": { - "description": "Sent from the client to request a list of resource templates the server has.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "resources/templates/list", - "type": "string" - }, - "params": { - "$ref": "#/$defs/PaginatedRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "ListResourceTemplatesResult": { - "description": "The result returned by the server for a {@link ListResourceTemplatesRequestresources/templates/list} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "cacheScope": { - "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).", - "enum": [ - "private", - "public" - ], - "type": "string" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "resourceTemplates": { - "items": { - "$ref": "#/$defs/ResourceTemplate" - }, - "type": "array" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - }, - "ttlMs": { - "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "cacheScope", - "resourceTemplates", - "resultType", - "ttlMs" - ], - "type": "object" - }, - "ListResourceTemplatesResultResponse": { - "description": "A successful response from the server for a {@link ListResourceTemplatesRequestresources/templates/list} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/$defs/ListResourceTemplatesResult" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "ListResourcesRequest": { - "description": "Sent from the client to request a list of resources the server has.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "resources/list", - "type": "string" - }, - "params": { - "$ref": "#/$defs/PaginatedRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "ListResourcesResult": { - "description": "The result returned by the server for a {@link ListResourcesRequestresources/list} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "cacheScope": { - "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).", - "enum": [ - "private", - "public" - ], - "type": "string" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "resources": { - "items": { - "$ref": "#/$defs/Resource" - }, - "type": "array" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - }, - "ttlMs": { - "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "cacheScope", - "resources", - "resultType", - "ttlMs" - ], - "type": "object" - }, - "ListResourcesResultResponse": { - "description": "A successful response from the server for a {@link ListResourcesRequestresources/list} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/$defs/ListResourcesResult" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "ListRootsRequest": { - "description": "Sent from the server to request a list of root URIs from the client. Roots allow\nservers to ask for specific directories or files to operate on. A common example\nfor roots is providing a set of repositories or directories a server should operate\non.\n\nThis request is typically used when the server needs to understand the file system\nstructure or access specific locations that the client has permission to read from.", - "properties": { - "method": { - "const": "roots/list", - "type": "string" - }, - "params": { - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - } - }, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "ListRootsResult": { - "description": "The result returned by the client for a {@link ListRootsRequestroots/list} request.\nThis result contains an array of {@link Root} objects, each representing a root directory\nor file that the server can operate on.", - "properties": { - "roots": { - "items": { - "$ref": "#/$defs/Root" - }, - "type": "array" - } - }, - "required": [ - "roots" - ], - "type": "object" - }, - "ListToolsRequest": { - "description": "Sent from the client to request a list of tools the server has.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "tools/list", - "type": "string" - }, - "params": { - "$ref": "#/$defs/PaginatedRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "ListToolsResult": { - "description": "The result returned by the server for a {@link ListToolsRequesttools/list} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "cacheScope": { - "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).", - "enum": [ - "private", - "public" - ], - "type": "string" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - }, - "tools": { - "items": { - "$ref": "#/$defs/Tool" - }, - "type": "array" - }, - "ttlMs": { - "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "cacheScope", - "resultType", - "tools", - "ttlMs" - ], - "type": "object" - }, - "ListToolsResultResponse": { - "description": "A successful response from the server for a {@link ListToolsRequesttools/list} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/$defs/ListToolsResult" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "LoggingLevel": { - "description": "The severity of a log message.\n\nThese map to syslog message severities, as specified in RFC-5424:\nhttps://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1", - "enum": [ - "alert", - "critical", - "debug", - "emergency", - "error", - "info", - "notice", - "warning" - ], - "type": "string" - }, - "LoggingMessageNotification": { - "description": "JSONRPCNotification of a log message passed from server to client. The client opts in by setting `\"io.modelcontextprotocol/logLevel\"` in a request's `_meta`.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/message", - "type": "string" - }, - "params": { - "$ref": "#/$defs/LoggingMessageNotificationParams" - } - }, - "required": [ - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "LoggingMessageNotificationParams": { - "description": "Parameters for a `notifications/message` notification.", - "properties": { - "_meta": { - "$ref": "#/$defs/NotificationMetaObject" - }, - "data": { - "description": "The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here." - }, - "level": { - "$ref": "#/$defs/LoggingLevel", - "description": "The severity of this log message." - }, - "logger": { - "description": "An optional name of the logger issuing this message.", - "type": "string" - } - }, - "required": [ - "data", - "level" - ], - "type": "object" - }, - "MetaObject": { - "description": "Represents the contents of a `_meta` field, which clients and servers use to attach additional metadata to their interactions.\n\nCertain key names are reserved by MCP for protocol-level metadata; implementations MUST NOT make assumptions about values at these keys. Additionally, specific schema definitions may reserve particular names for purpose-specific metadata, as declared in those definitions.\n\nValid keys have two segments:\n\n**Prefix:**\n- Optional — if specified, MUST be a series of _labels_ separated by dots (`.`), followed by a slash (`/`).\n- Labels MUST start with a letter and end with a letter or digit. Interior characters may be letters, digits, or hyphens (`-`).\n- Implementations SHOULD use reverse DNS notation (e.g., `com.example/` rather than `example.com/`).\n- Any prefix where the second label is `modelcontextprotocol` or `mcp` is **reserved** for MCP use. For example: `io.modelcontextprotocol/`, `dev.mcp/`, `org.modelcontextprotocol.api/`, and `com.mcp.tools/` are all reserved. However, `com.example.mcp/` is NOT reserved, as the second label is `example`.\n\n**Name:**\n- Unless empty, MUST start and end with an alphanumeric character (`[a-z0-9A-Z]`).\n- Interior characters may be alphanumeric, hyphens (`-`), underscores (`_`), or dots (`.`).", - "type": "object" - }, - "MethodNotFoundError": { - "description": "A JSON-RPC error indicating that the requested method does not exist or is not available.\n\nIn MCP, a server returns this error when a client invokes a method the server does not implement — either a genuinely unknown method, or one gated behind a server capability the server did not advertise (e.g., calling `prompts/list` when the `prompts` capability was not advertised).\n\nA request that requires a client capability the client did not declare is signalled instead by {@link MissingRequiredClientCapabilityError} (`-32021`).", - "properties": { - "code": { - "const": -32601, - "description": "The error type that occurred.", - "type": "integer" - }, - "data": { - "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." - }, - "message": { - "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", - "type": "string" - } - }, - "required": [ - "code", - "message" - ], - "type": "object" - }, - "MissingRequiredClientCapabilityError": { - "description": "Returned when processing a request requires a capability the client did not\ndeclare in `clientCapabilities`. For HTTP, the response status code MUST be\n`400 Bad Request`.", - "properties": { - "error": { - "allOf": [ - { - "$ref": "#/$defs/Error" - }, - { - "properties": { - "code": { - "const": -32021, - "type": "integer" - }, - "data": { - "properties": { - "requiredCapabilities": { - "$ref": "#/$defs/ClientCapabilities", - "description": "The capabilities the server requires from the client to process this request." - } - }, - "required": [ - "requiredCapabilities" - ], - "type": "object" - } - }, - "required": [ - "code", - "data" - ], - "type": "object" - } - ] - }, - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - } - }, - "required": [ - "error", - "jsonrpc" - ], - "type": "object" - }, - "ModelHint": { - "description": "Hints to use for model selection.\n\nKeys not declared here are currently left unspecified by the spec and are up\nto the client to interpret.", - "properties": { - "name": { - "description": "A hint for a model name.\n\nThe client SHOULD treat this as a substring of a model name; for example:\n - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n - `claude` should match any Claude model\n\nThe client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example:\n - `gemini-1.5-flash` could match `claude-3-haiku-20240307`", - "type": "string" - } - }, - "type": "object" - }, - "ModelPreferences": { - "description": "The server's preferences for model selection, requested of the client during sampling.\n\nBecause LLMs can vary along multiple dimensions, choosing the \"best\" model is\nrarely straightforward. Different models excel in different areas—some are\nfaster but less capable, others are more capable but more expensive, and so\non. This interface allows servers to express their priorities across multiple\ndimensions to help clients make an appropriate selection for their use case.\n\nThese preferences are always advisory. The client MAY ignore them. It is also\nup to the client to decide how to interpret these preferences and how to\nbalance them against other considerations.", - "properties": { - "costPriority": { - "description": "How much to prioritize cost when selecting a model. A value of 0 means cost\nis not important, while a value of 1 means cost is the most important\nfactor.", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "hints": { - "description": "Optional hints to use for model selection.\n\nIf multiple hints are specified, the client MUST evaluate them in order\n(such that the first match is taken).\n\nThe client SHOULD prioritize these hints over the numeric priorities, but\nMAY still use the priorities to select from ambiguous matches.", - "items": { - "$ref": "#/$defs/ModelHint" - }, - "type": "array" - }, - "intelligencePriority": { - "description": "How much to prioritize intelligence and capabilities when selecting a\nmodel. A value of 0 means intelligence is not important, while a value of 1\nmeans intelligence is the most important factor.", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "speedPriority": { - "description": "How much to prioritize sampling speed (latency) when selecting a model. A\nvalue of 0 means speed is not important, while a value of 1 means speed is\nthe most important factor.", - "maximum": 1, - "minimum": 0, - "type": "number" - } - }, - "type": "object" - }, - "MultiSelectEnumSchema": { - "anyOf": [ - { - "$ref": "#/$defs/UntitledMultiSelectEnumSchema" - }, - { - "$ref": "#/$defs/TitledMultiSelectEnumSchema" - } - ] - }, - "Notification": { - "properties": { - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "NotificationMetaObject": { - "description": "Extends {@link MetaObject} with additional notification-specific fields. All key naming rules from `MetaObject` apply.", - "properties": { - "io.modelcontextprotocol/subscriptionId": { - "$ref": "#/$defs/RequestId", - "description": "Identifies the subscription stream a notification was delivered on. The\nserver MUST include this key on every notification delivered via a\n{@link SubscriptionsListenRequestsubscriptions/listen} stream, so the\nclient can correlate the notification with the originating subscription.\nThe key is absent on notifications not delivered via a subscription\nstream (e.g. progress notifications for an in-flight request), which is\nwhy it is optional here.\n\nThe value is the JSON-RPC ID of the `subscriptions/listen` request that\nopened the stream." - } - }, - "type": "object" - }, - "NotificationParams": { - "description": "Common params for any notification.", - "properties": { - "_meta": { - "$ref": "#/$defs/NotificationMetaObject" - } - }, - "type": "object" - }, - "NumberSchema": { - "properties": { - "default": { - "type": "number" - }, - "description": { - "type": "string" - }, - "maximum": { - "type": "number" - }, - "minimum": { - "type": "number" - }, - "title": { - "type": "string" - }, - "type": { - "enum": [ - "integer", - "number" - ], - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "PaginatedRequest": { - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "type": "string" - }, - "params": { - "$ref": "#/$defs/PaginatedRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "PaginatedRequestParams": { - "description": "Common params for paginated requests.", - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - }, - "cursor": { - "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", - "type": "string" - } - }, - "required": [ - "_meta" - ], - "type": "object" - }, - "PaginatedResult": { - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "nextCursor": { - "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", - "type": "string" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - } - }, - "required": [ - "resultType" - ], - "type": "object" - }, - "ParseError": { - "description": "A JSON-RPC error indicating that invalid JSON was received by the server. This error is returned when the server cannot parse the JSON text of a message.", - "properties": { - "code": { - "const": -32700, - "description": "The error type that occurred.", - "type": "integer" - }, - "data": { - "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." - }, - "message": { - "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", - "type": "string" - } - }, - "required": [ - "code", - "message" - ], - "type": "object" - }, - "PrimitiveSchemaDefinition": { - "anyOf": [ - { - "$ref": "#/$defs/StringSchema" - }, - { - "$ref": "#/$defs/NumberSchema" - }, - { - "$ref": "#/$defs/BooleanSchema" - }, - { - "$ref": "#/$defs/UntitledSingleSelectEnumSchema" - }, - { - "$ref": "#/$defs/TitledSingleSelectEnumSchema" - }, - { - "$ref": "#/$defs/UntitledMultiSelectEnumSchema" - }, - { - "$ref": "#/$defs/TitledMultiSelectEnumSchema" - }, - { - "$ref": "#/$defs/LegacyTitledEnumSchema" - } - ], - "description": "Restricted schema definitions that only allow primitive types\nwithout nested objects or arrays." - }, - "ProgressNotification": { - "description": "An out-of-band notification used to inform the receiver of a progress update for a long-running request.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/progress", - "type": "string" - }, - "params": { - "$ref": "#/$defs/ProgressNotificationParams" - } - }, - "required": [ - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "ProgressNotificationParams": { - "description": "Parameters for a {@link ProgressNotificationnotifications/progress} notification.", - "properties": { - "_meta": { - "$ref": "#/$defs/NotificationMetaObject" - }, - "message": { - "description": "An optional message describing the current progress.", - "type": "string" - }, - "progress": { - "description": "The progress thus far. This should increase every time progress is made, even if the total is unknown.", - "type": "number" - }, - "progressToken": { - "$ref": "#/$defs/ProgressToken", - "description": "The progress token which was given in the initial request, used to associate this notification with the request that is proceeding." - }, - "total": { - "description": "Total number of items to process (or total progress required), if known.", - "type": "number" - } - }, - "required": [ - "progress", - "progressToken" - ], - "type": "object" - }, - "ProgressToken": { - "description": "A progress token, used to associate progress notifications with the original request.", - "type": [ - "string", - "integer" - ] - }, - "Prompt": { - "description": "A prompt or prompt template that the server offers.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "arguments": { - "description": "A list of arguments to use for templating the prompt.", - "items": { - "$ref": "#/$defs/PromptArgument" - }, - "type": "array" - }, - "description": { - "description": "An optional description of what this prompt provides", - "type": "string" - }, - "icons": { - "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", - "items": { - "$ref": "#/$defs/Icon" - }, - "type": "array" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "PromptArgument": { - "description": "Describes an argument that a prompt can accept.", - "properties": { - "description": { - "description": "A human-readable description of the argument.", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "required": { - "description": "Whether this argument must be provided.", - "type": "boolean" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "PromptListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This is only delivered on a {@link SubscriptionsListenRequestsubscriptions/listen} stream when the client requested it via the `promptsListChanged` filter field.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/prompts/list_changed", - "type": "string" - }, - "params": { - "$ref": "#/$defs/NotificationParams" - } - }, - "required": [ - "jsonrpc", - "method" - ], - "type": "object" - }, - "PromptMessage": { - "description": "Describes a message returned as part of a prompt.\n\nThis is similar to {@link SamplingMessage}, but also supports the embedding of\nresources from the MCP server.", - "properties": { - "content": { - "$ref": "#/$defs/ContentBlock" - }, - "role": { - "$ref": "#/$defs/Role" - } - }, - "required": [ - "content", - "role" - ], - "type": "object" - }, - "PromptReference": { - "description": "Identifies a prompt.", - "properties": { - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "type": { - "const": "ref/prompt", - "type": "string" - } - }, - "required": [ - "name", - "type" - ], - "type": "object" - }, - "ReadResourceRequest": { - "description": "Sent from the client to the server, to read a specific resource URI.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "resources/read", - "type": "string" - }, - "params": { - "$ref": "#/$defs/ReadResourceRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "ReadResourceRequestParams": { - "description": "Parameters for a `resources/read` request.", - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - }, - "inputResponses": { - "$ref": "#/$defs/InputResponses" - }, - "requestState": { - "type": "string" - }, - "uri": { - "description": "The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "_meta", - "uri" - ], - "type": "object" - }, - "ReadResourceResult": { - "description": "The result returned by the server for a {@link ReadResourceRequestresources/read} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "cacheScope": { - "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).", - "enum": [ - "private", - "public" - ], - "type": "string" - }, - "contents": { - "items": { - "anyOf": [ - { - "$ref": "#/$defs/TextResourceContents" - }, - { - "$ref": "#/$defs/BlobResourceContents" - } - ] - }, - "type": "array" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - }, - "ttlMs": { - "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "cacheScope", - "contents", - "resultType", - "ttlMs" - ], - "type": "object" - }, - "ReadResourceResultResponse": { - "description": "A successful response from the server for a {@link ReadResourceRequestresources/read} request.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "anyOf": [ - { - "$ref": "#/$defs/InputRequiredResult" - }, - { - "$ref": "#/$defs/ReadResourceResult" - } - ] - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "Request": { - "properties": { - "method": { - "type": "string" - }, - "params": { - "additionalProperties": {}, - "type": "object" - } - }, - "required": [ - "method" - ], - "type": "object" - }, - "RequestId": { - "description": "A uniquely identifying ID for a request in JSON-RPC.", - "type": [ - "string", - "integer" - ] - }, - "RequestMetaObject": { - "description": "Extends {@link MetaObject} with additional request-specific fields. All key naming rules from `MetaObject` apply.", - "properties": { - "io.modelcontextprotocol/clientCapabilities": { - "$ref": "#/$defs/ClientCapabilities", - "description": "The client's capabilities for this specific request. Required.\n\nCapabilities are declared per-request rather than once at initialization;\nan empty object means the client supports no optional capabilities.\nServers MUST NOT infer capabilities from prior requests." - }, - "io.modelcontextprotocol/clientInfo": { - "$ref": "#/$defs/Implementation", - "description": "Identifies the client software making the request. Clients SHOULD\ninclude this field on every request unless specifically configured not\nto do so.\n\nThe {@link Implementation} schema requires `name` and `version`; other\nfields are optional.\n\nThe value is self-reported by the client and is not verified by the\nprotocol. It is intended for display, logging, and debugging. Servers\nSHOULD NOT use it to change their behavior, and SHOULD NOT rely on it for\nsecurity decisions." - }, - "io.modelcontextprotocol/logLevel": { - "$ref": "#/$defs/LoggingLevel", - "description": "The desired log level for this request. Optional.\n\nIf absent, the server MUST NOT send any {@link LoggingMessageNotificationnotifications/message}\nnotifications for this request. The client opts in to log messages by\nexplicitly setting a level. Replaces the former `logging/setLevel` RPC." - }, - "io.modelcontextprotocol/protocolVersion": { - "description": "The MCP Protocol Version being used for this request. Required.\n\nFor the HTTP transport, this value MUST match the `MCP-Protocol-Version`\nheader; otherwise the server MUST return a `400 Bad Request`. If the\nserver does not support the requested version, it MUST return an\n{@link UnsupportedProtocolVersionError}.", - "type": "string" - }, - "progressToken": { - "$ref": "#/$defs/ProgressToken", - "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by {@link ProgressNotificationnotifications/progress}). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." - } - }, - "required": [ - "io.modelcontextprotocol/clientCapabilities", - "io.modelcontextprotocol/protocolVersion" - ], - "type": "object" - }, - "RequestParams": { - "description": "Common params for any request.", - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - } - }, - "required": [ - "_meta" - ], - "type": "object" - }, - "Resource": { - "description": "A known resource that the server is capable of reading.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "annotations": { - "$ref": "#/$defs/Annotations", - "description": "Optional annotations for the client." - }, - "description": { - "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "icons": { - "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", - "items": { - "$ref": "#/$defs/Icon" - }, - "type": "array" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "size": { - "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.", - "type": "integer" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "name", - "uri" - ], - "type": "object" - }, - "ResourceContents": { - "description": "The contents of a specific resource or sub-resource.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - }, - "ResourceLink": { - "description": "A resource that the server is capable of reading, included in a prompt or tool call result.\n\nNote: resource links returned by tools are not guaranteed to appear in the results of {@link ListResourcesRequestresources/list} requests.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "annotations": { - "$ref": "#/$defs/Annotations", - "description": "Optional annotations for the client." - }, - "description": { - "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "icons": { - "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", - "items": { - "$ref": "#/$defs/Icon" - }, - "type": "array" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "size": { - "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.", - "type": "integer" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "type": { - "const": "resource_link", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "name", - "type", - "uri" - ], - "type": "object" - }, - "ResourceListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This is only delivered on a {@link SubscriptionsListenRequestsubscriptions/listen} stream when the client requested it via the `resourcesListChanged` filter field.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/resources/list_changed", - "type": "string" - }, - "params": { - "$ref": "#/$defs/NotificationParams" - } - }, - "required": [ - "jsonrpc", - "method" - ], - "type": "object" - }, - "ResourceRequestParams": { - "description": "Common params for resource-related requests.", - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - }, - "uri": { - "description": "The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "_meta", - "uri" - ], - "type": "object" - }, - "ResourceTemplate": { - "description": "A template description for resources available on the server.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "annotations": { - "$ref": "#/$defs/Annotations", - "description": "Optional annotations for the client." - }, - "description": { - "description": "A description of what this template is for.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "icons": { - "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", - "items": { - "$ref": "#/$defs/Icon" - }, - "type": "array" - }, - "mimeType": { - "description": "The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.", - "type": "string" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - }, - "uriTemplate": { - "description": "A URI template (according to RFC 6570) that can be used to construct resource URIs.", - "format": "uri-template", - "type": "string" - } - }, - "required": [ - "name", - "uriTemplate" - ], - "type": "object" - }, - "ResourceTemplateReference": { - "description": "A reference to a resource or resource template definition.", - "properties": { - "type": { - "const": "ref/resource", - "type": "string" - }, - "uri": { - "description": "The URI or URI template of the resource.", - "format": "uri-template", - "type": "string" - } - }, - "required": [ - "type", - "uri" - ], - "type": "object" - }, - "ResourceUpdatedNotification": { - "description": "A notification from the server to the client, informing it that a resource has changed and may need to be read again. This is only sent for resources the client opted in to via the `resourceSubscriptions` field of a {@link SubscriptionsListenRequestsubscriptions/listen} request.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/resources/updated", - "type": "string" - }, - "params": { - "$ref": "#/$defs/ResourceUpdatedNotificationParams" - } - }, - "required": [ - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "ResourceUpdatedNotificationParams": { - "description": "Parameters for a `notifications/resources/updated` notification.", - "properties": { - "_meta": { - "$ref": "#/$defs/NotificationMetaObject" - }, - "uri": { - "description": "The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - }, - "Result": { - "additionalProperties": {}, - "description": "Common result fields.", - "properties": { - "_meta": { - "$ref": "#/$defs/ResultMetaObject" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - } - }, - "required": [ - "resultType" - ], - "type": "object" - }, - "ResultMetaObject": { - "description": "Extends {@link MetaObject} with additional result-specific fields. All key naming rules from `MetaObject` apply.", - "properties": { - "io.modelcontextprotocol/serverInfo": { - "$ref": "#/$defs/Implementation", - "description": "Identifies the server software producing the response. Servers SHOULD\ninclude this field on every response unless specifically configured not\nto do so.\n\nThe {@link Implementation} schema requires `name` and `version`; other\nfields are optional.\n\nThe value is self-reported by the server and is not verified by the\nprotocol. It is intended for display, logging, and debugging. Clients\nSHOULD NOT use it to change their behavior, and SHOULD NOT rely on it for\nsecurity decisions." - } - }, - "type": "object" - }, - "ResultType": { - "description": "Indicates the type of a {@link Result} object, allowing the client to\ndetermine how to parse the response.\n\ncomplete - the request completed successfully and the result contains the final content.\ninput_required - the request requires additional input and the result contains an {@link InputRequiredResult} object with instructions for the client to provide additional input before retrying the original request.", - "type": "string" - }, - "Role": { - "description": "The sender or recipient of messages and data in a conversation.", - "enum": [ - "assistant", - "user" - ], - "type": "string" - }, - "Root": { - "description": "Represents a root directory or file that the server can operate on.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "name": { - "description": "An optional name for the root. This can be used to provide a human-readable\nidentifier for the root, which may be useful for display purposes or for\nreferencing the root in other parts of the application.", - "type": "string" - }, - "uri": { - "description": "The URI identifying the root. This *must* start with `file://` for now.\nThis restriction may be relaxed in future versions of the protocol to allow\nother URI schemes.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "uri" - ], - "type": "object" - }, - "SamplingMessage": { - "description": "Describes a message issued to or received from an LLM API.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "content": { - "anyOf": [ - { - "$ref": "#/$defs/TextContent" - }, - { - "$ref": "#/$defs/ImageContent" - }, - { - "$ref": "#/$defs/AudioContent" - }, - { - "$ref": "#/$defs/ToolUseContent" - }, - { - "$ref": "#/$defs/ToolResultContent" - }, - { - "items": { - "$ref": "#/$defs/SamplingMessageContentBlock" - }, - "type": "array" - } - ] - }, - "role": { - "$ref": "#/$defs/Role" - } - }, - "required": [ - "content", - "role" - ], - "type": "object" - }, - "SamplingMessageContentBlock": { - "anyOf": [ - { - "$ref": "#/$defs/TextContent" - }, - { - "$ref": "#/$defs/ImageContent" - }, - { - "$ref": "#/$defs/AudioContent" - }, - { - "$ref": "#/$defs/ToolUseContent" - }, - { - "$ref": "#/$defs/ToolResultContent" - } - ] - }, - "ServerCapabilities": { - "description": "Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.", - "properties": { - "completions": { - "$ref": "#/$defs/JSONObject", - "description": "Present if the server supports argument autocompletion suggestions." - }, - "experimental": { - "additionalProperties": { - "$ref": "#/$defs/JSONObject" - }, - "description": "Experimental, non-standard capabilities that the server supports.", - "type": "object" - }, - "extensions": { - "additionalProperties": { - "$ref": "#/$defs/JSONObject" - }, - "description": "Optional MCP extensions that the server supports. Keys are extension identifiers\n(e.g., \"io.modelcontextprotocol/tasks\"), and values are per-extension settings\nobjects. An empty object indicates support with no settings.\n\nKeys MUST follow the {@link MetaObject`_meta` key naming rules}, with a\nmandatory prefix.", - "type": "object" - }, - "logging": { - "$ref": "#/$defs/JSONObject", - "description": "Present if the server supports sending log messages to the client." - }, - "prompts": { - "description": "Present if the server offers any prompt templates.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the prompt list.", - "type": "boolean" - } - }, - "type": "object" - }, - "resources": { - "description": "Present if the server offers any resources to read.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the resource list.", - "type": "boolean" - }, - "subscribe": { - "description": "Whether this server supports subscribing to resource updates.", - "type": "boolean" - } - }, - "type": "object" - }, - "tools": { - "description": "Present if the server offers any tools to call.", - "properties": { - "listChanged": { - "description": "Whether this server supports notifications for changes to the tool list.", - "type": "boolean" - } - }, - "type": "object" - } - }, - "type": "object" - }, - "ServerNotification": { - "anyOf": [ - { - "$ref": "#/$defs/CancelledNotification" - }, - { - "$ref": "#/$defs/ProgressNotification" - }, - { - "$ref": "#/$defs/ResourceListChangedNotification" - }, - { - "$ref": "#/$defs/SubscriptionsAcknowledgedNotification" - }, - { - "$ref": "#/$defs/ResourceUpdatedNotification" - }, - { - "$ref": "#/$defs/PromptListChangedNotification" - }, - { - "$ref": "#/$defs/ToolListChangedNotification" - }, - { - "$ref": "#/$defs/LoggingMessageNotification" - } - ] - }, - "ServerResult": { - "anyOf": [ - { - "$ref": "#/$defs/Result" - }, - { - "$ref": "#/$defs/InputRequiredResult" - }, - { - "$ref": "#/$defs/DiscoverResult" - }, - { - "$ref": "#/$defs/ListResourcesResult" - }, - { - "$ref": "#/$defs/ListResourceTemplatesResult" - }, - { - "$ref": "#/$defs/ReadResourceResult" - }, - { - "$ref": "#/$defs/SubscriptionsListenResult" - }, - { - "$ref": "#/$defs/ListPromptsResult" - }, - { - "$ref": "#/$defs/GetPromptResult" - }, - { - "$ref": "#/$defs/ListToolsResult" - }, - { - "$ref": "#/$defs/CallToolResult" - }, - { - "$ref": "#/$defs/CompleteResult" - } - ] - }, - "SingleSelectEnumSchema": { - "anyOf": [ - { - "$ref": "#/$defs/UntitledSingleSelectEnumSchema" - }, - { - "$ref": "#/$defs/TitledSingleSelectEnumSchema" - } - ] - }, - "StringSchema": { - "properties": { - "default": { - "type": "string" - }, - "description": { - "type": "string" - }, - "format": { - "enum": [ - "date", - "date-time", - "email", - "uri" - ], - "type": "string" - }, - "maxLength": { - "type": "integer" - }, - "minLength": { - "type": "integer" - }, - "title": { - "type": "string" - }, - "type": { - "const": "string", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "SubscriptionFilter": { - "description": "The set of notification types a client may opt in to on a\n{@link SubscriptionsListenRequestsubscriptions/listen} request.\n\nEach notification type is **opt-in**; the server **MUST NOT** send\nnotification types the client has not explicitly requested here.", - "properties": { - "promptsListChanged": { - "description": "If true, receive {@link PromptListChangedNotificationnotifications/prompts/list_changed}.", - "type": "boolean" - }, - "resourceSubscriptions": { - "description": "Subscribe to {@link ResourceUpdatedNotificationnotifications/resources/updated} for these resource URIs.\nReplaces the former `resources/subscribe` RPC.", - "items": { - "type": "string" - }, - "type": "array" - }, - "resourcesListChanged": { - "description": "If true, receive {@link ResourceListChangedNotificationnotifications/resources/list_changed}.", - "type": "boolean" - }, - "toolsListChanged": { - "description": "If true, receive {@link ToolListChangedNotificationnotifications/tools/list_changed}.", - "type": "boolean" - } - }, - "type": "object" - }, - "SubscriptionsAcknowledgedNotification": { - "description": "Sent by the server to acknowledge that a\n{@link SubscriptionsListenRequestsubscriptions/listen} subscription has been\nestablished and to report which notification types it agreed to honor.\n\nThis notification MUST be the first message the server sends carrying the\nsubscription's ID in `io.modelcontextprotocol/subscriptionId`. The server MUST\nNOT send any notification on the subscription before acknowledging it. On\nstdio, where every subscription shares one channel, this ordering is defined\nper subscription ID and not per channel: messages belonging to other\nsubscriptions MAY be interleaved before it.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/subscriptions/acknowledged", - "type": "string" - }, - "params": { - "$ref": "#/$defs/SubscriptionsAcknowledgedNotificationParams" - } - }, - "required": [ - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "SubscriptionsAcknowledgedNotificationParams": { - "description": "Parameters for a {@link SubscriptionsAcknowledgedNotificationnotifications/subscriptions/acknowledged} notification.", - "properties": { - "_meta": { - "$ref": "#/$defs/NotificationMetaObject" - }, - "notifications": { - "$ref": "#/$defs/SubscriptionFilter", - "description": "The subset of requested notification types the server agreed to honor.\nOnly includes notification types the server actually supports; if the\nclient requested an unsupported type (e.g., `promptsListChanged` when\nthe server has no prompts), it is omitted from this set." - } - }, - "required": [ - "notifications" - ], - "type": "object" - }, - "SubscriptionsListenRequest": { - "description": "Sent from the client to open a long-lived channel for receiving notifications\noutside the context of a specific request. Replaces the previous HTTP GET\nendpoint and ensures consistent behavior between HTTP and STDIO.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "subscriptions/listen", - "type": "string" - }, - "params": { - "$ref": "#/$defs/SubscriptionsListenRequestParams" - } - }, - "required": [ - "id", - "jsonrpc", - "method", - "params" - ], - "type": "object" - }, - "SubscriptionsListenRequestParams": { - "description": "Parameters for a {@link SubscriptionsListenRequestsubscriptions/listen} request.", - "properties": { - "_meta": { - "$ref": "#/$defs/RequestMetaObject" - }, - "notifications": { - "$ref": "#/$defs/SubscriptionFilter", - "description": "The notifications the client opts in to on this stream. The server\n**MUST NOT** send notification types the client has not explicitly\nrequested." - } - }, - "required": [ - "_meta", - "notifications" - ], - "type": "object" - }, - "SubscriptionsListenResult": { - "description": "The response to a {@link SubscriptionsListenRequestsubscriptions/listen}\nrequest, signalling that the subscription has ended gracefully (for example,\nduring server shutdown). Because the listen stream is long-lived, this result\nis sent only when the server tears the subscription down; an abrupt transport\nclose carries no response. The result body is otherwise empty.", - "properties": { - "_meta": { - "$ref": "#/$defs/SubscriptionsListenResultMetaObject" - }, - "resultType": { - "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.", - "type": "string" - } - }, - "required": [ - "_meta", - "resultType" - ], - "type": "object" - }, - "SubscriptionsListenResultMetaObject": { - "description": "Extends {@link ResultMetaObject} with the subscription-stream identifier carried by a\n{@link SubscriptionsListenResult}. All key naming rules from `MetaObject` apply.", - "properties": { - "io.modelcontextprotocol/serverInfo": { - "$ref": "#/$defs/Implementation", - "description": "Identifies the server software producing the response. Servers SHOULD\ninclude this field on every response unless specifically configured not\nto do so.\n\nThe {@link Implementation} schema requires `name` and `version`; other\nfields are optional.\n\nThe value is self-reported by the server and is not verified by the\nprotocol. It is intended for display, logging, and debugging. Clients\nSHOULD NOT use it to change their behavior, and SHOULD NOT rely on it for\nsecurity decisions." - }, - "io.modelcontextprotocol/subscriptionId": { - "$ref": "#/$defs/RequestId", - "description": "Identifies the subscription stream this response closes, so the client can\ncorrelate it with the originating subscription — mirroring the same key on\nthe stream's notifications. The value is the JSON-RPC ID of the\n`subscriptions/listen` request that opened the stream (and equals this\nresponse's `id`)." - } - }, - "required": [ - "io.modelcontextprotocol/subscriptionId" - ], - "type": "object" - }, - "SubscriptionsListenResultResponse": { - "description": "A successful response from the server for a {@link SubscriptionsListenRequestsubscriptions/listen}\nrequest, sent when the server tears the subscription down gracefully.", - "properties": { - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "result": { - "$ref": "#/$defs/SubscriptionsListenResult" - } - }, - "required": [ - "id", - "jsonrpc", - "result" - ], - "type": "object" - }, - "TextContent": { - "description": "Text provided to or from an LLM.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "annotations": { - "$ref": "#/$defs/Annotations", - "description": "Optional annotations for the client." - }, - "text": { - "description": "The text content of the message.", - "type": "string" - }, - "type": { - "const": "text", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "type": "object" - }, - "TextResourceContents": { - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "mimeType": { - "description": "The MIME type of this resource, if known.", - "type": "string" - }, - "text": { - "description": "The text of the item. This must only be set if the item can actually be represented as text (not binary data).", - "type": "string" - }, - "uri": { - "description": "The URI of this resource.", - "format": "uri", - "type": "string" - } - }, - "required": [ - "text", - "uri" - ], - "type": "object" - }, - "TitledMultiSelectEnumSchema": { - "description": "Schema for multiple-selection enumeration with display titles for each option.", - "properties": { - "default": { - "description": "Optional default value.", - "items": { - "type": "string" - }, - "type": "array" - }, - "description": { - "description": "Optional description for the enum field.", - "type": "string" - }, - "items": { - "description": "Schema for array items with enum options and display labels.", - "properties": { - "anyOf": { - "description": "Array of enum options with values and display labels.", - "items": { - "properties": { - "const": { - "description": "The constant enum value.", - "type": "string" - }, - "title": { - "description": "Display title for this option.", - "type": "string" - } - }, - "required": [ - "const", - "title" - ], - "type": "object" - }, - "type": "array" - } - }, - "required": [ - "anyOf" - ], - "type": "object" - }, - "maxItems": { - "description": "Maximum number of items to select.", - "type": "integer" - }, - "minItems": { - "description": "Minimum number of items to select.", - "type": "integer" - }, - "title": { - "description": "Optional title for the enum field.", - "type": "string" - }, - "type": { - "const": "array", - "type": "string" - } - }, - "required": [ - "items", - "type" - ], - "type": "object" - }, - "TitledSingleSelectEnumSchema": { - "description": "Schema for single-selection enumeration with display titles for each option.", - "properties": { - "default": { - "description": "Optional default value.", - "type": "string" - }, - "description": { - "description": "Optional description for the enum field.", - "type": "string" - }, - "oneOf": { - "description": "Array of enum options with values and display labels.", - "items": { - "properties": { - "const": { - "description": "The enum value.", - "type": "string" - }, - "title": { - "description": "Display label for this option.", - "type": "string" - } - }, - "required": [ - "const", - "title" - ], - "type": "object" - }, - "type": "array" - }, - "title": { - "description": "Optional title for the enum field.", - "type": "string" - }, - "type": { - "const": "string", - "type": "string" - } - }, - "required": [ - "oneOf", - "type" - ], - "type": "object" - }, - "Tool": { - "description": "Definition for a tool the client can call.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject" - }, - "annotations": { - "$ref": "#/$defs/ToolAnnotations", - "description": "Optional additional tool information.\n\nDisplay name precedence order is: `title`, `annotations.title`, then `name`." - }, - "description": { - "description": "A human-readable description of the tool.\n\nThis can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a \"hint\" to the model.", - "type": "string" - }, - "icons": { - "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", - "items": { - "$ref": "#/$defs/Icon" - }, - "type": "array" - }, - "inputSchema": { - "additionalProperties": {}, - "description": "A JSON Schema object defining the expected parameters for the tool.\n\nTool arguments are always JSON objects, so `type: \"object\"` is required at the root.\nBeyond that, any JSON Schema 2020-12 keyword may appear alongside `type` — including\ncomposition keywords (`oneOf`, `anyOf`, `allOf`, `not`), conditional keywords\n(`if`/`then`/`else`), reference keywords (`$ref`, `$defs`, `$anchor`), and any other\nstandard validation or annotation keywords.\n\nProperty schemas may carry an `x-mcp-header` annotation to mirror the\nargument value into an HTTP header on the Streamable HTTP transport. See\nthe Streamable HTTP transport specification for the validity and\nextraction rules.\n\nDefaults to JSON Schema 2020-12 when no explicit `$schema` is provided.", - "properties": { - "$schema": { - "type": "string" - }, - "type": { - "const": "object", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object" - }, - "name": { - "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", - "type": "string" - }, - "outputSchema": { - "additionalProperties": {}, - "description": "An optional JSON Schema object defining the structure of the tool's output returned in\nthe structuredContent field of a {@link CallToolResult}. This can be any valid JSON Schema 2020-12.\n\nDefaults to JSON Schema 2020-12 when no explicit `$schema` is provided.", - "properties": { - "$schema": { - "type": "string" - } - }, - "type": "object" - }, - "title": { - "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", - "type": "string" - } - }, - "required": [ - "inputSchema", - "name" - ], - "type": "object" - }, - "ToolAnnotations": { - "description": "Additional properties describing a {@link Tool} to clients.\n\nNOTE: all properties in `ToolAnnotations` are **hints**.\nThey are not guaranteed to provide a faithful description of\ntool behavior (including descriptive properties like `title`).\n\nClients should never make tool use decisions based on `ToolAnnotations`\nreceived from untrusted servers.", - "properties": { - "destructiveHint": { - "description": "If true, the tool may perform destructive updates to its environment.\nIf false, the tool performs only additive updates.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: true", - "type": "boolean" - }, - "idempotentHint": { - "description": "If true, calling the tool repeatedly with the same arguments\nwill have no additional effect on its environment.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: false", - "type": "boolean" - }, - "openWorldHint": { - "description": "If true, this tool may interact with an \"open world\" of external\nentities. If false, the tool's domain of interaction is closed.\nFor example, the world of a web search tool is open, whereas that\nof a memory tool is not.\n\nDefault: true", - "type": "boolean" - }, - "readOnlyHint": { - "description": "If true, the tool does not modify its environment.\n\nDefault: false", - "type": "boolean" - }, - "title": { - "description": "A human-readable title for the tool.", - "type": "string" - } - }, - "type": "object" - }, - "ToolChoice": { - "description": "Controls tool selection behavior for sampling requests.", - "properties": { - "mode": { - "description": "Controls the tool use ability of the model:\n- `\"auto\"`: Model decides whether to use tools (default)\n- `\"required\"`: Model MUST use at least one tool before completing\n- `\"none\"`: Model MUST NOT use any tools", - "enum": [ - "auto", - "none", - "required" - ], - "type": "string" - } - }, - "type": "object" - }, - "ToolListChangedNotification": { - "description": "An optional notification from the server to the client, informing it that the list of tools it offers has changed. This is only delivered on a {@link SubscriptionsListenRequestsubscriptions/listen} stream when the client requested it via the `toolsListChanged` filter field.", - "properties": { - "jsonrpc": { - "const": "2.0", - "type": "string" - }, - "method": { - "const": "notifications/tools/list_changed", - "type": "string" - }, - "params": { - "$ref": "#/$defs/NotificationParams" - } - }, - "required": [ - "jsonrpc", - "method" - ], - "type": "object" - }, - "ToolResultContent": { - "description": "The result of a tool use, provided by the user back to the assistant.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject", - "description": "Optional metadata about the tool result. Clients SHOULD preserve this field when\nincluding tool results in subsequent sampling requests to enable caching optimizations." - }, - "content": { - "description": "The unstructured result content of the tool use.\n\nThis has the same format as {@link CallToolResult.content} and can include text, images,\naudio, resource links, and embedded resources.", - "items": { - "$ref": "#/$defs/ContentBlock" - }, - "type": "array" - }, - "isError": { - "description": "Whether the tool use resulted in an error.\n\nIf true, the content typically describes the error that occurred.\nDefault: false", - "type": "boolean" - }, - "structuredContent": { - "description": "An optional structured result value.\n\nThis can be any JSON value (object, array, string, number, boolean, or null).\nIf the tool defined an {@link Tool.outputSchema}, this SHOULD conform to that schema." - }, - "toolUseId": { - "description": "The ID of the tool use this result corresponds to.\n\nThis MUST match the ID from a previous {@link ToolUseContent}.", - "type": "string" - }, - "type": { - "const": "tool_result", - "type": "string" - } - }, - "required": [ - "content", - "toolUseId", - "type" - ], - "type": "object" - }, - "ToolUseContent": { - "description": "A request from the assistant to call a tool.", - "properties": { - "_meta": { - "$ref": "#/$defs/MetaObject", - "description": "Optional metadata about the tool use. Clients SHOULD preserve this field when\nincluding tool uses in subsequent sampling requests to enable caching optimizations." - }, - "id": { - "description": "A unique identifier for this tool use.\n\nThis ID is used to match tool results to their corresponding tool uses.", - "type": "string" - }, - "input": { - "additionalProperties": {}, - "description": "The arguments to pass to the tool, conforming to the tool's input schema.", - "type": "object" - }, - "name": { - "description": "The name of the tool to call.", - "type": "string" - }, - "type": { - "const": "tool_use", - "type": "string" - } - }, - "required": [ - "id", - "input", - "name", - "type" - ], - "type": "object" - }, - "UnsupportedProtocolVersionError": { - "description": "Returned when the request's protocol version is unknown to the server or\nunsupported (e.g., a known experimental or draft version the server has\nchosen not to implement). For HTTP, the response status code MUST be\n`400 Bad Request`.", - "properties": { - "error": { - "allOf": [ - { - "$ref": "#/$defs/Error" - }, - { - "properties": { - "code": { - "const": -32022, - "type": "integer" - }, - "data": { - "properties": { - "requested": { - "description": "The protocol version that was requested by the client.", - "type": "string" - }, - "supported": { - "description": "Protocol versions the server supports. The client should choose a\nmutually supported version from this list and retry.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "requested", - "supported" - ], - "type": "object" - } - }, - "required": [ - "code", - "data" - ], - "type": "object" - } - ] - }, - "id": { - "$ref": "#/$defs/RequestId" - }, - "jsonrpc": { - "const": "2.0", - "type": "string" - } - }, - "required": [ - "error", - "jsonrpc" - ], - "type": "object" - }, - "UntitledMultiSelectEnumSchema": { - "description": "Schema for multiple-selection enumeration without display titles for options.", - "properties": { - "default": { - "description": "Optional default value.", - "items": { - "type": "string" - }, - "type": "array" - }, - "description": { - "description": "Optional description for the enum field.", - "type": "string" - }, - "items": { - "description": "Schema for the array items.", - "properties": { - "enum": { - "description": "Array of enum values to choose from.", - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "const": "string", - "type": "string" - } - }, - "required": [ - "enum", - "type" - ], - "type": "object" - }, - "maxItems": { - "description": "Maximum number of items to select.", - "type": "integer" - }, - "minItems": { - "description": "Minimum number of items to select.", - "type": "integer" - }, - "title": { - "description": "Optional title for the enum field.", - "type": "string" - }, - "type": { - "const": "array", - "type": "string" - } - }, - "required": [ - "items", - "type" - ], - "type": "object" - }, - "UntitledSingleSelectEnumSchema": { - "description": "Schema for single-selection enumeration without display titles for options.", - "properties": { - "default": { - "description": "Optional default value.", - "type": "string" - }, - "description": { - "description": "Optional description for the enum field.", - "type": "string" - }, - "enum": { - "description": "Array of enum values to choose from.", - "items": { - "type": "string" - }, - "type": "array" - }, - "title": { - "description": "Optional title for the enum field.", - "type": "string" - }, - "type": { - "const": "string", - "type": "string" - } - }, - "required": [ - "enum", - "type" - ], - "type": "object" - } - } -} - diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/docs-execute-sql-x-mcp-header.json b/crates/candler-schemas/tests/fixtures/spec/tools/docs-execute-sql-x-mcp-header.json deleted file mode 100644 index 00f74067..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/docs-execute-sql-x-mcp-header.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "execute_sql", - "description": "Execute SQL on Google Cloud Spanner", - "inputSchema": { - "type": "object", - "properties": { - "region": { - "type": "string", - "description": "The region to execute the query in", - "x-mcp-header": "Region" - }, - "query": { - "type": "string", - "description": "The SQL query to execute" - } - }, - "required": [ - "region", - "query" - ] - } -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/docs-get-weather-with-icons.json b/crates/candler-schemas/tests/fixtures/spec/tools/docs-get-weather-with-icons.json deleted file mode 100644 index cc8d19d1..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/docs-get-weather-with-icons.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "get_weather", - "title": "Weather Information Provider", - "description": "Get current weather information for a location", - "inputSchema": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "City name or zip code" - } - }, - "required": [ - "location" - ] - }, - "icons": [ - { - "src": "https://example.com/weather-icon.png", - "mimeType": "image/png", - "sizes": [ - "48x48" - ] - } - ] -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/docs-list-users-array-output.json b/crates/candler-schemas/tests/fixtures/spec/tools/docs-list-users-array-output.json deleted file mode 100644 index 559fd6d8..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/docs-list-users-array-output.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "list_users", - "title": "User List", - "description": "Returns a list of all users", - "inputSchema": { - "type": "object", - "properties": {} - }, - "outputSchema": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "email": { - "type": "string" - } - }, - "required": [ - "id", - "name", - "email" - ] - } - } -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/full.json b/crates/candler-schemas/tests/fixtures/spec/tools/full.json deleted file mode 100644 index 6be94f8c..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/full.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "name": "search_documents", - "title": "Document Search", - "description": "Search the document index and return the best matches", - "inputSchema": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Search text" - }, - "limit": { - "type": "integer", - "minimum": 1, - "maximum": 50, - "default": 10 - } - }, - "required": [ - "query" - ] - }, - "outputSchema": { - "type": "object", - "properties": { - "hits": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "score": { - "type": "number" - } - }, - "required": [ - "id", - "score" - ] - } - }, - "total": { - "type": "integer" - } - }, - "required": [ - "hits", - "total" - ] - }, - "annotations": { - "title": "Search documents", - "readOnlyHint": true, - "destructiveHint": false, - "idempotentHint": true, - "openWorldHint": false - }, - "icons": [ - { - "src": "https://example.com/search-light.png", - "mimeType": "image/png", - "sizes": [ - "48x48", - "96x96" - ], - "theme": "light" - }, - { - "src": "https://example.com/search-dark.svg", - "mimeType": "image/svg+xml", - "sizes": [ - "any" - ], - "theme": "dark" - } - ], - "_meta": { - "com.example/index": "documents-v2", - "com.example/cost": { - "credits": 1 - } - } -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/tool-with-array-output-schema.json b/crates/candler-schemas/tests/fixtures/spec/tools/tool-with-array-output-schema.json deleted file mode 100644 index 8c7edec6..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/tool-with-array-output-schema.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "list_users", - "title": "User List", - "description": "Returns a list of all users", - "inputSchema": { - "type": "object", - "properties": {} - }, - "outputSchema": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "User ID" - }, - "name": { - "type": "string", - "description": "User name" - }, - "email": { - "type": "string", - "description": "User email" - } - }, - "required": ["id", "name", "email"] - } - } -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/tool-with-composition-input-schema.json b/crates/candler-schemas/tests/fixtures/spec/tools/tool-with-composition-input-schema.json deleted file mode 100644 index 7c7253af..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/tool-with-composition-input-schema.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "find_resource", - "title": "Resource Finder", - "description": "Find a resource by ID or name", - "inputSchema": { - "type": "object", - "oneOf": [ - { - "properties": { - "id": { - "type": "string", - "description": "Resource ID" - } - }, - "required": ["id"] - }, - { - "properties": { - "name": { - "type": "string", - "description": "Resource name" - } - }, - "required": ["name"] - } - ] - } -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/with-default-2020-12-input-schema.json b/crates/candler-schemas/tests/fixtures/spec/tools/with-default-2020-12-input-schema.json deleted file mode 100644 index d79a00ee..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/with-default-2020-12-input-schema.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "calculate_sum", - "description": "Add two numbers", - "inputSchema": { - "type": "object", - "properties": { - "a": { "type": "number" }, - "b": { "type": "number" } - }, - "required": ["a", "b"] - } -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/with-explicit-draft-07-input-schema.json b/crates/candler-schemas/tests/fixtures/spec/tools/with-explicit-draft-07-input-schema.json deleted file mode 100644 index 698d95b8..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/with-explicit-draft-07-input-schema.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "calculate_sum", - "description": "Add two numbers", - "inputSchema": { - "$schema": "http://json-schema.org/draft-07/schema#", - "type": "object", - "properties": { - "a": { "type": "number" }, - "b": { "type": "number" } - }, - "required": ["a", "b"] - } -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/with-no-parameters.json b/crates/candler-schemas/tests/fixtures/spec/tools/with-no-parameters.json deleted file mode 100644 index 04a3a4e9..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/with-no-parameters.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "get_current_time", - "description": "Returns the current server time", - "inputSchema": { - "type": "object", - "additionalProperties": false - } -} diff --git a/crates/candler-schemas/tests/fixtures/spec/tools/with-output-schema-for-structured-content.json b/crates/candler-schemas/tests/fixtures/spec/tools/with-output-schema-for-structured-content.json deleted file mode 100644 index a1469834..00000000 --- a/crates/candler-schemas/tests/fixtures/spec/tools/with-output-schema-for-structured-content.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "get_weather_data", - "title": "Weather Data Retriever", - "description": "Get current weather data for a location", - "inputSchema": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "City name or zip code" - } - }, - "required": ["location"] - }, - "outputSchema": { - "type": "object", - "properties": { - "temperature": { - "type": "number", - "description": "Temperature in celsius" - }, - "conditions": { - "type": "string", - "description": "Weather conditions description" - }, - "humidity": { - "type": "number", - "description": "Humidity percentage" - } - }, - "required": ["temperature", "conditions", "humidity"] - } -} diff --git a/crates/candler-schemas/tests/fixtures/upstream/README.md b/crates/candler-schemas/tests/fixtures/upstream/README.md deleted file mode 100644 index 8d8e43b3..00000000 --- a/crates/candler-schemas/tests/fixtures/upstream/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# Upstream catalog snapshots - -Two tool-catalog snapshots captured from real MCP servers, in HTN's `tool-catalog-snapshot/0` -shape (`servers_dir` and `stubbed_modules` at the top level). They are inputs to the catalog tests, -which convert them to the `/1` shape in the test; the files themselves are verbatim. - -Source repository: `mcp-python-ingestion` (`/Users/hacker/Documents/src/External/PCfVW/mcp-python-ingestion`), -licence Apache-2.0. - -## `rikyu_mcp.json` - -| | | -|---|---| -| Tag | `htn-creator-eval@0.4.2` | -| Commit | `28be2c158fbc6ee786a789242c2d8fd47bfde9a8` | -| Path | `.claude/skills/htn-creator-workspace/infrastructure/htn_creator_eval/catalogs/rikyu_mcp.json` | -| Blob | `c3a1206abf4507cab53cd3f41ff6ffa4967e1757` | -| SHA-256 | `8e331d938505087e34839ba8d8d0b596032041af2dd1710315684c8d39f5b438` | -| Servers | `rikyu-hpc` (26 tools), `rikyu-docs` (3 tools) | -| Captured | `2026-10-28T01:09:04+00:00`, python 3.12.12, hpc-agent-core 0.5.0, mcp 2.0.0, pydantic 2.13.4 | - -Copied byte for byte (`git show 'htn-creator-eval@0.4.2:<path>'`). Server sources, at the same -commit, under `.claude/skills/htn-creator-workspace/servers/rikyu_mcp/`: - -| Source | Blob | Digest recorded in the snapshot | -|---|---|---| -| `hpc_server.py` | `60baf22df5deaaf46e18ac7febe6a964ebce3727` | `sha256:b2af8a23ff6f5ceef36217b7727bf515fbf345472d81e1872bbed43b57e55b4b` | -| `docs_server.py` | `0b75ec4fb499ebe98d95d70aa5285c8f367a9d1d` | `sha256:527acd8f431571903257dd51578b2a21bf8bb27b20d274e6fdfe82169968d638` | - -The capture command is in the docstring of the capture script (below). - -## `bio_opentrons.json` - -| | | -|---|---| -| Servers | `gripper-server` (1 tool), `liquid-server` (10), `module-server` (19), `movement-server` (6) | -| Server sources | `.claude/skills/htn-creator-workspace/servers/bio-opentrons/` at tag `htn-creator-eval@0.4.2` (`28be2c158fbc6ee786a789242c2d8fd47bfde9a8`) | -| Captured | `2026-10-28T15:10:36+00:00`, python 3.12.12, mcp 1.28.1, pydantic 2.13.4 | -| SHA-256 | `e049a47a610a69b8d407af169f7467fa3d5a5dfb2b999de4d0f8e8be0f0db35f` | -| Capture script | branch `feat/htn-eval-capture-lowlevel-servers`, commit `93ded966e710a6342efc66973c1af4fad48002a7` of `mcp-python-ingestion` (unpushed, not landed) | - -The four servers use the low-level `mcp.server.Server` with `@app.list_tools()`, which needs mcp 1.x: -mcp 2.0.0's `Server` has no `list_tools`. mcp 1.28.1 and pydantic 2.13.4 are the versions the -repository's `infrastructure/uv.lock` pins and the golden regrade's `PROVENANCE.json` records. The -script at the tag awaits `server.list_tools()` and cannot read these servers; the commit above makes -it call the registered `tools/list` handler of a low-level server, and its output for the rikyu -servers is unchanged. Server sources, under the path above: - -| Source | Digest recorded in the snapshot | -|---|---| -| `gripper_server.py` | `sha256:13b8472ce71cc074dfa02bcc12d4af3b4a4915eb55f5c18c1c8b604da6d53ade` | -| `liquid_server.py` | `sha256:a58d9c9abf64429005f79ba06142c1be939c8a18f0438ed764d123a31c90d99c` | -| `module_server.py` | `sha256:62f0ea336fc5a196d5180fbecea65f1b59d01723553c334febf1113c977730df` | -| `movement_server.py` | `sha256:47a2f81337dedb6ebe31a811db55cfb339a41857a3357c3842d57ce88b2493cb` | - -Command, from the root of a `mcp-python-ingestion` worktree at that commit, with `<out>` the path of -this file: - -``` -uv run --isolated --no-project --python 3.12 \ - --with 'mcp==1.28.1' --with 'pydantic==2.13.4' \ - python -I .claude/skills/htn-creator-workspace/infrastructure/scripts/capture_catalog_snapshot.py \ - --servers-dir .claude/skills/htn-creator-workspace/servers/bio-opentrons \ - --server bio-opentrons.gripper_server:app --server bio-opentrons.liquid_server:app \ - --server bio-opentrons.module_server:app --server bio-opentrons.movement_server:app \ - --pin mcp --pin pydantic \ - --out <out> -``` - -## Capture script - -`.claude/skills/htn-creator-workspace/infrastructure/scripts/capture_catalog_snapshot.py`, blob -`a7f07f1886301c788143b7f7b1d75ffb072dc963` at tag `htn-creator-eval@0.4.2`. It keeps `name`, -`description`, `inputSchema` and `outputSchema` of each tool and sorts tools by name. The bio-opentrons -tools carry no other field. diff --git a/crates/candler-schemas/tests/fixtures/upstream/bio_opentrons.json b/crates/candler-schemas/tests/fixtures/upstream/bio_opentrons.json deleted file mode 100644 index c1a9b84f..00000000 --- a/crates/candler-schemas/tests/fixtures/upstream/bio_opentrons.json +++ /dev/null @@ -1,919 +0,0 @@ -{ - "schema": "tool-catalog-snapshot/0", - "captured_at": "2026-10-28T15:10:36+00:00", - "provider": "htn-creator-eval/scripts/capture_catalog_snapshot.py@1", - "environment": { - "python": "3.12.12", - "mcp": "1.28.1", - "pydantic": "2.13.4" - }, - "servers_dir": ".claude/skills/htn-creator-workspace/servers/bio-opentrons", - "stubbed_modules": [], - "servers": [ - { - "name": "gripper-server", - "source_path": ".claude/skills/htn-creator-workspace/servers/bio-opentrons/gripper_server.py", - "source_digest": "sha256:13b8472ce71cc074dfa02bcc12d4af3b4a4915eb55f5c18c1c8b604da6d53ade", - "transport": "stdio", - "tools": [ - { - "name": "move_labware", - "description": "Move labware using the gripper from one location to another", - "inputSchema": { - "type": "object", - "properties": { - "labware_name": { - "type": "string", - "description": "Name/ID of the labware to move" - }, - "destination": { - "type": "string", - "description": "Destination slot (e.g., 'A1', 'B2', 'heater_shaker')" - }, - "use_gripper": { - "type": "boolean", - "description": "Whether to use gripper (true) or manual movement (false)", - "default": true - } - }, - "required": [ - "labware_name", - "destination" - ] - } - } - ] - }, - { - "name": "liquid-server", - "source_path": ".claude/skills/htn-creator-workspace/servers/bio-opentrons/liquid_server.py", - "source_digest": "sha256:a58d9c9abf64429005f79ba06142c1be939c8a18f0438ed764d123a31c90d99c", - "transport": "stdio", - "tools": [ - { - "name": "air_gap", - "description": "Create an air gap in the tip to prevent dripping. Corresponds to GTPyhop action: a_air_gap(state, pipette, volume)", - "inputSchema": { - "type": "object", - "properties": { - "pipette": { - "type": "string", - "description": "Pipette identifier (e.g., 'pip96', 'left', 'right')" - }, - "volume": { - "type": "number", - "description": "Air gap volume in \u00b5L", - "minimum": 1, - "maximum": 1000 - } - }, - "required": [ - "pipette", - "volume" - ] - } - }, - { - "name": "aspirate", - "description": "Aspirate liquid from a well into the pipette. Simulates Opentrons Flex pipette aspiration operation. Supports location parameter for precise Z-axis positioning (top/bottom/center). Corresponds to GTPyhop action: a_aspirate(state, mount, volume, labware_slot, well)", - "inputSchema": { - "type": "object", - "properties": { - "mount": { - "type": "string", - "description": "Pipette mount ('left' or 'right')", - "enum": [ - "left", - "right" - ] - }, - "volume": { - "type": "number", - "description": "Volume to aspirate in \u00b5L (1-1000)", - "minimum": 1, - "maximum": 1000 - }, - "labware_slot": { - "type": "string", - "description": "Deck slot containing the labware (e.g., 'A1', 'B2', 'D3') - backward compatible", - "pattern": "^[A-Da-d][1-3]$" - }, - "well": { - "type": "string", - "description": "Well to aspirate from (e.g., 'A1', 'B6', 'H12') - backward compatible", - "pattern": "^[A-Ha-h](1[0-2]|[1-9])$" - }, - "location": { - "type": "object", - "description": "Well location with optional Z-axis positioning (Opentrons API v2 compatible)", - "properties": { - "labware_slot": { - "type": "string", - "description": "Deck slot containing the labware", - "pattern": "^[A-Da-d][1-3]$" - }, - "well": { - "type": "string", - "description": "Well identifier", - "pattern": "^[A-Ha-h](1[0-2]|[1-9])$" - }, - "position_type": { - "type": "string", - "description": "Z-axis position (top/bottom/center) - maps to Well.top()/bottom()/center()", - "enum": [ - "top", - "bottom", - "center" - ], - "default": "bottom" - }, - "z_offset": { - "type": "number", - "description": "Z-axis offset in mm (positive = up, negative = down)", - "default": 0 - } - }, - "required": [ - "labware_slot", - "well" - ] - }, - "rate": { - "type": "number", - "description": "Flow rate multiplier (1.0 = default speed)", - "minimum": 0.1, - "maximum": 10.0, - "default": 1.0 - } - }, - "required": [ - "mount", - "volume" - ] - } - }, - { - "name": "blow_out", - "description": "Blow out any remaining liquid from the pipette tip. Ensures complete liquid transfer by expelling residual volume. Corresponds to GTPyhop action: a_blow_out(state, mount)", - "inputSchema": { - "type": "object", - "properties": { - "mount": { - "type": "string", - "description": "Pipette mount to blow out from ('left' or 'right')", - "enum": [ - "left", - "right" - ] - } - }, - "required": [ - "mount" - ] - } - }, - { - "name": "dispense", - "description": "Dispense liquid from the pipette into a well. Simulates Opentrons Flex pipette dispensing operation. Supports location parameter for precise Z-axis positioning (top/bottom/center). Corresponds to GTPyhop action: a_dispense(state, mount, volume, labware_slot, well)", - "inputSchema": { - "type": "object", - "properties": { - "mount": { - "type": "string", - "description": "Pipette mount ('left' or 'right')", - "enum": [ - "left", - "right" - ] - }, - "volume": { - "type": "number", - "description": "Volume to dispense in \u00b5L (1-1000)", - "minimum": 1, - "maximum": 1000 - }, - "labware_slot": { - "type": "string", - "description": "Deck slot containing the labware (e.g., 'A1', 'B2', 'D3') - backward compatible", - "pattern": "^[A-Da-d][1-3]$" - }, - "well": { - "type": "string", - "description": "Well to dispense into (e.g., 'A1', 'B6', 'H12') - backward compatible", - "pattern": "^[A-Ha-h](1[0-2]|[1-9])$" - }, - "location": { - "type": "object", - "description": "Well location with optional Z-axis positioning (Opentrons API v2 compatible)", - "properties": { - "labware_slot": { - "type": "string", - "description": "Deck slot containing the labware", - "pattern": "^[A-Da-d][1-3]$" - }, - "well": { - "type": "string", - "description": "Well identifier", - "pattern": "^[A-Ha-h](1[0-2]|[1-9])$" - }, - "position_type": { - "type": "string", - "description": "Z-axis position (top/bottom/center) - maps to Well.top()/bottom()/center()", - "enum": [ - "top", - "bottom", - "center" - ], - "default": "bottom" - }, - "z_offset": { - "type": "number", - "description": "Z-axis offset in mm (positive = up, negative = down)", - "default": 0 - } - }, - "required": [ - "labware_slot", - "well" - ] - }, - "rate": { - "type": "number", - "description": "Flow rate multiplier (1.0 = default speed)", - "minimum": 0.1, - "maximum": 10.0, - "default": 1.0 - } - }, - "required": [ - "mount", - "volume" - ] - } - }, - { - "name": "home", - "description": "Home the pipette to its starting position. Corresponds to GTPyhop action: a_home(state, pipette)", - "inputSchema": { - "type": "object", - "properties": { - "pipette": { - "type": "string", - "description": "Pipette identifier (e.g., 'pip96', 'left', 'right')" - } - }, - "required": [ - "pipette" - ] - } - }, - { - "name": "load_labware", - "description": "Register labware as loaded at a deck slot in liquid-server's own state (independent of movement-server's copy - see module docstring). Required before aspirate/dispense/mix will accept operations at that slot.", - "inputSchema": { - "type": "object", - "properties": { - "slot": { - "type": "string", - "description": "Deck slot position (e.g., 'A1', 'B2', 'D3')", - "pattern": "^[A-Da-d][1-3]$" - }, - "labware_type": { - "type": "string", - "description": "Type of labware (e.g., 'nest_96_wellplate_200ul_flat')" - } - }, - "required": [ - "slot", - "labware_type" - ] - } - }, - { - "name": "mix", - "description": "Mix contents of a well by repeated aspiration and dispensing. Simulates Opentrons Flex mixing operation for homogenization. Corresponds to GTPyhop action: a_mix(state, mount, repetitions, volume, labware_slot, well)", - "inputSchema": { - "type": "object", - "properties": { - "mount": { - "type": "string", - "description": "Pipette mount ('left' or 'right')", - "enum": [ - "left", - "right" - ] - }, - "repetitions": { - "type": "integer", - "description": "Number of mix cycles (1-50)", - "minimum": 1, - "maximum": 50 - }, - "volume": { - "type": "number", - "description": "Volume to mix in \u00b5L (1-1000)", - "minimum": 1, - "maximum": 1000 - }, - "labware_slot": { - "type": "string", - "description": "Deck slot containing the labware (e.g., 'A1', 'B2', 'D3')", - "pattern": "^[A-Da-d][1-3]$" - }, - "well": { - "type": "string", - "description": "Well to mix (e.g., 'A1', 'B6', 'H12')", - "pattern": "^[A-Ha-h](1[0-2]|[1-9])$" - } - }, - "required": [ - "mount", - "repetitions", - "volume", - "labware_slot", - "well" - ] - } - }, - { - "name": "pick_up_tip", - "description": "Pick up a tip from the specified rack for liquid handling operations. Corresponds to GTPyhop action: a_pick_up_tip(state, pipette, tip_rack)", - "inputSchema": { - "type": "object", - "properties": { - "pipette": { - "type": "string", - "description": "Pipette identifier (e.g., 'pip96', 'left', 'right')" - }, - "tip_rack": { - "type": "string", - "description": "Tip rack identifier (e.g., 'tips', 'tips1')" - } - }, - "required": [ - "pipette", - "tip_rack" - ] - } - }, - { - "name": "return_tip", - "description": "Return the current tip to the rack or trash. Corresponds to GTPyhop action: a_return_tip(state, pipette)", - "inputSchema": { - "type": "object", - "properties": { - "pipette": { - "type": "string", - "description": "Pipette identifier (e.g., 'pip96', 'left', 'right')" - } - }, - "required": [ - "pipette" - ] - } - }, - { - "name": "set_flow_rate", - "description": "Set pipette flow rates for liquid handling operations. Corresponds to GTPyhop action: a_set_flow_rate(state, pipette, aspirate_rate, dispense_rate)", - "inputSchema": { - "type": "object", - "properties": { - "pipette": { - "type": "string", - "description": "Pipette identifier (e.g., 'pip96', 'left', 'right')" - }, - "aspirate_rate": { - "type": "number", - "description": "Aspiration flow rate in \u00b5L/s", - "minimum": 0.1, - "maximum": 1000 - }, - "dispense_rate": { - "type": "number", - "description": "Dispense flow rate in \u00b5L/s", - "minimum": 0.1, - "maximum": 1000 - } - }, - "required": [ - "pipette", - "aspirate_rate", - "dispense_rate" - ] - } - } - ] - }, - { - "name": "module-server", - "source_path": ".claude/skills/htn-creator-workspace/servers/bio-opentrons/module_server.py", - "source_digest": "sha256:62f0ea336fc5a196d5180fbecea65f1b59d01723553c334febf1113c977730df", - "transport": "stdio", - "tools": [ - { - "name": "close_labware_latch", - "description": "Close heater-shaker labware latch before shaking. REQUIRED before starting shake operations. Corresponds to Opentrons API: heater_shaker.close_labware_latch()", - "inputSchema": { - "type": "object", - "properties": { - "module_slot": { - "type": "string", - "description": "Slot where heater-shaker is located (e.g., 'D1')" - } - }, - "required": [] - } - }, - { - "name": "close_thermocycler_lid", - "description": "Close the thermocycler lid for thermal cycling. Required before running temperature profiles. Corresponds to GTPyhop action: a_close_thermocycler_lid", - "inputSchema": { - "type": "object", - "properties": {}, - "required": [] - } - }, - { - "name": "deactivate_heater_shaker", - "description": "Deactivate the heater-shaker module. Stops both heating and shaking. Corresponds to GTPyhop action: a_deactivate_heater_shaker", - "inputSchema": { - "type": "object", - "properties": {}, - "required": [] - } - }, - { - "name": "deactivate_thermocycler", - "description": "Deactivate the thermocycler after completing thermal cycling. Stops heating and returns to ambient temperature. Corresponds to GTPyhop action: a_deactivate_thermocycler", - "inputSchema": { - "type": "object", - "properties": {}, - "required": [] - } - }, - { - "name": "delay", - "description": "Delay execution for specified duration (omega_hdq domain). Corresponds to GTPyhop action: a_delay", - "inputSchema": { - "type": "object", - "properties": { - "seconds": { - "type": "number", - "description": "Delay duration in seconds", - "minimum": 0 - }, - "message": { - "type": "string", - "description": "Optional message describing the delay purpose" - } - }, - "required": [ - "seconds" - ] - } - }, - { - "name": "execute_profile", - "description": "Execute a PCR thermocycler profile for specified number of cycles. Lid must be closed and thermocycler must be active. Uses steps array with temperature/hold_time per Opentrons API v2. Corresponds to GTPyhop action: a_execute_thermocycler_profile", - "inputSchema": { - "type": "object", - "properties": { - "steps": { - "type": "array", - "description": "Array of temperature steps for the profile", - "items": { - "type": "object", - "properties": { - "temperature": { - "type": "number", - "description": "Target temperature in \u00b0C", - "minimum": 4, - "maximum": 99 - }, - "hold_time_seconds": { - "type": "number", - "description": "Hold time in seconds", - "minimum": 0 - }, - "hold_time_minutes": { - "type": "number", - "description": "Hold time in minutes", - "minimum": 0 - } - }, - "required": [ - "temperature" - ] - } - }, - "repetitions": { - "type": "integer", - "description": "Number of times to repeat the profile (1-99)", - "minimum": 1, - "maximum": 99, - "default": 1 - }, - "block_max_volume": { - "type": "number", - "description": "Maximum volume in wells (\u00b5L) for temperature accuracy", - "minimum": 0, - "maximum": 100 - }, - "profile_name": { - "type": "string", - "description": "Profile name (backward compatible, ignored if steps provided)" - }, - "num_cycles": { - "type": "integer", - "description": "Alias for repetitions (backward compatible)", - "minimum": 1, - "maximum": 99 - } - }, - "required": [ - "steps" - ] - } - }, - { - "name": "hs_close_latch", - "description": "Close heater-shaker latch (omega_hdq domain). Corresponds to GTPyhop action: a_hs_close_latch", - "inputSchema": { - "type": "object", - "properties": {}, - "required": [] - } - }, - { - "name": "hs_deactivate_shaker", - "description": "Deactivate heater-shaker (omega_hdq domain). Corresponds to GTPyhop action: a_hs_deactivate_shaker", - "inputSchema": { - "type": "object", - "properties": {}, - "required": [] - } - }, - { - "name": "hs_open_latch", - "description": "Open heater-shaker latch (omega_hdq domain). Corresponds to GTPyhop action: a_hs_open_latch", - "inputSchema": { - "type": "object", - "properties": {}, - "required": [] - } - }, - { - "name": "hs_set_shake_speed", - "description": "Set heater-shaker shake speed (omega_hdq domain). Corresponds to GTPyhop action: a_hs_set_shake_speed", - "inputSchema": { - "type": "object", - "properties": { - "rpm": { - "type": "integer", - "description": "Shaking speed in RPM (0-3000)", - "minimum": 0, - "maximum": 3000 - } - }, - "required": [ - "rpm" - ] - } - }, - { - "name": "hs_set_temperature", - "description": "Set heater-shaker temperature (omega_hdq domain). Corresponds to GTPyhop action: a_hs_set_temperature", - "inputSchema": { - "type": "object", - "properties": { - "temperature": { - "type": "number", - "description": "Target temperature in \u00b0C (4-95)", - "minimum": 4, - "maximum": 95 - } - }, - "required": [ - "temperature" - ] - } - }, - { - "name": "open_labware_latch", - "description": "Open heater-shaker labware latch for loading/unloading plates. SAFETY: Shaking must be stopped before opening latch. Corresponds to Opentrons API: heater_shaker.open_labware_latch()", - "inputSchema": { - "type": "object", - "properties": { - "module_slot": { - "type": "string", - "description": "Slot where heater-shaker is located (e.g., 'D1')" - } - }, - "required": [] - } - }, - { - "name": "open_thermocycler_lid", - "description": "Open the thermocycler lid to allow plate access. Required before loading or retrieving plates. Corresponds to GTPyhop action: a_open_thermocycler_lid", - "inputSchema": { - "type": "object", - "properties": {}, - "required": [] - } - }, - { - "name": "set_and_wait_for_shake_speed", - "description": "Set heater-shaker shake speed and wait until target speed is reached. Blocks until operation complete. Latch must be closed. Corresponds to Opentrons API: heater_shaker.set_and_wait_for_shake_speed(rpm)", - "inputSchema": { - "type": "object", - "properties": { - "rpm": { - "type": "integer", - "description": "Target shaking speed in RPM (0-3000)", - "minimum": 0, - "maximum": 3000 - } - }, - "required": [ - "rpm" - ] - } - }, - { - "name": "set_and_wait_for_temperature", - "description": "Set module temperature and wait until target temperature is reached. Blocks until operation complete. Works with heater-shaker and temp module. Corresponds to Opentrons API: module.set_temperature() with wait", - "inputSchema": { - "type": "object", - "properties": { - "celsius": { - "type": "number", - "description": "Target temperature in \u00b0C (4-95 for heater-shaker)", - "minimum": 4, - "maximum": 95 - }, - "module_type": { - "type": "string", - "description": "Module type: 'heater_shaker' or 'temperature'", - "enum": [ - "heater_shaker", - "temperature" - ], - "default": "heater_shaker" - } - }, - "required": [ - "celsius" - ] - } - }, - { - "name": "set_block_temperature", - "description": "Set thermocycler block to a specific temperature with hold time. Lid must be closed. Temperature range: 4-99\u00b0C. Supports hold_time_seconds and hold_time_minutes per Opentrons API v2. Corresponds to GTPyhop action: a_set_thermocycler_temperature", - "inputSchema": { - "type": "object", - "properties": { - "temperature": { - "type": "number", - "description": "Target temperature in \u00b0C (4-99)", - "minimum": 4, - "maximum": 99 - }, - "hold_time": { - "type": "integer", - "description": "Hold time in seconds (0 = indefinite) - backward compatible", - "minimum": 0 - }, - "hold_time_seconds": { - "type": "number", - "description": "Hold time in seconds (Opentrons API v2 compatible)", - "minimum": 0 - }, - "hold_time_minutes": { - "type": "number", - "description": "Hold time in minutes (Opentrons API v2 compatible)", - "minimum": 0 - }, - "block_max_volume": { - "type": "number", - "description": "Maximum volume in wells (\u00b5L) for temperature accuracy optimization", - "minimum": 0, - "maximum": 100 - } - }, - "required": [ - "temperature" - ] - } - }, - { - "name": "set_heater_shaker", - "description": "Set heater-shaker module temperature and shaking speed. Temperature range: 4-95\u00b0C, Speed range: 0-3000 RPM. Corresponds to GTPyhop action: a_set_heater_shaker", - "inputSchema": { - "type": "object", - "properties": { - "temperature": { - "type": "number", - "description": "Target temperature in \u00b0C (4-95)", - "minimum": 4, - "maximum": 95 - }, - "speed": { - "type": "integer", - "description": "Shaking speed in RPM (0-3000)", - "minimum": 0, - "maximum": 3000 - } - }, - "required": [ - "temperature", - "speed" - ] - } - }, - { - "name": "set_temperature", - "description": "Set temperature module to target temperature. Useful for keeping reagents cold during protocols. Corresponds to GTPyhop action: a_set_temperature_module", - "inputSchema": { - "type": "object", - "properties": { - "temperature": { - "type": "number", - "description": "Target temperature in \u00b0C (4-99)", - "minimum": 4, - "maximum": 99 - } - }, - "required": [ - "temperature" - ] - } - }, - { - "name": "temp_set_temperature", - "description": "Set temperature module temperature (omega_hdq domain). Alias for set_temperature. Corresponds to GTPyhop action: a_temp_set_temperature", - "inputSchema": { - "type": "object", - "properties": { - "temperature": { - "type": "number", - "description": "Target temperature in \u00b0C (4-99)", - "minimum": 4, - "maximum": 99 - } - }, - "required": [ - "temperature" - ] - } - } - ] - }, - { - "name": "movement-server", - "source_path": ".claude/skills/htn-creator-workspace/servers/bio-opentrons/movement_server.py", - "source_digest": "sha256:47a2f81337dedb6ebe31a811db55cfb339a41857a3357c3842d57ce88b2493cb", - "transport": "stdio", - "tools": [ - { - "name": "drop_tip", - "description": "Drop the current tip from the pipette into the trash. Pipette must have a tip attached. Corresponds to GTPyhop action: a_drop_tip", - "inputSchema": { - "type": "object", - "properties": { - "mount": { - "type": "string", - "description": "Pipette mount ('left' or 'right')", - "enum": [ - "left", - "right" - ] - } - }, - "required": [ - "mount" - ] - } - }, - { - "name": "initialize_all", - "description": "Initialize/home the Opentrons Flex movement system before any deck or pipette operations. Mirrors the real robot's startup homing sequence. Corresponds to GTPyhop action: a_initialize_servers", - "inputSchema": { - "type": "object", - "properties": {}, - "required": [] - } - }, - { - "name": "load_labware", - "description": "Load labware onto the Opentrons Flex deck at a specified slot. Slots use format A1-D3 (4 rows \u00d7 3 columns). Corresponds to GTPyhop action: a_load_labware", - "inputSchema": { - "type": "object", - "properties": { - "slot": { - "type": "string", - "description": "Deck slot position (e.g., 'A1', 'B2', 'D3')", - "pattern": "^[A-Da-d][1-3]$" - }, - "labware_type": { - "type": "string", - "description": "Type of labware (e.g., 'nest_96_wellplate_200ul_flat')" - } - }, - "required": [ - "slot", - "labware_type" - ] - } - }, - { - "name": "load_pipette", - "description": "Load a pipette onto the specified mount of the Opentrons Flex. Mount can be 'left' or 'right'. Corresponds to GTPyhop action: a_load_pipette", - "inputSchema": { - "type": "object", - "properties": { - "mount": { - "type": "string", - "description": "Pipette mount position ('left' or 'right')", - "enum": [ - "left", - "right" - ] - }, - "pipette_type": { - "type": "string", - "description": "Pipette type (e.g., 'flex_1channel_1000', 'flex_8channel_1000')" - } - }, - "required": [ - "mount", - "pipette_type" - ] - } - }, - { - "name": "move_to_well", - "description": "Move pipette to a specific well position in a labware. Labware must be loaded at the specified slot. Corresponds to GTPyhop action: a_move_to_well", - "inputSchema": { - "type": "object", - "properties": { - "mount": { - "type": "string", - "description": "Pipette mount ('left' or 'right')", - "enum": [ - "left", - "right" - ] - }, - "labware_slot": { - "type": "string", - "description": "Deck slot containing the labware", - "pattern": "^[A-Da-d][1-3]$" - }, - "well": { - "type": "string", - "description": "Well identifier (e.g., 'A1', 'B6', 'H12')", - "pattern": "^[A-Ha-h](1[0-2]|[1-9])$" - } - }, - "required": [ - "mount", - "labware_slot", - "well" - ] - } - }, - { - "name": "pick_up_tip", - "description": "Pick up a tip from the specified tiprack slot. Pipette must be loaded and not already have a tip. If well is not specified, automatically picks up the next available tip. Corresponds to GTPyhop action: a_pick_up_tip", - "inputSchema": { - "type": "object", - "properties": { - "mount": { - "type": "string", - "description": "Pipette mount ('left' or 'right')", - "enum": [ - "left", - "right" - ] - }, - "tiprack_slot": { - "type": "string", - "description": "Deck slot containing the tiprack (e.g., 'C1')", - "pattern": "^[A-Da-d][1-3]$" - }, - "well": { - "type": "string", - "description": "Specific tip well to pick up (e.g., 'A1', 'B6'). Optional - if not specified, auto-increments to next available tip.", - "pattern": "^[A-Ha-h](1[0-2]|[1-9])$" - } - }, - "required": [ - "mount", - "tiprack_slot" - ] - } - } - ] - } - ] -} diff --git a/crates/candler-schemas/tests/fixtures/upstream/rikyu_mcp.json b/crates/candler-schemas/tests/fixtures/upstream/rikyu_mcp.json deleted file mode 100644 index c3a1206a..00000000 --- a/crates/candler-schemas/tests/fixtures/upstream/rikyu_mcp.json +++ /dev/null @@ -1,2709 +0,0 @@ -{ - "schema": "tool-catalog-snapshot/0", - "captured_at": "2026-10-28T01:09:04+00:00", - "provider": "htn-creator-eval/scripts/capture_catalog_snapshot.py@1", - "environment": { - "python": "3.12.12", - "hpc-agent-core": "0.5.0", - "mcp": "2.0.0", - "pydantic": "2.13.4" - }, - "servers_dir": ".claude/skills/htn-creator-workspace/servers/rikyu_mcp", - "stubbed_modules": [ - "hpc_agent_core.compute", - "hpc_agent_core.compute.slurm", - "hpc_agent_core.middleware", - "hpc_agent_core.rag", - "hpc_agent_core.rag.store", - "hpc_agent_core.serving" - ], - "servers": [ - { - "name": "rikyu-hpc", - "source_path": ".claude/skills/htn-creator-workspace/servers/rikyu_mcp/hpc_server.py", - "source_digest": "sha256:b2af8a23ff6f5ceef36217b7727bf515fbf345472d81e1872bbed43b57e55b4b", - "transport": "stdio", - "tools": [ - { - "name": "cancel_job", - "description": "Cancel a queued or running job via scancel. (IRI: DELETE /compute/job/{job_id})", - "inputSchema": { - "properties": { - "job_id": { - "title": "Job Id", - "type": "string" - } - }, - "required": [ - "job_id" - ], - "title": "cancel_jobArguments", - "type": "object" - }, - "outputSchema": { - "$defs": { - "Container": { - "description": "Container specification (IRI Container); executed via singularity exec.\n\nimage must be a path to a .sif file (absolute or using $HOME) or a\ndocker:// URI. GPU passthrough is added automatically by the rendering\nbackend when the job requests GPUs (vendor-specific flag chosen by that\nmachine's config, e.g. --nv vs --rocm). launcher (e.g. 'srun') is placed\noutside singularity exec so MPI works.", - "properties": { - "image": { - "description": "Singularity image path or URI (e.g. docker://ubuntu:22.04)", - "title": "Image", - "type": "string" - }, - "volume_mounts": { - "items": { - "$ref": "#/$defs/VolumeMount" - }, - "title": "Volume Mounts", - "type": "array" - } - }, - "required": [ - "image" - ], - "title": "Container", - "type": "object" - }, - "Job": { - "description": "IRI Job: identifier + current status + originating spec.", - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "status": { - "anyOf": [ - { - "$ref": "#/$defs/JobStatus" - }, - { - "type": "null" - } - ], - "default": null - }, - "job_spec": { - "anyOf": [ - { - "$ref": "#/$defs/JobSpec" - }, - { - "type": "null" - } - ], - "default": null - } - }, - "required": [ - "id" - ], - "title": "Job", - "type": "object" - }, - "JobAttributes": { - "description": "Scheduler attributes (IRI/PSI/J JobAttributes subset).\n\nqueue_name has no cross-machine default \u2014 each machine's tool layer\nshould supply its own default_partition (from that machine's config)\nwhen a JobSpec omits one.", - "properties": { - "duration": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "string" - } - ], - "default": 3600, - "description": "Wall time as integer seconds or HH:MM:SS / D-HH:MM:SS string", - "title": "Duration" - }, - "queue_name": { - "default": "", - "description": "Scheduler partition/queue; machine-specific default applied by the tool layer if omitted", - "title": "Queue Name", - "type": "string" - }, - "account": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Account/project to charge", - "title": "Account" - }, - "reservation_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Scheduler reservation name (--reservation)", - "title": "Reservation Id" - }, - "custom_attributes": { - "additionalProperties": { - "type": "string" - }, - "title": "Custom Attributes", - "type": "object" - }, - "scheduler": { - "anyOf": [ - { - "$ref": "#/$defs/Scheduler" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Override which SchedulerBackend handles this job, on a machine with more than one; None means the machine's tool layer decides (e.g. from queue_name)" - }, - "parallel_env": { - "default": "smp", - "description": "Grid Engine parallel environment (-pe); ignored by Slurm backends", - "title": "Parallel Env", - "type": "string" - } - }, - "title": "JobAttributes", - "type": "object" - }, - "JobSpec": { - "description": "Job specification (IRI/PSI/J JobSpec subset).\n\nexecutable plus arguments form the command run inside the batch script;\nexecutable may be a shell line (e.g. 'module load foo && srun ./app').\nlauncher, if set, is prepended to executable (e.g. 'srun').\npre_launch / post_launch are script lines inserted before / after.\nIf container is set, the command is wrapped in 'singularity exec'.", - "properties": { - "name": { - "default": "agent-job", - "title": "Name", - "type": "string" - }, - "executable": { - "title": "Executable", - "type": "string" - }, - "arguments": { - "items": { - "type": "string" - }, - "title": "Arguments", - "type": "array" - }, - "directory": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Working directory for the job", - "title": "Directory" - }, - "environment": { - "additionalProperties": { - "type": "string" - }, - "title": "Environment", - "type": "object" - }, - "inherit_environment": { - "default": true, - "description": "Inherit submission environment variables", - "title": "Inherit Environment", - "type": "boolean" - }, - "stdin_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Path to use as stdin (--input)", - "title": "Stdin Path" - }, - "stdout_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Stdout Path" - }, - "stderr_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Stderr Path" - }, - "resources": { - "$ref": "#/$defs/ResourceSpec" - }, - "attributes": { - "$ref": "#/$defs/JobAttributes" - }, - "pre_launch": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Script lines to insert before executable", - "title": "Pre Launch" - }, - "post_launch": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Script lines to insert after executable", - "title": "Post Launch" - }, - "launcher": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Launcher prefix, e.g. 'srun' or 'mpirun -np 4'", - "title": "Launcher" - }, - "container": { - "anyOf": [ - { - "$ref": "#/$defs/Container" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Run inside a Singularity container" - } - }, - "required": [ - "executable" - ], - "title": "JobSpec", - "type": "object" - }, - "JobState": { - "description": "Normalized job states (IRI/PSI-J), mapped from scheduler-native states.", - "enum": [ - "new", - "queued", - "held", - "active", - "completed", - "failed", - "canceled", - "unknown" - ], - "title": "JobState", - "type": "string" - }, - "JobStatus": { - "description": "IRI-compliant job status (state + time + message + exit_code + meta_data).\n\nScheduler-specific detail (native_state, partition, nodes, workdir,\nelapsed, start/end times, queue reason) is carried in meta_data.", - "properties": { - "state": { - "$ref": "#/$defs/JobState" - }, - "time": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Epoch seconds: end_time if finished, start_time if running", - "title": "Time" - }, - "message": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Human-readable status (queue reason, error, etc.)", - "title": "Message" - }, - "exit_code": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Exit Code" - }, - "meta_data": { - "anyOf": [ - { - "additionalProperties": true, - "type": "object" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Scheduler-specific fields: native_state, partition, nodes, workdir, elapsed, etc.", - "title": "Meta Data" - } - }, - "required": [ - "state" - ], - "title": "JobStatus", - "type": "object" - }, - "ResourceSpec": { - "description": "Resources for a job (PSI/J ResourceSpec + a GPU extension).\n\ngpus is a total-for-the-job GPU count extension (not in upstream PSI/J);\ngpu_cores_per_process is the PSI/J standard equivalent. If both are set,\ngpus takes precedence. How gpus maps to a scheduler flag (--gpus,\n--gres=gpu:N, --gpus-per-node) and whether node_count is derived from it\nor must be set explicitly is a per-machine SchedulerBackend concern \u2014\nsee that machine's compute/ module and config.", - "properties": { - "node_count": { - "default": 1, - "title": "Node Count", - "type": "integer" - }, - "process_count": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Total processes (alternative to processes_per_node \u00d7 node_count)", - "title": "Process Count" - }, - "processes_per_node": { - "default": 1, - "title": "Processes Per Node", - "type": "integer" - }, - "cpu_cores_per_process": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cpu Cores Per Process" - }, - "gpu_cores_per_process": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "PSI/J standard GPU field; prefer gpus where a machine supports it", - "title": "Gpu Cores Per Process" - }, - "gpus": { - "default": 0, - "description": "Total GPUs requested for the job (machine-specific extension); 0 means no GPU request", - "title": "Gpus", - "type": "integer" - }, - "exclusive_node_use": { - "default": false, - "description": "Request exclusive node allocation (--exclusive)", - "title": "Exclusive Node Use", - "type": "boolean" - }, - "memory": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Memory per node in bytes (maps to --mem)", - "title": "Memory" - } - }, - "title": "ResourceSpec", - "type": "object" - }, - "Scheduler": { - "description": "Target batch scheduler for a job submission \u2014 only meaningful on a\nmachine that composes more than one SchedulerBackend (e.g. a cluster\nwith both a Slurm partition and a Grid Engine partition). Single-scheduler\nmachines can ignore this field entirely.", - "enum": [ - "slurm", - "gridengine" - ], - "title": "Scheduler", - "type": "string" - }, - "VolumeMount": { - "description": "A host path mounted into a container (IRI VolumeMount).", - "properties": { - "source": { - "description": "Host path to mount", - "title": "Source", - "type": "string" - }, - "target": { - "description": "Path inside the container", - "title": "Target", - "type": "string" - }, - "read_only": { - "default": true, - "description": "Mount as read-only", - "title": "Read Only", - "type": "boolean" - } - }, - "required": [ - "source", - "target" - ], - "title": "VolumeMount", - "type": "object" - } - }, - "properties": { - "result": { - "anyOf": [ - { - "$ref": "#/$defs/Job" - }, - { - "type": "string" - } - ], - "title": "Result" - } - }, - "required": [ - "result" - ], - "title": "cancel_jobOutput", - "type": "object" - } - }, - { - "name": "fs_checksum", - "description": "SHA-256 checksum of a remote file. (IRI: GET /filesystem/checksum)", - "inputSchema": { - "properties": { - "path": { - "title": "Path", - "type": "string" - } - }, - "required": [ - "path" - ], - "title": "fs_checksumArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_checksumOutput", - "type": "object" - } - }, - { - "name": "fs_chmod", - "description": "Change a file/directory's permissions, e.g. mode=\"755\". (IRI: POST /filesystem/chmod)", - "inputSchema": { - "properties": { - "path": { - "title": "Path", - "type": "string" - }, - "mode": { - "title": "Mode", - "type": "string" - } - }, - "required": [ - "path", - "mode" - ], - "title": "fs_chmodArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_chmodOutput", - "type": "object" - } - }, - { - "name": "fs_chown", - "description": "Change a file/directory's owner (and optionally group, as\n \"user:group\"). Most users can only chown within their own group's\n permissions \u2014 Slurm/Lustre still enforces the actual ACL. (IRI: POST /filesystem/chown)", - "inputSchema": { - "properties": { - "path": { - "title": "Path", - "type": "string" - }, - "owner": { - "title": "Owner", - "type": "string" - } - }, - "required": [ - "path", - "owner" - ], - "title": "fs_chownArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_chownOutput", - "type": "object" - } - }, - { - "name": "fs_compress", - "description": "Create a tar archive from one or more remote paths. (IRI: POST /filesystem/compress)", - "inputSchema": { - "$defs": { - "CompressionType": { - "description": "Compression format for fs_compress / fs_extract (IRI CompressionType).", - "enum": [ - "none", - "bzip2", - "gzip", - "xz" - ], - "title": "CompressionType", - "type": "string" - } - }, - "properties": { - "paths": { - "items": { - "type": "string" - }, - "title": "Paths", - "type": "array" - }, - "archive_path": { - "title": "Archive Path", - "type": "string" - }, - "compression": { - "$ref": "#/$defs/CompressionType", - "default": "gzip" - } - }, - "required": [ - "paths", - "archive_path" - ], - "title": "fs_compressArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_compressOutput", - "type": "object" - } - }, - { - "name": "fs_cp", - "description": "Copy a file or (with recursive=True) a directory tree on the\n cluster. (IRI: POST /filesystem/cp)", - "inputSchema": { - "properties": { - "source": { - "title": "Source", - "type": "string" - }, - "dest": { - "title": "Dest", - "type": "string" - }, - "recursive": { - "default": false, - "title": "Recursive", - "type": "boolean" - } - }, - "required": [ - "source", - "dest" - ], - "title": "fs_cpArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_cpOutput", - "type": "object" - } - }, - { - "name": "fs_download", - "description": "Download a file from RIKYU via rsync (falling back to scp), with a\n SHA-256 verification of the transfer. (IRI: GET /filesystem/download)", - "inputSchema": { - "properties": { - "remote_path": { - "title": "Remote Path", - "type": "string" - }, - "local_path": { - "title": "Local Path", - "type": "string" - } - }, - "required": [ - "remote_path", - "local_path" - ], - "title": "fs_downloadArguments", - "type": "object" - } - }, - { - "name": "fs_extract", - "description": "Extract an archive on the cluster into dest_dir (created if needed).\n Compression format is auto-detected by tar. (IRI: POST /filesystem/extract)", - "inputSchema": { - "properties": { - "archive_path": { - "title": "Archive Path", - "type": "string" - }, - "dest_dir": { - "default": ".", - "title": "Dest Dir", - "type": "string" - } - }, - "required": [ - "archive_path" - ], - "title": "fs_extractArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_extractOutput", - "type": "object" - } - }, - { - "name": "fs_head", - "description": "Read the first N lines of a file. (IRI: GET /filesystem/head)", - "inputSchema": { - "properties": { - "path": { - "title": "Path", - "type": "string" - }, - "lines": { - "default": 20, - "title": "Lines", - "type": "integer" - } - }, - "required": [ - "path" - ], - "title": "fs_headArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_headOutput", - "type": "object" - } - }, - { - "name": "fs_ls", - "description": "List a directory's contents (long form). (IRI: GET /filesystem/ls)", - "inputSchema": { - "properties": { - "path": { - "default": ".", - "title": "Path", - "type": "string" - } - }, - "title": "fs_lsArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_lsOutput", - "type": "object" - } - }, - { - "name": "fs_mkdir", - "description": "Create a directory, including parents as needed. (IRI: POST /filesystem/mkdir)", - "inputSchema": { - "properties": { - "path": { - "title": "Path", - "type": "string" - } - }, - "required": [ - "path" - ], - "title": "fs_mkdirArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_mkdirOutput", - "type": "object" - } - }, - { - "name": "fs_mv", - "description": "Move or rename a file/directory on the cluster. (IRI: POST /filesystem/mv)", - "inputSchema": { - "properties": { - "source": { - "title": "Source", - "type": "string" - }, - "dest": { - "title": "Dest", - "type": "string" - } - }, - "required": [ - "source", - "dest" - ], - "title": "fs_mvArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_mvOutput", - "type": "object" - } - }, - { - "name": "fs_stat", - "description": "File/directory metadata: size, permissions, timestamps, owner. (IRI: GET /filesystem/stat)", - "inputSchema": { - "properties": { - "path": { - "title": "Path", - "type": "string" - } - }, - "required": [ - "path" - ], - "title": "fs_statArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_statOutput", - "type": "object" - } - }, - { - "name": "fs_symlink", - "description": "Create a symbolic link at link_name pointing to target. (IRI: POST /filesystem/symlink)", - "inputSchema": { - "properties": { - "target": { - "title": "Target", - "type": "string" - }, - "link_name": { - "title": "Link Name", - "type": "string" - } - }, - "required": [ - "target", - "link_name" - ], - "title": "fs_symlinkArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_symlinkOutput", - "type": "object" - } - }, - { - "name": "fs_tail", - "description": "Read the last N lines of a file \u2014 useful for checking a running\n job's stdout/stderr. (IRI: GET /filesystem/tail)", - "inputSchema": { - "properties": { - "path": { - "title": "Path", - "type": "string" - }, - "lines": { - "default": 20, - "title": "Lines", - "type": "integer" - } - }, - "required": [ - "path" - ], - "title": "fs_tailArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_tailOutput", - "type": "object" - } - }, - { - "name": "fs_upload", - "description": "Upload a local file to RIKYU via rsync (falling back to scp), with a\n SHA-256 verification of the transfer. (IRI: POST /filesystem/upload)", - "inputSchema": { - "properties": { - "local_path": { - "title": "Local Path", - "type": "string" - }, - "remote_path": { - "title": "Remote Path", - "type": "string" - } - }, - "required": [ - "local_path", - "remote_path" - ], - "title": "fs_uploadArguments", - "type": "object" - } - }, - { - "name": "fs_view", - "description": "Read a whole text file's contents. (IRI: GET /filesystem/view)", - "inputSchema": { - "properties": { - "path": { - "title": "Path", - "type": "string" - } - }, - "required": [ - "path" - ], - "title": "fs_viewArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "fs_viewOutput", - "type": "object" - } - }, - { - "name": "get_drained_nodes", - "description": "Nodes currently drained/down and why, via sinfo -R (extension \u2014 not\n an IRI endpoint, but directly useful for \"why won't my job start\").", - "inputSchema": { - "properties": {}, - "title": "get_drained_nodesArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "items": { - "additionalProperties": true, - "type": "object" - }, - "title": "Result", - "type": "array" - } - }, - "required": [ - "result" - ], - "title": "get_drained_nodesOutput", - "type": "object" - } - }, - { - "name": "get_facility", - "description": "Static RIKYU facility facts: the gpu partition, the GPU-count ->\n node/CPU/memory table, storage tiers, modules, and Spack. (IRI: GET /facility)", - "inputSchema": { - "properties": {}, - "title": "get_facilityArguments", - "type": "object" - } - }, - { - "name": "get_job_status", - "description": "Status of a single job. (IRI: GET /compute/job/{job_id})", - "inputSchema": { - "properties": { - "job_id": { - "title": "Job Id", - "type": "string" - } - }, - "required": [ - "job_id" - ], - "title": "get_job_statusArguments", - "type": "object" - }, - "outputSchema": { - "$defs": { - "Container": { - "description": "Container specification (IRI Container); executed via singularity exec.\n\nimage must be a path to a .sif file (absolute or using $HOME) or a\ndocker:// URI. GPU passthrough is added automatically by the rendering\nbackend when the job requests GPUs (vendor-specific flag chosen by that\nmachine's config, e.g. --nv vs --rocm). launcher (e.g. 'srun') is placed\noutside singularity exec so MPI works.", - "properties": { - "image": { - "description": "Singularity image path or URI (e.g. docker://ubuntu:22.04)", - "title": "Image", - "type": "string" - }, - "volume_mounts": { - "items": { - "$ref": "#/$defs/VolumeMount" - }, - "title": "Volume Mounts", - "type": "array" - } - }, - "required": [ - "image" - ], - "title": "Container", - "type": "object" - }, - "JobAttributes": { - "description": "Scheduler attributes (IRI/PSI/J JobAttributes subset).\n\nqueue_name has no cross-machine default \u2014 each machine's tool layer\nshould supply its own default_partition (from that machine's config)\nwhen a JobSpec omits one.", - "properties": { - "duration": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "string" - } - ], - "default": 3600, - "description": "Wall time as integer seconds or HH:MM:SS / D-HH:MM:SS string", - "title": "Duration" - }, - "queue_name": { - "default": "", - "description": "Scheduler partition/queue; machine-specific default applied by the tool layer if omitted", - "title": "Queue Name", - "type": "string" - }, - "account": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Account/project to charge", - "title": "Account" - }, - "reservation_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Scheduler reservation name (--reservation)", - "title": "Reservation Id" - }, - "custom_attributes": { - "additionalProperties": { - "type": "string" - }, - "title": "Custom Attributes", - "type": "object" - }, - "scheduler": { - "anyOf": [ - { - "$ref": "#/$defs/Scheduler" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Override which SchedulerBackend handles this job, on a machine with more than one; None means the machine's tool layer decides (e.g. from queue_name)" - }, - "parallel_env": { - "default": "smp", - "description": "Grid Engine parallel environment (-pe); ignored by Slurm backends", - "title": "Parallel Env", - "type": "string" - } - }, - "title": "JobAttributes", - "type": "object" - }, - "JobSpec": { - "description": "Job specification (IRI/PSI/J JobSpec subset).\n\nexecutable plus arguments form the command run inside the batch script;\nexecutable may be a shell line (e.g. 'module load foo && srun ./app').\nlauncher, if set, is prepended to executable (e.g. 'srun').\npre_launch / post_launch are script lines inserted before / after.\nIf container is set, the command is wrapped in 'singularity exec'.", - "properties": { - "name": { - "default": "agent-job", - "title": "Name", - "type": "string" - }, - "executable": { - "title": "Executable", - "type": "string" - }, - "arguments": { - "items": { - "type": "string" - }, - "title": "Arguments", - "type": "array" - }, - "directory": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Working directory for the job", - "title": "Directory" - }, - "environment": { - "additionalProperties": { - "type": "string" - }, - "title": "Environment", - "type": "object" - }, - "inherit_environment": { - "default": true, - "description": "Inherit submission environment variables", - "title": "Inherit Environment", - "type": "boolean" - }, - "stdin_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Path to use as stdin (--input)", - "title": "Stdin Path" - }, - "stdout_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Stdout Path" - }, - "stderr_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Stderr Path" - }, - "resources": { - "$ref": "#/$defs/ResourceSpec" - }, - "attributes": { - "$ref": "#/$defs/JobAttributes" - }, - "pre_launch": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Script lines to insert before executable", - "title": "Pre Launch" - }, - "post_launch": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Script lines to insert after executable", - "title": "Post Launch" - }, - "launcher": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Launcher prefix, e.g. 'srun' or 'mpirun -np 4'", - "title": "Launcher" - }, - "container": { - "anyOf": [ - { - "$ref": "#/$defs/Container" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Run inside a Singularity container" - } - }, - "required": [ - "executable" - ], - "title": "JobSpec", - "type": "object" - }, - "JobState": { - "description": "Normalized job states (IRI/PSI-J), mapped from scheduler-native states.", - "enum": [ - "new", - "queued", - "held", - "active", - "completed", - "failed", - "canceled", - "unknown" - ], - "title": "JobState", - "type": "string" - }, - "JobStatus": { - "description": "IRI-compliant job status (state + time + message + exit_code + meta_data).\n\nScheduler-specific detail (native_state, partition, nodes, workdir,\nelapsed, start/end times, queue reason) is carried in meta_data.", - "properties": { - "state": { - "$ref": "#/$defs/JobState" - }, - "time": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Epoch seconds: end_time if finished, start_time if running", - "title": "Time" - }, - "message": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Human-readable status (queue reason, error, etc.)", - "title": "Message" - }, - "exit_code": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Exit Code" - }, - "meta_data": { - "anyOf": [ - { - "additionalProperties": true, - "type": "object" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Scheduler-specific fields: native_state, partition, nodes, workdir, elapsed, etc.", - "title": "Meta Data" - } - }, - "required": [ - "state" - ], - "title": "JobStatus", - "type": "object" - }, - "ResourceSpec": { - "description": "Resources for a job (PSI/J ResourceSpec + a GPU extension).\n\ngpus is a total-for-the-job GPU count extension (not in upstream PSI/J);\ngpu_cores_per_process is the PSI/J standard equivalent. If both are set,\ngpus takes precedence. How gpus maps to a scheduler flag (--gpus,\n--gres=gpu:N, --gpus-per-node) and whether node_count is derived from it\nor must be set explicitly is a per-machine SchedulerBackend concern \u2014\nsee that machine's compute/ module and config.", - "properties": { - "node_count": { - "default": 1, - "title": "Node Count", - "type": "integer" - }, - "process_count": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Total processes (alternative to processes_per_node \u00d7 node_count)", - "title": "Process Count" - }, - "processes_per_node": { - "default": 1, - "title": "Processes Per Node", - "type": "integer" - }, - "cpu_cores_per_process": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cpu Cores Per Process" - }, - "gpu_cores_per_process": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "PSI/J standard GPU field; prefer gpus where a machine supports it", - "title": "Gpu Cores Per Process" - }, - "gpus": { - "default": 0, - "description": "Total GPUs requested for the job (machine-specific extension); 0 means no GPU request", - "title": "Gpus", - "type": "integer" - }, - "exclusive_node_use": { - "default": false, - "description": "Request exclusive node allocation (--exclusive)", - "title": "Exclusive Node Use", - "type": "boolean" - }, - "memory": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Memory per node in bytes (maps to --mem)", - "title": "Memory" - } - }, - "title": "ResourceSpec", - "type": "object" - }, - "Scheduler": { - "description": "Target batch scheduler for a job submission \u2014 only meaningful on a\nmachine that composes more than one SchedulerBackend (e.g. a cluster\nwith both a Slurm partition and a Grid Engine partition). Single-scheduler\nmachines can ignore this field entirely.", - "enum": [ - "slurm", - "gridengine" - ], - "title": "Scheduler", - "type": "string" - }, - "VolumeMount": { - "description": "A host path mounted into a container (IRI VolumeMount).", - "properties": { - "source": { - "description": "Host path to mount", - "title": "Source", - "type": "string" - }, - "target": { - "description": "Path inside the container", - "title": "Target", - "type": "string" - }, - "read_only": { - "default": true, - "description": "Mount as read-only", - "title": "Read Only", - "type": "boolean" - } - }, - "required": [ - "source", - "target" - ], - "title": "VolumeMount", - "type": "object" - } - }, - "description": "IRI Job: identifier + current status + originating spec.", - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "status": { - "anyOf": [ - { - "$ref": "#/$defs/JobStatus" - }, - { - "type": "null" - } - ], - "default": null - }, - "job_spec": { - "anyOf": [ - { - "$ref": "#/$defs/JobSpec" - }, - { - "type": "null" - } - ], - "default": null - } - }, - "required": [ - "id" - ], - "title": "Job", - "type": "object" - } - }, - { - "name": "get_job_statuses", - "description": "Status of several jobs, or \u2014 if job_ids is empty \u2014 every job the\n current user has touched in roughly the last two days (RIKYU has Slurm\n accounting, so this includes finished jobs, not just the live queue).\n (IRI: GET /compute/jobs)", - "inputSchema": { - "properties": { - "job_ids": { - "items": { - "type": "string" - }, - "title": "Job Ids", - "type": "array" - } - }, - "required": [ - "job_ids" - ], - "title": "get_job_statusesArguments", - "type": "object" - }, - "outputSchema": { - "$defs": { - "Container": { - "description": "Container specification (IRI Container); executed via singularity exec.\n\nimage must be a path to a .sif file (absolute or using $HOME) or a\ndocker:// URI. GPU passthrough is added automatically by the rendering\nbackend when the job requests GPUs (vendor-specific flag chosen by that\nmachine's config, e.g. --nv vs --rocm). launcher (e.g. 'srun') is placed\noutside singularity exec so MPI works.", - "properties": { - "image": { - "description": "Singularity image path or URI (e.g. docker://ubuntu:22.04)", - "title": "Image", - "type": "string" - }, - "volume_mounts": { - "items": { - "$ref": "#/$defs/VolumeMount" - }, - "title": "Volume Mounts", - "type": "array" - } - }, - "required": [ - "image" - ], - "title": "Container", - "type": "object" - }, - "Job": { - "description": "IRI Job: identifier + current status + originating spec.", - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "status": { - "anyOf": [ - { - "$ref": "#/$defs/JobStatus" - }, - { - "type": "null" - } - ], - "default": null - }, - "job_spec": { - "anyOf": [ - { - "$ref": "#/$defs/JobSpec" - }, - { - "type": "null" - } - ], - "default": null - } - }, - "required": [ - "id" - ], - "title": "Job", - "type": "object" - }, - "JobAttributes": { - "description": "Scheduler attributes (IRI/PSI/J JobAttributes subset).\n\nqueue_name has no cross-machine default \u2014 each machine's tool layer\nshould supply its own default_partition (from that machine's config)\nwhen a JobSpec omits one.", - "properties": { - "duration": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "string" - } - ], - "default": 3600, - "description": "Wall time as integer seconds or HH:MM:SS / D-HH:MM:SS string", - "title": "Duration" - }, - "queue_name": { - "default": "", - "description": "Scheduler partition/queue; machine-specific default applied by the tool layer if omitted", - "title": "Queue Name", - "type": "string" - }, - "account": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Account/project to charge", - "title": "Account" - }, - "reservation_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Scheduler reservation name (--reservation)", - "title": "Reservation Id" - }, - "custom_attributes": { - "additionalProperties": { - "type": "string" - }, - "title": "Custom Attributes", - "type": "object" - }, - "scheduler": { - "anyOf": [ - { - "$ref": "#/$defs/Scheduler" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Override which SchedulerBackend handles this job, on a machine with more than one; None means the machine's tool layer decides (e.g. from queue_name)" - }, - "parallel_env": { - "default": "smp", - "description": "Grid Engine parallel environment (-pe); ignored by Slurm backends", - "title": "Parallel Env", - "type": "string" - } - }, - "title": "JobAttributes", - "type": "object" - }, - "JobSpec": { - "description": "Job specification (IRI/PSI/J JobSpec subset).\n\nexecutable plus arguments form the command run inside the batch script;\nexecutable may be a shell line (e.g. 'module load foo && srun ./app').\nlauncher, if set, is prepended to executable (e.g. 'srun').\npre_launch / post_launch are script lines inserted before / after.\nIf container is set, the command is wrapped in 'singularity exec'.", - "properties": { - "name": { - "default": "agent-job", - "title": "Name", - "type": "string" - }, - "executable": { - "title": "Executable", - "type": "string" - }, - "arguments": { - "items": { - "type": "string" - }, - "title": "Arguments", - "type": "array" - }, - "directory": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Working directory for the job", - "title": "Directory" - }, - "environment": { - "additionalProperties": { - "type": "string" - }, - "title": "Environment", - "type": "object" - }, - "inherit_environment": { - "default": true, - "description": "Inherit submission environment variables", - "title": "Inherit Environment", - "type": "boolean" - }, - "stdin_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Path to use as stdin (--input)", - "title": "Stdin Path" - }, - "stdout_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Stdout Path" - }, - "stderr_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Stderr Path" - }, - "resources": { - "$ref": "#/$defs/ResourceSpec" - }, - "attributes": { - "$ref": "#/$defs/JobAttributes" - }, - "pre_launch": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Script lines to insert before executable", - "title": "Pre Launch" - }, - "post_launch": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Script lines to insert after executable", - "title": "Post Launch" - }, - "launcher": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Launcher prefix, e.g. 'srun' or 'mpirun -np 4'", - "title": "Launcher" - }, - "container": { - "anyOf": [ - { - "$ref": "#/$defs/Container" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Run inside a Singularity container" - } - }, - "required": [ - "executable" - ], - "title": "JobSpec", - "type": "object" - }, - "JobState": { - "description": "Normalized job states (IRI/PSI-J), mapped from scheduler-native states.", - "enum": [ - "new", - "queued", - "held", - "active", - "completed", - "failed", - "canceled", - "unknown" - ], - "title": "JobState", - "type": "string" - }, - "JobStatus": { - "description": "IRI-compliant job status (state + time + message + exit_code + meta_data).\n\nScheduler-specific detail (native_state, partition, nodes, workdir,\nelapsed, start/end times, queue reason) is carried in meta_data.", - "properties": { - "state": { - "$ref": "#/$defs/JobState" - }, - "time": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Epoch seconds: end_time if finished, start_time if running", - "title": "Time" - }, - "message": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Human-readable status (queue reason, error, etc.)", - "title": "Message" - }, - "exit_code": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Exit Code" - }, - "meta_data": { - "anyOf": [ - { - "additionalProperties": true, - "type": "object" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Scheduler-specific fields: native_state, partition, nodes, workdir, elapsed, etc.", - "title": "Meta Data" - } - }, - "required": [ - "state" - ], - "title": "JobStatus", - "type": "object" - }, - "ResourceSpec": { - "description": "Resources for a job (PSI/J ResourceSpec + a GPU extension).\n\ngpus is a total-for-the-job GPU count extension (not in upstream PSI/J);\ngpu_cores_per_process is the PSI/J standard equivalent. If both are set,\ngpus takes precedence. How gpus maps to a scheduler flag (--gpus,\n--gres=gpu:N, --gpus-per-node) and whether node_count is derived from it\nor must be set explicitly is a per-machine SchedulerBackend concern \u2014\nsee that machine's compute/ module and config.", - "properties": { - "node_count": { - "default": 1, - "title": "Node Count", - "type": "integer" - }, - "process_count": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Total processes (alternative to processes_per_node \u00d7 node_count)", - "title": "Process Count" - }, - "processes_per_node": { - "default": 1, - "title": "Processes Per Node", - "type": "integer" - }, - "cpu_cores_per_process": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cpu Cores Per Process" - }, - "gpu_cores_per_process": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "PSI/J standard GPU field; prefer gpus where a machine supports it", - "title": "Gpu Cores Per Process" - }, - "gpus": { - "default": 0, - "description": "Total GPUs requested for the job (machine-specific extension); 0 means no GPU request", - "title": "Gpus", - "type": "integer" - }, - "exclusive_node_use": { - "default": false, - "description": "Request exclusive node allocation (--exclusive)", - "title": "Exclusive Node Use", - "type": "boolean" - }, - "memory": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Memory per node in bytes (maps to --mem)", - "title": "Memory" - } - }, - "title": "ResourceSpec", - "type": "object" - }, - "Scheduler": { - "description": "Target batch scheduler for a job submission \u2014 only meaningful on a\nmachine that composes more than one SchedulerBackend (e.g. a cluster\nwith both a Slurm partition and a Grid Engine partition). Single-scheduler\nmachines can ignore this field entirely.", - "enum": [ - "slurm", - "gridengine" - ], - "title": "Scheduler", - "type": "string" - }, - "VolumeMount": { - "description": "A host path mounted into a container (IRI VolumeMount).", - "properties": { - "source": { - "description": "Host path to mount", - "title": "Source", - "type": "string" - }, - "target": { - "description": "Path inside the container", - "title": "Target", - "type": "string" - }, - "read_only": { - "default": true, - "description": "Mount as read-only", - "title": "Read Only", - "type": "boolean" - } - }, - "required": [ - "source", - "target" - ], - "title": "VolumeMount", - "type": "object" - } - }, - "properties": { - "result": { - "items": { - "$ref": "#/$defs/Job" - }, - "title": "Result", - "type": "array" - } - }, - "required": [ - "result" - ], - "title": "get_job_statusesOutput", - "type": "object" - } - }, - { - "name": "get_resource", - "description": "Live occupancy for one named partition. (IRI: GET /resources/{name})", - "inputSchema": { - "properties": { - "name": { - "title": "Name", - "type": "string" - } - }, - "required": [ - "name" - ], - "title": "get_resourceArguments", - "type": "object" - } - }, - { - "name": "get_resources", - "description": "Live occupancy for RIKYU's compute partitions (\"resources\" in IRI\n terms) via sinfo \u2014 allocated/idle/other/total node counts, i.e. \"will a\n job start soon\". RIKYU has exactly one partition, \"gpu\", covering all\n 400 nodes, but the occupancy numbers themselves change constantly, so\n this is a live query (hpc_agent_core's SlurmBackend.get_live_resources),\n not the static rikyu_config.json get_facility reads from.\n (IRI: GET /resources)\n ", - "inputSchema": { - "properties": {}, - "title": "get_resourcesArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "items": { - "additionalProperties": true, - "type": "object" - }, - "title": "Result", - "type": "array" - } - }, - "required": [ - "result" - ], - "title": "get_resourcesOutput", - "type": "object" - } - }, - { - "name": "run_command_on_cluster", - "description": "Run an arbitrary shell command on the login node (extension \u2014 not an\n IRI endpoint). Before calling this, show the user the exact command (or\n script) and a one-line explanation of what it does, then call it \u2014 skip\n the preview only if the user explicitly asked to just run something. Do\n not run heavy computation on the login node \u2014 submit a job instead.\n ", - "inputSchema": { - "properties": { - "command": { - "title": "Command", - "type": "string" - } - }, - "required": [ - "command" - ], - "title": "run_command_on_clusterArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "run_command_on_clusterOutput", - "type": "object" - } - }, - { - "name": "submit_job", - "description": "Submit a job to RIKYU's Slurm scheduler. Show the user the spec\n before submitting unless they asked to just run it (mirrors\n run_command_on_cluster's rule below). If spec.attributes.queue_name is\n left blank, it defaults to RIKYU's only partition, \"gpu\". (IRI: POST /compute/job)\n ", - "inputSchema": { - "$defs": { - "Container": { - "description": "Container specification (IRI Container); executed via singularity exec.\n\nimage must be a path to a .sif file (absolute or using $HOME) or a\ndocker:// URI. GPU passthrough is added automatically by the rendering\nbackend when the job requests GPUs (vendor-specific flag chosen by that\nmachine's config, e.g. --nv vs --rocm). launcher (e.g. 'srun') is placed\noutside singularity exec so MPI works.", - "properties": { - "image": { - "description": "Singularity image path or URI (e.g. docker://ubuntu:22.04)", - "title": "Image", - "type": "string" - }, - "volume_mounts": { - "items": { - "$ref": "#/$defs/VolumeMount" - }, - "title": "Volume Mounts", - "type": "array" - } - }, - "required": [ - "image" - ], - "title": "Container", - "type": "object" - }, - "JobAttributes": { - "description": "Scheduler attributes (IRI/PSI/J JobAttributes subset).\n\nqueue_name has no cross-machine default \u2014 each machine's tool layer\nshould supply its own default_partition (from that machine's config)\nwhen a JobSpec omits one.", - "properties": { - "duration": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "string" - } - ], - "default": 3600, - "description": "Wall time as integer seconds or HH:MM:SS / D-HH:MM:SS string", - "title": "Duration" - }, - "queue_name": { - "default": "", - "description": "Scheduler partition/queue; machine-specific default applied by the tool layer if omitted", - "title": "Queue Name", - "type": "string" - }, - "account": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Account/project to charge", - "title": "Account" - }, - "reservation_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Scheduler reservation name (--reservation)", - "title": "Reservation Id" - }, - "custom_attributes": { - "additionalProperties": { - "type": "string" - }, - "title": "Custom Attributes", - "type": "object" - }, - "scheduler": { - "anyOf": [ - { - "$ref": "#/$defs/Scheduler" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Override which SchedulerBackend handles this job, on a machine with more than one; None means the machine's tool layer decides (e.g. from queue_name)" - }, - "parallel_env": { - "default": "smp", - "description": "Grid Engine parallel environment (-pe); ignored by Slurm backends", - "title": "Parallel Env", - "type": "string" - } - }, - "title": "JobAttributes", - "type": "object" - }, - "JobSpec": { - "description": "Job specification (IRI/PSI/J JobSpec subset).\n\nexecutable plus arguments form the command run inside the batch script;\nexecutable may be a shell line (e.g. 'module load foo && srun ./app').\nlauncher, if set, is prepended to executable (e.g. 'srun').\npre_launch / post_launch are script lines inserted before / after.\nIf container is set, the command is wrapped in 'singularity exec'.", - "properties": { - "name": { - "default": "agent-job", - "title": "Name", - "type": "string" - }, - "executable": { - "title": "Executable", - "type": "string" - }, - "arguments": { - "items": { - "type": "string" - }, - "title": "Arguments", - "type": "array" - }, - "directory": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Working directory for the job", - "title": "Directory" - }, - "environment": { - "additionalProperties": { - "type": "string" - }, - "title": "Environment", - "type": "object" - }, - "inherit_environment": { - "default": true, - "description": "Inherit submission environment variables", - "title": "Inherit Environment", - "type": "boolean" - }, - "stdin_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Path to use as stdin (--input)", - "title": "Stdin Path" - }, - "stdout_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Stdout Path" - }, - "stderr_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Stderr Path" - }, - "resources": { - "$ref": "#/$defs/ResourceSpec" - }, - "attributes": { - "$ref": "#/$defs/JobAttributes" - }, - "pre_launch": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Script lines to insert before executable", - "title": "Pre Launch" - }, - "post_launch": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Script lines to insert after executable", - "title": "Post Launch" - }, - "launcher": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Launcher prefix, e.g. 'srun' or 'mpirun -np 4'", - "title": "Launcher" - }, - "container": { - "anyOf": [ - { - "$ref": "#/$defs/Container" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Run inside a Singularity container" - } - }, - "required": [ - "executable" - ], - "title": "JobSpec", - "type": "object" - }, - "ResourceSpec": { - "description": "Resources for a job (PSI/J ResourceSpec + a GPU extension).\n\ngpus is a total-for-the-job GPU count extension (not in upstream PSI/J);\ngpu_cores_per_process is the PSI/J standard equivalent. If both are set,\ngpus takes precedence. How gpus maps to a scheduler flag (--gpus,\n--gres=gpu:N, --gpus-per-node) and whether node_count is derived from it\nor must be set explicitly is a per-machine SchedulerBackend concern \u2014\nsee that machine's compute/ module and config.", - "properties": { - "node_count": { - "default": 1, - "title": "Node Count", - "type": "integer" - }, - "process_count": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Total processes (alternative to processes_per_node \u00d7 node_count)", - "title": "Process Count" - }, - "processes_per_node": { - "default": 1, - "title": "Processes Per Node", - "type": "integer" - }, - "cpu_cores_per_process": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Cpu Cores Per Process" - }, - "gpu_cores_per_process": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "PSI/J standard GPU field; prefer gpus where a machine supports it", - "title": "Gpu Cores Per Process" - }, - "gpus": { - "default": 0, - "description": "Total GPUs requested for the job (machine-specific extension); 0 means no GPU request", - "title": "Gpus", - "type": "integer" - }, - "exclusive_node_use": { - "default": false, - "description": "Request exclusive node allocation (--exclusive)", - "title": "Exclusive Node Use", - "type": "boolean" - }, - "memory": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Memory per node in bytes (maps to --mem)", - "title": "Memory" - } - }, - "title": "ResourceSpec", - "type": "object" - }, - "Scheduler": { - "description": "Target batch scheduler for a job submission \u2014 only meaningful on a\nmachine that composes more than one SchedulerBackend (e.g. a cluster\nwith both a Slurm partition and a Grid Engine partition). Single-scheduler\nmachines can ignore this field entirely.", - "enum": [ - "slurm", - "gridengine" - ], - "title": "Scheduler", - "type": "string" - }, - "VolumeMount": { - "description": "A host path mounted into a container (IRI VolumeMount).", - "properties": { - "source": { - "description": "Host path to mount", - "title": "Source", - "type": "string" - }, - "target": { - "description": "Path inside the container", - "title": "Target", - "type": "string" - }, - "read_only": { - "default": true, - "description": "Mount as read-only", - "title": "Read Only", - "type": "boolean" - } - }, - "required": [ - "source", - "target" - ], - "title": "VolumeMount", - "type": "object" - } - }, - "properties": { - "spec": { - "$ref": "#/$defs/JobSpec" - } - }, - "required": [ - "spec" - ], - "title": "submit_jobArguments", - "type": "object" - } - }, - { - "name": "update_job", - "description": "Modify an already-submitted job's Slurm attributes via `scontrol\n update`, e.g. {\"TimeLimit\": \"02:00:00\"} to extend the wall time. Only\n affects jobs still queued or running, and is subject to Slurm's own\n permission rules (some fields can only be lowered, not raised, by a\n non-admin). (IRI: PUT /compute/job/{job_id})\n ", - "inputSchema": { - "properties": { - "job_id": { - "title": "Job Id", - "type": "string" - }, - "updates": { - "additionalProperties": { - "type": "string" - }, - "title": "Updates", - "type": "object" - } - }, - "required": [ - "job_id", - "updates" - ], - "title": "update_jobArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "update_jobOutput", - "type": "object" - } - } - ] - }, - { - "name": "rikyu-docs", - "source_path": ".claude/skills/htn-creator-workspace/servers/rikyu_mcp/docs_server.py", - "source_digest": "sha256:527acd8f431571903257dd51578b2a21bf8bb27b20d274e6fdfe82169968d638", - "transport": "stdio", - "tools": [ - { - "name": "list_doc_sections", - "description": "List every section of the bundled guide (table of contents).", - "inputSchema": { - "properties": {}, - "title": "list_doc_sectionsArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "list_doc_sectionsOutput", - "type": "object" - } - }, - { - "name": "read_doc_section", - "description": "Read one guide section in full by its breadcrumb.\n\n Args:\n breadcrumb: Section path as shown by list_doc_sections or\n search_docs, e.g. 'Running jobs'. Partial matches work.\n ", - "inputSchema": { - "properties": { - "breadcrumb": { - "title": "Breadcrumb", - "type": "string" - } - }, - "required": [ - "breadcrumb" - ], - "title": "read_doc_sectionArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "read_doc_sectionOutput", - "type": "object" - } - }, - { - "name": "search_docs", - "description": "Search the machine's bundled documentation guide.\n\n Always call this first before answering any machine-specific\n question \u2014 job submission, modules, storage, login procedure, or\n any other cluster-specific detail. Do not rely on prior knowledge or\n the orientation facts embedded in skills \u2014 those are fallback aids,\n not authoritative.\n\n If a result carries no \"Source:\" line, that's deliberate (see this\n server's module docstring) \u2014 do not invent or guess a URL to send\n the user to.\n\n If this tool errors or returns no results, fall back to the inline\n facts in the active skill and note that docs were unavailable.\n\n When results begin with `[search_method: bm25]`, inform the user\n that keyword search was used because the embedding server could not\n be reached. Results may miss semantically relevant sections that\n don't share exact keywords with the query.\n\n Args:\n query: Natural-language question or keywords.\n top_k: Number of sections to return.\n ", - "inputSchema": { - "properties": { - "query": { - "title": "Query", - "type": "string" - }, - "top_k": { - "default": 4, - "title": "Top K", - "type": "integer" - } - }, - "required": [ - "query" - ], - "title": "search_docsArguments", - "type": "object" - }, - "outputSchema": { - "properties": { - "result": { - "title": "Result", - "type": "string" - } - }, - "required": [ - "result" - ], - "title": "search_docsOutput", - "type": "object" - } - } - ] - } - ] -} diff --git a/crates/candler-schemas/tests/it/catalog_fixtures.rs b/crates/candler-schemas/tests/it/catalog_fixtures.rs deleted file mode 100644 index 7e7eaed2..00000000 --- a/crates/candler-schemas/tests/it/catalog_fixtures.rs +++ /dev/null @@ -1,522 +0,0 @@ -//! The tool-catalog snapshot against the MCP specification and two catalogs captured from real -//! servers. -//! -//! The specification fixtures are tool objects the MCP `Tool` definition accepts; the snapshot -//! must accept them and keep every key. The real catalogs carry `servers_dir` and -//! `stubbed_modules` at the top level and the tag `tool-catalog-snapshot/0`; these tests rewrite -//! the tag to `SCHEMA_TAG` and move the two keys under `ext`, then check the result. - -// Marks the file as test code, so that clippy's test allowances reach its helpers. -#![cfg(test)] - -use std::fs; -use std::path::{Path, PathBuf}; -use std::slice; -use std::sync::LazyLock; - -use candler_schemas::catalog::{CatalogSnapshot, SCHEMA_TAG, Tool}; -use jsonschema::Validator; -use proptest::prelude::*; -use serde_json::{Map, Value, json}; - -fn manifest_path(parts: &[&str]) -> PathBuf { - let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - path.extend(parts); - path -} - -fn read_json(path: &Path) -> Value { - let text = fs::read_to_string(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - serde_json::from_str(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())) -} - -/// The snapshot schema as committed. -static SNAPSHOT_SCHEMA: LazyLock<Value> = - LazyLock::new(|| read_json(&manifest_path(&["schema", "catalog-snapshot.schema.json"]))); - -static SNAPSHOT: LazyLock<Validator> = LazyLock::new(|| { - jsonschema::validator_for(&SNAPSHOT_SCHEMA).expect("the snapshot schema compiles") -}); - -/// The `Tool` definition inside the snapshot schema. -static OUR_TOOL: LazyLock<Validator> = LazyLock::new(|| { - let schema = json!({ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$ref": "#/$defs/Tool", - "$defs": SNAPSHOT_SCHEMA["$defs"].clone(), - }); - jsonschema::validator_for(&schema).expect("the Tool definition compiles") -}); - -/// The `Tool` definition of the MCP specification, validated by the vendored schema file. -static MCP_TOOL: LazyLock<Validator> = LazyLock::new(|| { - let mut schema = read_json(&manifest_path(&[ - "tests", - "fixtures", - "spec", - "mcp-2026-07-28.schema.json", - ])); - schema["$ref"] = json!("#/$defs/Tool"); - jsonschema::validator_for(&schema).expect("the MCP schema compiles") -}); - -/// A snapshot of one server around `tools`. -fn wrap(tools: &[Value]) -> Value { - json!({ - "schema": SCHEMA_TAG, - "captured_at": "2026-10-28T01:09:04+00:00", - "provider": "capture@1", - "servers": [{ - "name": "server", - "source_path": "servers/server.py", - "source_digest": format!("sha256:{}", "cd".repeat(32)), - "transport": "stdio", - "tools": tools, - }], - }) -} - -// ---- the MCP specification ------------------------------------------------------------------ - -fn spec_tools() -> Vec<(String, Value)> { - let dir = manifest_path(&["tests", "fixtures", "spec", "tools"]); - let mut files: Vec<PathBuf> = fs::read_dir(&dir) - .expect("the spec tool directory is readable") - .map(|entry| entry.expect("a directory entry").path()) - .filter(|path| path.extension().is_some_and(|ext| ext == "json")) - .collect(); - files.sort(); - files - .iter() - .map(|path| { - let name = path - .file_name() - // BORROW: .into_owned() makes the owned file name the pair holds - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_default(); - (name, read_json(path)) - }) - .collect() -} - -#[test] -fn catalog_spec_tools_are_valid_mcp_tools() { - let tools = spec_tools(); - assert_eq!(tools.len(), 10); - for (name, tool) in &tools { - assert!(MCP_TOOL.is_valid(tool), "MCP rejects {name}"); - } -} - -#[test] -fn catalog_spec_tools_validate_and_round_trip_inside_a_snapshot() { - for (name, tool) in spec_tools() { - let snapshot = wrap(slice::from_ref(&tool)); - assert!(SNAPSHOT.is_valid(&snapshot), "the schema rejects {name}"); - assert!( - OUR_TOOL.is_valid(&tool), - "the Tool definition rejects {name}" - ); - - let read: CatalogSnapshot = - serde_json::from_value(snapshot.clone()).unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!( - serde_json::to_value(&read).expect("writes"), - snapshot, - "{name}" - ); - - let alone: Tool = serde_json::from_value(tool.clone()).expect("a tool reads"); - assert_eq!( - serde_json::to_value(&alone).expect("writes"), - tool, - "{name}" - ); - } -} - -#[test] -fn catalog_full_spec_tool_keeps_icons_and_meta_as_extra_keys() { - let full = spec_tools() - .into_iter() - .find(|(name, _)| name == "full.json") - .map(|(_, tool)| tool) - .expect("full.json is among the spec tools"); - let tool: Tool = serde_json::from_value(full.clone()).expect("reads"); - assert_eq!(tool.title(), Some("Document Search")); - assert!(tool.output_schema().is_some()); - assert_eq!(tool.annotations().map(Map::len), Some(5)); - // BORROW: explicit .as_str() to compare the keys with literals - let mut extra: Vec<&str> = tool.extra().keys().map(String::as_str).collect(); - extra.sort_unstable(); - assert_eq!(extra, ["_meta", "icons"]); - assert_eq!(tool.extra().get("icons"), full.get("icons")); -} - -/// Where the snapshot's `Tool` and the MCP `Tool` agree, where the snapshot accepts more (it records -/// what a server offered) and where it accepts less (an empty name). -/// -/// Each row: the tool, whether MCP accepts it, whether the snapshot accepts it. The schema and -/// the Rust reader agree on every row. -#[test] -fn catalog_tool_verdicts_of_mcp_and_the_snapshot() { - let object = json!({"type": "object"}); - let rows: Vec<(&str, Value, bool, bool)> = vec![ - ( - "required keys only", - json!({"name": "t", "inputSchema": object}), - true, - true, - ), - ( - "empty name", - json!({"name": "", "inputSchema": object}), - true, - false, - ), - ( - "an unknown key", - json!({"name": "t", "inputSchema": object, "x-y": [1]}), - true, - true, - ), - ( - "an unknown key of null", - json!({"name": "t", "inputSchema": object, "x": null}), - true, - true, - ), - ( - "an array output schema", - json!({"name": "t", "inputSchema": object, "outputSchema": {"type": "array"}}), - true, - true, - ), - ( - "an annotation of an unknown key", - json!({"name": "t", "inputSchema": object, "annotations": {"mine": null}}), - true, - true, - ), - ("no input schema", json!({"name": "t"}), false, false), - ("no name", json!({"inputSchema": object}), false, false), - ( - "a string input schema", - json!({"name": "t", "inputSchema": "object"}), - false, - false, - ), - ( - "a numeric title", - json!({"name": "t", "inputSchema": object, "title": 5}), - false, - false, - ), - ( - "a null description", - json!({"name": "t", "inputSchema": object, "description": null}), - false, - false, - ), - ( - "a null output schema", - json!({"name": "t", "inputSchema": object, "outputSchema": null}), - false, - false, - ), - ( - "a null annotations", - json!({"name": "t", "inputSchema": object, "annotations": null}), - false, - false, - ), - ( - "an input schema without a type", - json!({"name": "t", "inputSchema": {}}), - false, - true, - ), - ( - "an input schema of another type", - json!({"name": "t", "inputSchema": {"type": "string"}}), - false, - true, - ), - ( - "a mistyped annotation hint", - json!({"name": "t", "inputSchema": object, "annotations": {"readOnlyHint": "yes"}}), - false, - true, - ), - ( - "icons that are not an array", - json!({"name": "t", "inputSchema": object, "icons": "x"}), - false, - true, - ), - ( - "an icon without a source", - json!({"name": "t", "inputSchema": object, "icons": [{}]}), - false, - true, - ), - ( - "a meta that is not an object", - json!({"name": "t", "inputSchema": object, "_meta": 5}), - false, - true, - ), - ]; - for (what, tool, mcp, ours) in rows { - assert_eq!(MCP_TOOL.is_valid(&tool), mcp, "MCP, {what}"); - assert_eq!(OUR_TOOL.is_valid(&tool), ours, "the schema, {what}"); - assert_eq!( - serde_json::from_value::<Tool>(tool.clone()).is_ok(), - ours, - "the reader, {what}" - ); - let snapshot = wrap(slice::from_ref(&tool)); - assert_eq!(SNAPSHOT.is_valid(&snapshot), ours, "the snapshot, {what}"); - assert_eq!( - serde_json::from_value::<CatalogSnapshot>(snapshot).is_ok(), - ours, - "the snapshot reader, {what}" - ); - } -} - -fn arb_json() -> impl Strategy<Value = Value> { - let leaf = prop_oneof![ - Just(Value::Null), - any::<bool>().prop_map(Value::Bool), - any::<i64>().prop_map(Value::from), - "\\PC{0,8}".prop_map(Value::String), - ]; - leaf.prop_recursive(2, 12, 3, |inner| { - prop_oneof![ - prop::collection::vec(inner.clone(), 0..3).prop_map(Value::Array), - prop::collection::btree_map("\\PC{0,5}", inner, 0..3) - .prop_map(|map| Value::Object(map.into_iter().collect())), - ] - }) -} - -/// A tool of the MCP `Tool` definition with every optional key drawn independently. -fn arb_mcp_tool() -> impl Strategy<Value = Value> { - let icon = ( - "https://example\\.com/[a-z]{1,8}\\.png", - proptest::option::of("image/[a-z]{3,4}"), - proptest::option::of(prop::collection::vec("[0-9]{2}x[0-9]{2}|any", 0..3)), - proptest::option::of(prop_oneof![Just("dark"), Just("light")]), - ) - .prop_map(|(src, mime, sizes, theme)| { - let mut icon = json!({"src": src}); - if let Some(mime) = mime { - icon["mimeType"] = json!(mime); - } - if let Some(sizes) = sizes { - icon["sizes"] = json!(sizes); - } - if let Some(theme) = theme { - icon["theme"] = json!(theme); - } - icon - }); - let hints = ( - proptest::option::of(any::<bool>()), - proptest::option::of(any::<bool>()), - proptest::option::of(any::<bool>()), - proptest::option::of(any::<bool>()), - proptest::option::of("\\PC{0,8}"), - ) - .prop_map(|(read_only, destructive, idempotent, open_world, title)| { - let mut hints = Map::new(); - for (key, flag) in [ - ("readOnlyHint", read_only), - ("destructiveHint", destructive), - ("idempotentHint", idempotent), - ("openWorldHint", open_world), - ] { - if let Some(flag) = flag { - hints.insert(String::from(key), json!(flag)); - } - } - if let Some(title) = title { - hints.insert(String::from("title"), json!(title)); - } - Value::Object(hints) - }); - ( - "\\PC{1,8}", - proptest::option::of("\\PC{0,8}"), - proptest::option::of("\\PC{0,8}"), - prop::collection::btree_map("\\PC{0,5}", arb_json(), 0..3), - proptest::option::of(prop::collection::btree_map("\\PC{0,5}", arb_json(), 0..3)), - proptest::option::of(hints), - proptest::option::of(prop::collection::vec(icon, 0..3)), - proptest::option::of(prop::collection::btree_map("\\PC{0,5}", arb_json(), 0..3)), - ) - .prop_map( - |(name, title, description, input, output, annotations, icons, meta)| { - let mut input: Map<String, Value> = input.into_iter().collect(); - input.insert(String::from("type"), json!("object")); - let mut tool = json!({"name": name, "inputSchema": input}); - if let Some(title) = title { - tool["title"] = json!(title); - } - if let Some(description) = description { - tool["description"] = json!(description); - } - if let Some(output) = output { - tool["outputSchema"] = Value::Object(output.into_iter().collect()); - } - if let Some(annotations) = annotations { - tool["annotations"] = annotations; - } - if let Some(icons) = icons { - tool["icons"] = json!(icons); - } - if let Some(meta) = meta { - tool["_meta"] = Value::Object(meta.into_iter().collect()); - } - tool - }, - ) -} - -proptest! { - #![proptest_config(ProptestConfig::with_cases(128))] - - /// The snapshot narrows MCP only by requiring a non-empty name: any other tool the MCP `Tool` - /// definition accepts is accepted by the schema and the reader and is written back unchanged. - #[test] - fn catalog_accepts_every_tool_mcp_accepts(tool in arb_mcp_tool()) { - prop_assert!(MCP_TOOL.is_valid(&tool), "the generator makes MCP tools: {tool:#}"); - let snapshot = wrap(slice::from_ref(&tool)); - prop_assert!(SNAPSHOT.is_valid(&snapshot), "{snapshot:#}"); - let read: CatalogSnapshot = serde_json::from_str(&serde_json::to_string(&snapshot)?)?; - prop_assert_eq!(serde_json::to_value(&read)?, snapshot); - } -} - -// ---- real catalogs -------------------------------------------------------------------------- - -/// The text of a captured catalog. -fn catalog_text(name: &str) -> String { - let path = manifest_path(&["tests", "fixtures", "upstream", name]); - fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) -} - -/// A captured catalog as JSON. -fn catalog(name: &str) -> Value { - serde_json::from_str(&catalog_text(name)).expect("a captured catalog is JSON") -} - -/// Rewrites a captured catalog to the shape of `SCHEMA_TAG`: sets the tag and moves -/// `servers_dir` and `stubbed_modules` under `ext`. -fn rewrite(mut snapshot: Value) -> Value { - let object = snapshot.as_object_mut().expect("a snapshot is an object"); - assert_eq!( - object.get("schema"), - Some(&json!("tool-catalog-snapshot/0")), - "the catalog carries the `/0` tag" - ); - object.insert(String::from("schema"), json!(SCHEMA_TAG)); - let mut ext = Map::new(); - for key in ["servers_dir", "stubbed_modules"] { - let value = object - .remove(key) - .unwrap_or_else(|| panic!("the catalog has {key}")); - ext.insert(String::from(key), value); - } - object.insert(String::from("ext"), Value::Object(ext)); - snapshot -} - -fn tool_counts(snapshot: &Value) -> Vec<usize> { - snapshot["servers"] - .as_array() - .expect("servers is an array") - .iter() - .map(|server| server["tools"].as_array().map_or(0, Vec::len)) - .collect() -} - -fn assert_catalog_round_trips(file: &str, counts: &[usize]) { - let captured = catalog(file); - let rewritten = rewrite(captured.clone()); - assert_eq!(tool_counts(&rewritten), counts, "{file}"); - - assert!(SNAPSHOT.is_valid(&rewritten), "the schema rejects {file}"); - let snapshot: CatalogSnapshot = - serde_json::from_value(rewritten.clone()).unwrap_or_else(|e| panic!("{file}: {e}")); - assert_eq!( - serde_json::to_value(&snapshot).expect("writes"), - rewritten, - "{file} does not round-trip" - ); - // The same snapshot read from text, pretty-printed and compact. - for text in [ - serde_json::to_string_pretty(&rewritten).expect("writes"), - serde_json::to_string(&rewritten).expect("writes"), - ] { - let from_text: CatalogSnapshot = - serde_json::from_str(&text).unwrap_or_else(|e| panic!("{file}: {e}")); - assert_eq!(from_text, snapshot, "{file} reads differently from text"); - } - assert_eq!(snapshot.servers().len(), counts.len()); - let read_counts: Vec<usize> = snapshot.servers().iter().map(|s| s.tools().len()).collect(); - assert_eq!(read_counts, counts); - let ext = snapshot.ext().expect("the rewrite writes ext"); - assert_eq!(ext.get("servers_dir"), captured.get("servers_dir")); - assert_eq!(ext.get("stubbed_modules"), captured.get("stubbed_modules")); - - // The catalog as captured carries the `/0` tag and top-level keys the schema does not allow. - assert!( - !SNAPSHOT.is_valid(&captured), - "the schema accepts the `/0` catalog {file}" - ); - assert!( - serde_json::from_value::<CatalogSnapshot>(captured.clone()).is_err(), - "Rust accepts the `/0` catalog {file}" - ); - assert!(serde_json::from_str::<CatalogSnapshot>(&catalog_text(file)).is_err()); - - // The tag and the moved keys are each checked on their own. - let mut tag_only = captured; - tag_only["schema"] = json!(SCHEMA_TAG); - assert!( - !SNAPSHOT.is_valid(&tag_only), - "the schema accepts the top-level keys of {file}" - ); - let mut moved_only = rewritten; - moved_only["schema"] = json!("tool-catalog-snapshot/0"); - assert!(!SNAPSHOT.is_valid(&moved_only)); - assert!(serde_json::from_value::<CatalogSnapshot>(moved_only).is_err()); -} - -#[test] -fn catalog_rikyu_snapshot_validates_and_round_trips() { - assert_catalog_round_trips("rikyu_mcp.json", &[26, 3]); - let total: usize = tool_counts(&catalog("rikyu_mcp.json")).iter().sum(); - assert_eq!(total, 29); -} - -#[test] -fn catalog_bio_opentrons_snapshot_validates_and_round_trips() { - assert_catalog_round_trips("bio_opentrons.json", &[1, 10, 19, 6]); -} - -/// The reader ignores the top-level keys it does not know: `servers_dir` and `stubbed_modules` -/// under the tag `SCHEMA_TAG` are read and not written back, and only the schema refuses them. -#[test] -fn catalog_unknown_top_level_keys_are_dropped_by_the_reader() { - let mut tag_only = catalog("bio_opentrons.json"); - tag_only["schema"] = json!(SCHEMA_TAG); - assert!(!SNAPSHOT.is_valid(&tag_only)); - let snapshot: CatalogSnapshot = serde_json::from_value(tag_only).expect("reads"); - assert!(snapshot.ext().is_none()); - let written = serde_json::to_value(&snapshot).expect("writes"); - assert!(written.get("servers_dir").is_none()); - assert!(written.get("stubbed_modules").is_none()); -} diff --git a/crates/candler-schemas/tests/it/catalog_properties.rs b/crates/candler-schemas/tests/it/catalog_properties.rs deleted file mode 100644 index 7eb4227c..00000000 --- a/crates/candler-schemas/tests/it/catalog_properties.rs +++ /dev/null @@ -1,745 +0,0 @@ -//! Properties of the tool-catalog snapshot: generated snapshots are valid by the committed schema -//! and by the Rust reader, and round-trip without loss; each rule the format states is refused by -//! both. The cases where the schema and the Rust reader differ are pinned at the end. - -// Marks the file as test code, so that clippy's test allowances reach its helpers. -#![cfg(test)] - -use std::collections::{BTreeMap, BTreeSet}; -use std::fs; -use std::path::{Path, PathBuf}; -use std::sync::LazyLock; - -use candler_schemas::catalog::{CatalogServer, CatalogSnapshot, SCHEMA_TAG, Tool, Transport}; -use candler_schemas::primitives::{Digest, NameToken, RelPath, Timestamp}; -use jsonschema::Validator; -use proptest::prelude::*; -use serde_json::{Map, Value, json}; - -const NAMED_TOOL_KEYS: [&str; 6] = [ - "name", - "title", - "description", - "inputSchema", - "outputSchema", - "annotations", -]; - -const TRANSPORTS: [(&str, Transport); 3] = [ - ("stdio", Transport::Stdio), - ("http", Transport::Http), - ("sse", Transport::Sse), -]; - -fn schema_path() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("schema") - .join("catalog-snapshot.schema.json") -} - -fn read_schema() -> Value { - let text = fs::read_to_string(schema_path()).expect("the committed schema is readable"); - serde_json::from_str(&text).expect("the committed schema is JSON") -} - -static SCHEMA: LazyLock<Validator> = LazyLock::new(|| { - jsonschema::validator_for(&read_schema()).expect("the committed schema compiles") -}); - -// ---- generated snapshots -------------------------------------------------------------------- - -/// Any JSON value: `null`, booleans, integers, finite floats (zeros of both signs and subnormals -/// included), strings, arrays and objects. -fn arb_json() -> impl Strategy<Value = Value> { - let leaf = prop_oneof![ - Just(Value::Null), - any::<bool>().prop_map(Value::Bool), - any::<i64>().prop_map(Value::from), - any::<u64>().prop_map(Value::from), - (prop::num::f64::NORMAL | prop::num::f64::SUBNORMAL | prop::num::f64::ZERO) - .prop_filter_map("finite", |f| { - serde_json::Number::from_f64(f).map(Value::Number) - }), - Just(Value::from(-0.0_f64)), - Just(Value::from(0.0_f64)), - "\\PC{0,8}".prop_map(Value::String), - ]; - leaf.prop_recursive(3, 24, 4, |inner| { - prop_oneof![ - prop::collection::vec(inner.clone(), 0..4).prop_map(Value::Array), - prop::collection::btree_map("\\PC{0,6}", inner, 0..4) - .prop_map(|map| Value::Object(map.into_iter().collect())), - ] - }) -} - -fn arb_object() -> impl Strategy<Value = Map<String, Value>> { - prop::collection::btree_map("\\PC{0,6}", arb_json(), 0..4) - .prop_map(|map| map.into_iter().collect()) -} - -/// Objects whose keys are none of the named keys of a tool. -fn arb_extras() -> impl Strategy<Value = Map<String, Value>> { - let key = "\\PC{0,6}".prop_filter("a named key", |key| { - !NAMED_TOOL_KEYS.iter().any(|named| named == key) - }); - prop::collection::btree_map(key, arb_json(), 0..4).prop_map(|map| map.into_iter().collect()) -} - -#[derive(Debug, Clone)] -struct ToolParts { - name: String, - title: Option<String>, - description: Option<String>, - input_schema: Map<String, Value>, - output_schema: Option<Map<String, Value>>, - annotations: Option<Map<String, Value>>, - extra: Map<String, Value>, -} - -impl ToolParts { - /// The JSON the parts stand for, assembled without the library. - fn value(&self) -> Value { - let mut tool = self.extra.clone(); - tool.insert(String::from("name"), Value::String(self.name.clone())); - tool.insert( - String::from("inputSchema"), - Value::Object(self.input_schema.clone()), - ); - for (key, text) in [("title", &self.title), ("description", &self.description)] { - if let Some(text) = text { - tool.insert(String::from(key), Value::String(text.clone())); - } - } - for (key, object) in [ - ("outputSchema", &self.output_schema), - ("annotations", &self.annotations), - ] { - if let Some(object) = object { - tool.insert(String::from(key), Value::Object(object.clone())); - } - } - Value::Object(tool) - } - - /// The tool the parts stand for, built through the library. - fn built(&self) -> Tool { - let mut tool = Tool::new(self.name.clone(), self.input_schema.clone()) - .expect("generated tool names are not empty"); - if let Some(title) = &self.title { - tool = tool.with_title(title.clone()); - } - if let Some(description) = &self.description { - tool = tool.with_description(description.clone()); - } - if let Some(output_schema) = &self.output_schema { - tool = tool.with_output_schema(output_schema.clone()); - } - if let Some(annotations) = &self.annotations { - tool = tool.with_annotations(annotations.clone()); - } - for (key, value) in &self.extra { - tool = tool - .with_extra(key.clone(), value.clone()) - .expect("generated extra keys are not named keys"); - } - tool - } -} - -/// The items whose key has not occurred before, in order. -fn distinct_by<T>(items: Vec<T>, key: impl Fn(&T) -> String) -> Vec<T> { - let mut seen = BTreeSet::new(); - items - .into_iter() - .filter(|item| seen.insert(key(item))) - .collect() -} - -fn arb_tool() -> impl Strategy<Value = ToolParts> { - ( - "\\PC{1,8}", - proptest::option::of("\\PC{0,8}"), - proptest::option::of("\\PC{0,8}"), - arb_object(), - proptest::option::of(arb_object()), - proptest::option::of(arb_object()), - arb_extras(), - ) - .prop_map( - |(name, title, description, input_schema, output_schema, annotations, extra)| { - ToolParts { - name, - title, - description, - input_schema, - output_schema, - annotations, - extra, - } - }, - ) -} - -#[derive(Debug, Clone)] -struct ServerParts { - name: String, - source_path: String, - source_digest: String, - transport: (&'static str, Transport), - tools: Vec<ToolParts>, -} - -impl ServerParts { - fn value(&self) -> Value { - json!({ - "name": self.name, - "source_path": self.source_path, - "source_digest": self.source_digest, - "transport": self.transport.0, - "tools": self.tools.iter().map(ToolParts::value).collect::<Vec<_>>(), - }) - } - - fn built(&self) -> CatalogServer { - CatalogServer::new( - self.name.clone(), - self.source_path - .parse::<RelPath>() - .expect("generated paths are valid"), - self.source_digest - .parse::<Digest>() - .expect("generated digests are valid"), - self.transport.1, - self.tools.iter().map(ToolParts::built).collect(), - ) - .expect("generated server and tool names are valid") - } -} - -fn arb_server(min_tools: usize) -> impl Strategy<Value = ServerParts> { - ( - "\\PC{1,8}", - "[A-Za-z0-9_-][A-Za-z0-9._-]{0,6}(/[A-Za-z0-9_-][A-Za-z0-9._-]{0,6}){0,3}", - "[0-9a-f]{64}".prop_map(|hex| format!("sha256:{hex}")), - prop::sample::select(TRANSPORTS.to_vec()), - prop::collection::vec(arb_tool(), min_tools..4), - ) - .prop_map( - |(name, source_path, source_digest, transport, tools)| ServerParts { - name, - source_path, - source_digest, - transport, - tools: distinct_by(tools, |tool| tool.name.clone()), - }, - ) -} - -#[derive(Debug, Clone)] -struct SnapshotParts { - captured_at: String, - provider: String, - environment: Option<BTreeMap<String, String>>, - ext: Option<Map<String, Value>>, - servers: Vec<ServerParts>, -} - -impl SnapshotParts { - fn value(&self) -> Value { - let mut snapshot = json!({ - "schema": SCHEMA_TAG, - "captured_at": self.captured_at, - "provider": self.provider, - "servers": self.servers.iter().map(ServerParts::value).collect::<Vec<_>>(), - }); - if let Some(environment) = &self.environment { - snapshot["environment"] = json!(environment); - } - if let Some(ext) = &self.ext { - snapshot["ext"] = Value::Object(ext.clone()); - } - snapshot - } - - fn built(&self) -> CatalogSnapshot { - let mut builder = CatalogSnapshot::builder() - .captured_at( - self.captured_at - .parse::<Timestamp>() - .expect("generated timestamps are valid"), - ) - .provider( - self.provider - .parse::<NameToken>() - .expect("generated providers are valid"), - ); - if let Some(environment) = &self.environment { - builder = builder.environment(environment.clone()); - } - if let Some(ext) = &self.ext { - builder = builder.ext(ext.clone()); - } - for server in &self.servers { - builder = builder.server(server.built()); - } - builder.build().expect("both required fields are set") - } -} - -fn arb_timestamp() -> impl Strategy<Value = String> { - let offset = prop_oneof![ - Just(String::from("Z")), - (any::<bool>(), 0u32..24, 0u32..60).prop_map(|(negative, hours, minutes)| { - let sign = if negative { '-' } else { '+' }; - format!("{sign}{hours:02}:{minutes:02}") - }), - ]; - ( - (1970u32..2100, 1u32..=12, 1u32..=28), - (0u32..24, 0u32..60, 0u32..60), - proptest::option::of("[0-9]{1,9}"), - offset, - ) - .prop_map( - |((year, month, day), (hour, minute, second), fraction, offset)| { - let date = format!("{year:04}-{month:02}-{day:02}"); - let time = format!("{hour:02}:{minute:02}:{second:02}"); - let fraction = fraction - .map(|digits| format!(".{digits}")) - .unwrap_or_default(); - format!("{date}T{time}{fraction}{offset}") - }, - ) -} - -fn arb_snapshot(min_servers: usize, min_tools: usize) -> impl Strategy<Value = SnapshotParts> { - ( - arb_timestamp(), - "[A-Za-z0-9_./-]{1,12}@[0-9A-Za-z.+-]{1,8}", - proptest::option::of(prop::collection::btree_map("\\PC{0,6}", "\\PC{0,6}", 0..4)), - proptest::option::of(arb_object()), - prop::collection::vec(arb_server(min_tools), min_servers..3), - ) - .prop_map( - |(captured_at, provider, environment, ext, servers)| SnapshotParts { - captured_at, - provider, - environment, - ext, - servers: distinct_by(servers, |server| server.name.clone()), - }, - ) -} - -proptest! { - #![proptest_config(ProptestConfig::with_cases(128))] - - /// JSON of any shape the format allows is valid by the schema, is read by Rust and is written - /// back as the same value, through text. - #[test] - fn catalog_snapshot_json_with_arbitrary_extra_keys_is_valid_and_round_trips( - parts in arb_snapshot(0, 0), - ) { - let value = parts.value(); - prop_assert!(SCHEMA.is_valid(&value), "the schema rejects {value:#}"); - let text = serde_json::to_string(&value)?; - let snapshot: CatalogSnapshot = serde_json::from_str(&text)?; - prop_assert_eq!(serde_json::to_value(&snapshot)?, value); - // The text is the same too, so a float keeps its sign and its digits. - prop_assert_eq!(serde_json::to_string(&serde_json::to_value(&snapshot)?)?, text); - } - - /// A snapshot built through the builders writes the same JSON, which the schema accepts and - /// Rust reads back as an equal snapshot. - #[test] - fn catalog_snapshot_built_through_the_builders_writes_valid_json_and_reads_back_equal( - parts in arb_snapshot(0, 0), - ) { - let built = parts.built(); - let written = serde_json::to_value(&built)?; - prop_assert_eq!(&written, &parts.value()); - prop_assert!(SCHEMA.is_valid(&written)); - let again: CatalogSnapshot = serde_json::from_str(&serde_json::to_string(&built)?)?; - prop_assert_eq!(again, built); - } -} - -// ---- one mutation per rule ------------------------------------------------------------------ - -/// Both the schema and the Rust reader refuse `value`. -fn assert_rejected(value: &Value) -> Result<(), TestCaseError> { - prop_assert!(!SCHEMA.is_valid(value), "the schema accepts {value:#}"); - prop_assert!( - serde_json::from_value::<CatalogSnapshot>(value.clone()).is_err(), - "Rust accepts {value:#}" - ); - Ok(()) -} - -/// The value at `pointer`, which every snapshot of `arb_snapshot(1, 1)` has. -fn at<'a>(value: &'a mut Value, pointer: &str) -> &'a mut Value { - value - .pointer_mut(pointer) - .expect("a snapshot of one server and one tool has this path") -} - -fn set(value: &mut Value, pointer: &str, key: &str, replacement: Value) { - if let Some(object) = at(value, pointer).as_object_mut() { - object.insert(String::from(key), replacement); - } -} - -fn remove(value: &mut Value, pointer: &str, key: &str) { - if let Some(object) = at(value, pointer).as_object_mut() { - object.remove(key); - } -} - -const TOOL: &str = "/servers/0/tools/0"; -const SERVER: &str = "/servers/0"; - -fn arb_non_object() -> impl Strategy<Value = Value> { - prop_oneof![ - Just(Value::Null), - any::<bool>().prop_map(Value::Bool), - any::<i64>().prop_map(Value::from), - "\\PC{0,8}".prop_map(Value::String), - prop::collection::vec(arb_json(), 0..3).prop_map(Value::Array), - ] -} - -fn arb_bad_digest() -> impl Strategy<Value = String> { - prop_oneof![ - "[0-9a-f]{64}", - "[0-9a-f]{64}".prop_map(|hex| format!("md5:{hex}")), - "[A-F]{64}".prop_map(|hex| format!("sha256:{hex}")), - "[0-9a-f]{0,63}".prop_map(|hex| format!("sha256:{hex}")), - "[0-9a-f]{65,70}".prop_map(|hex| format!("sha256:{hex}")), - ] -} - -fn arb_bad_source_path() -> impl Strategy<Value = String> { - prop_oneof![ - "/[a-z]{1,5}(/[a-z]{1,5}){0,2}", - "[a-z]{1,4}/\\.\\./[a-z]{1,4}", - Just(String::new()), - "[a-z]{1,4}\\\\[a-z]{1,4}", - "[a-z]{1,4}//[a-z]{1,4}", - ] -} - -fn arb_unknown_transport() -> impl Strategy<Value = String> { - "[a-zA-Z]{1,8}".prop_filter("a known transport", |text| { - !TRANSPORTS.iter().any(|(known, _)| known == text) - }) -} - -/// A field the format names, with the object that holds it, as a pointer and a key. -const NULLABLE: [(&str, &str); 6] = [ - ("", "environment"), - ("", "ext"), - (TOOL, "title"), - (TOOL, "description"), - (TOOL, "outputSchema"), - (TOOL, "annotations"), -]; - -const REQUIRED: [(&str, &str); 11] = [ - ("", "schema"), - ("", "captured_at"), - ("", "provider"), - ("", "servers"), - (SERVER, "name"), - (SERVER, "source_path"), - (SERVER, "source_digest"), - (SERVER, "transport"), - (SERVER, "tools"), - (TOOL, "name"), - (TOOL, "inputSchema"), -]; - -proptest! { - #![proptest_config(ProptestConfig::with_cases(64))] - - #[test] - fn catalog_snapshot_without_input_schema_is_rejected(parts in arb_snapshot(1, 1)) { - let mut value = parts.value(); - remove(&mut value, TOOL, "inputSchema"); - assert_rejected(&value)?; - } - - #[test] - fn catalog_snapshot_with_a_non_object_input_schema_is_rejected( - parts in arb_snapshot(1, 1), - bad in arb_non_object(), - ) { - let mut value = parts.value(); - set(&mut value, TOOL, "inputSchema", bad); - assert_rejected(&value)?; - } - - #[test] - fn catalog_snapshot_with_a_bad_digest_is_rejected( - parts in arb_snapshot(1, 1), - bad in arb_bad_digest(), - ) { - let mut value = parts.value(); - set(&mut value, SERVER, "source_digest", Value::String(bad)); - assert_rejected(&value)?; - } - - #[test] - fn catalog_snapshot_with_a_bad_source_path_is_rejected( - parts in arb_snapshot(1, 1), - bad in arb_bad_source_path(), - ) { - let mut value = parts.value(); - set(&mut value, SERVER, "source_path", Value::String(bad)); - assert_rejected(&value)?; - } - - #[test] - fn catalog_snapshot_with_an_unknown_transport_is_rejected( - parts in arb_snapshot(1, 1), - bad in arb_unknown_transport(), - ) { - let mut value = parts.value(); - set(&mut value, SERVER, "transport", Value::String(bad)); - assert_rejected(&value)?; - } - - #[test] - fn catalog_snapshot_with_a_null_optional_field_is_rejected( - parts in arb_snapshot(1, 1), - (pointer, key) in prop::sample::select(NULLABLE.to_vec()), - ) { - let mut value = parts.value(); - set(&mut value, pointer, key, Value::Null); - assert_rejected(&value)?; - } - - #[test] - fn catalog_snapshot_without_a_required_field_is_rejected( - parts in arb_snapshot(1, 1), - (pointer, key) in prop::sample::select(REQUIRED.to_vec()), - ) { - let mut value = parts.value(); - remove(&mut value, pointer, key); - assert_rejected(&value)?; - } - - #[test] - fn catalog_snapshot_with_another_schema_tag_is_rejected( - parts in arb_snapshot(0, 0), - bad in "[a-z/0-9-]{0,30}".prop_filter("the tag", |text| text != SCHEMA_TAG), - ) { - let mut value = parts.value(); - set(&mut value, "", "schema", Value::String(bad)); - assert_rejected(&value)?; - } - - /// `null` is data inside the open objects of a tool and of the snapshot, so it never makes a - /// snapshot invalid there. - #[test] - fn catalog_snapshot_keeps_null_inside_open_objects(parts in arb_snapshot(1, 1)) { - let mut value = parts.value(); - for (pointer, key) in [ - (TOOL, "inputSchema"), - (TOOL, "outputSchema"), - (TOOL, "annotations"), - ("", "ext"), - ] { - set(&mut value, pointer, key, json!({"nested": null, "list": [null]})); - } - set(&mut value, TOOL, "extra", Value::Null); - prop_assert!(SCHEMA.is_valid(&value)); - let snapshot: CatalogSnapshot = serde_json::from_value(value.clone())?; - prop_assert_eq!(serde_json::to_value(&snapshot)?, value); - } -} - -// ---- where the schema and the Rust reader differ -------------------------------------------- - -fn minimal() -> Value { - json!({ - "schema": SCHEMA_TAG, - "captured_at": "2026-10-28T01:09:04+00:00", - "provider": "capture@1", - "servers": [{ - "name": "s", - "source_path": "servers/s.py", - "source_digest": format!("sha256:{}", "ab".repeat(32)), - "transport": "stdio", - "tools": [{"name": "t", "inputSchema": {"type": "object"}}], - }], - }) -} - -/// The schemas of the snapshot and of a server are strict: they list what a writer emits. The -/// reader ignores a field it does not know, so the field is not written back. -#[test] -fn catalog_unknown_fields_fail_the_schema_and_are_dropped_by_the_reader() { - for (pointer, key) in [("", "servers_dir"), (SERVER, "mode")] { - let mut value = minimal(); - set(&mut value, pointer, key, json!("x")); - assert!(!SCHEMA.is_valid(&value), "{key}"); - let snapshot: CatalogSnapshot = serde_json::from_value(value.clone()).expect("reads"); - assert_eq!(serde_json::to_value(&snapshot).expect("writes"), minimal()); - } -} - -/// The schema states the lexical form of a timestamp; the parser also refuses a date or time -/// that names no instant. -#[test] -fn catalog_timestamp_with_no_instant_passes_the_schema_and_fails_the_reader() { - for text in [ - "2026-13-01T00:00:00Z", - "2026-02-30T00:00:00Z", - "2026-01-01T24:00:00Z", - ] { - let mut value = minimal(); - set(&mut value, "", "captured_at", json!(text)); - assert!(SCHEMA.is_valid(&value), "{text}"); - assert!( - serde_json::from_value::<CatalogSnapshot>(value).is_err(), - "{text}" - ); - } -} - -/// A repeated key of the JSON text is refused when it names a field of a tool and the last value -/// wins when it is an extra key. -#[test] -fn catalog_repeated_keys_are_refused_for_fields_and_overwritten_for_extra_keys() { - let field = r#"{"name": "a", "name": "b", "inputSchema": {}}"#; - assert!(serde_json::from_str::<Tool>(field).is_err()); - let extra = r#"{"name": "a", "inputSchema": {}, "x": 1, "x": 2}"#; - let tool: Tool = serde_json::from_str(extra).expect("reads"); - assert_eq!(tool.extra().get("x"), Some(&json!(2))); -} - -/// Names are non-empty by the schema and by the reader. -#[test] -fn catalog_empty_names_fail_the_schema_and_the_reader() { - for pointer in [SERVER, TOOL] { - let mut value = minimal(); - set(&mut value, pointer, "name", json!("")); - assert!(!SCHEMA.is_valid(&value), "{pointer}"); - assert!( - serde_json::from_value::<CatalogSnapshot>(value).is_err(), - "{pointer}" - ); - } -} - -/// Uniqueness of names is not expressible in JSON Schema: the schema accepts a repeated name, the -/// reader refuses it, and the schema says so in a `$comment`. -#[test] -fn catalog_repeated_names_pass_the_schema_and_fail_the_reader() { - let mut tools = minimal(); - let tool = tools - .pointer("/servers/0/tools/0") - .cloned() - .expect("a tool"); - set(&mut tools, SERVER, "tools", json!([tool.clone(), tool])); - let mut servers = minimal(); - let server = servers.pointer(SERVER).cloned().expect("a server"); - set(&mut servers, "", "servers", json!([server.clone(), server])); - for (what, value) in [("tools", tools), ("servers", servers)] { - assert!(SCHEMA.is_valid(&value), "{what}"); - let error = serde_json::from_value::<CatalogSnapshot>(value).expect_err(what); - assert!(error.to_string().contains("is repeated within a"), "{what}"); - } - - let schema = read_schema(); - for pointer in [ - "/properties/servers/$comment", - "/$defs/CatalogServer/properties/tools/$comment", - ] { - let comment = schema.pointer(pointer).and_then(Value::as_str); - assert!( - comment.is_some_and(|text| text.contains("JSON Schema cannot state this")), - "{pointer}" - ); - } -} - -/// The environment maps names to text: any other value is refused by both. -#[test] -fn catalog_environment_with_a_non_string_value_is_rejected() { - let mut value = minimal(); - set(&mut value, "", "environment", json!({"python": "3.12"})); - assert!(SCHEMA.is_valid(&value)); - assert!(serde_json::from_value::<CatalogSnapshot>(value).is_ok()); - for bad in [ - json!(3), - json!(null), - json!(true), - json!(["3"]), - json!({"a": 1}), - ] { - let mut value = minimal(); - set(&mut value, "", "environment", json!({"python": bad})); - assert!(!SCHEMA.is_valid(&value), "{bad}"); - assert!( - serde_json::from_value::<CatalogSnapshot>(value).is_err(), - "{bad}" - ); - } - for bad in [json!(["python"]), json!("python"), json!(3)] { - let mut value = minimal(); - set(&mut value, "", "environment", bad.clone()); - assert!(!SCHEMA.is_valid(&value), "{bad}"); - assert!( - serde_json::from_value::<CatalogSnapshot>(value).is_err(), - "{bad}" - ); - } -} - -/// An object nested `depth` levels deep: `{"a": {"a": … {} …}}`. -fn nested(depth: usize) -> Map<String, Value> { - let mut inner = Map::new(); - for _ in 0..depth { - let mut outer = Map::new(); - outer.insert(String::from("a"), Value::Object(inner)); - inner = outer; - } - inner -} - -/// A document nested deeper than the reader's limit is written but not read back. The limit is -/// 128 levels of the whole document, so the depth left for an `inputSchema` is below that. -#[test] -fn catalog_deeply_nested_documents_are_written_and_refused_on_reading() { - let snapshot_with = |depth: usize| { - let tool = Tool::new(String::from("t"), nested(depth)).expect("a tool"); - let server = CatalogServer::new( - String::from("s"), - "a.py".parse::<RelPath>().expect("path"), - Digest::from_hex(&"ab".repeat(32)).expect("digest"), - Transport::Stdio, - vec![tool], - ) - .expect("a server"); - CatalogSnapshot::builder() - .captured_at("2026-10-28T01:09:04Z".parse().expect("timestamp")) - .provider("p@1".parse().expect("provider")) - .server(server) - .build() - .expect("a snapshot") - }; - - let shallow = snapshot_with(50); - let text = serde_json::to_string(&shallow).expect("writes"); - assert_eq!( - serde_json::from_str::<CatalogSnapshot>(&text).expect("reads"), - shallow - ); - - let deep = snapshot_with(200); - let text = serde_json::to_string(&deep).expect("writes without a limit"); - let error = serde_json::from_str::<CatalogSnapshot>(&text).expect_err("refused on reading"); - assert!(error.to_string().contains("recursion limit"), "{error}"); -} diff --git a/crates/candler-schemas/tests/it/guard_cell_digest.rs b/crates/candler-schemas/tests/it/guard_cell_digest.rs index 995002ab..70e59278 100644 --- a/crates/candler-schemas/tests/it/guard_cell_digest.rs +++ b/crates/candler-schemas/tests/it/guard_cell_digest.rs @@ -7,7 +7,6 @@ use std::collections::BTreeSet; use std::path::Path; use std::str::FromStr; -use candler_schemas::catalog::CatalogSnapshot; use candler_schemas::execution::{ Comparable, Deviation, DigestRef, EnvironmentRef, GitCommit, HarnessIdentity, ImportRecord, Integrity, RunManifest, SecretPresence, TreatmentRef, @@ -55,7 +54,7 @@ struct Parts { values: Vec<ResolvedValue>, harness: HarnessIdentity, treatment: TreatmentRef, - snapshots: Vec<DigestRef>, + snapshots: Option<Vec<DigestRef>>, inputs: Vec<DigestRef>, environments: Vec<EnvironmentRef>, } @@ -71,7 +70,7 @@ fn parts(text: &str) -> Parts { values: field(&doc, "values"), harness: field(&doc, "harness"), treatment: field(&doc, "treatment"), - snapshots: field(&doc, "snapshots"), + snapshots: doc.get("snapshots").map(|_| field(&doc, "snapshots")), inputs: field(&doc, "inputs"), environments: field(&doc, "environments"), } @@ -85,8 +84,8 @@ fn rebuild(parts: Parts) -> Comparable { for value in parts.values { builder = builder.value(value); } - for entry in parts.snapshots { - builder = builder.snapshot(entry); + if let Some(list) = parts.snapshots { + builder = builder.snapshots(list); } for entry in parts.inputs { builder = builder.input(entry); @@ -279,10 +278,14 @@ fn every_manifest_path_is_classified_and_hashed_parts_move_the_digest() { cell.harness.name = Name::from_str("another-harness").expect("name"); } "comparable.treatment" => cell.treatment.tag = Some(String::from("changed")), - "comparable.snapshots" => cell.snapshots.push(DigestRef::new( - Name::from_str("catalog").expect("name"), - digest('e'), - )), + "comparable.snapshots" => { + cell.snapshots + .get_or_insert_with(Vec::new) + .push(DigestRef::new( + Name::from_str("catalog").expect("name"), + digest('e'), + )); + } "comparable.inputs" => cell.inputs.push(DigestRef::new( Name::from_str("script").expect("name"), digest('e'), @@ -304,7 +307,7 @@ fn every_manifest_path_is_classified_and_hashed_parts_move_the_digest() { #[test] fn digests_equal_the_oracle() { let all = vectors(); - assert_eq!(all.len(), 6, "three corpus cells and three invented ones"); + assert_eq!(all.len(), 7, "three corpus cells and four invented ones"); for vector in &all { // BORROW: explicit .as_str() instead of Deref coercion let read: Comparable = serde_json::from_str(vector.comparable.as_str()).expect("reads"); @@ -690,14 +693,10 @@ fn reserved_roots_fill_the_typed_fields_and_absolute_paths_are_refused() { .treatment(treatment) .value(resolved("plan.a", &json!(1))) .value(resolved("plan.b", &json!("relative/dir/file.txt"))) - .snapshot(DigestRef::new( - Name::from_str("catalog").expect("name"), - digest('a'), - )) - .snapshot(DigestRef::new( - Name::from_str("catalog").expect("name"), - digest('b'), - )) + .snapshots(vec![ + DigestRef::new(Name::from_str("catalog").expect("name"), digest('a')), + DigestRef::new(Name::from_str("catalog").expect("name"), digest('b')), + ]) .build() .expect("expected cell"); let built = Comparable::from_resolved(&resolved_values).expect("from resolved"); @@ -751,58 +750,6 @@ fn reserved_roots_fill_the_typed_fields_and_absolute_paths_are_refused() { assert!(Comparable::from_resolved(&resolved_values[..2]).is_err()); } -#[derive(Deserialize)] -struct CatalogFile { - vector: Vec<CatalogVector>, -} - -#[derive(Deserialize)] -struct CatalogVector { - document_a: String, - document_b: String, - document_c: String, - digest_ab: String, - digest_c: String, -} - -/// Guards: Cond 1 — the digest of a catalog snapshot equals the independent one and does not change when only `captured_at` does, so a capture time never splits a cell. Oracle: `catalog_content_digest.toml` (Python `rfc8785`; A and B differ only in `captured_at`, C in a tool description). -#[test] -fn catalog_content_digest_ignores_the_capture_time() { - // BORROW: explicit .as_str() instead of Deref coercion - let file: CatalogFile = - toml::from_str(oracle("catalog_content_digest.toml").as_str()).expect("toml"); - let vector = file.vector.first().expect("a vector"); - // BORROW: explicit .as_str() instead of Deref coercion - let read = |text: &str| serde_json::from_str::<CatalogSnapshot>(text).expect("snapshot"); - // BORROW: explicit .as_str() instead of Deref coercion - let a = read(vector.document_a.as_str()); - // BORROW: explicit .as_str() instead of Deref coercion - let b = read(vector.document_b.as_str()); - // BORROW: explicit .as_str() instead of Deref coercion - let c = read(vector.document_c.as_str()); - assert_ne!( - a.captured_at(), - b.captured_at(), - "the captures differ in time" - ); - assert_eq!( - // BORROW: explicit .as_str() instead of Deref coercion - a.content_digest().expect("digest").as_str(), - vector.digest_ab - ); - assert_eq!( - // BORROW: explicit .as_str() instead of Deref coercion - b.content_digest().expect("digest").as_str(), - vector.digest_ab - ); - assert_eq!( - // BORROW: explicit .as_str() instead of Deref coercion - c.content_digest().expect("digest").as_str(), - vector.digest_c - ); - assert_ne!(vector.digest_ab, vector.digest_c); -} - /// Guards: Wire rule — an import record keeps the legacy integrity block it was given as a JSON value and reads it back, and `null` is refused where the record is read; the three reader causes are invalid reasons by their snake-case names. Oracle: README §Gotchas wire rules ("`null` is never written"), with the expected texts written by hand. #[test] fn import_record_round_trips_its_legacy_integrity_and_reasons_are_named() { diff --git a/crates/candler-schemas/tests/it/guard_execution_wire.rs b/crates/candler-schemas/tests/it/guard_execution_wire.rs index a4c9bee1..8350a4a8 100644 --- a/crates/candler-schemas/tests/it/guard_execution_wire.rs +++ b/crates/candler-schemas/tests/it/guard_execution_wire.rs @@ -153,7 +153,6 @@ fn comparable() -> Value { "values": [{"path": "plan.a", "value": 1}], "harness": {"name": "h", "version": "1.0.0"}, "treatment": {"name": "t"}, - "snapshots": [], "inputs": [], "environments": [] }) @@ -766,9 +765,10 @@ fn container_role_egress_round_trips_and_the_older_roles_still_read() { } /// Guards: I12 — one validator decides a replicate count, for the file and for `--set`: 0 is -/// refused as zero, a count beyond 32 bits is refused, and a count from 1 to `u32::MAX` is kept. -/// Oracle: the counts written below. -/// Bite: accept 0 in the validator. +/// refused as zero, a count beyond 32 bits is refused as no count (its own code, at `/replicates`, +/// and a message that gives the range), and a count from 1 to `u32::MAX` is kept. +/// Oracle: the counts, the code, the pointer and the range written below. +/// Bite: accept 0 in the validator, or refuse a count beyond 32 bits with the cost code. #[test] fn replicates_are_checked_once() { use candler_schemas::execution::{ExecutionError, check_replicates}; @@ -778,7 +778,16 @@ fn replicates_are_checked_once() { field: "replicates" }) )); - assert!(check_replicates(u64::from(u32::MAX) + 1).is_err()); + let beyond = check_replicates(u64::from(u32::MAX) + 1).expect_err("a count beyond 32 bits"); + assert_eq!( + candler_schemas::refusal::Refusal::code(&beyond).as_str(), + "experiment.replicates_not_count" + ); + assert_eq!( + candler_schemas::refusal::Refusal::path(&beyond).as_deref(), + Some("/replicates") + ); + assert!(beyond.to_string().contains("1 to 4294967295"), "{beyond}"); assert_eq!(check_replicates(1).ok(), Some(1)); assert_eq!(check_replicates(u64::from(u32::MAX)).ok(), Some(u32::MAX)); } diff --git a/crates/candler-schemas/tests/it/guard_mcp_server.rs b/crates/candler-schemas/tests/it/guard_mcp_server.rs new file mode 100644 index 00000000..0dec431f --- /dev/null +++ b/crates/candler-schemas/tests/it/guard_mcp_server.rs @@ -0,0 +1,147 @@ +//! Guards: the experiment schema cannot type the `mcp.servers` path, so it holds the entries as +//! generic JSON; the published mcp-server schema is the typed reader for the one entry, and it +//! refuses every shape `candler_harness::mcp::read` refuses. +//! +//! The experiment schema types every `fixed` value and every factor level as the same generic JSON +//! value, so it does not check the fields of an entry that sits under `mcp.servers`. The mcp-server +//! schema is the typed reader for the one entry: it requires exactly one of `command` and `url` +//! and keeps the two families apart, matching the reader. + +use std::path::Path; +use std::sync::OnceLock; + +use jsonschema::{Validator, validator_for}; +use serde_json::Value; + +fn mcp_server_schema<'a>() -> &'a Validator { + static MCP_SERVER: OnceLock<Validator> = OnceLock::new(); + MCP_SERVER.get_or_init(|| { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("schema/mcp-server.schema.json"); + let text = + std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let value: Value = serde_json::from_str(&text).expect("committed schema JSON"); + validator_for(&value).expect("the committed schema compiles") + }) +} + +/// The entry under `mcp.servers` that `mcp::read` accepts without launching anything. +fn valid_launched_entry() -> Value { + serde_json::json!({ + "type": "stdio", + "command": "docker", + "args": ["run", "-v"], + "env": { "KEY": "value" }, + "codemode": false, + "name": "movement" + }) +} + +/// The entry under `mcp.servers` that `mcp::read` accepts as reachable at a URL. +fn valid_remote_entry() -> Value { + serde_json::json!({ "type": "sse", "url": "http://h" }) +} + +/// Every entry `candler_harness::mcp::read` refuses for its shape is refused by the published +/// mcp-server schema, and the two valid entries are accepted. +fn mcp_server_refusal_rows() -> Vec<(&'static str, Value)> { + vec![ + ("neither `command` nor `url`", serde_json::json!({})), + ( + "a launched entry with no `command`", + serde_json::json!({ "type": "stdio", "name": "n" }), + ), + ( + "a remote entry with no `url`", + serde_json::json!({ "type": "remote" }), + ), + ( + "a `command` under a URL type", + serde_json::json!({ "command": "x", "type": "http" }), + ), + ( + "a `url` under a launched type", + serde_json::json!({ "url": "http://h", "type": "stdio" }), + ), + ( + "both `command` and `url`", + serde_json::json!({ "command": "x", "url": "http://h" }), + ), + ( + "both, under a stdio type", + serde_json::json!({ "command": "x", "url": "http://h", "type": "stdio" }), + ), + ( + "both, under a remote type", + serde_json::json!({ "command": "x", "url": "http://h", "type": "remote" }), + ), + ( + "a remote entry inferred from `url` alone, with `env`", + serde_json::json!({ "url": "http://h", "env": { "K": "v" } }), + ), + ( + "a remote entry with `env`", + serde_json::json!({ "url": "http://h", "env": { "K": "v" }, "type": "remote" }), + ), + ( + "a remote entry with `args`", + serde_json::json!({ "url": "http://h", "args": ["run"], "type": "remote" }), + ), + ( + "a `name` with a `.`", + serde_json::json!({ "command": "x", "name": "a.b" }), + ), + ( + "a `name` with a trailing `_`", + serde_json::json!({ "command": "x", "name": "s_" }), + ), + ( + "a launched entry with `headers`", + serde_json::json!({ "command": "x", "headers": { "K": "v" } }), + ), + ] +} + +/// Every entry `candler_harness::mcp::read` refuses for its shape is refused by the published +/// mcp-server schema, and the two valid entries are accepted. +#[test] +fn the_mcp_server_schema_refuses_what_the_reader_refuses() { + let mcp_server = mcp_server_schema(); + for (shape, entry) in mcp_server_refusal_rows() { + assert!( + !mcp_server.is_valid(&entry), + "mcp-server schema must refuse a server `{shape}`: {entry}" + ); + } + assert!( + mcp_server.is_valid(&valid_launched_entry()), + "the launched entry the reader accepts must validate: {}", + valid_launched_entry() + ); + assert!( + mcp_server.is_valid(&valid_remote_entry()), + "the remote entry the reader accepts must validate: {}", + valid_remote_entry() + ); +} + +/// The well-formed entry a driver writes validates against the mcp-server schema. +#[test] +fn the_mcp_server_schema_accepts_what_a_driver_writes() { + let mcp_server = mcp_server_schema(); + let wellformed = valid_launched_entry(); + assert!( + mcp_server.is_valid(&wellformed), + "a well-formed stdio server validates: {wellformed}" + ); +} + +/// Guards: serde refuses a key a server does not have, and reads the keys it has. +/// Oracle: the two entries are written by hand. +/// Bite: drop `deny_unknown_fields` from the type; the entry with `timeout` then reads. +#[test] +fn serde_refuses_an_unknown_key_in_a_server_entry() { + let unknown = serde_json::json!({ "command": "uvx", "timeout": 5 }); + assert!(serde_json::from_value::<candler_schemas::servers::McpServer>(unknown).is_err()); + let known = serde_json::json!({ "command": "uvx", "args": ["x"], "codemode": false }); + assert!(serde_json::from_value::<candler_schemas::servers::McpServer>(known).is_ok()); +} diff --git a/crates/candler-schemas/tests/it/guard_refusal.rs b/crates/candler-schemas/tests/it/guard_refusal.rs index 7245f4a8..caeaa246 100644 --- a/crates/candler-schemas/tests/it/guard_refusal.rs +++ b/crates/candler-schemas/tests/it/guard_refusal.rs @@ -155,7 +155,7 @@ fn c1_the_record_of_an_error_carries_its_code_side_path_and_message() { /// The hand list of the codes whose side is `candler`: errors only Candler can raise. No other row /// may be `candler`; an author's error is never blamed on Candler (A5). -const INTERNAL_CODES: [&str; 24] = [ +const INTERNAL_CODES: [&str; 21] = [ "manifest.git_commit_invalid", "manifest.field_unset", "manifest.list_unsorted", @@ -177,20 +177,16 @@ const INTERNAL_CODES: [&str; 24] = [ "format.job_id_invalid", "format.boot_id_invalid", "format.container_id_invalid", - "catalog.field_unset", - "catalog.extra_key_reserved", - "catalog.field_null", ]; /// The variants of each error type the registry covers, counted by hand from the enums: each /// variant has a row, and the wrapping ones are marked as delegating. -const VARIANT_COUNTS: [(&str, usize); 9] = [ - ("ExecutionError", 25), +const VARIANT_COUNTS: [(&str, usize); 8] = [ + ("ExecutionError", 26), ("EvaluationError", 14), ("OutcomeError", 16), ("FormatError", 19), ("CanonicalError", 5), - ("CatalogError", 6), ("ValuesError", 2), ("SchemaTagError", 1), ("VersionMismatch", 1), diff --git a/crates/candler-schemas/tests/it/guard_trace_wire.rs b/crates/candler-schemas/tests/it/guard_trace_wire.rs index 850ab0ad..b0d4086d 100644 --- a/crates/candler-schemas/tests/it/guard_trace_wire.rs +++ b/crates/candler-schemas/tests/it/guard_trace_wire.rs @@ -393,3 +393,32 @@ fn frames_of_awkward_streams_have_the_json_lines_the_test_states() { r#"{"kind":"header","schema":"raw-frames/1","stream":"legacy.log","clock":{"kind":"unrecorded"},"source":"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}"# ); } + +/// Guards: normalised-trace/1 — the `tool` of an MCP origin is optional: an origin stored without +/// it (as the hand-written trace file's wrapped call is) still reads and is written back without +/// it, and one with it round-trips. Oracle: the two origin literals, written by hand from the +/// schema. +#[test] +fn an_mcp_origin_without_a_tool_still_reads_and_one_with_it_round_trips() { + use candler_schemas::trace::ToolOrigin; + + let old = r#"{"kind":"mcp","server":"docs"}"#; + let read: ToolOrigin = + serde_json::from_str(old).expect("an origin stored before the field reads"); + assert!(matches!(&read, ToolOrigin::Mcp { server, tool: None, .. } if server == "docs")); + assert_eq!( + serde_json::to_string(&read).expect("the origin writes"), + old + ); + + let new = r#"{"kind":"mcp","server":"docs","tool":"search"}"#; + let read: ToolOrigin = serde_json::from_str(new).expect("an origin with a tool reads"); + assert_eq!( + read, + ToolOrigin::mcp_tool("docs".to_owned(), "search".to_owned()) + ); + assert_eq!( + serde_json::to_string(&read).expect("the origin writes"), + new + ); +} diff --git a/crates/candler-schemas/tests/it/guard_wire_shapes.rs b/crates/candler-schemas/tests/it/guard_wire_shapes.rs index de979fd9..85970fb7 100644 --- a/crates/candler-schemas/tests/it/guard_wire_shapes.rs +++ b/crates/candler-schemas/tests/it/guard_wire_shapes.rs @@ -2,17 +2,16 @@ //! The tagged enums of the wire are read from objects and from nothing else. use std::fs; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::str::FromStr; -use candler_schemas::catalog::{CatalogSnapshot, SCHEMA_TAG}; use candler_schemas::evaluation::PluginManifest; use candler_schemas::primitives::NameToken; use candler_schemas::process::{ExitStatus, ProcessStart}; use candler_schemas::refusal::Refusal; use candler_schemas::values::ValueSource; use serde::de::DeserializeOwned; -use serde_json::{Map, Value, json}; +use serde_json::json; fn read<T: DeserializeOwned>(text: &str) -> Result<T, serde_json::Error> { serde_json::from_str(text) @@ -68,139 +67,6 @@ fn tagged_enums_refuse_the_list_form_and_accept_the_object_form() { ); } -fn fixture_path(parts: &[&str]) -> PathBuf { - let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - path.extend(["tests", "fixtures"]); - path.extend(parts); - path -} - -fn json_files(dir: &Path) -> Vec<PathBuf> { - let mut files: Vec<PathBuf> = fs::read_dir(dir) - .unwrap_or_else(|e| panic!("{}: {e}", dir.display())) - .map(|entry| entry.expect("a directory entry").path()) - .filter(|path| path.extension().is_some_and(|ext| ext == "json")) - .collect(); - files.sort(); - files -} - -fn read_json(path: &Path) -> Value { - let text = fs::read_to_string(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - serde_json::from_str(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())) -} - -/// Every valid catalog snapshot the fixtures hold: the two captured catalogs, rewritten to the -/// current tag with their two extra top-level keys under `ext`, and one snapshot around each -/// MCP specification tool. -fn catalog_snapshot_fixtures() -> Vec<(String, Value)> { - let mut snapshots = Vec::new(); - for path in json_files(&fixture_path(&["upstream"])) { - let mut snapshot = read_json(&path); - let object = snapshot.as_object_mut().expect("a catalog is an object"); - object.insert(String::from("schema"), json!(SCHEMA_TAG)); - let mut ext = Map::new(); - for key in ["servers_dir", "stubbed_modules"] { - ext.insert( - String::from(key), - object.remove(key).expect("a captured key"), - ); - } - object.insert(String::from("ext"), Value::Object(ext)); - snapshots.push((path.display().to_string(), snapshot)); - } - for path in json_files(&fixture_path(&["spec", "tools"])) { - let snapshot = json!({ - "schema": SCHEMA_TAG, - "captured_at": "2026-10-28T01:09:04+00:00", - "provider": "capture@1", - "servers": [{ - "name": "server", - "source_path": "servers/server.py", - "source_digest": format!("sha256:{}", "cd".repeat(32)), - "transport": "stdio", - "tools": [read_json(&path)], - }], - }); - snapshots.push((path.display().to_string(), snapshot)); - } - snapshots -} - -/// JSON pointers to every struct of the catalog wire in `snapshot`: the snapshot, each server -/// and each tool. -fn catalog_struct_pointers(snapshot: &Value) -> Vec<String> { - let mut pointers = vec![String::new()]; - let servers = snapshot["servers"].as_array().expect("servers is a list"); - for (s, server) in servers.iter().enumerate() { - pointers.push(format!("/servers/{s}")); - let tools = server["tools"].as_array().expect("tools is a list"); - for t in 0..tools.len() { - pointers.push(format!("/servers/{s}/tools/{t}")); - } - } - pointers -} - -/// Guards: R01 §Wire encodings, for the catalog wire only (snapshot, server, tool) — a struct is -/// never written as a list of its values. Oracle: every committed valid catalog snapshot reads; -/// with any one of its snapshot, server or tool objects replaced by the list of that object's -/// values, the reader refuses it; the counts of fixtures and of objects tried are above zero. -/// Bite: removing `object_only!` from `CatalogServer` or `MapOnly` from the snapshot reader turns -/// this test red, because the lists are written in the order of the struct's fields. -#[test] -fn catalog_wire_structs_are_refused_as_lists_in_every_fixture() { - let fixtures = catalog_snapshot_fixtures(); - assert!(!fixtures.is_empty(), "no catalog fixture was found"); - let mut tried = 0_usize; - for (name, snapshot) in &fixtures { - serde_json::from_value::<CatalogSnapshot>(snapshot.clone()) - .unwrap_or_else(|e| panic!("{name} is a valid snapshot: {e}")); - for pointer in catalog_struct_pointers(snapshot) { - let mut mutated = snapshot.clone(); - let node = mutated - .pointer_mut(&pointer) - .expect("the pointer leads to an object"); - // A derived reader that took a list would take the values in the order of the - // struct's fields, an absent optional field being `{}`; a tool has a flattened - // remainder, so any order is a list of its values. - let fields: &[&str] = match pointer.matches('/').count() { - 0 => &[ - "schema", - "captured_at", - "provider", - "environment", - "ext", - "servers", - ], - 2 => &["name", "source_path", "source_digest", "transport", "tools"], - // EXPLICIT: any other depth is a tool, whose flattened extra keys give it no fixed - // field order - _ => &[], - }; - let list: Vec<Value> = if fields.is_empty() { - node.as_object() - .expect("an object") - .values() - .cloned() - .collect() - } else { - fields - .iter() - .map(|field| node.get(*field).cloned().unwrap_or_else(|| json!({}))) - .collect() - }; - *node = Value::Array(list); - assert!( - serde_json::from_value::<CatalogSnapshot>(mutated).is_err(), - "{name}: the object at '{pointer}' written as a list was read" - ); - tried += 1; - } - } - assert!(tried > 0, "no object was tried"); -} - /// Guards: Run manifest — a derived source may record the location its step read; without one it writes no `from`, and an explicit `null` is refused. Oracle: the three wire texts written by hand. #[test] fn derived_source_carries_an_optional_location() { diff --git a/crates/candler-schemas/tests/it/main.rs b/crates/candler-schemas/tests/it/main.rs index 45b31456..d6b513c9 100644 --- a/crates/candler-schemas/tests/it/main.rs +++ b/crates/candler-schemas/tests/it/main.rs @@ -1,8 +1,6 @@ //! The integration tests of this crate, one binary: one module per former test file. #![cfg(test)] -mod catalog_fixtures; -mod catalog_properties; mod guard_cell_digest; mod guard_context_digest; mod guard_evaluator_protocol; @@ -11,6 +9,7 @@ mod guard_execution_wire; mod guard_experiment_file; mod guard_import_origin; mod guard_jcs; +mod guard_mcp_server; mod guard_pattern_vectors; mod guard_refusal; mod guard_rpc_wire; diff --git a/crates/candler/src/commands/inspect.rs b/crates/candler/src/commands/inspect.rs index bfb60978..08ebe535 100644 --- a/crates/candler/src/commands/inspect.rs +++ b/crates/candler/src/commands/inspect.rs @@ -211,6 +211,22 @@ fn outcome_of(record: &OutcomeRecord) -> Result<InspectOutcome, CliError> { }) } +/// The resolved `mcp.*` values of the cell, by path: the MCP configuration the run was installed +/// with. +fn mcp_of(whole: &Value) -> BTreeMap<String, Value> { + whole + .pointer("/comparable/values") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|entry| { + let path = entry.get("path").and_then(Value::as_str)?; + let value = entry.get("value")?; + (path == "mcp" || path.starts_with("mcp.")).then(|| (path.to_owned(), value.clone())) // BORROW: the record owns its copy + }) + .collect() +} + /// The record of the run `key`: whether it is sealed and counts, what it was read from, the /// provenance and the other values it measured, and its outcomes with their evidence. /// @@ -270,6 +286,7 @@ pub fn render_run(store: &Store, key: &RunKey) -> Result<InspectRun, CliError> { ended_at: field("ended_at"), host: field("host"), import: field("import"), + mcp: mcp_of(&whole), provenance, measured, outcomes, @@ -356,7 +373,12 @@ pub fn render_job(store: &Store, id: &JobId) -> Result<InspectJob, CliError> { /// The run record as lines: the run, its seal, what it measured and each outcome. fn text_of_run(run: &InspectRun) -> String { let mut lines = vec![format!("run {}", run.run), format!("sealed {}", run.sealed)]; - for (path, value) in run.provenance.iter().chain(run.measured.iter()) { + for (path, value) in run + .mcp + .iter() + .chain(run.provenance.iter()) + .chain(run.measured.iter()) + { lines.push(format!("{path}\t{value}")); } for outcome in &run.outcomes { diff --git a/crates/candler/src/commands/kill.rs b/crates/candler/src/commands/kill.rs index 8cb7652e..ce317648 100644 --- a/crates/candler/src/commands/kill.rs +++ b/crates/candler/src/commands/kill.rs @@ -5,7 +5,7 @@ //! A job whose supervisor is gone, or still has not ended the job after the grace, is recovered. use std::error::Error; -use std::io::{self, BufRead, Write}; +use std::io::{self, BufRead, IsTerminal as _, Write}; use std::path::Path; use candler_core::jobs::dir::JobDir; @@ -220,6 +220,11 @@ pub async fn kill( let root = common::store_root("kill", store).await?; let names = targets(args, &root.join("jobs"))?; if !args.yes { + // Off a terminal the question cannot be answered, so the verb is refused before any line + // of the prompt is emitted. + if !io::stdin().is_terminal() { + return Err(CliError::refused_by(CliRefusal::KillNotConfirmed)); + } writeln!(out, "would stop: {}", names.join(" ")).map_err(fail)?; write!(out, "stop them? [y/N] ").map_err(fail)?; out.flush().map_err(fail)?; diff --git a/crates/candler/src/commands/preflight.rs b/crates/candler/src/commands/preflight.rs index e36d4d7c..fc206912 100644 --- a/crates/candler/src/commands/preflight.rs +++ b/crates/candler/src/commands/preflight.rs @@ -6,7 +6,6 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; -use std::time::Duration; use candler_core::isolation::docker::{ClientEnv, DockerCli}; use candler_core::isolation::image::{DockerImageService, ImageAssets}; @@ -17,13 +16,10 @@ use candler_core::resolve::preflight::{ResolveError, Resolver}; use candler_core::resolve::steps::env::EnvRefusal; use candler_core::resolve::steps::ground_truth::{GroundTruth, GroundTruthStep}; use candler_core::resolve::steps::{M2bServices, register_m2b_steps}; -use candler_core::runner::evidence::catalog::{CatalogCommand, CommandCatalogProvider}; use candler_core::runner::plan::{PlanError, experiment_of}; use candler_core::supervise::{EventSink, Supervisor}; use candler_schemas::execution::paths; -use candler_schemas::execution::{ - EventPayload, ExecutionError, ExperimentFile, Level, check_replicates, -}; +use candler_schemas::execution::{EventPayload, ExperimentFile, Level}; use candler_schemas::primitives::{FieldPath, RunKey}; use candler_schemas::refusal::pointer_of; use candler_schemas::values::JsonValue; @@ -32,17 +28,11 @@ use super::CliError; use super::assets; use super::refusal::{CliRefusal, FieldLocation, REQUEST_KEYS}; use candler_harness::driver::HarnessDriver; +use candler_harness::spec::AgentSetting; /// The path of the setting `[treatment] source` replaces; `--set` refuses it by name. const RETIRED_TREATMENT_SOURCE: &str = concat!("request.", "treatment_source"); -/// The time the catalog command gets inside the image. -const CATALOG_TIMEOUT: Duration = Duration::from_secs(60); - -/// The program that prints the catalog of an image that offers no MCP server: a snapshot with no -/// server in it, captured now. -const CATALOG_PROGRAM: &str = "printf '{\"schema\":\"tool-catalog-snapshot/1\",\"captured_at\":\"%s\",\"provider\":\"candler-image@1\",\"servers\":[]}' \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\""; - /// The places the sources of the images are. pub(crate) struct AssetPaths { /// The base and env build contexts and the store root. @@ -94,8 +84,8 @@ pub(crate) fn refused(reason: impl Into<String>) -> CliError { } } -/// The resolver with the preflight steps of the image, the harness, the treatment, the catalog -/// and the ground truth registered; the services say where the harness reads its skills. +/// The resolver with the preflight steps of the image, the harness, the treatment and the ground +/// truth registered; the services say where the harness reads its skills. /// /// # Errors /// [`ResolveError`] when a step name is registered twice or malformed. @@ -266,22 +256,6 @@ fn check_set_paths(fields: &[(FieldPath, String)]) -> Result<(), CliError> { Ok(()) } -/// Refuses a `replicates` value that is not a count: an integer is checked by -/// [`check_replicates`], the validator of the experiment file, and anything else is refused as -/// not positive. -fn check_replicate_count(value: &JsonValue) -> Result<(), CliError> { - let count = value - .as_value() - .as_u64() - .ok_or(ExecutionError::NotPositive { - field: "replicates", - }) - .map_err(CliError::refused_by)?; - check_replicates(count) - .map(drop) - .map_err(CliError::refused_by) -} - /// Refuses the first of `paths` that names `env`, which only the `[env]` table sets. fn check_env_source<'a>(paths: impl IntoIterator<Item = &'a FieldPath>) -> Result<(), CliError> { paths @@ -296,6 +270,25 @@ fn check_env_source<'a>(paths: impl IntoIterator<Item = &'a FieldPath>) -> Resul }) } +/// The input with `level` as the setting `request.treatment`, its `source` relative to the +/// experiment file's directory `dir` as the file writes it. +pub(crate) fn input_for_level( + input: &ResolveInput, + level: &serde_json::Value, + dir: &Path, +) -> Result<ResolveInput, CliError> { + let path = path_of(paths::REQUEST_TREATMENT)?; + let given = FileValues::new(vec![(path.clone(), json_of(level)?)]) // BORROW: the values own the path + .relative_to(dir) + .map_err(CliError::refused_by)?; + let mut input = input.clone(); // BORROW: each level resolves its own copy + if let (Some(file), Some((_, value))) = (input.file.as_mut(), given.values.into_iter().next()) { + file.values.retain(|(held, _)| *held != path); + file.values.push((path, value)); + } + Ok(input) +} + /// What the experiment file and the command line ask for, as the input of a resolution: the /// file's fixed values, the settings `request.harness` and `request.treatment` it names, and the /// arguments of `--set` as explicit values. A location setting (the treatment's source, the build @@ -331,9 +324,6 @@ pub fn request_settings( if let Some(treatment) = file.treatment() { values.insert(path_of(paths::REQUEST_TREATMENT)?, json_of(treatment)?); } - if let Some(count) = values.get(&path_of("replicates")?) { - check_replicate_count(count)?; - } let file_values = FileValues::new(values.into_iter().collect()) .relative_to(experiment_dir) .map_err(CliError::refused_by)?; @@ -343,9 +333,6 @@ pub fn request_settings( check_set_paths(fields)?; for (path, text) in fields { let mut value = value_of(text)?; - if path.as_str() == "replicates" { - check_replicate_count(&value)?; - } if path.as_str() == paths::REQUEST_TREATMENT { // BORROW: .clone() gives the file values their own path let given = FileValues::new(vec![(path.clone(), value.clone())]) @@ -398,7 +385,7 @@ pub(crate) fn requested_harness(input: &ResolveInput) -> Result<String, CliError name.ok_or_else(|| refused("`request.harness` names no harness")) } -/// Builds the docker client, the image service and the catalog provider over one supervisor, and +/// Builds the docker client and the image service over one supervisor, and /// composes the resolver on them. The harness is the registry's `driver`: it reads the /// image's version and says which versions are supported, and its base context builds the base /// image. @@ -424,25 +411,15 @@ pub(crate) fn foreground( let images = DockerImageService::new( Arc::clone(&supervisor), cli.clone(), // BORROW: the service owns its client - env.clone(), // BORROW: the service owns its env + env, assets.images, Arc::clone(&driver), ); - // BORROW: .to_owned() gives the command its own words - let argv = vec!["sh".to_owned(), "-c".to_owned(), CATALOG_PROGRAM.to_owned()]; - let catalog = CommandCatalogProvider::new( - Arc::clone(&supervisor), - cli.clone(), // BORROW: the provider owns its client - env, - root.to_path_buf(), // BORROW: the provider owns its root - CatalogCommand::new(argv, CATALOG_TIMEOUT), - ); let services = M2bServices { supervisor, images: Arc::new(images), - catalog: Arc::new(catalog), harness_supported: driver.supported(), - session_capable: driver.capabilities().session, + session_capable: !driver.answer(AgentSetting::SessionMode).is_refused(), skills: driver.skills(), }; let resolver = compose_resolver(config, &services, truth).map_err(failed)?; @@ -476,20 +453,6 @@ mod tests { request_settings(file, Path::new("/work"), &fields, Path::new("/work")) } - /// Guards: I12 — a replicate count of `--set` or of `[fixed]` goes through the validator of - /// the experiment file: 0 and a value that is no integer are refused, a count is kept. - /// Oracle: the values written below. - /// Bite: skip the check for `--set` (the first rows go red), or for `[fixed]` (the last). - #[test] - fn a_replicates_value_that_is_not_a_count_is_refused() { - let plain = file(""); - assert!(settings(&plain, &["replicates=3"]).is_ok()); - for bad in ["replicates=0", "replicates=abc", "replicates=2.5"] { - assert!(settings(&plain, &[bad]).is_err(), "{bad}"); - } - assert!(settings(&file("\n[fixed]\nreplicates = 0\n"), &[]).is_err()); - } - /// Guards: an experiment file without an `env` table gives the resolution no `env` value, so /// it resolves, and hashes, as before; a file with one gives exactly one `env` value, the /// table as written. diff --git a/crates/candler/src/commands/refusal.rs b/crates/candler/src/commands/refusal.rs index 682cd9f4..4a1a354a 100644 --- a/crates/candler/src/commands/refusal.rs +++ b/crates/candler/src/commands/refusal.rs @@ -76,8 +76,10 @@ pub enum CliRefusal { /// What the operating system reported. detail: String, }, - /// `kill` asked for a confirmation and was not given one. - #[error("pass -y to confirm")] + /// `kill` was not confirmed: stdin is not a terminal, or the question was not answered yes. + #[error( + "nothing was stopped: pass -y to confirm; `candler ps` lists the jobs that would be stopped" + )] KillNotConfirmed, /// `inspect` was given a target that is none of its three forms. #[error("`{target}` is none of: {}", super::inspect::FORMS)] @@ -283,7 +285,7 @@ refusal_table! { KillNotConfirmed { .. } => row( "config.kill_not_confirmed", Side::Config, - "`kill` asked for a confirmation and was not answered `y` or `yes`; `-y` skips the question.", + "`kill` stopped nothing because it was not confirmed: stdin is not a terminal, or the question was not answered `y` or `yes`; `-y` confirms, and `candler ps` lists the jobs that would be stopped.", "-", ), InspectTargetInvalid { .. } => row( diff --git a/crates/candler/src/commands/resolve.rs b/crates/candler/src/commands/resolve.rs index f175f935..d1b3f6f0 100644 --- a/crates/candler/src/commands/resolve.rs +++ b/crates/candler/src/commands/resolve.rs @@ -25,12 +25,15 @@ use candler_core::resolve::layers::Resolution; use candler_core::resolve::preflight::{ResolveError, StepError, StepReport}; use candler_core::resolve::steps::gateway::register_gateway_step; use candler_core::resolve::steps::secrets::register_secret_step; +use candler_core::runner::plan::{check_cells, treatment_levels}; use candler_core::supervise::{EventSink, Supervisor}; use candler_schemas::execution::{EventPayload, ExperimentFile}; use candler_schemas::primitives::{FieldPath, RunKey}; use candler_schemas::values::{SourceEntry, ValueSource}; -use super::preflight::{check_factors, foreground, request_settings, requested_harness}; +use super::preflight::{ + check_factors, foreground, input_for_level, request_settings, requested_harness, +}; use super::refusal::CliRefusal; use super::term::Paint; use super::{CliError, Exit, OutputArgs, common}; @@ -268,15 +271,27 @@ pub async fn run(args: Args, store: Option<&Path>) -> Result<Exit, CliError> { .map_err(failed_here)?; let mut failures = plugin_dir_failures(&config); - let mut resolution = None; let mut summary = None; - match resolver.resolve(input).await { - Ok(found) => resolution = Some(found), - Err(ResolveError::Preflight { reports, errors }) => { - failures.extend(render_failures(&reports, &errors)); - summary = Some(ResolveError::Preflight { reports, errors }); + let declared_levels = treatment_levels(&file); + let given = if declared_levels.is_empty() { + vec![input.clone()] // BORROW: the single resolution starts from the same input + } else { + declared_levels + .iter() + .map(|level| input_for_level(&input, level, experiment_dir.as_path())) + .collect::<Result<Vec<_>, _>>()? + }; + let mut levels = Vec::with_capacity(given.len()); + for level in given { + match resolver.resolve(level).await { + Ok(found) => levels.push(found), + Err(ResolveError::Preflight { reports, errors }) => { + failures.extend(render_failures(&reports, &errors)); + summary = Some(ResolveError::Preflight { reports, errors }); + break; + } + Err(other) => return Err(CliError::refused_by(other)), } - Err(other) => return Err(CliError::refused_by(other)), } let mut stdout = std::io::stdout().lock(); @@ -290,9 +305,11 @@ pub async fn run(args: Args, store: Option<&Path>) -> Result<Exit, CliError> { )), }); } - let Some(resolution) = resolution else { + // BORROW: the levels own their resolutions + let Some(resolution) = levels.first().cloned() else { return Ok(Exit::Success); }; + check_cells(&file, levels.as_slice(), driver.as_ref()).map_err(CliError::refused_by)?; // BORROW: explicit .as_slice() if text { for line in render_values(&resolution, Paint::detect()) { writeln!(stdout, "{line}").map_err(failed_here)?; diff --git a/crates/candler/src/commands/run.rs b/crates/candler/src/commands/run.rs index 8b1500d0..3251c118 100644 --- a/crates/candler/src/commands/run.rs +++ b/crates/candler/src/commands/run.rs @@ -42,8 +42,8 @@ use candler_schemas::execution::{ExperimentFile, JobRecord, JobState}; use candler_schemas::primitives::FieldPath; use super::preflight::{ - check_factors, failed, foreground, json_of, path_of, refuse_plan, refused, request_settings, - requested_harness, + check_factors, failed, foreground, input_for_level, json_of, path_of, refuse_plan, refused, + request_settings, requested_harness, }; use super::refusal::CliRefusal; use super::{CliError, Exit, common}; @@ -249,25 +249,6 @@ fn with_declared_inputs( Ok(input) } -/// The input with `level` as the setting `request.treatment`, its `source` relative to the -/// experiment file's directory `dir` as the file writes it. -fn input_for_level( - input: &ResolveInput, - level: &serde_json::Value, - dir: &Path, -) -> Result<ResolveInput, CliError> { - let path = path_of(paths::REQUEST_TREATMENT)?; - let given = FileValues::new(vec![(path.clone(), json_of(level)?)]) // BORROW: the values own the path - .relative_to(dir) - .map_err(CliError::refused_by)?; - let mut input = input.clone(); // BORROW: each level resolves its own copy - if let (Some(file), Some((_, value))) = (input.file.as_mut(), given.values.into_iter().next()) { - file.values.retain(|(held, _)| *held != path); - file.values.push((path, value)); - } - Ok(input) -} - /// Plans the runs without the experiment lock and builds the job's spec: the agent's input files /// are mounted into every run and the evaluator-only inputs are listed for the manifest. fn plan_job( diff --git a/crates/candler/src/drivers.rs b/crates/candler/src/drivers.rs index c40c4762..56a9432c 100644 --- a/crates/candler/src/drivers.rs +++ b/crates/candler/src/drivers.rs @@ -61,7 +61,8 @@ impl Registry { } /// The streams the harness `name` collects after a run, each with the offline reader its - /// driver gives it. A harness that is not registered, or that collects none, gives none. + /// driver gives it, for a run whose cell is not known: no MCP server is declared to it. A + /// harness that is not registered, or that collects none, gives none. // TRAIT_OBJECT: the readers are the drivers', chosen by the harness's name at runtime #[must_use] pub fn offline(&self, name: &str) -> Vec<(StreamName, Box<dyn TraceReader>)> { @@ -72,7 +73,7 @@ impl Registry { .offline_streams() .into_iter() .filter_map(|stream| { - let reader = driver.offline_reader(&stream)?; + let reader = driver.offline_reader(&stream, &[])?; Some((stream, reader)) }) .collect() diff --git a/crates/candler/tests/fixtures/mcp_origin/claude_code.jsonl b/crates/candler/tests/fixtures/mcp_origin/claude_code.jsonl new file mode 100644 index 00000000..385f17f5 --- /dev/null +++ b/crates/candler/tests/fixtures/mcp_origin/claude_code.jsonl @@ -0,0 +1,5 @@ +{"type":"system","subtype":"init","cwd":"/work","model":"claude-synthetic-1","claude_code_version":"2.1.230","tools":["Bash","mcp__s__t"],"mcp_servers":[{"name":"s","status":"connected"}],"session_id":"33333333-3333-4333-8333-333333333333","uuid":"00000000-0000-4000-8000-000000000000"} +{"type":"user","parent_tool_use_id":null,"message":{"role":"user","content":[{"type":"text","text":"Call the tool."}]},"session_id":"33333333-3333-4333-8333-333333333333","uuid":"00000000-0000-4000-8000-000000000001","timestamp":"2026-01-02T03:04:01.000Z"} +{"type":"assistant","parent_tool_use_id":null,"message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-synthetic-1","content":[{"type":"tool_use","id":"toolu_mcp_cc","name":"mcp__s__t","input":{}}],"usage":{"input_tokens":8,"output_tokens":4,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}},"session_id":"33333333-3333-4333-8333-333333333333","uuid":"00000000-0000-4000-8000-000000000002","timestamp":"2026-01-02T03:04:02.000Z"} +{"type":"user","parent_tool_use_id":null,"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_mcp_cc","content":"{\"ok\":true}"}]},"session_id":"33333333-3333-4333-8333-333333333333","uuid":"00000000-0000-4000-8000-000000000003","timestamp":"2026-01-02T03:04:03.000Z"} +{"type":"result","subtype":"success","is_error":false,"num_turns":1,"duration_ms":10,"stop_reason":"end_turn","total_cost_usd":0.1,"usage":{"input_tokens":8,"output_tokens":4,"cache_read_input_tokens":0,"cache_creation_input_tokens":0},"permission_denials":[],"api_error_status":null,"terminal_reason":"completed","session_id":"33333333-3333-4333-8333-333333333333","uuid":"00000000-0000-4000-8000-000000000004"} diff --git a/crates/candler/tests/fixtures/mcp_origin/opencode_export.json b/crates/candler/tests/fixtures/mcp_origin/opencode_export.json new file mode 100644 index 00000000..44c1d9b3 --- /dev/null +++ b/crates/candler/tests/fixtures/mcp_origin/opencode_export.json @@ -0,0 +1,142 @@ +{ + "info": { + "id": "ses_e32c3735effeWwyJD6JU8Pywnx", + "projectID": "bc7447dce6aa45fd13129230dddc6abeb62cb974", + "model": { + "id": "o1", + "providerID": "fake", + "variant": "default" + }, + "cost": 0, + "tokens": { + "input": 300, + "output": 60, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + }, + "outcome": "succeeded", + "time": { + "created": 1794444660066, + "updated": 1794444660390, + "busy": 1794444660226, + "idle": 1794444660392 + }, + "title": "done: the tool finished.", + "location": { + "directory": "/work" + } + }, + "messages": [ + { + "id": "msg_1cd3c8d6d001KBxxEZ6sgLHwri", + "time": { + "created": 1794444660244 + }, + "text": "Call the tool.", + "files": [], + "type": "user" + }, + { + "id": "msg_1cd3c8e27001RnhlEqrcKAlomW", + "time": { + "created": 1794444660271, + "streamed": 1794444660324, + "completed": 1794444660333 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "o1", + "providerID": "fake", + "variant": "default" + }, + "content": [ + { + "type": "text", + "text": "I will call the tool." + }, + { + "type": "tool", + "id": "toolu_mcp_oc", + "name": "s_t", + "executed": false, + "state": { + "status": "completed", + "input": {}, + "content": [ + { + "type": "text", + "text": "{\"ok\":true}" + } + ], + "metadata": { + "status": "completed", + "truncated": false + } + }, + "time": { + "created": 1794444660297, + "ran": 1794444660319, + "completed": 1794444660332 + } + } + ], + "finish": "tool-calls", + "rawFinish": "tool_use", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_1cd3c8e72001i5yThIjgPP02T3", + "time": { + "created": 1794444660340, + "streamed": 1794444660389, + "completed": 1794444660390 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "o1", + "providerID": "fake", + "variant": "default" + }, + "content": [ + { + "type": "text", + "text": "done: the tool finished." + } + ], + "finish": "stop", + "rawFinish": "end_turn", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_1cd3c8ea8002dLQ356DM9P1duK", + "time": { + "created": 1794444660392 + }, + "type": "idle", + "outcome": "succeeded" + } + ] +} \ No newline at end of file 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/contract_pages.rs b/crates/candler/tests/it/contract_pages.rs index 8153abd6..1b1a8914 100644 --- a/crates/candler/tests/it/contract_pages.rs +++ b/crates/candler/tests/it/contract_pages.rs @@ -29,7 +29,10 @@ fn versions() -> Versions { Versions::read(&repo_root()).expect("the manifests are readable") } -/// Compares a file with its generated text, or writes it when blessing. +/// Compares a file with its generated text, or writes it when blessing. The panic names the first +/// differing line, and when it is a row of a table, its first cell: the row of a Fields table +/// (a path, a capability label or a code), so a driver whose answer changed is followed to the row +/// at fault. fn settle(name: &str, generated: &str) { let path = docs_dir().join(name); let current = fs::read_to_string(&path).ok(); @@ -45,14 +48,25 @@ fn settle(name: &str, generated: &str) { panic!("docs/contract/{name} does not exist; regenerate with CANDLER_BLESS_CONTRACT=1") } Some(current) => { - let at = current + let line = current .lines() .zip(generated.lines()) .position(|(a, b)| a != b) - .unwrap_or(current.lines().count().min(generated.lines().count())); + .unwrap_or(current.lines().count().min(generated.lines().count())) + + 1; + let current_line = current.lines().nth(line - 1).unwrap_or_default(); + let generated_line = generated.lines().nth(line - 1).unwrap_or_default(); + let row = current_line + .strip_prefix("| ") + .and_then(|rest| rest.split(" | ").next()) + .map(|label| label.trim_end_matches(' ')) + .filter(|label| !label.is_empty()) + .map_or_else( + || "a line of the surface outside a table".to_owned(), + |label| format!("the `{label}` row"), + ); panic!( - "docs/contract/{name} differs from the generated page at line {}; regenerate with CANDLER_BLESS_CONTRACT=1", - at + 1 + "docs/contract/{name} differs at line {line} in {row}: committed `{current_line}` vs generated `{generated_line}`; regenerate with CANDLER_BLESS_CONTRACT=1" ); } } @@ -98,8 +112,12 @@ fn d1_regenerating_the_pages_changes_nothing() { ) .expect("the capability page is rendered"); settle("harness-capabilities.md", &capabilities); - let paths = render_paths(&versions, existing("configuration-paths.md").as_deref()) - .expect("the configuration paths page is rendered"); + let paths = render_paths( + registry, + &versions, + existing("configuration-paths.md").as_deref(), + ) + .expect("the configuration paths page is rendered"); settle("configuration-paths.md", &paths); let file_page = render_file_page(&versions, existing("config-file.md").as_deref()) .expect("the configuration file page is rendered"); diff --git a/crates/candler/tests/it/guard_cli_e2e.rs b/crates/candler/tests/it/guard_cli_e2e.rs index 3e36e631..2dbe59de 100644 --- a/crates/candler/tests/it/guard_cli_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e.rs @@ -496,16 +496,7 @@ mod kill_e2e { let shim = Shim::install(&scratch.path().join("bin"), &real, &[]); let dry = candler(&["kill", "--all"], &shim); let dry_out = String::from_utf8_lossy(&dry.stdout).into_owned(); - let mut own: Vec<String> = [&first_lost, &second_lost, &ended] - .iter() - .map(ToString::to_string) - .collect(); - own.sort(); - assert_eq!( - dry_out.lines().next(), - Some(format!("would stop: {}", own.join(" ")).as_str()), - "the store holds jobs the test did not make: {dry_out}" - ); + assert_eq!(dry_out, "", "the refusal off a terminal printed to stdout"); assert_eq!(dry.status.code(), Some(2), "the dry run was not refused"); assert_eq!(shim.log(), "", "the dry run made a docker call"); @@ -547,6 +538,11 @@ mod kill_e2e { let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); let stderr = String::from_utf8_lossy(&out.stderr).into_owned(); assert_eq!(out.status.code(), Some(0), "{stdout}{stderr}"); + assert_eq!( + stdout.lines().count(), + 3, + "kill --all reported other jobs than the test's own three: {stdout}" + ); for job in [&first_lost, &second_lost] { let wanted = format!("{job}: recovered (1 containers destroyed)"); @@ -810,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<String>, - containers: Vec<String>, - images: Vec<String>, +pub(super) struct Made { + pub(super) real: PathBuf, + pub(super) job: Option<String>, + pub(super) containers: Vec<String>, + pub(super) images: Vec<String>, } impl Drop for Made { @@ -111,7 +111,7 @@ impl Drop for Made { } /// What `docker <args>` 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::<Value>(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<Value> { + 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<Value>, + origins: Vec<Value>, +} + +/// The origin of every tool call among the events of the trace `text`, one JSON object per line. +fn call_origins(text: &str) -> Vec<Value> { + fn walk(value: &Value, found: &mut Vec<Value>) { + 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::<Value>(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<Value> = + 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<Vec<Value>> = 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:#?}"); +} diff --git a/crates/candler/tests/it/guard_cli_kill.rs b/crates/candler/tests/it/guard_cli_kill.rs index e771bef6..03967eea 100644 --- a/crates/candler/tests/it/guard_cli_kill.rs +++ b/crates/candler/tests/it/guard_cli_kill.rs @@ -111,6 +111,81 @@ fn kill_all_without_confirmation_makes_no_docker_call() { ); } +/// Guards: B42 — `candler kill <job>` with stdin not a terminal and no `-y` prints nothing on +/// stdout, names the confirm flag on stderr, and reaches no docker client, so the job stays as it +/// was. On a terminal, or with `-y`, the confirmation is unchanged and the stop proceeds. +/// +/// Oracle: the fake client's call log (empty), the exit status (2), and the absent stdout. The +/// command prints nothing while it is refused, so a runner that cannot see a prompt is not left +/// waiting on one. +/// +/// Bite: `kill` writes the prompt to stdout and reads stdin, so off a terminal the prompt reaches +/// the pipe unchanged. +#[test] +fn kill_off_a_terminal_refuses_before_prompting() { + let root = world(); + let out = candler(&root, &["kill", JOB]); + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&out.stderr).into_owned(); + assert_eq!(out.status.code(), Some(2), "{stdout}{stderr}"); + assert_eq!( + stdout, "", + "stdout carried the prompt or the plan: {stdout:?}" + ); + assert!( + stderr.contains("-y"), + "stderr does not name the confirm flag: {stderr}" + ); + assert!( + stderr.contains("candler ps"), + "stderr does not name the command that lists the jobs: {stderr}" + ); + assert_eq!(calls(&root), "", "a refused kill made a docker call"); + + let control = world(); + let out = candler(&control, &["kill", JOB, "-y"]); + let stderr = String::from_utf8_lossy(&out.stderr).into_owned(); + assert_eq!(out.status.code(), Some(0), "{stderr}"); +} + +/// Guards: a store that cannot be read is reported as such, whether or not stdin is a terminal: +/// `candler kill --all --store <a regular file>` with stdin closed and no `-y` gives the store's +/// failure and not the "not confirmed" refusal. +/// +/// Oracle: the exit status and stderr of the real binary; the control run on the same line with +/// the store that exists gives the "not confirmed" refusal, so the two texts differ by cause. +/// +/// Bite: the terminal test runs before the store and the targets are resolved, so the refusal to +/// confirm hides the store's. +#[test] +fn kill_off_a_terminal_reports_the_store_before_the_confirmation() { + let root = world(); + let missing = root.join("a-file"); + fs::write(&missing, "").unwrap(); + let run = |store: &Path| { + Command::new(env!("CARGO_BIN_EXE_candler")) + .args(["kill", "--all", "--store"]) + .arg(store) + .env( + "PATH", + format!("{}:/usr/bin:/bin", root.join("bin").display()), + ) + .stdin(Stdio::null()) + .output() + .unwrap() + }; + let out = run(&missing); + let stderr = String::from_utf8_lossy(&out.stderr).into_owned(); + assert!(!out.status.success(), "{stderr}"); + assert!( + !stderr.contains("pass -y"), + "the store's failure was hidden behind the confirmation: {stderr}" + ); + let control = run(&root.join("store")); + let stderr = String::from_utf8_lossy(&control.stderr).into_owned(); + assert!(stderr.contains("pass -y"), "{stderr}"); +} + /// Runs the real binary on the world, naming its store as `how` says: `CANDLER_STORE` alone, /// or `--store` before the verb. The working directory and the state home name no store. fn candler_naming(root: &Path, how: &str, args: &[&str]) -> Output { diff --git a/crates/candler/tests/it/guard_cli_kill_live.rs b/crates/candler/tests/it/guard_cli_kill_live.rs index 177f0f32..8e85db2b 100644 --- a/crates/candler/tests/it/guard_cli_kill_live.rs +++ b/crates/candler/tests/it/guard_cli_kill_live.rs @@ -424,20 +424,14 @@ exit 1 ); } - // The dry run: without `-y` and with stdin closed the binary refuses, and what it would - // stop is exactly the test's own jobs. + // The dry run: without `-y` and with stdin closed the binary refuses on stderr and keeps + // stdout empty, so no job is stopped or even listed to a stream no one reads. let mut dry = Command::new(env!("CARGO_BIN_EXE_candler")); dry.args(["kill", "--all", "--store"]).arg(&root); confine(&mut dry, tmp.path(), &path); let (dry, said) = bounded(&mut dry); assert_eq!(dry.code(), Some(2), "the dry run was not refused: {said}"); - let mut wanted: Vec<String> = rigs.iter().map(|rig| rig.id.to_string()).collect(); - wanted.sort(); - assert_eq!( - said.lines().next().map(str::to_owned), - Some(format!("would stop: {}", wanted.join(" "))), - "the dry run would stop other jobs than the test's own: {said}" - ); + assert_eq!(said, "", "the dry run printed to stdout: {said:?}"); // The real binary, stdin closed. The test reaps its own supervisors while it waits, as // their parent would: a zombie is not a process that is gone. diff --git a/crates/candler/tests/it/guard_cli_observe.rs b/crates/candler/tests/it/guard_cli_observe.rs index 681d42e0..97ed716d 100644 --- a/crates/candler/tests/it/guard_cli_observe.rs +++ b/crates/candler/tests/it/guard_cli_observe.rs @@ -195,6 +195,201 @@ fn container_calls(world: &World) -> Vec<String> { .collect() } +/// Guards: `resolve` refuses a replicate count the plan refuses, with the same record: `0` from +/// `--set` and from `[fixed]` is `experiment.count_zero` at `/replicates`, and a `[fixed]` count +/// that differs from the file's own is `experiment.replicates_conflict`. +/// +/// Oracle: the codes and the pointer, written by hand. +/// +/// Bite: leave the cell check without the replicate count. +#[test] +fn o1_resolve_refuses_a_replicate_count_the_plan_refuses() { + let world = world(); + let models = Models::start(TOKEN); + let out = resolve( + &world, + &models.url(), + &["--set", "replicates=0"], + Some(TOKEN), + ); + let record: serde_json::Value = serde_json::from_str(text(&out.stderr).trim_end()).unwrap(); + assert_eq!(record["code"], "experiment.count_zero", "{record}"); + assert_eq!(record["path"], "/replicates", "{record}"); + let original = fs::read_to_string(&world.experiment).unwrap(); + fs::write( + &world.experiment, + original.replace("[fixed]\n", "[fixed]\nreplicates = 4\n"), + ) + .unwrap(); + let out = resolve(&world, &models.url(), &[], Some(TOKEN)); + let record: serde_json::Value = serde_json::from_str(text(&out.stderr).trim_end()).unwrap(); + assert_eq!(record["code"], "experiment.replicates_conflict", "{record}"); + assert_eq!(record["path"], "/replicates", "{record}"); + world.remove(); +} + +/// Guards: `resolve --set replicates=<v>` refuses a value that is no count with the record the +/// op API's planning gives it (`guard_silent_acceptance`, the rows of the same three values): the +/// code `experiment.replicates_not_count` at `/replicates`, and a message that gives the range. +/// +/// Oracle: the code, the pointer and the range, written by hand. +/// +/// Bite: `resolve` reads the count in its own layer, so `-1` is refused as "not a whole number" +/// under a code of its own and `5000000000` as a cost cap that is not positive. +#[test] +fn o1_resolve_refuses_what_is_no_replicate_count_as_the_plan_does() { + let world = world(); + let models = Models::start(TOKEN); + for value in ["-1", "2.5", "5000000000"] { + let set = format!("replicates={value}"); + let out = resolve(&world, &models.url(), &["--set", set.as_str()], Some(TOKEN)); + let record: serde_json::Value = serde_json::from_str(text(&out.stderr).trim_end()).unwrap(); + assert_eq!( + record["code"], "experiment.replicates_not_count", + "{value}: {record}" + ); + assert_eq!(record["path"], "/replicates", "{value}: {record}"); + let message = record["message"].as_str().unwrap_or_default(); + assert!(message.contains("1 to 4294967295"), "{value}: {message}"); + } + world.remove(); +} + +/// Guards: `resolve` accepts a valid experiment whose `request.treatment` factor has two table +/// levels, each its own skills commit: every level has a resolution, so no level is reported +/// unresolved. +/// +/// Oracle: the exit code and the two tags, written here; `run` plans the same file to two cells. +/// +/// Bite: give the cell check one resolution for every level. +#[test] +fn o1_resolve_accepts_an_experiment_with_two_treatment_levels() { + let world = world(); + let models = Models::start(TOKEN); + world.tag_new_commit("v2"); + let source = world.skills.display().to_string(); + let text_of = fs::read_to_string(&world.experiment).unwrap(); + let factor = format!( + "[[factors]]\npath = \"request.treatment\"\nlevels = [{{name = \"demo\", tag = \"v1\", source = \"{source}\"}}, {{name = \"demo\", tag = \"v2\", source = \"{source}\"}}]\n\n[budget.per_run]" + ); + fs::write( + &world.experiment, + text_of.replace("[budget.per_run]", &factor), + ) + .unwrap(); + let out = resolve(&world, &models.url(), &[], Some(TOKEN)); + let stderr = text(&out.stderr); + assert_eq!(out.status.code(), Some(0), "stderr: {stderr}"); + assert!(!stderr.contains("has no resolution"), "{stderr}"); + world.remove(); +} + +/// Guards: a treatment level that cannot be resolved is reported the same way whether it is the +/// first level or a later one: the failed check goes through the failure lines on stdout, and the +/// refusal on stderr is the preflight's. +/// +/// Oracle: the exit code and the stdout and stderr of two real runs, one with the missing tag in +/// the first level and one with it in the second; the tags are written here. +/// +/// Bite: a later level's preflight failure is returned as the refusal alone, so stdout stays +/// empty and the failed check is not listed. +#[test] +fn o1_resolve_reports_a_later_level_failure_like_a_first_one() { + let world = world(); + let models = Models::start(TOKEN); + let source = world.skills.display().to_string(); + let original = fs::read_to_string(&world.experiment).unwrap(); + let outputs: Vec<Output> = [("nope", "v1"), ("v1", "nope")] + .iter() + .map(|(first, second)| { + let factor = format!( + "[[factors]]\npath = \"request.treatment\"\nlevels = [{{name = \"demo\", tag = \"{first}\", source = \"{source}\"}}, {{name = \"demo\", tag = \"{second}\", source = \"{source}\"}}]\n\n[budget.per_run]" + ); + fs::write( + &world.experiment, + original.replace("[budget.per_run]", &factor), + ) + .unwrap(); + resolve(&world, &models.url(), &[], Some(TOKEN)) + }) + .collect(); + let [first, later] = outputs.as_slice() else { + unreachable!("two runs") + }; + assert_eq!(first.status.code(), Some(2), "{}", text(&first.stderr)); + assert!( + !first.stdout.is_empty(), + "no failure line for the first level: {}", + text(&first.stderr) + ); + assert_eq!(text(&later.stdout), text(&first.stdout)); + assert_eq!(text(&later.stderr), text(&first.stderr)); + world.remove(); +} + +/// Guards: `resolve` builds each cell, so an absolute path in the `args` of a server (which `run` +/// refuses as `experiment.absolute_path`) and a malformed server written in a factor level are +/// refused by `resolve` too. +/// +/// Oracle: the code and the side, written by hand; the paths and the factor are written here. +/// +/// Bite: leave `resolve` at the resolved values, so neither input is refused. +#[test] +fn o1_resolve_refuses_what_a_cell_holds() { + let world = world(); + let models = Models::start(TOKEN); + let absolute = [ + "--set", + "mcp.servers.fs.command=mcp-fs", + "--set", + "mcp.servers.fs.args=[\"/home/me/data\"]", + ]; + let out = resolve(&world, &models.url(), &absolute, Some(TOKEN)); + let record: serde_json::Value = serde_json::from_str(text(&out.stderr).trim_end()).unwrap(); + assert_eq!(record["code"], "experiment.absolute_path", "{record}"); + let mut experiment = fs::read_to_string(&world.experiment).unwrap(); + experiment.push_str("\n[[factors]]\npath = \"mcp.servers.fs\"\nlevels = [{ command = 7 }]\n"); + fs::write(&world.experiment, experiment).unwrap(); + let out = resolve(&world, &models.url(), &[], Some(TOKEN)); + let record: serde_json::Value = serde_json::from_str(text(&out.stderr).trim_end()).unwrap(); + assert_eq!(record["code"], "experiment.cell_value_invalid", "{record}"); + world.remove(); +} + +/// Guards: a malformed MCP server (a `command` that is not text) is refused by `resolve` and by +/// `run` with the same record: the code `experiment.cell_value_invalid`, side `experiment`, and +/// the path of the server in the message. +/// +/// Oracle: the code, the side and the path, written by hand; the server is set with `--set`. +/// +/// Bite: read the servers leniently again in the verb, as the start check did, so `resolve` prints +/// the values and exits 0. +#[test] +fn o1_resolve_and_run_refuse_a_malformed_mcp_server_with_one_record() { + let world = world(); + let models = Models::start(TOKEN); + let set = ["--set", "mcp.servers.fs.command=7"]; + let resolved = resolve(&world, &models.url(), &set, Some(TOKEN)); + let ran = world.launch_with(&set); + let records: Vec<serde_json::Value> = [&resolved, &ran] + .iter() + .map(|out| { + assert_eq!(out.status.code(), Some(2), "{}", text(&out.stderr)); + let line = text(&out.stderr); + serde_json::from_str(line.trim_end()).unwrap_or_else(|e| panic!("{e}: {line}")) + }) + .collect(); + for record in &records { + assert_eq!(record["code"], "experiment.cell_value_invalid", "{record}"); + assert_eq!(record["side"], "experiment", "{record}"); + let message = record["message"].as_str().unwrap_or_default(); + assert!(message.contains("mcp.servers.fs"), "{message}"); + } + assert_eq!(records[0]["code"], records[1]["code"]); + assert_eq!(records[0]["message"], records[1]["message"]); + world.remove(); +} + /// Guards: O1 — `candler resolve` prints every value and setting with its source from a real /// preflight, from a directory outside the project, and starts no job and no agent. A project /// `candler.toml` gives `plugins.dirs`, a user configuration gives `slots.count`, `--set` gives diff --git a/crates/candler/tests/it/guard_cli_refusal.rs b/crates/candler/tests/it/guard_cli_refusal.rs index aabffae1..329cc9fa 100644 --- a/crates/candler/tests/it/guard_cli_refusal.rs +++ b/crates/candler/tests/it/guard_cli_refusal.rs @@ -904,3 +904,31 @@ fn r2_a_bad_equivalence_file_is_refused_with_its_code() { "{text}" ); } + +/// Guards: an experiment that sets `snapshots` is refused at resolve as an unknown path, as `--set` +/// and as a `[fixed]` value, so no run Candler makes can carry the list. +/// +/// Oracle: the code `experiment.unknown_path` and the path text `snapshots`, written by hand. +/// +/// Bite: put the `snapshots` row back in `CONFIGURATION_PATHS` (the experiment is accepted). +#[test] +fn r3_an_experiment_cannot_set_snapshots() { + let world = cli_run::world(); + let out = world.launch_with(&["--set", "snapshots=[]"]); + let record = record_of(&out); + assert_eq!(record["code"], "experiment.unknown_path", "{record}"); + let message = record["message"].as_str().expect("a message"); + assert!(message.contains("`snapshots`"), "{message}"); + + let world = cli_run::world(); + add_to_fixed(&world, "snapshots = []"); + let record = record_of(&world.launch_with(&[])); + assert_eq!(record["code"], "experiment.unknown_path", "{record}"); + assert!( + record["message"] + .as_str() + .expect("a message") + .contains("`snapshots`"), + "{record}" + ); +} diff --git a/crates/candler/tests/it/guard_driver_answers.rs b/crates/candler/tests/it/guard_driver_answers.rs new file mode 100644 index 00000000..89ee0101 --- /dev/null +++ b/crates/candler/tests/it/guard_driver_answers.rs @@ -0,0 +1,61 @@ +//! Guards: every agent setting is reached by a configuration path or is listed in `NO_PATH` with +//! where it comes from, `NO_PATH` lists nothing a path reaches, and every driver answers every +//! setting a path reaches with words. + +use std::mem::discriminant; + +use candler_core::resolve::paths::{CONFIGURATION_PATHS, NO_PATH, Reach}; +use candler_harness::spec::AgentSetting; + +use crate::drivers::Registry; + +fn reached(setting: AgentSetting) -> bool { + CONFIGURATION_PATHS.iter().any(|row| match row.reach { + Reach::Agent(keys) => keys + .iter() + .any(|key| discriminant(key) == discriminant(&setting)), + Reach::CandlerOnly => false, + }) +} + +#[test] +fn every_agent_setting_is_reached_by_a_path_or_has_no_path() { + let stray: Vec<AgentSetting> = AgentSetting::ALL + .into_iter() + .filter(|setting| { + !reached(*setting) + && !NO_PATH + .iter() + .any(|(listed, _)| discriminant(listed) == discriminant(setting)) + }) + .collect(); + assert!(stray.is_empty(), "reached by no path: {stray:?}"); + let stale: Vec<AgentSetting> = NO_PATH + .iter() + .map(|(listed, _)| *listed) + .filter(|listed| reached(*listed)) + .collect(); + assert!(stale.is_empty(), "listed in NO_PATH and reached: {stale:?}"); +} + +#[test] +fn every_driver_answers_every_path_that_reaches_the_agent() { + let registry = Registry::builtin(); + for name in registry.names() { + let Ok(driver) = registry.driver(&name) else { + panic!("{name} is registered"); + }; + for row in &CONFIGURATION_PATHS { + let Reach::Agent(keys) = row.reach else { + continue; + }; + for key in keys { + assert!( + !driver.answer(*key).text().is_empty(), + "{name}: {} has no answer for {key:?}", + row.path + ); + } + } + } +} diff --git a/crates/candler/tests/it/guard_ingest.rs b/crates/candler/tests/it/guard_ingest.rs index 93d42b04..8ecaf8bc 100644 --- a/crates/candler/tests/it/guard_ingest.rs +++ b/crates/candler/tests/it/guard_ingest.rs @@ -221,6 +221,56 @@ fn i1_each_stream_becomes_one_run() { assert_eq!(seen, expected); } +/// Guards: a raw-ingested cell is keyed as it was before the cell's `snapshots` became optional: +/// it carries an empty list, and its run key names the digest of the cell written with that list. +/// Without it a stream ingested earlier would find its held run keyed by another cell. +/// +/// Oracle: the sha256 of the cell text written by hand, with the sorted keys and `"snapshots":[]`, +/// computed with `Digest::of_bytes`; the harness and treatment members are copied from the stored +/// manifest. +/// +/// Bite: leave `.snapshots(vec![])` out of the raw cell (the key vanishes and the key's cell +/// digest differs). +#[test] +fn i1_a_raw_cell_keeps_the_digest_it_had_with_an_empty_snapshots_list() { + let dir = TempDir::new().expect("a directory"); + let traces = fixture_directory(dir.path()); + let store = Store::init(&dir.path().join("store")).expect("a store"); + ingest_raw(&store, &traces, &recognise, readers().as_ref()).expect("the ingest runs"); + for (name, manifest) in manifests(&dir.path().join("store")) { + let cell = &manifest["comparable"]; + assert_eq!( + cell["snapshots"], + json!([]), + "{name}: the empty list is kept" + ); + let text = format!( + "{{\"environments\":[],\"harness\":{},\"inputs\":[],\"snapshots\":[],\"treatment\":{},\"values\":[]}}", + canonical(&cell["harness"]), + canonical(&cell["treatment"]), + ); + let expected = candler_schemas::primitives::Digest::of_bytes(text.as_bytes()); + assert_eq!( + manifest["run"]["cell"].as_str(), + Some(expected.as_str()), + "{name}: the run key names the old cell digest" + ); + } +} + +/// A JSON object as compact text with its keys in code point order, as the members of a +/// canonical cell are written. +fn canonical(value: &Value) -> String { + let object = value.as_object().expect("an object"); + let mut keys: Vec<&String> = object.keys().collect(); + keys.sort(); + let members: Vec<String> = keys + .iter() + .map(|key| format!("{}:{}", Value::from((*key).as_str()), object[*key])) + .collect(); + format!("{{{}}}", members.join(",")) +} + /// Guards: I1, I17 — no field of a stored manifest or tree, and no source path, starts with `/` or /// holds the temporary directory's text. /// Oracle: the temporary directory's own path, which the test created, and the rule that a stored diff --git a/crates/candler/tests/it/guard_inspect_mcp_config.rs b/crates/candler/tests/it/guard_inspect_mcp_config.rs new file mode 100644 index 00000000..2c9bf460 --- /dev/null +++ b/crates/candler/tests/it/guard_inspect_mcp_config.rs @@ -0,0 +1,113 @@ +//! Guards the MCP configuration `candler inspect` shows for a run the real runner sealed: the +//! resolved `mcp.*` values the cell digest hashes. +#![cfg(test)] +#![cfg(unix)] + +use crate::support::cli_run::world; +use crate::support::seam::finish; + +use std::fs; +use std::process::Command; + +use serde_json::Value; + +/// Guards: a run launched with one declared MCP server is read back through `inspect`, as JSON and +/// as text, and the declared server is among the shown `mcp.*` values. +/// +/// Oracle: the server name and command are the literals the test passes to `candler run --set`. +/// +/// Bite: leave the `mcp.*` values out of what `inspect` shows (the `mcp` member of the record and +/// the text lines both lose the server). +#[test] +fn inspect_shows_the_mcp_server_a_run_was_launched_with() { + let world = world(); + let launched = world.launch_with(&[ + "--set", + "mcp.servers.fs.command=mcp-fs", + "--set", + "mcp.servers.fs.args=[\"data\"]", + ]); + finish(&world, &launched); + world.assert_sealed(1); + + let runs = world.store().join("runs"); + let run_dir = fs::read_dir(&runs) + .unwrap() + .flatten() + .map(|entry| entry.path()) + .find(|path| path.join("run.done").is_file()) + .expect("a sealed run"); + let inspect = |extra: &[&str]| { + let out = Command::new(env!("CARGO_BIN_EXE_candler")) + .arg("inspect") + .arg(&run_dir) + .args(extra) + .current_dir(&world.work) + .env_clear() + .output() + .unwrap(); + assert!(out.status.success(), "inspect exits 0: {out:?}"); + String::from_utf8(out.stdout).unwrap() + }; + + let record: Value = serde_json::from_str(&inspect(&[])).unwrap(); + let shown = record["mcp"] + .as_object() + .unwrap_or_else(|| panic!("the record shows the mcp values: {record}")); + assert_eq!( + shown.get("mcp.servers.fs.command"), + Some(&Value::from("mcp-fs")), + "the declared command is shown: {record}" + ); + assert_eq!( + shown.get("mcp.servers.fs.args"), + Some(&serde_json::json!(["data"])), + "the declared arguments are shown: {record}" + ); + + let text = inspect(&["--format", "text"]); + assert!( + text.lines() + .any(|line| line.starts_with("mcp.servers.fs") && line.contains("mcp-fs")), + "the text shows the declared server:\n{text}" + ); +} + +/// Guards: a cell Candler resolves and runs carries no `snapshots` key, and its digest, which +/// names the run, is the digest of the cell written without it. +/// +/// Oracle: the run's key names the cell digest the runner computed; the test recomputes it from +/// the stored `comparable` text with `Digest::of_canonical`, so a key written or hashed but not +/// stored (or the other way round) moves one side only. +/// +/// Bite: have resolve fill `comparable.snapshots` with an empty list (the key appears in the +/// stored cell and the digest changes). +#[test] +fn a_cell_from_resolve_is_stored_and_hashed_without_snapshots() { + let world = world(); + let launched = world.launch(); + finish(&world, &launched); + world.assert_sealed(1); + + let runs = world.store().join("runs"); + let run_dir = fs::read_dir(&runs) + .unwrap() + .flatten() + .map(|entry| entry.path()) + .find(|path| path.join("run.done").is_file()) + .expect("a sealed run"); + let manifest: Value = + serde_json::from_slice(&fs::read(run_dir.join("manifest.json")).unwrap()).unwrap(); + let comparable = manifest["comparable"].as_object().expect("a stored cell"); + assert!( + !comparable.contains_key("snapshots"), + "a new cell carries no snapshots key: {comparable:?}" + ); + let recomputed = candler_schemas::primitives::Digest::of_canonical(&manifest["comparable"]) + .expect("the cell has a canonical form"); + assert_eq!( + manifest["run"]["cell"].as_str(), + Some(recomputed.as_str()), + "the run is keyed by the digest of the cell as stored" + ); +} diff --git a/crates/candler/tests/it/guard_mcp_origin.rs b/crates/candler/tests/it/guard_mcp_origin.rs new file mode 100644 index 00000000..1caa76a5 --- /dev/null +++ b/crates/candler/tests/it/guard_mcp_origin.rs @@ -0,0 +1,116 @@ +#![cfg(test)] +//! Both readers record a call to one tool of one declared MCP server as the same origin. +//! +//! Guards: README (an MCP call reads the same in the trace of either harness) -- the recorded +//! output of one call to the tool `t` of the server `s`, read by Claude Code's live reader and by +//! `OpenCode`'s export reader, gives the same `origin`, and Claude Code's trace keeps the raw +//! `system/init` line that names the server's status. +//! Oracle: the `origin` object written by hand from the trace schema; the recorded streams in +//! `tests/fixtures/mcp_origin/`, whose tool is `mcp__s__t` for Claude Code and `s_t` for `OpenCode`. +//! Bite: a reader that loses the server (`other` for an unknown prefix), one that keeps the +//! harness's spelling of the tool, or a Claude Code reader that drops the init line. + +use std::error::Error; +use std::path::{Path, PathBuf}; + +use candler_harness::reader::{FrameIn, TraceReader}; +use candler_schemas::raw::{FrameData, RawFrame, RawRef, StreamName}; +use candler_schemas::trace::SessionEvent; +use serde_json::{Value, json}; + +use crate::drivers::Registry; + +// TRAIT_OBJECT: a test returns any error its steps raise; the error is only printed +type Res<T> = Result<T, Box<dyn Error>>; + +fn fixture(file: &str) -> Res<Vec<u8>> { + let dir: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("fixtures") + .join("mcp_origin"); + Ok(std::fs::read(dir.join(file))?) +} + +/// Feeds each frame to `reader` and returns the events of the finished trace. +fn read_frames( + mut reader: Box<dyn TraceReader>, + stream: &str, + frames: &[&[u8]], +) -> Res<Vec<SessionEvent>> { + let name: StreamName = stream.parse()?; + let mut events = Vec::new(); + for (index, bytes) in frames.iter().enumerate() { + let frame = RawFrame::new(None, FrameData::from_bytes(bytes)); + let raw_ref = RawRef::new(name.clone(), u64::try_from(index)?); // BORROW: one name per frame + events.extend(reader.feed(FrameIn::new(raw_ref, None, &frame))?); + } + reader.finish()?; + Ok(events) +} + +/// The `origin` of each tool call among `events`, as the trace file writes it. +fn origins(events: &[SessionEvent]) -> Res<Vec<Value>> { + let mut found = Vec::new(); + for entry in events { + let kind = serde_json::to_value(&entry.event.kind)?; + if kind.get("kind") == Some(&json!("tool_call")) { + found.push(kind.get("origin").cloned().unwrap_or(Value::Null)); // BORROW: .cloned() copies the origin + } + } + Ok(found) +} + +/// Claude Code's trace of the recorded stream. +fn claude_code() -> Res<Vec<SessionEvent>> { + let bytes = fixture("claude_code.jsonl")?; + let lines: Vec<&[u8]> = bytes + .split(|byte| *byte == b'\n') + .filter(|line| !line.is_empty()) + .collect(); + let driver = Registry::builtin() + .driver("claude-code") + .map_err(|_| "no driver")?; + let reader = driver.live_reader().ok_or("no live reader")?; + read_frames(reader, "stdout", &lines) +} + +/// `OpenCode`'s trace of the recorded export of a cell that declares the server `s`. +fn opencode() -> Res<Vec<SessionEvent>> { + let bytes = fixture("opencode_export.json")?; + let driver = Registry::builtin() + .driver("opencode") + .map_err(|_| "no driver")?; + let export: StreamName = "export".parse()?; + let servers = vec!["s".to_owned()]; + let reader = driver + .offline_reader(&export, &servers) + .ok_or("no export reader")?; + read_frames(reader, "export", &[&bytes]) +} + +#[test] +fn one_call_has_one_origin_on_both_harnesses() -> Res<()> { + let one = json!({"kind": "mcp", "server": "s", "tool": "t"}); + let want = json!({"claude-code": [one.clone()], "opencode": [one]}); // BORROW: .clone() gives each harness its own copy + let got = json!({ + "claude-code": origins(&claude_code()?)?, + "opencode": origins(&opencode()?)?, + }); + assert_eq!(got, want, "the origin of the call on each harness"); + Ok(()) +} + +#[test] +fn claude_code_trace_keeps_the_raw_init_line() -> Res<()> { + let events = serde_json::to_string( + &claude_code()? + .iter() + .map(|entry| &entry.event) + .collect::<Vec<_>>(), + )?; + assert!( + events.contains("\"subtype\":\"init\"") && events.contains("\"status\":\"connected\""), + "the trace holds the init line with the server status: {events}" + ); + Ok(()) +} diff --git a/crates/candler/tests/it/guard_run_context_files.rs b/crates/candler/tests/it/guard_run_context_files.rs new file mode 100644 index 00000000..c1bfaaf3 --- /dev/null +++ b/crates/candler/tests/it/guard_run_context_files.rs @@ -0,0 +1,196 @@ +//! Guards for the file rule of a run context over runs the real runner sealed: the agent leaves a +//! file set in its workspace under `candler run`, and the context a plug-in receives is built from +//! the store that run left. The runner never collects `.claude` (`EXCLUDED_DIRS` in the Claude Code +//! driver's `discovery.rs`), so the file rule's `.claude` cases are sealed in the core's guards. +#![cfg(test)] +#![cfg(unix)] + +use crate::support::cli_run::{World, world}; +use crate::support::seam::finish; + +use std::collections::BTreeSet; +use std::os::unix::fs::MetadataExt as _; +use std::path::Path; +use std::str::FromStr as _; + +use candler_core::evaluation::context::{assemble, materialise}; +use candler_core::store::Store; +use candler_schemas::evaluation::{ContextArtifact, Needs, RunContext}; +use candler_schemas::primitives::{Digest, RelPath, RunKey}; +use candler_testkit::file_set; + +/// One row of the file-rule table: artifact globs, the files the agent leaves (each holds its own +/// path as bytes), and the hand-listed set of paths that the context carries. +struct Case { + name: &'static str, + globs: &'static [&'static str], + stored: &'static [&'static str], + kept: &'static [&'static str], +} + +/// The file-rule table; the sets in `kept` are written by hand from R03's file rule. +const CASES: &[Case] = &[ + Case { + name: "a nested match counts", + globs: &["outputs/**"], + stored: &["a.py", "sub/deep/b.py", "sub/c.json"], + kept: &["a.py", "sub/c.json", "sub/deep/b.py"], + }, + Case { + name: "AppleDouble files are dropped", + globs: &["outputs/**"], + stored: &["domain.py", "._domain.py", "sub/._b.py", "sub/b.py"], + kept: &["domain.py", "sub/b.py"], + }, + Case { + name: ".DS_Store is dropped", + globs: &["outputs/**"], + stored: &["x.py", ".DS_Store", "sub/.DS_Store"], + kept: &["x.py"], + }, + Case { + name: "a hidden directory below a nested path is dropped", + globs: &["outputs/**"], + stored: &["sub/.hidden/y.py", "sub/z.py"], + kept: &["sub/z.py"], + }, + Case { + name: "an empty outputs gives no artifact and no error", + globs: &["outputs/**"], + stored: &[], + kept: &[], + }, + Case { + name: "a literal dot file is kept by its own glob and not by another", + globs: &["outputs/**", "outputs/.env"], + stored: &[".env", "a/.env", "x"], + kept: &[".env", "x"], + }, + Case { + name: "a glob keeps only what it matches", + globs: &["outputs/*.py"], + stored: &["a.py", "sub/b.py", "c.json"], + kept: &["a.py"], + }, +]; + +/// Needs with the given artifact globs and no metadata. +fn needs_of(globs: &[&str]) -> Needs { + let mut needs = Needs::default(); + needs.artifacts = globs.iter().map(|g| (*g).to_owned()).collect(); + needs +} + +/// Runs the experiment of a world whose agent leaves exactly `files` (each holding its own path as +/// bytes) through `candler run`, and returns the world, its store and the one sealed run. +fn sealed_run_with(files: &[&str]) -> (World, Store, RunKey) { + let world = world(); + let leaves: Vec<(&str, &[u8])> = files.iter().map(|f| (*f, f.as_bytes())).collect(); + world.agent_leaves(&leaves); + let launched = world.launch(); + finish(&world, &launched); + world.assert_sealed(1); + let store = Store::open(&world.store()).expect("the store opens"); + let run = store + .runs() + .expect("the runs list") + .into_iter() + .next() + .expect("a run") + .key; + (world, store, run) +} + +/// The context `run` gets in `workspace` under `needs`. +fn context_of(store: &Store, run: &RunKey, needs: &Needs, workspace: &Path) -> RunContext { + let assembled = assemble(store, run, needs).expect("the run assembles"); + materialise(&assembled, workspace).expect("the run materialises") +} + +/// Guards: R9 — the paths of a materialised context and the paths its digest covers are exactly the files the file rule keeps: a nested match counts, `._*` and `.DS_Store` are dropped unless a glob names them, and an empty `outputs/` gives no artifact and no error. Each run is made by `candler run` over a fake agent that leaves the case's files. Oracle: hand-listed path sets, and the digest of a context built from the listed paths and the literal bytes. +#[test] +fn the_file_rule_decides_the_paths_and_the_digest() { + for case in CASES { + let (_world, store, run) = sealed_run_with(case.stored); + let workspace = tempfile::tempdir().expect("a workspace"); + let context = context_of(&store, &run, &needs_of(case.globs), workspace.path()); + let expected: BTreeSet<String> = case.kept.iter().map(|p| (*p).to_owned()).collect(); + assert_eq!( + file_set(&workspace.path().join("outputs")), + expected, + "materialised files: {}", + case.name + ); + let artifacts: BTreeSet<String> = context + .artifacts() + .iter() + .map(|a| a.path.to_string()) + .collect(); + assert_eq!(artifacts, expected, "digest path list: {}", case.name); + let mut builder = RunContext::builder() + .run(run.clone()) + .root("/unused".into()); + for path in case.kept { + builder = builder.artifact(ContextArtifact::new( + RelPath::from_str(path).expect("a path"), + String::from("/unused"), + Digest::of_bytes(path.as_bytes()), + )); + } + assert_eq!( + context.context_digest(), + builder.build().expect("a context").context_digest(), + "digest: {}", + case.name + ); + } +} + +/// Guards: R9 and I11 — a file the agent left is materialised as a private read-only copy, not a link: a fresh inode with one link and mode `0444`, while the store blob keeps its own inode and mode `0444`. The run is made by `candler run`. Oracle: `stat` of the copy and of the blob. +#[test] +fn a_materialised_file_is_a_private_read_only_copy() { + let (_world, store, run) = sealed_run_with(&["plain.py"]); + let workspace = tempfile::tempdir().expect("a workspace"); + context_of(&store, &run, &needs_of(&["outputs/**"]), workspace.path()); + + let copy = std::fs::metadata(workspace.path().join("outputs/plain.py")).expect("a copy"); + let blob = std::fs::metadata(store.blob_path(&Digest::of_bytes(b"plain.py"))).expect("a blob"); + assert_eq!(copy.mode() & 0o777, 0o444, "the mode of the copy"); + assert_eq!(copy.nlink(), 1, "the copy has one link"); + assert_ne!(copy.ino(), blob.ino(), "the copy is not the blob"); + assert_eq!(blob.nlink(), 1, "the blob gained no link"); + assert_eq!(blob.mode() & 0o777, 0o444, "the mode of the blob"); +} + +/// Guards: R9 and I11 — an output the agent left with an execute bit materialises as `0555` and +/// one without as `0444`: the run stores the bit it collected. The run is made by `candler run` +/// over a fake agent whose `run.sh` is executable. Oracle: `stat` of the copies, and the mode given +/// to the file the agent leaves. +#[test] +fn an_executable_output_materialises_as_0555_and_a_plain_one_as_0444() { + let world = world(); + world.agent_leaves(&[("run.sh", b"#!/bin/sh\n"), ("note.txt", b"note\n")]); + world.agent_leaves_executable("run.sh"); + let launched = world.launch(); + finish(&world, &launched); + world.assert_sealed(1); + let store = Store::open(&world.store()).expect("the store opens"); + let run = store + .runs() + .expect("the runs list") + .into_iter() + .next() + .expect("a run") + .key; + let workspace = tempfile::tempdir().expect("a workspace"); + context_of(&store, &run, &needs_of(&["outputs/**"]), workspace.path()); + + let mode = |name: &str| { + std::fs::metadata(workspace.path().join("outputs").join(name)) + .expect("a copy") + .mode() + & 0o777 + }; + assert_eq!(mode("run.sh"), 0o555, "the mode of the executable"); + assert_eq!(mode("note.txt"), 0o444, "the mode of the plain file"); +} diff --git a/crates/candler/tests/it/main.rs b/crates/candler/tests/it/main.rs index 6b4e8a46..fab5294a 100644 --- a/crates/candler/tests/it/main.rs +++ b/crates/candler/tests/it/main.rs @@ -58,6 +58,7 @@ mod guard_cli_observe; mod guard_cli_refusal; mod guard_cli_run; mod guard_cli_surface; +mod guard_driver_answers; mod guard_eval_infra; mod guard_golden_design; mod guard_golden_parity; @@ -65,5 +66,8 @@ mod guard_ground_truth_cli; mod guard_ingest; mod guard_input_seam; mod guard_inspect; +mod guard_inspect_mcp_config; +mod guard_mcp_origin; mod guard_registry; +mod guard_run_context_files; mod guard_run_evaluate; diff --git a/crates/candler/tests/it/support/cli_run.rs b/crates/candler/tests/it/support/cli_run.rs index e23d89dc..fd593616 100644 --- a/crates/candler/tests/it/support/cli_run.rs +++ b/crates/candler/tests/it/support/cli_run.rs @@ -132,7 +132,11 @@ start) *" -a "*) id=$(last "$@") if [ -f "$st/c/$id.work" ]; then - printf 'graded from the store\n' > "$(cat "$st/c/$id.work")/answer.txt" + if [ -d "$here/agent-files" ]; then + cp -Rp "$here/agent-files/." "$(cat "$st/c/$id.work")/" + else + printf 'graded from the store\n' > "$(cat "$st/c/$id.work")/answer.txt" + fi fi sleep 1 echo exited > "$st/c/$(last "$@").state" @@ -157,12 +161,12 @@ exec) esac ;; logs) ;; +inspect) + # The start probe of a declared MCP server asks whether the container is still running. + echo true + ;; run) - if case " $* " in *" --version "*) true;; *) false;; esac; then - echo "2.1.311 (Claude Code)" - else - printf '{"schema":"tool-catalog-snapshot/1","captured_at":"2024-01-01T00:00:00Z","provider":"candler-image@1","servers":[]}' - fi + case " $* " in *" --version "*) echo "2.1.311 (Claude Code)" ;; esac ;; *) echo "UNHANDLED: $*" >> "$here/docker.log" @@ -326,11 +330,26 @@ impl World { let sealed = self.sealed_runs(); assert!( sealed >= at_least, - "no run sealed: {sealed} sealed, {at_least} expected\ncalls:\n{}", - self.calls() + "no run sealed: {sealed} sealed, {at_least} expected\ncalls:\n{}\nevents:\n{}", + self.calls(), + self.job_events() ); } + /// The events of every job of the store, as the supervisor wrote them. + fn job_events(&self) -> String { + let mut text = String::new(); + let Ok(jobs) = fs::read_dir(self.store().join("jobs")) else { + return text; + }; + for job in jobs.flatten() { + if let Ok(events) = fs::read_to_string(job.path().join("events.jsonl")) { + text.push_str(&events); + } + } + text + } + /// What the fake client was asked, one call per line. pub fn calls(&self) -> String { fs::read_to_string(self.bin.join("docker.log")).unwrap() @@ -401,6 +420,34 @@ impl World { (before, rev_parse(&self.skills, "v1^{commit}")) } + /// Makes the fake agent leave exactly `files` in its workspace, as `(path, bytes)`, in place + /// of the file it writes by default; no file at all when `files` is empty. + pub fn agent_leaves(&self, files: &[(&str, &[u8])]) { + let dir = self.bin.join("agent-files"); + fs::create_dir_all(&dir).unwrap(); + for (path, bytes) in files { + let at = dir.join(path); + fs::create_dir_all(at.parent().unwrap()).unwrap(); + fs::write(at, bytes).unwrap(); + } + } + + /// Gives the file the fake agent leaves at `path` the execute bit; the fake's copy keeps the + /// mode of the file as a real agent's workspace does. + pub fn agent_leaves_executable(&self, path: &str) { + let at = self.bin.join("agent-files").join(path); + fs::set_permissions(at, fs::Permissions::from_mode(0o755)).unwrap(); + } + + /// Makes a new commit in the skills repository and tags it `tag`, leaving the earlier tags + /// where they are. + pub fn tag_new_commit(&self, tag: &str) { + let skill = self.skills.join(".claude").join("skills").join("demo"); + fs::write(skill.join("SKILL.md"), format!("# {tag}\n")).unwrap(); + git(&self.skills, &["commit", "-q", "-a", "-m", tag]); + git(&self.skills, &["tag", tag]); + } + /// Removes the world's directory. pub fn remove(&self) { drop(fs::remove_dir_all(&self.root)); diff --git a/crates/candler/tests/it/support/contract_pages/capabilities.rs b/crates/candler/tests/it/support/contract_pages/capabilities.rs index 87afef85..0ebadbe7 100644 --- a/crates/candler/tests/it/support/contract_pages/capabilities.rs +++ b/crates/candler/tests/it/support/contract_pages/capabilities.rs @@ -1,22 +1,21 @@ //! The capability page: what a run can expect of each driver the binary registers, one column per -//! driver and one row per capability. +//! driver and one row per setting, per fact and per typed spec. //! -//! Each row has one mapping from what a driver declares to the words of its cell, so a reader never -//! meets two spellings of one fact. +//! The rows come from `AgentSetting::ALL` and `DriverFact::ALL`, one row per entry, plus the rows a +//! driver does not declare words for (gateway route, authoritative trace), which read the driver's +//! typed specs. Each cell of a setting or fact row is [`answer_words`] of the driver's `answer` or +//! `fact`; a reader never meets one fact in two spellings. use std::fmt::Write; -use std::path::Path; -use std::str::FromStr as _; use std::sync::Arc; -use candler_harness::driver::{Disposition, HarnessDriver}; -use candler_harness::spec::{Action, StopSignal, StopSpec}; -use candler_schemas::execution::{GitCommit, TreatmentRef}; -use candler_schemas::primitives::Name; +use candler_harness::driver::HarnessDriver; +use candler_harness::spec::{AgentSetting, DriverFact}; use super::harness::{HarnessPage, assemble, cell, version_section}; use super::refusals::{Entry, catalogue_entries}; use super::versions::Versions; +use super::{answer_words, setting_label}; use crate::drivers::Registry; /// The page of the capabilities of the registered drivers. @@ -34,109 +33,34 @@ const CAPABILITY_CODES: [&str; 2] = [ "experiment.setting_unsupported", ]; -/// A cell of the capability table, from one driver. -type Mapping = fn(&str, &Arc<dyn HarnessDriver>, &Registry) -> Result<String, String>; - -/// The rows of the capability table: the row's name and the one mapping that words its cells. -const ROWS: [(&str, Mapping); 8] = [ - ("gateway route", gateway_route), - ("census source", census_source), - ("session mode", session_mode), - ("turn cap", turn_cap), - ("cost cap", cost_cap), - ("stop", stop), - ("authoritative trace", authoritative_trace), - ("skills layout", skills_layout), -]; +/// The label of the row a driver fact words. +const fn fact_label(fact: DriverFact) -> &'static str { + match fact { + DriverFact::GracefulStop => "graceful stop", + DriverFact::LiveEvents => "live events", + DriverFact::InHarnessGuard => "in-harness guard", + DriverFact::ExecutionOutsideChild => "execution outside the child", + DriverFact::Census => "census source", + DriverFact::UnsetPermissionMode => "permission mode when none is set", + } +} -fn gateway_route(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> { +/// The cell of one driver for its gateway variables. +/// +/// # Errors +/// `Err` when the driver names no gateway variables; no registered driver fails this. +fn gateway_route(driver: &Arc<dyn HarnessDriver>) -> Result<String, String> { let env = driver .gateway() .ok_or("a registered driver names its gateway variables")?; Ok(format!("Candler: gateway, address in `{}`", env.base_url)) } -fn census_source(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> { - match (driver.capabilities().census, driver.census_stream()) { - (true, Some(_)) => Ok("Candler: gateway, first request with tools".to_owned()), - (true, None) => Ok("yes".to_owned()), - (false, _) => Err("a registered driver without a census has no cell wording".to_owned()), - } -} - -#[expect( - clippy::unnecessary_wraps, - reason = "every row of the table has the one mapping type" -)] -fn session_mode(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> { - Ok(if driver.capabilities().session { - "yes".to_owned() - } else { - "no (refused)".to_owned() - }) -} - -/// A cap the harness enforces is `yes`; one it lacks must be a refused row of its settings table. -fn cap(driver: &Arc<dyn HarnessDriver>, enforced: bool, setting: &str) -> Result<String, String> { - if enforced { - return Ok("yes".to_owned()); - } - let refused = driver - .settings_table() - .iter() - .any(|row| row.setting == setting && row.disposition == Disposition::Refused); - if refused { - Ok("no (refused)".to_owned()) - } else { - Err(format!( - "a driver that lacks `{setting}` declares a refused row for it" - )) - } -} - -fn turn_cap(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> { - cap( - driver, - driver.capabilities().budgets.turns, - "budget.per_run.turns", - ) -} - -fn cost_cap(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> { - cap( - driver, - driver.capabilities().budgets.cost, - "budget.per_run.max_cost_usd", - ) -} - -fn signal(spec: &StopSpec) -> Result<&'static str, String> { - match spec.signal { - StopSignal::Term => Ok("SIGTERM"), - StopSignal::Int => Ok("SIGINT"), - StopSignal::Hup => Ok("SIGHUP"), - _ => Err("a stop signal has no wording".to_owned()), - } -} - -fn stop(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> { - let spec = driver.stop(); - let signal = signal(&spec)?; - match (&spec.pre_stop, driver.capabilities().graceful_stop) { - (None, true) => Ok("yes".to_owned()), - (Some(Action::Exec(_)), _) => Ok(format!( - "Candler: interrupt command in the container, then {signal}" - )), - (Some(Action::Command(_)), _) => Ok(format!( - "Candler: interrupt command on the host, then {signal}" - )), - (Some(Action::Http { .. }), _) => Ok(format!("Candler: interrupt request, then {signal}")), - (None, false) | (Some(_), _) => { - Err("a registered driver's stop has no cell wording".to_owned()) - } - } -} - +/// The cell of one driver for its authoritative trace: the offline stream the registry collects, +/// or the driver's live reader when it streams events itself. +/// +/// # Errors +/// `Err` when the driver's trace has no cell wording; no registered driver fails this. fn authoritative_trace( name: &str, driver: &Arc<dyn HarnessDriver>, @@ -145,73 +69,39 @@ fn authoritative_trace( if let Some((stream, _)) = registry.offline(name).first() { return Ok(format!("Candler: collects `{stream}` after the run")); } - if driver.live_reader().is_some() && driver.capabilities().live_events { + if driver.live_reader().is_some() && !driver.fact(DriverFact::LiveEvents).is_refused() { return Ok("yes".to_owned()); } Err("a registered driver's trace has no cell wording".to_owned()) } -/// A treatment whose tree the driver's skill layout is asked about. -fn probe_treatment() -> Result<TreatmentRef, String> { - let name = Name::from_str("probe").map_err(|e| e.to_string())?; - let mut treatment = TreatmentRef::new(name); - treatment.commit = Some(GitCommit::from_str(&"0".repeat(40)).map_err(|e| e.to_string())?); - Ok(treatment) -} - -/// A tar archive with one regular file `path` that holds `x`. -fn tar_of(path: &str) -> Vec<u8> { - let mut header = [0_u8; 512]; - header[..path.len()].copy_from_slice(path.as_bytes()); - header[100..107].copy_from_slice(b"0000644"); - header[124..135].copy_from_slice(b"00000000001"); - header[136..147].copy_from_slice(b"00000000000"); - header[156] = b'0'; - header[257..263].copy_from_slice(b"ustar\0"); - header[148..156].copy_from_slice(b" "); - let sum: u32 = header.iter().map(|byte| u32::from(*byte)).sum(); - header[148..155].copy_from_slice(format!("{sum:06o}\0").as_bytes()); - let mut out = header.to_vec(); - let mut data = [0_u8; 512]; - data[0] = b'x'; - out.extend_from_slice(&data); - out.extend_from_slice(&[0_u8; 1024]); - out -} - -fn skills_layout(_: &str, driver: &Arc<dyn HarnessDriver>, _: &Registry) -> Result<String, String> { - let treatment = probe_treatment()?; - let skills = driver.skills(); - let archive = skills - .archive_command(&treatment, Path::new("/probe")) - .map_err(|e| e.to_string())?; - let subtree = archive - .argv() - .last() - .ok_or("the archive command has no pathspec")? - .clone(); - let files = skills - .files(&treatment, &tar_of(&format!("{subtree}/SKILL.md"))) - .map_err(|e| e.to_string())?; - let first = files - .first() - .map(|file| file.path.as_str()) - .ok_or("the layout places no file")?; - let tree = first - .strip_suffix("/SKILL.md") - .ok_or("the layout does not place SKILL.md")?; - if tree == subtree { - Ok("yes".to_owned()) - } else { - Ok(format!( - "Candler: places the tree at `{}`", - tree.replace("probe", "<name>") - )) +/// Writes one row: the label and each driver's cell. +/// +/// # Errors +/// [`CliError`](crate::commands::CliError) of the registry, when no registered driver has the +/// name; no registered driver fails a cell. +fn write_row( + out: &mut String, + label: &str, + names: &[String], + registry: &Registry, + cells: impl Fn(&str, &Arc<dyn HarnessDriver>) -> Result<String, String>, +) -> Result<(), String> { + let _ = write!(out, "| {label} |"); + for name in names { + let driver = registry + .driver(name) + .map_err(|_| format!("no driver for `{name}`"))?; + let text = cells(name, &driver).map_err(|e| format!("{label} of `{name}`: {e}"))?; + let _ = write!(out, " {} |", cell(&text)); } + out.push('\n'); + Ok(()) } -/// The capability table: one row per capability, one column per registered driver. -fn capability_fields(registry: &Registry) -> Result<String, String> { +/// The capability table: one row per setting, per typed spec or per fact, one column per +/// registered driver. +fn fields_table(registry: &Registry) -> Result<String, String> { let names = registry.names(); let mut out = String::from("| Capability |"); for name in &names { @@ -222,17 +112,29 @@ fn capability_fields(registry: &Registry) -> Result<String, String> { out.push_str("---|"); } out.push('\n'); - for (label, mapping) in ROWS { - let _ = write!(out, "| {label} |"); - for name in &names { - let driver = registry - .driver(name) - .map_err(|_| format!("no driver for `{name}`"))?; - let text = mapping(name, &driver, registry) - .map_err(|e| format!("{label} of `{name}`: {e}"))?; - let _ = write!(out, " {} |", cell(&text)); - } - out.push('\n'); + for setting in AgentSetting::ALL { + write_row( + &mut out, + setting_label(setting), + &names, + registry, + |_, driver| Ok(answer_words(driver.answer(setting))), + )?; + } + write_row(&mut out, "gateway route", &names, registry, |_, driver| { + gateway_route(driver) + })?; + write_row( + &mut out, + "authoritative trace", + &names, + registry, + |name, driver| authoritative_trace(name, driver, registry), + )?; + for fact in DriverFact::ALL { + write_row(&mut out, fact_label(fact), &names, registry, |_, driver| { + Ok(answer_words(driver.fact(fact))) + })?; } Ok(out) } @@ -258,7 +160,7 @@ pub fn render_capabilities( &CAPABILITY_PAGE, CAPABILITY_SURFACE, &version_section(versions)?, - &capability_fields(registry)?, + &fields_table(registry)?, &refusals, existing, )) diff --git a/crates/candler/tests/it/support/contract_pages/config_pages.rs b/crates/candler/tests/it/support/contract_pages/config_pages.rs index ce860b65..c423220f 100644 --- a/crates/candler/tests/it/support/contract_pages/config_pages.rs +++ b/crates/candler/tests/it/support/contract_pages/config_pages.rs @@ -3,14 +3,18 @@ use std::fmt::Write; use std::fs; +use std::mem; -use candler_core::resolve::paths::{CONFIGURATION_PATHS, ConfigFile, Kind}; +use candler_core::resolve::paths::{CONFIGURATION_PATHS, ConfigFile, Kind, Reach}; +use candler_harness::spec::AgentSetting; use syn::{Expr, ExprArray, ExprLit, Item, Lit}; use super::harness::{HarnessPage, assemble, cell}; use super::refusals::{Entry, all_entries}; use super::repo_root; use super::versions::{CLOSE, OPEN, Versions}; +use super::{answer_words, setting_label}; +use crate::drivers::Registry; /// The page of the configuration paths. pub const PATHS_PAGE: HarnessPage = HarnessPage { @@ -79,10 +83,54 @@ fn names(kind: Kind) -> &'static str { } } -fn paths_fields() -> String { - let mut out = String::from("| Path | Names | Class | Meaning |\n|---|---|---|---|\n"); +/// The settings of the same family as `sample`: every `AgentSetting` whose variant is the sample's, +/// so a path that holds one value of a closed family shows every value the cell could hold. +#[must_use] +pub fn family_of(sample: AgentSetting) -> Vec<AgentSetting> { + AgentSetting::ALL + .into_iter() + .filter(|setting| mem::discriminant(setting) == mem::discriminant(&sample)) + .collect() +} + +/// The cell of one driver for the agent settings a path reaches: each family of the row's keys, +/// every value of the family labelled with its setting, joined by `; `. +/// +/// # Errors +/// `Err` naming the driver when the registry has no driver for `name`; never otherwise, as every +/// registered driver answers every setting. +fn driver_cells( + name: &str, + registry: &Registry, + settings: &[AgentSetting], +) -> Result<String, String> { + let driver = registry + .driver(name) + .map_err(|_| format!("no driver for `{name}`"))?; + let mut fragments: Vec<String> = Vec::new(); + for sample in settings { + let values = family_of(*sample); + for setting in values { + let text = answer_words(driver.answer(setting)); + fragments.push(format!("{}: {text}", setting_label(setting))); + } + } + Ok(fragments.join("; ")) +} + +fn paths_fields(registry: &Registry) -> Result<String, String> { + let registered = registry.names(); + let mut out = String::from("| Path | Names | Class | Meaning |"); + for driver in ®istered { + let _ = write!(out, " {driver} |"); + } + out.push_str("\n|---|---|---|---|"); + for _ in ®istered { + out.push_str("---|"); + } + out.push('\n'); for row in &CONFIGURATION_PATHS { - let _ = writeln!( + let _ = write!( out, "| `{}` | {} | {} | {} |", cell(row.path), @@ -90,8 +138,22 @@ fn paths_fields() -> String { row.class.text(), cell(row.meaning) ); + match &row.reach { + Reach::CandlerOnly => { + for _ in ®istered { + out.push_str(" Candler only |"); + } + } + Reach::Agent(settings) => { + for driver in ®istered { + let text = driver_cells(driver, registry, settings)?; + let _ = write!(out, " {} |", cell(&text)); + } + } + } + out.push('\n'); } - out + Ok(out) } fn file_fields() -> String { @@ -114,12 +176,16 @@ fn file_fields() -> String { } /// The page of the configuration paths. -pub fn render_paths(versions: &Versions, existing: Option<&str>) -> Result<String, String> { +pub fn render_paths( + registry: &Registry, + versions: &Versions, + existing: Option<&str>, +) -> Result<String, String> { Ok(assemble( &PATHS_PAGE, PATHS_SURFACE, &version_block(versions)?, - &paths_fields(), + &paths_fields(registry)?, &entries(&PATHS_CODES)?, existing, )) diff --git a/crates/candler/tests/it/support/contract_pages/mod.rs b/crates/candler/tests/it/support/contract_pages/mod.rs index f62bf51c..3937cf12 100644 --- a/crates/candler/tests/it/support/contract_pages/mod.rs +++ b/crates/candler/tests/it/support/contract_pages/mod.rs @@ -17,6 +17,9 @@ pub mod versions; use std::fs; use std::path::{Path, PathBuf}; +use candler_harness::spec::{AgentSetting, Answer, EffortLevel, PermissionMode}; +use candler_schemas::servers::McpServerKind; + /// The environment variable that makes the guards write the pages instead of comparing them. pub const BLESS_ENV: &str = "CANDLER_BLESS_CONTRACT"; @@ -46,3 +49,58 @@ pub fn write_atomically(path: &Path, text: &str) -> Result<(), String> { fs::write(&temporary, text).map_err(|e| format!("{}: {e}", temporary.display()))?; fs::rename(&temporary, path).map_err(|e| format!("{}: {e}", path.display())) } + +/// The words of a driver's answer, as a page writes them: the construct, the Candler action behind +/// `Candler: `, or the refusal behind `no (…)`. The one producer every per-driver cell reads. +#[must_use] +pub fn answer_words(answer: Answer) -> String { + match answer { + Answer::Mapped { construct } => construct.to_owned(), // BORROW: .to_owned() makes the owned cell text + Answer::Candler { how } => format!("Candler: {how}"), + Answer::Refused { reason } => format!("no ({reason})"), + } +} + +/// The label of the row an agent setting words. +#[must_use] +pub const fn setting_label(setting: AgentSetting) -> &'static str { + match setting { + AgentSetting::ModelId => "model id", + AgentSetting::ModelEndpoint => "model endpoint", + AgentSetting::Effort(level) => match level { + EffortLevel::Low => "model effort: low", + EffortLevel::Medium => "model effort: medium", + EffortLevel::High => "model effort: high", + EffortLevel::Xhigh => "model effort: xhigh", + EffortLevel::Max => "model effort: max", + EffortLevel::Ultracode => "model effort: ultracode", + }, + AgentSetting::PermissionMode(mode) => match mode { + PermissionMode::Default => "permission mode: default", + PermissionMode::AcceptEdits => "permission mode: acceptEdits", + PermissionMode::Plan => "permission mode: plan", + PermissionMode::BypassPermissions => "permission mode: bypassPermissions", + PermissionMode::Auto => "permission mode: auto", + PermissionMode::DontAsk => "permission mode: dontAsk", + }, + AgentSetting::ToolsAllowed => "tools allowed", + AgentSetting::ToolsDisallowed => "tools disallowed", + AgentSetting::Env => "env", + AgentSetting::Inputs => "inputs", + AgentSetting::Skills => "skills", + AgentSetting::McpTransport(kind) => match kind { + McpServerKind::Stdio => "MCP transport: stdio", + McpServerKind::Local => "MCP transport: local", + McpServerKind::Http => "MCP transport: http", + McpServerKind::Sse => "MCP transport: sse", + McpServerKind::Remote => "MCP transport: remote", + }, + AgentSetting::Codemode(true) => "MCP codemode: on", + AgentSetting::Codemode(false) => "MCP codemode: off", + AgentSetting::McpName => "MCP server name", + AgentSetting::WallBudget => "wall cap", + AgentSetting::TurnBudget => "turn cap", + AgentSetting::CostBudget => "cost cap", + AgentSetting::SessionMode => "session mode", + } +} diff --git a/crates/candler/tests/it/support/contract_pages/refusals.rs b/crates/candler/tests/it/support/contract_pages/refusals.rs index e3f68c95..13b522e0 100644 --- a/crates/candler/tests/it/support/contract_pages/refusals.rs +++ b/crates/candler/tests/it/support/contract_pages/refusals.rs @@ -22,7 +22,7 @@ pub enum Home { /// The surface of a code is the part before its dot. Every surface the catalogue and the helper's /// section hold is named here; a surface that is not named fails the guard with its name. -pub const SURFACES: [(&str, Home); 24] = [ +pub const SURFACES: [(&str, Home); 23] = [ ("plugin", Home::Page("plugin-manifest.md")), ("suite", Home::Page("suite-file.md")), ("protocol", Home::Page("evaluator-protocol.md")), @@ -38,7 +38,6 @@ pub const SURFACES: [(&str, Home); 24] = [ ("candler", Home::Index), ("analysis", Home::Index), ("cli", Home::Index), - ("catalog", Home::Index), ("config", Home::Index), ("evaluation", Home::Index), ("harness", Home::Index), diff --git a/docs/contract/codes.toml b/docs/contract/codes.toml index 6bd510ef..52f5eab0 100644 --- a/docs/contract/codes.toml +++ b/docs/contract/codes.toml @@ -65,6 +65,11 @@ side = "experiment" enum = "ExecutionError" variant = "NotPositive" +[schemas."experiment.replicates_not_count"] +side = "experiment" +enum = "ExecutionError" +variant = "ReplicatesNotCount" + [schemas."experiment.factor_without_levels"] side = "experiment" enum = "ExecutionError" @@ -395,36 +400,6 @@ side = "plugin" enum = "EvaluationError" variant = "ManifestToml" -[schemas."catalog.schema_tag_mismatch"] -side = "environment" -enum = "CatalogError" -variant = "SchemaTag" - -[schemas."catalog.field_unset"] -side = "candler" -enum = "CatalogError" -variant = "MissingField" - -[schemas."catalog.extra_key_reserved"] -side = "candler" -enum = "CatalogError" -variant = "ReservedKey" - -[schemas."catalog.field_null"] -side = "candler" -enum = "CatalogError" -variant = "Null" - -[schemas."catalog.name_empty"] -side = "environment" -enum = "CatalogError" -variant = "EmptyName" - -[schemas."catalog.name_repeated"] -side = "environment" -enum = "CatalogError" -variant = "DuplicateName" - [schemas."experiment.unknown_field"] side = "experiment" enum = "ExecutionError" @@ -541,26 +516,16 @@ side = "experiment" enum = "PlanError" variant = "StoredCellUnknown" +[runner."experiment.replicates_conflict"] +side = "experiment" +enum = "PlanError" +variant = "ReplicatesConflict" + [runner."experiment.setting_as_factor"] side = "experiment" enum = "PlanError" variant = "SettingAsFactor" -[runner."runner.catalog_command_failed"] -side = "environment" -enum = "CatalogError" -variant = "Command" - -[runner."runner.catalog_timeout"] -side = "environment" -enum = "CatalogError" -variant = "Timeout" - -[runner."runner.catalog_unreadable"] -side = "environment" -enum = "CatalogError" -variant = "Parse" - [runner."runner.census_no_init"] side = "environment" enum = "CensusError" @@ -797,6 +762,11 @@ side = "experiment" enum = "DriverError" variant = "InvalidValue" +[harness."experiment.mcp_server_prefix_ambiguous"] +side = "experiment" +enum = "DriverError" +variant = "AmbiguousServers" + [harness."harness.version_unreadable"] side = "environment" enum = "DriverError" @@ -821,6 +791,7 @@ variant = "EmptyToolName" side = "environment" enum = "InitReportError" variant = "ServersNotList" +lifted = "No harness's server list is read: the census records tools only, and a server's status stays in the harness's own raw output." [harness."harness.inventory_unrecorded"] side = "environment" @@ -1413,21 +1384,6 @@ enum = "PlanError" variant = "Lock" reason = "a lock that cannot be tried is an operating-system fault, not an input of the author" -[internal."candler_core::runner::evidence::catalog::CatalogError::Unavailable"] -enum = "CatalogError" -variant = "Unavailable" -reason = "an unwired capture port is a fault of the binary, not an input of the author" - -[internal."candler_core::runner::evidence::catalog::CatalogError::AbsolutePath"] -enum = "CatalogError" -variant = "AbsolutePath" -reason = "the catalog is captured by Candler's own command, so an absolute path is Candler's fault" - -[internal."candler_core::runner::evidence::catalog::CatalogError::Digest"] -enum = "CatalogError" -variant = "Digest" -reason = "a catalog with no canonical form is a fault of the capture, not an input of the author" - [internal."candler_core::runner::evidence::census::CensusError::Value"] enum = "CensusError" variant = "Value" @@ -1973,8 +1929,3 @@ variant = "TokenSecret" side = "experiment" enum = "ResolveError" variant = "ReplicatesPath" - -[resolve."experiment.replicates_not_integer"] -side = "experiment" -enum = "ResolveError" -variant = "ReplicatesNotInteger" diff --git a/docs/contract/configuration-paths.md b/docs/contract/configuration-paths.md index 3c466107..d95b4465 100644 --- a/docs/contract/configuration-paths.md +++ b/docs/contract/configuration-paths.md @@ -15,57 +15,56 @@ Core line: `v0.15.0`. ## Fields <!-- generated:fields --> -| Path | Names | Class | Meaning | -|---|---|---|---| -| `model.id` | the path | experiment value | The model the harness runs. | -| `model.endpoint` | the path | experiment value | The endpoint the gateway forwards model requests to. | -| `model.effort` | the path | experiment value | The effort level the harness asks of the model. | -| `model.token_secret` | the path | setting | The name of the secret that holds the gateway's token. | -| `tools.allowed` | the path | experiment value | The tools the harness may use. | -| `tools.disallowed` | the path | experiment value | The tools the harness may not use. | -| `env` | the path | experiment value | The environment of the harness process: a table of variable name to text. | -| `mcp` | the path and every path below it | experiment value | The MCP servers of a run; the names below are free. | -| `permission_mode` | the path | experiment value | The permission mode the harness runs in. | -| `request.harness` | the path | request key | The harness the run uses. | -| `request.treatment` | the path | request key | The treatment the run applies. | -| `request.inputs` | the path | request key | The inputs the run is given. | -| `prompt.template` | the path | experiment value | The prompt template. | -| `prompt.values` | the path and every path below it | experiment value | The values the prompt template fills in; the names below are free. | -| `isolation.image` | the path | experiment value | The container image a run starts in. | -| `isolation.network` | the path | experiment value | The network mode of the container. | -| `isolation.env_lock` | the path | experiment value | The environment lock the image must match. | -| `isolation.limits` | the path | experiment value | The resource limits of the container; the limits are below. | -| `isolation.limits.pids` | the path | experiment value | The process limit of the container. | -| `isolation.limits.memory` | the path | experiment value | The memory limit of the container. | -| `isolation.limits.cpus` | the path | experiment value | The CPU limit of the container. | -| `isolation.egress` | the path | experiment value | The hosts the container may reach. | -| `isolation.record_packages` | the path | setting | Whether a run records the packages of its image. | -| `isolation.build` | every path below it | setting | Every path below it is a request to build an image. | -| `isolation.build.plugin` | the path | setting | The image build plug-in. | -| `isolation.build.dockerfile` | the path | setting | The Dockerfile of an image build. | -| `isolation.build.context` | the path | setting | The build context directory of an image build. | -| `isolation.build.requirements` | the path | setting | The requirements file of an image build. | -| `isolation.build.prune` | the path | setting | Whether an image build prunes what it leaves. | -| `isolation.build.lock` | the path | setting | The lock file of an image build. | -| `budget` | the path and every path below it | setting | A job cap: every path below it, except the per-run caps. | -| `budget.per_run` | the path and every path below it, which the enclosing family does not reach | experiment value | The per-run caps are experiment values. | -| `budget.per_run.wall_s` | the path | experiment value | The wall-clock cap of one run, in seconds. | -| `budget.per_run.turns` | the path | experiment value | The turn cap of one run. | -| `budget.per_run.max_cost_usd` | the path | experiment value | The cost cap of one run, in US dollars. | -| `replicates` | the path and every path below it | setting | How many runs each cell gets. | -| `runner.mode` | the path | experiment value | `headless` or `session`. | -| `runner.idle_s` | the path | experiment value | The idle time that ends a session, in whole seconds, or `none`. | -| `harness` | the path and every path below it | experiment value | The harness table; the names below belong to the harness. | -| `treatment` | the path and every path below it | experiment value | The treatment table. | -| `inputs` | the path and every path below it | experiment value | The inputs table. | -| `snapshots` | the path and every path below it | experiment value | The snapshots table. | -| `environments` | the path and every path below it | experiment value | The environments table. | -| `treatment:` | text that is not a field path | experiment value | The prefix of a value that names a treatment source; the rest is the path. | -| `store.root` | the path | configuration key | The store root; a relative path is read from the project root. | -| `plugins.dirs` | the path | configuration key | The directories that hold plug-ins; relative paths are read from the project root. | -| `slots.count` | the path | configuration key | How many run slots the machine offers. | -| `slots.evaluators` | the path | configuration key | How many of the slots evaluators may use. | -| `gateway.upstream_ca` | text that is not a field path | configuration key | A PEM file whose certificates the gateway trusts for its upstream. | +| Path | Names | Class | Meaning | claude-code | opencode | +|---|---|---|---|---|---| +| `model.id` | the path | experiment value | The model the harness runs. | model id: `--model` on the command line | model id: `-m candler/<model>` on the command line | +| `model.endpoint` | the path | experiment value | The endpoint the gateway forwards model requests to. | model endpoint: Candler: the gateway forwards model requests to the endpoint | model endpoint: Candler: the gateway forwards model requests to the endpoint | +| `model.effort` | the path | experiment value | The effort level the harness asks of the model. | model effort: low: `--effort <level>` on the command line; model effort: medium: `--effort <level>` on the command line; model effort: high: `--effort <level>` on the command line; model effort: xhigh: `--effort <level>` on the command line; model effort: max: `--effort <level>` on the command line; model effort: ultracode: `--effort ultracode` on the command line, which Claude Code reads as `xhigh` with its ultracode mode on | model effort: low: a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model; model effort: medium: a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model; model effort: high: a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model; model effort: xhigh: a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model; model effort: max: a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model; model effort: ultracode: no (`ultracode` is `xhigh` effort with an ultracode mode on, and OpenCode has no equivalent of that mode, so it is refused rather than run as `xhigh`) | +| `model.token_secret` | the path | setting | The name of the secret that holds the gateway's token. | Candler only | Candler only | +| `tools.allowed` | the path | experiment value | The tools the harness may use. | tools allowed: `permissions.allow` of `.claude/settings.json` | tools allowed: a permission row {action, *, allow} per name, a no-op over the baseline | +| `tools.disallowed` | the path | experiment value | The tools the harness may not use. | tools disallowed: `permissions.deny` of `.claude/settings.json` | tools disallowed: a permission row {action, *, deny} per name, written after the allow rows | +| `env` | the path | experiment value | The environment of the harness process: a table of variable name to text. | env: Candler: the core sets the cell's variables on the agent's process | env: Candler: the core sets the cell's variables on the agent's process | +| `mcp` | the path and every path below it | experiment value | The MCP servers of a run; the names below are free. | MCP transport: stdio: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: local: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: http: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP transport: sse: an entry of `mcpServers` in `.mcp.json`, of type `sse`; MCP transport: remote: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP codemode: off: no key: Claude Code offers the server's tools directly; MCP codemode: on: no (Claude Code offers MCP tools directly; it has no code mode); MCP server name: the key of the server's `.mcp.json` entry | MCP transport: stdio: an `mcp` entry of type `local`; MCP transport: local: an `mcp` entry of type `local`; MCP transport: http: an `mcp` entry of type `remote`; MCP transport: sse: no (OpenCode documents no SSE transport; its `remote` is Streamable HTTP); MCP transport: remote: an `mcp` entry of type `remote`; MCP codemode: off: the `codemode` key of the `mcp` entry, `false`: the server's tools are direct tools; MCP codemode: on: the `codemode` key of the `mcp` entry, `true`: the server's tools are reached through `execute`, whose calls the trace records with empty `wrapped_calls`, so MCP calls made inside `execute` are not attributed and do not compare with Claude Code; MCP server name: the key of the `mcp` entry | +| `permission_mode` | the path | experiment value | The permission mode the harness runs in. | permission mode: default: `--permission-mode <mode>` on the command line; permission mode: acceptEdits: `--permission-mode <mode>` on the command line; permission mode: plan: `--permission-mode <mode>` on the command line; permission mode: bypassPermissions: `--permission-mode <mode>` on the command line; permission mode: auto: `--permission-mode <mode>` on the command line; permission mode: dontAsk: `--permission-mode <mode>` on the command line | permission mode: default: no (Claude Code's default mode allows reads and a built-in, non-configurable set of read-only shell commands that its own parser decides, and denies the rest in a headless run. OpenCode without `--auto` also rejects what no rule allows, but its shell rows are wildcards on the text of each parsed command, which approximate that set without being it); permission mode: acceptEdits: no (Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, rm, rmdir, mv, cp and sed, inside the working directory only. OpenCode's shell resource is the command's text, which knows no working directory, so "inside it" cannot be written as a rule); permission mode: plan: no (Claude Code's plan mode reads and runs read-only shell commands (a built-in, non-configurable set its own parser decides). The OpenCode ruleset that is certainly read-only (the `explore` agent's: deny everything, allow read, glob, grep, webfetch, websearch, skill) denies the shell altogether, and a wildcard on command text cannot express the read-only set; the stock `plan` agent is not read-only once a global rule follows it (the last match wins) and its `subagent` child can edit); permission mode: bypassPermissions: `--auto` on the command line: every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` answers the one pending ask (`.env` reads) with once, which a headless run needs; permission mode: auto: no (Claude Code's auto mode has a model classifier review each action, such as a shell command or a network request, before it runs. OpenCode has no classifier, and a ruleset decides by the action's text alone); permission mode: dontAsk: no (Claude Code's dontAsk mode denies every call that would prompt, so it allows the allow rules plus reads and the built-in, non-configurable set of read-only shell commands its own parser decides. OpenCode's shell rows are wildcards on the text of each parsed command, which approximate that set without being it) | +| `request.harness` | the path | request key | The harness the run uses. | Candler only | Candler only | +| `request.treatment` | the path | request key | The treatment the run applies. | Candler only | Candler only | +| `request.inputs` | the path | request key | The inputs the run is given. | Candler only | Candler only | +| `prompt.template` | the path | experiment value | The prompt template. | Candler only | Candler only | +| `prompt.values` | the path and every path below it | experiment value | The values the prompt template fills in; the names below are free. | Candler only | Candler only | +| `isolation.image` | the path | experiment value | The container image a run starts in. | Candler only | Candler only | +| `isolation.network` | the path | experiment value | The network mode of the container. | Candler only | Candler only | +| `isolation.env_lock` | the path | experiment value | The environment lock the image must match. | Candler only | Candler only | +| `isolation.limits` | the path | experiment value | The resource limits of the container; the limits are below. | Candler only | Candler only | +| `isolation.limits.pids` | the path | experiment value | The process limit of the container. | Candler only | Candler only | +| `isolation.limits.memory` | the path | experiment value | The memory limit of the container. | Candler only | Candler only | +| `isolation.limits.cpus` | the path | experiment value | The CPU limit of the container. | Candler only | Candler only | +| `isolation.egress` | the path | experiment value | The hosts the container may reach. | Candler only | Candler only | +| `isolation.record_packages` | the path | setting | Whether a run records the packages of its image. | Candler only | Candler only | +| `isolation.build` | every path below it | setting | Every path below it is a request to build an image. | Candler only | Candler only | +| `isolation.build.plugin` | the path | setting | The image build plug-in. | Candler only | Candler only | +| `isolation.build.dockerfile` | the path | setting | The Dockerfile of an image build. | Candler only | Candler only | +| `isolation.build.context` | the path | setting | The build context directory of an image build. | Candler only | Candler only | +| `isolation.build.requirements` | the path | setting | The requirements file of an image build. | Candler only | Candler only | +| `isolation.build.prune` | the path | setting | Whether an image build prunes what it leaves. | Candler only | Candler only | +| `isolation.build.lock` | the path | setting | The lock file of an image build. | Candler only | Candler only | +| `budget` | the path and every path below it | setting | A job cap: every path below it, except the per-run caps. | Candler only | Candler only | +| `budget.per_run` | the path and every path below it, which the enclosing family does not reach | experiment value | The per-run caps are experiment values. | Candler only | Candler only | +| `budget.per_run.wall_s` | the path | experiment value | The wall-clock cap of one run, in seconds. | wall cap: Candler: the core ends the run at the wall budget | wall cap: Candler: the core ends the run at the wall budget | +| `budget.per_run.turns` | the path | experiment value | The turn cap of one run. | turn cap: `--max-turns` on the command line | turn cap: no (`agents.<id>.steps` makes the last request a tool-less one with an injected prompt and ends the run as completed (the `oc_step_cap` fixture), where Claude Code ends the run with `error_max_turns`, so the cap class would be lost and the model's last turn changed) | +| `budget.per_run.max_cost_usd` | the path | experiment value | The cost cap of one run, in US dollars. | cost cap: `--max-budget-usd` on the command line | cost cap: no (OpenCode has no cost cap) | +| `replicates` | the path and every path below it | setting | How many runs each cell gets. | Candler only | Candler only | +| `runner.mode` | the path | experiment value | `headless` or `session`. | session mode: stream-json over an open stdin, one turn per message | session mode: no (OpenCode runs no session: its trace comes from the export after the run) | +| `runner.idle_s` | the path | experiment value | The idle time that ends a session, in whole seconds, or `none`. | Candler only | Candler only | +| `harness` | the path and every path below it | experiment value | The harness table; the names below belong to the harness. | Candler only | Candler only | +| `treatment` | the path and every path below it | experiment value | The treatment table. | Candler only | Candler only | +| `inputs` | the path and every path below it | experiment value | The inputs table. | inputs: Candler: the core places the inputs in the workspace | inputs: Candler: the core places the inputs in the workspace | +| `environments` | the path and every path below it | experiment value | The environments table. | Candler only | Candler only | +| `treatment:` | text that is not a field path | experiment value | The prefix of a value that names a treatment source; the rest is the path. | Candler only | Candler only | +| `store.root` | the path | configuration key | The store root; a relative path is read from the project root. | Candler only | Candler only | +| `plugins.dirs` | the path | configuration key | The directories that hold plug-ins; relative paths are read from the project root. | Candler only | Candler only | +| `slots.count` | the path | configuration key | How many run slots the machine offers. | Candler only | Candler only | +| `slots.evaluators` | the path | configuration key | How many of the slots evaluators may use. | Candler only | Candler only | +| `gateway.upstream_ca` | text that is not a field path | configuration key | A PEM file whose certificates the gateway trusts for its upstream. | Candler only | Candler only | <!-- /generated:fields --> ## Refusals diff --git a/docs/contract/driver-traits.md b/docs/contract/driver-traits.md index 01ca8034..66924617 100644 --- a/docs/contract/driver-traits.md +++ b/docs/contract/driver-traits.md @@ -23,9 +23,9 @@ Core line: `v0.15.0`; the `candler-harness` crate has the same version. | `HarnessDriver::supported` | `(&self) -> semver::VersionReq` | required | - | | `HarnessDriver::version_probe` | `(&self) -> CommandSpec` | required | - | | `HarnessDriver::parse_version` | `(&self, output: &[u8]) -> Result<semver::Version, DriverError>` | required | - | -| `HarnessDriver::capabilities` | `(&self) -> Capabilities` | required | - | +| `HarnessDriver::answer` | `(&self, setting: AgentSetting) -> Answer` | required | - | +| `HarnessDriver::fact` | `(&self, fact: DriverFact) -> Answer` | required | - | | `HarnessDriver::plan` | `(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result<Plan, DriverError>` | required | - | -| `HarnessDriver::settings_table` | `(&self) -> Vec<SettingRow>` | optional | `Vec::new()` | | `HarnessDriver::check_settings` | `(&self, cell: &Cell<'_>) -> Result<(), DriverError>` | optional | `Ok(())` | | `HarnessDriver::gateway` | `(&self) -> Option<GatewayEnv>` | optional | `None` | | `HarnessDriver::state_paths` | `(&self) -> Vec<StatePath>` | optional | `Vec::new()` | @@ -37,7 +37,7 @@ Core line: `v0.15.0`; the `candler-harness` crate has the same version. | `HarnessDriver::session_tracker` | `(&self) -> Option<Box<dyn SessionTracker>>` | optional | `None` | | `HarnessDriver::stop` | `(&self) -> StopSpec` | required | - | | `HarnessDriver::live_reader` | `(&self) -> Option<Box<dyn TraceReader>>` | required | - | -| `HarnessDriver::offline_reader` | `(&self, stream: &StreamName) -> Option<Box<dyn TraceReader>>` | required | - | +| `HarnessDriver::offline_reader` | `(&self, stream: &StreamName, servers: &[String]) -> Option<Box<dyn TraceReader>>` | required | - | | `HarnessDriver::classify_exit` | `(&self, exit: &ProcessExit, sessions: &[Session]) -> EndedBy` | required | - | | `HarnessDriver::classify_end` | `(&self, exit: &ProcessExit, sessions: &[Session], observed: &Observed) -> EndedBy` | optional | `self.classify_exit(exit, sessions)` | | `HarnessDriver::collect` | `(&self, workspace: &Workspace<'_>, observed: &Observed) -> Vec<CollectSpec>` | required | - | @@ -60,8 +60,9 @@ Core line: `v0.15.0`; the `candler-harness` crate has the same version. <!-- generated:refusals --> | Code | When | Path at fault | Side to fix | |---|---|---|---| -| `experiment.cell_value_invalid` | A cell value cannot be used by the harness driver. | - | experiment | +| `experiment.cell_value_invalid` | A cell value cannot be used by the harness driver. | The field of the value, such as `/mcp/servers/fs/command`. | experiment | | `experiment.cell_value_missing` | A cell lacks a value that the harness driver needs. | - | experiment | +| `experiment.mcp_server_prefix_ambiguous` | Two MCP servers of a cell have names that make one tool name read two ways: the name of one, then `_`, is a prefix of the other's name, so a tool of the longer-named server cannot be told from a tool of the shorter-named one. | The table of servers, `/mcp/servers`. | experiment | | `experiment.setting_unsupported` | The experiment sets a setting that the harness has no way to honour, such as a turn cap for a harness with no turn limit; the run is refused rather than the setting dropped. | The setting in the experiment file: a field under `/budget`, or the key of `[fixed]` that holds it, such as `/fixed/model.effort`. | experiment | | `harness.session_record_unreadable` | A session record that the harness wrote, such as a hook payload or a stream event, cannot be read by the driver's tracker. | - | environment | | `harness.version_unreadable` | The output of the harness version probe names no version. | - | environment | @@ -72,4 +73,4 @@ Core line: `v0.15.0`; the `candler-harness` crate has the same version. - Drivers never act on a process: they return commands, specs and readers, and the core runs them. [checked: v@0.7.0] - A reader is synchronous and holds no clock; the core supplies each frame's place and wall time. [checked: v@0.7.0] - `census_stream()` names the raw stream the gateway's census is stored under; the core reads the gateway census itself and reports it as the inventory. [checked: v@0.7.0] -- A driver that sets `Capabilities::session` also gives its `plan` a `session` and returns a `session_tracker`. [checked: v@0.7.0] +- A driver that does not refuse `AgentSetting::SessionMode` also gives its `plan` a `session` and returns a `session_tracker`. [checked: v@0.7.0] diff --git a/docs/contract/evaluator-protocol.md b/docs/contract/evaluator-protocol.md index 8e617fd3..1fda8044 100644 --- a/docs/contract/evaluator-protocol.md +++ b/docs/contract/evaluator-protocol.md @@ -509,3 +509,4 @@ Wire line: `schemas@0.12.0`. - A request with a valid `id` and a method other than `describe` or `evaluate` is answered with error -32601; `evaluate` params that break the schema, with error -32602. [checked: candler-evaluator@0.1.0] - An `evaluate` request ends with the result `{"reported": n}`, after its `n` outcome notifications. [checked: candler-evaluator@0.1.0] - Candler does not compare protocol versions: any `describe` protocol is accepted. [checked: v@0.6.0] +- Each output keeps its execute bit; its copy at `context.artifacts[].abs` is read-only, `0555` for an executable and `0444` otherwise. [checked: schemas@0.12.0] diff --git a/docs/contract/experiment-file.md b/docs/contract/experiment-file.md index 8f14b49e..f3333263 100644 --- a/docs/contract/experiment-file.md +++ b/docs/contract/experiment-file.md @@ -64,7 +64,7 @@ Wire line: `schemas@0.12.0`. | `canonical.number_not_finite` | A number is not finite. | - | experiment | | `canonical.syntax_invalid` | A text is not valid JSON. | - | experiment | | `experiment.absolute_path` | A value holds an absolute path as a string, and a file enters a cell as an input digest. | - | experiment | -| `experiment.cell_value_invalid` | A cell value cannot be used by the harness driver. | - | experiment | +| `experiment.cell_value_invalid` | A cell value cannot be used by the harness driver. | The field of the value, such as `/mcp/servers/fs/command`. | experiment | | `experiment.cell_value_missing` | A cell lacks a value that the harness driver needs. | - | experiment | | `experiment.cost_not_positive` | A cost cap is not a finite number above 0. | - | experiment | | `experiment.count_zero` | A count, duration or process id that must be at least 1 is 0. | The field when it is `replicates` or one under `budget`; none otherwise. | experiment | @@ -79,9 +79,11 @@ Wire line: `schemas@0.12.0`. | `experiment.input_invalid` | An input declaration uses the kind the wire reserves, or mounts under an empty, absolute or escaping directory. | `/inputs`, the list that holds the declaration. | experiment | | `experiment.input_not_stored` | A declared input file or list could not be copied into the store. | The `inputs` array of the experiment file. | experiment | | `experiment.input_unusable` | A declared input cannot be used as written, for example a missing file or a directory where a file is needed. | The `inputs` array of the experiment file. | experiment | +| `experiment.mcp_server_prefix_ambiguous` | Two MCP servers of a cell have names that make one tool name read two ways: the name of one, then `_`, is a prefix of the other's name, so a tool of the longer-named server cannot be told from a tool of the shorter-named one. | The table of servers, `/mcp/servers`. | experiment | | `experiment.name_collision` | Two names under one root map to the same deviation path, so a deviation there would be ambiguous. | - | experiment | | `experiment.path_overlap` | Two paths set by the fixed values and the factors are the same, or one lies below the other. | - | experiment | -| `experiment.replicates_not_integer` | `replicates` in `[fixed]` or in a `--set` is not a whole number, such as a string or a fraction. | The `replicates` key. | experiment | +| `experiment.replicates_conflict` | `replicates` in `[fixed]` differs from the experiment file's own `replicates`; write the count once. | The `replicates` key. | experiment | +| `experiment.replicates_not_count` | `replicates` is not a whole number from 1 to 4294967295, such as a negative number, a fraction, a count beyond 32 bits or a string. | The `replicates` key. | experiment | | `experiment.replicates_path` | A `[fixed]` key or a `--set` names a path below `replicates`; `replicates` is one count and has no fields. | The path that was written. | experiment | | `experiment.reserved_root_misused` | A value at a reserved root is not the root alone, or has no value. | - | experiment | | `experiment.reserved_value_malformed` | The value of a reserved root is not the shape the root takes. | - | experiment | @@ -112,7 +114,8 @@ Wire line: `schemas@0.12.0`. ## Notes - The document has no `free` fields. An unknown key outside `[fixed]` and the `levels` of a factor is `experiment.unknown_field`; a key under `[fixed]` or in a level table that is no setting path is `experiment.unknown_path`. [checked: v@0.7.0] -- A TOML date or time among the values is refused with `experiment.value_unrepresentable`. [checked: v@0.7.0] -- A name, secret name or `schema` marker of the wrong form, an integer out of range and a value that breaks its field's format print `experiment.document_invalid`, never `format.*`. Any other value-invalid file prints its own code, such as `experiment.factor_without_levels` or `experiment.path_overlap`. [checked: v@0.13.0] -- `canonical.integer_out_of_range` and `values.null` print only for a value given with `--set`. [checked: v@0.7.0] +- A TOML date or time is refused with `experiment.value_unrepresentable`. [checked: v@0.7.0] +- A name, secret name or `schema` marker of the wrong form, an integer out of range and a value that breaks its field's format print `experiment.document_invalid`, never `format.*`. Any other value-invalid file prints its own code. [checked: v@0.13.0] +- `canonical.integer_out_of_range` and `values.null` print only with `--set`. [checked: v@0.7.0] - `mcp.servers.<key>.name` names a server (default the key); a driver refuses a name with `__` or one two servers share. [checked: v@0.7.0] +- `experiment.schema.json` does not check the entries of `mcp.servers`; `mcp-server.schema.json` checks one entry. [checked: schemas@0.12.0] diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index fee714e6..3057f605 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -17,14 +17,45 @@ Core line: `v0.15.0`; the `candler-harness` crate has the same version. <!-- generated:fields --> | Capability | `claude-code` | `opencode` | |---|---|---| +| model id | `--model` on the command line | `-m candler/<model>` on the command line | +| model endpoint | Candler: the gateway forwards model requests to the endpoint | Candler: the gateway forwards model requests to the endpoint | +| model effort: low | `--effort <level>` on the command line | a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model | +| model effort: medium | `--effort <level>` on the command line | a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model | +| model effort: high | `--effort <level>` on the command line | a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model | +| model effort: xhigh | `--effort <level>` on the command line | a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model | +| model effort: max | `--effort <level>` on the command line | a `variants` entry on the model, selected by `-m <model>#<level>`, for a Claude opus, sonnet, fable or mythos of 4.6 or later (`xhigh` from 4.7); refused for any other model | +| model effort: ultracode | `--effort ultracode` on the command line, which Claude Code reads as `xhigh` with its ultracode mode on | no (`ultracode` is `xhigh` effort with an ultracode mode on, and OpenCode has no equivalent of that mode, so it is refused rather than run as `xhigh`) | +| permission mode: default | `--permission-mode <mode>` on the command line | no (Claude Code's default mode allows reads and a built-in, non-configurable set of read-only shell commands that its own parser decides, and denies the rest in a headless run. OpenCode without `--auto` also rejects what no rule allows, but its shell rows are wildcards on the text of each parsed command, which approximate that set without being it) | +| permission mode: acceptEdits | `--permission-mode <mode>` on the command line | no (Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, rm, rmdir, mv, cp and sed, inside the working directory only. OpenCode's shell resource is the command's text, which knows no working directory, so "inside it" cannot be written as a rule) | +| permission mode: plan | `--permission-mode <mode>` on the command line | no (Claude Code's plan mode reads and runs read-only shell commands (a built-in, non-configurable set its own parser decides). The OpenCode ruleset that is certainly read-only (the `explore` agent's: deny everything, allow read, glob, grep, webfetch, websearch, skill) denies the shell altogether, and a wildcard on command text cannot express the read-only set; the stock `plan` agent is not read-only once a global rule follows it (the last match wins) and its `subagent` child can edit) | +| permission mode: bypassPermissions | `--permission-mode <mode>` on the command line | `--auto` on the command line: every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` answers the one pending ask (`.env` reads) with once, which a headless run needs | +| permission mode: auto | `--permission-mode <mode>` on the command line | no (Claude Code's auto mode has a model classifier review each action, such as a shell command or a network request, before it runs. OpenCode has no classifier, and a ruleset decides by the action's text alone) | +| permission mode: dontAsk | `--permission-mode <mode>` on the command line | no (Claude Code's dontAsk mode denies every call that would prompt, so it allows the allow rules plus reads and the built-in, non-configurable set of read-only shell commands its own parser decides. OpenCode's shell rows are wildcards on the text of each parsed command, which approximate that set without being it) | +| tools allowed | `permissions.allow` of `.claude/settings.json` | a permission row {action, *, allow} per name, a no-op over the baseline | +| tools disallowed | `permissions.deny` of `.claude/settings.json` | a permission row {action, *, deny} per name, written after the allow rows | +| env | Candler: the core sets the cell's variables on the agent's process | Candler: the core sets the cell's variables on the agent's process | +| inputs | Candler: the core places the inputs in the workspace | Candler: the core places the inputs in the workspace | +| skills | the project skill directory | the project skill directory | +| MCP transport: stdio | an entry of `mcpServers` in `.mcp.json`, of type `stdio` | an `mcp` entry of type `local` | +| MCP transport: local | an entry of `mcpServers` in `.mcp.json`, of type `stdio` | an `mcp` entry of type `local` | +| MCP transport: http | an entry of `mcpServers` in `.mcp.json`, of type `http` | an `mcp` entry of type `remote` | +| MCP transport: sse | an entry of `mcpServers` in `.mcp.json`, of type `sse` | no (OpenCode documents no SSE transport; its `remote` is Streamable HTTP) | +| MCP transport: remote | an entry of `mcpServers` in `.mcp.json`, of type `http` | an `mcp` entry of type `remote` | +| MCP codemode: off | no key: Claude Code offers the server's tools directly | the `codemode` key of the `mcp` entry, `false`: the server's tools are direct tools | +| MCP codemode: on | no (Claude Code offers MCP tools directly; it has no code mode) | the `codemode` key of the `mcp` entry, `true`: the server's tools are reached through `execute`, whose calls the trace records with empty `wrapped_calls`, so MCP calls made inside `execute` are not attributed and do not compare with Claude Code | +| MCP server name | the key of the server's `.mcp.json` entry | the key of the `mcp` entry | +| wall cap | Candler: the core ends the run at the wall budget | Candler: the core ends the run at the wall budget | +| turn cap | `--max-turns` on the command line | no (`agents.<id>.steps` makes the last request a tool-less one with an injected prompt and ends the run as completed (the `oc_step_cap` fixture), where Claude Code ends the run with `error_max_turns`, so the cap class would be lost and the model's last turn changed) | +| cost cap | `--max-budget-usd` on the command line | no (OpenCode has no cost cap) | +| session mode | stream-json over an open stdin, one turn per message | no (OpenCode runs no session: its trace comes from the export after the run) | | gateway route | Candler: gateway, address in `ANTHROPIC_BASE_URL` | Candler: gateway, address in `CANDLER_GATEWAY_URL` | -| census source | yes | Candler: gateway, first request with tools | -| session mode | yes | no (refused) | -| turn cap | yes | no (refused) | -| cost cap | yes | no (refused) | -| stop | yes | Candler: interrupt command in the container, then SIGTERM | | authoritative trace | yes | Candler: collects `export` after the run | -| skills layout | yes | Candler: places the tree at `.opencode/skills/<name>` | +| graceful stop | SIGTERM ends the sessions cleanly | an interrupt request to the `serve` child, then SIGTERM to the client | +| live events | stream-json events on stdout while the run lasts | no (the live reader emits no event: the trace comes from the export) | +| in-harness guard | no (the driver configures no Claude Code hook) | no (the driver configures no OpenCode guard) | +| execution outside the child | no (tools run in the child process) | tools run in the `serve` child, which the stop interrupts first | +| census source | Claude Code's `system/init` event lists the tools | Candler: the tools the gateway offered the model in its first request | +| permission mode when none is set | `--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it | Candler: the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode | <!-- /generated:fields --> ## Refusals @@ -38,6 +69,6 @@ Core line: `v0.15.0`; the `candler-harness` crate has the same version. ## Notes -- `no (refused)` is a refusal with a code: `experiment.session_refused` while resolving, `experiment.setting_unsupported` when the cells are planned, before a job starts. [checked: v@0.7.0] +- `no (…)` is a refusal: `experiment.session_refused` while resolving, `experiment.setting_unsupported` when the cells are planned, before a job starts. [checked: v@0.15.0] - In session mode Candler also counts turns across the session and ends the run when they exceed `budget.per_run.turns`. [checked: v@0.7.0] -- The settings a driver maps or refuses, such as permission modes, effort levels and tool names, are rows of its `settings_table()`. [checked: v@0.7.0] +- The settings a driver maps or refuses, such as permission modes, effort levels and tool names, are the answers its driver gives for each `AgentSetting`. [checked: v@0.7.0] diff --git a/docs/contract/index.md b/docs/contract/index.md index 7a0cf22c..6698bc34 100644 --- a/docs/contract/index.md +++ b/docs/contract/index.md @@ -65,9 +65,6 @@ Surfaces that name no page of their own: configuration, resolving, running, isol | `analysis.no_outcomes` | The store holds no outcome record, so there is nothing to analyse; run `evaluate` first. | - | environment | | `analysis.no_stored_trace` | The run given to `inspect --transcript` has no stored normalised trace, or the target is a job, which holds none. | - | config | | `analysis.unknown_evaluator` | The evaluator, or the version, named has no outcome in the store. | - | config | -| `catalog.name_empty` | A server or tool name in the catalog an image prints is empty. | - | environment | -| `catalog.name_repeated` | A server or tool name in the catalog an image prints is repeated within its scope. | - | environment | -| `catalog.schema_tag_mismatch` | The tool catalog an image prints carries another `schema` marker than `tool-catalog-snapshot/1`. | `/schema` | environment | | `cli.usage_invalid` | The command line is not one the parser accepts: an unknown option, a missing argument, or a value such as a `--set` without `=`. | - | config | | `config.ambiguous_run` | More than one run of the store has a key that starts with the prefix given to `inspect`. | - | config | | `config.cwd_not_absolute` | The working directory is not an absolute path, so no ancestor can be searched for a configuration. | - | config | @@ -78,7 +75,7 @@ Surfaces that name no page of their own: configuration, resolving, running, isol | `config.import_rule_invalid` | A rule of the import rules is not valid. | - | config | | `config.import_rules_invalid` | The import rules file given to `ingest --rules` is not the rules format: it is not TOML, a field is missing, or a field is not one the format has. | - | config | | `config.inspect_target_invalid` | The target given to `inspect` is none of a run directory, a prefix of a run key of at least 6 characters, or a job id. | - | config | -| `config.kill_not_confirmed` | `kill` asked for a confirmation and was not answered `y` or `yes`; `-y` skips the question. | - | config | +| `config.kill_not_confirmed` | `kill` stopped nothing because it was not confirmed: stdin is not a terminal, or the question was not answered `y` or `yes`; `-y` confirms, and `candler ps` lists the jobs that would be stopped. | - | config | | `config.machine_wide_key` | A project configuration sets a machine-wide key, which only the user configuration may set. | The key in the project configuration file named in the message. | config | | `config.no_evaluator_slots` | `slots.evaluators` is 0 in the user configuration, so the pool that evaluators draw from has no slot. | - | config | | `config.no_plugin_dirs` | `evaluate` is run where no `candler.toml` at or above the working directory lists a plug-in directory under `plugins.dirs`. | - | config | @@ -113,7 +110,7 @@ Surfaces that name no page of their own: configuration, resolving, running, isol | `harness.inventory_empty_name` | The tool inventory a harness or the gateway observed holds an empty tool name. | - | environment | | `harness.inventory_malformed` | The tool inventory a harness or the gateway observed is not a list of names. | - | environment | | `harness.inventory_unrecorded` | A gateway or collected census source saw no tool, so the inventory is unrecorded rather than empty. | - | environment | -| `harness.server_list_malformed` | The MCP server list a harness observed is not a list. | - | environment | +| `harness.server_list_malformed` | Lifted, no refusal emits it: No harness's server list is read: the census records tools only, and a server's status stays in the harness's own raw output. | - | environment | | `harness.session_record_unreadable` | A session record that the harness wrote, such as a hook payload or a stream event, cannot be read by the driver's tracker. | - | environment | | `harness.version_unreadable` | The output of the harness version probe names no version. | - | environment | | `import.file_unreadable` | A file or directory of the legacy results folder cannot be read. | - | environment | @@ -195,9 +192,6 @@ Surfaces that name no page of their own: configuration, resolving, running, isol | `resolve.preflight_failed` | At least one preflight step failed; every step ran and the message lists the failures. | - | environment | | `resolve.preflight_step_failed` | A preflight step failed before it could report, for example a missing directory or program. | - | environment | | `resolve.value_invalid` | A value of the resolution has the wrong form for what it names, such as a name with a space. | - | config | -| `runner.catalog_command_failed` | The command that prints the tool catalog exited non-zero or was ended by a signal. | - | environment | -| `runner.catalog_timeout` | The command that prints the tool catalog overran its time. | - | environment | -| `runner.catalog_unreadable` | The output of the catalog command is not a tool catalog. | - | environment | | `runner.census_malformed` | The tool inventory lacks a list the census needs, or the list holds an entry of the wrong kind. | - | environment | | `runner.census_no_init` | The harness reported no tool inventory, so it did not run usably. | - | environment | | `runner.experiment_locked` | Another supervisor holds the experiment, or a job that owns an unfinished attempt is alive. | - | environment | diff --git a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_describe_result.py b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_describe_result.py index 445206cc..14143aee 100644 --- a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_describe_result.py +++ b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_describe_result.py @@ -1,6 +1,6 @@ # Generated by scripts/gen_models.py; do not edit. # schema: crates/candler-schemas/schema/evaluator-describe-result.schema.json -# sha256: 944c2b2a1603e7e0d340c4914553db596ee1a5d289c1440dcdb1364f3748c7ad +# sha256: 0e839d32e2e777f818b2f4641e89cb75e4541b0ddc9124592bbb2882b8122829 from __future__ import annotations @@ -103,7 +103,10 @@ class Needs(BaseModel): Field(description="The paths of the metadata fields the check reads."), ] snapshots: Annotated[ - list[Name], Field(description="The kinds of snapshot the check reads.") + list[Name], + Field( + description="The kinds of snapshot the check reads. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released." + ), ] trace: Annotated[ bool, Field(description="Whether the check reads the normalised trace.") diff --git a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_evaluate_params.py b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_evaluate_params.py index 5f951d0b..93968be2 100644 --- a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_evaluate_params.py +++ b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_evaluate_params.py @@ -1,6 +1,6 @@ # Generated by scripts/gen_models.py; do not edit. # schema: crates/candler-schemas/schema/evaluator-evaluate-params.schema.json -# sha256: 74741ff467b74fe48ec1e457317de2866959f8820da61c8a74046a43100a82cd +# sha256: ecc2ca822aec9e321b7acc64ccca9c5598c7decba42595875d939126dfabaca4 from __future__ import annotations @@ -592,7 +592,10 @@ class RunContext(BaseModel): ] run: Annotated[RunKey, Field(description="The key of the run.")] snapshots: Annotated[ - list[ContextRef], Field(description="The snapshots the run was made against.") + list[ContextRef], + Field( + description="The snapshots the run was made against. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released." + ), ] trace: Annotated[ str | None, diff --git a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_message.py b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_message.py index 0f4de727..f7da0485 100644 --- a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_message.py +++ b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_message.py @@ -1,6 +1,6 @@ # Generated by scripts/gen_models.py; do not edit. # schema: crates/candler-schemas/schema/evaluator-message.schema.json -# sha256: 53f9174db72fdd0dd28796f8b124acdbb3d19aeafd165f41f2f414e9420304a5 +# sha256: 068864918640e9ca9e683cb70df83141236e53b60454ee375ba64bc0b340684c from __future__ import annotations @@ -177,7 +177,10 @@ class Needs(BaseModel): Field(description="The paths of the metadata fields the check reads."), ] snapshots: Annotated[ - list[Name], Field(description="The kinds of snapshot the check reads.") + list[Name], + Field( + description="The kinds of snapshot the check reads. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released." + ), ] trace: Annotated[ bool, Field(description="Whether the check reads the normalised trace.") @@ -805,7 +808,10 @@ class RunContext(BaseModel): ] run: Annotated[RunKey, Field(description="The key of the run.")] snapshots: Annotated[ - list[ContextRef], Field(description="The snapshots the run was made against.") + list[ContextRef], + Field( + description="The snapshots the run was made against. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released." + ), ] trace: Annotated[ str | None, diff --git a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_request_side.py b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_request_side.py index acf1bea2..3ae1fbc5 100644 --- a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_request_side.py +++ b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_request_side.py @@ -1,6 +1,6 @@ # Generated by scripts/gen_models.py; do not edit. # schema: crates/candler-schemas/schema/evaluator-request-side.schema.json -# sha256: 1ed95c08d0b1c1aab3d8affbd7db773d21925d4d5046985ca91c4c770b137729 +# sha256: 0f621f5ddac76a745cc1a3946d9a7d55b90e638f93f9ec13a7694771f70b3501 from __future__ import annotations @@ -631,7 +631,10 @@ class RunContext(BaseModel): ] run: Annotated[RunKey, Field(description="The key of the run.")] snapshots: Annotated[ - list[ContextRef], Field(description="The snapshots the run was made against.") + list[ContextRef], + Field( + description="The snapshots the run was made against. Always empty for a run Candler made; the field is\nkept so a released helper and stored grading contexts stay valid, and it is removed once a\nhelper that treats it as optional is released." + ), ] trace: Annotated[ str | None, diff --git a/python/candler-evaluator/src/candler_evaluator/plugin.py b/python/candler-evaluator/src/candler_evaluator/plugin.py index a6e93af2..1225bc09 100644 --- a/python/candler-evaluator/src/candler_evaluator/plugin.py +++ b/python/candler-evaluator/src/candler_evaluator/plugin.py @@ -116,7 +116,7 @@ def from_wire(cls, context: Mapping[str, Any], scratch: str) -> RunContext: raw=tuple(context["raw"]), trace=None if trace is None else Path(trace), artifact_files=files, - snapshots=tuple(context["snapshots"]), + snapshots=tuple(context.get("snapshots", [])), inputs=tuple(context["inputs"]), ) diff --git a/python/candler-evaluator/tests/test_guard_context.py b/python/candler-evaluator/tests/test_guard_context.py new file mode 100644 index 00000000..105e8dd2 --- /dev/null +++ b/python/candler-evaluator/tests/test_guard_context.py @@ -0,0 +1,31 @@ +from candler_evaluator.plugin import RunContext + +CELL = "sha256:" + "ab" * 32 + + +def wire_context(): + return { + "run": {"cell": CELL, "replicate": 1, "attempt": 1}, + "root": "/runs/r1", + "raw": [], + "artifacts": [], + "inputs": [], + "metadata": {}, + } + + +def test_a_context_without_snapshots_is_accepted(): + """Guards: the helper reads `snapshots` as optional, so a context that omits the key builds. + + Oracle: the context is written by hand with every member of the wire but `snapshots`. + Bite: read `context["snapshots"]` again and this raises KeyError. + """ + context = RunContext.from_wire(wire_context(), "/scratch") + assert context.snapshots == () + + +def test_a_context_with_snapshots_keeps_them(): + wire = wire_context() + wire["snapshots"] = [{"kind": "catalog", "path": "/s/c", "digest": CELL}] + context = RunContext.from_wire(wire, "/scratch") + assert [entry["kind"] for entry in context.snapshots] == ["catalog"]