From 90d0c4ca01c0818df25239500e6e998e4724944e Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:05:01 +0900 Subject: [PATCH 01/93] reports(evaluation): record the approved run context plan A kind can be handed a sealed run's artifacts but not its trace, raw streams or manifest, and needs.trace is silently ignored. The plan serves each part on declaration, adds a typed exit status to shell tool results, and names the guards, the probe and their bites. Co-Authored-By: Claude Opus 5.5 --- .../run-context/00-plan_run_context_v0.md | 300 ++++++++++++++++++ 1 file changed, 300 insertions(+) create mode 100644 __reports__/run-context/00-plan_run_context_v0.md diff --git a/__reports__/run-context/00-plan_run_context_v0.md b/__reports__/run-context/00-plan_run_context_v0.md new file mode 100644 index 00000000..bc73fff4 --- /dev/null +++ b/__reports__/run-context/00-plan_run_context_v0.md @@ -0,0 +1,300 @@ +# Plan: the evaluator run context carries what a sealed run stored (v0, approved 2026-11-25) + +## Context + +The README's purpose paragraph is the yardstick, quoted verbatim: + +> 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 census, provenance). +> - **Evaluation:** grade traces and artifacts, fresh or already on disk, through pluggable +> evaluators that emit one outcome record format. + +Today an evaluator can only be handed the artifacts half of "grade traces and artifacts". The wire +already has `context.trace` and `context.raw[]`, and `needs.trace` is a declared field, but +`assemble` never fills them and silently ignores `needs.trace = true` +(`crates/candler-core/src/evaluation/context/assemble.rs`, doc line 99; ruling +`__reports__/m2a-evaluation-parity/l1/00-rulings_v0.md:75`). AGENTS.md calls that silent, more +lenient reading a defect. + +"Sealed" means complete and protected from overwrite, nothing more: `RunWriter::done` writes +`run.done` last and "nothing in the run directory changes afterwards" +(`crates/candler-core/src/store/run.rs:239`), a finished run is refused by `RunWriter::create` and +by `seal_interrupted`, and evaluation reads only sealed runs so it never sees a half-written one. +The seal hides nothing from readers. Because a sealed run never changes, a digest taken at assembly +holds for the whole evaluation. + +The feature's intent is general: an evaluator can be handed any part a sealed run stored (trace, +raw streams, manifest), the same way it is handed artifacts today. htn-creator-eval is the first +consumer to need it (its probe P0 grades one run with a kind that needs artifacts and the trace, and +it wants each shell call's command and exit status and each MCP call's `{server, tool}`), but the +design answers the intent, not that probe: every choice below reuses an idiom Candler already has, +and the one structural change is a refactor that leaves `materialise` simpler than it is. + +Settled with the maintainer (2026-11-25): + +| Question | Ruling | +|---|---| +| Exit status | Reuse `candler_schemas::process::ExitStatus` on the tool result | +| Releases | One release carries the whole feature (trace, exit status, raw, manifest, helper, consumer-path guard) | +| Blinding | No new concept: a kind's declared needs already state what it sees (see below) | + +## What the trace already holds, and what it lacks + +- **MCP origin:** held. `ToolCall.origin = Mcp { server, tool }` (`crates/candler-schemas/src/trace.rs:645`). +- **Command text:** held. `ToolCall.argv = [input.command]` for Claude Code's `Bash` + (`crates/candler-harness-claude-code/src/parse.rs:359`) and OpenCode's `shell` + (`crates/candler-harness-opencode/src/export.rs:180-219`). +- **Exit status:** lacking. `ToolResult` keeps only the harness's `is_error`. The raw streams hold it: + +| Harness | Exit 0 | Nonzero | Interrupt | Denial | Timeout | +|---|---|---|---|---|---| +| Claude Code (real fixtures) | `is_error: false` | `is_error: true`, content starts `Exit code N` (1, 127 seen); no numeric field | `tool_use_result.interrupted`, never seen true | `tool_result_meta[].non_execution_kind` | no sample | +| OpenCode 2.2.7 (real binary, fake model) | `status: completed`, `metadata.exit: 0` | no fixture (expected `completed`, `metadata.exit: N`) | `status: error`, `error.type: aborted`, no exit | `status: error`, `error.type: permission.rejected` | no fixture | + +## The exit-status field + +`ToolResult` gains `exit: Option`, the same tagged object every supervised process +carries (`crates/candler-schemas/src/process.rs:284`: `{kind: code, code}` | `{kind: signal, signal}`). +It is absent when the call is not a shell call, was denied, or the harness gave no code (interrupt, +timeout). Candler never infers a signal from a code such as 137; the `signal` variant stays unused +until a harness reports one. `is_error` keeps meaning "the harness said so" and is not comparable +across harnesses for shell calls; the contract page says so. + +Reader rules (the call's name comes from the call joined on `(session, span)`): + +- Claude Code, `Bash` result: content prefix `Exit code N` gives `code N`; `is_error: false` gives + `code 0`; `interrupted: true`, a denial, or any other error text gives no exit. +- OpenCode, `shell` result: `metadata.exit: N` gives `code N`; `error.*` gives no exit. + +The optional field keeps the marker `normalised-trace/1` (old traces lack it and still read); the +schemas crate bumps its minor. The schema leaf confirms this against `__design__/architecture.md` +§Wire encodings before blessing. + +## Each need + +| Need | Today | After | Served as | +|---|---|---|---| +| `artifacts` | served | unchanged | `/files/...`, digest-checked copies | +| `inputs`, `metadata` | served | unchanged | as today | +| `snapshots` | refused `Unsupported` | unchanged | — | +| `trace: bool` | silently ignored | served | `/trace.jsonl` (0444), `context.trace` | +| `raw: bool` (new) | — | served | `/raw/.jsonl.gz`, `context.raw[]` (field exists) | +| `manifest: bool` (new) | — | served | `/manifest.json`, new optional `context.manifest` | + +- The manifest carries usage, the tool census (`run.tool_calls`), `run.exit`, `run.ended_by`, + factors and provenance, so "the rest of the stored run" is one file, not a family of needs. +- `tree.json` is not served: artifacts already give the files with digests. +- New `Needs` fields default to `false`, so an existing plug-in's `describe` stays valid. A run + that lacks the requested part (an imported run with no trace) is refused with a new + `ContextError` variant and refusal code, never served empty. +- **Refactor, one copy path:** `materialise.rs` has one copy routine, `copy_artifact` (create-new, + 0600, digest check, then 0444/0555), written for blobs. It becomes the single routine that copies + any stored file into the workspace given a source path and an expected digest; artifacts, inputs, + trace, raw streams and manifest all go through it, and `Assembled` carries one list of + `(stored source, workspace path, digest)` instead of a field per part. Adding a part then costs a + line in `assemble`, not a new copy path. The store records no trace or manifest digest, so + `assemble` hashes those once and the copy is checked against that hash, as blobs are. + +**Wire shape of a served file** (settled at roadmap authoring). `context_digest` is a pure function +of the wire `RunContext`, so each served file's digest travels on the wire, in the idiom +`ContextArtifact` already uses (`{path, abs, sha256}`: run-relative path, where the evaluator reads +it, digest). `context.trace` and `context.manifest` are that object (`{path: "trace.jsonl", abs, +sha256}`), and `ContextRaw` gains `sha256`. `context.trace` has never been filled, so changing it +from a path string to that object breaks no context Candler ever wrote. + +**Context digest** (`RunContext::context_digest`, used in `I4Key` for outcome reuse): each served +part adds its key (`trace: `, `raw: [{stream, sha256}]`, `manifest: `) only when +served, so every existing digest (golden imports, oracle vectors) is unchanged. + +## What a kind can see + +Candler has no blinding concept, and this feature adds none. The idiom that already covers it: a +kind declares its needs in `describe`, Candler serves exactly those and refuses what it does not +understand, so what a kind saw is stated by the kind itself. The trace, raw streams and manifest name +the model and the treatment's effects; whether seeing them biases a grade is domain science, and the +core names no domain. The contract page states what each part reveals, once. + +This agrees with the instruction-files feature (M6.5, plan v2): its v0 blinding gate G10 was +dropped, the maintainer ruled on 2026-11-25 that evaluator access to instructions is "deferred until a +consumer brings a reason", and G10 now names `experiment.instructions_collide` (the brief's +description of G10 is out of date). M6.5's new `context_start {system, first_message}` trace event +puts instruction texts in the trace; a kind that declares `needs.trace` sees them, as it declared. + +## Protocol, schemas, helper + +- `crates/candler-schemas/src/trace.rs`: `ToolResult.exit`. +- `crates/candler-schemas/src/evaluation.rs`: `Needs.raw`, `Needs.manifest`; `RunContext.manifest`; + `context_digest` keys. +- Regenerate `crates/candler-schemas/schema/*.json` (`CANDLER_BLESS_SCHEMAS=1 cargo nextest run -p + candler-schemas drift`) and the contract pages `docs/contract/{evaluator-protocol, + evaluator-helper}.md`; the outcome record is unchanged. +- `python/candler-evaluator`: `RunContext.manifest`; typed trace models generated from + `normalised-trace.schema.json` by `scripts/gen_models.py`; a reader that yields typed events from + `context.trace`; helper minor bump. +- `assemble.rs` doc and the M2a ruling: a new ruling note replaces "trace not served". + +## Release and order + +1. This feature lands on one integration branch cut from `origin/main`, merged to `main` through one + PR after the maintainer's go; the CI release cuts it (expected workspace v0.17.0, `schemas@0.14.0`). +2. As soon as the plan is approved, the field names go to the HTN Phase coordinator (the consumer + contact), so their probe kind can be written in parallel. +3. HTN pins the release and runs its probe P0; on pass, its redesign is unblocked. +4. M6.5 rebases its `trace_context` leaf onto this release: both edit `trace.rs` and bump the schemas + minor, and this one unblocks the consumer. No external users, so no compatibility shims. + +## Test plan + +Roles: a **guard** stays in the suite and carries the claim; a **probe** answers a question that a +decision waits on, its answer is recorded and its code deleted; a **confirm** checks one build step +and is culled. Each guard below extends a guard the suite already has wherever one owns the +behaviour, keeps the doc shape `Guards: / Oracle: / Bite:`, and takes its expected values from a +source independent of the code under test. + +### Behaviours, and who would be hurt if they broke + +| # | Behaviour | Who relies on it | Kind of risk | +|---|---|---|---| +| B1 | A shell call's exit status in the trace is the one the harness reported, and absent when it reported none | every plug-in that grades agent behaviour | seam with harnesses Candler does not own | +| B2 | A kind that declares `trace`, `raw` or `manifest` gets exactly the stored bytes, in its private workspace, read-only | every plug-in author | design cornerstone (R9, I11) | +| B3 | The context digest covers what was served, and is unchanged for a context that serves none of the new parts | outcome reuse (`I4Key`), golden imports | cornerstone: when it breaks, reuse breaks silently | +| B4 | A need the run cannot meet is refused with a code, never served empty | plug-in authors; AGENTS.md's one-reader rule | silent acceptance | +| B5 | The wire refuses what it does not understand (`exit`, `Needs.raw`, `Needs.manifest`) | the one reader per input | lenient second reading | +| B6 | The Python helper hands the kind the paths and a typed trace | plug-ins written with the helper | consumer interface | +| B7 | A real agent run, graded, shows its plug-in each shell call's command and exit, and each MCP call's `{server, tool}` | the consumer path end to end | seam: the whole chain on real harnesses | + +### Probe (its own step, before the readers) + +**P-shell** (leaf `probe_shell_shapes`): what do real Claude Code and real OpenCode 2.2.7 write for +a shell call that exits nonzero, one that writes only to stderr and exits nonzero, and one ended by +the harness's own timeout? It runs the `parity_e2e.rs` rig with a scripted fake-model turn. +Decisions it feeds: the OpenCode reader rule for nonzero exits (no fixture exists today); whether +either harness gives a code on a timeout (if neither does, `exit` stays absent and no timeout guard is +written); whether Claude Code's `Exit code N` prefix holds when stdout is empty. Kept afterwards: +the recorded raw streams, as reader fixtures made by the real harnesses, and the answer in the leaf +report. Deleted: the probe's test code. + +### Guards, by leaf + +| Leaf | Guard (extends) | Behaviour | Scope, and why | Oracle | Bite (seen red) | +|---|---|---|---|---|---| +| `schema_exit_needs` | `exit` rows in the schemas crate's trace reader table | B5 | unit at the one reader that every trace consumer goes through | hand-written lines: valid `{kind: code, code: 3}`; refused `{code: 3}`, a string, `exit` on a call event; a result with no `exit` still reads | `exit` typed as a free JSON value | +| `schema_exit_needs` | `Needs` rows in the shared wire vectors that Rust and `test_guard_wire_vectors.py` both read | B5 | the wire, where both readers meet | hand-written vectors: `raw`/`manifest` absent means false; non-boolean and unknown keys refused | a default that accepts any value | +| `cc_reader_exit` | `guard_reader.rs::expected_facts`, new `exits` rows in each fixture's `expected.toml` | B1 | integration over the real recorded streams, the seam's faithful copy | rows written from `jq` over the raw lines, never from reader output; classes: exit 0, nonzero (1, 127), a denial, a non-`Bash` tool, a call in a child session, and the probe's new shapes | (a) drop the prefix parse; (b) give code 0 to every non-error result, `Read` included; (c) join on span without session | +| `oc_reader_exit` | the export reader table `opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions` | B1 | same seam, OpenCode's exports | `jq` over the exports: completed with exit 0, completed with exit N (probe fixture), aborted, permission rejected | (a) read `metadata.exit` only on errors; (b) take a missing `metadata` as 0 | +| `serve_context` | `guard_run_context.rs`: serving and isolation | B2 | integration at `assemble` + `materialise`, the function pair every surface calls | sha256 of the stored files taken in the test from the store paths; file modes read back | (a) restore the silent ignore; (b) a hard link instead of a copy | +| `serve_context` | `a_plug_in_cannot_write_through_to_the_store`, extended to the new parts | B2 | same | the store's trace, raw and manifest bytes before and after a careless plug-in writes | hard link instead of copy | +| `serve_context` | `the_live_context_digest_is_the_independent_vector`, plus new rows from the independent generator (`gen_live_context.py`, python `rfc8785`) | B3 | same | existing rows untouched and still green; new rows for contexts with trace, raw, manifest served | (a) add the trace key even when not served (old rows go red); (b) leave it out when served (new rows go red) | +| `serve_context` | one row in `needs_inputs_refused_when_the_run_cannot_serve_them`'s pattern, or in `guard_silent_acceptance.rs`'s table | B4 | same | the refusal code written by hand from the leaf | serve the context with no trace. If the leaf finds that every sealed run stores a trace by construction, there is nothing to refuse: no guard, and the leaf report says why | +| `helper_context` | `test_guard_context.py` | B6 | the helper's interface, where plug-in code meets it | hand-written wire context and trace lines | (a) a model that accepts unknown fields; (b) `manifest` dropped by `from_wire` | +| `graded_run_sees_trace` | new e2e guard in `guard_cli_e2e/`, on the `parity_e2e.rs` rig | B7 | e2e through `candler run` and `candler evaluate` on the real harnesses and the production gateway: B1's seam is only real there | the fake-model script's own commands (write `answer.txt` and exit 0, `exit 3`, call `parity/stamp`); the kind's verdict depends on the trace (pass only if it finds those `(argv, exit)` pairs and that origin), so a missing or wrong trace changes the outcome itself, not only an echo of it | (a) serve no trace; (b) OpenCode reader without `exit`: the OpenCode row goes red while Claude Code stays green | + +The e2e guard is `#[ignore]` like the parity guard, runs in `.github/workflows/container-e2e.yml`, +and joins that workflow's expected-guard list, so a skip fails the job. It asks the same question +as HTN's P0, from inside the suite. + +### Trust boundaries and fixtures + +- Real: the harness binaries and the gateway (e2e and probe), the store and the copy (all + `serve_context` guards), the Python helper's own reader. +- Recorded: harness streams and exports, only as written by the real harness on Candler's own rig. + The one producer of a sealed run is Candler, so no guard builds a trace or a run by hand: runs come + from the mini-corpus import already used by `guard_run_context.rs` or from a run under the scripted + agent. +- Scripted: the fake model, whose script is the e2e oracle. + +### Deliberately not tested + +- `ExitStatus` serialisation: the type is reused, and its process tests already guard it. +- The `signal` variant in traces: no harness reports one and no reader writes one. +- Timeouts, unless the probe finds a harness that reports a code. +- Tampering with a stored trace before assembly: the seal records no trace digest, so Candler makes + no such promise; the copy check covers only assembly to copy. +- Raw stream and manifest contents: Candler copies bytes. The manifest's producer already has its + guards. +- The generated helper models field by field: CI's `gen_models.py` drift check covers them. +- The one-copy-routine refactor: the existing `guard_run_context.rs` guards (artifacts, inputs, + corrupt blob, isolation, write-through) passing unchanged is its guard. It adds no test of its own. +- The golden runs: not served the new parts, so B3's untouched rows already guard their digests. + +### Confirms + +They are not listed here. Implementers write them freely while building, under the name prefix +`confirm_`. Each one is deleted before its leaf merges, or rewritten to guard standard (with the +`Guards / Oracle / Bite` doc) when it guards a behaviour no guard above covers. The leaf's verifier +checks that `git grep -n confirm_ -- crates python` is empty on the leaf tip. + +## Roadmap node tree (sketch; authored with `dirtree-rdm` after approval) + +Campaign `__roadmap__/run_context/` (milestone label left to the coordinator, e.g. M6d). Depth is +order; siblings run in parallel. + +``` +run_context/ +├── schema_exit_needs.md L1 ToolResult.exit, Needs.raw/manifest, RunContext.manifest, +│ digest keys, blessed schemas, contract pages +├── probe_shell_shapes.md L1 probe P-shell: real Claude Code and OpenCode shell shapes +└── readers/ + ├── cc_reader_exit.md L2 critical path + ├── oc_reader_exit.md L2 critical path + ├── serve_context.md L2 critical path: one copy routine, assemble/materialise, + │ refusal, ruling note + ├── helper_context.md L2 non-critical (RiVault trial candidate) + └── e2e/ + ├── graded_run_sees_trace.md L3 e2e guard + CI list + └── review/ + └── adversarial_review.md L4 adversarial review of the whole diff against the README + paragraph, the codebase's idioms, and waste +``` + +The critical path for HTN's pin is L1 schema → L2 readers + serve → L3 e2e guard; the helper leaf +ships in the same release but no gate on that path depends on it. + +## Follow-ups (not in this release) + +- Claude Code hook denials (`confine_hook`) read as `DeniedBy::Harness`; `user-rejected` too. +- OpenCode `permission.rejected` read as a plain error, not a denial. +- Timeout as a distinct shell end, if a consumer asks (no harness evidence yet). + +## Done-criteria + +- Every guard above was seen red on the base or under its named bite, then green on the tip. The leaf + report records which bite was used and the failing message (leaf template convention 2). +- The probe is answered, its answer recorded in the leaf report, its fixtures committed, its code + deleted. +- No `confirm_` test is left on any leaf tip. +- The e2e guard is listed as PASS in a `container-e2e` run on the integration PR (convention 3). A + merge that touches the container path waits for it (convention 5). +- The project's checks (AGENTS.md §Checks, helper `pytest`/`ruff`/`gen_models.py`) pass as entry + conditions; they are not evidence of the feature. +- Acceptance from outside: HTN's P0 on the pinned release. + +## Execution model (coordinator-led team-of-subagents) + +- The coordinator writes no implementation; every subagent runs Claude Sonnet 5 with the model + passed explicitly. The `helper_context` leaf may run as a RiVault trial (Reasoning-Medium, then + Reasoning-Large, then Sonnet), with a mandatory Sonnet review briefed without the run's summary. +- One implementer per leaf, each on its own worktree cut from the integration branch (itself from + `origin/main`). Briefs carry: colgrep worktree init and absolute `paths` scoped to the worktree; + the environment (local `uv` for the Python helper, Docker for the rig); the target dir the campaign + README names, one per leaf, removed at its merge (leaf template convention 6), and the images the + probe or e2e built; the estimate and its cap as a stop action; reporting spec defects instead of + working around them; the leaf's guards with their bites, written first. +- A seam review of the whole diff so far follows each merge level (convention 4); the + `adversarial_review` leaf is the last of them. +- The coordinator never verifies its own dispatches: `spec-verifier` per leaf, a Rust conventions + review per Rust leaf, and the named `adversarial_review` leaf at L4. Agents are reused through + SendMessage. +- Per level: integration review by the coordinator; each leaf rebased onto the integration tip, then + `git merge --no-ff`; re-verify after any rebase or conflict; commit messages through `-F `; + confirm with `git log`. +- Push nothing without the maintainer's go; the PR description speaks from outside. + +## Roadmap authoring (Phase 0, after approval) + +Bootstrap `__roadmap__/run_context/` with `dirtree-rdm init`, add every node above with +`dirtree-rdm add`, write each leaf's Goal, Implementation Logic, Deliverables and Success Gates, +run `dirtree-rdm validate`, and commit the roadmap on the integration branch before any dispatch. From 18effe8d41b6987d7a72b397db98aa6e1b19b257 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:05:01 +0900 Subject: [PATCH 02/93] rdm(evaluation): open M6d Run context Eight nodes in four levels: the schema and a probe of real shell shapes, then both readers, the serving of the stored run and the helper, then a graded run on both harnesses, then an adversarial review of the whole diff. Each leaf states its guards, bites, estimate and cap. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/README.md | 47 +++++++++++++++++ __roadmap__/run_context/probe_shell_shapes.md | 31 +++++++++++ __roadmap__/run_context/readers/README.md | 46 +++++++++++++++++ .../run_context/readers/cc_reader_exit.md | 41 +++++++++++++++ __roadmap__/run_context/readers/e2e/README.md | 39 ++++++++++++++ .../readers/e2e/graded_run_sees_trace.md | 35 +++++++++++++ .../run_context/readers/e2e/review/README.md | 37 ++++++++++++++ .../readers/e2e/review/adversarial_review.md | 28 ++++++++++ .../run_context/readers/helper_context.md | 43 ++++++++++++++++ .../run_context/readers/oc_reader_exit.md | 40 +++++++++++++++ .../run_context/readers/serve_context.md | 45 ++++++++++++++++ __roadmap__/run_context/schema_exit_needs.md | 51 +++++++++++++++++++ 12 files changed, 483 insertions(+) create mode 100644 __roadmap__/run_context/README.md create mode 100644 __roadmap__/run_context/probe_shell_shapes.md create mode 100644 __roadmap__/run_context/readers/README.md create mode 100644 __roadmap__/run_context/readers/cc_reader_exit.md create mode 100644 __roadmap__/run_context/readers/e2e/README.md create mode 100644 __roadmap__/run_context/readers/e2e/graded_run_sees_trace.md create mode 100644 __roadmap__/run_context/readers/e2e/review/README.md create mode 100644 __roadmap__/run_context/readers/e2e/review/adversarial_review.md create mode 100644 __roadmap__/run_context/readers/helper_context.md create mode 100644 __roadmap__/run_context/readers/oc_reader_exit.md create mode 100644 __roadmap__/run_context/readers/serve_context.md create mode 100644 __roadmap__/run_context/schema_exit_needs.md diff --git a/__roadmap__/run_context/README.md b/__roadmap__/run_context/README.md new file mode 100644 index 00000000..16ec0f51 --- /dev/null +++ b/__roadmap__/run_context/README.md @@ -0,0 +1,47 @@ +# M6d Run context + +## Context +The README promises that Candler's evaluation half can "grade traces and artifacts, fresh or already on disk, through pluggable evaluators that emit one outcome record format". Today an evaluator is handed only the artifacts: `context.trace` and `context.raw[]` exist on the wire, but `assemble` never fills them and silently ignores `needs.trace = true`. This campaign builds the approved plan [`__reports__/run-context/00-plan_run_context_v0.md`](../../__reports__/run-context/00-plan_run_context_v0.md): an evaluator can be handed any part a sealed run stored (trace, raw streams, manifest) the same way it is handed artifacts, and the trace records each shell call's exit status as `ToolResult.exit`, the `ExitStatus` object every supervised process already carries. htn-creator-eval is the first consumer (its probe P0 pins the release this campaign cuts); the design answers the feature's intent, not that probe. Depth gives the order: level 1 holds `schema_exit_needs.md` (the wire) and `probe_shell_shapes.md` (what real harnesses write for a failing shell call) in parallel; `readers/` (level 2) holds both trace readers, the serving in `assemble`/`materialise` and the Python helper in parallel; `readers/e2e/` (level 3) holds the end-to-end guard on real harnesses; `readers/e2e/review/` (level 4) holds the adversarial review of the whole diff. The test plan (guards with their oracle and bite, the probe, what is deliberately not tested) is the plan's §Test plan; each leaf names the guards it owns. The integration branch is `feat/run-context`, cut from `origin/main` at `8d82f63b`; each leaf runs in its own worktree made by `scripts/worktree.py add` from the `feat/run-context` tip and removed at merge. Every build sets `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/run-context-target/` and `RUSTC_WRAPPER=sccache` in its own environment, one dir per leaf; 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 by the probe and the e2e guard only, each of which removes what it built by id; nothing is pruned and Docker is never stopped. Test names that start with `confirm_` are build-step checks: each is deleted before its leaf merges, or rewritten to guard standard (`Guards: / Oracle: / Bite:`). The milestone label M6d is the coordinator's; the instruction-files campaign (M6.5) rebases its `trace_context` leaf onto this release. + +## Goal +An evaluator plug-in that declares `needs.trace`, `needs.raw` or `needs.manifest` is handed a private, read-only, digest-checked copy of that part of the sealed run, or a refusal with a code; the trace records each shell call's exit status as the harness reported it on both Claude Code and OpenCode; and one real run graded through `candler evaluate` shows its plug-in each shell call's command and exit and each MCP call's `{server, tool}`. + +## Pre-conditions +- [x] `[nl]` The maintainer approved plan v0 (2026-11-25), with its rulings on exit status, one release, and no blinding concept +- [x] `[cmd]` `git merge-base --is-ancestor 8d82f63b feat/run-context` succeeds +- [ ] `[nl]` The maintainer approved the campaign's spend cap below before the first dispatch + +## Success Gates +- ⬜ Every leaf is `done`, and each leaf report records every guard it owns seen red (on the base or under its named bite) and then green, with the failing message +- ⬜ `git grep -n confirm_ -- crates python` prints nothing on the `feat/run-context` tip +- ⬜ `container-e2e` on the integration pull request lists `graded_run_sees_trace` (or the name the e2e leaf records) as PASS, and every merge into `feat/run-context` that touched the paths that workflow watches waited for it to be green +- ⬜ The pull request into `main` is opened only after the maintainer's go; after it merges, the CI release cuts the version and the HTN Phase coordinator is told the version to pin +- ⬜ Spend is measured from transcripts per leaf, and no leaf passed its cap without stopping. Leaf estimates add to $57, caps to $114; the campaign, coordinator included, stays within the cap the maintainer approves + +## Status +```mermaid +graph TD + schema_exit_needs[Schema: exit and needs]:::planned + probe_shell_shapes[Probe: shell shapes]:::planned + readers[Readers and serving]:::planned + 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 | +|:-----|:-----|:-------| +| `schema_exit_needs.md` | 📄 Leaf Task | ⬜ Planned | +| `probe_shell_shapes.md` | 📄 Leaf Task | ⬜ Planned | +| `readers/` | 📁 Directory | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/run_context/probe_shell_shapes.md b/__roadmap__/run_context/probe_shell_shapes.md new file mode 100644 index 00000000..2b85e4dc --- /dev/null +++ b/__roadmap__/run_context/probe_shell_shapes.md @@ -0,0 +1,31 @@ +# Probe: shell shapes + +**Goal**: Probe P-shell. The readers' rules for a failing shell call rest on what the real harnesses write, recorded on Candler's own rig, not on what they are expected to write. Three questions, each with the decision it feeds: (1) what does OpenCode 2.2.7 write for a `shell` call that exits nonzero (the OpenCode reader rule; no fixture exists today); (2) does either harness give a code when its own timeout ends a shell call (if neither does, `exit` stays absent and no timeout guard is written); (3) does Claude Code's `Exit code N` prefix hold when the command writes only to stderr (the Claude Code reader rule) (critical path) +**Estimate**: Sonnet, $6, cap $12. At the cap, stop, commit the fixtures already recorded, and list the questions left open in the leaf report. Builds use the target dir the campaign README names; the leaf removes it at its merge, and removes every image and container it built, by id. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/run-context HEAD` succeeds +- [ ] `[cmd]` `docker info` answers (start it with `docker desktop start` if it is down; never stop it, never prune) +**Success Gates**: +- ⬜ The leaf report answers each of the three questions with the raw line that shows it, quoted from a recorded stream, and names the reader rule each answer implies +- ⬜ For each harness, the streams of three calls are committed as reader fixtures made by the real harness: a nonzero exit, a stderr-only nonzero exit, and a call ended by the harness's timeout. Each fixture has its `PROVENANCE.toml` entry (harness version, image, date, the fake-model script). If a harness cannot be made to time a call out within the cap, the report says so and the decision of question (2) is "absent" +- ⬜ The probe's test code is deleted before merge: only the fixtures, their provenance and the report land +- The leaf touches `crates/**` (fixtures only); `container-e2e` is green on the pull request +**References**: [plan §What the trace already holds, §Probe](../../__reports__/run-context/00-plan_run_context_v0.md). Code: +- `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs`: the rig (both real harnesses, the production gateway, a scripted fake model); +- `crates/candler-harness-claude-code/tests/fixtures/streams/` and `crates/candler-harness-opencode/tests/fixtures/streams/` with their `PROVENANCE.toml`: where reader fixtures live and how their provenance is written. + +## Step 1: Record the shapes +**Goal**: Each harness's stream for the three calls is on disk. +**Implementation Logic**: +On the `parity_e2e.rs` rig, script the fake model to make three `shell`/`Bash` calls in one turn: `exit 3`; `echo oops >&2; exit 2`; and a call that outlives the harness's own shell timeout (set the shortest timeout the harness allows through its configuration, as the rig already configures each harness). Run it once on each harness. Copy the raw stream (Claude Code `stream-json`; OpenCode `stdout.jsonl` and `export.json`) into a fixture directory per harness, named for what it shows, and write each `PROVENANCE.toml` entry. Answer the three questions in the report from those lines only. +**Deliverables**: two fixture directories and their provenance entries; the probe's scratch test (deleted in Step 2) +**Consistency Checks**: `ls` of both fixture directories shows the stream files (expected: PASS) +**Commit**: `test(harness): record each harness's failing and timed-out shell call` + +## Step 2: Delete the probe, report +**Goal**: Only the answer and the fixtures stay. +**Implementation Logic**: +Remove the scratch test and anything it added to the rig. Remove the images and containers the runs built, by id. Write the report: each question, the line that answers it, the rule it implies for `readers/cc_reader_exit.md` and `readers/oc_reader_exit.md`. A fresh Sonnet verifier gets the leaf, the report and the fixtures and checks each quoted line against the fixture file. +**Deliverables**: `__reports__/run-context/leaves/probe_shell_shapes_v0.md` +**Consistency Checks**: `git diff feat/run-context --stat -- crates/candler/tests` prints nothing (expected: PASS) +**Commit**: `reports(harness): answer how each harness reports a failing shell call` diff --git a/__roadmap__/run_context/readers/README.md b/__roadmap__/run_context/readers/README.md new file mode 100644 index 00000000..80a04dc5 --- /dev/null +++ b/__roadmap__/run_context/readers/README.md @@ -0,0 +1,46 @@ +# Readers and serving + +## Context +Level 2 of M6d, after `../schema_exit_needs.md` (the wire: `ToolResult.exit`, `Needs.raw`, `Needs.manifest`, `RunContext.manifest`, the digest keys) and `../probe_shell_shapes.md` (real harness fixtures for nonzero exits and timeouts). Four leaves run in parallel: each trace reader fills `exit` from what its harness wrote, `serve_context.md` serves the declared parts through one copy routine, and `helper_context.md` gives Python plug-ins the new fields and a typed trace. `e2e/` follows. + +## Goal +Both trace readers record the harness's exit status, `assemble`/`materialise` serve the trace, raw streams and manifest or refuse with a code, and the Python helper exposes them. + +## Pre-conditions +- [ ] `[nl]` `../schema_exit_needs.md` and `../probe_shell_shapes.md` are `done` and merged into `feat/run-context` + +## Success Gates +- ⬜ `cc_reader_exit.md`, `oc_reader_exit.md`, `serve_context.md`, `helper_context.md` and `e2e/` are `done` +- ⬜ A seam review of the whole `feat/run-context` diff after this level's merges is recorded under `__reports__/run-context/`, and its findings are fixed or ruled on + +## Status +```mermaid +graph TD + cc_reader_exit[Claude Code exit]:::planned + oc_reader_exit[OpenCode exit]:::planned + serve_context[Serve the run]:::planned + helper_context[Helper context]:::planned + e2e[Consumer path]:::planned + 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 | +|:-----|:-----|:-------| +| `cc_reader_exit.md` | 📄 Leaf Task | ⬜ Planned | +| `oc_reader_exit.md` | 📄 Leaf Task | ⬜ Planned | +| `serve_context.md` | 📄 Leaf Task | ⬜ Planned | +| `helper_context.md` | 📄 Leaf Task | ⬜ Planned | +| `e2e/` | 📁 Directory | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/run_context/readers/cc_reader_exit.md b/__roadmap__/run_context/readers/cc_reader_exit.md new file mode 100644 index 00000000..386559cc --- /dev/null +++ b/__roadmap__/run_context/readers/cc_reader_exit.md @@ -0,0 +1,41 @@ +# Claude Code exit + +**Goal**: A `Bash` call in a Claude Code trace carries the exit status Claude Code reported: `exit: {kind: code, code: N}` when the result's content starts with `Exit code N`, `{kind: code, code: 0}` when the result is not an error, and no `exit` for an interrupted call, a denial, any other error text, or any tool that is not `Bash`. The call's name comes from the call joined on `(session, span)` (critical path) +**Estimate**: Sonnet, $6, cap $12. 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 feat/run-context HEAD` succeeds +- [ ] `[nl]` `../schema_exit_needs.md` and `../probe_shell_shapes.md` are `done`; the probe report's answer to question (3) (the prefix with stderr only) and to question (2) (a code on timeout) are read before Step 1 +**Success Gates**: +- ⬜ `guard_reader.rs::expected_facts` reads new `exits` rows from each fixture's `expected.toml`, written from `jq` over the raw lines and never from the reader's output. The rows cover: a `Bash` call that exited 0; nonzero exits (1 and 127 in the real fixtures); a denial; a call to a tool that is not `Bash` (for example `Read`); a call in a child session; and the probe's stderr-only and timed-out calls. On the base every `exits` row with a code fails +- ⬜ Each of three bites turns the guard red, and the report records the failing message: (a) the prefix parse removed; (b) code 0 given to every non-error result, `Read` included; (c) the call joined on span without the session +- ⬜ Rows with a code are added only to fixtures that a real Claude Code wrote, as their provenance records (the probe's among them). A synthetic fixture made by `make_synthetic.py` gets an `exits` row only where it states an absence, since a hand-built line cannot say what Claude Code writes +- ⬜ `parse.rs` reads only the result's `is_error` and the start of its first text content for this, and never infers a signal from a code +- `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; `container-e2e` is green on the pull request +**References**: [plan §The exit-status field, §Test plan](../../../__reports__/run-context/00-plan_run_context_v0.md); `__reports__/run-context/leaves/probe_shell_shapes_v0.md`. Code: +- `crates/candler-harness-claude-code/src/parse.rs`: `block_draft` and the `tool_result` handling, `tool_call`; +- `crates/candler-harness-claude-code/tests/it/guard_reader.rs`: `expected_facts`, `load_streams`; +- `crates/candler-harness-claude-code/tests/fixtures/{streams,sessions}/*/expected.toml`. + +## Step 1: Guard on the base +**Goal**: The `exits` rows exist and fail on the base. +**Implementation Logic**: +Extend `expected_facts` to compare a list of `(span, exit)` from the reader with an `exits` table in each `expected.toml`. Write each row from `jq` over the fixture's raw lines: find the `tool_use` of `Bash` and its `tool_result`, and read `is_error` and the content's first line. Record the `jq` expression in the report so the oracle can be rerun. Run the guard on the base. +**Deliverables**: `guard_reader.rs`; the `exits` rows +**Consistency Checks**: `expected_facts` on the base (expected: FAIL) +**Commit**: `test(adapter-claude-code): state each Bash call's exit from the raw lines` + +## Step 2: Read the exit +**Goal**: The guard passes. +**Implementation Logic**: +When a `tool_result` block pairs with a `Bash` call of the same session, set `exit` by the rule in the Goal. The prefix is `Exit code ` followed by a decimal `i32` at the start of the first text content; anything else in an error result gives no `exit`. A denial (`tool_result_meta` non-execution) and `interrupted: true` give no `exit` whatever the content. +**Deliverables**: `crates/candler-harness-claude-code/src/parse.rs` +**Consistency Checks**: `expected_facts` on the tip (expected: PASS) +**Commit**: `feat(adapter-claude-code): read a Bash call's exit status` + +## Step 3: Bite and verify +**Goal**: Each bite turns the guard red. +**Implementation Logic**: +On a scratch branch apply bites (a), (b) and (c) one at a time and record each failing message. Delete every `confirm_` test. A fresh Sonnet verifier gets the leaf, the report and the diff, and is asked to find a recorded `Bash` result whose `exit` the reader gets wrong, or a non-`Bash` result that gets one. +**Deliverables**: `__reports__/run-context/leaves/cc_reader_exit_v0.md` +**Consistency Checks**: `git grep -n confirm_ -- crates python` prints nothing (expected: PASS) +**Commit**: `reports(adapter-claude-code): close the Bash exit status` diff --git a/__roadmap__/run_context/readers/e2e/README.md b/__roadmap__/run_context/readers/e2e/README.md new file mode 100644 index 00000000..f3c5016d --- /dev/null +++ b/__roadmap__/run_context/readers/e2e/README.md @@ -0,0 +1,39 @@ +# Consumer path + +## Context +Level 3 of M6d, after every `readers/` leaf merged. One end-to-end guard asks, from inside Candler's suite, the question htn-creator-eval's probe P0 asks: does a real agent run, graded through `candler evaluate`, show its plug-in each shell call's command and exit and each MCP call's origin? `review/` follows. + +## Goal +The consumer path (run, seal, evaluate with `needs.trace`) is seen working on both real harnesses in `container-e2e`, and seen failing without the trace. + +## Pre-conditions +- [ ] `[nl]` `cc_reader_exit.md`, `oc_reader_exit.md`, `serve_context.md` and `helper_context.md` are `done` and merged into `feat/run-context` + +## Success Gates +- ⬜ `graded_run_sees_trace.md` and `review/` are `done` + +## Status +```mermaid +graph TD + graded_run_sees_trace[Graded run sees trace]:::planned + review[Review]:::planned + 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 | +|:-----|:-----|:-------| +| `graded_run_sees_trace.md` | 📄 Leaf Task | ⬜ Planned | +| `review/` | 📁 Directory | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/run_context/readers/e2e/graded_run_sees_trace.md b/__roadmap__/run_context/readers/e2e/graded_run_sees_trace.md new file mode 100644 index 00000000..fb59f10c --- /dev/null +++ b/__roadmap__/run_context/readers/e2e/graded_run_sees_trace.md @@ -0,0 +1,35 @@ +# Graded run sees trace + +**Goal**: A real agent run on either harness, sealed by `candler run` and graded by `candler evaluate` with a kind that declares `needs.trace` and an artifact, shows its plug-in each shell call's command and exit status and each MCP call's `{server, tool}`; without the trace, or with a reader that loses `exit`, the kind's own verdict changes (critical path) +**Estimate**: Sonnet, $10, 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; the leaf removes it at its merge, and removes every image and container it built, by id. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/run-context HEAD` succeeds +- [ ] `[nl]` Every `../` leaf is `done` and merged into `feat/run-context` +- [ ] `[cmd]` `docker info` answers (never stop Docker, never prune) +**Success Gates**: +- ⬜ A new guard in `crates/candler/tests/it/guard_cli_e2e/`, on the `parity_e2e.rs` rig (both real harnesses, the production gateway, the scripted fake model), runs one cell per harness whose script writes `answer.txt` with a command that exits 0, runs `exit 3`, and calls the `parity` server's `stamp` tool. It then grades each run with a plug-in kind that declares `needs.trace = true` and `needs.artifacts = ["answer.txt"]`. The kind passes only if the trace holds the pairs `(argv, exit)` for both commands and the origin `{kind: mcp, server: parity, tool: stamp}`, and `answer.txt` is served. The oracle is the fake-model script's own commands, not Candler's output +- ⬜ The guard is `#[ignore]` like the parity guard, joins `.github/workflows/container-e2e.yml`'s expected-guard list, and is listed as PASS in a `container-e2e` run on this leaf's pull request; the report quotes the PASS line +- ⬜ Each of two bites turns the guard red, and the report records the failing message: (a) `assemble` serves no trace (the outcome is a fail or a refusal, not a pass); (b) the OpenCode reader writes no `exit` (the OpenCode row goes red while Claude Code's stays green) +- ⬜ The guard asks the question htn-creator-eval's probe P0 asks; the report says which parts of P0 it does not cover (P0's own kind and suite) +- The leaf touches `crates/**` and `.github/workflows/container-e2e.yml`; `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` pass, and the guard passes locally with `--run-ignored only` before the pull request +**References**: [plan §Test plan (B7)](../../../../__reports__/run-context/00-plan_run_context_v0.md). Code: +- `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs`: `parity_one_installed_server_one_traced_call`, the rig; +- `crates/candler/tests/it/guard_run_evaluate.rs`: `plugin`, a run graded by a plug-in set up beside it; +- `crates/candler/tests/it/guard_cli_e2e.rs`: the module list; +- `.github/workflows/container-e2e.yml`. + +## Step 1: The guard +**Goal**: The guard runs both cells and grades them. +**Implementation Logic**: +Reuse the parity rig and its fake model; add the script turns named in the gate. Set up the plug-in beside the world as `guard_run_evaluate.rs` does, with the Python helper's typed trace reader, and a kind whose verdict is computed from the trace. Run `candler run` then `candler evaluate` through the CLI, and read the outcome record. Add the guard's name to the workflow's expected list. +**Deliverables**: a new module under `crates/candler/tests/it/guard_cli_e2e/` and its line in `guard_cli_e2e.rs`; `.github/workflows/container-e2e.yml` +**Consistency Checks**: `cargo nextest run -p candler --test it -E 'test(/^guard_cli_e2e::/)' --run-ignored only` locally (expected: PASS) +**Commit**: `test(library): grade a real run by its trace on both harnesses` + +## Step 2: Bite and verify +**Goal**: Each bite turns the guard red, and CI ran it. +**Implementation Logic**: +On a scratch branch apply bites (a) and (b) one at a time, run the guard locally, and record each failing message. Remove the images and containers built, by id. Open the leaf's pull request into `feat/run-context` and wait for `container-e2e`. A fresh Sonnet verifier gets the leaf, the report, the diff and the CI log, and is asked to find a way the guard could pass while a plug-in on either harness would not see a shell call's exit. +**Deliverables**: `__reports__/run-context/leaves/graded_run_sees_trace_v0.md` +**Consistency Checks**: `git grep -n confirm_ -- crates python` prints nothing (expected: PASS) +**Commit**: `reports(library): close the graded run's trace` diff --git a/__roadmap__/run_context/readers/e2e/review/README.md b/__roadmap__/run_context/readers/e2e/review/README.md new file mode 100644 index 00000000..ebd0b38a --- /dev/null +++ b/__roadmap__/run_context/readers/e2e/review/README.md @@ -0,0 +1,37 @@ +# Review + +## Context +Level 4 of M6d, the last. An adversarial reviewer who did not build any leaf reads the whole `feat/run-context` diff against the README purpose paragraph, the codebase's idioms and waste, before the integration pull request is proposed to the maintainer. + +## Goal +The whole diff is judged by someone with no stake in it, and every finding is fixed or ruled on before the pull request into `main`. + +## Pre-conditions +- [ ] `[nl]` `../graded_run_sees_trace.md` is `done` and merged into `feat/run-context` + +## Success Gates +- ⬜ `adversarial_review.md` is `done` + +## Status +```mermaid +graph TD + adversarial_review[Adversarial review]:::planned + 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 | +|:-----|:-----|:-------| +| `adversarial_review.md` | 📄 Leaf Task | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/run_context/readers/e2e/review/adversarial_review.md b/__roadmap__/run_context/readers/e2e/review/adversarial_review.md new file mode 100644 index 00000000..cbe07f74 --- /dev/null +++ b/__roadmap__/run_context/readers/e2e/review/adversarial_review.md @@ -0,0 +1,28 @@ +# Adversarial review + +**Goal**: The whole `feat/run-context` diff is judged by a reviewer who built none of it, against the README purpose paragraph quoted verbatim, the codebase's idioms (AGENTS.md: one producer per stored state, one reader per input that refuses what it does not understand; Grit; source files say what is), and waste at the three levels (how it was developed, what it leaves in the code, how it is consumed); every finding is fixed or ruled on before the integration pull request is proposed +**Estimate**: Sonnet, $5, cap $10, review only; fixes are dispatched as their own work and costed apart. At the cap, stop and report what was read and what was not. The review builds nothing; a fix that builds uses the target dir the campaign README names and removes it at its merge. +**Pre-conditions**: +- [ ] `[cmd]` `git merge-base --is-ancestor feat/run-context HEAD` succeeds in the reviewer's checkout +- [ ] `[nl]` `../graded_run_sees_trace.md` is `done` and merged into `feat/run-context` +**Success Gates**: +- ⬜ A findings report `__reports__/run-context/02-review_adversarial_v0.md` covers the whole diff `origin/main...feat/run-context`. For each finding it gives the file and line, the failure it would cause, and its class (defect, idiom, waste). It answers at least: is any stored part served by a second path; does any reader accept what the schema refuses; does the context digest change for a context serving none of the new parts; does any doc carry history or plan references; did the refactor leave `materialise` simpler, judged by its call sites, not its line count +- ⬜ Every finding is fixed on `feat/run-context` (the fix's commit cited) or ruled on by the coordinator with the reason recorded in the report; a finding that needs the maintainer goes to them before the pull request +- ⬜ After the fixes, the project's checks pass on the tip and `container-e2e` is green on the integration pull request draft +**References**: [README.md](../../../../../README.md) purpose paragraph; [AGENTS.md](../../../../../AGENTS.md); [plan](../../../../../__reports__/run-context/00-plan_run_context_v0.md); every leaf report under `__reports__/run-context/leaves/`. + +## Step 1: Review +**Goal**: The findings report exists. +**Implementation Logic**: +A fresh Sonnet reviewer gets the README paragraph, AGENTS.md, the plan, and the diff; not the leaf reports' conclusions until it has read the diff once. It reads code through colgrep with absolute paths in its own checkout of `feat/run-context`. It writes findings, not fixes. +**Deliverables**: `__reports__/run-context/02-review_adversarial_v0.md` +**Consistency Checks**: the report lists every file in `git diff --stat origin/main...feat/run-context` as read or says why not (expected: PASS) +**Commit**: `reports(evaluation): review the run context campaign adversarially` + +## Step 2: Fix or rule +**Goal**: No finding is left open. +**Implementation Logic**: +The coordinator dispatches each fix to an implementer on its own worktree and merges it as any leaf; a finding not fixed gets a ruling in the report. Rerun the checks and `container-e2e`. +**Deliverables**: the fixes; the rulings in `02-review_adversarial_v0.md` +**Consistency Checks**: `cargo nextest run --workspace` on the tip (expected: PASS) +**Commit**: `reports(evaluation): close the adversarial review` diff --git a/__roadmap__/run_context/readers/helper_context.md b/__roadmap__/run_context/readers/helper_context.md new file mode 100644 index 00000000..6f963046 --- /dev/null +++ b/__roadmap__/run_context/readers/helper_context.md @@ -0,0 +1,43 @@ +# Helper context + +**Goal**: A plug-in written with the Python helper reads what it declared without parsing the wire: `RunContext` carries `trace`, `raw` and `manifest` as paths with their digests, and a reader yields the trace's events as typed models generated from `normalised-trace.schema.json`, refusing a line the schema refuses (non-critical: no gate on HTN's path depends on it; RiVault trial candidate) +**Estimate**: RiVault trial (Reasoning-Medium, then Reasoning-Large), falling back to Sonnet, $5, cap $10, plus a mandatory Sonnet review briefed without the run's summary. At the cap, stop, commit what is green, and list what is left in the leaf report. No Rust build is expected; if one is needed, it uses the target dir the campaign README names and the leaf removes it at its merge. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/run-context HEAD` succeeds +- [ ] `[nl]` `../schema_exit_needs.md` is `done` (the schemas and the generated models it regenerated are on the tip) +**Success Gates**: +- ⬜ `tests/test_guard_context.py`, over hand-written wire contexts, shows `RunContext.from_wire` keeping `trace`, `raw` (with `sha256`) and `manifest`, each `None` or empty when absent. On the base `manifest` is dropped and `trace` is read as a bare path. Bite: `manifest` dropped by `from_wire` +- ⬜ A trace reader in the helper yields typed events from `context.trace`, and the same test file shows it reading hand-written lines with `exit`, `origin: {kind: mcp, server, tool}` and `argv`, and refusing a line with an unknown field. Bite: a model that accepts unknown fields +- ⬜ `scripts/gen_models.py` generates the trace models from `normalised-trace.schema.json` deterministically, and CI's regeneration check passes +- ⬜ `docs/contract/evaluator-helper.md` lists the new fields and the reader, within its Notes limit and with stamps; `pyproject.toml`'s version is bumped by hand to the next minor, as CONTRIBUTING.md §Evaluator helper line says, and no tag is cut +- `uv run pytest`, `uv run ruff check`, `uv run ruff format --check` and `uv run --frozen python scripts/gen_models.py` with no diff, all from `python/candler-evaluator` +**References**: [plan §Protocol, schemas, helper, §Test plan](../../../__reports__/run-context/00-plan_run_context_v0.md). Code: +- `python/candler-evaluator/src/candler_evaluator/plugin.py`: `RunContext`, `RunContext.from_wire`; +- `python/candler-evaluator/scripts/gen_models.py`: `roots`; +- `python/candler-evaluator/tests/test_guard_context.py`; +- `crates/candler-schemas/schema/normalised-trace.schema.json`; +- `docs/contract/evaluator-helper.md`. + +## Step 1: Guards on the base +**Goal**: The context and reader guards are written first and seen red on the base. +**Implementation Logic**: +Extend `test_guard_context.py` with wire contexts that carry the new parts and trace lines written by hand from the schema. Use the project's environment (`uv`, from `python/candler-evaluator`). Run on the base and record each failing message. +**Deliverables**: `tests/test_guard_context.py` +**Consistency Checks**: the new tests on the base (expected: FAIL) +**Commit**: `test(evaluator-helper): state the stored run's parts and a typed trace` + +## Step 2: Fields and reader +**Goal**: The guards pass. +**Implementation Logic**: +Add `normalised-trace.schema.json` to `gen_models.py`'s roots and regenerate. Give `RunContext` the `manifest` field and keep each served file's digest beside its path. Add a reader that opens `context.trace` and validates each line strictly against the generated event model, yielding the models. Update the contract page and bump the version. +**Deliverables**: `plugin.py` (or a module beside it for the reader); `scripts/gen_models.py`; `_models/`; `docs/contract/evaluator-helper.md`; `pyproject.toml` +**Consistency Checks**: `uv run pytest` (expected: PASS) +**Commit**: `feat(evaluator-helper): hand a kind the stored run's parts and a typed trace` + +## Step 3: Bite and review +**Goal**: Each bite turns a guard red, and a Sonnet reviewer read the change. +**Implementation Logic**: +On a scratch branch apply each bite and record each failing message. Delete every `confirm_` test. A Sonnet reviewer, briefed with this leaf and the diff but not the run's summary, is asked to find a wire context or trace line the helper reads differently from the Rust reader. +**Deliverables**: `__reports__/run-context/leaves/helper_context_v0.md` +**Consistency Checks**: `git grep -n confirm_ -- crates python` prints nothing (expected: PASS) +**Commit**: `reports(evaluator-helper): close the stored run's parts in the helper` diff --git a/__roadmap__/run_context/readers/oc_reader_exit.md b/__roadmap__/run_context/readers/oc_reader_exit.md new file mode 100644 index 00000000..07b5d3d7 --- /dev/null +++ b/__roadmap__/run_context/readers/oc_reader_exit.md @@ -0,0 +1,40 @@ +# OpenCode exit + +**Goal**: A `shell` call in an OpenCode trace carries the exit status OpenCode reported: `exit: {kind: code, code: N}` from the tool part's `state.metadata.exit` (the rule for a nonzero exit is the one the probe recorded), and no `exit` when the part's state is an error (`aborted`, `permission.rejected`, …), when `metadata.exit` is missing, or for any tool that is not `shell` (critical path) +**Estimate**: Sonnet, $5, cap $10. 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 feat/run-context HEAD` succeeds +- [ ] `[nl]` `../schema_exit_needs.md` and `../probe_shell_shapes.md` are `done`; the probe report's answers to questions (1) and (2) are read before Step 1. If the probe found that OpenCode writes a nonzero exit somewhere other than `state.metadata.exit`, the rule follows the probe and the report says so +**Success Gates**: +- ⬜ The export reader's table `opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions` gains an `exit` column, written from `jq` over the exports and never from the reader's output. Its rows cover: a completed `shell` call with exit 0 (`completed_o1`); a completed call with a nonzero exit, a stderr-only nonzero exit and a timed-out call (the probe's fixture); an aborted call (`sigint_mid_tool` or `interrupt_api`); a rejected permission (`oc_permission_ask`); a tool that is not `shell`. On the base every row with a code fails +- ⬜ Each of two bites turns the table red, and the report records the failing message: (a) `metadata.exit` read only on error states; (b) a missing `metadata` taken as exit 0 +- ⬜ `export.rs` never infers a signal from a code and never reads an exit from the tool's text output +- `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; `container-e2e` is green on the pull request +**References**: [plan §The exit-status field, §Test plan](../../../__reports__/run-context/00-plan_run_context_v0.md); `__reports__/run-context/leaves/probe_shell_shapes_v0.md`. Code: +- `crates/candler-harness-opencode/src/export.rs`: `tool_drafts`; +- `crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs`: `opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions`; +- `crates/candler-harness-opencode/tests/fixtures/streams/*/export.json`. + +## Step 1: Guard on the base +**Goal**: The `exit` column exists and fails on the base. +**Implementation Logic**: +Add the `exit` column to the table and the probe fixture's rows. Write each expected value from `jq` over the fixture's `export.json` (the tool part's `state.status`, `state.metadata.exit`, `state.error`) and record the expression in the report. Run the table on the base. +**Deliverables**: `guard_opencode_driver.rs` +**Consistency Checks**: the table on the base (expected: FAIL) +**Commit**: `test(adapter-opencode): state each shell call's exit from the export` + +## Step 2: Read the exit +**Goal**: The table passes. +**Implementation Logic**: +In `tool_drafts`, for a `shell` part, read the exit by the rule in the Goal and pass it to the result's constructor. Keep the rule in one place beside the existing `argv` reading. +**Deliverables**: `crates/candler-harness-opencode/src/export.rs` +**Consistency Checks**: the table on the tip (expected: PASS) +**Commit**: `feat(adapter-opencode): read a shell call's exit status` + +## Step 3: Bite and verify +**Goal**: Each bite turns the table red. +**Implementation Logic**: +On a scratch branch apply bites (a) and (b) one at a time and record each failing message. Delete every `confirm_` test. A fresh Sonnet verifier gets the leaf, the report and the diff, and is asked to find a recorded `shell` part whose `exit` the reader gets wrong, or another tool that gets one. +**Deliverables**: `__reports__/run-context/leaves/oc_reader_exit_v0.md` +**Consistency Checks**: `git grep -n confirm_ -- crates python` prints nothing (expected: PASS) +**Commit**: `reports(adapter-opencode): close the shell exit status` diff --git a/__roadmap__/run_context/readers/serve_context.md b/__roadmap__/run_context/readers/serve_context.md new file mode 100644 index 00000000..a326d4d6 --- /dev/null +++ b/__roadmap__/run_context/readers/serve_context.md @@ -0,0 +1,45 @@ +# Serve the run + +**Goal**: A kind that declares `needs.trace`, `needs.raw` or `needs.manifest` is handed exactly the stored bytes of that part, copied into its private workspace, read-only, with the digest in its context and in the context digest; a run that lacks the part is refused with a code, never served empty. Every stored file reaches the workspace through one copy routine: `materialise` has one routine that copies a stored file given its source and expected digest, and `Assembled` carries one list of `(stored source, workspace path, digest)` instead of a field per part (critical path) +**Estimate**: Sonnet, $12, cap $24. 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 feat/run-context HEAD` succeeds +- [ ] `[nl]` `../schema_exit_needs.md` is `done` +**Success Gates**: +- ⬜ In `guard_run_context.rs`, a kind declaring `trace`, `raw` and `manifest` over a sealed run gets `context.trace`, `context.raw[]` and `context.manifest` whose files hash to the sha256 the test takes from the store's own paths (`runs//trace.jsonl`, `raw/.jsonl.gz`, `manifest.json`), with mode `0444` read back, and whose `sha256` fields equal those hashes. On the base `needs.trace` is silently ignored and the guard fails. Bites: (a) restore the silent ignore; (b) a hard link instead of a copy +- ⬜ `a_plug_in_cannot_write_through_to_the_store` extends to the trace, raw streams and manifest: the store's bytes are the same after a careless plug-in writes to its copies. Bite: a hard link instead of a copy +- ⬜ `the_live_context_digest_is_the_independent_vector` keeps every existing row unchanged and green, and new rows for contexts that serve a trace, raw streams or a manifest, written by `gen_live_context.py` over python `rfc8785`, pass. Bites: (a) the trace key added even when not served (old rows go red); (b) left out when served (new rows go red) +- ⬜ A kind that declares a part the run does not hold is refused with a new `ContextError` variant and a code in `docs/contract/codes.toml`, guarded by a row in `needs_inputs_refused_when_the_run_cannot_serve_them`'s pattern or `guard_silent_acceptance.rs`'s table, with the code written by hand. If the leaf finds that every sealed run holds a trace, raw streams and a manifest by construction (imported runs included), there is nothing to refuse for that part: the report says why, with the producer that guarantees it, and no guard is written for it +- ⬜ The existing `guard_run_context.rs` guards (artifacts, inputs, corrupt blob, isolation, write-through) pass unchanged after the refactor; that is the refactor's guard, and the leaf adds no test of its own for it. `materialise.rs` has one copy routine, and the report shows its call sites +- ⬜ `assemble.rs`'s doc states what is served and refused, with no history; a note `__reports__/run-context/01-ruling_trace_served_v0.md` records that the M2a ruling "trace not served" (`__reports__/m2a-evaluation-parity/l1/00-rulings_v0.md:75`) is replaced, and why +- `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; `container-e2e` is green on the pull request +**References**: [plan §Each need, §Wire shape of a served file, §Test plan](../../../__reports__/run-context/00-plan_run_context_v0.md). Code: +- `crates/candler-core/src/evaluation/context/{assemble,materialise,mod}.rs`: `assemble`, `Assembled`, `copy_artifact`, `materialise`, `ContextError`; +- `crates/candler-core/src/store/{layout,run}.rs`: the run's stored paths, `RunWriter::done`; +- `crates/candler-core/tests/it/guard_run_context.rs`, `guard_silent_acceptance.rs`; +- `crates/candler-core/tests/oracle/vectors/{gen_live_context.py,live_context_runs.toml}`; +- `docs/contract/codes.toml`. + +## Step 1: Guards on the base +**Goal**: The serving, write-through, digest and refusal guards are written first and seen red on the base. +**Implementation Logic**: +Runs come from the mini-corpus import `guard_run_context.rs` already uses, or from a run under the scripted agent; no test builds a run or a trace by hand. Write the serving guard and extend write-through to the new parts. Extend `gen_live_context.py` with the new contexts and add their rows without regenerating the existing ones. Write the refusal row once Step 2's reading of the store says which parts can be missing; until then, record in the report which import paths store no trace. Run every guard on the base and record each failing message. +**Deliverables**: `guard_run_context.rs`; `gen_live_context.py` and `live_context_runs.toml` +**Consistency Checks**: on the base, every new guard fails and every existing digest row passes (expected: PASS) +**Commit**: `test(evaluation): state the serving of the trace, raw streams and manifest` + +## Step 2: One copy path, every part +**Goal**: The guards pass, and every stored file goes through one routine. +**Implementation Logic**: +Turn `copy_artifact` into the routine that copies any stored file into the workspace given its source path and expected digest (create-new, `0600`, digest check, then `0444` or `0555` by the execute bit), and route artifacts and inputs through it unchanged in behaviour. Replace `Assembled`'s per-part fields with one list of `(stored source, workspace path, digest)`. In `assemble`, add the trace, each raw stream and the manifest to that list when declared, hashing each once (the store records no digest for them); refuse a declared part the run lacks with the new `ContextError` variant and its code. Fill `context.trace`, `context.raw[]` and `context.manifest` from the list. Rewrite `assemble.rs`'s doc and write the ruling note. +**Deliverables**: `crates/candler-core/src/evaluation/context/{assemble,materialise,mod}.rs`; `docs/contract/codes.toml`; `__reports__/run-context/01-ruling_trace_served_v0.md` +**Consistency Checks**: every `guard_run_context.rs` guard on the tip (expected: PASS) +**Commit**: `feat(evaluation): serve a run's trace, raw streams and manifest to a kind that declares them` + +## Step 3: Bite and verify +**Goal**: Each guard goes red under its bite. +**Implementation Logic**: +On a scratch branch apply each named bite one at a time and record each failing message. Delete every `confirm_` test. A fresh Sonnet verifier gets the leaf, the report and the diff, and is asked to find a path by which a plug-in reads or writes a stored file other than through the one copy routine, a part served without its digest in the context digest, or a declared part served empty. +**Deliverables**: `__reports__/run-context/leaves/serve_context_v0.md` +**Consistency Checks**: `git grep -n confirm_ -- crates python` prints nothing (expected: PASS) +**Commit**: `reports(evaluation): close the serving of the stored run` diff --git a/__roadmap__/run_context/schema_exit_needs.md b/__roadmap__/run_context/schema_exit_needs.md new file mode 100644 index 00000000..21cee398 --- /dev/null +++ b/__roadmap__/run_context/schema_exit_needs.md @@ -0,0 +1,51 @@ +# Schema: exit and needs + +**Goal**: The wire can say what a plug-in may be served and what a shell call returned: a trace line's `tool_result` carries an optional `exit` (`candler_schemas::process::ExitStatus`), `Needs` has `raw` and `manifest` (default `false`), `RunContext` has `manifest`, `trace` and `manifest` are `{path, abs, sha256}` objects, `ContextRaw` carries `sha256`, and `context_digest` adds a key for each served part only when it is served. The one reader of each refuses what it does not understand (critical path) +**Estimate**: Sonnet, $8, cap $16. 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 feat/run-context HEAD` succeeds +**Success Gates**: +- ⬜ A trace line `{"kind":"tool_result","is_error":true,"exit":{"kind":"code","code":3}}` reads, and the result keeps `exit` when written back. `exit` given as `{"code":3}`, as a string, or on a `tool_call` line is refused. A `tool_result` with no `exit` still reads. On the base, the line with `exit` is refused as an unknown field +- ⬜ In the shared wire vectors (`crates/candler-schemas/tests/fixtures/rpc/`), which the Rust reader and the Python helper's `test_guard_wire_vectors.py` both read, a `describe` response whose needs omit `raw` and `manifest` is valid, and one whose needs set `raw` to a non-boolean, or carry an unknown key, is invalid. Both readers decide every vector alike +- ⬜ The context digest vectors keep every existing row unchanged and green, and new rows (contexts serving a trace, raw streams, a manifest), written by the independent Python generator over python `rfc8785`, pass. Under the bite "the trace key is always added" the old rows go red; under "the key is left out when served" the new rows go red +- ⬜ The marker stays `normalised-trace/1`: the leaf report cites `__design__/architecture.md` §Wire encodings on why an optional field leaves it unchanged, or stops and tells the lead if that section says otherwise +- ⬜ The JSON Schemas under `crates/candler-schemas/schema/` and the helper's generated models (`python/candler-evaluator/scripts/gen_models.py`) are regenerated, and the helper's `pytest` passes with the smallest change to its hand-written code that keeps it reading the new shapes; the helper's new API belongs to `readers/helper_context.md` +- ⬜ The doc comments of `Needs`, `RunContext` and `ToolResult` (which reach the schemas) state each need, what each served part reveals of the run (once, with no domain judgement), that `is_error` is not comparable across harnesses for shell calls, and that `exit` is absent for a non-shell, denied or uncoded result. `docs/contract/evaluator-protocol.md`'s generated sections are regenerated, and its Notes stay within the page's 120 words, each with its stamp (CONTRIBUTING.md §Contract pages) +- ⬜ Both trace readers compile against the new constructor and write no `exit` yet (`readers/` fills it) +- `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; helper `uv run pytest`, `uv run ruff check` pass; `container-e2e` is green on the pull request (it touches `crates/**`) +**References**: [plan §The exit-status field, §Each need, §Wire shape of a served file, §Test plan](../../__reports__/run-context/00-plan_run_context_v0.md). Code: +- `crates/candler-schemas/src/trace.rs`: `KnownKind::ToolResult`, `EventKind::tool_result`; +- `crates/candler-schemas/src/process.rs`: `ExitStatus` (reused as is); +- `crates/candler-schemas/src/evaluation.rs`: `Needs`, `RawRunContext`, `RunContext`, `ContextRaw`, `ContextArtifact`, `context_digest`; +- `crates/candler-schemas/tests/it/guard_trace_wire.rs`, `guard_evaluator_protocol.rs`, `guard_context_digest.rs`; `crates/candler-schemas/tests/fixtures/rpc/`; the context digest vectors and their generator under `crates/candler-core/tests/oracle/vectors/`; +- `python/candler-evaluator/tests/test_guard_wire_vectors.py`, `scripts/gen_models.py`. + +## Step 1: Guards on the base +**Goal**: Every guard this leaf owns is written first and seen red on the base. +**Implementation Logic**: +Add the `exit` rows to the trace reader's table in `guard_trace_wire.rs` (hand-written lines, as above). Add the `Needs` vectors to `fixtures/rpc/valid` and `fixtures/rpc/invalid`, with their `PROVENANCE.toml` entries. Extend the context digest generator with contexts that serve a trace, raw streams and a manifest, and write their rows; existing rows are not regenerated. Run each guard on the base and record the failing message in the leaf report. +**Deliverables**: the guard rows and vectors named above; the generator's new cases +**Consistency Checks**: on the base, every new row fails and every existing digest row passes (expected: PASS) +**Commit**: `test(schemas): state the exit field, the new needs and their digest keys` + +## Step 2: The wire +**Goal**: The guards pass on the tip. +**Implementation Logic**: +Add `exit: Option` to `ToolResult` with the same `default`, `skip_serializing_if` and `present` attributes its siblings use, and an `exit` parameter to `EventKind::tool_result`; both readers pass `None`. Add `raw` and `manifest` to `Needs` as booleans that default to `false` when absent, refusing any other type. Make `trace` and `manifest` on `RunContext` optional `{path, abs, sha256}` objects in `ContextArtifact`'s idiom (reuse the type if its doc reads true for them, or give the shape one name used by all three), and add `sha256` to `ContextRaw`. Add to `context_digest` a `trace`, `raw` (`[{stream, sha256}]`, sorted by stream) and `manifest` key, each only when that part is present, and update its doc. Bless the schemas, regenerate the helper's models, keep `pytest` green, and rewrite the contract page's sections on needs and the context. + +Commit one release line per commit, as CONTRIBUTING.md §Versioning requires (a release-triggering commit that touches `crates/candler-schemas/` touches no other crate): +- the commit named below, with a `BREAKING CHANGE:` footer and its migration path: `context.trace` becomes an object and `ContextRaw` gains a required `sha256`, so a context valid before is invalid now (none was ever written with a trace or raw streams); +- `refactor(adapter-claude-code): …` and `refactor(adapter-opencode): …` for the call sites, if the build needs them in their own commits; +- `feat(evaluator-helper): …` for the regenerated models and the smallest hand-written change; +- `docs(evaluator-protocol): …` for the contract page. +**Deliverables**: `crates/candler-schemas/src/{trace,evaluation}.rs`; `crates/candler-schemas/schema/*.json`; both readers' call sites; `python/candler-evaluator/src/candler_evaluator/_models/`; `docs/contract/evaluator-protocol.md` +**Consistency Checks**: the guards of Step 1 on the tip (expected: PASS) +**Commit**: `feat(schemas)!: carry a shell call's exit and the stored run's needs` + +## Step 3: Bite and verify +**Goal**: Each guard goes red under its named bite. +**Implementation Logic**: +On a scratch branch: type `exit` as a free JSON value and see the trace rows go red; give `raw` a default that accepts any value and see the invalid vectors go red; apply each digest bite in turn. Record each failing message. Delete every `confirm_` test. A fresh Sonnet verifier gets this leaf, the report and the diff, and is asked to find a line or context the wire now reads in two ways, or a digest that changed for a context serving none of the new parts. +**Deliverables**: `__reports__/run-context/leaves/schema_exit_needs_v0.md` +**Consistency Checks**: `git grep -n confirm_ -- crates python` prints nothing (expected: PASS) +**Commit**: `reports(schemas): close the exit field and the new needs` From 0528fd5eaf7191109e17f0ff4f005a112dee73b6 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:06:16 +0900 Subject: [PATCH 03/93] rdm(evaluation): order the schema leaf with M6.5's trace_context Both leaves edit the trace enum, its generated schema and its contract page. The schema leaf now checks first whether trace_context has merged: the second to land rebases and regenerates, and the two land in one release for one minor bump. Its doc gate also says that needs.trace hands a kind the run's instruction texts once the trace holds context_start. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/schema_exit_needs.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/__roadmap__/run_context/schema_exit_needs.md b/__roadmap__/run_context/schema_exit_needs.md index 21cee398..235f7dd6 100644 --- a/__roadmap__/run_context/schema_exit_needs.md +++ b/__roadmap__/run_context/schema_exit_needs.md @@ -4,13 +4,14 @@ **Estimate**: Sonnet, $8, cap $16. 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 feat/run-context HEAD` succeeds +- [ ] `[nl]` The lead checked whether M6.5's `trace_context` leaf (campaign `feat/m6.5-agent-config`) has merged into `origin/main`. That leaf adds `KnownKind::ContextStart` to `crates/candler-schemas/src/trace.rs` and regenerates the same trace schema and contract page. If it has merged, `feat/run-context` is rebased onto it before this leaf starts. If not, this leaf goes ahead, and whichever of the two lands second rebases onto the other and regenerates the schema and pages instead of merging them by hand. Neither leaf bumps a version by hand: the `feat(schemas)` commits set the bump, and the lead lands both in one release when both are ready, so they make one minor bump, not two **Success Gates**: - ⬜ A trace line `{"kind":"tool_result","is_error":true,"exit":{"kind":"code","code":3}}` reads, and the result keeps `exit` when written back. `exit` given as `{"code":3}`, as a string, or on a `tool_call` line is refused. A `tool_result` with no `exit` still reads. On the base, the line with `exit` is refused as an unknown field - ⬜ In the shared wire vectors (`crates/candler-schemas/tests/fixtures/rpc/`), which the Rust reader and the Python helper's `test_guard_wire_vectors.py` both read, a `describe` response whose needs omit `raw` and `manifest` is valid, and one whose needs set `raw` to a non-boolean, or carry an unknown key, is invalid. Both readers decide every vector alike - ⬜ The context digest vectors keep every existing row unchanged and green, and new rows (contexts serving a trace, raw streams, a manifest), written by the independent Python generator over python `rfc8785`, pass. Under the bite "the trace key is always added" the old rows go red; under "the key is left out when served" the new rows go red - ⬜ The marker stays `normalised-trace/1`: the leaf report cites `__design__/architecture.md` §Wire encodings on why an optional field leaves it unchanged, or stops and tells the lead if that section says otherwise - ⬜ The JSON Schemas under `crates/candler-schemas/schema/` and the helper's generated models (`python/candler-evaluator/scripts/gen_models.py`) are regenerated, and the helper's `pytest` passes with the smallest change to its hand-written code that keeps it reading the new shapes; the helper's new API belongs to `readers/helper_context.md` -- ⬜ The doc comments of `Needs`, `RunContext` and `ToolResult` (which reach the schemas) state each need, what each served part reveals of the run (once, with no domain judgement), that `is_error` is not comparable across harnesses for shell calls, and that `exit` is absent for a non-shell, denied or uncoded result. `docs/contract/evaluator-protocol.md`'s generated sections are regenerated, and its Notes stay within the page's 120 words, each with its stamp (CONTRIBUTING.md §Contract pages) +- ⬜ The doc comments of `Needs`, `RunContext` and `ToolResult` (which reach the schemas) state each need, what each served part reveals of the run (once, with no domain judgement; when the trace holds a `context_start` event, the doc next to `needs.trace` says that declaring it hands the kind the run's system text and first message verbatim, which may be the treatment under test), that `is_error` is not comparable across harnesses for shell calls, and that `exit` is absent for a non-shell, denied or uncoded result. `docs/contract/evaluator-protocol.md`'s generated sections are regenerated, and its Notes stay within the page's 120 words, each with its stamp (CONTRIBUTING.md §Contract pages) - ⬜ Both trace readers compile against the new constructor and write no `exit` yet (`readers/` fills it) - `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; helper `uv run pytest`, `uv run ruff check` pass; `container-e2e` is green on the pull request (it touches `crates/**`) **References**: [plan §The exit-status field, §Each need, §Wire shape of a served file, §Test plan](../../__reports__/run-context/00-plan_run_context_v0.md). Code: From abdf7c2259963f762d9d894eb7f84e21b129714f Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:29:31 +0900 Subject: [PATCH 04/93] rdm(evaluation): start level 1 of M6d Run context The maintainer approved the spend cap with the go for level 1. The probe leaf commits under trace-model, since harness is not a scope cog.toml allows. M6.5's trace_context has not merged into origin/main, so the schema leaf goes ahead and whichever lands second rebases. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/README.md | 10 +++++----- __roadmap__/run_context/probe_shell_shapes.md | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/__roadmap__/run_context/README.md b/__roadmap__/run_context/README.md index 16ec0f51..c731c89e 100644 --- a/__roadmap__/run_context/README.md +++ b/__roadmap__/run_context/README.md @@ -9,7 +9,7 @@ An evaluator plug-in that declares `needs.trace`, `needs.raw` or `needs.manifest ## Pre-conditions - [x] `[nl]` The maintainer approved plan v0 (2026-11-25), with its rulings on exit status, one release, and no blinding concept - [x] `[cmd]` `git merge-base --is-ancestor 8d82f63b feat/run-context` succeeds -- [ ] `[nl]` The maintainer approved the campaign's spend cap below before the first dispatch +- [x] `[nl]` The maintainer approved the campaign's spend cap below before the first dispatch (2026-11-25, with the go for level 1) ## Success Gates - ⬜ Every leaf is `done`, and each leaf report records every guard it owns seen red (on the base or under its named bite) and then green, with the failing message @@ -21,8 +21,8 @@ An evaluator plug-in that declares `needs.trace`, `needs.raw` or `needs.manifest ## Status ```mermaid graph TD - schema_exit_needs[Schema: exit and needs]:::planned - probe_shell_shapes[Probe: shell shapes]:::planned + schema_exit_needs[Schema: exit and needs]:::inprogress + probe_shell_shapes[Probe: shell shapes]:::inprogress readers[Readers and serving]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -34,8 +34,8 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `schema_exit_needs.md` | 📄 Leaf Task | ⬜ Planned | -| `probe_shell_shapes.md` | 📄 Leaf Task | ⬜ Planned | +| `schema_exit_needs.md` | 📄 Leaf Task | 🔄 In Progress | +| `probe_shell_shapes.md` | 📄 Leaf Task | 🔄 In Progress | | `readers/` | 📁 Directory | ⬜ Planned | ## Amendment Log diff --git a/__roadmap__/run_context/probe_shell_shapes.md b/__roadmap__/run_context/probe_shell_shapes.md index 2b85e4dc..44ca8d12 100644 --- a/__roadmap__/run_context/probe_shell_shapes.md +++ b/__roadmap__/run_context/probe_shell_shapes.md @@ -20,7 +20,7 @@ On the `parity_e2e.rs` rig, script the fake model to make three `shell`/`Bash` calls in one turn: `exit 3`; `echo oops >&2; exit 2`; and a call that outlives the harness's own shell timeout (set the shortest timeout the harness allows through its configuration, as the rig already configures each harness). Run it once on each harness. Copy the raw stream (Claude Code `stream-json`; OpenCode `stdout.jsonl` and `export.json`) into a fixture directory per harness, named for what it shows, and write each `PROVENANCE.toml` entry. Answer the three questions in the report from those lines only. **Deliverables**: two fixture directories and their provenance entries; the probe's scratch test (deleted in Step 2) **Consistency Checks**: `ls` of both fixture directories shows the stream files (expected: PASS) -**Commit**: `test(harness): record each harness's failing and timed-out shell call` +**Commit**: `test(trace-model): record each harness's failing and timed-out shell call` ## Step 2: Delete the probe, report **Goal**: Only the answer and the fixtures stay. @@ -28,4 +28,4 @@ On the `parity_e2e.rs` rig, script the fake model to make three `shell`/`Bash` c Remove the scratch test and anything it added to the rig. Remove the images and containers the runs built, by id. Write the report: each question, the line that answers it, the rule it implies for `readers/cc_reader_exit.md` and `readers/oc_reader_exit.md`. A fresh Sonnet verifier gets the leaf, the report and the fixtures and checks each quoted line against the fixture file. **Deliverables**: `__reports__/run-context/leaves/probe_shell_shapes_v0.md` **Consistency Checks**: `git diff feat/run-context --stat -- crates/candler/tests` prints nothing (expected: PASS) -**Commit**: `reports(harness): answer how each harness reports a failing shell call` +**Commit**: `reports(trace-model): answer how each harness reports a failing shell call` From 94ffb54e0ee167cb216ebd9566a66e21c1cc3cdf Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:40:10 +0900 Subject: [PATCH 05/93] rdm(evaluation): fold the shell probe's timeout shapes into the readers The probe recorded that Claude Code moves a timed-out command to the background with is_error false, so the Claude Code reader must not give it code 0; a fourth bite guards that. OpenCode kills a timed-out command and writes its signal by name with no exit, so the OpenCode reader gives no exit when metadata.exit is missing, whatever the status. The plan keeps exit absent on a timeout; mapping the signal name waits for a consumer and joins the follow-ups. Co-Authored-By: Claude Opus 5.5 --- __reports__/run-context/00-plan_run_context_v0.md | 5 ++++- __roadmap__/run_context/readers/cc_reader_exit.md | 10 +++++----- __roadmap__/run_context/readers/oc_reader_exit.md | 6 +++--- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/__reports__/run-context/00-plan_run_context_v0.md b/__reports__/run-context/00-plan_run_context_v0.md index bc73fff4..7d394f33 100644 --- a/__reports__/run-context/00-plan_run_context_v0.md +++ b/__reports__/run-context/00-plan_run_context_v0.md @@ -257,7 +257,10 @@ ships in the same release but no gate on that path depends on it. - Claude Code hook denials (`confine_hook`) read as `DeniedBy::Harness`; `user-rejected` too. - OpenCode `permission.rejected` read as a plain error, not a denial. -- Timeout as a distinct shell end, if a consumer asks (no harness evidence yet). +- Timeout as a distinct shell end, if a consumer asks. The probe recorded the evidence: Claude Code moves a + timed-out command to the background (`backgroundTaskId`, `timedOutAfterMs`, `is_error: false`); OpenCode + kills it and writes `signal: "SIGTERM"`, `timeout: true` and no `exit`. Mapping that signal name into + `ExitStatus`'s integer `signal` waits for the same consumer. ## Done-criteria diff --git a/__roadmap__/run_context/readers/cc_reader_exit.md b/__roadmap__/run_context/readers/cc_reader_exit.md index 386559cc..47d43b86 100644 --- a/__roadmap__/run_context/readers/cc_reader_exit.md +++ b/__roadmap__/run_context/readers/cc_reader_exit.md @@ -1,15 +1,15 @@ # Claude Code exit -**Goal**: A `Bash` call in a Claude Code trace carries the exit status Claude Code reported: `exit: {kind: code, code: N}` when the result's content starts with `Exit code N`, `{kind: code, code: 0}` when the result is not an error, and no `exit` for an interrupted call, a denial, any other error text, or any tool that is not `Bash`. The call's name comes from the call joined on `(session, span)` (critical path) +**Goal**: A `Bash` call in a Claude Code trace carries the exit status Claude Code reported: `exit: {kind: code, code: N}` when the result's content starts with `Exit code N`, `{kind: code, code: 0}` when the result is not an error and Claude Code did not move the command to the background, and no `exit` for a call its timeout moved to the background (the result's `tool_use_result` carries `backgroundTaskId` or `timedOutAfterMs`, with `is_error: false`, as the probe recorded), an interrupted call, a denial, any other error text, or any tool that is not `Bash`. The call's name comes from the call joined on `(session, span)` (critical path) **Estimate**: Sonnet, $6, cap $12. 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 feat/run-context HEAD` succeeds - [ ] `[nl]` `../schema_exit_needs.md` and `../probe_shell_shapes.md` are `done`; the probe report's answer to question (3) (the prefix with stderr only) and to question (2) (a code on timeout) are read before Step 1 **Success Gates**: -- ⬜ `guard_reader.rs::expected_facts` reads new `exits` rows from each fixture's `expected.toml`, written from `jq` over the raw lines and never from the reader's output. The rows cover: a `Bash` call that exited 0; nonzero exits (1 and 127 in the real fixtures); a denial; a call to a tool that is not `Bash` (for example `Read`); a call in a child session; and the probe's stderr-only and timed-out calls. On the base every `exits` row with a code fails -- ⬜ Each of three bites turns the guard red, and the report records the failing message: (a) the prefix parse removed; (b) code 0 given to every non-error result, `Read` included; (c) the call joined on span without the session +- ⬜ `guard_reader.rs::expected_facts` reads new `exits` rows from each fixture's `expected.toml`, written from `jq` over the raw lines and never from the reader's output. The rows cover: a `Bash` call that exited 0; nonzero exits (1 and 127 in the real fixtures); a denial; a call to a tool that is not `Bash` (for example `Read`); a call in a child session; and the probe's stderr-only call (`Exit code 2` followed by the stderr text) and timed-out call (no `exit`, although `is_error` is false). On the base every `exits` row with a code fails +- ⬜ Each of four bites turns the guard red, and the report records the failing message: (a) the prefix parse removed; (b) code 0 given to every non-error result, `Read` included; (c) the call joined on span without the session; (d) the background check removed, so the probe's timed-out call reads code 0 - ⬜ Rows with a code are added only to fixtures that a real Claude Code wrote, as their provenance records (the probe's among them). A synthetic fixture made by `make_synthetic.py` gets an `exits` row only where it states an absence, since a hand-built line cannot say what Claude Code writes -- ⬜ `parse.rs` reads only the result's `is_error` and the start of its first text content for this, and never infers a signal from a code +- ⬜ `parse.rs` reads only the result's `is_error`, the first line of its first text content, and the presence of `backgroundTaskId` or `timedOutAfterMs` in `tool_use_result` for this; it never reads the background task's later summary text and never infers a signal from a code - `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; `container-e2e` is green on the pull request **References**: [plan §The exit-status field, §Test plan](../../../__reports__/run-context/00-plan_run_context_v0.md); `__reports__/run-context/leaves/probe_shell_shapes_v0.md`. Code: - `crates/candler-harness-claude-code/src/parse.rs`: `block_draft` and the `tool_result` handling, `tool_call`; @@ -27,7 +27,7 @@ Extend `expected_facts` to compare a list of `(span, exit)` from the reader with ## Step 2: Read the exit **Goal**: The guard passes. **Implementation Logic**: -When a `tool_result` block pairs with a `Bash` call of the same session, set `exit` by the rule in the Goal. The prefix is `Exit code ` followed by a decimal `i32` at the start of the first text content; anything else in an error result gives no `exit`. A denial (`tool_result_meta` non-execution) and `interrupted: true` give no `exit` whatever the content. +When a `tool_result` block pairs with a `Bash` call of the same session, set `exit` by the rule in the Goal. The prefix is `Exit code ` followed by a decimal `i32` at the start of the first text content; anything else in an error result gives no `exit`. A denial (`tool_result_meta` non-execution), `interrupted: true`, and a result moved to the background (`backgroundTaskId` or `timedOutAfterMs` in `tool_use_result`) give no `exit` whatever the content. **Deliverables**: `crates/candler-harness-claude-code/src/parse.rs` **Consistency Checks**: `expected_facts` on the tip (expected: PASS) **Commit**: `feat(adapter-claude-code): read a Bash call's exit status` diff --git a/__roadmap__/run_context/readers/oc_reader_exit.md b/__roadmap__/run_context/readers/oc_reader_exit.md index 07b5d3d7..93372e8a 100644 --- a/__roadmap__/run_context/readers/oc_reader_exit.md +++ b/__roadmap__/run_context/readers/oc_reader_exit.md @@ -1,14 +1,14 @@ # OpenCode exit -**Goal**: A `shell` call in an OpenCode trace carries the exit status OpenCode reported: `exit: {kind: code, code: N}` from the tool part's `state.metadata.exit` (the rule for a nonzero exit is the one the probe recorded), and no `exit` when the part's state is an error (`aborted`, `permission.rejected`, …), when `metadata.exit` is missing, or for any tool that is not `shell` (critical path) +**Goal**: A `shell` call in an OpenCode trace carries the exit status OpenCode reported: `exit: {kind: code, code: N}` from the tool part's `state.metadata.exit` (the rule for a nonzero exit is the one the probe recorded), and no `exit` when the part's state is an error (`aborted`, `permission.rejected`, …), when `metadata.exit` is missing whatever `state.status` says (the probe's timed-out call is `completed` with `signal: "SIGTERM"`, `timeout: true` and no `exit`), or for any tool that is not `shell`. The plan rules `exit` absent on a timeout, so the reader does not map the harness's signal name into `ExitStatus`'s integer `signal` (critical path) **Estimate**: Sonnet, $5, cap $10. 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 feat/run-context HEAD` succeeds - [ ] `[nl]` `../schema_exit_needs.md` and `../probe_shell_shapes.md` are `done`; the probe report's answers to questions (1) and (2) are read before Step 1. If the probe found that OpenCode writes a nonzero exit somewhere other than `state.metadata.exit`, the rule follows the probe and the report says so **Success Gates**: - ⬜ The export reader's table `opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions` gains an `exit` column, written from `jq` over the exports and never from the reader's output. Its rows cover: a completed `shell` call with exit 0 (`completed_o1`); a completed call with a nonzero exit, a stderr-only nonzero exit and a timed-out call (the probe's fixture); an aborted call (`sigint_mid_tool` or `interrupt_api`); a rejected permission (`oc_permission_ask`); a tool that is not `shell`. On the base every row with a code fails -- ⬜ Each of two bites turns the table red, and the report records the failing message: (a) `metadata.exit` read only on error states; (b) a missing `metadata` taken as exit 0 -- ⬜ `export.rs` never infers a signal from a code and never reads an exit from the tool's text output +- ⬜ Each of two bites turns the table red, and the report records the failing message: (a) `metadata.exit` read only on error states; (b) a missing `metadata.exit` taken as exit 0, so the probe's timed-out row reads code 0 +- ⬜ `export.rs` never infers a signal from a code, never reads an exit from the tool's text output (OpenCode renders `Exit code: 143 (SIGTERM)` there for the model), and reads no `signal` or `timeout` key - `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; `container-e2e` is green on the pull request **References**: [plan §The exit-status field, §Test plan](../../../__reports__/run-context/00-plan_run_context_v0.md); `__reports__/run-context/leaves/probe_shell_shapes_v0.md`. Code: - `crates/candler-harness-opencode/src/export.rs`: `tool_drafts`; From 37e1a159872b9c84affe7cd96337e355b1908709 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:38:00 +0900 Subject: [PATCH 06/93] test(trace-model): record each harness's failed and timed-out shell call Real Claude Code 2.1.311 and real OpenCode 2.2.7, each on the parity rig, ran one scripted turn of three shell calls: exit 3, a stderr-only exit 2, and a sleep that outlives a 1000 ms timeout. Their raw streams are kept as reader fixtures with provenance. The scratch test and the fake-model script that produced them ride in this commit and are removed by the next one. Co-Authored-By: Claude Sonnet 5.5 --- assets/docker/fakemodel/fakemodel.py | 14 ++ .../tests/fixtures/PROVENANCE.toml | 32 +++ .../agent_stream.jsonl.gz | Bin 0 -> 3496 bytes .../shell_exit_stderr_timeout/expected.toml | 17 ++ .../usage_totals.toml | 13 ++ .../tests/fixtures/PROVENANCE.toml | 18 ++ .../shell_exit_stderr_timeout/export.json | 219 ++++++++++++++++++ .../shell_exit_stderr_timeout/stdout.jsonl | 10 + .../tests/it/guard_cli_e2e/parity_e2e.rs | 140 +++++++++++ 9 files changed, 463 insertions(+) create mode 100644 crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/agent_stream.jsonl.gz create mode 100644 crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml create mode 100644 crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/usage_totals.toml create mode 100644 crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/export.json create mode 100644 crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/stdout.jsonl diff --git a/assets/docker/fakemodel/fakemodel.py b/assets/docker/fakemodel/fakemodel.py index d238ac8a..02bcec77 100644 --- a/assets/docker/fakemodel/fakemodel.py +++ b/assets/docker/fakemodel/fakemodel.py @@ -138,6 +138,20 @@ def script_blocks(model, state, tools, messages): 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("sh1"): + shell = [n for n in tools if n in ("Bash", "shell", "bash")] + if state == "prompt" and shell: + calls = [ + {"type": "tool_use", "id": "toolu_fake_sh_exit3", "name": shell[0], + "input": {"command": "exit 3", "description": "exit 3"}}, + {"type": "tool_use", "id": "toolu_fake_sh_stderr", "name": shell[0], + "input": {"command": "echo oops >&2; exit 2", "description": "stderr only"}}, + {"type": "tool_use", "id": "toolu_fake_sh_timeout", "name": shell[0], + "input": {"command": "python3 -c 'import time; time.sleep(30)'", "description": "outlives timeout", "timeout": 1000}}, + ] + return [{"type": "text", "text": "I will run three shell calls."}] + calls, \ + "tool_use", "sh1-calls" + return [{"type": "text", "text": "done"}], "end_turn", "sh1-text" if model.startswith("c2"): return [{"type": "text", "text": "hello"}], "end_turn", "c2-hello" if model.startswith("c3"): diff --git a/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml b/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml index 7ae76e0d..22fc7059 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml @@ -240,3 +240,35 @@ path = "sessions/c2/timings.toml" source = "recorded: Claude Code 2.1.311 against assets/docker/fakemodel, see sessions/PROVENANCE.toml" sha256 = "e1fd828f6621aeb731ea1564b9dfe7a16bb2e2de7a3c31612925220c11bf4600" synthetic = false + +# Recorded on 2026-11-25 by real Claude Code 2.1.311 on the parity rig +# (crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs: the production gateway sidecar, the scripted +# fake model, bypassPermissions, one cell), image candler-env:...-src-83c18228eddb-env-e7ca5eaba54a +# (sha256:57f339fc3580d09e8f0c9284d2177449c476f31e8bcd092dcdc631c3b3ea2a48, on candler-base +# candler.cc_version=2.1.311). Docker 29.9.2, Docker Desktop on macOS. No token was spent. +# The fake model is the fakemodel.py of the repository with one extra script, model id sh1, kept +# outside the repository: the first prompt is answered with one assistant message holding three +# Bash calls, toolu_fake_sh_exit3 {command: "exit 3"}, toolu_fake_sh_stderr {command: +# "echo oops >&2; exit 2"} and toolu_fake_sh_timeout {command: "python3 -c 'import time; +# time.sleep(30)'", timeout: 1000}; any later request is answered "done". The timeout is the Bash +# tool's own input field in milliseconds, the shortest the rig's configuration gives (the rig sets +# no default). A bare "sleep 30" was refused by Claude Code itself ("Blocked: standalone sleep 30"), +# hence the Python sleep. The stream is the harness's stdout, each raw frame's text as one line. + +[[files]] +path = "streams/shell_exit_stderr_timeout/agent_stream.jsonl.gz" +source = "real Claude Code 2.1.311 stream-json, probe_shell_shapes, 2026-11-25" +sha256 = "9ac94aaf71539045fcbac4f2994df5491f9bf311137317e4a740f7f596f5a35a" +synthetic = false + +[[files]] +path = "streams/shell_exit_stderr_timeout/expected.toml" +source = "hand-written from jq over the raw lines" +sha256 = "fac1f66effd975731684ab68d59c8fb1b42b76e7f0a4c2b359aa7e435a7b8e55" +synthetic = false + +[[files]] +path = "streams/shell_exit_stderr_timeout/usage_totals.toml" +source = "usage_totals.jq" +sha256 = "df78975da8a46ba3ac67f3a6d64767bd0569846e0b65ac690177c79de9e68a0e" +synthetic = false diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/agent_stream.jsonl.gz b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/agent_stream.jsonl.gz new file mode 100644 index 0000000000000000000000000000000000000000..432253128e96b2654fc50c4e6d29c42b95869e8e GIT binary patch literal 3496 zcmV;Z4Oj9XiwFP!000021MM1FZzH$)y}x3hhb93`dG5mjiYB{Tz-TuKvKuU#CKzx? zj>LMd4ms8;hW~rNkDM7vws%+AtlFTJAFSd1-4}Vc(A!Qdt`=&mw5S&s3pEsDmu#el z4z}UYxZJe;4Gs&XWZUEtJ9$)=ktiAASs0KorSu zUQ>m8d`;CFexCJh^Q;$Ci?Q)sRAO%YO)5P7xlnS|yxKMl8ZWqk=tZMN{|4aEy};=& z-b%gK#FbyIM57fnUbcWm+r!s4trkVw-i(`kFDN%ZUEAxw$cD>ig$rJ>wctY~-q0H{ zbl4#p{t~dJE8P6mjjSs8MO0qt7AL$0^j-@XD&);AbxZ$)7J4 zHS2OE`diT>aj>K1qC#G*J($;tzLtjAFQFg0i)}}h`flzH4SFIEEB5Mkc?GyfZb>(p|KfhL+GH_Z4Z2a&VFd@f1;4$ z1o$a>YB%YsVI`Y`>2%^ZbhZQuNtDorf7k;A>L@ePTmeN4HdSkX=aC8XcF^6RiPGCj z*nTbE;tWxiAS;L|HL_W@Y``6fVGQ>pBIZf?|~^m+|5o3W~6}<4OGv!hJxL+ zjhKZZM>)$;DL{l^&|iAX!1HFltz?G)9B0v@~>_ z*!aZ!KTp%{FP_*|gT1eX?zcy7JI{arwojOcV|IVIYwDCv{?zhHwfAcdnhAx*ar8^;otr~ z(;oRCbKnNGz0goYU()?qj8+vc1}z0_bq>}uH#QNcpcw!|velBQoJ&QE3Lv>EX{7`( ztZ(_iV2KdCpzP-HjA1Y#2#x*1EvX;@rwIvZNlC^zL?n@)#Q_z8Ta*Y67~p=JqZ|PL z?u=8wsAk>P;?jug<=v!L+(G=K9jEyaZ8OfLN@I@jDEOD2Ipw^c4oU1aSZ* zvr>XC-2@IGO~49vBXmAW;-#*;OOQS6RhQ`!e@Dk+NR*>>LiudV@}PgB19CVQc`Ih>p%pS4?iteiKio~xAjBCUAJq7WdW?O5YKGz{ zktK*%j%*(1*K>T-x7DK!4#FDaPN5$S&A57Wujc1!aqVotU^!sA9KD8!&QWUtZ4@T8 zG|H$T?wav$hN>F76e>o8YHd4*8SVxhhXx;q7S40s*_q6JsNxX${5VL<~zBTh*w zcp5}*nue}>gv2DS`@5AGr8zj#qeO9V2eOcOY&6UwR*p9l&%vo1s+_vL72MG+q|CzE5!3nn z`uUYJGxUq4^R0;o9I2c_$Y$kida2=PSbF8yqJ%9iVi4kuC6Hr?c4^e;az1Kl1COQi z_ja%eeIXDbSxNwOvlfWTjGbCK*CloUTuP7We}nMRQj6a4+}e@N1LQ7n!L&67Mjh;o z1lc}uBphINpZ0Cq&6UGjLt~=^4t10OK5zi4+X95L5_kYC*oUrZovH=P(L0S0AgmYW zWDAL2JJYq$()k7w3`^@Z;SX|xZO5@`M}l=Y@(^GE*wT1=LW(~L#q*h5>XL#r?<|~0CmmS7{tP0 zBh?x?@Va#%@?$rSDM-qCJ``ly!Rs0TSCozGhXxj*<*@WCl=GKrjQ)>zsXN1RTAzAUg65y5BFOQ6=$sH)KU~Ic zR6=a$r4Y)8tcVG9JxV<8i7-xMFV4Iplpu@7goqElMVodquaO{e`hd_2ysf}m@<(6) zYpj{KN&^{Sox23r62Fs6zU%%Lo;>1k_^=Dq18t?b2SA^CgXQ^sp4vN?$Qs4`Vd4v_=fs}Z``oeQe7#3t zgBALS>;1{oz_StChl88xg~a#!G(}1I;nnkC3|>8-05#x#4&zd!@gFxMI7o7=2B_{$b$Q+(7Kn zfO&mjvKvXOkz?~M`>cXfpu|7vB@rY8=I+aEWb{FGbkm@;xbrDbEUhFj? zMiP3Ie4A0=Ne|WlzW~h+@4wuO>7=~a<`Wnb`zKV*L7=JQC*EUQV60`eCu1CL_Ols| zfuR>A^mFU};K00+wbbM84I6sYnC)I~G4R!d003mY&>gZ!QBZFHQDdfyQy+vo;Q5Ez zSVz=^{rn2zG6vRiVV*nKHMxCrFu8#_wdVE#gw~}tHrRK=*^$mU!fdI{j4+O7pO6X~ zmT?i1)E9z;SSc$w_le-H#}YpaL5rsCl?Iup$5R69D8QiP^QAJnfB=p+0-TS&IWHk9 z6}wgAwYIrnWWZoO3XBO?KuyJ4%W-qrYwUckBpRs-Wppp%I$M}iT9_jW0QT9+#})uO z^K`|8&Q`Dw43&u+B$m*bTz?Am=^r#T?(_&7?x%0W0 z%Y5z^d)LmTo28K#lQ<0uOu;yzEOiMFl2W8JVP4>#fMG{e?{?+1q=*X$h67RraYRDF zAVQ7`PFyc66G4k2J4re1{95+>TK4=}_WWA*{95+>TK4=}_WWA*cllbjjAK8bkR-;O zh9u;n4>==N)IF98h(Em44bHD+Px4weIM>EcUK`I?>_N&%ct|1g=b1}rQUt^;(=aTH z7}9{?{k8Gv%8i$96u+Z3?g##Vpf>J@?!lk`ex`lGQn`OFm4CugdGNT96`!(@^@QA< zE9WPwoLlFHEC+h=v8F^G)Re4Swo+|v1JO38he-4K9c88ab6NgVm*u@rRF+S&4^-vT zaQ9fD2;4IEIPsaAk}!&~Chvk*Dw4!!B1t)aswSVLPnYC<@7)!71nZcBy!Vj>dGE0u W^G|8V-1L9AApdW;Spv^-KL7xsCB4o7 literal 0 HcmV?d00001 diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml new file mode 100644 index 00000000..580b5b59 --- /dev/null +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml @@ -0,0 +1,17 @@ +# Hand-written from the raw lines with jq. Recorded by real Claude Code on the parity rig: one turn +# of three Bash calls (`exit 3`; `echo oops >&2; exit 2`; a Python sleep with `timeout: 1000`), +# then a second turn that starts when the backgrounded sleep ends. No denial, no subagent. +stream = "agent_stream.jsonl.gz" +frames = 18 +blank_frames = [] +non_json_frames = [] +subagent_ids = [] +denials = [] +mcp_calls = [] +frame_sessions = [] +cost_reporting = "running" +tokens_reporting = "per_turn" + +[[sessions]] +id = "d5ff5efc-d943-44df-a357-f087b8668786" +ended_by = "completed" diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/usage_totals.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/usage_totals.toml new file mode 100644 index 00000000..7ea75627 --- /dev/null +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/usage_totals.toml @@ -0,0 +1,13 @@ +[message."d5ff5efc-d943-44df-a357-f087b8668786"] +input_tokens = 300 +output_tokens = 3 +cache_read_tokens = 0 +cache_creation_tokens = 0 + +[session_total."d5ff5efc-d943-44df-a357-f087b8668786"] +input_tokens = 300 +output_tokens = 60 +cache_read_tokens = 0 +cache_creation_tokens = 0 +cost_usd = 0.0024000000000000002 + diff --git a/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml b/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml index bc68afcb..9b8cc3b1 100644 --- a/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml +++ b/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml @@ -186,3 +186,21 @@ run = "3333333333333333333333333333333333333333333333333333333333333333-r1-a1" log = "crates/candler-core/tests/fixtures/gateway/census_log.txt" log_sha256 = "55ac88272a5bd76ed130f13d8e872586bda81c048215d8226a58d5084f834a36" synthetic = true + +# shell_exit_stderr_timeout (probe_shell_shapes, 2026-11-25): real OpenCode 2.2.7 on the parity rig +# (crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs: the production gateway sidecar, the scripted +# fake model, --auto), image candler-env:...-src-b062c666af0a-env-e7ca5eaba54a +# (sha256:e287badacc755d5f2d0de612340f4efe8ab52b9f68ead85b8db2a5abb65b0d64, on candler-base +# candler.cc_version=2.2.7). Docker 29.9.2, Docker Desktop on macOS. No token was spent. +# Fake model: the repository's fakemodel.py with one extra script, model id sh1, kept outside the +# repository: the first prompt is answered with one assistant message holding three shell calls, +# toolu_fake_sh_exit3 {command: "exit 3"}, toolu_fake_sh_stderr {command: "echo oops >&2; exit 2"} +# and toolu_fake_sh_timeout {command: "python3 -c 'import time; time.sleep(30)'", timeout: 1000}; +# any later request is answered "done". The timeout is the shell tool's own input field in +# milliseconds. stdout.jsonl is each raw frame's text of the harness's stdout as one line; +# export.json is the text of the one frame of the export stream. The single `retry` line in stdout is +# a 429 the gateway answered to the run's first model request; the retry succeeded. +[stream.shell_exit_stderr_timeout] +model = "fake" +stdout_sha256 = "40445d8d5a3ff50322f8c57f986edb5c5e26cd02ddfbbd2bba6c3be36a8addfb" +export_sha256 = "ebadedd16e3bbcd6597251af0bbb2ff62c994d0aa913196fa6bb6102c7695fc1" diff --git a/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/export.json b/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/export.json new file mode 100644 index 00000000..0a39d5f7 --- /dev/null +++ b/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/export.json @@ -0,0 +1,219 @@ +{ + "info": { + "id": "ses_dee27c7a8ffe6tHUOiSdJDTWaO", + "projectID": "bc7447dce6aa45fd13129230dddc6abeb62cb974", + "model": { + "id": "sh1", + "providerID": "candler", + "variant": "default" + }, + "cost": 0, + "tokens": { + "input": 300, + "output": 60, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + }, + "outcome": "succeeded", + "time": { + "created": 1795595712887, + "updated": 1795595716486, + "busy": 1795595713150, + "idle": 1795595716491 + }, + "title": "done", + "location": { + "directory": "/work" + } + }, + "messages": [ + { + "id": "msg_211d8399900101Y00e0pzrSXwG", + "time": { + "created": 1795595713171 + }, + "text": "Run the three shell calls, then reply done.", + "files": [], + "type": "user" + }, + { + "id": "msg_211d83aae001AL9qnBRsPxMIyk", + "time": { + "created": 1795595715251, + "streamed": 1795595715354, + "completed": 1795595716394 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "sh1", + "providerID": "candler", + "variant": "default" + }, + "content": [ + { + "type": "text", + "text": "I will run three shell calls." + }, + { + "type": "tool", + "id": "toolu_fake_sh_exit3", + "name": "shell", + "executed": false, + "state": { + "status": "completed", + "input": { + "command": "exit 3", + "description": "exit 3" + }, + "content": [ + { + "type": "text", + "text": "(no output)" + }, + { + "type": "text", + "text": "Exit code: 3" + } + ], + "metadata": { + "status": "completed", + "truncated": false, + "exit": 3 + } + }, + "time": { + "created": 1795595715316, + "ran": 1795595715324, + "completed": 1795595715373 + } + }, + { + "type": "tool", + "id": "toolu_fake_sh_stderr", + "name": "shell", + "executed": false, + "state": { + "status": "completed", + "input": { + "command": "echo oops >&2; exit 2", + "description": "stderr only" + }, + "content": [ + { + "type": "text", + "text": "oops\n" + }, + { + "type": "text", + "text": "Exit code: 2" + } + ], + "metadata": { + "status": "completed", + "truncated": false, + "exit": 2 + } + }, + "time": { + "created": 1795595715326, + "ran": 1795595715333, + "completed": 1795595715383 + } + }, + { + "type": "tool", + "id": "toolu_fake_sh_timeout", + "name": "shell", + "executed": false, + "state": { + "status": "completed", + "input": { + "command": "python3 -c 'import time; time.sleep(30)'", + "description": "outlives timeout", + "timeout": 1000 + }, + "content": [ + { + "type": "text", + "text": "(no output)" + }, + { + "type": "text", + "text": "Command timed out after 1 seconds. If it needs longer and isn't waiting for input, rerun with a larger timeout.\nExit code: 143 (SIGTERM)" + } + ], + "metadata": { + "status": "completed", + "truncated": false, + "signal": "SIGTERM", + "timeout": true + } + }, + "time": { + "created": 1795595715336, + "ran": 1795595715350, + "completed": 1795595716390 + } + } + ], + "finish": "tool-calls", + "rawFinish": "tool_use", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_211d8473c001mKKMTC6sFSMc9e", + "time": { + "created": 1795595716420, + "streamed": 1795595716484, + "completed": 1795595716486 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "sh1", + "providerID": "candler", + "variant": "default" + }, + "content": [ + { + "type": "text", + "text": "done" + } + ], + "finish": "stop", + "rawFinish": "end_turn", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_211d8478b00142ClyXBTwu684i", + "time": { + "created": 1795595716491 + }, + "type": "idle", + "outcome": "succeeded" + } + ] +} + diff --git a/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/stdout.jsonl b/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/stdout.jsonl new file mode 100644 index 00000000..d4db6bef --- /dev/null +++ b/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/stdout.jsonl @@ -0,0 +1,10 @@ +{"type":"step_start","timestamp":1795595713237,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"id":"prt_211d83ad5001M5pDoBsj62qgHk","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d83aae001AL9qnBRsPxMIyk","type":"step-start"}} +{"type":"retry","timestamp":1795595713246,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d83aae001AL9qnBRsPxMIyk","attempt":2,"nextRetryAt":1795595715224,"error":{"type":"provider.rate-limit","message":"Provider request failed with HTTP 429","status":429,"response":{"body":"\r\n429 Too Many Requests\r\n\r\n

429 Too Many Requests

\r\n
nginx/1.28.3
\r\n\r\n\r\n"}}} +{"type":"text","timestamp":1795595715312,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"id":"prt_211d842eb001fLHU8EWqkRxCO3","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d83aae001AL9qnBRsPxMIyk","type":"text","text":"I will run three shell calls.","time":{"start":1795595715307,"end":1795595715312}}} +{"type":"tool_use","timestamp":1795595715373,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"partID":"prt_211d842f4001TMw71eZXnFDZWB","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d83aae001AL9qnBRsPxMIyk","type":"tool","id":"toolu_fake_sh_exit3","tool":"shell","state":{"status":"completed","input":{"command":"exit 3","description":"exit 3"},"output":"(no output)","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":3},"content":[{"type":"text","text":"(no output)"},{"type":"text","text":"Exit code: 3"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\": \"exit 3\", \"description\": \"exit 3\"}"},"time":{"start":1795595715316,"end":1795595715373}}}} +{"type":"tool_use","timestamp":1795595715383,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"partID":"prt_211d842fe0012U4662ystlN1hC","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d83aae001AL9qnBRsPxMIyk","type":"tool","id":"toolu_fake_sh_stderr","tool":"shell","state":{"status":"completed","input":{"command":"echo oops >&2; exit 2","description":"stderr only"},"output":"oops\n","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":2},"content":[{"type":"text","text":"oops\n"},{"type":"text","text":"Exit code: 2"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\": \"echo oops >&2; exit 2\", \"description\": \"stderr only\"}"},"time":{"start":1795595715326,"end":1795595715383}}}} +{"type":"tool_use","timestamp":1795595716390,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"partID":"prt_211d843080018O6qKNGI6Ippop","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d83aae001AL9qnBRsPxMIyk","type":"tool","id":"toolu_fake_sh_timeout","tool":"shell","state":{"status":"completed","input":{"command":"python3 -c 'import time; time.sleep(30)'","description":"outlives timeout","timeout":1000},"output":"(no output)","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"signal":"SIGTERM","timeout":true},"content":[{"type":"text","text":"(no output)"},{"type":"text","text":"Command timed out after 1 seconds. If it needs longer and isn't waiting for input, rerun with a larger timeout.\nExit code: 143 (SIGTERM)"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\": \"python3 -c 'import time; time.sleep(30)'\", \"description\": \"outlives timeout\", \"timeout\": 1000}"},"time":{"start":1795595715336,"end":1795595716390}}}} +{"type":"step_finish","timestamp":1795595716394,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"id":"prt_211d8472a001RPeG5416Zyt9Iu","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d83aae001AL9qnBRsPxMIyk","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":100,"output":20,"reasoning":0,"cache":{"read":0,"write":0}}}} +{"type":"step_start","timestamp":1795595716471,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"id":"prt_211d84777001qG5atV1uJcK0ht","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d8473c001mKKMTC6sFSMc9e","type":"step-start"}} +{"type":"text","timestamp":1795595716480,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"id":"prt_211d8477c001wx8VMjIBG8mbWZ","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d8473c001mKKMTC6sFSMc9e","type":"text","text":"done","time":{"start":1795595716476,"end":1795595716480}}} +{"type":"step_finish","timestamp":1795595716486,"sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","part":{"id":"prt_211d847860011hL6YeyDzXF26X","sessionID":"ses_dee27c7a8ffe6tHUOiSdJDTWaO","messageID":"msg_211d8473c001mKKMTC6sFSMc9e","type":"step-finish","reason":"stop","cost":0,"tokens":{"input":100,"output":20,"reasoning":0,"cache":{"read":0,"write":0}}}} diff --git a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs index e2734028..0ad5ebe4 100644 --- a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs @@ -184,6 +184,12 @@ fn run_once( .map(|entry| entry.path()) .find(|path| path.join("run.done").is_file()) .unwrap_or_else(|| panic!("a sealed run\n{log}")); + if let Ok(out) = std::env::var("PROBE_OUT") { + let dest = Path::new(&out).join(place.1.replace('/', "_")); + fs::create_dir_all(&dest).unwrap(); + let status = Command::new("cp").arg("-R").arg(&run_dir).arg(&dest).status().unwrap(); + assert!(status.success()); + } let inspected = Command::new(env!("CARGO_BIN_EXE_candler")) .arg("inspect") .arg(&run_dir) @@ -408,3 +414,137 @@ fn parity_one_installed_server_one_traced_call() { eprintln!("parity: {:?} wall", started.elapsed()); assert!(failures.is_empty(), "{failures:#?}"); } + +#[test] +#[ignore = "needs Docker; run with --run-ignored only"] +fn probe_shell_shapes_scratch() { + 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:probe-{}", std::process::id()); + must( + &real, + &[ + "build", + "-q", + "--label", + "candler.test=probe", + "-t", + &tag, + context, + ], + ); + made.images.push(must( + &real, + &["image", "inspect", "--format", "{{.Id}}", &tag], + )); + let fake = must( + &real, + &[ + "run", + "-d", + "--label", + "candler.test=probe", + "-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\"", "\"sh1\"") + .replace( + "say hello", + "Run the three shell calls, then reply done.", + ) + .replace("wall_s = 30", "wall_s = 300") + .replacen( + "[harness]\nname = \"claude-code\"", + "[harness]\nname = \"@HARNESS@\"", + 1, + ) + }; + 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 failures: Vec = 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); + eprintln!("{harness}: {} calls, {} answers", seen.origins.len(), answers.len()); + if let Ok(out) = std::env::var("PROBE_OUT") { + fs::write(Path::new(&out).join(format!("records_{harness}.jsonl")), records(&real, &fake)).unwrap(); + } + } + drop(made); + assert_eq!( + must(&real, &["ps", "-aq"]), + before, + "no container is left behind" + ); + eprintln!("parity: {:?} wall", started.elapsed()); + assert!(failures.is_empty(), "{failures:#?}"); +} From 222f147c1b62c29ea0b36be5a12b568870694919 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:38:45 +0900 Subject: [PATCH 07/93] reports(trace-model): how each harness reports a failed shell call Removes the scratch test and the fake-model script from the rig, and records what the recorded streams show: OpenCode writes the code in metadata.exit, Claude Code prefixes the content with Exit code N, and neither gives a code on its own timeout. Co-Authored-By: Claude Sonnet 5.5 --- .../leaves/probe_shell_shapes_v0.md | 112 ++++++++++++++ assets/docker/fakemodel/fakemodel.py | 14 -- .../tests/it/guard_cli_e2e/parity_e2e.rs | 140 ------------------ 3 files changed, 112 insertions(+), 154 deletions(-) create mode 100644 __reports__/run-context/leaves/probe_shell_shapes_v0.md diff --git a/__reports__/run-context/leaves/probe_shell_shapes_v0.md b/__reports__/run-context/leaves/probe_shell_shapes_v0.md new file mode 100644 index 00000000..a13cc84d --- /dev/null +++ b/__reports__/run-context/leaves/probe_shell_shapes_v0.md @@ -0,0 +1,112 @@ +# Probe P-shell: how each harness reports a failing shell call + +Recorded on 2026-11-25 on the `parity_e2e.rs` rig: real Claude Code 2.1.311 and real OpenCode 2.2.7, +each in its agent base image, behind the production gateway sidecar, against the scripted fake model +(model `sh1`, one turn of three shell calls: `exit 3`; `echo oops >&2; exit 2`; +`python3 -c 'import time; time.sleep(30)'` with the tool's own `timeout: 1000`, in milliseconds). +No token was spent. The streams are the harnesses' stdout, one raw frame's text per line. + +Fixtures (provenance in each harness's `tests/fixtures/PROVENANCE.toml`): + +- `crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/agent_stream.jsonl.gz` +- `crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_stderr_timeout/stdout.jsonl` and `export.json` + +Every line below is quoted from those files (line numbers are the fixture's). + +| Q | Answer in one line | Decision | +|---|---|---| +| 1 | OpenCode writes `status: completed` with the code in `metadata.exit` | the OpenCode reader takes `exit` from `metadata.exit` whatever the status | +| 2 | Neither gives a code on its own timeout, and the shapes differ | `exit` stays absent on a timeout; one guard, below, that a timeout never reads as code 0 | +| 3 | Yes: `Exit code N` leads the content, stdout empty or not | the Claude Code prefix rule holds; stderr text follows it | + +## 1. OpenCode, a nonzero exit + +`stdout.jsonl` line 4 (the `tool_use` event; `state.metadata.metadata` is the one that matters, the outer +`metadata` also carries `content`, `providerCall`, `rawInput`): + + {"status":"completed","truncated":false,"exit":3} + +`export.json` lines 67 and 83-86 (the same call, the export reader's input): `state.status` is `"completed"` (line 67) and +`state.metadata` holds `"exit": 3` (line 85). `state.error` is absent. The content blocks end with +`"Exit code: 3"`. The plan's expectation (`completed`, `metadata.exit: N`) holds. + +Reader rule for `oc_reader_exit`: a `shell` result with `state.metadata.exit` an integer gives `exit = code N`, +whatever `state.status` says (`completed` here). Read it in the export (`state.metadata.exit`); the live +`stdout.jsonl` event nests it one level deeper (`state.metadata.metadata.exit`) and is not the reader's input. +No `exit` key gives no exit (a missing `metadata` is not code 0). + +## 3. Claude Code, stderr only (question 3 before 2) + +`agent_stream.jsonl.gz` line 6, `exit 3`: + + "content":"Exit code 3","is_error":true (tool_use_result: "Error: Exit code 3") + +Line 7, `echo oops >&2; exit 2`: + + "content":"Exit code 2\noops","is_error":true (tool_use_result: "Error: Exit code 2\noops") + +The prefix holds when stdout is empty and the command wrote only to stderr: the stderr text follows +the first line. There is no numeric field anywhere in either result. OpenCode, for the same stderr-only +call: `stdout.jsonl` line 5 `{"status":"completed","truncated":false,"exit":2}`, output `"oops\n"`. + +Reader rule for `cc_reader_exit`: for a `Bash` result with `is_error: true`, the content up to the first +newline matching `^Exit code (\d+)$` gives `code N`, with or without text after it. Content that does not +start so gives no exit. + +## 2. A call ended by the harness's own timeout + +Claude Code: the timeout does not end the call. `agent_stream.jsonl.gz` line 10: + + "is_error":false, "content":"Command did not complete within its 1s timeout and was moved to the background (ID: bpvpiu488). ..." + tool_use_result: {"stdout":"","stderr":"","interrupted":false,...,"backgroundTaskId":"bpvpiu488","timedOutAfterMs":1000} + +The result is `is_error: false` and carries no code. Line 14, long after, is a separate system line about the +background task: `"summary":"Background command \"outlives timeout\" completed (exit code 0)"` (the sleep ran to +its end). That text belongs to the task, not to the call's result. + +OpenCode: the harness kills the command. `stdout.jsonl` line 6 and `export.json` lines 150-153: + + {"status":"completed","truncated":false,"signal":"SIGTERM","timeout":true} + +`status` is `completed`, `exit` is absent, `signal` is `"SIGTERM"`, `timeout` is `true`. The content text says +`Exit code: 143 (SIGTERM)`, the harness's rendering for the model, not a field. + +Decision: neither harness gives a code field on a timeout, so `exit` stays absent on a timeout and the +plan's "no timeout guard" holds in the sense that no code is read. Two guards the readers still need, because +the shapes are traps for the two rules above: + +- `cc_reader_exit`: the plan's rule "`is_error: false` gives code 0" must not fire on this result. + A result whose `tool_use_result` has `backgroundTaskId` or `timedOutAfterMs` gives no exit. +- `oc_reader_exit`: a result with no `metadata.exit` gives no exit even when `status` is `completed`. + The `signal` and `timeout` keys are the harness's own report; the plan's rule that Candler never infers a + signal from a code stays, and whether to feed `signal: "SIGTERM"` to the `signal` variant of `ExitStatus` + is the reader leaf's call (it is a harness-reported name, not an inference). + +## Other things seen + +- Claude Code refused a bare `sleep 30` itself (`Blocked: standalone sleep 30 ...`); the + recorded call uses a Python sleep. A reader meets that text as an `is_error: true` result with no + `Exit code` prefix, and it gives no exit. +- The Claude Code stream holds two `init` and two `result` lines in one session: the background task's end + started a second turn. The committed `expected.toml` (one session, `completed`) and `usage_totals.toml` keep + `guard_reader` green; the reader leaf adds its `exits` rows. +- OpenCode's stdout holds one `retry` line (a 429 from the gateway on the first model request). The retry + succeeded; it does not touch the shell calls. + +## Deviations + +- The two commit subjects are shortened to 72 characters, which the commit hook allows: Step 1 is + `test(trace-model): record each harness's failed and timed-out shell call` and Step 2 is + `reports(trace-model): how each harness reports a failed shell call`. +- The fake-model script `sh1` is not committed: it was added to `assets/docker/fakemodel/fakemodel.py` for the + run and reverted in Step 2; its text is in each `PROVENANCE.toml` entry. `git diff feat/run-context --stat -- + crates/candler/tests assets` prints nothing at the tip. + +## Docker + +Before: 19 images, 3 containers. After: no container of mine remains (`docker ps -aq` is as before); the fake-model +image the test built was removed by the test's own cleanup by id. The two agent images the runs used +(`sha256:57f339fc3580...` for Claude Code, `sha256:e287badacc75...` for OpenCode) were already present and are +left. `candler-gateway:latest` now resolves to `5913b0aa1289` (created 2026-11-17), where it resolved to +`17f734223887` before the run, which is no longer present: the product's own build step rebuilt that shared +tag, so it is not removed here. diff --git a/assets/docker/fakemodel/fakemodel.py b/assets/docker/fakemodel/fakemodel.py index 02bcec77..d238ac8a 100644 --- a/assets/docker/fakemodel/fakemodel.py +++ b/assets/docker/fakemodel/fakemodel.py @@ -138,20 +138,6 @@ def script_blocks(model, state, tools, messages): 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("sh1"): - shell = [n for n in tools if n in ("Bash", "shell", "bash")] - if state == "prompt" and shell: - calls = [ - {"type": "tool_use", "id": "toolu_fake_sh_exit3", "name": shell[0], - "input": {"command": "exit 3", "description": "exit 3"}}, - {"type": "tool_use", "id": "toolu_fake_sh_stderr", "name": shell[0], - "input": {"command": "echo oops >&2; exit 2", "description": "stderr only"}}, - {"type": "tool_use", "id": "toolu_fake_sh_timeout", "name": shell[0], - "input": {"command": "python3 -c 'import time; time.sleep(30)'", "description": "outlives timeout", "timeout": 1000}}, - ] - return [{"type": "text", "text": "I will run three shell calls."}] + calls, \ - "tool_use", "sh1-calls" - return [{"type": "text", "text": "done"}], "end_turn", "sh1-text" if model.startswith("c2"): return [{"type": "text", "text": "hello"}], "end_turn", "c2-hello" if model.startswith("c3"): diff --git a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs index 0ad5ebe4..e2734028 100644 --- a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs @@ -184,12 +184,6 @@ fn run_once( .map(|entry| entry.path()) .find(|path| path.join("run.done").is_file()) .unwrap_or_else(|| panic!("a sealed run\n{log}")); - if let Ok(out) = std::env::var("PROBE_OUT") { - let dest = Path::new(&out).join(place.1.replace('/', "_")); - fs::create_dir_all(&dest).unwrap(); - let status = Command::new("cp").arg("-R").arg(&run_dir).arg(&dest).status().unwrap(); - assert!(status.success()); - } let inspected = Command::new(env!("CARGO_BIN_EXE_candler")) .arg("inspect") .arg(&run_dir) @@ -414,137 +408,3 @@ fn parity_one_installed_server_one_traced_call() { eprintln!("parity: {:?} wall", started.elapsed()); assert!(failures.is_empty(), "{failures:#?}"); } - -#[test] -#[ignore = "needs Docker; run with --run-ignored only"] -fn probe_shell_shapes_scratch() { - 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:probe-{}", std::process::id()); - must( - &real, - &[ - "build", - "-q", - "--label", - "candler.test=probe", - "-t", - &tag, - context, - ], - ); - made.images.push(must( - &real, - &["image", "inspect", "--format", "{{.Id}}", &tag], - )); - let fake = must( - &real, - &[ - "run", - "-d", - "--label", - "candler.test=probe", - "-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\"", "\"sh1\"") - .replace( - "say hello", - "Run the three shell calls, then reply done.", - ) - .replace("wall_s = 30", "wall_s = 300") - .replacen( - "[harness]\nname = \"claude-code\"", - "[harness]\nname = \"@HARNESS@\"", - 1, - ) - }; - 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 failures: Vec = 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); - eprintln!("{harness}: {} calls, {} answers", seen.origins.len(), answers.len()); - if let Ok(out) = std::env::var("PROBE_OUT") { - fs::write(Path::new(&out).join(format!("records_{harness}.jsonl")), records(&real, &fake)).unwrap(); - } - } - drop(made); - assert_eq!( - must(&real, &["ps", "-aq"]), - before, - "no container is left behind" - ); - eprintln!("parity: {:?} wall", started.elapsed()); - assert!(failures.is_empty(), "{failures:#?}"); -} From 81611eff6d4b4f5a44fa66155cd7a49b93c434bb Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:40:42 +0900 Subject: [PATCH 08/93] rdm(evaluation): close the shell probe Verified against its fixtures; merged as e58f091e. Its container-e2e run waits for the integration branch to reach a pull request. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/README.md b/__roadmap__/run_context/README.md index c731c89e..dced3898 100644 --- a/__roadmap__/run_context/README.md +++ b/__roadmap__/run_context/README.md @@ -22,7 +22,7 @@ An evaluator plug-in that declares `needs.trace`, `needs.raw` or `needs.manifest ```mermaid graph TD schema_exit_needs[Schema: exit and needs]:::inprogress - probe_shell_shapes[Probe: shell shapes]:::inprogress + probe_shell_shapes[Probe: shell shapes]:::done readers[Readers and serving]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -35,7 +35,7 @@ graph TD | Node | Type | Status | |:-----|:-----|:-------| | `schema_exit_needs.md` | 📄 Leaf Task | 🔄 In Progress | -| `probe_shell_shapes.md` | 📄 Leaf Task | 🔄 In Progress | +| `probe_shell_shapes.md` | 📄 Leaf Task | ✅ Done | | `readers/` | 📁 Directory | ⬜ Planned | ## Amendment Log From 69da51c06b428bc5c9ff43821e1d3b376d7558b7 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:54:36 +0900 Subject: [PATCH 09/93] rdm(evaluation): rule on the schema leaf's two spec defects A reader of a record Candler writes ignores an unknown field, so the trace reader cannot refuse `exit` on a call line; the gate now states what holds. `Needs` keeps the reading `KindSpec` and `DescribeResult` have, schema strict and Rust reader lenient, instead of becoming the one strict struct in the describe result. The serving leaf now carries the engine's needs union, and the helper leaf the `bool | None` models that could write a null the Rust reader refuses. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/helper_context.md | 1 + __roadmap__/run_context/readers/serve_context.md | 1 + __roadmap__/run_context/schema_exit_needs.md | 4 ++-- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/readers/helper_context.md b/__roadmap__/run_context/readers/helper_context.md index 6f963046..94c98603 100644 --- a/__roadmap__/run_context/readers/helper_context.md +++ b/__roadmap__/run_context/readers/helper_context.md @@ -8,6 +8,7 @@ **Success Gates**: - ⬜ `tests/test_guard_context.py`, over hand-written wire contexts, shows `RunContext.from_wire` keeping `trace`, `raw` (with `sha256`) and `manifest`, each `None` or empty when absent. On the base `manifest` is dropped and `trace` is read as a bare path. Bite: `manifest` dropped by `from_wire` - ⬜ A trace reader in the helper yields typed events from `context.trace`, and the same test file shows it reading hand-written lines with `exit`, `origin: {kind: mcp, server, tool}` and `argv`, and refusing a line with an unknown field. Bite: a model that accepts unknown fields +- ⬜ The generated `Needs.raw` and `Needs.manifest` are typed `bool | None`, while the schema and the Rust reader refuse `null` (§Wire encodings, "Absent vs null"). A describe result the helper writes never carries `"raw": null` or `"manifest": null`, guarded over the helper's own writer with the shared wire vectors as oracle. Bite: the writer emits `null` for an unset need - ⬜ `scripts/gen_models.py` generates the trace models from `normalised-trace.schema.json` deterministically, and CI's regeneration check passes - ⬜ `docs/contract/evaluator-helper.md` lists the new fields and the reader, within its Notes limit and with stamps; `pyproject.toml`'s version is bumped by hand to the next minor, as CONTRIBUTING.md §Evaluator helper line says, and no tag is cut - `uv run pytest`, `uv run ruff check`, `uv run ruff format --check` and `uv run --frozen python scripts/gen_models.py` with no diff, all from `python/candler-evaluator` diff --git a/__roadmap__/run_context/readers/serve_context.md b/__roadmap__/run_context/readers/serve_context.md index a326d4d6..b180187e 100644 --- a/__roadmap__/run_context/readers/serve_context.md +++ b/__roadmap__/run_context/readers/serve_context.md @@ -10,6 +10,7 @@ - ⬜ `a_plug_in_cannot_write_through_to_the_store` extends to the trace, raw streams and manifest: the store's bytes are the same after a careless plug-in writes to its copies. Bite: a hard link instead of a copy - ⬜ `the_live_context_digest_is_the_independent_vector` keeps every existing row unchanged and green, and new rows for contexts that serve a trace, raw streams or a manifest, written by `gen_live_context.py` over python `rfc8785`, pass. Bites: (a) the trace key added even when not served (old rows go red); (b) left out when served (new rows go red) - ⬜ A kind that declares a part the run does not hold is refused with a new `ContextError` variant and a code in `docs/contract/codes.toml`, guarded by a row in `needs_inputs_refused_when_the_run_cannot_serve_them`'s pattern or `guard_silent_acceptance.rs`'s table, with the code written by hand. If the leaf finds that every sealed run holds a trace, raw streams and a manifest by construction (imported runs included), there is nothing to refuse for that part: the report says why, with the producer that guarantees it, and no guard is written for it +- ⬜ The needs the engine folds across a plug-in's kinds (`crates/candler-core/src/evaluation/engine/run.rs`, which unions them field by field) carry `raw` and `manifest`, so a part one kind declares is never dropped before `assemble`; the serving guard declares each part through that path - ⬜ The existing `guard_run_context.rs` guards (artifacts, inputs, corrupt blob, isolation, write-through) pass unchanged after the refactor; that is the refactor's guard, and the leaf adds no test of its own for it. `materialise.rs` has one copy routine, and the report shows its call sites - ⬜ `assemble.rs`'s doc states what is served and refused, with no history; a note `__reports__/run-context/01-ruling_trace_served_v0.md` records that the M2a ruling "trace not served" (`__reports__/m2a-evaluation-parity/l1/00-rulings_v0.md:75`) is replaced, and why - `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; `container-e2e` is green on the pull request diff --git a/__roadmap__/run_context/schema_exit_needs.md b/__roadmap__/run_context/schema_exit_needs.md index 235f7dd6..107734c6 100644 --- a/__roadmap__/run_context/schema_exit_needs.md +++ b/__roadmap__/run_context/schema_exit_needs.md @@ -6,8 +6,8 @@ - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/run-context HEAD` succeeds - [ ] `[nl]` The lead checked whether M6.5's `trace_context` leaf (campaign `feat/m6.5-agent-config`) has merged into `origin/main`. That leaf adds `KnownKind::ContextStart` to `crates/candler-schemas/src/trace.rs` and regenerates the same trace schema and contract page. If it has merged, `feat/run-context` is rebased onto it before this leaf starts. If not, this leaf goes ahead, and whichever of the two lands second rebases onto the other and regenerates the schema and pages instead of merging them by hand. Neither leaf bumps a version by hand: the `feat(schemas)` commits set the bump, and the lead lands both in one release when both are ready, so they make one minor bump, not two **Success Gates**: -- ⬜ A trace line `{"kind":"tool_result","is_error":true,"exit":{"kind":"code","code":3}}` reads, and the result keeps `exit` when written back. `exit` given as `{"code":3}`, as a string, or on a `tool_call` line is refused. A `tool_result` with no `exit` still reads. On the base, the line with `exit` is refused as an unknown field -- ⬜ In the shared wire vectors (`crates/candler-schemas/tests/fixtures/rpc/`), which the Rust reader and the Python helper's `test_guard_wire_vectors.py` both read, a `describe` response whose needs omit `raw` and `manifest` is valid, and one whose needs set `raw` to a non-boolean, or carry an unknown key, is invalid. Both readers decide every vector alike +- ⬜ A trace line `{"kind":"tool_result","is_error":true,"exit":{"kind":"code","code":3}}` reads, and the result keeps `exit` when written back. `exit` given as `{"code":3}`, as a string or as `null` is refused. A `tool_result` with no `exit` still reads. A reader of a record Candler writes ignores an unknown field (`__design__/architecture.md` §Wire encodings, "Unknown fields"), so `exit` on a `tool_call` line is not refused by the reader, only by the schema; on the base the line with `exit` reads and loses its `exit` when written back +- ⬜ In the shared wire vectors (`crates/candler-schemas/tests/fixtures/rpc/`), which the Rust reader and the Python helper's `test_guard_wire_vectors.py` both read, a `describe` response whose needs omit `raw` and `manifest` is valid, and one whose needs set `raw` to a non-boolean is invalid. Both readers decide every vector alike. `Needs` keeps the reading its siblings `KindSpec` and `DescribeResult` have (the schema refuses an unknown key, the Rust reader ignores it), so no vector states an unknown key in needs - ⬜ The context digest vectors keep every existing row unchanged and green, and new rows (contexts serving a trace, raw streams, a manifest), written by the independent Python generator over python `rfc8785`, pass. Under the bite "the trace key is always added" the old rows go red; under "the key is left out when served" the new rows go red - ⬜ The marker stays `normalised-trace/1`: the leaf report cites `__design__/architecture.md` §Wire encodings on why an optional field leaves it unchanged, or stops and tells the lead if that section says otherwise - ⬜ The JSON Schemas under `crates/candler-schemas/schema/` and the helper's generated models (`python/candler-evaluator/scripts/gen_models.py`) are regenerated, and the helper's `pytest` passes with the smallest change to its hand-written code that keeps it reading the new shapes; the helper's new API belongs to `readers/helper_context.md` From c33c6b82308cabc5cbb6cb226408e2b3f3e7c57d Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:00:14 +0900 Subject: [PATCH 10/93] rdm(evaluation): write the context_start caveat when both schemas meet The schema leaf's doc gate asked for a sentence about an event the trace cannot carry until M6.5's trace_context lands, so the published schema would describe a field the wire does not have. Whichever of the two lands second writes it, in the commit that brings both together. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/schema_exit_needs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/__roadmap__/run_context/schema_exit_needs.md b/__roadmap__/run_context/schema_exit_needs.md index 107734c6..42b859d8 100644 --- a/__roadmap__/run_context/schema_exit_needs.md +++ b/__roadmap__/run_context/schema_exit_needs.md @@ -11,7 +11,7 @@ - ⬜ The context digest vectors keep every existing row unchanged and green, and new rows (contexts serving a trace, raw streams, a manifest), written by the independent Python generator over python `rfc8785`, pass. Under the bite "the trace key is always added" the old rows go red; under "the key is left out when served" the new rows go red - ⬜ The marker stays `normalised-trace/1`: the leaf report cites `__design__/architecture.md` §Wire encodings on why an optional field leaves it unchanged, or stops and tells the lead if that section says otherwise - ⬜ The JSON Schemas under `crates/candler-schemas/schema/` and the helper's generated models (`python/candler-evaluator/scripts/gen_models.py`) are regenerated, and the helper's `pytest` passes with the smallest change to its hand-written code that keeps it reading the new shapes; the helper's new API belongs to `readers/helper_context.md` -- ⬜ The doc comments of `Needs`, `RunContext` and `ToolResult` (which reach the schemas) state each need, what each served part reveals of the run (once, with no domain judgement; when the trace holds a `context_start` event, the doc next to `needs.trace` says that declaring it hands the kind the run's system text and first message verbatim, which may be the treatment under test), that `is_error` is not comparable across harnesses for shell calls, and that `exit` is absent for a non-shell, denied or uncoded result. `docs/contract/evaluator-protocol.md`'s generated sections are regenerated, and its Notes stay within the page's 120 words, each with its stamp (CONTRIBUTING.md §Contract pages) +- ⬜ The doc comments of `Needs`, `RunContext` and `ToolResult` (which reach the schemas) state each need, what each served part reveals of the run (once, with no domain judgement, and only of events the trace can carry at this commit. M6.5's `context_start` event is not on `origin/main` yet, so the sentence saying that declaring `needs.trace` hands the kind the run's system text and first message verbatim, which may be the treatment under test, is written by whichever of this campaign and M6.5's `trace_context` lands second, in the commit that puts both on one branch), that `is_error` is not comparable across harnesses for shell calls, and that `exit` is absent for a non-shell, denied or uncoded result. `docs/contract/evaluator-protocol.md`'s generated sections are regenerated, and its Notes stay within the page's 120 words, each with its stamp (CONTRIBUTING.md §Contract pages) - ⬜ Both trace readers compile against the new constructor and write no `exit` yet (`readers/` fills it) - `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; helper `uv run pytest`, `uv run ruff check` pass; `container-e2e` is green on the pull request (it touches `crates/**`) **References**: [plan §The exit-status field, §Each need, §Wire shape of a served file, §Test plan](../../__reports__/run-context/00-plan_run_context_v0.md). Code: From e8bb3a4cd6f79aa9a56d318bfac0c62bfaa677bb Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:02:35 +0900 Subject: [PATCH 11/93] rdm(evaluation): meet M6.5 by merging origin/main in History is not rewritten, so whichever of M6d and M6.5 lands second merges origin/main in rather than rebasing, then regenerates the schemas and contract pages. M6.5's side is its leaf meet_run_context.md. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/README.md | 2 +- __roadmap__/run_context/schema_exit_needs.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/README.md b/__roadmap__/run_context/README.md index dced3898..dfc8ba22 100644 --- a/__roadmap__/run_context/README.md +++ b/__roadmap__/run_context/README.md @@ -1,7 +1,7 @@ # M6d Run context ## Context -The README promises that Candler's evaluation half can "grade traces and artifacts, fresh or already on disk, through pluggable evaluators that emit one outcome record format". Today an evaluator is handed only the artifacts: `context.trace` and `context.raw[]` exist on the wire, but `assemble` never fills them and silently ignores `needs.trace = true`. This campaign builds the approved plan [`__reports__/run-context/00-plan_run_context_v0.md`](../../__reports__/run-context/00-plan_run_context_v0.md): an evaluator can be handed any part a sealed run stored (trace, raw streams, manifest) the same way it is handed artifacts, and the trace records each shell call's exit status as `ToolResult.exit`, the `ExitStatus` object every supervised process already carries. htn-creator-eval is the first consumer (its probe P0 pins the release this campaign cuts); the design answers the feature's intent, not that probe. Depth gives the order: level 1 holds `schema_exit_needs.md` (the wire) and `probe_shell_shapes.md` (what real harnesses write for a failing shell call) in parallel; `readers/` (level 2) holds both trace readers, the serving in `assemble`/`materialise` and the Python helper in parallel; `readers/e2e/` (level 3) holds the end-to-end guard on real harnesses; `readers/e2e/review/` (level 4) holds the adversarial review of the whole diff. The test plan (guards with their oracle and bite, the probe, what is deliberately not tested) is the plan's §Test plan; each leaf names the guards it owns. The integration branch is `feat/run-context`, cut from `origin/main` at `8d82f63b`; each leaf runs in its own worktree made by `scripts/worktree.py add` from the `feat/run-context` tip and removed at merge. Every build sets `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/run-context-target/` and `RUSTC_WRAPPER=sccache` in its own environment, one dir per leaf; 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 by the probe and the e2e guard only, each of which removes what it built by id; nothing is pruned and Docker is never stopped. Test names that start with `confirm_` are build-step checks: each is deleted before its leaf merges, or rewritten to guard standard (`Guards: / Oracle: / Bite:`). The milestone label M6d is the coordinator's; the instruction-files campaign (M6.5) rebases its `trace_context` leaf onto this release. +The README promises that Candler's evaluation half can "grade traces and artifacts, fresh or already on disk, through pluggable evaluators that emit one outcome record format". Today an evaluator is handed only the artifacts: `context.trace` and `context.raw[]` exist on the wire, but `assemble` never fills them and silently ignores `needs.trace = true`. This campaign builds the approved plan [`__reports__/run-context/00-plan_run_context_v0.md`](../../__reports__/run-context/00-plan_run_context_v0.md): an evaluator can be handed any part a sealed run stored (trace, raw streams, manifest) the same way it is handed artifacts, and the trace records each shell call's exit status as `ToolResult.exit`, the `ExitStatus` object every supervised process already carries. htn-creator-eval is the first consumer (its probe P0 pins the release this campaign cuts); the design answers the feature's intent, not that probe. Depth gives the order: level 1 holds `schema_exit_needs.md` (the wire) and `probe_shell_shapes.md` (what real harnesses write for a failing shell call) in parallel; `readers/` (level 2) holds both trace readers, the serving in `assemble`/`materialise` and the Python helper in parallel; `readers/e2e/` (level 3) holds the end-to-end guard on real harnesses; `readers/e2e/review/` (level 4) holds the adversarial review of the whole diff. The test plan (guards with their oracle and bite, the probe, what is deliberately not tested) is the plan's §Test plan; each leaf names the guards it owns. The integration branch is `feat/run-context`, cut from `origin/main` at `8d82f63b`; each leaf runs in its own worktree made by `scripts/worktree.py add` from the `feat/run-context` tip and removed at merge. Every build sets `CARGO_TARGET_DIR=/Users/hacker/Documents/tmp/claude-worktrees/Candler/run-context-target/` and `RUSTC_WRAPPER=sccache` in its own environment, one dir per leaf; 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 by the probe and the e2e guard only, each of which removes what it built by id; nothing is pruned and Docker is never stopped. Test names that start with `confirm_` are build-step checks: each is deleted before its leaf merges, or rewritten to guard standard (`Guards: / Oracle: / Bite:`). The milestone label M6d is the coordinator's; the instruction-files campaign (M6.5) meets this one through its leaf `meet_run_context.md`: whichever lands second merges `origin/main` in (no rebase), regenerates the schemas and contract pages instead of resolving them by hand, and writes the `needs.trace` sentence about `context_start`. ## Goal An evaluator plug-in that declares `needs.trace`, `needs.raw` or `needs.manifest` is handed a private, read-only, digest-checked copy of that part of the sealed run, or a refusal with a code; the trace records each shell call's exit status as the harness reported it on both Claude Code and OpenCode; and one real run graded through `candler evaluate` shows its plug-in each shell call's command and exit and each MCP call's `{server, tool}`. diff --git a/__roadmap__/run_context/schema_exit_needs.md b/__roadmap__/run_context/schema_exit_needs.md index 42b859d8..ab911bc9 100644 --- a/__roadmap__/run_context/schema_exit_needs.md +++ b/__roadmap__/run_context/schema_exit_needs.md @@ -4,7 +4,7 @@ **Estimate**: Sonnet, $8, cap $16. 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 feat/run-context HEAD` succeeds -- [ ] `[nl]` The lead checked whether M6.5's `trace_context` leaf (campaign `feat/m6.5-agent-config`) has merged into `origin/main`. That leaf adds `KnownKind::ContextStart` to `crates/candler-schemas/src/trace.rs` and regenerates the same trace schema and contract page. If it has merged, `feat/run-context` is rebased onto it before this leaf starts. If not, this leaf goes ahead, and whichever of the two lands second rebases onto the other and regenerates the schema and pages instead of merging them by hand. Neither leaf bumps a version by hand: the `feat(schemas)` commits set the bump, and the lead lands both in one release when both are ready, so they make one minor bump, not two +- [ ] `[nl]` The lead checked whether M6.5's `trace_context` leaf (campaign `feat/m6.5-agent-config`) has merged into `origin/main`. That leaf adds `KnownKind::ContextStart` to `crates/candler-schemas/src/trace.rs` and regenerates the same trace schema and contract page. If it has merged, `origin/main` is merged into `feat/run-context` before this leaf starts (history is not rewritten, so no rebase). If not, this leaf goes ahead, and whichever of the two lands second merges `origin/main` in and regenerates the schema and pages instead of resolving them by hand; M6.5's side of this is its leaf `meet_run_context.md`. Neither leaf bumps a version by hand: the `feat(schemas)` commits set the bump, and the lead lands both in one release when both are ready, so they make one minor bump, not two **Success Gates**: - ⬜ A trace line `{"kind":"tool_result","is_error":true,"exit":{"kind":"code","code":3}}` reads, and the result keeps `exit` when written back. `exit` given as `{"code":3}`, as a string or as `null` is refused. A `tool_result` with no `exit` still reads. A reader of a record Candler writes ignores an unknown field (`__design__/architecture.md` §Wire encodings, "Unknown fields"), so `exit` on a `tool_call` line is not refused by the reader, only by the schema; on the base the line with `exit` reads and loses its `exit` when written back - ⬜ In the shared wire vectors (`crates/candler-schemas/tests/fixtures/rpc/`), which the Rust reader and the Python helper's `test_guard_wire_vectors.py` both read, a `describe` response whose needs omit `raw` and `manifest` is valid, and one whose needs set `raw` to a non-boolean is invalid. Both readers decide every vector alike. `Needs` keeps the reading its siblings `KindSpec` and `DescribeResult` have (the schema refuses an unknown key, the Rust reader ignores it), so no vector states an unknown key in needs From b9934d62cf25fe3be8763ccb16cf518c5ccaeb3f Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:38:13 +0900 Subject: [PATCH 12/93] test(schemas): state the exit field, the new needs and their digest keys Guards, written before the code and red on the base: - a tool_result with an exit object reads and is written back; a bare {code}, a string and null are refused - a describe result whose needs set raw and manifest is valid; a non-boolean raw and an unknown needs key are invalid, for the Rust reader and the helper's models alike - context digest vectors for contexts that serve a trace, raw streams and a manifest, generated by the independent Python generator; the existing rows are unchanged Co-Authored-By: Claude Sonnet 5.5 --- .../oracle/vectors/context_digest_served.toml | 71 +++++++++ .../tests/oracle/vectors/gen_vectors.py | 91 ++++++++++- .../tests/fixtures/rpc/PROVENANCE.toml | 2 +- .../tests/fixtures/rpc/README.md | 5 +- .../rpc/invalid/needs_raw_not_boolean.json | 45 ++++++ .../rpc/invalid/needs_unknown_key.json | 45 ++++++ .../response_describe_needs_raw_manifest.json | 46 ++++++ .../tests/it/guard_context_digest.rs | 149 +++++++++++++++++- .../tests/it/guard_rpc_wire.rs | 4 +- .../tests/it/guard_trace_wire.rs | 40 +++++ 10 files changed, 490 insertions(+), 8 deletions(-) create mode 100644 crates/candler-core/tests/oracle/vectors/context_digest_served.toml create mode 100644 crates/candler-schemas/tests/fixtures/rpc/invalid/needs_raw_not_boolean.json create mode 100644 crates/candler-schemas/tests/fixtures/rpc/invalid/needs_unknown_key.json create mode 100644 crates/candler-schemas/tests/fixtures/rpc/valid/response_describe_needs_raw_manifest.json diff --git a/crates/candler-core/tests/oracle/vectors/context_digest_served.toml b/crates/candler-core/tests/oracle/vectors/context_digest_served.toml new file mode 100644 index 00000000..be21f76e --- /dev/null +++ b/crates/candler-core/tests/oracle/vectors/context_digest_served.toml @@ -0,0 +1,71 @@ +# context_digest_served.toml: context digests of contexts that serve a trace, raw streams or a manifest (R01 §Digests of a request). +# 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: }` 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: , digest: "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 `-r-a` 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-`. +# 14. Served parts (`context_digest_served.toml`): a context that serves the trace, the raw streams +# or the manifest adds one key to the projection for each, and only for a part it serves: +# `trace` is the sha256 of the trace file as the string `sha256:<64 hex>`, `manifest` likewise, +# and `raw` is `[{stream, sha256}]` sorted by `stream` by Unicode code point. A part that is not +# served has no key, so every projection of the other files is unchanged. The paths and the +# absolute paths of a served part stay outside the projection, as an artifact's absolute path does. + + +# `input` is the projection as a caller may hold it (`raw` in any order); the digest is +# over the projection with `raw` sorted by `stream`, returned in `sorted`. Each key is +# present only for a part the case serves. + +[[vector]] +title = "a served trace" +input = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"trace\":\"sha256:eafe895eb8119e6e5d06463590b2ef81b3651c157d5c8e18f1889186c7fd0ac0\"}" +sorted = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"trace\":\"sha256:eafe895eb8119e6e5d06463590b2ef81b3651c157d5c8e18f1889186c7fd0ac0\"}" +digest = "sha256:00023d5a2534319a27d169ec12fb049d701d7e42cf7e1f23c42211b2349a1b1a" + +[[vector]] +title = "two served raw streams, given out of order" +input = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"raw\":[{\"stream\":\"stdout\",\"sha256\":\"sha256:63d42d26156fcc761e57da4128e9881d5bdf3bf933f0f6e9c93d6e26b9b90ae7\"},{\"stream\":\"stderr\",\"sha256\":\"sha256:7e6b710b765404cccbad9eedcff7615fc37b269d6db12cd81a58be541d93083c\"}]}" +sorted = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"raw\":[{\"stream\":\"stderr\",\"sha256\":\"sha256:7e6b710b765404cccbad9eedcff7615fc37b269d6db12cd81a58be541d93083c\"},{\"stream\":\"stdout\",\"sha256\":\"sha256:63d42d26156fcc761e57da4128e9881d5bdf3bf933f0f6e9c93d6e26b9b90ae7\"}]}" +digest = "sha256:e627ea2026c477f64710db4f760b100e9f6542e2606bf537d9fb07e4beeb5248" + +[[vector]] +title = "a served manifest" +input = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"manifest\":\"sha256:05b3abf2579a5eb66403cd78be557fd860633a1fe2103c7642030defe32c657f\"}" +sorted = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"manifest\":\"sha256:05b3abf2579a5eb66403cd78be557fd860633a1fe2103c7642030defe32c657f\"}" +digest = "sha256:8cb2f3b6032d4de189b9ffb962f61df3ec317ca3a6a4ca92d4b365be276f9b07" + +[[vector]] +title = "a trace, raw streams and a manifest together" +input = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"trace\":\"sha256:eafe895eb8119e6e5d06463590b2ef81b3651c157d5c8e18f1889186c7fd0ac0\",\"raw\":[{\"stream\":\"stdout\",\"sha256\":\"sha256:63d42d26156fcc761e57da4128e9881d5bdf3bf933f0f6e9c93d6e26b9b90ae7\"}],\"manifest\":\"sha256:05b3abf2579a5eb66403cd78be557fd860633a1fe2103c7642030defe32c657f\"}" +sorted = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"trace\":\"sha256:eafe895eb8119e6e5d06463590b2ef81b3651c157d5c8e18f1889186c7fd0ac0\",\"raw\":[{\"stream\":\"stdout\",\"sha256\":\"sha256:63d42d26156fcc761e57da4128e9881d5bdf3bf933f0f6e9c93d6e26b9b90ae7\"}],\"manifest\":\"sha256:05b3abf2579a5eb66403cd78be557fd860633a1fe2103c7642030defe32c657f\"}" +digest = "sha256:bf23968740b078448acf59d897cdeb9df01ca75f05f8a37283927616a61773ac" + +[[vector]] +title = "a trace and a manifest, no raw streams" +input = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"trace\":\"sha256:da62c78ef08080958f79ea5d8ab7e490711b0ccc9b426ca7b6bb7c521adc392f\",\"manifest\":\"sha256:8609f1753a27537fa5ea65336ba11cdfbc364f9430995d7e3039b6d3b0a31a27\"}" +sorted = "{\"artifacts\":[{\"path\":\"outputs/plan.json\",\"sha256\":\"sha256:64879f7d6b960a01909762d911a32d4582c20010c5641ee90278b644a9e3b525\"}],\"snapshots\":[],\"inputs\":[{\"kind\":\"mapping\",\"digest\":\"sha256:a6375ee99716acf4635ba3c192f7578a85ad4b479d09174e7d80d01aa91443af\"}],\"metadata\":{\"plan.model\":\"claude-haiku-4-5\"},\"trace\":\"sha256:da62c78ef08080958f79ea5d8ab7e490711b0ccc9b426ca7b6bb7c521adc392f\",\"manifest\":\"sha256:8609f1753a27537fa5ea65336ba11cdfbc364f9430995d7e3039b6d3b0a31a27\"}" +digest = "sha256:71126869ae286fbea41e0733fadba5a9474b5612f44fc4bfc99762847b00fe1e" diff --git a/crates/candler-core/tests/oracle/vectors/gen_vectors.py b/crates/candler-core/tests/oracle/vectors/gen_vectors.py index c4100673..2a1a5fb7 100644 --- a/crates/candler-core/tests/oracle/vectors/gen_vectors.py +++ b/crates/candler-core/tests/oracle/vectors/gen_vectors.py @@ -49,6 +49,14 @@ cell's `experiment.json`, not a `measured` value and not read from the run's files. 13. The `run` key of a runs vector is `/run-` (`with_skill/run-6`), the run folder relative to `_run_cache/`. + +ASSUMED for served run parts (`context_digest_served.toml` only) +14. Served parts (`context_digest_served.toml`): a context that serves the trace, the raw streams + or the manifest adds one key to the projection for each, and only for a part it serves: + `trace` is the sha256 of the trace file as the string `sha256:<64 hex>`, `manifest` likewise, + and `raw` is `[{stream, sha256}]` sorted by `stream` by Unicode code point. A part that is not + served has no key, so every projection of the other files is unchanged. The paths and the + absolute paths of a served part stay outside the projection, as an artifact's absolute path does. """ import argparse @@ -65,8 +73,10 @@ import rfc8785 _NOTES = __doc__.split("ASSUMED (also listed under Findings in the leaf report)\n", 1)[1] -ASSUMED, ASSUMED_RUNS = _NOTES.split("\nASSUMED for imported runs", 1) -ASSUMED_RUNS = ASSUMED_RUNS.split("\n", 1)[1].rsplit('"""', 1)[0] +ASSUMED, _REST = _NOTES.split("\nASSUMED for imported runs", 1) +ASSUMED_RUNS, ASSUMED_SERVED = _REST.split("\nASSUMED for served run parts", 1) +ASSUMED_RUNS = ASSUMED_RUNS.split("\n", 1)[1] +ASSUMED_SERVED = ASSUMED_SERVED.split("\n", 1)[1].rsplit('"""', 1)[0] HERE = os.path.dirname(os.path.abspath(__file__)) MINI = os.path.normpath(os.path.join(HERE, "..", "..", "fixtures", "mini-corpus")) @@ -84,6 +94,7 @@ "suite_entry_digest.toml", "request_id.toml", "context_digest_runs.toml", + "context_digest_served.toml", ) @@ -431,6 +442,79 @@ def context_vectors(): return "\n".join(out), cases +def served_projection(base, trace=None, raw=None, manifest=None): + """ASSUMED 14: the base projection plus a key for each served part, sorted as R01 says.""" + proj = context_projection(*base) + if trace is not None: + proj["trace"] = trace + if raw: + proj["raw"] = sorted(raw, key=lambda r: r["stream"]) + if manifest is not None: + proj["manifest"] = manifest + return proj + + +SERVED_BASE = ( + [{"path": "outputs/plan.json", "sha256": hexd("plan")}], + [], + [{"kind": "mapping", "digest": hexd("mapping")}], + {"plan.model": "claude-haiku-4-5"}, +) +SERVED_CASES = ( + ("a served trace", {"trace": hexd("trace")}), + ( + "two served raw streams, given out of order", + { + "raw": [ + {"stream": "stdout", "sha256": hexd("stdout")}, + {"stream": "stderr", "sha256": hexd("stderr")}, + ] + }, + ), + ("a served manifest", {"manifest": hexd("manifest")}), + ( + "a trace, raw streams and a manifest together", + { + "trace": hexd("trace"), + "raw": [{"stream": "stdout", "sha256": hexd("stdout")}], + "manifest": hexd("manifest"), + }, + ), + ( + "a trace and a manifest, no raw streams", + {"trace": hexd("trace-2"), "manifest": hexd("manifest-2")}, + ), +) + + +def served_vectors(): + out = [ + header( + "context_digest_served.toml", + "context digests of contexts that serve a trace, raw streams or a manifest (R01 §Digests of a request).", + ASSUMED_SERVED, + ) + ] + out.append( + "# `input` is the projection as a caller may hold it (`raw` in any order); the digest is\n" + "# over the projection with `raw` sorted by `stream`, returned in `sorted`. Each key is\n" + "# present only for a part the case serves.\n" + ) + cases = [] + for title, parts in SERVED_CASES: + given = context_projection(*SERVED_BASE) + given.update(parts) + proj = served_projection(SERVED_BASE, **parts) + cases.append((title, proj)) + out.append("[[vector]]") + out.append(f"title = {toml_str(title)}") + out.append(f"input = {toml_str(jtext(given))}") + out.append(f"sorted = {toml_str(jtext(proj))}") + out.append(f"digest = {toml_str(digest_of(proj))}") + out.append("") + return "\n".join(out), cases + + def run_artifacts(cell, config, n): """ASSUMED 11: every file under the run's `outputs/`, by relative path and raw-byte sha256.""" root = os.path.join(MINI, cell, "_run_cache", config, f"run-{n}", "outputs") @@ -609,8 +693,9 @@ def generate(): suite_text, suite_entries = suite_vectors() request_text, request_rows = request_vectors(comparables) runs_text, _runs = run_context_vectors() + served_text, _served = served_vectors() texts = dict( - zip(FILES, (cells_text, context_text, suite_text, request_text, runs_text)) + zip(FILES, (cells_text, context_text, suite_text, request_text, runs_text, served_text)) ) return texts, comparables, context_cases, suite_entries, request_rows diff --git a/crates/candler-schemas/tests/fixtures/rpc/PROVENANCE.toml b/crates/candler-schemas/tests/fixtures/rpc/PROVENANCE.toml index 9622b378..44c48fee 100644 --- a/crates/candler-schemas/tests/fixtures/rpc/PROVENANCE.toml +++ b/crates/candler-schemas/tests/fixtures/rpc/PROVENANCE.toml @@ -1,3 +1,3 @@ synthetic = true -clause = "JSON-RPC 2.0 §4 Request, §4.1 Notification, §5 Response, §5.1 Error object; R01 §Evaluator protocol" +clause = "JSON-RPC 2.0 §4 Request, §4.1 Notification, §5 Response, §5.1 Error object; R01 §Evaluator protocol (describe result, `needs`)" files = "valid/*.json, invalid/*.json" diff --git a/crates/candler-schemas/tests/fixtures/rpc/README.md b/crates/candler-schemas/tests/fixtures/rpc/README.md index 7dcdd098..87c1a68a 100644 --- a/crates/candler-schemas/tests/fixtures/rpc/README.md +++ b/crates/candler-schemas/tests/fixtures/rpc/README.md @@ -10,7 +10,8 @@ Valid, each must be accepted: |:-----|:-------| | `request_describe`, `request_evaluate` | §4 Request: `jsonrpc` "2.0", `method`, `params`, a string `id` (the protocol mints UUIDv7 text ids) | | `notification_outcome`, `notification_progress`, `notification_log`, `notification_cancel` | §4.1 Notification: a request without `id` | -| `response_describe`, `response_evaluate` | §5 Response: `jsonrpc`, `id`, `result` | +| `response_describe`, `response_evaluate` | §5 Response: `jsonrpc`, `id`, `result`; `response_describe`'s needs omit `raw` and `manifest`, which read as `false` | +| `response_describe_needs_raw_manifest` | §5 Response: a describe result whose needs set `raw` and `manifest` | | `error_cancelled` | §5.1 Error object: integer `code`, `message`; `-32800` is the protocol's cancelled request | Invalid, each is one fault on a valid base and must be refused: @@ -23,3 +24,5 @@ Invalid, each is one fault on a valid base and must be refused: | `id_null` | `id` is `null` | §4: the protocol never uses a null id | | `unknown_key` | a top-level key `extra` | §4: the members are those listed | | `result_and_method` | `result` beside `method` | §5: `result` belongs to a response only | +| `needs_raw_not_boolean` | a kind's `needs.raw` is the string `"yes"` | R01 §Evaluator protocol: `needs.raw` is a boolean | +| `needs_unknown_key` | a kind's `needs` has a key `traces` | R01 §Evaluator protocol: the members of `needs` are those listed | diff --git a/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_raw_not_boolean.json b/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_raw_not_boolean.json new file mode 100644 index 00000000..1c181774 --- /dev/null +++ b/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_raw_not_boolean.json @@ -0,0 +1,45 @@ +{ + "jsonrpc": "2.0", + "id": "0192f4e0-7b3a-7c1d-8a2e-4f5b6c7d8e9f", + "result": { + "protocol": { + "major": 1, + "minor": 0 + }, + "name": "demo-evaluator", + "version": "0.1.0", + "instruments": [ + { + "name": "demo-grader", + "version": "1.0.0", + "digest": "git:0123456789abcdef0123456789abcdef01234567", + "dirty": false + } + ], + "environment": { + "packages": { + "demo": "1.0.0" + } + }, + "kind": "deterministic", + "kinds": [ + { + "kind": "file_exists", + "params_schema": { + "type": "object" + }, + "needs": { + "trace": false, + "artifacts": [ + "plan.md" + ], + "snapshots": [], + "inputs": [], + "metadata": [], + "raw": "yes" + }, + "default_deadline_ms": 5000 + } + ] + } +} \ No newline at end of file diff --git a/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_unknown_key.json b/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_unknown_key.json new file mode 100644 index 00000000..1c3ba28d --- /dev/null +++ b/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_unknown_key.json @@ -0,0 +1,45 @@ +{ + "jsonrpc": "2.0", + "id": "0192f4e0-7b3a-7c1d-8a2e-4f5b6c7d8e9f", + "result": { + "protocol": { + "major": 1, + "minor": 0 + }, + "name": "demo-evaluator", + "version": "0.1.0", + "instruments": [ + { + "name": "demo-grader", + "version": "1.0.0", + "digest": "git:0123456789abcdef0123456789abcdef01234567", + "dirty": false + } + ], + "environment": { + "packages": { + "demo": "1.0.0" + } + }, + "kind": "deterministic", + "kinds": [ + { + "kind": "file_exists", + "params_schema": { + "type": "object" + }, + "needs": { + "trace": false, + "artifacts": [ + "plan.md" + ], + "snapshots": [], + "inputs": [], + "metadata": [], + "traces": true + }, + "default_deadline_ms": 5000 + } + ] + } +} \ No newline at end of file diff --git a/crates/candler-schemas/tests/fixtures/rpc/valid/response_describe_needs_raw_manifest.json b/crates/candler-schemas/tests/fixtures/rpc/valid/response_describe_needs_raw_manifest.json new file mode 100644 index 00000000..274a7998 --- /dev/null +++ b/crates/candler-schemas/tests/fixtures/rpc/valid/response_describe_needs_raw_manifest.json @@ -0,0 +1,46 @@ +{ + "jsonrpc": "2.0", + "id": "0192f4e0-7b3a-7c1d-8a2e-4f5b6c7d8e9f", + "result": { + "protocol": { + "major": 1, + "minor": 0 + }, + "name": "demo-evaluator", + "version": "0.1.0", + "instruments": [ + { + "name": "demo-grader", + "version": "1.0.0", + "digest": "git:0123456789abcdef0123456789abcdef01234567", + "dirty": false + } + ], + "environment": { + "packages": { + "demo": "1.0.0" + } + }, + "kind": "deterministic", + "kinds": [ + { + "kind": "file_exists", + "params_schema": { + "type": "object" + }, + "needs": { + "trace": false, + "artifacts": [ + "plan.md" + ], + "snapshots": [], + "inputs": [], + "metadata": [], + "raw": true, + "manifest": true + }, + "default_deadline_ms": 5000 + } + ] + } +} \ No newline at end of file diff --git a/crates/candler-schemas/tests/it/guard_context_digest.rs b/crates/candler-schemas/tests/it/guard_context_digest.rs index 43894324..72c6216b 100644 --- a/crates/candler-schemas/tests/it/guard_context_digest.rs +++ b/crates/candler-schemas/tests/it/guard_context_digest.rs @@ -10,12 +10,17 @@ use candler_schemas::evaluation::{ use candler_schemas::primitives::{Digest, FieldPath, Name, RelPath, RunKey}; use candler_schemas::raw::StreamName; use candler_schemas::values::JsonValue; -use serde_json::Value; +use serde_json::{Value, json}; /// The vectors of `context_digest.toml`, generated by Python with the `rfc8785` package. const CONTEXT_VECTORS: &str = include_str!("../../../candler-core/tests/oracle/vectors/context_digest.toml"); +/// The vectors of `context_digest_served.toml`, generated by Python with the `rfc8785` package: +/// contexts that serve a trace, raw streams or a manifest. +const SERVED_VECTORS: &str = + include_str!("../../../candler-core/tests/oracle/vectors/context_digest_served.toml"); + /// The vectors of `suite_entry_digest.toml`, generated by Python with the `rfc8785` package. const ENTRY_VECTORS: &str = include_str!("../../../candler-core/tests/oracle/vectors/suite_entry_digest.toml"); @@ -316,3 +321,145 @@ fn suite_entry_digest_follows_the_oracle_and_ignores_names() { } assert_eq!(reversed, 1, "one oracle entry has two conditions"); } + +/// The wire form of the context a vector's projection describes, with made-up paths: the served +/// parts are objects that carry their digests, and a part the projection lacks is not served. +fn wire_context(projection: &Value) -> Value { + let run = json!({"cell": digest('a'), "replicate": 1, "attempt": 1}); + // INDEX: a projection and each of its members carry every key the closures name + let list = |key: &str| projection[key].as_array().expect("a list").clone(); + let mut context = json!({ + "run": run, + "root": "/made/up", + "raw": [], + "artifacts": list("artifacts").iter() + .map(|a| json!({"path": a["path"], "abs": "/made/up/artifact", "sha256": a["sha256"]})) + .collect::>(), + "snapshots": list("snapshots").iter() + .map(|r| json!({"kind": r["kind"], "path": "/made/up/snapshot", "digest": r["digest"]})) + .collect::>(), + "inputs": list("inputs").iter() + .map(|r| json!({"kind": r["kind"], "path": "/made/up/input", "digest": r["digest"]})) + .collect::>(), + "metadata": projection["metadata"], + }); + if let Some(sha256) = projection.get("trace") { + // INDEX: `context` is the object built above + context["trace"] = + json!({"path": "trace.jsonl", "abs": "/made/up/trace.jsonl", "sha256": sha256}); + } + if let Some(sha256) = projection.get("manifest") { + // INDEX: `context` is the object built above + context["manifest"] = + json!({"path": "manifest.json", "abs": "/made/up/manifest.json", "sha256": sha256}); + } + if projection.get("raw").is_some() { + let raw = list("raw") + .iter() + .map(|r| { + let stream = r["stream"].as_str().expect("a stream"); + json!({"stream": stream, "path": format!("/made/up/raw/{stream}.jsonl.gz"), "sha256": r["sha256"]}) + }) + .collect::>(); + // INDEX: `context` is the object built above + context["raw"] = Value::from(raw); + } + context +} + +/// An edit of the wire form of a context. +type WireEdit = fn(&mut Value); + +fn read_context(wire: Value) -> RunContext { + serde_json::from_value(wire).expect("a context") +} + +/// Guards: R9 — a context that serves a trace, raw streams or a manifest has the digest Python +/// computes from the RFC 8785 form of the projection with one more key for each served part (the +/// raw streams sorted by stream); the paths of a served part stay outside the digest, its digest +/// is inside it, and a part that is not served adds no key. Oracle: `context_digest_served.toml`, +/// generated by Python `rfc8785`, whose projection is written from the plan's wire shape, and +/// the four rows of `context_digest.toml` for the contexts that serve none of the parts. +/// Bite: the trace key is always added (the old rows go red); the key is left out when served +/// (these rows go red). +#[test] +fn the_digest_of_a_context_adds_a_key_for_each_served_part_and_only_for_those() { + let cases = vectors(SERVED_VECTORS); + assert_eq!(cases.len(), 5); + for case in &cases { + // INDEX: every served vector carries `title`, `digest`, `input` and `sorted` + // BORROW: .as_str() reads the text of a TOML value + let title = case["title"].as_str().expect("a title"); + // INDEX: every served vector carries `title`, `digest`, `input` and `sorted` + // BORROW: .as_str() reads the text of a TOML value + let expected = case["digest"].as_str().expect("a digest"); + for form in ["input", "sorted"] { + // INDEX: every served vector carries `title`, `digest`, `input` and `sorted` + // BORROW: .as_str() reads the JSON text of a TOML value + let text = case[form].as_str().expect("JSON text"); + let projection: Value = serde_json::from_str(text).expect("JSON"); + let context = read_context(wire_context(&projection)); + assert_eq!( + // BORROW: .as_str() compares the digest as text + context.context_digest().as_str(), + expected, + "{title} ({form})" + ); + } + } + + // The case that serves all three parts, edited one fact at a time. + // INDEX: the fourth served vector serves all three parts + let all: Value = + serde_json::from_str(cases[3]["sorted"].as_str().expect("JSON text")).expect("JSON"); + let digest_of = |edit: WireEdit| { + let mut wire = wire_context(&all); + edit(&mut wire); + read_context(wire).context_digest() + }; + let base = read_context(wire_context(&all)).context_digest(); + let keeps: [(&str, WireEdit); 4] = [ + ("trace path", |w| { + w["trace"]["abs"] = Value::from("/elsewhere/trace.jsonl"); + }), + ("manifest path", |w| { + w["manifest"]["abs"] = Value::from("/elsewhere/manifest.json"); + }), + ("raw path", |w| { + w["raw"][0]["path"] = Value::from("/elsewhere/stdout.jsonl.gz"); + }), + ("root", |w| w["root"] = Value::from("/elsewhere")), + ]; + for (name, edit) in keeps { + assert_eq!( + digest_of(edit), + base, + "changing the {name} keeps the digest" + ); + } + let changes: [(&str, WireEdit); 6] = [ + ("trace sha256", |w| { + w["trace"]["sha256"] = json!(digest('9')); + }), + ("manifest sha256", |w| { + w["manifest"]["sha256"] = json!(digest('9')); + }), + ("raw sha256", |w| { + w["raw"][0]["sha256"] = json!(digest('9')); + }), + ("trace served", |w| { + drop(w.as_object_mut().expect("an object").remove("trace")); + }), + ("manifest served", |w| { + drop(w.as_object_mut().expect("an object").remove("manifest")); + }), + ("raw served", |w| w["raw"] = json!([])), + ]; + for (name, edit) in changes { + assert_ne!( + digest_of(edit), + base, + "changing the {name} changes the digest" + ); + } +} diff --git a/crates/candler-schemas/tests/it/guard_rpc_wire.rs b/crates/candler-schemas/tests/it/guard_rpc_wire.rs index 216b19b7..a48695b3 100644 --- a/crates/candler-schemas/tests/it/guard_rpc_wire.rs +++ b/crates/candler-schemas/tests/it/guard_rpc_wire.rs @@ -55,8 +55,8 @@ fn accepted(value: &Value) -> bool { fn the_envelope_accepts_valid_messages_and_refuses_single_faults() { let valid = vectors("valid"); let invalid = vectors("invalid"); - assert_eq!(valid.len(), 9, "the valid vectors are all present"); - assert_eq!(invalid.len(), 6, "the invalid vectors are all present"); + assert_eq!(valid.len(), 10, "the valid vectors are all present"); + assert_eq!(invalid.len(), 8, "the invalid vectors are all present"); for (name, text) in &valid { let result = serde_json::from_str::(text); assert!(result.is_ok(), "{name} is refused: {result:?}"); diff --git a/crates/candler-schemas/tests/it/guard_trace_wire.rs b/crates/candler-schemas/tests/it/guard_trace_wire.rs index b0d4086d..8f251b24 100644 --- a/crates/candler-schemas/tests/it/guard_trace_wire.rs +++ b/crates/candler-schemas/tests/it/guard_trace_wire.rs @@ -422,3 +422,43 @@ fn an_mcp_origin_without_a_tool_still_reads_and_one_with_it_round_trips() { new ); } + +/// Guards: normalised-trace/1 — a `tool_result` carries an optional `exit`, the process exit +/// object `{kind, code}`: a line with one reads and is written back as it was, a result without +/// one still reads, and an `exit` that is not that object (a bare `{code}`, a string, `null`) is +/// refused, so the wire has one reading of it. Oracle: the event lines below, written by hand from the architecture's +/// §Normalised trace model and §Wire encodings; the line without `exit` is the positive control. +#[test] +fn a_tool_result_carries_its_exit_as_the_process_exit_object_and_nothing_else() { + let file_with = |event: &str| { + let line = format!( + r#"{{"kind":"event","session":"root-1","event":{{"seq":0,"kind":{event},"raw_ref":{{"stream":"stdout","frame":0}},"ext":{{}}}}}}"# + ); + let mut text = [TRACE_LINES[0], TRACE_LINES[1], line.as_str()].join("\n"); + text.push('\n'); + text.into_bytes() + }; + + let kept = [ + r#"{"kind":"tool_result","is_error":false}"#, + r#"{"kind":"tool_result","is_error":true,"exit":{"kind":"code","code":3}}"#, + r#"{"kind":"tool_result","is_error":false,"exit":{"kind":"code","code":0}}"#, + ]; + for event in kept { + let literal = file_with(event); + let file = TraceFile::read(&literal).unwrap_or_else(|e| panic!("{event} is refused: {e}")); + assert_eq!(file.write(), literal, "{event} is not written back as read"); + } + + let refused = [ + r#"{"kind":"tool_result","is_error":true,"exit":{"code":3}}"#, + r#"{"kind":"tool_result","is_error":true,"exit":"3"}"#, + r#"{"kind":"tool_result","is_error":true,"exit":null}"#, + ]; + for event in refused { + assert!( + TraceFile::read(&file_with(event)).is_err(), + "{event} is accepted" + ); + } +} From bf1f6c2c06239f993ff39362e74b26881192a4c1 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:42:18 +0900 Subject: [PATCH 13/93] feat(schemas)!: carry a shell call's exit and the stored run's needs A trace line's tool_result gains an optional exit, the process exit object. Needs gains raw and manifest, booleans that read as false when absent, and refuses a key it does not know. RunContext gains an optional manifest, and its trace and manifest are {path, abs, sha256} objects. ContextRaw gains sha256. context_digest adds a key for each served part, only when it is served, so the digest of a context that serves none of them is unchanged. BREAKING CHANGE: RunContext.trace is an object, no longer a path string, and ContextRaw has a required sha256, so a context written before is invalid now. Candler never wrote a context with a trace or a raw stream. Migration: write trace as {"path": "trace.jsonl", "abs": , "sha256": } and add "sha256" to each raw stream. In Rust, EventKind::tool_result takes the exit as a third argument, ContextRaw::new takes the digest, and RunContextBuilder::trace takes a ContextArtifact. A describe result whose needs carry a key other than the listed ones is refused. Co-Authored-By: Claude Sonnet 5.5 --- .../evaluator-describe-result.schema.json | 16 +- .../evaluator-evaluate-params.schema.json | 29 ++-- .../schema/evaluator-message.schema.json | 45 ++++-- .../schema/evaluator-request-side.schema.json | 29 ++-- .../schema/normalised-trace.schema.json | 51 ++++++- crates/candler-schemas/src/evaluation.rs | 142 +++++++++++++----- crates/candler-schemas/src/trace.rs | 28 +++- .../tests/it/guard_context_digest.rs | 29 +--- .../tests/it/guard_evaluator_protocol.rs | 4 +- .../tests/vectors/field_classes.toml | 28 ++++ 10 files changed, 298 insertions(+), 103 deletions(-) diff --git a/crates/candler-schemas/schema/evaluator-describe-result.schema.json b/crates/candler-schemas/schema/evaluator-describe-result.schema.json index 3c82c676..2b0d6e28 100644 --- a/crates/candler-schemas/schema/evaluator-describe-result.schema.json +++ b/crates/candler-schemas/schema/evaluator-describe-result.schema.json @@ -151,10 +151,10 @@ }, "Needs": { "additionalProperties": false, - "description": "What one kind of check needs from a run, written as an object whose five lists are all present, empty when the kind needs nothing of that sort.", + "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A key that is not one of these is refused.", "properties": { "artifacts": { - "description": "Globs, relative to the run, of the artifacts the check reads.", + "description": "Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced.", "items": { "type": "string" }, @@ -167,6 +167,11 @@ }, "type": "array" }, + "manifest": { + "default": false, + "description": "Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process.", + "type": "boolean" + }, "metadata": { "description": "The paths of the metadata fields the check reads.", "items": { @@ -174,6 +179,11 @@ }, "type": "array" }, + "raw": { + "default": false, + "description": "Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep.", + "type": "boolean" + }, "snapshots": { "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": { @@ -182,7 +192,7 @@ "type": "array" }, "trace": { - "description": "Whether the check reads the normalised trace.", + "description": "Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test.", "type": "boolean" } }, diff --git a/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json b/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json index bdc7d3e4..4813c669 100644 --- a/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json +++ b/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json @@ -60,19 +60,19 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One artifact of a run: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", + "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", "properties": { "abs": { - "description": "The absolute path of the artifact, valid where the evaluator runs.", + "description": "The absolute path of the file, valid where the evaluator runs.", "type": "string" }, "path": { "$ref": "#/$defs/RelPath", - "description": "The path of the artifact relative to the run." + "description": "The path of the file relative to the run." }, "sha256": { "$ref": "#/$defs/Digest", - "description": "The digest of the artifact's bytes." + "description": "The digest of the file's bytes." } }, "required": [ @@ -84,12 +84,16 @@ }, "ContextRaw": { "additionalProperties": false, - "description": "One raw stream of a run: its name and the path where the evaluator reads it, written as an object with the strings `stream` and `path`.", + "description": "One raw stream of a run: its name, the path where the evaluator reads it and its digest, written as an object with the strings `stream`, `path` and `sha256`.", "properties": { "path": { "description": "The absolute path of the stream, valid where the evaluator runs.", "type": "string" }, + "sha256": { + "$ref": "#/$defs/Digest", + "description": "The digest of the stream's bytes." + }, "stream": { "$ref": "#/$defs/StreamName", "description": "The name of the raw stream." @@ -97,7 +101,8 @@ }, "required": [ "stream", - "path" + "path", + "sha256" ], "type": "object" }, @@ -608,7 +613,7 @@ }, "RunContext": { "additionalProperties": false, - "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace when there is one, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", + "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", "properties": { "artifacts": { "description": "The artifacts of the run.", @@ -624,6 +629,10 @@ }, "type": "array" }, + "manifest": { + "$ref": "#/$defs/ContextArtifact", + "description": "The manifest of the run, served when the kind needs it; absent otherwise." + }, "metadata": { "additionalProperties": false, "description": "The metadata of the run, keyed by the dotted path of the field.", @@ -643,7 +652,7 @@ "type": "object" }, "raw": { - "description": "The raw streams of the run.", + "description": "The raw streams of the run, served when the kind needs them; empty otherwise.", "items": { "$ref": "#/$defs/ContextRaw" }, @@ -665,8 +674,8 @@ "type": "array" }, "trace": { - "description": "The absolute path of the normalised trace; absent when the run has none.", - "type": "string" + "$ref": "#/$defs/ContextArtifact", + "description": "The normalised trace, served when the kind needs it; absent otherwise." } }, "required": [ diff --git a/crates/candler-schemas/schema/evaluator-message.schema.json b/crates/candler-schemas/schema/evaluator-message.schema.json index 2c18715e..52c790bf 100644 --- a/crates/candler-schemas/schema/evaluator-message.schema.json +++ b/crates/candler-schemas/schema/evaluator-message.schema.json @@ -74,19 +74,19 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One artifact of a run: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", + "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", "properties": { "abs": { - "description": "The absolute path of the artifact, valid where the evaluator runs.", + "description": "The absolute path of the file, valid where the evaluator runs.", "type": "string" }, "path": { "$ref": "#/$defs/RelPath", - "description": "The path of the artifact relative to the run." + "description": "The path of the file relative to the run." }, "sha256": { "$ref": "#/$defs/Digest", - "description": "The digest of the artifact's bytes." + "description": "The digest of the file's bytes." } }, "required": [ @@ -98,12 +98,16 @@ }, "ContextRaw": { "additionalProperties": false, - "description": "One raw stream of a run: its name and the path where the evaluator reads it, written as an object with the strings `stream` and `path`.", + "description": "One raw stream of a run: its name, the path where the evaluator reads it and its digest, written as an object with the strings `stream`, `path` and `sha256`.", "properties": { "path": { "description": "The absolute path of the stream, valid where the evaluator runs.", "type": "string" }, + "sha256": { + "$ref": "#/$defs/Digest", + "description": "The digest of the stream's bytes." + }, "stream": { "$ref": "#/$defs/StreamName", "description": "The name of the raw stream." @@ -111,7 +115,8 @@ }, "required": [ "stream", - "path" + "path", + "sha256" ], "type": "object" }, @@ -501,10 +506,10 @@ }, "Needs": { "additionalProperties": false, - "description": "What one kind of check needs from a run, written as an object whose five lists are all present, empty when the kind needs nothing of that sort.", + "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A key that is not one of these is refused.", "properties": { "artifacts": { - "description": "Globs, relative to the run, of the artifacts the check reads.", + "description": "Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced.", "items": { "type": "string" }, @@ -517,6 +522,11 @@ }, "type": "array" }, + "manifest": { + "default": false, + "description": "Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process.", + "type": "boolean" + }, "metadata": { "description": "The paths of the metadata fields the check reads.", "items": { @@ -524,6 +534,11 @@ }, "type": "array" }, + "raw": { + "default": false, + "description": "Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep.", + "type": "boolean" + }, "snapshots": { "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": { @@ -532,7 +547,7 @@ "type": "array" }, "trace": { - "description": "Whether the check reads the normalised trace.", + "description": "Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test.", "type": "boolean" } }, @@ -1157,7 +1172,7 @@ }, "RunContext": { "additionalProperties": false, - "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace when there is one, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", + "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", "properties": { "artifacts": { "description": "The artifacts of the run.", @@ -1173,6 +1188,10 @@ }, "type": "array" }, + "manifest": { + "$ref": "#/$defs/ContextArtifact", + "description": "The manifest of the run, served when the kind needs it; absent otherwise." + }, "metadata": { "additionalProperties": false, "description": "The metadata of the run, keyed by the dotted path of the field.", @@ -1192,7 +1211,7 @@ "type": "object" }, "raw": { - "description": "The raw streams of the run.", + "description": "The raw streams of the run, served when the kind needs them; empty otherwise.", "items": { "$ref": "#/$defs/ContextRaw" }, @@ -1214,8 +1233,8 @@ "type": "array" }, "trace": { - "description": "The absolute path of the normalised trace; absent when the run has none.", - "type": "string" + "$ref": "#/$defs/ContextArtifact", + "description": "The normalised trace, served when the kind needs it; absent otherwise." } }, "required": [ diff --git a/crates/candler-schemas/schema/evaluator-request-side.schema.json b/crates/candler-schemas/schema/evaluator-request-side.schema.json index 95c070d3..004ad344 100644 --- a/crates/candler-schemas/schema/evaluator-request-side.schema.json +++ b/crates/candler-schemas/schema/evaluator-request-side.schema.json @@ -60,19 +60,19 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One artifact of a run: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", + "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", "properties": { "abs": { - "description": "The absolute path of the artifact, valid where the evaluator runs.", + "description": "The absolute path of the file, valid where the evaluator runs.", "type": "string" }, "path": { "$ref": "#/$defs/RelPath", - "description": "The path of the artifact relative to the run." + "description": "The path of the file relative to the run." }, "sha256": { "$ref": "#/$defs/Digest", - "description": "The digest of the artifact's bytes." + "description": "The digest of the file's bytes." } }, "required": [ @@ -84,12 +84,16 @@ }, "ContextRaw": { "additionalProperties": false, - "description": "One raw stream of a run: its name and the path where the evaluator reads it, written as an object with the strings `stream` and `path`.", + "description": "One raw stream of a run: its name, the path where the evaluator reads it and its digest, written as an object with the strings `stream`, `path` and `sha256`.", "properties": { "path": { "description": "The absolute path of the stream, valid where the evaluator runs.", "type": "string" }, + "sha256": { + "$ref": "#/$defs/Digest", + "description": "The digest of the stream's bytes." + }, "stream": { "$ref": "#/$defs/StreamName", "description": "The name of the raw stream." @@ -97,7 +101,8 @@ }, "required": [ "stream", - "path" + "path", + "sha256" ], "type": "object" }, @@ -730,7 +735,7 @@ }, "RunContext": { "additionalProperties": false, - "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace when there is one, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", + "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", "properties": { "artifacts": { "description": "The artifacts of the run.", @@ -746,6 +751,10 @@ }, "type": "array" }, + "manifest": { + "$ref": "#/$defs/ContextArtifact", + "description": "The manifest of the run, served when the kind needs it; absent otherwise." + }, "metadata": { "additionalProperties": false, "description": "The metadata of the run, keyed by the dotted path of the field.", @@ -765,7 +774,7 @@ "type": "object" }, "raw": { - "description": "The raw streams of the run.", + "description": "The raw streams of the run, served when the kind needs them; empty otherwise.", "items": { "$ref": "#/$defs/ContextRaw" }, @@ -787,8 +796,8 @@ "type": "array" }, "trace": { - "description": "The absolute path of the normalised trace; absent when the run has none.", - "type": "string" + "$ref": "#/$defs/ContextArtifact", + "description": "The normalised trace, served when the kind needs it; absent otherwise." } }, "required": [ diff --git a/crates/candler-schemas/schema/normalised-trace.schema.json b/crates/candler-schemas/schema/normalised-trace.schema.json index bb8e824b..839e2ed2 100644 --- a/crates/candler-schemas/schema/normalised-trace.schema.json +++ b/crates/candler-schemas/schema/normalised-trace.schema.json @@ -316,8 +316,12 @@ "$ref": "#/$defs/Denial", "description": "Who refused the call, when it was refused." }, + "exit": { + "$ref": "#/$defs/ExitStatus", + "description": "How the shell call ended, as the harness reported it: `{kind: code, code}` or `{kind: signal, signal}`. Absent when the call is not a shell call, was denied, or came back without a code." + }, "is_error": { - "description": "Whether the result is an error.", + "description": "Whether the harness marked the result as an error. A harness decides this for itself, so for a shell call it is not comparable across harnesses: read `exit` for the status.", "type": "boolean" }, "kind": { @@ -402,6 +406,51 @@ } ] }, + "ExitStatus": { + "description": "How a process ended: an object whose `kind` is `code` (with the integer `code`) or `signal` (with the integer `signal`).", + "oneOf": [ + { + "additionalProperties": false, + "description": "The process exited with a status code.", + "properties": { + "code": { + "description": "The exit code.", + "format": "int32", + "type": "integer" + }, + "kind": { + "const": "code", + "type": "string" + } + }, + "required": [ + "kind", + "code" + ], + "type": "object" + }, + { + "additionalProperties": false, + "description": "A signal ended the process.", + "properties": { + "kind": { + "const": "signal", + "type": "string" + }, + "signal": { + "description": "The signal number.", + "format": "int32", + "type": "integer" + } + }, + "required": [ + "kind", + "signal" + ], + "type": "object" + } + ] + }, "Finite": { "description": "A finite real number: neither `NaN` nor infinite. Negative zero is finite.", "format": "double", diff --git a/crates/candler-schemas/src/evaluation.rs b/crates/candler-schemas/src/evaluation.rs index 609dfe2f..95b58954 100644 --- a/crates/candler-schemas/src/evaluation.rs +++ b/crates/candler-schemas/src/evaluation.rs @@ -1332,15 +1332,21 @@ pub struct EvaluatorEnvironment { object_only!(EvaluatorEnvironment); -/// What one kind of check needs from a run, written as an object whose five lists are all present, empty when the kind needs nothing of that sort. +/// What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A key that is not one of these is refused. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -#[serde(remote = "Self")] +#[serde(remote = "Self", deny_unknown_fields)] #[schemars(deny_unknown_fields)] #[non_exhaustive] pub struct Needs { - /// Whether the check reads the normalised trace. + /// Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test. pub trace: bool, - /// Globs, relative to the run, of the artifacts the check reads. + /// Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep. + #[serde(default)] + pub raw: bool, + /// Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process. + #[serde(default)] + pub manifest: bool, + /// Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced. pub artifacts: Vec, /// 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 @@ -1528,7 +1534,7 @@ impl DescribeResultBuilder { } } -/// One raw stream of a run: its name and the path where the evaluator reads it, written as an object with the strings `stream` and `path`. +/// One raw stream of a run: its name, the path where the evaluator reads it and its digest, written as an object with the strings `stream`, `path` and `sha256`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(remote = "Self")] #[schemars(deny_unknown_fields)] @@ -1538,6 +1544,8 @@ pub struct ContextRaw { pub stream: StreamName, /// The absolute path of the stream, valid where the evaluator runs. pub path: String, + /// The digest of the stream's bytes. + pub sha256: Digest, } object_only!(ContextRaw); @@ -1545,29 +1553,33 @@ object_only!(ContextRaw); impl ContextRaw { /// A raw stream of a run. #[must_use] - pub const fn new(stream: StreamName, path: String) -> Self { - Self { stream, path } + pub const fn new(stream: StreamName, path: String, sha256: Digest) -> Self { + Self { + stream, + path, + sha256, + } } } -/// One artifact of a run: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. +/// One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(remote = "Self")] #[schemars(deny_unknown_fields)] #[non_exhaustive] pub struct ContextArtifact { - /// The path of the artifact relative to the run. + /// The path of the file relative to the run. pub path: RelPath, - /// The absolute path of the artifact, valid where the evaluator runs. + /// The absolute path of the file, valid where the evaluator runs. pub abs: String, - /// The digest of the artifact's bytes. + /// The digest of the file's bytes. pub sha256: Digest, } object_only!(ContextArtifact); impl ContextArtifact { - /// An artifact of a run. + /// A stored file of a run. #[must_use] pub const fn new(path: RelPath, abs: String, sha256: Digest) -> Self { Self { path, abs, sha256 } @@ -1598,7 +1610,7 @@ impl ContextRef { } } -/// What an evaluator may read of one run, written as an object: the run's key and root directory, the trace when there is one, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort. +/// What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort. #[derive(Deserialize, JsonSchema)] #[schemars(deny_unknown_fields, rename = "RunContext")] struct RawRunContext { @@ -1606,10 +1618,13 @@ struct RawRunContext { run: RunKey, /// The absolute path of the run's directory, valid where the evaluator runs. root: String, - /// The absolute path of the normalised trace; absent when the run has none. + /// The normalised trace, served when the kind needs it; absent otherwise. #[serde(default, deserialize_with = "present")] - trace: Option, - /// The raw streams of the run. + trace: Option, + /// The manifest of the run, served when the kind needs it; absent otherwise. + #[serde(default, deserialize_with = "present")] + manifest: Option, + /// The raw streams of the run, served when the kind needs them; empty otherwise. raw: Vec, /// The artifacts of the run. artifacts: Vec, @@ -1631,7 +1646,7 @@ impl TryFrom> for RunContext { } } -/// What an evaluator may read of one run, written as an object: the run's key and root directory, the trace when there is one, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort. +/// What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(try_from = "MapOnly")] #[non_exhaustive] @@ -1639,7 +1654,9 @@ pub struct RunContext { run: RunKey, root: String, #[serde(skip_serializing_if = "Option::is_none")] - trace: Option, + trace: Option, + #[serde(skip_serializing_if = "Option::is_none")] + manifest: Option, raw: Vec, artifacts: Vec, snapshots: Vec, @@ -1661,17 +1678,29 @@ impl RunContext { run, root, trace, + manifest, raw, artifacts, snapshots, inputs, metadata, } = raw; - let context_digest = context_digest(&artifacts, &snapshots, &inputs, &metadata)?; + let context_digest = context_digest( + &ServedParts { + trace: trace.as_ref(), + raw: &raw, + manifest: manifest.as_ref(), + }, + &artifacts, + &snapshots, + &inputs, + &metadata, + )?; Ok(Self { run, root, trace, + manifest, raw, artifacts, snapshots, @@ -1684,9 +1713,12 @@ impl RunContext { /// The digest of the part of the context that decides a verdict: `sha256` of the RFC 8785 /// form of `{artifacts: [{path, sha256}], snapshots: [{kind, digest}], inputs: [{kind, /// digest}], metadata}`, with the artifacts sorted by `path` and the snapshots and the inputs - /// by `(kind, digest)`, both by code point, and every key present. + /// by `(kind, digest)`, both by code point, and every key present. Each served part adds a + /// key, and only when it is served: `trace` and `manifest` are the digest of the file, and + /// `raw` is `[{stream, sha256}]` sorted by `stream` by code point, present when there is a + /// raw stream. /// - /// The run key, the root, the trace, the raw streams and the absolute paths are outside it, + /// The run key, the root and the paths of every file, absolute or relative, are outside it, /// so moving a run to another directory keeps its digest. #[must_use] pub fn context_digest(&self) -> Digest { @@ -1707,10 +1739,16 @@ impl RunContext { self.root.as_str() } - /// The absolute path of the normalised trace, if the run has one. + /// The normalised trace, if it is served. + #[must_use] + pub const fn trace<'a>(&'a self) -> Option<&'a ContextArtifact> { + self.trace.as_ref() + } + + /// The manifest of the run, if it is served. #[must_use] - pub fn trace<'a>(&'a self) -> Option<&'a str> { - self.trace.as_deref() + pub const fn manifest<'a>(&'a self) -> Option<&'a ContextArtifact> { + self.manifest.as_ref() } /// The raw streams of the run. @@ -1748,8 +1786,16 @@ impl RunContext { } } +/// The parts of a run that a context may serve beyond the artifacts, as they enter the digest. +struct ServedParts<'a> { + trace: Option<&'a ContextArtifact>, + raw: &'a [ContextRaw], + manifest: Option<&'a ContextArtifact>, +} + /// Computes [`RunContext::context_digest`]. fn context_digest( + served: &ServedParts<'_>, artifacts: &[ContextArtifact], snapshots: &[ContextRef], inputs: &[ContextRef], @@ -1769,26 +1815,42 @@ fn context_digest( .map(|r| json!({"kind": r.kind, "digest": r.digest})) .collect() }; - let projection = json!({ - "artifacts": artifacts, - "snapshots": refs(snapshots), - "inputs": refs(inputs), - "metadata": metadata, - }); + let mut projection = Map::new(); + projection.insert("artifacts".to_owned(), Value::from(artifacts)); + projection.insert("snapshots".to_owned(), Value::from(refs(snapshots))); + projection.insert("inputs".to_owned(), Value::from(refs(inputs))); + projection.insert("metadata".to_owned(), json!(metadata)); + if let Some(trace) = served.trace { + projection.insert("trace".to_owned(), json!(trace.sha256)); + } + if !served.raw.is_empty() { + let mut streams: Vec<&ContextRaw> = served.raw.iter().collect(); + streams.sort_by(|a, b| a.stream.cmp(&b.stream)); + let streams: Vec = streams + .iter() + .map(|r| json!({"stream": r.stream, "sha256": r.sha256})) + .collect(); + projection.insert("raw".to_owned(), Value::from(streams)); + } + if let Some(manifest) = served.manifest { + projection.insert("manifest".to_owned(), json!(manifest.sha256)); + } + let projection = Value::Object(projection); Ok(Digest::of_canonical(&projection)?) } /// Builds a [`RunContext`]. /// -/// `run` and `root` are required. `trace` is absent until set; the lists and the metadata are -/// empty until set, and `raw`, `artifact`, `snapshot`, `input` and `metadata` add one member per -/// call. +/// `run` and `root` are required. `trace` and `manifest` are absent until set; the lists and the +/// metadata are empty until set, and `raw`, `artifact`, `snapshot`, `input` and `metadata` add one +/// member per call. #[derive(Debug, Clone, Default)] #[non_exhaustive] pub struct RunContextBuilder { run: Option, root: Option, - trace: Option, + trace: Option, + manifest: Option, raw: Vec, artifacts: Vec, snapshots: Vec, @@ -1811,13 +1873,20 @@ impl RunContextBuilder { self } - /// Sets the path of the trace. + /// Sets the served trace. #[must_use] - pub fn trace(mut self, trace: String) -> Self { + pub fn trace(mut self, trace: ContextArtifact) -> Self { self.trace = Some(trace); self } + /// Sets the served manifest. + #[must_use] + pub fn manifest(mut self, manifest: ContextArtifact) -> Self { + self.manifest = Some(manifest); + self + } + /// Adds a raw stream. #[must_use] pub fn raw(mut self, raw: ContextRaw) -> Self { @@ -1864,6 +1933,7 @@ impl RunContextBuilder { run: self.run.ok_or_else(|| missing("run"))?, root: self.root.ok_or_else(|| missing("root"))?, trace: self.trace, + manifest: self.manifest, raw: self.raw, artifacts: self.artifacts, snapshots: self.snapshots, diff --git a/crates/candler-schemas/src/trace.rs b/crates/candler-schemas/src/trace.rs index 9384ebd4..7dd1d270 100644 --- a/crates/candler-schemas/src/trace.rs +++ b/crates/candler-schemas/src/trace.rs @@ -23,6 +23,7 @@ use crate::primitives::{ Digest, Name, NameVersion, ReasonCode, SEMVER_PATTERN, Timestamp, object_only, present, schema_tag, text_type, }; +use crate::process::ExitStatus; use crate::raw::{RawRef, StreamName}; /// The version marker of a trace file, written in its header. @@ -781,10 +782,14 @@ pub enum EventKind { /// A tool call came back. #[non_exhaustive] ToolResult { - /// Whether the result is an error. + /// Whether the harness marked the result as an error. A harness decides this for itself, + /// so for a shell call it is not comparable across harnesses: read `exit` for the status. is_error: bool, /// Who refused the call, when it was refused. denied: Option, + /// How the shell call ended, as the harness reported it. Absent when the call is not a + /// shell call, was denied, or came back without a code. + exit: Option, }, /// A line of the stream that is none of the other kinds; its content is in the event's `ext`. #[non_exhaustive] @@ -856,8 +861,16 @@ impl EventKind { /// A tool result. #[must_use] - pub const fn tool_result(is_error: bool, denied: Option) -> Self { - Self::ToolResult { is_error, denied } + pub const fn tool_result( + is_error: bool, + denied: Option, + exit: Option, + ) -> Self { + Self::ToolResult { + is_error, + denied, + exit, + } } /// A notification. @@ -950,7 +963,7 @@ enum KnownKind { }, /// A tool call came back. ToolResult { - /// Whether the result is an error. + /// Whether the harness marked the result as an error. A harness decides this for itself, so for a shell call it is not comparable across harnesses: read `exit` for the status. is_error: bool, /// Who refused the call, when it was refused. #[serde( @@ -959,6 +972,13 @@ enum KnownKind { deserialize_with = "present" )] denied: Option, + /// How the shell call ended, as the harness reported it: `{kind: code, code}` or `{kind: signal, signal}`. Absent when the call is not a shell call, was denied, or came back without a code. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present" + )] + exit: Option, }, /// A line of the stream that is none of the other kinds; its content is in the event's `ext`. Notification, diff --git a/crates/candler-schemas/tests/it/guard_context_digest.rs b/crates/candler-schemas/tests/it/guard_context_digest.rs index 72c6216b..6505456d 100644 --- a/crates/candler-schemas/tests/it/guard_context_digest.rs +++ b/crates/candler-schemas/tests/it/guard_context_digest.rs @@ -5,10 +5,9 @@ use std::str::FromStr; use candler_schemas::evaluation::{ - ContextArtifact, ContextRaw, ContextRef, EvaluateParams, RunContext, SuiteEntry, + ContextArtifact, ContextRef, EvaluateParams, RunContext, SuiteEntry, }; use candler_schemas::primitives::{Digest, FieldPath, Name, RelPath, RunKey}; -use candler_schemas::raw::StreamName; use candler_schemas::values::JsonValue; use serde_json::{Value, json}; @@ -52,8 +51,6 @@ type Edit = fn(&mut Parts); #[derive(Clone)] struct Parts { root: String, - trace: Option, - raw: Vec<(String, String)>, artifacts: Vec<(String, String, Digest)>, snapshots: Vec<(String, String, Digest)>, inputs: Vec<(String, String, Digest)>, @@ -61,15 +58,12 @@ struct Parts { } impl Parts { - /// A context with one of each part. + /// A context with one of each part it serves in every case of this file: no trace, raw stream or + /// manifest. fn base() -> Self { Self { // BORROW: .to_owned() makes the owned text the part keeps root: "/runs/a".to_owned(), - // BORROW: .to_owned() makes the owned text the part keeps - trace: Some("/runs/a/trace.jsonl".to_owned()), - // BORROW: .to_owned() makes the owned text each pair keeps - raw: vec![("stdout".to_owned(), "/runs/a/raw/stdout".to_owned())], artifacts: vec![( // BORROW: .to_owned() makes the owned text the triple keeps "outputs/plan.json".to_owned(), @@ -111,8 +105,6 @@ impl Parts { Self { // BORROW: .to_owned() makes the owned text the part keeps root: "/made/up".to_owned(), - trace: None, - raw: Vec::new(), artifacts: list("artifacts") .iter() .map(|a| { @@ -138,15 +130,6 @@ impl Parts { let run = RunKey::new(digest('a'), 1, 1).expect("a run key"); // BORROW: .clone() hands the builder its own copy of the root let mut builder = RunContext::builder().run(run).root(self.root.clone()); - if let Some(trace) = &self.trace { - // BORROW: .clone() hands the builder its own copy of the trace path - builder = builder.trace(trace.clone()); - } - for (stream, path) in &self.raw { - let stream = StreamName::from_str(stream).expect("a stream name"); - // BORROW: .clone() hands the builder its own copy of the path - builder = builder.raw(ContextRaw::new(stream, path.clone())); - } for (path, abs, sha256) in &self.artifacts { let path = RelPath::from_str(path).expect("a relative path"); // BORROW: .clone() hands the builder its own copy of the path and the digest @@ -174,7 +157,7 @@ impl Parts { /// Guards: Cond 7 — the context digest of each oracle case equals the digest /// Python computes from the RFC 8785 form of the case, however the lists are ordered; a change to -/// `root`, `trace`, `raw`, `scratch` or an absolute path keeps the digest, and a change to an +/// `root`, `scratch` or an absolute path keeps the digest, and a change to an /// artifact's `sha256`, a snapshot's or an input's digest or a metadata value changes it. /// Oracle: `context_digest.toml`, generated by Python `rfc8785`, and a hand-written table of /// edits. @@ -210,11 +193,9 @@ fn context_digest_follows_the_oracle_and_ignores_paths() { parts.context().context_digest() }; let base = Parts::base().context().context_digest(); - let keeps: [(&str, Edit); 6] = [ + let keeps: [(&str, Edit); 4] = [ // BORROW: .to_owned() makes the owned text the part keeps ("root", |p| p.root = "/elsewhere".to_owned()), - ("trace", |p| p.trace = None), - ("raw", |p| p.raw.clear()), ("artifact abs", |p| { // INDEX: the base context holds one member of each part, so index 0 exists // BORROW: .to_owned() makes the owned text the triple keeps diff --git a/crates/candler-schemas/tests/it/guard_evaluator_protocol.rs b/crates/candler-schemas/tests/it/guard_evaluator_protocol.rs index 9393d3f3..2ef7af20 100644 --- a/crates/candler-schemas/tests/it/guard_evaluator_protocol.rs +++ b/crates/candler-schemas/tests/it/guard_evaluator_protocol.rs @@ -280,8 +280,8 @@ fn an_outcome_notification_refuses_the_legacy_cause() { ); object_not_list::( "ContextRaw", - r#"{"stream":"stdout","path":"/p"}"#, - r#"["stdout","/p"]"#, + &format!(r#"{{"stream":"stdout","path":"/p","sha256":"{digest}"}}"#), + &format!(r#"["stdout","/p","{digest}"]"#), ); object_not_list::( "ContextArtifact", diff --git a/crates/candler-schemas/tests/vectors/field_classes.toml b/crates/candler-schemas/tests/vectors/field_classes.toml index 0fee138d..2e13f02d 100644 --- a/crates/candler-schemas/tests/vectors/field_classes.toml +++ b/crates/candler-schemas/tests/vectors/field_classes.toml @@ -133,7 +133,9 @@ "kinds[].needs" = "required" "kinds[].needs.artifacts" = "required" "kinds[].needs.inputs" = "required" +"kinds[].needs.manifest" = "optional" "kinds[].needs.metadata" = "required" +"kinds[].needs.raw" = "optional" "kinds[].needs.snapshots" = "required" "kinds[].needs.trace" = "required" "kinds[].params_schema" = "required" @@ -154,9 +156,14 @@ "context.inputs[].digest" = "required" "context.inputs[].kind" = "required" "context.inputs[].path" = "required" +"context.manifest" = "optional" +"context.manifest.abs" = "required" +"context.manifest.path" = "required" +"context.manifest.sha256" = "required" "context.metadata" = "required" "context.raw" = "required" "context.raw[].path" = "required" +"context.raw[].sha256" = "required" "context.raw[].stream" = "required" "context.root" = "required" "context.run" = "required" @@ -168,6 +175,9 @@ "context.snapshots[].kind" = "required" "context.snapshots[].path" = "required" "context.trace" = "optional" +"context.trace.abs" = "required" +"context.trace.path" = "required" +"context.trace.sha256" = "required" "items" = "candler" "items[].deadline_ms" = "required" "items[].expectation_id" = "required" @@ -226,9 +236,14 @@ "params.context.inputs[].digest" = "required" "params.context.inputs[].kind" = "required" "params.context.inputs[].path" = "required" +"params.context.manifest" = "optional" +"params.context.manifest.abs" = "required" +"params.context.manifest.path" = "required" +"params.context.manifest.sha256" = "required" "params.context.metadata" = "required" "params.context.raw" = "required" "params.context.raw[].path" = "required" +"params.context.raw[].sha256" = "required" "params.context.raw[].stream" = "required" "params.context.root" = "required" "params.context.run" = "required" @@ -240,6 +255,9 @@ "params.context.snapshots[].kind" = "required" "params.context.snapshots[].path" = "required" "params.context.trace" = "optional" +"params.context.trace.abs" = "required" +"params.context.trace.path" = "required" +"params.context.trace.sha256" = "required" "params.items" = "candler" "params.items[].deadline_ms" = "required" "params.items[].expectation_id" = "required" @@ -343,7 +361,9 @@ "result.kinds[].needs" = "required" "result.kinds[].needs.artifacts" = "required" "result.kinds[].needs.inputs" = "required" +"result.kinds[].needs.manifest" = "optional" "result.kinds[].needs.metadata" = "required" +"result.kinds[].needs.raw" = "optional" "result.kinds[].needs.snapshots" = "required" "result.kinds[].needs.trace" = "required" "result.kinds[].params_schema" = "required" @@ -415,9 +435,14 @@ "params.context.inputs[].digest" = "required" "params.context.inputs[].kind" = "required" "params.context.inputs[].path" = "required" +"params.context.manifest" = "optional" +"params.context.manifest.abs" = "required" +"params.context.manifest.path" = "required" +"params.context.manifest.sha256" = "required" "params.context.metadata" = "required" "params.context.raw" = "required" "params.context.raw[].path" = "required" +"params.context.raw[].sha256" = "required" "params.context.raw[].stream" = "required" "params.context.root" = "required" "params.context.run" = "required" @@ -429,6 +454,9 @@ "params.context.snapshots[].kind" = "required" "params.context.snapshots[].path" = "required" "params.context.trace" = "optional" +"params.context.trace.abs" = "required" +"params.context.trace.path" = "required" +"params.context.trace.sha256" = "required" "params.items" = "candler" "params.items[].deadline_ms" = "required" "params.items[].expectation_id" = "required" From a5b09166124d98371ecf3d069e3e1325d891cae8 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:42:23 +0900 Subject: [PATCH 14/93] refactor(adapter-claude-code): pass no exit to the tool result The event constructor takes the shell call's exit; the reader gives none yet. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-harness-claude-code/src/parse.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/candler-harness-claude-code/src/parse.rs b/crates/candler-harness-claude-code/src/parse.rs index b6fbd6a4..a3a7eeaa 100644 --- a/crates/candler-harness-claude-code/src/parse.rs +++ b/crates/candler-harness-claude-code/src/parse.rs @@ -315,7 +315,7 @@ fn block_draft(role: Role, block: &Value, line: &Map) -> Draft { .get("is_error") .and_then(Value::as_bool) .unwrap_or(false); - let mut draft = Draft::new(EventKind::tool_result(is_error, denial_of(line, id))); + let mut draft = Draft::new(EventKind::tool_result(is_error, denial_of(line, id), None)); draft.span = span_of(id, &mut draft.ext); draft } From 05d32dc563fb8b043c55612e10d365a0166c64bf Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:42:23 +0900 Subject: [PATCH 15/93] refactor(adapter-opencode): pass no exit to the tool result The event constructor takes the shell call's exit; the reader gives none yet. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-harness-opencode/src/export.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/candler-harness-opencode/src/export.rs b/crates/candler-harness-opencode/src/export.rs index 26ec5e6d..81f98518 100644 --- a/crates/candler-harness-opencode/src/export.rs +++ b/crates/candler-harness-opencode/src/export.rs @@ -209,7 +209,7 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>, servers: &[String] let status = state.and_then(|state| text(state, "status")); if matches!(status, Some("completed" | "error")) { let mut result = Draft::new( - EventKind::tool_result(status == Some("error"), None), + EventKind::tool_result(status == Some("error"), None, None), time("completed"), ); result.span = span; From 77739580e2822c3cd5689caaeb480c963986bc2d Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:42:54 +0900 Subject: [PATCH 16/93] feat(evaluator-helper): read the trace of a context as the object it is The generated models follow the schemas: needs gain raw and manifest, a context gains a manifest, and its trace and manifest carry their digests. The helper's context builder takes the trace's absolute path from the object. The vector check of the isolation test skips the vectors whose fault is in a kind's needs, which an envelope check does not read. Co-Authored-By: Claude Sonnet 5.5 --- .../_models/evaluator_describe_result.py | 21 +++++++-- .../_models/evaluator_evaluate_params.py | 26 ++++++++--- .../_models/evaluator_message.py | 45 +++++++++++++++---- .../_models/evaluator_request_side.py | 26 ++++++++--- .../src/candler_evaluator/plugin.py | 2 +- .../tests/test_guard_isolation.py | 2 + 6 files changed, 95 insertions(+), 27 deletions(-) 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 14143aee..76badd5e 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: 0e839d32e2e777f818b2f4641e89cb75e4541b0ddc9124592bbb2882b8122829 +# sha256: 83041f80a1a204ebc69ce729fc1562c4e37416d37744a668c7b1053d952a2258 from __future__ import annotations @@ -92,16 +92,28 @@ class Needs(BaseModel): artifacts: Annotated[ list[str], Field( - description="Globs, relative to the run, of the artifacts the check reads." + description="Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced." ), ] inputs: Annotated[ list[Name], Field(description="The kinds of input the check reads.") ] + manifest: Annotated[ + bool | None, + Field( + description="Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process." + ), + ] = False metadata: Annotated[ list[FieldPath], Field(description="The paths of the metadata fields the check reads."), ] + raw: Annotated[ + bool | None, + Field( + description="Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep." + ), + ] = False snapshots: Annotated[ list[Name], Field( @@ -109,7 +121,10 @@ class Needs(BaseModel): ), ] trace: Annotated[ - bool, Field(description="Whether the check reads the normalised trace.") + bool, + Field( + description="Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test." + ), ] 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 93968be2..e0ee8882 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: ecc2ca822aec9e321b7acc64ccca9c5598c7decba42595875d939126dfabaca4 +# sha256: a3ed8b6a4619d11f6f1da1ebb42d9c732f0f52e8f1505391a3dd1c8d24ae2d8d from __future__ import annotations @@ -330,13 +330,13 @@ class ContextArtifact(BaseModel): abs: Annotated[ str, Field( - description="The absolute path of the artifact, valid where the evaluator runs." + description="The absolute path of the file, valid where the evaluator runs." ), ] path: Annotated[ - RelPath, Field(description="The path of the artifact relative to the run.") + RelPath, Field(description="The path of the file relative to the run.") ] - sha256: Annotated[Digest, Field(description="The digest of the artifact's bytes.")] + sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] class ContextRaw(BaseModel): @@ -349,6 +349,7 @@ class ContextRaw(BaseModel): description="The absolute path of the stream, valid where the evaluator runs." ), ] + sha256: Annotated[Digest, Field(description="The digest of the stream's bytes.")] stream: Annotated[StreamName, Field(description="The name of the raw stream.")] @@ -569,6 +570,12 @@ class RunContext(BaseModel): inputs: Annotated[ list[ContextRef], Field(description="The inputs the run was made from.") ] + manifest: Annotated[ + ContextArtifact | None, + Field( + description="The manifest of the run, served when the kind needs it; absent otherwise." + ), + ] = None metadata: Annotated[ dict[ Annotated[ @@ -583,7 +590,12 @@ class RunContext(BaseModel): description="The metadata of the run, keyed by the dotted path of the field." ), ] - raw: Annotated[list[ContextRaw], Field(description="The raw streams of the run.")] + raw: Annotated[ + list[ContextRaw], + Field( + description="The raw streams of the run, served when the kind needs them; empty otherwise." + ), + ] root: Annotated[ str, Field( @@ -598,9 +610,9 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - str | None, + ContextArtifact | None, Field( - description="The absolute path of the normalised trace; absent when the run has none." + description="The normalised trace, served when the kind needs it; absent otherwise." ), ] = 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 f7da0485..8375e42b 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: 068864918640e9ca9e683cb70df83141236e53b60454ee375ba64bc0b340684c +# sha256: 25dae1782426d16d369d188077794ebd7928db291ec39f85a0cf782fcc7c2633 from __future__ import annotations @@ -166,16 +166,28 @@ class Needs(BaseModel): artifacts: Annotated[ list[str], Field( - description="Globs, relative to the run, of the artifacts the check reads." + description="Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced." ), ] inputs: Annotated[ list[Name], Field(description="The kinds of input the check reads.") ] + manifest: Annotated[ + bool | None, + Field( + description="Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process." + ), + ] = False metadata: Annotated[ list[FieldPath], Field(description="The paths of the metadata fields the check reads."), ] + raw: Annotated[ + bool | None, + Field( + description="Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep." + ), + ] = False snapshots: Annotated[ list[Name], Field( @@ -183,7 +195,10 @@ class Needs(BaseModel): ), ] trace: Annotated[ - bool, Field(description="Whether the check reads the normalised trace.") + bool, + Field( + description="Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test." + ), ] @@ -512,13 +527,13 @@ class ContextArtifact(BaseModel): abs: Annotated[ str, Field( - description="The absolute path of the artifact, valid where the evaluator runs." + description="The absolute path of the file, valid where the evaluator runs." ), ] path: Annotated[ - RelPath, Field(description="The path of the artifact relative to the run.") + RelPath, Field(description="The path of the file relative to the run.") ] - sha256: Annotated[Digest, Field(description="The digest of the artifact's bytes.")] + sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] class ContextRaw(BaseModel): @@ -531,6 +546,7 @@ class ContextRaw(BaseModel): description="The absolute path of the stream, valid where the evaluator runs." ), ] + sha256: Annotated[Digest, Field(description="The digest of the stream's bytes.")] stream: Annotated[StreamName, Field(description="The name of the raw stream.")] @@ -785,6 +801,12 @@ class RunContext(BaseModel): inputs: Annotated[ list[ContextRef], Field(description="The inputs the run was made from.") ] + manifest: Annotated[ + ContextArtifact | None, + Field( + description="The manifest of the run, served when the kind needs it; absent otherwise." + ), + ] = None metadata: Annotated[ dict[ Annotated[ @@ -799,7 +821,12 @@ class RunContext(BaseModel): description="The metadata of the run, keyed by the dotted path of the field." ), ] - raw: Annotated[list[ContextRaw], Field(description="The raw streams of the run.")] + raw: Annotated[ + list[ContextRaw], + Field( + description="The raw streams of the run, served when the kind needs them; empty otherwise." + ), + ] root: Annotated[ str, Field( @@ -814,9 +841,9 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - str | None, + ContextArtifact | None, Field( - description="The absolute path of the normalised trace; absent when the run has none." + description="The normalised trace, served when the kind needs it; absent otherwise." ), ] = 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 3ae1fbc5..da65f103 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: 0f621f5ddac76a745cc1a3946d9a7d55b90e638f93f9ec13a7694771f70b3501 +# sha256: efd739f905668936c947fe87dba686f464fe2e08bd540e14ecbe83a69c3c7092 from __future__ import annotations @@ -369,13 +369,13 @@ class ContextArtifact(BaseModel): abs: Annotated[ str, Field( - description="The absolute path of the artifact, valid where the evaluator runs." + description="The absolute path of the file, valid where the evaluator runs." ), ] path: Annotated[ - RelPath, Field(description="The path of the artifact relative to the run.") + RelPath, Field(description="The path of the file relative to the run.") ] - sha256: Annotated[Digest, Field(description="The digest of the artifact's bytes.")] + sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] class ContextRaw(BaseModel): @@ -388,6 +388,7 @@ class ContextRaw(BaseModel): description="The absolute path of the stream, valid where the evaluator runs." ), ] + sha256: Annotated[Digest, Field(description="The digest of the stream's bytes.")] stream: Annotated[StreamName, Field(description="The name of the raw stream.")] @@ -608,6 +609,12 @@ class RunContext(BaseModel): inputs: Annotated[ list[ContextRef], Field(description="The inputs the run was made from.") ] + manifest: Annotated[ + ContextArtifact | None, + Field( + description="The manifest of the run, served when the kind needs it; absent otherwise." + ), + ] = None metadata: Annotated[ dict[ Annotated[ @@ -622,7 +629,12 @@ class RunContext(BaseModel): description="The metadata of the run, keyed by the dotted path of the field." ), ] - raw: Annotated[list[ContextRaw], Field(description="The raw streams of the run.")] + raw: Annotated[ + list[ContextRaw], + Field( + description="The raw streams of the run, served when the kind needs them; empty otherwise." + ), + ] root: Annotated[ str, Field( @@ -637,9 +649,9 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - str | None, + ContextArtifact | None, Field( - description="The absolute path of the normalised trace; absent when the run has none." + description="The normalised trace, served when the kind needs it; absent otherwise." ), ] = None diff --git a/python/candler-evaluator/src/candler_evaluator/plugin.py b/python/candler-evaluator/src/candler_evaluator/plugin.py index 1225bc09..40b53f4a 100644 --- a/python/candler-evaluator/src/candler_evaluator/plugin.py +++ b/python/candler-evaluator/src/candler_evaluator/plugin.py @@ -114,7 +114,7 @@ def from_wire(cls, context: Mapping[str, Any], scratch: str) -> RunContext: scratch=Path(scratch), run=context["run"], raw=tuple(context["raw"]), - trace=None if trace is None else Path(trace), + trace=None if trace is None else Path(trace["abs"]), artifact_files=files, snapshots=tuple(context.get("snapshots", [])), inputs=tuple(context["inputs"]), diff --git a/python/candler-evaluator/tests/test_guard_isolation.py b/python/candler-evaluator/tests/test_guard_isolation.py index 63f4e89c..ae6d3e4a 100644 --- a/python/candler-evaluator/tests/test_guard_isolation.py +++ b/python/candler-evaluator/tests/test_guard_isolation.py @@ -62,6 +62,8 @@ def test_one_fault_costs_one_item(vectors, run_helper): for path in sorted((vectors / "valid").glob("*.json")): assert is_frame(json.loads(path.read_text())), path.name for path in sorted((vectors / "invalid").glob("*.json")): + if path.name.startswith("needs_"): + continue # the fault is in a kind's needs, which the envelope check does not read assert not is_frame(json.loads(path.read_text())), path.name params = { From 39e1a866d7089106dd191c51ac58074252f88141 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:43:28 +0900 Subject: [PATCH 17/93] docs(evaluator-protocol): regenerate the needs and the context sections Needs gain raw and manifest; the context holds an optional manifest, its trace and manifest are objects with a digest, and each raw stream carries its digest. The Notes are unchanged and stay within the budget. Co-Authored-By: Claude Sonnet 5.5 --- docs/contract/evaluator-protocol.md | 34 ++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/docs/contract/evaluator-protocol.md b/docs/contract/evaluator-protocol.md index d6d1373b..0eb879e5 100644 --- a/docs/contract/evaluator-protocol.md +++ b/docs/contract/evaluator-protocol.md @@ -36,7 +36,9 @@ Wire line: `schemas@0.13.0`. | `kinds[].needs` | `Needs` | required | - | | `kinds[].needs.artifacts` | `array of string` | required | - | | `kinds[].needs.inputs` | `array of Name` | required | - | +| `kinds[].needs.manifest` | `boolean` | optional | `false` | | `kinds[].needs.metadata` | `array of FieldPath` | required | - | +| `kinds[].needs.raw` | `boolean` | optional | `false` | | `kinds[].needs.snapshots` | `array of Name` | required | - | | `kinds[].needs.trace` | `boolean` | required | - | | `kinds[].params_schema` | `any` | required | - | @@ -60,9 +62,14 @@ Wire line: `schemas@0.13.0`. | `context.inputs[].digest` | `Digest` | required | - | | `context.inputs[].kind` | `Name` | required | - | | `context.inputs[].path` | `string` | required | - | +| `context.manifest` | `ContextArtifact` | optional | - | +| `context.manifest.abs` | `string` | required | - | +| `context.manifest.path` | `RelPath` | required | - | +| `context.manifest.sha256` | `Digest` | required | - | | `context.metadata` | `map` | required | - | | `context.raw` | `array of ContextRaw` | required | - | | `context.raw[].path` | `string` | required | - | +| `context.raw[].sha256` | `Digest` | required | - | | `context.raw[].stream` | `StreamName` | required | - | | `context.root` | `string` | required | - | | `context.run` | `RunKey` | required | - | @@ -73,7 +80,10 @@ Wire line: `schemas@0.13.0`. | `context.snapshots[].digest` | `Digest` | required | - | | `context.snapshots[].kind` | `Name` | required | - | | `context.snapshots[].path` | `string` | required | - | -| `context.trace` | `string` | optional | - | +| `context.trace` | `ContextArtifact` | optional | - | +| `context.trace.abs` | `string` | required | - | +| `context.trace.path` | `RelPath` | required | - | +| `context.trace.sha256` | `Digest` | required | - | | `items` | `array of Item` | candler | - | | `items[].deadline_ms` | `integer` | required | - | | `items[].expectation_id` | `ExpectationId` | required | - | @@ -148,9 +158,14 @@ Wire line: `schemas@0.13.0`. | `params.context.inputs[].digest` | `Digest` | required | - | | `params.context.inputs[].kind` | `Name` | required | - | | `params.context.inputs[].path` | `string` | required | - | +| `params.context.manifest` | `ContextArtifact` | optional | - | +| `params.context.manifest.abs` | `string` | required | - | +| `params.context.manifest.path` | `RelPath` | required | - | +| `params.context.manifest.sha256` | `Digest` | required | - | | `params.context.metadata` | `map` | required | - | | `params.context.raw` | `array of ContextRaw` | required | - | | `params.context.raw[].path` | `string` | required | - | +| `params.context.raw[].sha256` | `Digest` | required | - | | `params.context.raw[].stream` | `StreamName` | required | - | | `params.context.root` | `string` | required | - | | `params.context.run` | `RunKey` | required | - | @@ -161,7 +176,10 @@ Wire line: `schemas@0.13.0`. | `params.context.snapshots[].digest` | `Digest` | required | - | | `params.context.snapshots[].kind` | `Name` | required | - | | `params.context.snapshots[].path` | `string` | required | - | -| `params.context.trace` | `string` | optional | - | +| `params.context.trace` | `ContextArtifact` | optional | - | +| `params.context.trace.abs` | `string` | required | - | +| `params.context.trace.path` | `RelPath` | required | - | +| `params.context.trace.sha256` | `Digest` | required | - | | `params.items` | `array of Item` | candler | - | | `params.items[].deadline_ms` | `integer` | required | - | | `params.items[].expectation_id` | `ExpectationId` | required | - | @@ -302,7 +320,9 @@ Wire line: `schemas@0.13.0`. | `result.kinds[].needs` | `Needs` | required | - | | `result.kinds[].needs.artifacts` | `array of string` | required | - | | `result.kinds[].needs.inputs` | `array of Name` | required | - | +| `result.kinds[].needs.manifest` | `boolean` | optional | `false` | | `result.kinds[].needs.metadata` | `array of FieldPath` | required | - | +| `result.kinds[].needs.raw` | `boolean` | optional | `false` | | `result.kinds[].needs.snapshots` | `array of Name` | required | - | | `result.kinds[].needs.trace` | `boolean` | required | - | | `result.kinds[].params_schema` | `any` | required | - | @@ -419,9 +439,14 @@ Wire line: `schemas@0.13.0`. | `params.context.inputs[].digest` | `Digest` | required | - | | `params.context.inputs[].kind` | `Name` | required | - | | `params.context.inputs[].path` | `string` | required | - | +| `params.context.manifest` | `ContextArtifact` | optional | - | +| `params.context.manifest.abs` | `string` | required | - | +| `params.context.manifest.path` | `RelPath` | required | - | +| `params.context.manifest.sha256` | `Digest` | required | - | | `params.context.metadata` | `map` | required | - | | `params.context.raw` | `array of ContextRaw` | required | - | | `params.context.raw[].path` | `string` | required | - | +| `params.context.raw[].sha256` | `Digest` | required | - | | `params.context.raw[].stream` | `StreamName` | required | - | | `params.context.root` | `string` | required | - | | `params.context.run` | `RunKey` | required | - | @@ -432,7 +457,10 @@ Wire line: `schemas@0.13.0`. | `params.context.snapshots[].digest` | `Digest` | required | - | | `params.context.snapshots[].kind` | `Name` | required | - | | `params.context.snapshots[].path` | `string` | required | - | -| `params.context.trace` | `string` | optional | - | +| `params.context.trace` | `ContextArtifact` | optional | - | +| `params.context.trace.abs` | `string` | required | - | +| `params.context.trace.path` | `RelPath` | required | - | +| `params.context.trace.sha256` | `Digest` | required | - | | `params.items` | `array of Item` | candler | - | | `params.items[].deadline_ms` | `integer` | required | - | | `params.items[].expectation_id` | `ExpectationId` | required | - | From a31a88e7a52520ec62dcd1519b40a3f6db26f848 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:49:37 +0900 Subject: [PATCH 18/93] style(adapter-claude-code): wrap the tool result call as rustfmt does Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-harness-claude-code/src/parse.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/candler-harness-claude-code/src/parse.rs b/crates/candler-harness-claude-code/src/parse.rs index a3a7eeaa..99050dcc 100644 --- a/crates/candler-harness-claude-code/src/parse.rs +++ b/crates/candler-harness-claude-code/src/parse.rs @@ -315,7 +315,8 @@ fn block_draft(role: Role, block: &Value, line: &Map) -> Draft { .get("is_error") .and_then(Value::as_bool) .unwrap_or(false); - let mut draft = Draft::new(EventKind::tool_result(is_error, denial_of(line, id), None)); + let mut draft = + Draft::new(EventKind::tool_result(is_error, denial_of(line, id), None)); draft.span = span_of(id, &mut draft.ext); draft } From 657bbf9a7125d2ea9900946c130774ddc1799aed Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:51:34 +0900 Subject: [PATCH 19/93] test(schemas): check the refused exit rows before the kept ones A reader that takes exit as free JSON now fails on the refused row it accepts, not on the key order of a kept row. Co-Authored-By: Claude Sonnet 5.5 --- .../tests/it/guard_trace_wire.rs | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/crates/candler-schemas/tests/it/guard_trace_wire.rs b/crates/candler-schemas/tests/it/guard_trace_wire.rs index 8f251b24..1945635b 100644 --- a/crates/candler-schemas/tests/it/guard_trace_wire.rs +++ b/crates/candler-schemas/tests/it/guard_trace_wire.rs @@ -426,8 +426,9 @@ fn an_mcp_origin_without_a_tool_still_reads_and_one_with_it_round_trips() { /// Guards: normalised-trace/1 — a `tool_result` carries an optional `exit`, the process exit /// object `{kind, code}`: a line with one reads and is written back as it was, a result without /// one still reads, and an `exit` that is not that object (a bare `{code}`, a string, `null`) is -/// refused, so the wire has one reading of it. Oracle: the event lines below, written by hand from the architecture's -/// §Normalised trace model and §Wire encodings; the line without `exit` is the positive control. +/// refused, so the wire has one reading of it. Oracle: the event lines below, written by hand +/// from the architecture's §Normalised trace model and §Wire encodings; the line without `exit` +/// is the positive control. #[test] fn a_tool_result_carries_its_exit_as_the_process_exit_object_and_nothing_else() { let file_with = |event: &str| { @@ -439,17 +440,6 @@ fn a_tool_result_carries_its_exit_as_the_process_exit_object_and_nothing_else() text.into_bytes() }; - let kept = [ - r#"{"kind":"tool_result","is_error":false}"#, - r#"{"kind":"tool_result","is_error":true,"exit":{"kind":"code","code":3}}"#, - r#"{"kind":"tool_result","is_error":false,"exit":{"kind":"code","code":0}}"#, - ]; - for event in kept { - let literal = file_with(event); - let file = TraceFile::read(&literal).unwrap_or_else(|e| panic!("{event} is refused: {e}")); - assert_eq!(file.write(), literal, "{event} is not written back as read"); - } - let refused = [ r#"{"kind":"tool_result","is_error":true,"exit":{"code":3}}"#, r#"{"kind":"tool_result","is_error":true,"exit":"3"}"#, @@ -461,4 +451,15 @@ fn a_tool_result_carries_its_exit_as_the_process_exit_object_and_nothing_else() "{event} is accepted" ); } + + let kept = [ + r#"{"kind":"tool_result","is_error":false}"#, + r#"{"kind":"tool_result","is_error":true,"exit":{"kind":"code","code":3}}"#, + r#"{"kind":"tool_result","is_error":false,"exit":{"kind":"code","code":0}}"#, + ]; + for event in kept { + let literal = file_with(event); + let file = TraceFile::read(&literal).unwrap_or_else(|e| panic!("{event} is refused: {e}")); + assert_eq!(file.write(), literal, "{event} is not written back as read"); + } } From 29b39f0e8740fe75130840ce527b99dd75d37e69 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:52:23 +0900 Subject: [PATCH 20/93] reports(schemas): close the exit field and the new needs Co-Authored-By: Claude Sonnet 5.5 --- .../leaves/schema_exit_needs_v0.md | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 __reports__/run-context/leaves/schema_exit_needs_v0.md diff --git a/__reports__/run-context/leaves/schema_exit_needs_v0.md b/__reports__/run-context/leaves/schema_exit_needs_v0.md new file mode 100644 index 00000000..3c37aaba --- /dev/null +++ b/__reports__/run-context/leaves/schema_exit_needs_v0.md @@ -0,0 +1,55 @@ +# Leaf report: schema_exit_needs (v0) + +Branch `leaf/run-context/schema_exit_needs`, cut from `feat/run-context` at `abdf7c22`. + +## Spec defects, first + +1. **`exit` on a `tool_call` line is not refused by the Rust reader, and the base does not refuse a `tool_result` with `exit` either.** The leaf says both are refused as an unknown field. `__design__/architecture.md` §Wire encodings, row "Unknown fields", says readers of the records Candler writes ignore unknown fields so an older reader reads a newer record, and `KnownKind` has no serde `deny_unknown_fields` (only the schema has `additionalProperties: false`). On the base the line with `exit` reads and the `exit` is dropped; the guard failed there as "not written back as read" and, in its final order, as "`{"code":3}` is accepted". The guard therefore asserts the refusals that hold (a bare `{code}`, a string, `null`) and omits the `tool_call` row. Meeting the row would mean refusing unknown keys on every event, which reverses that rule; it is the lead's call. +2. **`Needs` now refuses an unknown key in serde** (`deny_unknown_fields`), which the gate "needs that carry an unknown key are invalid, both readers alike" requires: on the base the Rust reader ignored an unknown key in `needs` (`needs_unknown_key.json` was accepted), so a plug-in's misspelt need would be silently unserved. This departs from the blanket "Unknown fields" sentence for a describe result; AGENTS.md's one-reader rule supports it. Removing the attribute is one line if the lead rules otherwise. + +## Guards, each seen red on the base and under its bite + +| Guard | Base failing message | Bite and its failing message | +|---|---|---| +| `guard_trace_wire::a_tool_result_carries_its_exit_as_the_process_exit_object_and_nothing_else` | `{"kind":"tool_result","is_error":true,"exit":{"code":3}} is accepted` (first version of the test: `...exit":{"kind":"code","code":3}} is not written back as read`) | `exit` typed `Option`: `{"kind":"tool_result","is_error":true,"exit":{"code":3}} is accepted` | +| `guard_rpc_wire::the_envelope_accepts_valid_messages_and_refuses_single_faults` (vectors `response_describe_needs_raw_manifest`, `needs_raw_not_boolean`, `needs_unknown_key`) and `test_guard_wire_vectors.py` | Rust: `needs_raw_not_boolean.json is accepted`; Python: `response_describe_needs_raw_manifest.json` refused (assert `[...] == []`) | `raw` with a deserialiser that takes any value: `needs_raw_not_boolean.json is accepted`; no `deny_unknown_fields`: `needs_unknown_key.json is accepted` | +| `guard_context_digest::the_digest_of_a_context_adds_a_key_for_each_served_part_and_only_for_those` (rows of the new `context_digest_served.toml`) | `a context: Error("invalid type: map, expected a string")` | trace key left out when served: `assertion left == right failed: a served trace (input)` | +| `guard_context_digest::context_digest_follows_the_oracle_and_ignores_paths` (the four existing rows, unchanged) | passes on the base | trace key always added: `empty lists and empty metadata (input)` fails (the new rows fail too) | + +The helper's `test_guard_isolation.py` checks the invalid vectors with an envelope-only `is_frame`; it now skips `needs_*` vectors, whose fault that check cannot see. + +Existing digest rows: `context_digest.toml`, `context_digest_runs.toml` and the other generated files are byte-identical after the generator was extended (`gen_vectors.py --check` regenerates them). The new rows are a new file, `context_digest_served.toml`, five contexts from `gen_vectors.py` over python `rfc8785` (ASSUMED note 14 gives the spelling: `trace` and `manifest` are the digest string, `raw` is `[{stream, sha256}]` sorted by stream, each only when served). The old test of `context_digest_follows_the_oracle_and_ignores_paths` kept its claim for root and absolute paths and lost its `trace` and `raw` rows, because those parts now enter the digest; the new test covers them. + +## Marker + +`normalised-trace/1` stays. `__design__/architecture.md` §Wire encodings: "Absent vs null" (an optional field is omitted when absent), "Rust shape" (a new optional field is a minor in Rust as in the schema) and "Version marker" (the marker is the `schema` tag of the header, which names the file's shape family, not each field) say an optional field does not move it; the §Normalised trace model section names no rule that does. Old traces lack `exit` and read unchanged. + +## Type of `{path, abs, sha256}` + +`ContextArtifact` is reused for `context.trace` and `context.manifest`; only its doc was reworded from "artifact" to "stored file of a run" (its fields say path, abs, sha256 and are true for all three). A rename to a new shared name would have churned the schema definition, the generated models and every caller for no change in shape. `ContextRaw` keeps its own `path` (absolute) and gains `sha256`. + +## Commits and builds + +| Commit | Builds | +|---|---| +| `test(schemas): state the exit field, the new needs and their digest keys` | yes (guards red) | +| `feat(schemas)!: carry a shell call's exit and the stored run's needs` | schemas crate yes; workspace no: the two readers still call `tool_result` with two arguments. No API added only for that | +| `refactor(adapter-claude-code): pass no exit to the tool result` | workspace builds only after the next commit | +| `refactor(adapter-opencode): pass no exit to the tool result` | yes, from here the workspace builds | +| `style(adapter-claude-code): wrap the tool result call as rustfmt does` | yes (the commit above it was not formatted) | +| `feat(evaluator-helper): read the trace of a context as the object it is` | yes | +| `docs(evaluator-protocol): regenerate the needs and the context sections` | yes | +| `test(schemas): check the refused exit rows before the kept ones` | yes | +| this report | yes | + +## Checks on the tip + +`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps`, `cargo nextest run --workspace` (735 passed, 32 skipped); helper `uv run pytest` (12 passed), `uv run ruff check`, `gen_models.py` leaves no diff; `scripts/contract_versions.py --check` exits 0; `git grep -n confirm_ -- crates python` prints nothing. `container-e2e` was not run (CI). + +## Left for other leaves, and observations + +- `crates/candler-core/src/evaluation/engine/run.rs` unions the needs of the sent entries field by field and does not copy `raw` or `manifest`; `serve_context` must fold them, or a declared need is dropped silently. +- The contract page's Notes are unchanged (the page is at its 120-word budget); the new needs, `exit` and the `is_error` caveat reach the schema descriptions, not the page. Whether a Note should state them, at the price of an older one, is open. +- The generated Python `Needs.raw` and `Needs.manifest` are typed `bool | None` with default `False`, so the helper's model takes `null` where the Rust reader and the schema (`type: boolean`) refuse it. No vector tests it. +- The helper's new API (typed trace, manifest, raw digests) is `helper_context`'s; here `RunContext.from_wire` takes the trace's `abs` and nothing else changed by hand. +- Spend was not measured from transcripts. From fc77fa54841cc52144260bdc19d10a5e9b484deb Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:55:53 +0900 Subject: [PATCH 21/93] fix(schemas): read an unknown key in needs as its siblings do Needs ignores an unknown key in serde, as KindSpec and DescribeResult do; the schema still refuses it. The needs_unknown_key vector goes, with its README row. Co-Authored-By: Claude Sonnet 5.5 --- .../evaluator-describe-result.schema.json | 2 +- .../schema/evaluator-message.schema.json | 2 +- crates/candler-schemas/src/evaluation.rs | 4 +- .../tests/fixtures/rpc/README.md | 1 - .../rpc/invalid/needs_unknown_key.json | 45 ------------------- .../tests/it/guard_rpc_wire.rs | 2 +- 6 files changed, 5 insertions(+), 51 deletions(-) delete mode 100644 crates/candler-schemas/tests/fixtures/rpc/invalid/needs_unknown_key.json diff --git a/crates/candler-schemas/schema/evaluator-describe-result.schema.json b/crates/candler-schemas/schema/evaluator-describe-result.schema.json index 2b0d6e28..a7c2d8fb 100644 --- a/crates/candler-schemas/schema/evaluator-describe-result.schema.json +++ b/crates/candler-schemas/schema/evaluator-describe-result.schema.json @@ -151,7 +151,7 @@ }, "Needs": { "additionalProperties": false, - "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A key that is not one of these is refused.", + "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent.", "properties": { "artifacts": { "description": "Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced.", diff --git a/crates/candler-schemas/schema/evaluator-message.schema.json b/crates/candler-schemas/schema/evaluator-message.schema.json index 52c790bf..50e0cfa8 100644 --- a/crates/candler-schemas/schema/evaluator-message.schema.json +++ b/crates/candler-schemas/schema/evaluator-message.schema.json @@ -506,7 +506,7 @@ }, "Needs": { "additionalProperties": false, - "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A key that is not one of these is refused.", + "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent.", "properties": { "artifacts": { "description": "Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced.", diff --git a/crates/candler-schemas/src/evaluation.rs b/crates/candler-schemas/src/evaluation.rs index 95b58954..9b192f2c 100644 --- a/crates/candler-schemas/src/evaluation.rs +++ b/crates/candler-schemas/src/evaluation.rs @@ -1332,9 +1332,9 @@ pub struct EvaluatorEnvironment { object_only!(EvaluatorEnvironment); -/// What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A key that is not one of these is refused. +/// What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -#[serde(remote = "Self", deny_unknown_fields)] +#[serde(remote = "Self")] #[schemars(deny_unknown_fields)] #[non_exhaustive] pub struct Needs { diff --git a/crates/candler-schemas/tests/fixtures/rpc/README.md b/crates/candler-schemas/tests/fixtures/rpc/README.md index 87c1a68a..57ee59cb 100644 --- a/crates/candler-schemas/tests/fixtures/rpc/README.md +++ b/crates/candler-schemas/tests/fixtures/rpc/README.md @@ -25,4 +25,3 @@ Invalid, each is one fault on a valid base and must be refused: | `unknown_key` | a top-level key `extra` | §4: the members are those listed | | `result_and_method` | `result` beside `method` | §5: `result` belongs to a response only | | `needs_raw_not_boolean` | a kind's `needs.raw` is the string `"yes"` | R01 §Evaluator protocol: `needs.raw` is a boolean | -| `needs_unknown_key` | a kind's `needs` has a key `traces` | R01 §Evaluator protocol: the members of `needs` are those listed | diff --git a/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_unknown_key.json b/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_unknown_key.json deleted file mode 100644 index 1c3ba28d..00000000 --- a/crates/candler-schemas/tests/fixtures/rpc/invalid/needs_unknown_key.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "jsonrpc": "2.0", - "id": "0192f4e0-7b3a-7c1d-8a2e-4f5b6c7d8e9f", - "result": { - "protocol": { - "major": 1, - "minor": 0 - }, - "name": "demo-evaluator", - "version": "0.1.0", - "instruments": [ - { - "name": "demo-grader", - "version": "1.0.0", - "digest": "git:0123456789abcdef0123456789abcdef01234567", - "dirty": false - } - ], - "environment": { - "packages": { - "demo": "1.0.0" - } - }, - "kind": "deterministic", - "kinds": [ - { - "kind": "file_exists", - "params_schema": { - "type": "object" - }, - "needs": { - "trace": false, - "artifacts": [ - "plan.md" - ], - "snapshots": [], - "inputs": [], - "metadata": [], - "traces": true - }, - "default_deadline_ms": 5000 - } - ] - } -} \ No newline at end of file diff --git a/crates/candler-schemas/tests/it/guard_rpc_wire.rs b/crates/candler-schemas/tests/it/guard_rpc_wire.rs index a48695b3..cb0ecc96 100644 --- a/crates/candler-schemas/tests/it/guard_rpc_wire.rs +++ b/crates/candler-schemas/tests/it/guard_rpc_wire.rs @@ -56,7 +56,7 @@ fn the_envelope_accepts_valid_messages_and_refuses_single_faults() { let valid = vectors("valid"); let invalid = vectors("invalid"); assert_eq!(valid.len(), 10, "the valid vectors are all present"); - assert_eq!(invalid.len(), 8, "the invalid vectors are all present"); + assert_eq!(invalid.len(), 7, "the invalid vectors are all present"); for (name, text) in &valid { let result = serde_json::from_str::(text); assert!(result.is_ok(), "{name} is refused: {result:?}"); From 31d17dd352d92a97c7e16a852599fc01dc168f61 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:56:14 +0900 Subject: [PATCH 22/93] fix(evaluator-helper): regenerate the models for the needs description Co-Authored-By: Claude Sonnet 5.5 --- .../src/candler_evaluator/_models/evaluator_describe_result.py | 2 +- .../src/candler_evaluator/_models/evaluator_message.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 76badd5e..fb23e9d9 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: 83041f80a1a204ebc69ce729fc1562c4e37416d37744a668c7b1053d952a2258 +# sha256: 0c06e2aaff04266fd208b23bc0cf1e6e73118e8f97f8ac4d05fb987fc5310087 from __future__ import annotations 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 8375e42b..7fe0212d 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: 25dae1782426d16d369d188077794ebd7928db291ec39f85a0cf782fcc7c2633 +# sha256: 6a104f6d1ad9fca9aa06465db154be09a838e0849cbbf89359193b6c4fc3cebe from __future__ import annotations From feb5dbd22e48e7eaebb4c52680f5f56f99462006 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:58:07 +0900 Subject: [PATCH 23/93] reports(schemas): record the rulings on the two spec defects Co-Authored-By: Claude Sonnet 5.5 --- __reports__/run-context/leaves/schema_exit_needs_v0.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/__reports__/run-context/leaves/schema_exit_needs_v0.md b/__reports__/run-context/leaves/schema_exit_needs_v0.md index 3c37aaba..9627e33f 100644 --- a/__reports__/run-context/leaves/schema_exit_needs_v0.md +++ b/__reports__/run-context/leaves/schema_exit_needs_v0.md @@ -4,15 +4,17 @@ Branch `leaf/run-context/schema_exit_needs`, cut from `feat/run-context` at `abd ## Spec defects, first -1. **`exit` on a `tool_call` line is not refused by the Rust reader, and the base does not refuse a `tool_result` with `exit` either.** The leaf says both are refused as an unknown field. `__design__/architecture.md` §Wire encodings, row "Unknown fields", says readers of the records Candler writes ignore unknown fields so an older reader reads a newer record, and `KnownKind` has no serde `deny_unknown_fields` (only the schema has `additionalProperties: false`). On the base the line with `exit` reads and the `exit` is dropped; the guard failed there as "not written back as read" and, in its final order, as "`{"code":3}` is accepted". The guard therefore asserts the refusals that hold (a bare `{code}`, a string, `null`) and omits the `tool_call` row. Meeting the row would mean refusing unknown keys on every event, which reverses that rule; it is the lead's call. -2. **`Needs` now refuses an unknown key in serde** (`deny_unknown_fields`), which the gate "needs that carry an unknown key are invalid, both readers alike" requires: on the base the Rust reader ignored an unknown key in `needs` (`needs_unknown_key.json` was accepted), so a plug-in's misspelt need would be silently unserved. This departs from the blanket "Unknown fields" sentence for a describe result; AGENTS.md's one-reader rule supports it. Removing the attribute is one line if the lead rules otherwise. +Both were ruled on by the coordinator (gate amended on `feat/run-context` at `69da51c0`). + +1. **`exit` on a `tool_call` line is not refused by the Rust reader, and the base does not refuse a `tool_result` with `exit` either.** `__design__/architecture.md` §Wire encodings, row "Unknown fields", says readers of the records Candler writes ignore unknown fields, and `KnownKind` has no serde `deny_unknown_fields` (only the schema has `additionalProperties: false`). Ruling: the reader ignores it, only the schema refuses it, and the base evidence is "reads and loses `exit` on write-back". The guard asserts the refusals that hold (a bare `{code}`, a string, `null`) and the round trip; no `tool_call` row. No code change. +2. **`Needs` ignores an unknown key in serde**, as `KindSpec` and `DescribeResult` do, while the schema refuses it. I had made `Needs` alone strict; the coordinator ruled that this left one message with two rules, so it is reverted (`fix(schemas): read an unknown key in needs as its siblings do`) and the `needs_unknown_key.json` vector is deleted. Whether the whole describe result should refuse unknown keys goes to the maintainer separately. ## Guards, each seen red on the base and under its bite | Guard | Base failing message | Bite and its failing message | |---|---|---| | `guard_trace_wire::a_tool_result_carries_its_exit_as_the_process_exit_object_and_nothing_else` | `{"kind":"tool_result","is_error":true,"exit":{"code":3}} is accepted` (first version of the test: `...exit":{"kind":"code","code":3}} is not written back as read`) | `exit` typed `Option`: `{"kind":"tool_result","is_error":true,"exit":{"code":3}} is accepted` | -| `guard_rpc_wire::the_envelope_accepts_valid_messages_and_refuses_single_faults` (vectors `response_describe_needs_raw_manifest`, `needs_raw_not_boolean`, `needs_unknown_key`) and `test_guard_wire_vectors.py` | Rust: `needs_raw_not_boolean.json is accepted`; Python: `response_describe_needs_raw_manifest.json` refused (assert `[...] == []`) | `raw` with a deserialiser that takes any value: `needs_raw_not_boolean.json is accepted`; no `deny_unknown_fields`: `needs_unknown_key.json is accepted` | +| `guard_rpc_wire::the_envelope_accepts_valid_messages_and_refuses_single_faults` (vectors `response_describe_needs_raw_manifest` and `needs_raw_not_boolean`) and `test_guard_wire_vectors.py` | Rust: `needs_raw_not_boolean.json is accepted`; Python: `response_describe_needs_raw_manifest.json` refused (assert `[...] == []`) | `raw` with a deserialiser that takes any value: `needs_raw_not_boolean.json is accepted` | | `guard_context_digest::the_digest_of_a_context_adds_a_key_for_each_served_part_and_only_for_those` (rows of the new `context_digest_served.toml`) | `a context: Error("invalid type: map, expected a string")` | trace key left out when served: `assertion left == right failed: a served trace (input)` | | `guard_context_digest::context_digest_follows_the_oracle_and_ignores_paths` (the four existing rows, unchanged) | passes on the base | trace key always added: `empty lists and empty metadata (input)` fails (the new rows fail too) | @@ -40,6 +42,8 @@ Existing digest rows: `context_digest.toml`, `context_digest_runs.toml` and the | `feat(evaluator-helper): read the trace of a context as the object it is` | yes | | `docs(evaluator-protocol): regenerate the needs and the context sections` | yes | | `test(schemas): check the refused exit rows before the kept ones` | yes | +| `fix(schemas): read an unknown key in needs as its siblings do` | yes | +| `fix(evaluator-helper): regenerate the models for the needs description` | yes | | this report | yes | ## Checks on the tip From 983cc8a7ffccfbd6e463977e1b66783591719fdf Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:06:46 +0900 Subject: [PATCH 24/93] test(schemas): state the bites and pick the served case by content Co-Authored-By: Claude Sonnet 5.5 --- .../tests/it/guard_context_digest.rs | 24 ++++++++++++------- .../tests/it/guard_trace_wire.rs | 2 +- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/crates/candler-schemas/tests/it/guard_context_digest.rs b/crates/candler-schemas/tests/it/guard_context_digest.rs index 6505456d..9e7fce8f 100644 --- a/crates/candler-schemas/tests/it/guard_context_digest.rs +++ b/crates/candler-schemas/tests/it/guard_context_digest.rs @@ -58,7 +58,7 @@ struct Parts { } impl Parts { - /// A context with one of each part it serves in every case of this file: no trace, raw stream or + /// A context with one artifact, snapshot, input and metadata value, and no trace, raw stream or /// manifest. fn base() -> Self { Self { @@ -359,14 +359,14 @@ fn read_context(wire: Value) -> RunContext { /// computes from the RFC 8785 form of the projection with one more key for each served part (the /// raw streams sorted by stream); the paths of a served part stay outside the digest, its digest /// is inside it, and a part that is not served adds no key. Oracle: `context_digest_served.toml`, -/// generated by Python `rfc8785`, whose projection is written from the plan's wire shape, and -/// the four rows of `context_digest.toml` for the contexts that serve none of the parts. -/// Bite: the trace key is always added (the old rows go red); the key is left out when served -/// (these rows go red). +/// generated by Python `rfc8785` from the projection of `__design__/architecture.md` §Evaluator +/// protocol (Digests of a request) with the keys its generator documents; `context_digest.toml` +/// holds the contexts that serve none of the parts. +/// Bite: the trace key added when not served turns the rows of `context_digest.toml` red; the key +/// left out when served turns the served rows red. #[test] fn the_digest_of_a_context_adds_a_key_for_each_served_part_and_only_for_those() { let cases = vectors(SERVED_VECTORS); - assert_eq!(cases.len(), 5); for case in &cases { // INDEX: every served vector carries `title`, `digest`, `input` and `sorted` // BORROW: .as_str() reads the text of a TOML value @@ -391,8 +391,16 @@ fn the_digest_of_a_context_adds_a_key_for_each_served_part_and_only_for_those() // The case that serves all three parts, edited one fact at a time. // INDEX: the fourth served vector serves all three parts - let all: Value = - serde_json::from_str(cases[3]["sorted"].as_str().expect("JSON text")).expect("JSON"); + let all: Value = cases + .iter() + // BORROW: .as_str() reads the JSON text of a TOML value + .filter_map(|case| serde_json::from_str::(case["sorted"].as_str()?).ok()) + .find(|p| { + ["trace", "raw", "manifest"] + .iter() + .all(|k| p.get(*k).is_some()) + }) + .expect("the oracle holds a case that serves a trace, raw streams and a manifest"); let digest_of = |edit: WireEdit| { let mut wire = wire_context(&all); edit(&mut wire); diff --git a/crates/candler-schemas/tests/it/guard_trace_wire.rs b/crates/candler-schemas/tests/it/guard_trace_wire.rs index 1945635b..250c0159 100644 --- a/crates/candler-schemas/tests/it/guard_trace_wire.rs +++ b/crates/candler-schemas/tests/it/guard_trace_wire.rs @@ -428,7 +428,7 @@ fn an_mcp_origin_without_a_tool_still_reads_and_one_with_it_round_trips() { /// one still reads, and an `exit` that is not that object (a bare `{code}`, a string, `null`) is /// refused, so the wire has one reading of it. Oracle: the event lines below, written by hand /// from the architecture's §Normalised trace model and §Wire encodings; the line without `exit` -/// is the positive control. +/// is the positive control. Bite: `exit` typed as a free JSON value, so the refused rows read. #[test] fn a_tool_result_carries_its_exit_as_the_process_exit_object_and_nothing_else() { let file_with = |event: &str| { From 59e885496b18d9432084cb661c3eb368b2601b68 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:06:47 +0900 Subject: [PATCH 25/93] fix(schemas): describe only what the wire carries in the needs docs The trace need no longer mentions an event the schema cannot hold, and ContextArtifact says that the trace and the manifest have its shape. Co-Authored-By: Claude Sonnet 5.5 --- .../schema/evaluator-describe-result.schema.json | 2 +- .../schema/evaluator-evaluate-params.schema.json | 2 +- crates/candler-schemas/schema/evaluator-message.schema.json | 4 ++-- .../candler-schemas/schema/evaluator-request-side.schema.json | 2 +- crates/candler-schemas/src/evaluation.rs | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/candler-schemas/schema/evaluator-describe-result.schema.json b/crates/candler-schemas/schema/evaluator-describe-result.schema.json index a7c2d8fb..4f1ef82d 100644 --- a/crates/candler-schemas/schema/evaluator-describe-result.schema.json +++ b/crates/candler-schemas/schema/evaluator-describe-result.schema.json @@ -192,7 +192,7 @@ "type": "array" }, "trace": { - "description": "Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test.", + "description": "Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage.", "type": "boolean" } }, diff --git a/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json b/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json index 4813c669..780f5bd0 100644 --- a/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json +++ b/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json @@ -60,7 +60,7 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", + "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", "properties": { "abs": { "description": "The absolute path of the file, valid where the evaluator runs.", diff --git a/crates/candler-schemas/schema/evaluator-message.schema.json b/crates/candler-schemas/schema/evaluator-message.schema.json index 50e0cfa8..1343adb1 100644 --- a/crates/candler-schemas/schema/evaluator-message.schema.json +++ b/crates/candler-schemas/schema/evaluator-message.schema.json @@ -74,7 +74,7 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", + "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", "properties": { "abs": { "description": "The absolute path of the file, valid where the evaluator runs.", @@ -547,7 +547,7 @@ "type": "array" }, "trace": { - "description": "Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test.", + "description": "Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage.", "type": "boolean" } }, diff --git a/crates/candler-schemas/schema/evaluator-request-side.schema.json b/crates/candler-schemas/schema/evaluator-request-side.schema.json index 004ad344..748f8107 100644 --- a/crates/candler-schemas/schema/evaluator-request-side.schema.json +++ b/crates/candler-schemas/schema/evaluator-request-side.schema.json @@ -60,7 +60,7 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`.", + "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", "properties": { "abs": { "description": "The absolute path of the file, valid where the evaluator runs.", diff --git a/crates/candler-schemas/src/evaluation.rs b/crates/candler-schemas/src/evaluation.rs index 9b192f2c..0d4d7596 100644 --- a/crates/candler-schemas/src/evaluation.rs +++ b/crates/candler-schemas/src/evaluation.rs @@ -1338,7 +1338,7 @@ object_only!(EvaluatorEnvironment); #[schemars(deny_unknown_fields)] #[non_exhaustive] pub struct Needs { - /// Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test. + /// Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. pub trace: bool, /// Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep. #[serde(default)] @@ -1562,7 +1562,7 @@ impl ContextRaw { } } -/// One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. +/// One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(remote = "Self")] #[schemars(deny_unknown_fields)] From fde4f5a0d6da464f982b8dcaf8ec361f8d7aa6fb Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:06:47 +0900 Subject: [PATCH 26/93] fix(evaluator-helper): regenerate the models for the needs docs Co-Authored-By: Claude Sonnet 5.5 --- .../candler_evaluator/_models/evaluator_describe_result.py | 4 ++-- .../candler_evaluator/_models/evaluator_evaluate_params.py | 2 +- .../src/candler_evaluator/_models/evaluator_message.py | 4 ++-- .../src/candler_evaluator/_models/evaluator_request_side.py | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) 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 fb23e9d9..03c1a111 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: 0c06e2aaff04266fd208b23bc0cf1e6e73118e8f97f8ac4d05fb987fc5310087 +# sha256: 8feb70c5893c7633830cfad09f533a8e8f1708388903192e151939075c6b2914 from __future__ import annotations @@ -123,7 +123,7 @@ class Needs(BaseModel): trace: Annotated[ bool, Field( - description="Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test." + description="Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage." ), ] 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 e0ee8882..4a9dfbe0 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: a3ed8b6a4619d11f6f1da1ebb42d9c732f0f52e8f1505391a3dd1c8d24ae2d8d +# sha256: e169785d20bc401b87b6bb74b917b9af827c1ad5ef5e917be8db8617ed533e3d from __future__ import annotations 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 7fe0212d..0942467c 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: 6a104f6d1ad9fca9aa06465db154be09a838e0849cbbf89359193b6c4fc3cebe +# sha256: 0e4283779332598799f3ebf26f753d358c1788f8b317a5768b19c2a82317b73b from __future__ import annotations @@ -197,7 +197,7 @@ class Needs(BaseModel): trace: Annotated[ bool, Field( - description="Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. When the trace holds a `context_start` event, declaring this need hands the kind the run's system text and first message verbatim, which may be the treatment under test." + description="Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage." ), ] 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 da65f103..1e2a7d99 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: efd739f905668936c947fe87dba686f464fe2e08bd540e14ecbe83a69c3c7092 +# sha256: 293e488295656b18da5eb3638b7cc02387711ff22f708d6840834e9f61f4cdb6 from __future__ import annotations From 38856a8e455d16f1565ac288acb3ed8f07bec2c7 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:07:38 +0900 Subject: [PATCH 27/93] docs(design): state the served parts of the run context and its digest Co-Authored-By: Claude Sonnet 5.5 --- __design__/architecture.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/__design__/architecture.md b/__design__/architecture.md index 95a62328..fc91e924 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -1026,15 +1026,17 @@ as the evaluator's log. | ↳ result | | response | `{reported: n}` | | `cancel` | core → evaluator | notification | request id; the evaluator answers `evaluate` with error `-32800` (request cancelled) | -**`needs`** = `{trace: bool, artifacts[] (run-relative globs), snapshots[] (kinds), inputs[] -(kinds), metadata[] (run-manifest field paths)}`. `resolve` checks every need the core can meet +**`needs`** = `{trace: bool, raw: bool, manifest: bool, artifacts[] (run-relative globs), +snapshots[] (kinds), inputs[] (kinds), metadata[] (run-manifest field paths)}`; `raw` and +`manifest` read as `false` when absent. `resolve` checks every need the core can meet without a run; an `inputs` need for `build_inputs` is refused there, by name. A need a run cannot meet, such as a kind the run holds in neither list, is refused for that run, by name. **Run context:** `run` (key); `root` (a read-only, workspace-shaped view of the run: content- addressed blobs materialised under their workspace paths by hard links or clones, so `domain.py` -sits beside `problems.py`); `trace` (normalised trace file); `raw[]`; `artifacts[] {path -(run-relative), abs, sha256}`; `snapshots[] {kind, path, digest}`; `inputs[] {kind, path, digest}` +sits beside `problems.py`); `trace {path, abs, sha256}` (the normalised trace file) and `manifest {path, abs, sha256}` +(the run manifest), each present only when the kind needs it; `raw[] {stream, path, sha256}`; +`artifacts[] {path (run-relative), abs, sha256}`; `snapshots[] {kind, path, digest}`; `inputs[] {kind, path, digest}` (a need for kind K is served from `comparable.inputs` or from `evaluation_inputs`, with `path` a read-only tree: its files read-only, its directories writable, as under `outputs/`; an input only the evaluators see never enters the isolation, I8); `metadata` (the declared manifest fields). Absolute paths are valid where the @@ -1049,8 +1051,11 @@ them as optional is released. - `context_digest` covers the projection `{artifacts: [{path, sha256}], snapshots: [{kind, digest}], inputs: [{kind, digest}], metadata: {: value}}`: lists sorted by `path` or - by `(kind, digest)`, every key present (lists possibly empty). Absolute paths, `root`, `trace`, - `raw[]` and `scratch` are outside it: they say where the run is, not what was graded. + by `(kind, digest)`, every key present (lists possibly empty). Each served part adds a key, and + only when it is served: `trace` (its sha256), `raw` (`[{stream, sha256}]` sorted by `stream`) + and `manifest` (its sha256), so a context that serves none of them has the digest of the + projection above. Absolute paths, run-relative paths of served files, `root` and `scratch` are + outside it: they say where the run is, not what was graded. - `suite_entry_digest` covers `{kind, params, role, depends_on, applies_to?}` of one suite entry: `depends_on` sorted, `applies_to` omitted when absent. `id`, `group`, `evaluator` and `deadline_ms` are outside it, so renaming an expectation or moving its deadline keeps its digest. @@ -1235,7 +1240,7 @@ never compares an inventory with one of another source. The census names no serv `Session {id, source{harness, harness_version, reader, reader_version}, model, started_at?, ended_at?, ended_by, parent_session?, raw_ref}`; `Event {seq, at?, kind, span?, raw_ref, ext}` with kinds `user_message`, `assistant_message`, `tool_call` (`origin`, `argv?`, `wrapped_calls[]?` for a -call that bundles several MCP calls), `tool_result` (`is_error`, `denied?`), `notification`, `usage` +call that bundles several MCP calls), `tool_result` (`is_error`, `denied?`, `exit?`: the shell call's `ExitStatus` as the harness reported it, absent for a non-shell, denied or uncoded result), `notification`, `usage` (`scope: message | session_total`). `at` comes from the harness when it emits one, else from the frame time in the raw file, else it is absent. From fb03568b482b69b782a2edc773f20fc3f2755b0b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:07:38 +0900 Subject: [PATCH 28/93] reports(schemas): bring the leaf report up to date with the rulings Co-Authored-By: Claude Sonnet 5.5 --- __reports__/run-context/leaves/schema_exit_needs_v0.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/__reports__/run-context/leaves/schema_exit_needs_v0.md b/__reports__/run-context/leaves/schema_exit_needs_v0.md index 9627e33f..79577ba8 100644 --- a/__reports__/run-context/leaves/schema_exit_needs_v0.md +++ b/__reports__/run-context/leaves/schema_exit_needs_v0.md @@ -57,3 +57,10 @@ Existing digest rows: `context_digest.toml`, `context_digest_runs.toml` and the - The generated Python `Needs.raw` and `Needs.manifest` are typed `bool | None` with default `False`, so the helper's model takes `null` where the Rust reader and the schema (`type: boolean`) refuse it. No vector tests it. - The helper's new API (typed trace, manifest, raw digests) is `helper_context`'s; here `RunContext.from_wire` takes the trace's `abs` and nothing else changed by hand. - Spend was not measured from transcripts. + +## Later changes + +- The `context_start` sentence of the `Needs.trace` doc was dropped by the coordinator's ruling `c33c6b82`: whichever of M6d and M6.5 lands second writes it. The schemas and models were re-blessed. +- The exit test doc has its `Bite:` line; the digest test doc cites §Evaluator protocol (Digests of a request) and picks its served case by content; `ContextArtifact`'s doc says the trace and the manifest have its shape. +- `__design__/architecture.md` §Evaluator protocol states the `raw` and `manifest` needs, the object shape of `trace`, `manifest` and `raw[]`, and the served-part keys of `context_digest`; §Normalised trace model lists `exit?`. +- Commits since the rulings: `fix(schemas): read an unknown key in needs as its siblings do`, `fix(evaluator-helper): regenerate the models for the needs description`, `test(schemas): state the bites and pick the served case by content`, `fix(schemas): describe only what the wire carries in the needs docs`, `fix(evaluator-helper): regenerate the models for the needs docs`, `docs(design): state the served parts of the run context and its digest`. From 62038d1cffb1ba716c28a652ccab415df5bf3454 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:09:45 +0900 Subject: [PATCH 29/93] rdm(evaluation): close the schema leaf and open level 2 The schema leaf is merged, so the readers level starts: both trace readers, the serving in assemble/materialise and the Python helper run in parallel, each on its own worktree. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/README.md | 8 ++++---- __roadmap__/run_context/readers/README.md | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/__roadmap__/run_context/README.md b/__roadmap__/run_context/README.md index dfc8ba22..6f1d5fb3 100644 --- a/__roadmap__/run_context/README.md +++ b/__roadmap__/run_context/README.md @@ -21,9 +21,9 @@ An evaluator plug-in that declares `needs.trace`, `needs.raw` or `needs.manifest ## Status ```mermaid graph TD - schema_exit_needs[Schema: exit and needs]:::inprogress + schema_exit_needs[Schema: exit and needs]:::done probe_shell_shapes[Probe: shell shapes]:::done - readers[Readers and serving]:::planned + readers[Readers and serving]:::inprogress classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -34,9 +34,9 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `schema_exit_needs.md` | 📄 Leaf Task | 🔄 In Progress | +| `schema_exit_needs.md` | 📄 Leaf Task | ✅ Done | | `probe_shell_shapes.md` | 📄 Leaf Task | ✅ Done | -| `readers/` | 📁 Directory | ⬜ Planned | +| `readers/` | 📁 Directory | 🔄 In Progress | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/run_context/readers/README.md b/__roadmap__/run_context/readers/README.md index 80a04dc5..d84d12d6 100644 --- a/__roadmap__/run_context/readers/README.md +++ b/__roadmap__/run_context/readers/README.md @@ -16,10 +16,10 @@ Both trace readers record the harness's exit status, `assemble`/`materialise` se ## Status ```mermaid graph TD - cc_reader_exit[Claude Code exit]:::planned - oc_reader_exit[OpenCode exit]:::planned - serve_context[Serve the run]:::planned - helper_context[Helper context]:::planned + cc_reader_exit[Claude Code exit]:::inprogress + oc_reader_exit[OpenCode exit]:::inprogress + serve_context[Serve the run]:::inprogress + helper_context[Helper context]:::inprogress e2e[Consumer path]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -31,10 +31,10 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `cc_reader_exit.md` | 📄 Leaf Task | ⬜ Planned | -| `oc_reader_exit.md` | 📄 Leaf Task | ⬜ Planned | -| `serve_context.md` | 📄 Leaf Task | ⬜ Planned | -| `helper_context.md` | 📄 Leaf Task | ⬜ Planned | +| `cc_reader_exit.md` | 📄 Leaf Task | 🔄 In Progress | +| `oc_reader_exit.md` | 📄 Leaf Task | 🔄 In Progress | +| `serve_context.md` | 📄 Leaf Task | 🔄 In Progress | +| `helper_context.md` | 📄 Leaf Task | 🔄 In Progress | | `e2e/` | 📁 Directory | ⬜ Planned | ## Amendment Log From e04c3871d599134f89ddafda3a9136470d7c4f1e Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:12:54 +0900 Subject: [PATCH 30/93] test(adapter-opencode): state each shell call's exit from the export Co-Authored-By: Claude Sonnet 5.5 --- .../tests/it/guard_opencode_driver.rs | 58 ++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) 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 e54a11f1..7c45b1bf 100644 --- a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs +++ b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs @@ -761,7 +761,7 @@ fn opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions() -> json!({"kind": "tool_call", "name": "shell", "origin": {"kind": "builtin"}, "argv": ["echo hello-from-tool > /work/o1.txt && cat /work/o1.txt"], "wrapped_calls": []}), - json!({"kind": "tool_result", "is_error": false}), + json!({"kind": "tool_result", "is_error": false, "exit": {"kind": "code", "code": 0}}), usage("message", 100, 20), json!({"kind": "assistant_message", "text": "done: the tool finished."}), usage("message", 100, 20), @@ -798,6 +798,62 @@ fn opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions() -> results, vec![json!({"kind": "tool_result", "is_error": true})] ); + + // Exit: a `shell` call that completed carries the code in `state.metadata.exit`; a call whose + // state is an error, or that reported none (the timed-out call is `completed` with a signal + // name and no code), carries none. Expected values come from + // `jq -c '[.messages[].content[]? | select(.type == "tool") | .state.metadata.exit]'`. + let exit_rows: [(&str, Vec); 4] = [ + ( + "shell_exit_stderr_timeout", + vec![ + json!({"kind": "tool_result", "is_error": false, "exit": {"kind": "code", "code": 3}}), + json!({"kind": "tool_result", "is_error": false, "exit": {"kind": "code", "code": 2}}), + json!({"kind": "tool_result", "is_error": false}), + ], + ), + ( + "sigint_mid_tool", + vec![json!({"kind": "tool_result", "is_error": true})], + ), + ( + "oc_permission_ask", + vec![json!({"kind": "tool_result", "is_error": true})], + ), + ( + "interrupt_api", + vec![json!({"kind": "tool_result", "is_error": true})], + ), + ]; + for (fixture, expected) in exit_rows { + let (events, _) = read_export(&stream_file(fixture, "export.json")?)?; + let results: Vec = kinds(&events)? + .into_iter() + .filter(|k| k["kind"] == "tool_result") + .collect(); + assert_eq!(results, expected, "{fixture}"); + } + // A tool that is not `shell` carries no exit even when its state holds one. + let other_tool = json!({ + "info": {"id": "ses_x", "outcome": "succeeded"}, + "messages": [ + {"id": "m1", "type": "user", "text": "go"}, + {"id": "m2", "type": "assistant", "finish": "stop", "content": [ + {"type": "tool", "id": "chatcmpl-tool-x", "name": "read", + "state": {"status": "completed", "input": {}, "metadata": {"exit": 7}}} + ]} + ] + }); + let (events, _) = read_export(&serde_json::to_vec(&other_tool)?)?; + let results: Vec = kinds(&events)? + .into_iter() + .filter(|k| k["kind"] == "tool_result") + .collect(); + assert_eq!( + results, + vec![json!({"kind": "tool_result", "is_error": false})] + ); + let (events, sessions) = read_export(&stream_file("unknown_model_local", "export.json")?)?; let labels: Vec = kinds(&events)? .iter() From 49f196914fdd0345b9d1cc941813eb3d4d987321 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:13:16 +0900 Subject: [PATCH 31/93] feat(adapter-opencode): read a shell call's exit status Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-harness-opencode/src/export.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/candler-harness-opencode/src/export.rs b/crates/candler-harness-opencode/src/export.rs index 81f98518..bb820c63 100644 --- a/crates/candler-harness-opencode/src/export.rs +++ b/crates/candler-harness-opencode/src/export.rs @@ -11,6 +11,7 @@ use candler_harness::reader::{FrameIn, ReaderError, TraceReader}; use candler_harness::spec::{Confidence, FormatVersion, Framing, Observed, ObservedEnd}; use candler_schemas::outcome::Finite; use candler_schemas::primitives::{NameVersion, ReasonCode, Timestamp}; +use candler_schemas::process::ExitStatus; use candler_schemas::raw::StreamName; use candler_schemas::trace::{ EndedBy, Event, EventKind, Session, SessionEvent, SessionId, SpanId, ToolOrigin, UsageScope, @@ -188,6 +189,20 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>, servers: &[String] .map(|command| vec![command.to_owned()]) // BORROW: .to_owned() makes owned text }) .flatten(); + // The code OpenCode reports for a `shell` call in `state.metadata.exit`. A call that ended in + // an error state, that reported none (a timeout reports a signal name and no code), or that is + // not `shell` has none. + let exit = (name == "shell" + && state.and_then(|state| text(state, "status")) == Some("completed")) + .then(|| { + state + .and_then(|state| field(state, "metadata")) + .and_then(|metadata| metadata.get("exit")) + .and_then(Value::as_i64) + .and_then(|code| i32::try_from(code).ok()) + .map(|code| ExitStatus::Code { code }) + }) + .flatten(); 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( @@ -209,7 +224,7 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>, servers: &[String] let status = state.and_then(|state| text(state, "status")); if matches!(status, Some("completed" | "error")) { let mut result = Draft::new( - EventKind::tool_result(status == Some("error"), None, None), + EventKind::tool_result(status == Some("error"), None, exit), time("completed"), ); result.span = span; From 6f27bead16d4b3d0e739f133aa318d8629b320a8 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:25:30 +0900 Subject: [PATCH 32/93] reports(adapter-opencode): close the shell exit status Co-Authored-By: Claude Sonnet 5.5 --- .../run-context/leaves/oc_reader_exit_v0.md | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 __reports__/run-context/leaves/oc_reader_exit_v0.md diff --git a/__reports__/run-context/leaves/oc_reader_exit_v0.md b/__reports__/run-context/leaves/oc_reader_exit_v0.md new file mode 100644 index 00000000..a3c8292e --- /dev/null +++ b/__reports__/run-context/leaves/oc_reader_exit_v0.md @@ -0,0 +1,80 @@ +# Leaf report: OpenCode exit + +Leaf: `__roadmap__/run_context/readers/oc_reader_exit.md`. Branch `leaf/run-context/oc_reader_exit`. + +## The exit rule as implemented + +In `tool_drafts` (`crates/candler-harness-opencode/src/export.rs`), beside the `argv` reading: a part +named `shell` whose `state.status` is `completed` and whose `state.metadata.exit` is an integer gives +`exit: {kind: code, code: N}` on its result. Everything else gives none: an error state (`aborted`, +`permission.rejected`, ...), a `completed` state with no `metadata.exit` (the probe's timed-out call, +which reports `signal: "SIGTERM"` and `timeout: true`), a non-integer or out-of-range value, and any +tool that is not `shell`. The reader reads no `signal` key, no `timeout` key and no tool output text, +and never builds a signal from a code. + +The probe (question 1) found the code at `state.metadata.exit` as the plan expected, so the rule is +the plan's. The probe's table says "whatever the status"; the leaf Goal says an error state has none. +No recorded error state carries `metadata.exit`, so the two agree on every fixture; the code follows +the leaf. + +## The oracle + +Expected values come from `jq` over each `export.json`, never from the reader: + +``` +jq -c '[.messages[]?.content[]? | select(.type=="tool") + | {id, name, status: .state.status, exit: .state.metadata.exit, + signal: .state.metadata.signal, timeout: .state.metadata.timeout, err: .state.error.type}]' \ + crates/candler-harness-opencode/tests/fixtures/streams//export.json +``` + +| Fixture | name | status | exit | other | expected `exit` on the result | +|---|---|---|---|---|---| +| `completed_o1` | shell | completed | 0 | | code 0 | +| `shell_exit_stderr_timeout` call 1 | shell | completed | 3 | | code 3 | +| `shell_exit_stderr_timeout` call 2 (stderr only) | shell | completed | 2 | | code 2 | +| `shell_exit_stderr_timeout` call 3 | shell | completed | null | signal SIGTERM, timeout true | none | +| `sigint_mid_tool`, `interrupt_api` | shell | error | null | `aborted` | none | +| `oc_permission_ask` | shell | error | null | `permission.rejected` | none | +| inline document, tool `read` | read | completed | 7 (hand-written) | | none | + +No recorded export holds a non-`shell` tool, so that row is an inline document in the table whose +`metadata.exit` is set to 7 to show the rule reads the tool's name. + +## Guards on the base + +Table: `opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions`. On the base +(`exit` column added, reader passing `None`) it fails at the first row, `completed_o1`: + +``` +assertion `left == right` failed + left: ... {"is_error": false, "kind": "tool_result"} ... + right: ... {"exit": {"code": 0, "kind": "code"}, "is_error": false, "kind": "tool_result"} ... +``` + +The rows after it (the probe's code 3 and code 2) are not reached on the base because the table +stops at its first failure; the probe's rows were seen failing under bite (b) below, and the rows +without an exit (aborted, rejected, `read`) pass on the base by design: they guard against reading +too much. + +## Bites + +Each applied on a scratch branch (deleted), the table run, the first failing message recorded. + +| Bite | Change | Failing message | +|---|---|---| +| (a) `metadata.exit` read only on error states | `Some("completed")` replaced by `Some("error")` in the status test | `completed_o1` row: left `{"is_error": false, "kind": "tool_result"}`, right carries `"exit": {"code": 0, "kind": "code"}` | +| (b) a missing `metadata.exit` taken as 0 | `.or(Some(0))` after `as_i64` | `assertion left == right failed: shell_exit_stderr_timeout`: left's third result carries `"exit": {"code": 0, ...}`, right's carries none | + +## Finding outside the leaf + +`cargo nextest run --workspace` has one failure, not caused by this leaf: +`candler-core::it guard_harness_facts::harness_census_equals_cf3de30_on_every_fixture` panics with +`no baseline for streams/shell_exit_stderr_timeout` (`guard_harness_facts.rs:726`). The probe's new +fixture directory has no baseline row in that census. The other 734 tests pass. The fix belongs to +whoever owns the probe fixture's census entry. + +## What is left + +- The coordinator's fresh Sonnet verifier (Step 3) and `container-e2e` on the pull request. +- Nothing else; no `confirm_` check remains (`git grep -n confirm_ -- crates python` prints nothing). From 6451280b004966ecb3fa189444c5004a2554f3e6 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:32:06 +0900 Subject: [PATCH 33/93] fix(adapter-opencode): state the exit rule's guard and its lenient drop Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-harness-opencode/src/export.rs | 26 +++++++++---------- .../tests/it/guard_opencode_driver.rs | 10 +++++-- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/crates/candler-harness-opencode/src/export.rs b/crates/candler-harness-opencode/src/export.rs index bb820c63..d4164419 100644 --- a/crates/candler-harness-opencode/src/export.rs +++ b/crates/candler-harness-opencode/src/export.rs @@ -189,20 +189,21 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>, servers: &[String] .map(|command| vec![command.to_owned()]) // BORROW: .to_owned() makes owned text }) .flatten(); + let status = state.and_then(|state| text(state, "status")); // The code OpenCode reports for a `shell` call in `state.metadata.exit`. A call that ended in // an error state, that reported none (a timeout reports a signal name and no code), or that is - // not `shell` has none. - let exit = (name == "shell" - && state.and_then(|state| text(state, "status")) == Some("completed")) - .then(|| { - state - .and_then(|state| field(state, "metadata")) - .and_then(|metadata| metadata.get("exit")) - .and_then(Value::as_i64) - .and_then(|code| i32::try_from(code).ok()) - .map(|code| ExitStatus::Code { code }) - }) - .flatten(); + // not `shell` has none; so has one whose `exit` is not an `i32`, dropped as the reader drops + // any other malformed harness field. + let exit = (name == "shell" && status == Some("completed")) + .then(|| { + state + .and_then(|state| field(state, "metadata")) + .and_then(|metadata| metadata.get("exit")) + .and_then(Value::as_i64) + .and_then(|code| i32::try_from(code).ok()) + .map(|code| ExitStatus::Code { code }) + }) + .flatten(); 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( @@ -221,7 +222,6 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>, servers: &[String] call = call.with("input", input.clone()); // BORROW: .clone() keeps the input in the event } let mut drafts = vec![call]; - let status = state.and_then(|state| text(state, "status")); if matches!(status, Some("completed" | "error")) { let mut result = Draft::new( EventKind::tool_result(status == Some("error"), None, exit), 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 7c45b1bf..4dd9fe4c 100644 --- a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs +++ b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs @@ -743,13 +743,19 @@ fn usage(scope: &str, input: u64, output: u64) -> Value { /// reads and writes in their own fields, the cost as a number, reasoning tokens kept beside the /// usage, a reasoning block as its own event, and a tool with no recorded origin as `other`); a /// child session (`info.parentID`) is never a root, its id its parent's, `/`, its own; a document -/// that is not an export is refused, and one that names no outcome ends `unknown`. +/// that is not an export is refused, and one that names no outcome ends `unknown`; exit (a +/// completed `shell` call carries the code of `state.metadata.exit`; an error state, a call with +/// no `metadata.exit` such as the timeout, and a tool that is not `shell` carry none). /// Oracle: `completed_o1/export.json`, read by hand: two assistant messages of 100/20 tokens, one /// `shell` call that completed, `info.tokens` 300/60; `interrupt_api/export.json` (`state.status` /// is `error`, outcome `interrupted`) and `unknown_model_local/export.json` (no assistant message, /// `idle.error`), read by hand; a document written by hand in the recorded shape, with the numbers /// `opencode_facts` reports for the real-model run (cost 0.00054, 4704 cached tokens); the schema's -/// rule that a child's id is its parent's id, `/`, a call id; hand-written documents. +/// rule that a child's id is its parent's id, `/`, a call id; hand-written documents; for the +/// exit, `jq` over the named exports reading `state.status`, `state.metadata.exit` and +/// `state.error`, and a hand-written document whose non-`shell` `read` tool holds `exit: 7`. +/// Bite: no `shell` gate, so the `read` tool with exit 7 carries 7; a missing exit taken as 0, so +/// the timeout row reads 0; the exit read only on error states, so `completed_o1` fails. #[test] fn opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions() -> Res<()> { let (events, sessions) = read_export(&stream_file("completed_o1", "export.json")?)?; From f1eb188a79ca9551edba0fbbb50e0aea2df0a739 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:32:28 +0900 Subject: [PATCH 34/93] reports(adapter-opencode): record the base failure of the code rows Co-Authored-By: Claude Sonnet 5.5 --- .../run-context/leaves/oc_reader_exit_v0.md | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/__reports__/run-context/leaves/oc_reader_exit_v0.md b/__reports__/run-context/leaves/oc_reader_exit_v0.md index a3c8292e..c1a106fa 100644 --- a/__reports__/run-context/leaves/oc_reader_exit_v0.md +++ b/__reports__/run-context/leaves/oc_reader_exit_v0.md @@ -52,10 +52,27 @@ assertion `left == right` failed right: ... {"exit": {"code": 0, "kind": "code"}, "is_error": false, "kind": "tool_result"} ... ``` -The rows after it (the probe's code 3 and code 2) are not reached on the base because the table -stops at its first failure; the probe's rows were seen failing under bite (b) below, and the rows -without an exit (aborted, rejected, `read`) pass on the base by design: they guard against reading -too much. +The table stops at its first failure, so the later rows were checked separately: on a scratch branch +from the base plus the test commit (deleted), with the `completed_o1` row's exit temporarily removed +from the expectation, the table fails at the probe's rows with the reader giving none: + +``` +assertion `left == right` failed: shell_exit_stderr_timeout + left: [{"is_error": false, "kind": "tool_result"} x3] + right: [{"exit": {"code": 3, ...}, ...}, {"exit": {"code": 2, ...}, ...}, {"is_error": false, ...}] +``` + +So every row with a code fails on the base. The rows without an exit (aborted, rejected, `read`) +pass on the base by design: they guard against reading too much (the `read` row bites when the +`shell` check is dropped). + +## Rulings + +- The non-`shell` row's inline document is an accepted deviation from "written from `jq` over the + exports": no recorded export holds a non-`shell` tool. The hand-set `exit: 7` is an input, and the + row bites if the `shell` check is dropped. +- `sigterm_mid_tool` (aborted, not in the table) also reads no exit. +- An `exit` that is not an `i32` gives no exit, as the reader treats other malformed harness fields. ## Bites From 9d8542513454c4d0dcce648df92546e4822f6ff7 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:32:55 +0900 Subject: [PATCH 35/93] rdm(evaluation): close the OpenCode exit reader Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/readers/README.md b/__roadmap__/run_context/readers/README.md index d84d12d6..77901d7f 100644 --- a/__roadmap__/run_context/readers/README.md +++ b/__roadmap__/run_context/readers/README.md @@ -17,7 +17,7 @@ Both trace readers record the harness's exit status, `assemble`/`materialise` se ```mermaid graph TD cc_reader_exit[Claude Code exit]:::inprogress - oc_reader_exit[OpenCode exit]:::inprogress + oc_reader_exit[OpenCode exit]:::done serve_context[Serve the run]:::inprogress helper_context[Helper context]:::inprogress e2e[Consumer path]:::planned @@ -32,7 +32,7 @@ graph TD | Node | Type | Status | |:-----|:-----|:-------| | `cc_reader_exit.md` | 📄 Leaf Task | 🔄 In Progress | -| `oc_reader_exit.md` | 📄 Leaf Task | 🔄 In Progress | +| `oc_reader_exit.md` | 📄 Leaf Task | ✅ Done | | `serve_context.md` | 📄 Leaf Task | 🔄 In Progress | | `helper_context.md` | 📄 Leaf Task | 🔄 In Progress | | `e2e/` | 📁 Directory | ⬜ Planned | From bdc1f72880939ee535201b0f41ab7323d1b8d0b3 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:35:00 +0900 Subject: [PATCH 36/93] test(library): record the census of the probe's timeout stream The guard harness_census_equals_cf3de30_on_every_fixture found no entry for streams/shell_exit_stderr_timeout, a fixture the probe added after the baseline was recorded. Recorded in a scratch checkout of cf3de30 (v0.7.0) with the fixture copied in, by the same producers as tests/it/support/harness_facts.rs: the stream fed to ClaudeCodeReader, then census() and run_values() over the sessions and events, called as cf3de30 offers them (census takes the sessions and events; RunFacts got a scratch constructor because it is non_exhaustive there). The same run over the existing streams gave the existing entries again, so the adapter is sound; census.mcp_servers is left out, as in every existing entry. Values: census.init_tools and census.tools of the fixture's init frame; run.cost_usd 0.0024000000000000002, run.num_turns 1, run.usage as in run_totals.json. Only the two new keys are inserted, in key order. Co-Authored-By: Claude Sonnet 5.5 --- .../fixtures/harness_baseline/census.json | 52 +++++++++++++++++++ .../fixtures/harness_baseline/run_totals.json | 26 ++++++++++ 2 files changed, 78 insertions(+) diff --git a/crates/candler-core/tests/fixtures/harness_baseline/census.json b/crates/candler-core/tests/fixtures/harness_baseline/census.json index bfde840c..29daec78 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/census.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/census.json @@ -235,6 +235,58 @@ "Write" ] }, + "streams/shell_exit_stderr_timeout": { + "census.init_tools": [ + "Bash", + "CronCreate", + "CronDelete", + "CronList", + "DesignSync", + "Edit", + "EnterWorktree", + "ExitWorktree", + "ListAgents", + "Monitor", + "NotebookEdit", + "Read", + "ReportFindings", + "ScheduleWakeup", + "SendMessage", + "Skill", + "Task", + "TaskStop", + "ToolSearch", + "WebFetch", + "WebSearch", + "Workflow", + "Write" + ], + "census.tools": [ + "Task", + "Bash", + "CronCreate", + "CronDelete", + "CronList", + "DesignSync", + "Edit", + "EnterWorktree", + "ExitWorktree", + "ListAgents", + "Monitor", + "NotebookEdit", + "Read", + "ReportFindings", + "ScheduleWakeup", + "SendMessage", + "Skill", + "TaskStop", + "ToolSearch", + "WebFetch", + "WebSearch", + "Workflow", + "Write" + ] + }, "streams/subagent_denials": { "census.init_tools": [ "Bash", diff --git a/crates/candler-core/tests/fixtures/harness_baseline/run_totals.json b/crates/candler-core/tests/fixtures/harness_baseline/run_totals.json index f2503f4c..9000f034 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/run_totals.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/run_totals.json @@ -119,6 +119,32 @@ "speed": "standard" } }, + "streams/shell_exit_stderr_timeout": { + "run.cost_usd": 0.0024000000000000002, + "run.num_turns": 1, + "run.usage": { + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 0 + }, + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + "fallback_credit": null, + "inference_geo": "", + "input_tokens": 100, + "iterations": [], + "output_tokens": 20, + "output_tokens_details": { + "thinking_tokens": 0 + }, + "server_tool_use": { + "web_fetch_requests": 0, + "web_search_requests": 0 + }, + "service_tier": "standard", + "speed": "standard" + } + }, "streams/subagent_denials": { "run.cost_usd": 0.50419205, "run.num_turns": 32, From 033896a2deee9966d4870a013c29d22f11c8b1f5 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:40:12 +0900 Subject: [PATCH 37/93] rdm(adapter-claude-code): state the reads and the join the leaf needs The Bash exit leaf's gate on what the parser reads left out the `interrupted` flag and the denial meta that its own Step 2 requires, and its gate on synthetic rows forbade the one hand-built stream that can pin the (session, span) join, since real call ids never collide. Both gates now say what the leaf has to do. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/cc_reader_exit.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/readers/cc_reader_exit.md b/__roadmap__/run_context/readers/cc_reader_exit.md index 47d43b86..4ec8c80e 100644 --- a/__roadmap__/run_context/readers/cc_reader_exit.md +++ b/__roadmap__/run_context/readers/cc_reader_exit.md @@ -8,8 +8,8 @@ **Success Gates**: - ⬜ `guard_reader.rs::expected_facts` reads new `exits` rows from each fixture's `expected.toml`, written from `jq` over the raw lines and never from the reader's output. The rows cover: a `Bash` call that exited 0; nonzero exits (1 and 127 in the real fixtures); a denial; a call to a tool that is not `Bash` (for example `Read`); a call in a child session; and the probe's stderr-only call (`Exit code 2` followed by the stderr text) and timed-out call (no `exit`, although `is_error` is false). On the base every `exits` row with a code fails - ⬜ Each of four bites turns the guard red, and the report records the failing message: (a) the prefix parse removed; (b) code 0 given to every non-error result, `Read` included; (c) the call joined on span without the session; (d) the background check removed, so the probe's timed-out call reads code 0 -- ⬜ Rows with a code are added only to fixtures that a real Claude Code wrote, as their provenance records (the probe's among them). A synthetic fixture made by `make_synthetic.py` gets an `exits` row only where it states an absence, since a hand-built line cannot say what Claude Code writes -- ⬜ `parse.rs` reads only the result's `is_error`, the first line of its first text content, and the presence of `backgroundTaskId` or `timedOutAfterMs` in `tool_use_result` for this; it never reads the background task's later summary text and never infers a signal from a code +- ⬜ Rows with a code are added only to fixtures that a real Claude Code wrote, as their provenance records (the probe's among them). A synthetic fixture made by `make_synthetic.py` gets an `exits` row only where it states an absence, since a hand-built line cannot say what Claude Code writes. The one exception is a literal stream in `guard_reader.rs` that pins the `(session, span)` join, where two sessions reuse one call id: real ids never collide, so only a hand-built line can state it, and its rows test the join, not what Claude Code writes +- ⬜ `parse.rs` reads only the result's `is_error`, the first line of its first text content, the presence of `backgroundTaskId` or `timedOutAfterMs` and the value of `interrupted` in `tool_use_result`, and the denial meta Step 2 names, for this; the check that the call is a `Bash` call lives where calls are joined to results (`sessions.rs`), and a result joined to no call gets no `exit`; the reader never reads the background task's later summary text and never infers a signal from a code - `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; `container-e2e` is green on the pull request **References**: [plan §The exit-status field, §Test plan](../../../__reports__/run-context/00-plan_run_context_v0.md); `__reports__/run-context/leaves/probe_shell_shapes_v0.md`. Code: - `crates/candler-harness-claude-code/src/parse.rs`: `block_draft` and the `tool_result` handling, `tool_call`; From c26af3b924d19ce54dc86540afd774186173a47d Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:15:24 +0900 Subject: [PATCH 38/93] test(adapter-claude-code): state each Bash call exit from the raw lines Add an exits table to each fixture's expected.toml, written from jq over the raw lines, and check it against the reader's result of each listed call. A literal stream whose root and subagent sessions share a call id pins the join to the session. Synthetic fixtures list absences only. Co-Authored-By: Claude Sonnet 5.5 --- .../tests/fixtures/PROVENANCE.toml | 16 +-- .../fixtures/streams/api_error/expected.toml | 50 +++++++++ .../fixtures/streams/mini_clean/expected.toml | 39 +++++++ .../streams/mini_incomplete/expected.toml | 29 +++++ .../streams/mini_zero_mappings/expected.toml | 47 ++++++++ .../fixtures/streams/multi_init/expected.toml | 61 +++++++++++ .../shell_exit_stderr_timeout/expected.toml | 20 ++++ .../streams/subagent_denials/expected.toml | 56 ++++++++++ .../streams/synthetic_mcp/expected.toml | 7 ++ .../tests/it/guard_reader.rs | 101 ++++++++++++++++++ 10 files changed, 418 insertions(+), 8 deletions(-) diff --git a/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml b/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml index 22fc7059..cc6d1fe1 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml @@ -28,7 +28,7 @@ synthetic = false [[files]] path = "streams/api_error/expected.toml" source = "hand-written from jq over the raw lines" -sha256 = "8bb2fc851a086aded4bd73382f8044d49e9aef88ca11c162d566689bd2d01cba" +sha256 = "005e7f04f8474888ebda65fe1265e44d532f50a236b62e82614dc3da743565a7" synthetic = false [[files]] @@ -46,7 +46,7 @@ synthetic = false [[files]] path = "streams/mini_clean/expected.toml" source = "hand-written from jq over the raw lines" -sha256 = "dc14977220bb9e2067b7ab6033ab19b26763b92d6f6e1e94e3b341b86885534e" +sha256 = "e8ff405324bc903993b300df676168d81cd752ee0d9e0e2cdc240b2c2af0d53e" synthetic = false [[files]] @@ -64,7 +64,7 @@ synthetic = false [[files]] path = "streams/mini_incomplete/expected.toml" source = "hand-written from jq over the raw lines" -sha256 = "e1e7c3c8734bde2e6727f33b204a216a1c125afc6f66c1ce170f4ab27d2e0e81" +sha256 = "17735b82b702712c3ce044ea22554d888ec02215ce02fc4892a6bea9a6264fb2" synthetic = false [[files]] @@ -82,7 +82,7 @@ synthetic = false [[files]] path = "streams/mini_zero_mappings/expected.toml" source = "hand-written from jq over the raw lines" -sha256 = "ab7d6be178ce4b41c6126b956290212b89d5ee3e6b19a32c1653aea5a1a031dc" +sha256 = "8442d42c7c8e1ad55e37ff97bb46ece34fe9a7f4df248f8c02c7b568ffc19159" synthetic = false [[files]] @@ -100,7 +100,7 @@ synthetic = false [[files]] path = "streams/multi_init/expected.toml" source = "hand-written from jq over the raw lines" -sha256 = "cd25036a0bada36b0bacf511f8f240ef948d3151d7e252e275a53d63e1750fe0" +sha256 = "d59e95184b8728ccb3b55bc6d2de8539e31bd4c70f873c863eaefeeede459c5f" synthetic = false [[files]] @@ -118,7 +118,7 @@ synthetic = false [[files]] path = "streams/subagent_denials/expected.toml" source = "hand-written from jq over the raw lines" -sha256 = "e534d3795d9fe68c7fc60fb8edb5b6b85ceaef0f8a08df7c5165fc94c6aaf48f" +sha256 = "6bf85daceff63092725cfeec3bd72542b56aabce8a6af0cabf99eba6f9f61f6b" synthetic = false [[files]] @@ -154,7 +154,7 @@ synthetic = true [[files]] path = "streams/synthetic_mcp/expected.toml" source = "hand-written from jq over the raw lines" -sha256 = "102d9b72911088de7fd0304303994a00756883b0e3666ca6650f32074d8ca1d4" +sha256 = "b12e3bef2407cf07560bcb51870340a10b63a6a081b380ff2cdce84e40b450f0" synthetic = true [[files]] @@ -264,7 +264,7 @@ synthetic = false [[files]] path = "streams/shell_exit_stderr_timeout/expected.toml" source = "hand-written from jq over the raw lines" -sha256 = "fac1f66effd975731684ab68d59c8fb1b42b76e7f0a4c2b359aa7e435a7b8e55" +sha256 = "e9352a677f3bd42c37073c3022808b7e8e4cdf1dfacde7797a2a8a4af4ea09d5" synthetic = false [[files]] diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/api_error/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/api_error/expected.toml index 81b8bd4d..2b91f02b 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/streams/api_error/expected.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/api_error/expected.toml @@ -30,3 +30,53 @@ tool_use_id = "toolu_01KsbY7G8xTcnAyngvjNgG6t" reason = "permission-rule" by = "harness" session = "50b18959-0cb5-4deb-b336-1c8c57970383" + +# Exit of each listed result, from jq over the raw lines (the rule: Bash only; "Exit code N" leads the content -> N; +# a result moved to the background or any other error text -> no code; a non-error result -> 0). `code` absent means no exit. +# Rows cover every distinct shape of a result in the stream, and every nonzero exit. +[[exits]] +tool_use_id = "toolu_01NmVTy7CtJXWmkzZhfECk2M" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_019oLKsnNZZYDgoAFCpGxN9k" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "Bash" +code = 127 + +[[exits]] +tool_use_id = "toolu_01Thg1E955WUNoMx7KGjFQ3t" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "Bash" + +[[exits]] +tool_use_id = "toolu_01DvCBeLjPX4jbFuFuTJRphU" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "Edit" + +[[exits]] +tool_use_id = "toolu_01MKnAPNMeokYonYMk9PA115" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_01N9czBcd4cbbMRYu2CnsyDc" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "TaskCreate" + +[[exits]] +tool_use_id = "toolu_013xWN3NaxDT4gBMJA6pDiJg" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "TaskUpdate" + +[[exits]] +tool_use_id = "toolu_0189zxXdLX3QFYWQi5TfbUZo" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "ToolSearch" + +[[exits]] +tool_use_id = "toolu_01VQxozwLuG4UNucsmP3EBzG" +session = "50b18959-0cb5-4deb-b336-1c8c57970383" +tool = "Write" diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/mini_clean/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/mini_clean/expected.toml index 147bfcde..59bddaf6 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/streams/mini_clean/expected.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/mini_clean/expected.toml @@ -18,3 +18,42 @@ tool_use_id = "toolu_01AKgpUZerL3kMxQpnDLXUkR" reason = "permission-rule" by = "harness" session = "6e52d785-692b-43e6-9145-1a1eb5de265d" + +# Exit of each listed result, from jq over the raw lines (the rule: Bash only; "Exit code N" leads the content -> N; +# a result moved to the background or any other error text -> no code; a non-error result -> 0). `code` absent means no exit. +# Rows cover every distinct shape of a result in the stream, and every nonzero exit. +[[exits]] +tool_use_id = "toolu_012rTgNpxZyZxLFCakSM5Fx7" +session = "6e52d785-692b-43e6-9145-1a1eb5de265d" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_01AKgpUZerL3kMxQpnDLXUkR" +session = "6e52d785-692b-43e6-9145-1a1eb5de265d" +tool = "Bash" + +[[exits]] +tool_use_id = "toolu_01LpYWyPZvNwWHva7Y6edrPe" +session = "6e52d785-692b-43e6-9145-1a1eb5de265d" +tool = "Edit" + +[[exits]] +tool_use_id = "toolu_012uXd7KUg9hFtSEeNVbQRPC" +session = "6e52d785-692b-43e6-9145-1a1eb5de265d" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_0168p7t7DkWTHPmT4t2NGmmv" +session = "6e52d785-692b-43e6-9145-1a1eb5de265d" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_01CTGsqHxs2Eh1FgmayamWCx" +session = "6e52d785-692b-43e6-9145-1a1eb5de265d" +tool = "Skill" + +[[exits]] +tool_use_id = "toolu_012RVMjQuf6QtWV4R68SRzVj" +session = "6e52d785-692b-43e6-9145-1a1eb5de265d" +tool = "Write" diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/mini_incomplete/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/mini_incomplete/expected.toml index e5f0b253..8273ea67 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/streams/mini_incomplete/expected.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/mini_incomplete/expected.toml @@ -18,3 +18,32 @@ tool_use_id = "toolu_01WKwgRvHAbP3sibb1dUXTZZ" reason = "permission-rule" by = "harness" session = "4f403f2d-a74d-41fa-8a88-4fb8a38f1b18" + +# Exit of each listed result, from jq over the raw lines (the rule: Bash only; "Exit code N" leads the content -> N; +# a result moved to the background or any other error text -> no code; a non-error result -> 0). `code` absent means no exit. +# Rows cover every distinct shape of a result in the stream, and every nonzero exit. +[[exits]] +tool_use_id = "toolu_015gkhs4y7iR3iV8t33NRRHV" +session = "4f403f2d-a74d-41fa-8a88-4fb8a38f1b18" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_01WKwgRvHAbP3sibb1dUXTZZ" +session = "4f403f2d-a74d-41fa-8a88-4fb8a38f1b18" +tool = "Bash" + +[[exits]] +tool_use_id = "toolu_01KMtSUihaKuixTGZ4Qyopdt" +session = "4f403f2d-a74d-41fa-8a88-4fb8a38f1b18" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_01YAW9TLc1C8jLZq27hygjyQ" +session = "4f403f2d-a74d-41fa-8a88-4fb8a38f1b18" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_01LEMjeuw9GcVxvvE4aUVkL4" +session = "4f403f2d-a74d-41fa-8a88-4fb8a38f1b18" +tool = "Write" diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/mini_zero_mappings/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/mini_zero_mappings/expected.toml index 88b65545..cacd8d50 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/streams/mini_zero_mappings/expected.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/mini_zero_mappings/expected.toml @@ -13,3 +13,50 @@ tokens_reporting = "per_turn" [[sessions]] id = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" ended_by = "completed" + +# Exit of each listed result, from jq over the raw lines (the rule: Bash only; "Exit code N" leads the content -> N; +# a result moved to the background or any other error text -> no code; a non-error result -> 0). `code` absent means no exit. +# Rows cover every distinct shape of a result in the stream, and every nonzero exit. +[[exits]] +tool_use_id = "toolu_01HjEbccZbRisAvaVC7nixfM" +session = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_018SGUXwYyWm4kqGvbx95hGa" +session = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" +tool = "Bash" +code = 1 + +[[exits]] +tool_use_id = "toolu_01F9M16sniJZQvtpxWj7VSvi" +session = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" +tool = "Bash" +code = 1 + +[[exits]] +tool_use_id = "toolu_01TG9BrL5QWoUcbJTsxKGTP1" +session = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" +tool = "Bash" +code = 1 + +[[exits]] +tool_use_id = "toolu_0125ZJksRek8Db8vs5ERwxYo" +session = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" +tool = "Edit" + +[[exits]] +tool_use_id = "toolu_019UkoTwRW43HQYBr5BYx5Ao" +session = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_019dVgP6Hgxg6YDE6eS9CZii" +session = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_01BfmwiZ9bz4cij2PSY8WN9k" +session = "803a72b6-cbd3-4b0d-9279-a6ff142555a1" +tool = "Write" diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/multi_init/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/multi_init/expected.toml index 7c5c7414..90683082 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/streams/multi_init/expected.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/multi_init/expected.toml @@ -21,3 +21,64 @@ ended_by = "completed" id = "ea98d538-0c5d-4bb7-a243-1b890dda15d3/toolu_01GvxyCVQDtQf2ByXX2qt9gx" parent = "ea98d538-0c5d-4bb7-a243-1b890dda15d3" ended_by = "completed" + +# Exit of each listed result, from jq over the raw lines (the rule: Bash only; "Exit code N" leads the content -> N; +# a result moved to the background or any other error text -> no code; a non-error result -> 0). `code` absent means no exit. +# Rows cover every distinct shape of a result in the stream, and every nonzero exit. +[[exits]] +tool_use_id = "toolu_01GvxyCVQDtQf2ByXX2qt9gx" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3" +tool = "Agent" + +[[exits]] +tool_use_id = "toolu_013rUBv8WaxMpvAnSxiaJqvt" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_018w9kSKemJqDwMiXrxSkitE" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_01Mud8pkCLU11w5wd5RkXvhB" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_01HJafK6ZEMVouptJbdqEe8s" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3" +tool = "ScheduleWakeup" + +[[exits]] +tool_use_id = "toolu_01STZvWneBTdZbdov85XbMYh" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3/toolu_01GvxyCVQDtQf2ByXX2qt9gx" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_016xvToFsnpc4cHDeRAnxcGu" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3/toolu_01GvxyCVQDtQf2ByXX2qt9gx" +tool = "Bash" +code = 1 + +[[exits]] +tool_use_id = "toolu_01W7rC53fjUaVdze1SiTCy46" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3/toolu_01GvxyCVQDtQf2ByXX2qt9gx" +tool = "Edit" + +[[exits]] +tool_use_id = "toolu_01QY2QFkrQhSEZtujTqZWBW9" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3/toolu_01GvxyCVQDtQf2ByXX2qt9gx" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_011zRqPekYZe1CGUCiUTa66E" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3/toolu_01GvxyCVQDtQf2ByXX2qt9gx" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_011n8HZjkrjkBmqrGCcrZjG6" +session = "ea98d538-0c5d-4bb7-a243-1b890dda15d3/toolu_01GvxyCVQDtQf2ByXX2qt9gx" +tool = "Write" diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml index 580b5b59..dfde1bba 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml @@ -15,3 +15,23 @@ tokens_reporting = "per_turn" [[sessions]] id = "d5ff5efc-d943-44df-a357-f087b8668786" ended_by = "completed" + +# Exit of each listed result, from jq over the raw lines (the rule: Bash only; "Exit code N" leads the content -> N; +# a result moved to the background or any other error text -> no code; a non-error result -> 0). `code` absent means no exit. +# Rows cover every distinct shape of a result in the stream, and every nonzero exit. +[[exits]] +tool_use_id = "toolu_fake_sh_timeout" +session = "d5ff5efc-d943-44df-a357-f087b8668786" +tool = "Bash" + +[[exits]] +tool_use_id = "toolu_fake_sh_stderr" +session = "d5ff5efc-d943-44df-a357-f087b8668786" +tool = "Bash" +code = 2 + +[[exits]] +tool_use_id = "toolu_fake_sh_exit3" +session = "d5ff5efc-d943-44df-a357-f087b8668786" +tool = "Bash" +code = 3 diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/subagent_denials/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/subagent_denials/expected.toml index d7a5a150..b287f40d 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/streams/subagent_denials/expected.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/subagent_denials/expected.toml @@ -24,3 +24,59 @@ tool_use_id = "toolu_01X5u9fEqbbE81797As5G5so" reason = "permission-rule" by = "harness" session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" + +# Exit of each listed result, from jq over the raw lines (the rule: Bash only; "Exit code N" leads the content -> N; +# a result moved to the background or any other error text -> no code; a non-error result -> 0). `code` absent means no exit. +# Rows cover every distinct shape of a result in the stream, and every nonzero exit. +[[exits]] +tool_use_id = "toolu_013DzQNP5eghtZzg2B3yVjBD" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" +tool = "Agent" + +[[exits]] +tool_use_id = "toolu_01UD7QWiFcsquMvnCjYbpEcw" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_01DkRDrfN5Ko7P4Qj4xvSFcV" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" +tool = "Bash" +code = 1 + +[[exits]] +tool_use_id = "toolu_01X5u9fEqbbE81797As5G5so" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" +tool = "Bash" + +[[exits]] +tool_use_id = "toolu_0196kqWT5QrYkYYY4MoBSFdg" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" +tool = "Edit" + +[[exits]] +tool_use_id = "toolu_01VjVDWurs4LmdJFy9hb1BkL" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" +tool = "Read" + +[[exits]] +tool_use_id = "toolu_01Nps2fAwbu3SMArPmUXMENK" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" +tool = "Skill" + +[[exits]] +tool_use_id = "toolu_01EoHQvHQ8KvCyGUrU7Xbivm" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b" +tool = "Write" + +[[exits]] +tool_use_id = "toolu_013JezHaK1JMDqGYDvRSBCxt" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b/toolu_013DzQNP5eghtZzg2B3yVjBD" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_01Suta5jdXAbr5fR8t6KwHRS" +session = "c4795c86-ed65-45c8-9b21-e095d2025a1b/toolu_013DzQNP5eghtZzg2B3yVjBD" +tool = "Read" diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/synthetic_mcp/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/synthetic_mcp/expected.toml index b40eaa22..c797b77e 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/streams/synthetic_mcp/expected.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/synthetic_mcp/expected.toml @@ -39,3 +39,10 @@ ended_by = "unknown" [[frame_sessions]] frame = 8 session = "22222222-2222-4222-8222-222222222222/toolu_m_n1/toolu_m_n2" + +# A hand-built line cannot say what Claude Code writes for an exit, so only an absence is listed: +# an MCP tool's error result carries no exit. +[[exits]] +tool_use_id = "toolu_m_ls" +session = "22222222-2222-4222-8222-222222222222" +tool = "mcp__plugin_banyan_banyan-hpc__fs_ls" diff --git a/crates/candler-harness-claude-code/tests/it/guard_reader.rs b/crates/candler-harness-claude-code/tests/it/guard_reader.rs index 70102e98..76827702 100644 --- a/crates/candler-harness-claude-code/tests/it/guard_reader.rs +++ b/crates/candler-harness-claude-code/tests/it/guard_reader.rs @@ -12,6 +12,7 @@ use candler_harness::reader::{FrameIn, TraceReader}; use candler_harness::spec::Confidence; use candler_harness_claude_code::{ClaudeCodeReader, READER}; use candler_schemas::primitives::Digest; +use candler_schemas::process::ExitStatus; use candler_schemas::raw::{FrameData, RawFrame, RawRef, StreamName}; use candler_schemas::trace::{ Cap, EndedBy, EventKind, RawFileRef, Session, SessionEvent, ToolOrigin, TraceFile, TraceHeader, @@ -266,6 +267,99 @@ fn stream_with(result: Option<&str>) -> Vec> { lines } +/// A result's exit as `expected.toml` writes it: session, call id, the name of the call, and the exit code when there is one. +type ExitRow = (String, String, String, Option); + +fn expected_exits(stream: &Stream) -> Res> { + let Some(rows) = stream.expected.get("exits") else { + return Ok(Vec::new()); + }; + let mut out = Vec::new(); + for entry in rows.as_array().ok_or("`exits` is not a list")? { + let entry = table(entry, "an exit row")?; + let code = entry + .get("code") + .map(|code| -> Res { Ok(i32::try_from(code.as_integer().ok_or("code")?)?) }) + .transpose()?; + out.push(( + text(entry, "session")?.to_owned(), // BORROW: owned copy + text(entry, "tool_use_id")?.to_owned(), // BORROW: owned copy + text(entry, "tool")?.to_owned(), // BORROW: owned copy + code, + )); + } + Ok(out) +} + +/// Checks each row against the reader's result of that call in that session: the call has the name the row gives, and the result has the exit code the row gives, or none. +fn check_exits(name: &str, output: &Output, rows: &[ExitRow]) -> Res<()> { + for (session, id, tool, want) in rows { + let held: Vec<&SessionEvent> = output + .events + .iter() + .filter(|record| { + record.session.as_str() == session + && record + .event + .span + .as_ref() + .is_some_and(|span| span.as_str() == id) + }) + .collect(); + let called: Vec<&str> = held + .iter() + .filter_map(|record| match &record.event.kind { + EventKind::ToolCall { name, .. } => Some(name.as_str()), + _ => None, + }) + .collect(); + assert_eq!( + called, + [tool.as_str()], + "{name}: the call {id} in {session}" + ); + let mut results = Vec::new(); + for record in &held { + if let EventKind::ToolResult { exit, .. } = &record.event.kind { + results.push(match exit { + None => None, + Some(ExitStatus::Code { code }) => Some(*code), + Some(other) => return Err(format!("{name}: {id}: unexpected {other:?}").into()), + }); + } + } + assert_eq!( + results, + [*want], + "{name}: exit of the result of {tool} call {id} in {session}" + ); + } + Ok(()) +} + +/// Lines in which one call id names a `Read` in the root session and a `Bash` in the subagent session `S/A`: the result in each session gets the exit of its own call. +fn shared_id_stream() -> Vec> { + let bash = r#"{"type":"tool_use","id":"X","name":"Bash","input":{"command":"true"}}"#; + let read = r#"{"type":"tool_use","id":"X","name":"Read","input":{}}"#; + let agent = r#"{"type":"tool_use","id":"A","name":"Agent","input":{}}"#; + let result = + |text: &str| format!(r#"{{"type":"tool_result","tool_use_id":"X","content":"{text}"}}"#); + let line = |kind: &str, parent: &str, blocks: &[&str]| { + format!( + r#"{{"type":"{kind}","session_id":"S",{parent}"message":{{"role":"{kind}","content":[{}]}}}}"#, + blocks.join(",") + ) + .into_bytes() + }; + let child = r#""parent_tool_use_id":"A","#; + let mut lines = stream_with(None); + lines.push(line("assistant", "", &[agent, read])); + lines.push(line("assistant", child, &[bash])); + lines.push(line("user", "", &[&result("file text")])); + lines.push(line("user", child, &[&result("")])); + lines +} + /// Guards: Reader correctness — sessions, subagent ids, denials by the harness, MCP origins, unreadable lines and `ended_by` of each stream, and `ended_by` for each result shape, are what the raw lines say. Oracle: the hand-written `expected.toml` of each stream, written from `jq` over its lines, and literal result lines with the ends R01 §Ends gives them. #[test] fn expected_facts() -> Res<()> { @@ -312,6 +406,7 @@ fn expected_facts() -> Res<()> { expected_denials(&stream)?, "{name}: denials (call, reason, by, session)" ); + check_exits(name, &output, &expected_exits(&stream)?)?; for row in expected_frame_sessions(&stream)? { let (frame, session) = row; let holders: BTreeSet = output @@ -424,6 +519,12 @@ fn expected_facts() -> Res<()> { .clone(); // BORROW: owned end to compare assert_eq!(got, want, "result line {result:?}"); } + let shared = run(&shared_id_stream(), false)?; + let rows: [ExitRow; 2] = [ + ("S".to_owned(), "X".to_owned(), "Read".to_owned(), None), // BORROW: owned text + ("S/A".to_owned(), "X".to_owned(), "Bash".to_owned(), Some(0)), // BORROW: owned text + ]; + check_exits("shared call id", &shared, &rows)?; Ok(()) } From 4fd36bcfc266497d6f2bac8dc6ecfcf652bf27fe Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:16:19 +0900 Subject: [PATCH 39/93] feat(adapter-claude-code): read a Bash call's exit status A Bash result carries the exit Claude Code reported: Exit code N leading an error result's first text line is N, a result that is not an error is 0, and a result moved to the background, interrupted or denied has none. The call's name is joined on the session and the call id, and any other tool gets none. The reader identity moves to 0.3.0 because its output changed. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-harness-claude-code/src/lib.rs | 4 +- .../candler-harness-claude-code/src/parse.rs | 48 ++++++++++++++++++- .../src/sessions.rs | 14 ++++-- .../tests/it/guard_reader.rs | 26 +++++++--- 4 files changed, 78 insertions(+), 14 deletions(-) diff --git a/crates/candler-harness-claude-code/src/lib.rs b/crates/candler-harness-claude-code/src/lib.rs index 06bfb4fb..bde2885e 100644 --- a/crates/candler-harness-claude-code/src/lib.rs +++ b/crates/candler-harness-claude-code/src/lib.rs @@ -55,10 +55,10 @@ pub const PINNED: semver::Version = semver::Version::new(2, 1, 311); const HARNESS: &str = "claude-code"; /// The identity of this reader as text, `claude-code-stream-json@`; the version changes whenever the reader's output does. -pub const READER: &str = "claude-code-stream-json@0.2.0"; +pub const READER: &str = "claude-code-stream-json@0.3.0"; /// The version of [`READER`]. -const READER_VERSION: semver::Version = semver::Version::new(0, 2, 0); +const READER_VERSION: semver::Version = semver::Version::new(0, 3, 0); /// A frame that arrived before any session was known. struct Held { diff --git a/crates/candler-harness-claude-code/src/parse.rs b/crates/candler-harness-claude-code/src/parse.rs index 99050dcc..f44da0d4 100644 --- a/crates/candler-harness-claude-code/src/parse.rs +++ b/crates/candler-harness-claude-code/src/parse.rs @@ -3,6 +3,7 @@ use candler_harness::spec::{CensusSource, InitReport}; use candler_schemas::outcome::Finite; use candler_schemas::primitives::Timestamp; +use candler_schemas::process::ExitStatus; use candler_schemas::raw::{FrameData, RawFrame}; use candler_schemas::trace::{Denial, DeniedBy, EndedBy, EventKind, SpanId, ToolOrigin}; use serde_json::{Map, Value}; @@ -315,8 +316,13 @@ fn block_draft(role: Role, block: &Value, line: &Map) -> Draft { .get("is_error") .and_then(Value::as_bool) .unwrap_or(false); - let mut draft = - Draft::new(EventKind::tool_result(is_error, denial_of(line, id), None)); + let denied = denial_of(line, id); + let exit = if denied.is_some() { + None + } else { + exit_of(block, line, is_error) + }; + let mut draft = Draft::new(EventKind::tool_result(is_error, denied, exit)); draft.span = span_of(id, &mut draft.ext); draft } @@ -338,6 +344,44 @@ fn denial_of(line: &Map, id: &str) -> Option { .map(|kind| Denial::new(DeniedBy::Harness, Some(kind.to_owned()))) } +/// The exit a shell result reports, before the call's name is known. +/// +/// An error result whose first text line is `Exit code N` exited with `N`; any other error text gives none. A result that +/// is not an error exited with 0, unless Claude Code moved the command to the background (`backgroundTaskId` or +/// `timedOutAfterMs` in the line's `tool_use_result`) or it was interrupted, which give none. +fn exit_of(block: &Value, line: &Map, is_error: bool) -> Option { + let report = line.get("tool_use_result").and_then(Value::as_object); + let flagged = |key: &str| report.is_some_and(|report| report.contains_key(key)); + let interrupted = report + .and_then(|report| report.get("interrupted")) + .and_then(Value::as_bool) + == Some(true); + if flagged("backgroundTaskId") || flagged("timedOutAfterMs") || interrupted { + return None; + } + if !is_error { + return Some(ExitStatus::Code { code: 0 }); + } + let content = block.get("content")?; + let first = match content { + Value::String(text) => Some(text.as_str()), + Value::Array(parts) => parts + .iter() + .find(|part| part.get("type").and_then(Value::as_str) == Some("text")) + .and_then(|part| part.get("text")) + .and_then(Value::as_str), + Value::Null | Value::Bool(_) | Value::Number(_) | Value::Object(_) => None, + }?; + let digits = first.lines().next()?.strip_prefix("Exit code ")?; + if !digits.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + digits + .parse::() + .ok() + .map(|code| ExitStatus::Code { code }) +} + /// A notification that keeps a content block this reader has no event for. fn unknown_block(block: &Value) -> Draft { // BORROW: .clone() keeps the whole block in the event diff --git a/crates/candler-harness-claude-code/src/sessions.rs b/crates/candler-harness-claude-code/src/sessions.rs index a16ad9de..52a3cd96 100644 --- a/crates/candler-harness-claude-code/src/sessions.rs +++ b/crates/candler-harness-claude-code/src/sessions.rs @@ -77,6 +77,8 @@ pub(crate) struct Registry { index: HashMap, /// The session that holds each call, by call id. owner: HashMap, + /// The name of each call, by the session that holds it and the call id. + names: HashMap<(usize, String), String>, /// The ids of the calls that have a result. answered: HashSet, /// The ids of the messages whose usage was counted. @@ -224,14 +226,20 @@ impl Registry { target: usize, raw_ref: &RawRef, at: Option<&Timestamp>, - draft: Draft, + mut draft: Draft, ) -> Result { if let Some(span) = &draft.span { // BORROW: .as_str().to_owned() makes the owned call id the maps keep let call = span.as_str().to_owned(); - if matches!(draft.kind, EventKind::ToolCall { .. }) { + if let EventKind::ToolCall { name, .. } = &draft.kind { + // BORROW: .clone() keeps the name of the call for its result + self.names.insert((target, call.clone()), name.clone()); self.owner.insert(call, target); - } else if matches!(draft.kind, EventKind::ToolResult { .. }) { + } else if let EventKind::ToolResult { exit, .. } = &mut draft.kind { + // Only a shell call reports an exit. + if self.names.get(&(target, call.clone())).map(String::as_str) != Some("Bash") { + *exit = None; + } self.answered.insert(call); } } diff --git a/crates/candler-harness-claude-code/tests/it/guard_reader.rs b/crates/candler-harness-claude-code/tests/it/guard_reader.rs index 76827702..ffbb432b 100644 --- a/crates/candler-harness-claude-code/tests/it/guard_reader.rs +++ b/crates/candler-harness-claude-code/tests/it/guard_reader.rs @@ -308,9 +308,12 @@ fn check_exits(name: &str, output: &Output, rows: &[ExitRow]) -> Res<()> { .collect(); let called: Vec<&str> = held .iter() - .filter_map(|record| match &record.event.kind { - EventKind::ToolCall { name, .. } => Some(name.as_str()), - _ => None, + .filter_map(|record| { + if let EventKind::ToolCall { name, .. } = &record.event.kind { + Some(name.as_str()) + } else { + None + } }) .collect(); assert_eq!( @@ -337,8 +340,8 @@ fn check_exits(name: &str, output: &Output, rows: &[ExitRow]) -> Res<()> { Ok(()) } -/// Lines in which one call id names a `Read` in the root session and a `Bash` in the subagent session `S/A`: the result in each session gets the exit of its own call. -fn shared_id_stream() -> Vec> { +/// Lines in which one call id names a `Read` in the root session and a `Bash` in the subagent session `S/A`, so the result in each session gets the exit of its own call; and a `Bash` call whose result is not an error but reports `interrupted`. +fn exit_join_stream() -> Vec> { let bash = r#"{"type":"tool_use","id":"X","name":"Bash","input":{"command":"true"}}"#; let read = r#"{"type":"tool_use","id":"X","name":"Read","input":{}}"#; let agent = r#"{"type":"tool_use","id":"A","name":"Agent","input":{}}"#; @@ -351,12 +354,20 @@ fn shared_id_stream() -> Vec> { ) .into_bytes() }; + let cut = r#"{"type":"tool_use","id":"I","name":"Bash","input":{"command":"sleep 9"}}"#; + let cut_result = r#"{"type":"tool_result","tool_use_id":"I","content":"partial"}"#; let child = r#""parent_tool_use_id":"A","#; let mut lines = stream_with(None); lines.push(line("assistant", "", &[agent, read])); lines.push(line("assistant", child, &[bash])); lines.push(line("user", "", &[&result("file text")])); lines.push(line("user", child, &[&result("")])); + lines.push(line("assistant", "", &[cut])); + lines.push(line( + "user", + r#""tool_use_result":{"interrupted":true},"#, + &[cut_result], + )); lines } @@ -519,10 +530,11 @@ fn expected_facts() -> Res<()> { .clone(); // BORROW: owned end to compare assert_eq!(got, want, "result line {result:?}"); } - let shared = run(&shared_id_stream(), false)?; - let rows: [ExitRow; 2] = [ + let shared = run(&exit_join_stream(), false)?; + let rows: [ExitRow; 3] = [ ("S".to_owned(), "X".to_owned(), "Read".to_owned(), None), // BORROW: owned text ("S/A".to_owned(), "X".to_owned(), "Bash".to_owned(), Some(0)), // BORROW: owned text + ("S".to_owned(), "I".to_owned(), "Bash".to_owned(), None), // BORROW: owned text ]; check_exits("shared call id", &shared, &rows)?; Ok(()) From 62c27d5a7cd7450f06f71eb2604193bc53495e02 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:35:00 +0900 Subject: [PATCH 40/93] reports(adapter-claude-code): close the Bash exit status Co-Authored-By: Claude Sonnet 5.5 --- .../run-context/leaves/cc_reader_exit_v0.md | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 __reports__/run-context/leaves/cc_reader_exit_v0.md diff --git a/__reports__/run-context/leaves/cc_reader_exit_v0.md b/__reports__/run-context/leaves/cc_reader_exit_v0.md new file mode 100644 index 00000000..8956e652 --- /dev/null +++ b/__reports__/run-context/leaves/cc_reader_exit_v0.md @@ -0,0 +1,97 @@ +# Leaf report: Claude Code reader exit status + +The Claude Code reader sets `ToolResult.exit` on a `Bash` result from what Claude Code wrote, in +`crates/candler-harness-claude-code`. Branch `leaf/run-context/cc_reader_exit`, two commits on `feat/run-context`. + +## The exit rule as implemented + +`parse.rs::exit_of` reads, from the result block and its line: the block's `is_error`; the first line of the first +text content; and `backgroundTaskId`, `timedOutAfterMs` and `interrupted` in the line's `tool_use_result`. + +1. A denial (`tool_result_meta` non-execution entry for the call) gives no exit. +2. A result whose `tool_use_result` has `backgroundTaskId` or `timedOutAfterMs`, or `interrupted: true`, gives none. +3. An error result whose first text line is `Exit code ` followed only by decimal digits that fit an `i32` gives `code N`; + any other error text gives none. +4. A result that is not an error gives `code 0`. +5. `sessions.rs::Registry::emit` clears the exit unless the call that this result answers, found by the session that + holds the result and the call id, is named `Bash`. The name is stored when the call is emitted. + +The prefix is read only on an error result: a successful command that prints `Exit code 5` on stdout is code 0. +The reader never reads the system line about the background task and never infers a signal. +`READER` and `READER_VERSION` move to `0.3.0` since the output changed. + +## The jq oracle + +Every expected `exits` row in the seven real fixtures' `expected.toml` comes from this, run over the decompressed raw stream +(`gzip -dc | jq -n -r -f oracle.jq | jq -n -r -R --arg root -f rows.jq`). + +```jq +# oracle.jq: one row per tool_result: session (root, or root/), call id, call name, is_error, +# first line of first text content, background flag, non-execution kind +[inputs | select(.type=="assistant" or .type=="user")] as $lines +| ([$lines[] | .message.content | if type=="array" then .[] else empty end | select(.type=="tool_use") | {key:.id, value:.name}] | from_entries) as $names +| $lines[] | . as $l +| ($l.message.content | if type=="array" then .[] else empty end | select(.type=="tool_result")) as $r +| [ ($l.session_id + (if $l.parent_tool_use_id then "/" + $l.parent_tool_use_id else "" end)), + $r.tool_use_id, $names[$r.tool_use_id], ($r.is_error // false), + (($r.content | if type=="string" then . elif type=="array" then ([.[]|select(.type=="text")|.text]|first // "") else "" end) | split("\n")[0]), + ($l.tool_use_result | if type=="object" then (has("backgroundTaskId") or has("timedOutAfterMs")) else false end), + ($l.tool_result_meta // [] | map(select(.id==$r.tool_use_id) | .non_execution_kind) | first) ] | @json +``` + +`rows.jq` applies the rule to each oracle row (Bash only; background gives none; `^Exit code [0-9]+$` gives N; other error +gives none; non-error gives 0) and keeps every nonzero or background row plus the first row of each distinct shape +(child or root session, tool, is_error, expected value, background, denial). The rows are in +`tests/fixtures/streams/*/expected.toml` under `[[exits]]`; each also names the call's `tool`, which the guard checks. +Real fixtures with rows: `api_error` (Exit code 127, a denial), `mini_zero_mappings` (Exit code 1), `multi_init` +(child-session Bash, exit 1 and 0), `subagent_denials` (child-session Bash, a denial), `mini_clean`, `mini_incomplete`, +and the probe's `shell_exit_stderr_timeout` (`Exit code 3`, `Exit code 2` followed by `oops`, and the timed-out call with +no exit although `is_error` is false). `synthetic_mcp` has one absence row (an MCP tool's error). The other synthetic +fixtures have none. + +Beside the fixtures, `expected_facts` runs a literal stream (`exit_join_stream`): one call id is a `Read` in the root +session and a `Bash` in the subagent session; and a `Bash` result that is not an error but reports `interrupted`. +Only absences and the child's code 0 (a code row on hand-built lines that no Claude Code wrote, kept to pin the join). + +## Guards on the base (eb83b015, reader passes `None`) + +`cargo nextest run -p candler-harness-claude-code -E 'test(expected_facts)'` fails: + +``` +api_error: exit of the result of Bash call toolu_01NmVTy7CtJXWmkzZhfECk2M in 50b18959-0cb5-4deb-b336-1c8c57970383 + left: [None] + right: [Some(0)] +``` + +The test stops at the first failing row. Row classes by what each needs: a `Bash` code 0 (above); nonzero 1 and 127; +the stderr-only `Exit code 2`; a child-session `Bash`; every absence row (denial, `Read`, `Edit`, `Agent`, an MCP tool, +the timed-out call) passes on the base because the base gives no exit. The literal stream's child `Bash` code 0 fails on the base too. + +## Bites + +Each applied on `scratch/bites` (deleted), one at a time, then reverted. All failures are from `expected_facts`. + +| bite | change | failing message | +|---|---|---| +| (a) prefix parse removed | the prefix `Exit code ` made unmatchable | `api_error: exit of the result of Bash call toolu_019oLKsnNZZYDgoAFCpGxN9k in 50b18959-...` left `[None]` right `[Some(127)]` | +| (b) code 0 for every non-error result | the `Bash` name check never clears | `api_error: exit of the result of Edit call toolu_01DvCBeLjPX4jbFuFuTJRphU in 50b18959-...` left `[Some(0)]` right `[None]` | +| (c) join on span without the session | name map keyed by call id only | `shared call id: exit of the result of Read call X in S` left `[Some(0)]` right `[None]` | +| (d) background check removed | `backgroundTaskId` and `timedOutAfterMs` ignored | `shell_exit_stderr_timeout: exit of the result of Bash call toolu_fake_sh_timeout in d5ff5efc-...` left `[Some(0)]` right `[None]` | +| (e) extra: `interrupted` removed | `interrupted` ignored | `shared call id: exit of the result of Bash call I in S` left `[Some(0)]` right `[None]` | + +Bite (c) cannot fail on a real fixture: Claude Code's call ids are unique, so span-only and (session, span) agree on every +recorded stream. The literal stream is the only place the two differ. + +## What is left + +- `tests/fixtures/digests.toml` still names `claude-code-stream-json@0.2.0` and the old digests. No test reads it in this tree + (the ratchet named in its header and in the fixtures README is not present), so it is untouched and stale; it needs a bless + when the ratchet returns. +- The fresh Sonnet verifier of Step 3 is the coordinator's to dispatch. +- No signal is read; Claude Code reports none. +- `container-e2e` on the pull request is not run here. +- Workspace suite with `--no-fail-fast`: 732 of 735 pass. `guard_harness_facts::harness_census_equals_cf3de30_on_every_fixture` + fails on the base too ("no baseline for streams/shell_exit_stderr_timeout"; known, fixed on another branch). + `guard_supervise::a_pre_stop_command_leaves_nothing_in_its_group` and `guard_wiring::wiring_stop_execs_in_the_container_with_the_observed_id` + failed under full load and pass alone (0.9 s and 97 s). `fmt --check`, `clippy -D warnings` and `doc -D warnings` pass. +- Gate 4 lists what `parse.rs` reads; the code also reads `interrupted` and the denial meta, as Step 2's text requires. From ee7921681d076bbb80ad3bbd9f9a90a217ee48f1 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:53:01 +0900 Subject: [PATCH 41/93] fix(adapter-claude-code): clear the exit of a result that joins no call A result whose call id is no span kept the exit the parse gave it. Clear it, keep one name for the shell tool, and store only the Bash calls. Co-Authored-By: Claude Sonnet 5.5 --- .../candler-harness-claude-code/src/parse.rs | 15 ++++---- .../src/sessions.rs | 35 +++++++++++-------- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/crates/candler-harness-claude-code/src/parse.rs b/crates/candler-harness-claude-code/src/parse.rs index f44da0d4..74c96b18 100644 --- a/crates/candler-harness-claude-code/src/parse.rs +++ b/crates/candler-harness-claude-code/src/parse.rs @@ -344,11 +344,11 @@ fn denial_of(line: &Map, id: &str) -> Option { .map(|kind| Denial::new(DeniedBy::Harness, Some(kind.to_owned()))) } -/// The exit a shell result reports, before the call's name is known. +/// The exit a result reports. /// -/// An error result whose first text line is `Exit code N` exited with `N`; any other error text gives none. A result that -/// is not an error exited with 0, unless Claude Code moved the command to the background (`backgroundTaskId` or -/// `timedOutAfterMs` in the line's `tool_use_result`) or it was interrupted, which give none. +/// A result with a `backgroundTaskId` or `timedOutAfterMs` in the line's `tool_use_result`, or with `interrupted` true, +/// has none. Of the others, an error result whose first text line is `Exit code N` has code `N` and any other error +/// text has none; a non-error result with none of those flags reads as exit 0. fn exit_of(block: &Value, line: &Map, is_error: bool) -> Option { let report = line.get("tool_use_result").and_then(Value::as_object); let flagged = |key: &str| report.is_some_and(|report| report.contains_key(key)); @@ -373,7 +373,7 @@ fn exit_of(block: &Value, line: &Map, is_error: bool) -> Option None, }?; let digits = first.lines().next()?.strip_prefix("Exit code ")?; - if !digits.bytes().all(|byte| byte.is_ascii_digit()) { + if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) { return None; } digits @@ -400,9 +400,12 @@ fn span_of(id: &str, ext: &mut Map) -> Option { ) } +/// The name of the shell tool, the only one whose result reports an exit. +pub(crate) const SHELL_TOOL: &str = "Bash"; + /// The call of the tool `name` with the id `id`. fn tool_call(id: &str, name: &str, input: Option<&Value>) -> Draft { - let argv = (name == "Bash") + let argv = (name == SHELL_TOOL) .then(|| { input .and_then(|input| input.get("command")) diff --git a/crates/candler-harness-claude-code/src/sessions.rs b/crates/candler-harness-claude-code/src/sessions.rs index 52a3cd96..926a6344 100644 --- a/crates/candler-harness-claude-code/src/sessions.rs +++ b/crates/candler-harness-claude-code/src/sessions.rs @@ -10,7 +10,7 @@ use candler_schemas::trace::{ }; use serde_json::{Map, Value}; -use crate::parse::Draft; +use crate::parse::{Draft, SHELL_TOOL}; use crate::usage::Tokens; /// How a root session ended, from its last `result` line. @@ -77,8 +77,8 @@ pub(crate) struct Registry { index: HashMap, /// The session that holds each call, by call id. owner: HashMap, - /// The name of each call, by the session that holds it and the call id. - names: HashMap<(usize, String), String>, + /// The session and call id of each `Bash` call. + shell: HashSet<(usize, String)>, /// The ids of the calls that have a result. answered: HashSet, /// The ids of the messages whose usage was counted. @@ -219,8 +219,9 @@ impl Registry { /// The event `draft` of the session `target`, read from the frame `raw_ref` at time `at`. /// - /// A call records its session as the holder of the call id, and a result records its call as - /// answered. + /// A call records its session as the holder of the call id, and a `Bash` call records its session and id as a shell + /// call. A result records its call as answered and keeps its exit only when its call is a `Bash` call of the same + /// session; a result that joins no call (its id is no span) has no exit. pub(crate) fn emit( &mut self, target: usize, @@ -228,19 +229,25 @@ impl Registry { at: Option<&Timestamp>, mut draft: Draft, ) -> Result { - if let Some(span) = &draft.span { - // BORROW: .as_str().to_owned() makes the owned call id the maps keep - let call = span.as_str().to_owned(); - if let EventKind::ToolCall { name, .. } = &draft.kind { - // BORROW: .clone() keeps the name of the call for its result - self.names.insert((target, call.clone()), name.clone()); + // BORROW: .as_str().to_owned() makes the owned call id the maps keep + let call = draft.span.as_ref().map(|span| span.as_str().to_owned()); + if let EventKind::ToolCall { name, .. } = &draft.kind { + if let Some(call) = call { + if name == SHELL_TOOL { + // BORROW: .clone() keeps the id for the holder map + self.shell.insert((target, call.clone())); + } self.owner.insert(call, target); - } else if let EventKind::ToolResult { exit, .. } = &mut draft.kind { - // Only a shell call reports an exit. - if self.names.get(&(target, call.clone())).map(String::as_str) != Some("Bash") { + } + } else if let EventKind::ToolResult { exit, .. } = &mut draft.kind { + if let Some(call) = call { + // BORROW: .clone() makes the owned key the set looks up + if !self.shell.contains(&(target, call.clone())) { *exit = None; } self.answered.insert(call); + } else { + *exit = None; } } let node = self.node(target)?; From e894dba88d6249ed53e6399c8485a37cd1b74090 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:53:19 +0900 Subject: [PATCH 42/93] test(adapter-claude-code): pin both join orders and the unjoined result Both orders of a shared call id, and a result with no span. Co-Authored-By: Claude Sonnet 5.5 --- .../tests/it/guard_reader.rs | 94 ++++++++++++------- 1 file changed, 61 insertions(+), 33 deletions(-) diff --git a/crates/candler-harness-claude-code/tests/it/guard_reader.rs b/crates/candler-harness-claude-code/tests/it/guard_reader.rs index ffbb432b..1910d7eb 100644 --- a/crates/candler-harness-claude-code/tests/it/guard_reader.rs +++ b/crates/candler-harness-claude-code/tests/it/guard_reader.rs @@ -267,10 +267,10 @@ fn stream_with(result: Option<&str>) -> Vec> { lines } -/// A result's exit as `expected.toml` writes it: session, call id, the name of the call, and the exit code when there is one. -type ExitRow = (String, String, String, Option); +/// A result's exit as a row states it: session, call id, the name of the call, and the exit code when there is one. +type ExitRow<'a> = (&'a str, &'a str, &'a str, Option); -fn expected_exits(stream: &Stream) -> Res> { +fn expected_exits(stream: &Stream) -> Res>> { let Some(rows) = stream.expected.get("exits") else { return Ok(Vec::new()); }; @@ -282,9 +282,9 @@ fn expected_exits(stream: &Stream) -> Res> { .map(|code| -> Res { Ok(i32::try_from(code.as_integer().ok_or("code")?)?) }) .transpose()?; out.push(( - text(entry, "session")?.to_owned(), // BORROW: owned copy - text(entry, "tool_use_id")?.to_owned(), // BORROW: owned copy - text(entry, "tool")?.to_owned(), // BORROW: owned copy + text(entry, "session")?, + text(entry, "tool_use_id")?, + text(entry, "tool")?, code, )); } @@ -292,8 +292,8 @@ fn expected_exits(stream: &Stream) -> Res> { } /// Checks each row against the reader's result of that call in that session: the call has the name the row gives, and the result has the exit code the row gives, or none. -fn check_exits(name: &str, output: &Output, rows: &[ExitRow]) -> Res<()> { - for (session, id, tool, want) in rows { +fn check_exits(name: &str, output: &Output, rows: &[ExitRow<'_>]) -> Res<()> { + for &(session, id, tool, want) in rows { let held: Vec<&SessionEvent> = output .events .iter() @@ -316,11 +316,11 @@ fn check_exits(name: &str, output: &Output, rows: &[ExitRow]) -> Res<()> { } }) .collect(); - assert_eq!( - called, - [tool.as_str()], - "{name}: the call {id} in {session}" - ); + if called != [tool] { + return Err( + format!("{name}: the call {id} in {session} is {called:?}, want {tool}").into(), + ); + } let mut results = Vec::new(); for record in &held { if let EventKind::ToolResult { exit, .. } = &record.event.kind { @@ -331,22 +331,45 @@ fn check_exits(name: &str, output: &Output, rows: &[ExitRow]) -> Res<()> { }); } } - assert_eq!( - results, - [*want], - "{name}: exit of the result of {tool} call {id} in {session}" - ); + if results != [want] { + return Err(format!( + "{name}: exit of the result of {tool} call {id} in {session} is {results:?}, want {want:?}" + ) + .into()); + } } Ok(()) } -/// Lines in which one call id names a `Read` in the root session and a `Bash` in the subagent session `S/A`, so the result in each session gets the exit of its own call; and a `Bash` call whose result is not an error but reports `interrupted`. +/// Checks that no result without a span carries an exit, and that the stream has one. +fn check_spanless_results(name: &str, output: &Output) -> Res<()> { + let mut seen = 0_usize; + for record in &output.events { + if let (EventKind::ToolResult { exit, .. }, None) = (&record.event.kind, &record.event.span) + { + seen += 1; + if exit.is_some() { + return Err(format!("{name}: a result joined to no call has exit {exit:?}").into()); + } + } + } + if seen == 0 { + return Err(format!("{name}: the stream has no result without a span").into()); + } + Ok(()) +} + +/// Lines in which a call id names a `Read` in the root session and a `Bash` in the subagent session `S/A`, so the result in each session gets the exit of its own call: `X` answers the root result first, `Y` the child result first; a `Bash` call whose result is not an error but reports `interrupted`; and a result whose id is no span (it holds white space), which joins no call. fn exit_join_stream() -> Vec> { - let bash = r#"{"type":"tool_use","id":"X","name":"Bash","input":{"command":"true"}}"#; - let read = r#"{"type":"tool_use","id":"X","name":"Read","input":{}}"#; + let bash = |id: &str| { + format!(r#"{{"type":"tool_use","id":"{id}","name":"Bash","input":{{"command":"true"}}}}"#) + }; + let read = + |id: &str| format!(r#"{{"type":"tool_use","id":"{id}","name":"Read","input":{{}}}}"#); let agent = r#"{"type":"tool_use","id":"A","name":"Agent","input":{}}"#; - let result = - |text: &str| format!(r#"{{"type":"tool_result","tool_use_id":"X","content":"{text}"}}"#); + let result = |id: &str, text: &str| { + format!(r#"{{"type":"tool_result","tool_use_id":"{id}","content":"{text}"}}"#) + }; let line = |kind: &str, parent: &str, blocks: &[&str]| { format!( r#"{{"type":"{kind}","session_id":"S",{parent}"message":{{"role":"{kind}","content":[{}]}}}}"#, @@ -355,19 +378,21 @@ fn exit_join_stream() -> Vec> { .into_bytes() }; let cut = r#"{"type":"tool_use","id":"I","name":"Bash","input":{"command":"sleep 9"}}"#; - let cut_result = r#"{"type":"tool_result","tool_use_id":"I","content":"partial"}"#; let child = r#""parent_tool_use_id":"A","#; let mut lines = stream_with(None); - lines.push(line("assistant", "", &[agent, read])); - lines.push(line("assistant", child, &[bash])); - lines.push(line("user", "", &[&result("file text")])); - lines.push(line("user", child, &[&result("")])); + lines.push(line("assistant", "", &[agent, &read("X"), &read("Y")])); + lines.push(line("assistant", child, &[&bash("X"), &bash("Y")])); + lines.push(line("user", "", &[&result("X", "file text")])); + lines.push(line("user", child, &[&result("X", "")])); + lines.push(line("user", child, &[&result("Y", "")])); + lines.push(line("user", "", &[&result("Y", "file text")])); lines.push(line("assistant", "", &[cut])); lines.push(line( "user", r#""tool_use_result":{"interrupted":true},"#, - &[cut_result], + &[&result("I", "partial")], )); + lines.push(line("user", "", &[&result("no span", "")])); lines } @@ -531,12 +556,15 @@ fn expected_facts() -> Res<()> { assert_eq!(got, want, "result line {result:?}"); } let shared = run(&exit_join_stream(), false)?; - let rows: [ExitRow; 3] = [ - ("S".to_owned(), "X".to_owned(), "Read".to_owned(), None), // BORROW: owned text - ("S/A".to_owned(), "X".to_owned(), "Bash".to_owned(), Some(0)), // BORROW: owned text - ("S".to_owned(), "I".to_owned(), "Bash".to_owned(), None), // BORROW: owned text + let rows: [ExitRow<'_>; 5] = [ + ("S", "X", "Read", None), + ("S/A", "X", "Bash", Some(0)), + ("S", "Y", "Read", None), + ("S/A", "Y", "Bash", Some(0)), + ("S", "I", "Bash", None), ]; check_exits("shared call id", &shared, &rows)?; + check_spanless_results("shared call id", &shared)?; Ok(()) } From 16bfc967cc15ab821fbf57194bfdc192aada29e8 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:53:48 +0900 Subject: [PATCH 43/93] reports(adapter-claude-code): record the review round of the Bash exit Co-Authored-By: Claude Sonnet 5.5 --- .../run-context/leaves/cc_reader_exit_v0.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/__reports__/run-context/leaves/cc_reader_exit_v0.md b/__reports__/run-context/leaves/cc_reader_exit_v0.md index 8956e652..a108bd68 100644 --- a/__reports__/run-context/leaves/cc_reader_exit_v0.md +++ b/__reports__/run-context/leaves/cc_reader_exit_v0.md @@ -95,3 +95,22 @@ recorded stream. The literal stream is the only place the two differ. `guard_supervise::a_pre_stop_command_leaves_nothing_in_its_group` and `guard_wiring::wiring_stop_execs_in_the_container_with_the_observed_id` failed under full load and pass alone (0.9 s and 97 s). `fmt --check`, `clippy -D warnings` and `doc -D warnings` pass. - Gate 4 lists what `parse.rs` reads; the code also reads `interrupted` and the denial meta, as Step 2's text requires. + +## Review round + +- **Unjoined result kept its exit.** `SpanId` refuses an empty id, `#` and white space, so a raw line can carry + `"tool_use_id":"no span"`; `span_of` then gives no span and the result kept `exit_of`'s code 0. `Registry::emit` now clears + the exit of a result with no span too. A literal row (a non-error result with id `no span`, `check_spanless_results`) was + red on the code before the fix: `Error: "shared call id: a result joined to no call has exit Some(Code { code: 0 })"`. +- **One shell name.** `SHELL_TOOL` (`parse.rs`) is used by the argv rule and by the gate in `sessions.rs`. +- **Only what the gate needs.** `names: HashMap<(usize, String), String>` became `shell: HashSet<(usize, String)>`, filled by + `Bash` calls only; each remaining clone keeps its `// BORROW:` note. +- **Both join orders.** The shared-id stream has `X` (root `Read` result first) and `Y` (child `Bash` result first, root `Read` + result after it). `Y` already passed on the code before the fix. +- **Docs.** `emit` and `exit_of` say what they do (no construction detail; non-error result with no flag reads as exit 0); + the empty-digits case is explicit. +- **Tests.** `ExitRow` holds `&str`, no `// BORROW: owned text` on literals; `check_exits` returns `Err` for every failure. +- **Bite (c) again**, on `scratch/bites` (deleted), set keyed by call id only: `Error: "shared call id: exit of the result of + Read call X in S is [Some(0)], want None"`. +- Checks: `fmt --check`, `clippy -p ... --all-targets -D warnings`, `nextest run -p ...` (21 of 21), `doc -D warnings`, and + `git grep -n confirm_ -- crates python` (empty) pass. From ac4e2be40131c433bd6790bfbdd1b6193f972fb1 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:54:16 +0900 Subject: [PATCH 44/93] rdm(adapter-claude-code): close the Claude Code exit reader Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/readers/README.md b/__roadmap__/run_context/readers/README.md index 77901d7f..23b26b53 100644 --- a/__roadmap__/run_context/readers/README.md +++ b/__roadmap__/run_context/readers/README.md @@ -16,7 +16,7 @@ Both trace readers record the harness's exit status, `assemble`/`materialise` se ## Status ```mermaid graph TD - cc_reader_exit[Claude Code exit]:::inprogress + cc_reader_exit[Claude Code exit]:::done oc_reader_exit[OpenCode exit]:::done serve_context[Serve the run]:::inprogress helper_context[Helper context]:::inprogress @@ -31,7 +31,7 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `cc_reader_exit.md` | 📄 Leaf Task | 🔄 In Progress | +| `cc_reader_exit.md` | 📄 Leaf Task | ✅ Done | | `oc_reader_exit.md` | 📄 Leaf Task | ✅ Done | | `serve_context.md` | 📄 Leaf Task | 🔄 In Progress | | `helper_context.md` | 📄 Leaf Task | 🔄 In Progress | From f03d4554e3c099128c5ead710a6a70f745b8694c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:56:56 +0900 Subject: [PATCH 45/93] fix(adapter-opencode): name the export reader that writes exit status A shell result read from the export now carries `exit`, so traces with and without it claimed the same `opencode-export@0.1.0`. The export reader is now `opencode-export@0.2.0`, and its id and the header text come from one version constant. The live reader's output did not change and stays at 0.1.0. Both reader docs state the rule that the version changes whenever the reader's output does. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/tests/it/guard_wiring.rs | 2 +- crates/candler-harness-opencode/src/export.rs | 4 ++-- crates/candler-harness-opencode/src/lib.rs | 9 ++++++--- crates/candler/tests/it/guard_registry.rs | 2 +- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/candler-core/tests/it/guard_wiring.rs b/crates/candler-core/tests/it/guard_wiring.rs index 52561223..4d08d34f 100644 --- a/crates/candler-core/tests/it/guard_wiring.rs +++ b/crates/candler-core/tests/it/guard_wiring.rs @@ -124,7 +124,7 @@ fn wiring_collect_exports_before_the_destroy_and_the_export_is_the_trace() { let first: Value = serde_json::from_str(trace.lines().next().expect("a header")).expect("header JSON"); assert_eq!( - first["reader"], "opencode-export@0.1.0", + first["reader"], "opencode-export@0.2.0", "{case}: the trace names the export reader: {first}" ); assert!( diff --git a/crates/candler-harness-opencode/src/export.rs b/crates/candler-harness-opencode/src/export.rs index d4164419..d7853889 100644 --- a/crates/candler-harness-opencode/src/export.rs +++ b/crates/candler-harness-opencode/src/export.rs @@ -18,7 +18,7 @@ use candler_schemas::trace::{ }; use serde_json::{Map, Value}; -use crate::{VALIDATED, session_source}; +use crate::{EXPORT_READER_VERSION, VALIDATED, session_source}; use candler_schemas::name; /// The tools `OpenCode` offers the model by itself, as `opencode_facts` listed them. @@ -333,7 +333,7 @@ impl OpenCodeExportReader { // 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)), + identity: NameVersion::of(&name!("opencode-export"), EXPORT_READER_VERSION), read: None, servers, } diff --git a/crates/candler-harness-opencode/src/lib.rs b/crates/candler-harness-opencode/src/lib.rs index 4951256e..18715695 100644 --- a/crates/candler-harness-opencode/src/lib.rs +++ b/crates/candler-harness-opencode/src/lib.rs @@ -30,11 +30,14 @@ pub const SUPPORTED: &str = "=2.2.7"; /// `harness_version` is this one, which is true because the driver refuses every other. pub const VALIDATED: semver::Version = semver::Version::new(2, 2, 7); -/// The reader of the live NDJSON, as the trace header names it. +/// The reader of the live NDJSON, as the trace header names it, `opencode-ndjson@`; the version changes whenever the reader's output does. pub const LIVE_READER: &str = "opencode-ndjson@0.1.0"; -/// The reader of the session export, as the trace header names it. -pub const EXPORT_READER: &str = "opencode-export@0.1.0"; +/// The reader of the session export, as the trace header names it, `opencode-export@`; the version changes whenever the reader's output does. +pub const EXPORT_READER: &str = "opencode-export@0.2.0"; + +/// The version of [`EXPORT_READER`]. +const EXPORT_READER_VERSION: semver::Version = semver::Version::new(0, 2, 0); /// The stream name under which the gateway's census is stored. pub const CENSUS_STREAM: &str = "gateway_census"; diff --git a/crates/candler/tests/it/guard_registry.rs b/crates/candler/tests/it/guard_registry.rs index 4d6780c0..d323914c 100644 --- a/crates/candler/tests/it/guard_registry.rs +++ b/crates/candler/tests/it/guard_registry.rs @@ -281,7 +281,7 @@ fn registry_ingest_reads_each_path_with_its_own_harness() { readers.sort(); assert_eq!(readers.len(), 2, "two runs: {readers:?}"); assert!(readers[0].starts_with("claude-code"), "{readers:?}"); // INDEX: two readers, checked above - assert_eq!(readers[1], "opencode-export@0.1.0", "{readers:?}"); // INDEX: two readers, checked above + assert_eq!(readers[1], "opencode-export@0.2.0", "{readers:?}"); // INDEX: two readers, checked above let corpus = root.join("../candler-core/tests/fixtures/mini-corpus"); let rules = fs::read_to_string(root.join("tests/fixtures/cli/mini-corpus-rules.toml")) From 410085d45489ccc4f44bb3d4edfa3bbff8750754 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:22:16 +0900 Subject: [PATCH 46/93] test(evaluation): state serving of the trace, raw streams and manifest The guards state what a kind that declares needs.trace, needs.raw or needs.manifest is handed: a private 0444 copy of each stored file with its digest in the context and in the context digest, untouched store bytes after a careless write, and a refusal with a code when the run lacks the part. The live digest generator gains served rows. The engine's fold of a plug-in's needs moves into union_needs unchanged (it still drops raw and manifest), so the guards declare each part through the path the engine uses. Co-Authored-By: Claude Sonnet 5.5 --- .../src/evaluation/context/mod.rs | 2 + .../src/evaluation/context/union.rs | 37 +++ .../candler-core/src/evaluation/engine/run.rs | 30 +- .../tests/it/guard_run_context.rs | 262 +++++++++++++++++- .../tests/oracle/vectors/gen_live_context.py | 125 ++++++++- .../oracle/vectors/live_context_runs.toml | 31 +++ 6 files changed, 453 insertions(+), 34 deletions(-) create mode 100644 crates/candler-core/src/evaluation/context/union.rs diff --git a/crates/candler-core/src/evaluation/context/mod.rs b/crates/candler-core/src/evaluation/context/mod.rs index 56802aae..0376cff3 100644 --- a/crates/candler-core/src/evaluation/context/mod.rs +++ b/crates/candler-core/src/evaluation/context/mod.rs @@ -13,10 +13,12 @@ use crate::store::StoreError; mod assemble; mod materialise; mod rule; +mod union; pub use assemble::{Assembled, AssembledArtifact, AssembledInput, assemble}; pub use materialise::{Workspace, materialise}; pub use rule::{FileRule, file_rule_keeps}; +pub use union::union_needs; /// Why a run's context could not be assembled or materialised. #[derive(Debug, thiserror::Error)] diff --git a/crates/candler-core/src/evaluation/context/union.rs b/crates/candler-core/src/evaluation/context/union.rs new file mode 100644 index 00000000..dac45a56 --- /dev/null +++ b/crates/candler-core/src/evaluation/context/union.rs @@ -0,0 +1,37 @@ +//! The needs one request carries when it serves several kinds. + +use candler_schemas::evaluation::Needs; + +/// The needs of one request that serves every kind of `kinds`: a flag is set when any kind sets +/// it, and each list holds the members of the kinds once, in the order they are first named. +#[must_use] +pub fn union_needs<'a, I>(kinds: I) -> Needs +where + I: IntoIterator, +{ + let mut union = Needs::default(); + for more in kinds { + union.trace |= more.trace; + for artifact in &more.artifacts { + if !union.artifacts.contains(artifact) { + union.artifacts.push(artifact.clone()); // BORROW: the union owns its globs + } + } + for kind in &more.snapshots { + if !union.snapshots.contains(kind) { + union.snapshots.push(kind.clone()); // BORROW: the union owns its kinds + } + } + for kind in &more.inputs { + if !union.inputs.contains(kind) { + union.inputs.push(kind.clone()); // BORROW: the union owns its kinds + } + } + for path in &more.metadata { + if !union.metadata.contains(path) { + union.metadata.push(path.clone()); // BORROW: the union owns its paths + } + } + } + union +} diff --git a/crates/candler-core/src/evaluation/engine/run.rs b/crates/candler-core/src/evaluation/engine/run.rs index 54f851c0..92f34a30 100644 --- a/crates/candler-core/src/evaluation/engine/run.rs +++ b/crates/candler-core/src/evaluation/engine/run.rs @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; -use candler_schemas::evaluation::{EvaluateParams, Item, Needs}; +use candler_schemas::evaluation::{EvaluateParams, Item}; use candler_schemas::execution::EventPayload; use candler_schemas::outcome::{Instrument, OutcomeRecord, Status}; use candler_schemas::primitives::{ @@ -21,7 +21,7 @@ use tokio::sync::watch; use super::plan::{Batch, RunPlan}; use super::write::{self, Stamp}; use crate::evaluation::client::{Client, ClientError, EvaluatorCommand, ItemOutcome}; -use crate::evaluation::context::{assemble, materialise}; +use crate::evaluation::context::{assemble, materialise, union_needs}; use crate::evaluation::registry::CheckedEntry; use crate::jobs::slots::{Holder, Slot, SlotError, Slots}; use crate::store::Store; @@ -617,31 +617,7 @@ async fn send( batch_ids: &BTreeSet, ticket: &mut Ticket, ) -> Result<(crate::evaluation::client::ClientOutcome, Digest), Fault> { - let mut needs = Needs::default(); - for checked in sendable { - let more = &checked.spec.needs; - needs.trace |= more.trace; - for artifact in &more.artifacts { - if !needs.artifacts.contains(artifact) { - needs.artifacts.push(artifact.clone()); // BORROW: the union owns its globs - } - } - for kind in &more.snapshots { - if !needs.snapshots.contains(kind) { - needs.snapshots.push(kind.clone()); // BORROW: the union owns its kinds - } - } - for kind in &more.inputs { - if !needs.inputs.contains(kind) { - needs.inputs.push(kind.clone()); // BORROW: the union owns its kinds - } - } - for path in &more.metadata { - if !needs.metadata.contains(path) { - needs.metadata.push(path.clone()); // BORROW: the union owns its paths - } - } - } + let needs = union_needs(sendable.iter().map(|checked| &checked.spec.needs)); let store = shared.store.clone(); // BORROW: the blocking task owns a handle on the store let key = run.clone(); // BORROW: the blocking task owns the key let dir = shared.work.join(ticket.minted.as_str()); diff --git a/crates/candler-core/tests/it/guard_run_context.rs b/crates/candler-core/tests/it/guard_run_context.rs index 7f82733e..cd9de015 100644 --- a/crates/candler-core/tests/it/guard_run_context.rs +++ b/crates/candler-core/tests/it/guard_run_context.rs @@ -15,12 +15,13 @@ use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _}; use std::path::{Path, PathBuf}; use std::str::FromStr as _; -use candler_core::evaluation::context::{ContextError, assemble, materialise}; +use candler_core::evaluation::context::{ContextError, assemble, materialise, union_needs}; use candler_core::store::Store; use candler_core::store::run::{Existing, RunWriter}; use candler_schemas::evaluation::{Needs, RunContext}; use candler_schemas::execution::{RunManifest, RunTree, TreeEntry}; use candler_schemas::primitives::{Digest, FieldPath, RelPath, RunKey}; +use candler_schemas::refusal::Refusal as _; use legacy_import::{cell_of, copy_tree, import_with_reader, mini}; use sha2::{Digest as _, Sha256}; @@ -101,7 +102,136 @@ fn context_of(store: &Store, run: &RunKey, needs: &Needs, workspace: &Path) -> R materialise(&assembled, workspace).expect("the run materialises") } -/// Guards: R9 — the digest of a materialised live context equals the independent vector of the run's raw `outputs/` files and `experiment.json`, and a twin whose `domain.py` differs by one byte has the vector of the twin, which is not the original's. Oracle: `live_context_runs.toml`, written by `gen_live_context.py` with python `rfc8785` from the raw corpus. +/// The needs of a request that serves one kind per entry of `parts` (`trace`, `raw` or +/// `manifest`, each declared by a kind of its own) and a kind that wants the parity suite's +/// artifacts and metadata, folded the way the engine folds the kinds of a plug-in. +fn needs_declaring(parts: &[&str]) -> Needs { + let mut kinds = vec![parity_needs()]; + for part in parts { + let mut kind = Needs::default(); + match *part { + "trace" => kind.trace = true, + "raw" => kind.raw = true, + "manifest" => kind.manifest = true, + other => panic!("`{other}` is not a part of a run"), + } + kinds.push(kind); + } + union_needs(&kinds) +} + +/// The files the store holds for the trace, the raw streams and the manifest of `run`, each as +/// its path in the store and its path below a workspace. The streams are listed from the store's +/// `raw/` directory. +fn stored_parts(store: &Store, run: &RunKey) -> Vec<(PathBuf, String)> { + let layout = store.layout(); + let mut parts = vec![(layout.trace(run), "trace.jsonl".to_owned())]; + let mut streams: Vec = fs::read_dir(layout.raw_dir(run)) + .expect("the raw directory lists") + .map(|entry| { + entry + .expect("an entry") + .file_name() + .into_string() + .expect("a UTF-8 name") + }) + .collect(); + streams.sort(); + for name in streams { + parts.push((layout.raw_dir(run).join(&name), format!("raw/{name}"))); + } + parts.push((layout.manifest(run), "manifest.json".to_owned())); + parts +} + +/// Guards: R9 and R01 §Evaluator protocol — kinds that declare `trace`, `raw` and `manifest`, folded as the engine folds them, get `context.trace`, `context.raw[]` and `context.manifest`: each a private read-only copy (`0444`, one link, an inode of its own) of the file the store holds, whose bytes hash to the sha256 the context states; and a request that declares none of them is served none. Oracle: the sha256, bytes and inode of the store's own `trace.jsonl`, `raw/.jsonl.gz` and `manifest.json`, read here. +#[test] +fn kinds_that_declare_the_run_parts_are_served_their_stored_bytes() { + let (_keep, store) = mini_store(&mini()); + let run = key_of(&store, 6); + let stored = stored_parts(&store, &run); + assert!( + stored.len() >= 3, + "the run stores a trace, a stream and a manifest" + ); + + let workspace = tempfile::tempdir().expect("a workspace"); + let context = context_of( + &store, + &run, + &needs_declaring(&["trace", "raw", "manifest"]), + workspace.path(), + ); + let trace = context.trace().expect("the context serves the trace"); + let manifest = context.manifest().expect("the context serves the manifest"); + let mut served: Vec<(String, String, Digest)> = vec![ + ( + "trace.jsonl".to_owned(), + trace.abs.clone(), + trace.sha256.clone(), + ), + ( + "manifest.json".to_owned(), + manifest.abs.clone(), + manifest.sha256.clone(), + ), + ]; + assert_eq!(trace.path.as_str(), "trace.jsonl"); + assert_eq!(manifest.path.as_str(), "manifest.json"); + for raw in context.raw() { + let name = format!("raw/{}.jsonl.gz", raw.stream); + served.push((name, raw.path.clone(), raw.sha256.clone())); + } + assert_eq!( + served.len(), + stored.len(), + "one served file per stored part" + ); + + for (in_store, below) in &stored { + let (_, abs, stated) = served + .iter() + .find(|(name, _, _)| name == below) + .unwrap_or_else(|| panic!("`{below}` is not served")); + let copy = Path::new(abs); + assert_eq!( + copy, + workspace.path().join(below), + "where {below} is served" + ); + let bytes = fs::read(in_store).expect("a stored file reads"); + assert_eq!( + fs::read(copy).expect("a copy reads"), + bytes, + "bytes of {below}" + ); + assert_eq!(&sha256_of(&bytes), stated, "the digest stated for {below}"); + let (meta, original) = ( + fs::metadata(copy).expect("a copy"), + fs::metadata(in_store).expect("a stored file"), + ); + assert_eq!(meta.mode() & 0o777, 0o444, "the mode of {below}"); + assert_eq!(meta.nlink(), 1, "{below} has one link"); + assert_ne!( + meta.ino(), + original.ino(), + "{below} is not the store's inode" + ); + } + + let bare = tempfile::tempdir().expect("a workspace"); + let plain = context_of(&store, &run, &parity_needs(), bare.path()); + assert!( + plain.trace().is_none() && plain.manifest().is_none() && plain.raw().is_empty(), + "a request that declares no part is served none" + ); + assert!( + !bare.path().join("trace.jsonl").exists() && !bare.path().join("raw").exists(), + "no part is copied for a request that declares none" + ); +} + +/// Guards: R9 — the digest of a materialised live context equals the independent vector of the run's raw `outputs/` files and `experiment.json`, and a twin whose `domain.py` differs by one byte has the vector of the twin, which is not the original's. and a context that also serves the trace, the raw streams or the manifest has the vector of its `[[served]]` row, whose recorded hashes equal the hashes of the files the store holds. Oracle: `live_context_runs.toml`, written by `gen_live_context.py` with python `rfc8785` from the raw corpus and the stored files' hashes. #[test] fn the_live_context_digest_is_the_independent_vector() { let vectors = live_vectors(); @@ -167,15 +297,66 @@ fn the_live_context_digest_is_the_independent_vector() { base_digest, "one byte changes the digest" ); + + let vectors = toml::Value::Table(vectors); + let served = tables_at(&vectors, "served"); + assert_eq!(served.len(), 3, "vector rows that serve parts"); + for vector in served { + let run = text_at(vector, "run"); + let parts: Vec<&str> = tables_at_str(vector, "needs"); + let key = key_of(&store, replicate_of(run)); + let stored = |name: &str| { + sha256_of( + &fs::read(store.layout().run_dir(&key).join(name)).expect("a stored file reads"), + ) + }; + // The hashes the row records are those of the files this store holds. + if parts.contains(&"trace") { + assert_eq!( + stored("trace.jsonl").to_string(), + text_at(vector, "trace_sha256"), + "trace of {run}" + ); + } + if parts.contains(&"manifest") { + assert_eq!( + stored("manifest.json").to_string(), + text_at(vector, "manifest_sha256"), + "manifest of {run}" + ); + } + if parts.contains(&"raw") { + for stream in tables_at(vector, "raw") { + let name = format!("raw/{}.jsonl.gz", text_at(stream, "stream")); + assert_eq!( + stored(&name).to_string(), + text_at(stream, "sha256"), + "{name} of {run}" + ); + } + } + let workspace = tempfile::tempdir().expect("a workspace"); + let context = context_of(&store, &key, &needs_declaring(&parts), workspace.path()); + assert_eq!( + context.context_digest().to_string(), + text_at(vector, "digest"), + "{run} serving {parts:?}" + ); + } } -/// 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. +/// Guards: R9 and I11 — a plug-in that appends to, or overwrites, a materialised file (an artifact, the trace, a raw stream or the manifest), after making it writable as a careless one would, leaves every blob, the trace, the raw streams and the manifest of the store with their bytes and modes. Oracle: the sha256 the store's tree records for each blob, and a read of each stored file's bytes and mode taken here before the plug-in writes. #[test] fn a_plug_in_cannot_write_through_to_the_store() { let (_keep, store) = mini_store(&mini()); let run = key_of(&store, 6); let workspace = tempfile::tempdir().expect("a workspace"); - let context = context_of(&store, &run, &parity_needs(), workspace.path()); + let context = context_of( + &store, + &run, + &needs_declaring(&["trace", "raw", "manifest"]), + workspace.path(), + ); assert!(context.artifacts().len() >= 3, "the run has artifacts"); let tree = store.read_tree(&run).expect("the tree reads"); @@ -193,6 +374,26 @@ fn a_plug_in_cannot_write_through_to_the_store() { }) .collect(); + let parts = stored_parts(&store, &run); + let parts_before: Vec<(Vec, u32)> = parts + .iter() + .map(|(file, _)| { + ( + fs::read(file).expect("a stored file reads"), + fs::metadata(file).expect("a stored file").mode(), + ) + }) + .collect(); + for (_, below) in &parts { + let copy = workspace.path().join(below); + fs::set_permissions(©, fs::Permissions::from_mode(0o644)).expect("chmod u+w"); + let mut append = OpenOptions::new().append(true).open(©).expect("opens"); + append.write_all(b"\nTAMPERED\n").expect("appends"); + drop(append); + let mut head = OpenOptions::new().write(true).open(©).expect("opens"); + head.write_all(b"XXXX").expect("overwrites"); + } + for (blob, path, sha) in &recorded { let copy = workspace.path().join("outputs").join(path.as_str()); assert_eq!( @@ -220,6 +421,18 @@ fn a_plug_in_cannot_write_through_to_the_store() { "the mode of the store blob of {path}" ); } + for ((file, below), (bytes, mode)) in parts.iter().zip(&parts_before) { + assert_eq!( + &fs::read(file).expect("a stored file reads"), + bytes, + "the stored bytes of {below}" + ); + assert_eq!( + fs::metadata(file).expect("a stored file").mode(), + *mode, + "the stored mode of {below}" + ); + } } /// Guards: R9 — the digest of a materialised context is taken from the bytes written to the workspace, and a store blob that no longer holds the bytes of its recorded sha256 is refused with `CorruptBlob` and no context. Oracle: a blob of the store overwritten here with other bytes, so the recorded sha256 and the written bytes differ. @@ -375,6 +588,14 @@ fn input_vectors() -> toml::Table { text.parse().expect("the vectors parse") } +/// The strings of the array `key` of `value`. +fn tables_at_str<'t>(value: &'t toml::Value, key: &str) -> Vec<&'t str> { + tables_at(value, key) + .iter() + .map(|item| item.as_str().expect("a string")) + .collect() +} + /// The array of tables `key` of `value`. fn tables_at<'t>(value: &'t toml::Value, key: &str) -> &'t [toml::Value] { value @@ -638,3 +859,36 @@ fn needs_inputs_refused_when_the_list_blob_is_not_its_digests_list() { "`{text}` names the kind and the non-canonical list" ); } + +/// Guards: R01 §Evaluator protocol — a kind that declares the trace, or the raw streams, of a run that stores none of them is refused with the code `evaluation.run_part_missing`, naming the part, and no context is made; the same run serves its manifest. Oracle: hand-written; the parts and the code are the ones written below, and the run is sealed over a manifest alone by the store's own writer. +#[test] +fn needs_parts_refused_when_the_run_cannot_serve_them() { + let (_keep, store) = mini_store(&mini()); + let template = key_of(&store, 6); + let bare = seal_with_inputs(&store, &template, 2, &[], &[]); + assert!( + !store.layout().trace(&bare).exists() && !store.layout().raw_dir(&bare).exists(), + "the run stores neither a trace nor a raw stream" + ); + for part in ["trace", "raw"] { + let error = assemble(&store, &bare, &needs_declaring(&[part])) + .expect_err("a part the run lacks is refused"); + assert_eq!( + error.code().as_str(), + "evaluation.run_part_missing", + "{part}" + ); + assert!( + error.to_string().contains(&format!("`{part}`")), + "`{error}` names the part `{part}`" + ); + } + let workspace = tempfile::tempdir().expect("a workspace"); + let context = context_of( + &store, + &bare, + &needs_declaring(&["manifest"]), + workspace.path(), + ); + assert!(context.manifest().is_some(), "the manifest is always held"); +} diff --git a/crates/candler-core/tests/oracle/vectors/gen_live_context.py b/crates/candler-core/tests/oracle/vectors/gen_live_context.py index 15b5f56d..0e1afd8f 100644 --- a/crates/candler-core/tests/oracle/vectors/gen_live_context.py +++ b/crates/candler-core/tests/oracle/vectors/gen_live_context.py @@ -20,14 +20,29 @@ The twin: `run-6` of the first cell with the first byte of `outputs/domain.py` XORed with 0x01. Its digest must differ from the run's own. + +Served parts (the `[[served]]` rows). A context whose kinds declare `trace`, `raw` or `manifest` +adds, to the projection above, one key per served part and only for a served part: + + trace the sha256 of the stored `trace.jsonl`, as `sha256:` + raw `[{stream, sha256}]` sorted by `stream`, one per stored `raw/.jsonl.gz` + manifest the sha256 of the stored `manifest.json` + +The bytes of those files are the store's, written by the import, so the generator reads them from +a store folder given with `--store` (the hash of a file is the only thing it takes from there) and +records each hash in its row. Without `--store` it reuses the hashes its rows already record, so +`--check` needs no store; the Rust guard compares each recorded hash with the hash of the file the +store holds before it compares digests. """ import argparse +import glob import hashlib import importlib.metadata import json import os import sys +import tomllib import rfc8785 @@ -42,6 +57,11 @@ METADATA_PATHS = ["plan.prompt_domain_name"] TWIN_RUN = (V3, 6) TWIN_FILE = "domain.py" +SERVED = [ + (V3, 6, ["trace", "raw", "manifest"]), + (V6, 12, ["trace"]), + (V3, 17, ["raw", "manifest"]), +] def digest_of(value): @@ -127,7 +147,98 @@ def header(): ) -def generate(corpus): +def sha_of_file(path): + with open(path, "rb") as f: + return "sha256:" + hashlib.sha256(f.read()).hexdigest() + + +def stored_hashes(store, n): + """The sha256 of the trace, manifest and each raw stream the store holds for replicate `n`.""" + found = glob.glob(os.path.join(store, "runs", f"*-r{n}-a1")) + assert len(found) == 1, (n, found) + run = found[0] + raw = sorted( + (name[: -len(".jsonl.gz")], sha_of_file(os.path.join(run, "raw", name))) + for name in os.listdir(os.path.join(run, "raw")) + if name.endswith(".jsonl.gz") + ) + return { + "trace": sha_of_file(os.path.join(run, "trace.jsonl")), + "manifest": sha_of_file(os.path.join(run, "manifest.json")), + "raw": raw, + } + + +def recorded_hashes(path): + """The hashes the `[[served]]` rows of the file on disk record, by replicate.""" + with open(path, "rb") as f: + rows = tomllib.load(f).get("served", []) + return { + replicate_of(row["run"]): { + "trace": row.get("trace_sha256"), + "manifest": row.get("manifest_sha256"), + "raw": [(r["stream"], r["sha256"]) for r in row.get("raw", [])], + } + for row in rows + } + + +def replicate_of(run): + return int(run.rsplit("run-", 1)[1]) + + +def served_projection(base, parts, held): + proj = dict(base) + if "trace" in parts: + proj["trace"] = held["trace"] + if "raw" in parts: + proj["raw"] = [{"stream": s, "sha256": h} for s, h in sorted(held["raw"])] + if "manifest" in parts: + proj["manifest"] = held["manifest"] + return proj + + +def served_rows(corpus, hashes): + out = [ + "# Served parts: the same runs and needs as above, with the kinds declaring the parts named in", + "# `needs`. `trace_sha256`, `manifest_sha256` and `raw` record the hash of each stored file", + "# (see gen_live_context.py); a part a row does not serve has none of them and no key in its projection.", + "", + ] + base_digests = {} + for cell, n, parts in SERVED: + held = hashes[n] + base = projection(run_artifacts(corpus, cell, n), run_metadata(corpus, cell)) + proj = served_projection(base, parts, held) + digest = digest_of(proj) + assert digest != digest_of(base) + assert digest not in base_digests.values() + base_digests[n] = digest + out += [ + "[[served]]", + f"cell = {toml_str(cell)}", + f"run = {toml_str(f'{CONFIG}/run-{n}')}", + f"needs = [{', '.join(toml_str(p) for p in parts)}]", + ] + if "trace" in parts: + out.append(f"trace_sha256 = {toml_str(held['trace'])}") + if "manifest" in parts: + out.append(f"manifest_sha256 = {toml_str(held['manifest'])}") + if "raw" in parts: + items = ", ".join( + f"{{ stream = {toml_str(s)}, sha256 = {toml_str(h)} }}" + for s, h in sorted(held["raw"]) + ) + out.append(f"raw = [{items}]") + out += [ + f"projection = {toml_str(jtext(proj))}", + f"digest = {toml_str(digest)}", + "", + ] + return "\n".join(out) + + +def generate(corpus, hashes): out = [header()] digests = {} for cell, n in REAL_RUNS: @@ -159,7 +270,7 @@ def generate(corpus): f"digest = {toml_str(twin_digest)}", "", ] - return "\n".join(out) + return "\n".join(out) + "\n" + served_rows(corpus, hashes) def main(): @@ -168,9 +279,17 @@ def main(): "--check", action="store_true", help="compare with the file on disk" ) ap.add_argument("corpus", help="the mini-corpus folder") + ap.add_argument( + "--store", + help="a store folder holding the import of the corpus: the source of the served files' hashes", + ) args = ap.parse_args() - text = generate(args.corpus) path = os.path.join(HERE, OUT) + if args.store: + hashes = {n: stored_hashes(args.store, n) for _, n, _ in SERVED} + else: + hashes = recorded_hashes(path) + text = generate(args.corpus, hashes) if not args.check: with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(text) diff --git a/crates/candler-core/tests/oracle/vectors/live_context_runs.toml b/crates/candler-core/tests/oracle/vectors/live_context_runs.toml index 9e6ceefc..a2580f83 100644 --- a/crates/candler-core/tests/oracle/vectors/live_context_runs.toml +++ b/crates/candler-core/tests/oracle/vectors/live_context_runs.toml @@ -38,3 +38,34 @@ file = "domain.py" xor_first_byte = 1 projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:9e79641026c088d5977727a252eccb44aa5a440399011f497b5504e82ce33e0b\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:0c2651a20f393284ab0880100416feda100c6ee8428c0d97367d0e624568e9b4\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:57d084dc0f9ea0b8a555d66fba8a0fc441a14675442af09964a2f1f9ef710d28\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"}}" digest = "sha256:c09cf0ea32d68a6f13fa8418a7d26844212dbe6e514c8a486829cab7af5d5fb9" + +# Served parts: the same runs and needs as above, with the kinds declaring the parts named in +# `needs`. `trace_sha256`, `manifest_sha256` and `raw` record the hash of each stored file +# (see gen_live_context.py); a part a row does not serve has none of them and no key in its projection. + +[[served]] +cell = "20260806-035940_v0.2.3_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-v0.2.3" +run = "with_skill/run-6" +needs = ["trace", "raw", "manifest"] +trace_sha256 = "sha256:69a060902f6c8e57181e00e1168db325f161e0dc2a7c4fd5d17120adc8015d7b" +manifest_sha256 = "sha256:0b63023ac489f555b8b43a45e67e88614cdf047d2b9f24613ddffddee0ce9bfd" +raw = [{ stream = "stderr", sha256 = "sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e" }, { stream = "stdout", sha256 = "sha256:20d43143e335ec527bdbb3943aea771523bac466a366f5bc1efb114d9df676c8" }] +projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:9e79641026c088d5977727a252eccb44aa5a440399011f497b5504e82ce33e0b\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:67bc1eac7242670159d22fcfa503416b4f0874a405c206eb4c6a0d1126130b61\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:57d084dc0f9ea0b8a555d66fba8a0fc441a14675442af09964a2f1f9ef710d28\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:69a060902f6c8e57181e00e1168db325f161e0dc2a7c4fd5d17120adc8015d7b\",\"raw\":[{\"stream\":\"stderr\",\"sha256\":\"sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e\"},{\"stream\":\"stdout\",\"sha256\":\"sha256:20d43143e335ec527bdbb3943aea771523bac466a366f5bc1efb114d9df676c8\"}],\"manifest\":\"sha256:0b63023ac489f555b8b43a45e67e88614cdf047d2b9f24613ddffddee0ce9bfd\"}" +digest = "sha256:3407dcc0e38bf8d10392423e0bdb6f9b8eff44416ecdd315bcc8cf44e4bde3c6" + +[[served]] +cell = "20260806-035940_v0.2.6_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-0.2.6" +run = "with_skill/run-12" +needs = ["trace"] +trace_sha256 = "sha256:c0f214b78374d1917a4e30a7a6d443d8cea2463ef23c5d88057b3b92df438d90" +projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:d1238cde58dc83c8a22ec512974681b3c4f30c7eeeab977d5e3096058f318552\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:12b3cddb89db9df478e0f38a2b5ae531ddb968d330c3d8b71295b101795cb83f\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:588434f85cfb10eca786c798729a2a1a315c61caa1a26d8ff0504a5a39918fd4\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:c0f214b78374d1917a4e30a7a6d443d8cea2463ef23c5d88057b3b92df438d90\"}" +digest = "sha256:913328a495dd9dc92143923bb4bb9de30eadba74dda98db986457483de7b5c13" + +[[served]] +cell = "20260806-035940_v0.2.3_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-v0.2.3" +run = "with_skill/run-17" +needs = ["raw", "manifest"] +manifest_sha256 = "sha256:99e1e4149b6ab19493168633a19b71c4f5963a1d34a660408dec9e43045a399d" +raw = [{ stream = "stderr", sha256 = "sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e" }, { stream = "stdout", sha256 = "sha256:840f56d62935579f8449462b6835fe040bf5189f413b973240328181dec3e5ea" }] +projection = "{\"artifacts\":[{\"path\":\"domain.py\",\"sha256\":\"sha256:9796f2ffee49bed8fcb2d2f6b6a79ae0b615a17d30743f167287730f51e45733\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:242e73f98151c800389f902d956a1193d1abfeb12beaff734f3c84b7cbcc58da\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"raw\":[{\"stream\":\"stderr\",\"sha256\":\"sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e\"},{\"stream\":\"stdout\",\"sha256\":\"sha256:840f56d62935579f8449462b6835fe040bf5189f413b973240328181dec3e5ea\"}],\"manifest\":\"sha256:99e1e4149b6ab19493168633a19b71c4f5963a1d34a660408dec9e43045a399d\"}" +digest = "sha256:c02e9ee8328f73f73bb39ef87c416367c301847dd46699c3312e250009c33d09" From 55d5f3f52cfa8011cca54a6b93cc470c6677543b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:30:50 +0900 Subject: [PATCH 47/93] feat(evaluation): serve a run's trace, raw streams and manifest A kind that declares needs.trace, needs.raw or needs.manifest is handed the stored file, copied read-only into its workspace, with the digest in the context and in the context digest. A trace or raw need on a run that stores none is refused with evaluation.run_part_missing. Every stored file reaches the workspace through one routine given its source and expected digest, and Assembled carries one list of files. The union of a plug-in's needs now carries raw and manifest. Co-Authored-By: Claude Sonnet 5.5 --- .../run-context/01-ruling_trace_served_v0.md | 30 +++ __roadmap__/m3-lean-cli/refusal_scope.tsv | 2 +- .../src/evaluation/context/assemble.rs | 212 ++++++++++++++---- .../src/evaluation/context/materialise.rs | 78 ++++--- .../src/evaluation/context/mod.rs | 19 +- .../src/evaluation/context/union.rs | 2 + crates/candler-core/src/evaluation/refusal.rs | 8 + .../src/evaluation/registry/needs.rs | 7 +- docs/contract/codes.toml | 5 + docs/contract/index.md | 1 + 10 files changed, 279 insertions(+), 85 deletions(-) create mode 100644 __reports__/run-context/01-ruling_trace_served_v0.md diff --git a/__reports__/run-context/01-ruling_trace_served_v0.md b/__reports__/run-context/01-ruling_trace_served_v0.md new file mode 100644 index 00000000..b1796083 --- /dev/null +++ b/__reports__/run-context/01-ruling_trace_served_v0.md @@ -0,0 +1,30 @@ +# Ruling: the trace, the raw streams and the manifest are served (v0) + +## What is replaced + +The M2a ruling for `run_context` (`__reports__/m2a-evaluation-parity/l1/00-rulings_v0.md:75`) +accepted "`needs.trace` is ignored". That ruling is replaced. A kind that declares `needs.trace`, +`needs.raw` or `needs.manifest` is handed the stored file, and the context says which one by its +digest. + +## Why + +- **The README's evaluation half names traces.** "Grade traces and artifacts, fresh or already on + disk" cannot hold while a declared need for the trace is accepted and dropped. AGENTS.md calls a + second, more lenient reading of a declaration a defect even when nothing reaches it yet; ignoring + a declared need is that reading. +- **The declaration states what a kind sees.** Candler has no blinding concept. A kind lists its + needs in `describe`, Candler serves exactly those and refuses what it cannot serve, so what a kind + saw is on record in the kind itself. Serving the trace adds no hidden channel. +- **A sealed run never changes.** "Sealed" means complete and protected from overwrite, so the + digest taken when a stored file is chosen for a context holds for the whole evaluation, and the + outcome-reuse key can carry it. + +## What follows + +- A part the run lacks (the trace or the raw streams of a run the importer could not read, or of a + run sealed after an interruption) is refused with `ContextError::PartMissing`, code + `evaluation.run_part_missing`, and never served empty. The manifest is written when the run + directory is made, so every run holds it. +- Every stored file reaches a workspace through one copy routine, so a served part has the + guarantees an artifact has: a private copy, `0444`, checked against its digest. diff --git a/__roadmap__/m3-lean-cli/refusal_scope.tsv b/__roadmap__/m3-lean-cli/refusal_scope.tsv index 1945dff6..75c3375a 100644 --- a/__roadmap__/m3-lean-cli/refusal_scope.tsv +++ b/__roadmap__/m3-lean-cli/refusal_scope.tsv @@ -1,6 +1,6 @@ enum file variants author side section leaf note candler_core::evaluation::client::ClientError crates/candler-core/src/evaluation/client/mod.rs 5 mixed plugin evaluation refusal_late author-facing: Spawn (evaluator will not start), Cancelled, Describe failure; internal: Pipes, Encode -candler_core::evaluation::context::ContextError crates/candler-core/src/evaluation/context/mod.rs 10 mixed plugin evaluation refusal_late author-facing: glob invalid, unsupported need, input kind, metadata path, workspace; internal: Build, Store wrappers +candler_core::evaluation::context::ContextError crates/candler-core/src/evaluation/context/mod.rs 11 mixed plugin evaluation refusal_late author-facing: glob invalid, unsupported need, input kind, metadata path, workspace; internal: Build, Store wrappers candler_core::evaluation::engine::EvaluateError crates/candler-core/src/evaluation/engine/mod.rs 9 mixed plugin evaluation refusal_late author-facing: env not ready, Registry, suite invalid, run glob, Plan, plug-in; internal: Task; transparent Store candler_core::evaluation::engine::plan::PlanError crates/candler-core/src/evaluation/engine/plan.rs 3 yes suite evaluation refusal_late suite dependency cycle, unknown dependency candler_core::evaluation::registry::RegistryError crates/candler-core/src/evaluation/registry/mod.rs 13 yes plugin evaluation refusal_late plug-in manifest, evaluator, kind, params, no state home diff --git a/crates/candler-core/src/evaluation/context/assemble.rs b/crates/candler-core/src/evaluation/context/assemble.rs index 4a64b0ac..877ffa43 100644 --- a/crates/candler-core/src/evaluation/context/assemble.rs +++ b/crates/candler-core/src/evaluation/context/assemble.rs @@ -1,38 +1,62 @@ //! Step one of a context: choosing a run's artifacts and metadata from the needs of a suite. use std::collections::BTreeMap; +use std::io; use std::path::{Path, PathBuf}; +use std::str::FromStr as _; use candler_schemas::evaluation::Needs; use candler_schemas::execution::{ DigestRef, InputEntry, RunManifest, TreeEntry, input_list_digest, }; use candler_schemas::primitives::{Digest, FieldPath, Name, RelPath, RunKey}; +use candler_schemas::raw::StreamName; use candler_schemas::values::JsonValue; use super::ContextError; use super::rule::FileRule; use crate::store::Store; +use crate::store::blob::digest_of_file; -/// One artifact chosen for a context: its path below `outputs/`, the digest the store records -/// for its blob, where the blob lies and whether the file had an execute bit. +/// What a stored file is in the context it is served in. #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] -pub struct AssembledArtifact { - /// The path relative to `outputs/`, with `/` separators. - pub path: RelPath, - /// The digest the store records for the file's bytes. +pub enum Served { + /// An artifact, named by its path relative to `outputs/`. + Artifact(RelPath), + /// A file of an input, whose kind is named. + Input(Name), + /// The run's normalised trace, `trace.jsonl`. + Trace, + /// One raw stream of the run, `raw/.jsonl.gz`. + Raw(StreamName), + /// The run's manifest, `manifest.json`. + Manifest, +} + +/// One stored file chosen for a context: where it lies in the store, where its copy goes below +/// the workspace, the digest its copy must have and what it is served as. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct AssembledFile { + /// The stored file. It is only read, never exposed to a plug-in. + pub source: PathBuf, + /// The path of the copy relative to the workspace, with `/` separators. + pub workspace: RelPath, + /// The digest the bytes of the file have: the store's record for a blob, the hash taken when + /// the file was chosen for any other file. pub sha256: Digest, - /// The blob in the store. It is only read, never exposed to a plug-in. - pub blob: PathBuf, /// Whether the stored file had an execute bit. pub executable: bool, + /// What the file is served as. + pub served: Served, } /// The kind of the input list the image step derives. It is the image's, never an evaluator's. const RESERVED_INPUT_KIND: &str = "build_inputs"; -/// One input an evaluator needs: its kind, its digest and the stored blob of each of its files. +/// One input an evaluator needs: its kind and its digest. Its files are among +/// [`Assembled::files`], served as [`Served::Input`]. #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub struct AssembledInput { @@ -40,17 +64,15 @@ pub struct AssembledInput { pub kind: Name, /// The digest of the input, the key of its list blob. pub digest: Digest, - /// The files of the input, sorted by path relative to the input's root. - pub files: Vec, } -/// The artifacts and the metadata the needs chose for one run, before anything is copied. +/// The files and the metadata the needs chose for one run, before anything is copied. #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] pub struct Assembled { run: RunKey, store_root: PathBuf, - artifacts: Vec, + files: Vec, inputs: Vec, metadata: BTreeMap, } @@ -68,11 +90,13 @@ impl Assembled { self.store_root.as_path() } - /// The chosen artifacts, sorted by path. + /// Every stored file the context serves, in the order they are copied: the artifacts sorted + /// by path, the files of each input in the order of the needs, then the trace, the raw + /// streams sorted by name and the manifest. #[must_use] - pub const fn artifacts<'a>(&'a self) -> &'a [AssembledArtifact] { + pub const fn files<'a>(&'a self) -> &'a [AssembledFile] { // BORROW: .as_slice() views the owned list - self.artifacts.as_slice() + self.files.as_slice() } /// The inputs, one per input need, in the order of the needs. @@ -89,22 +113,29 @@ impl Assembled { } } -/// Chooses the artifacts and metadata of the sealed run `run` that `needs` name. +/// Chooses the stored files and the metadata of the sealed run `run` that `needs` name. /// -/// The artifacts are the files of the run's stored `outputs/` that the file rule keeps for the -/// artifact globs, by path relative to `outputs/`. There is one metadata entry per metadata -/// need, keyed by the dotted path, holding the JSON leaf of the manifest's `comparable.values`. -/// There is one input per input need: the kind is looked up in the manifest's `comparable.inputs` -/// and then in its `evaluation_inputs`, and the files are those of the input's list blob. The -/// trace need is not served in this version, and the context carries none. An `outputs/` -/// with no files gives no artifacts and is not an error. +/// A context serves exactly what the needs declare. The artifacts are the files of the run's +/// stored `outputs/` that the file rule keeps for the artifact globs, by path relative to +/// `outputs/`. There is one metadata entry per metadata need, keyed by the dotted path, holding +/// the JSON leaf of the manifest's `comparable.values`. There is one input per input need: the +/// kind is looked up in the manifest's `comparable.inputs` and then in its `evaluation_inputs`, +/// and the files are those of the input's list blob. The trace need serves the stored +/// `trace.jsonl`, the raw need serves every stored `raw/.jsonl.gz`, and the manifest need +/// serves the stored `manifest.json`; each is hashed once here, and its copy is checked against +/// that hash. A need the run cannot meet is refused and is never served empty: a trace or raw +/// need on a run that stores none, an input the run lacks, a metadata path with no value, and +/// snapshots. A run holds its manifest from the moment its directory exists, so that need has no +/// refusal of its own. An `outputs/` with no files gives no artifacts and is not an error. /// /// # Errors /// Returns [`ContextError::Unsupported`] when the needs ask for snapshots, /// [`ContextError::InputRefused`] when an input need names the reserved kind `build_inputs`, a /// kind the manifest holds in neither list, or a kind whose list or file blobs the store lacks, -/// [`ContextError::NotSealed`] when the run has no seal, [`ContextError::Glob`] for a bad glob, -/// [`ContextError::Store`] when the manifest or tree cannot be read, and +/// [`ContextError::PartMissing`] when the trace or the raw streams are needed and the run stores +/// none, [`ContextError::NotSealed`] when the run has no seal, [`ContextError::Glob`] for a bad +/// glob, [`ContextError::Store`] when the manifest or tree cannot be read, +/// [`ContextError::Io`] when a stored file cannot be read, and /// [`ContextError::MissingMetadata`] when a metadata path has no value in the manifest. pub fn assemble(store: &Store, run: &RunKey, needs: &Needs) -> Result { if !needs.snapshots.is_empty() { @@ -130,15 +161,17 @@ pub fn assemble(store: &Store, run: &RunKey, needs: &Needs) -> Result Result Result { + stored_path(&format!("{dir}/{name}")) +} + +/// `text` as a path relative to the workspace. +fn stored_path(text: &str) -> Result { + RelPath::from_str(text).map_err(|_| ContextError::Workspace { + path: PathBuf::from(text), + detail: "is not a relative path", + }) +} + +/// A stored file that has no digest on record: its hash is taken here, once, and its copy is +/// checked against it. +fn stored_file( + source: PathBuf, + workspace: &str, + served: Served, +) -> Result { + let sha256 = digest_of_file(&source)?; + Ok(AssembledFile { + source, + workspace: stored_path(workspace)?, + sha256, + executable: false, + served, + }) +} + +/// The suffix of a stored raw stream's file name. +const RAW_SUFFIX: &str = ".jsonl.gz"; + +/// The streams the run stores below `raw/`, sorted by name. A file whose name is not +/// `.jsonl.gz` is not a stream. +fn stored_streams(store: &Store, run: &RunKey) -> Result, ContextError> { + let dir = store.layout().raw_dir(run); + let listing = match std::fs::read_dir(&dir) { + Ok(listing) => listing, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(source) => { + return Err(ContextError::Io { + op: "list the raw streams", + path: dir, + source, + }); + } + }; + let mut streams = Vec::new(); + for entry in listing { + let entry = entry.map_err(|source| ContextError::Io { + op: "list the raw streams", + path: dir.clone(), // BORROW: the error owns the path + source, + })?; + if let Some(name) = entry.file_name().to_str() + && let Some(stem) = name.strip_suffix(RAW_SUFFIX) + && let Ok(stream) = StreamName::from_str(stem) + { + streams.push(stream); + } + } + streams.sort(); + Ok(streams) +} + /// The entry of `kind` in a manifest list of inputs. fn held<'a>(list: &'a [DigestRef], kind: &Name) -> Option<&'a DigestRef> { list.iter().find(|entry| &entry.kind == kind) } -/// The input of `kind` that `manifest` holds, with the stored blob of each of its files. +/// The input of `kind` that `manifest` holds, and the stored blob of each of its files. fn assemble_input( store: &Store, manifest: &RunManifest, kind: &Name, -) -> Result { +) -> Result<(AssembledInput, Vec), ContextError> { let refuse = |reason: String| ContextError::InputRefused { kind: kind.to_string(), reason, @@ -224,17 +350,19 @@ fn assemble_input( if !blob.is_file() { return Err(refuse(format!("lacks the blob of `{}`", entry.path))); } - files.push(AssembledArtifact { - path: entry.path.clone(), // BORROW: the result owns its paths + files.push(AssembledFile { + source: blob, + // BORROW: explicit .as_str() + workspace: below(&format!("inputs/{}", kind.as_str()), entry.path.as_str())?, sha256: entry.sha256.clone(), // BORROW: the result owns its digests - blob, executable: false, + served: Served::Input(kind.clone()), // BORROW: the result owns the kind }); } - files.sort_by(|a, b| a.path.cmp(&b.path)); - Ok(AssembledInput { + files.sort_by(|a, b| a.workspace.cmp(&b.workspace)); + let input = AssembledInput { kind: kind.clone(), // BORROW: the result owns the kind digest, - files, - }) + }; + Ok((input, files)) } diff --git a/crates/candler-core/src/evaluation/context/materialise.rs b/crates/candler-core/src/evaluation/context/materialise.rs index 177d97c4..88626ea1 100644 --- a/crates/candler-core/src/evaluation/context/materialise.rs +++ b/crates/candler-core/src/evaluation/context/materialise.rs @@ -1,14 +1,15 @@ -//! Step two of a context: private copies of the artifacts, and the digest of what was written. +//! Step two of a context: private copies of the chosen stored files, and the digest of what was written. use std::fs::{self, OpenOptions, Permissions}; use std::io; use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _}; use std::path::{Path, PathBuf}; -use candler_schemas::evaluation::{ContextArtifact, ContextRef, RunContext}; +use candler_schemas::evaluation::{ContextArtifact, ContextRaw, ContextRef, RunContext}; +use candler_schemas::primitives::Digest; use super::ContextError; -use super::assemble::{Assembled, AssembledArtifact}; +use super::assemble::{Assembled, AssembledFile, Served}; use crate::store::blob::digest_of_file; /// Wraps a failed call on `path` as a [`ContextError::Io`] of `op`. @@ -111,40 +112,39 @@ impl Workspace { } } -/// Copies one artifact's blob to a new file under `outputs`, makes it read-only and returns the -/// digest-checked context entry for it. -fn copy_artifact( - outputs: &Path, - artifact: &AssembledArtifact, -) -> Result { - let target = outputs.join(artifact.path.as_str()); // BORROW: explicit .as_str() +/// Copies the stored file of `file` to its path below `root` as a new file, makes it read-only +/// and returns the absolute path of the copy and the digest it was checked to have. +/// +/// This is the only routine that copies a stored file to a workspace. +fn copy_stored(root: &Path, file: &AssembledFile) -> Result<(String, Digest), ContextError> { + let target = root.join(file.workspace.as_str()); // BORROW: explicit .as_str() if let Some(parent) = target.parent() { - fs::create_dir_all(parent).map_err(io_error("create an artifact directory", parent))?; + fs::create_dir_all(parent).map_err(io_error("create a served directory", parent))?; } let mut source = - fs::File::open(&artifact.blob).map_err(io_error("open a blob", &artifact.blob))?; + fs::File::open(&file.source).map_err(io_error("open a stored file", &file.source))?; // `create_new` refuses an existing name, a dangling link included, so the copy is a new inode. let mut copy = OpenOptions::new() .write(true) .create_new(true) .mode(WRITING) .open(&target) - .map_err(io_error("create an artifact copy", &target))?; - io::copy(&mut source, &mut copy).map_err(io_error("copy an artifact", &target))?; + .map_err(io_error("create a served copy", &target))?; + io::copy(&mut source, &mut copy).map_err(io_error("copy a stored file", &target))?; // The copy is scratch for one request and is removed after it, so it is never synced. drop(copy); - let mode = if artifact.executable { + let mode = if file.executable { READ_ONLY_EXEC } else { READ_ONLY }; fs::set_permissions(&target, Permissions::from_mode(mode)) - .map_err(io_error("make an artifact read-only", &target))?; + .map_err(io_error("make a served copy read-only", &target))?; let written = digest_of_file(&target)?; - if written != artifact.sha256 { + if written != file.sha256 { return Err(ContextError::CorruptBlob { - path: artifact.path.to_string(), - expected: artifact.sha256.to_string(), + path: file.workspace.to_string(), + expected: file.sha256.to_string(), actual: written.to_string(), }); } @@ -155,18 +155,20 @@ fn copy_artifact( detail: "is not valid UTF-8", })? .to_owned(); // BORROW: the context owns its path text - Ok(ContextArtifact::new(artifact.path.clone(), abs, written)) // BORROW: the context owns the path + Ok((abs, written)) } -/// Copies the assembled artifacts into `/outputs/` and the files of each assembled -/// input into `/inputs//`, and builds the run's context from the files as -/// written. An input's entry in the context holds the directory of its tree and the digest of its -/// list; each file is checked against the digest of its blob. +/// Copies every assembled file into the workspace and builds the run's context from the files as +/// written: the artifacts below `/outputs/`, the files of each input below +/// `/inputs//`, the trace as `/trace.jsonl`, each raw stream as +/// `/raw/.jsonl.gz` and the manifest as `/manifest.json`. An +/// input's entry in the context holds the directory of its tree and the digest of its list; every +/// file is checked against the digest recorded when it was assembled. /// -/// Each file is a fresh copy, never a hard link or a symbolic link to a store blob, and is made +/// Each file is a fresh copy, never a hard link or a symbolic link to a stored file, and is made /// read-only once written. The digest of the context is computed from the hash of each written -/// file, and a file whose hash differs from the store's record is an error. `workspace` must be -/// an absolute directory outside the store whose `outputs/` does not exist; its removal is the +/// file, and a file whose hash differs from the record is an error. `workspace` must be an +/// absolute directory outside the store whose `outputs/` does not exist; its removal is the /// engine's job. /// /// # Errors @@ -175,7 +177,6 @@ fn copy_artifact( /// [`ContextError::Build`] when the context cannot be built. pub fn materialise(assembled: &Assembled, workspace: &Path) -> Result { let space = Workspace::prepare(workspace, assembled.store_root())?; - let outputs = space.outputs_dir(); let root = space .root() .to_str() @@ -187,15 +188,26 @@ pub fn materialise(assembled: &Assembled, workspace: &Path) -> Result { + // BORROW: the context owns its paths + builder.artifact(ContextArtifact::new(path.clone(), abs, digest)) + } + Served::Input(_) => builder, + Served::Trace => { + builder.trace(ContextArtifact::new(file.workspace.clone(), abs, digest)) + } + Served::Raw(stream) => builder.raw(ContextRaw::new(stream.clone(), abs, digest)), + Served::Manifest => { + builder.manifest(ContextArtifact::new(file.workspace.clone(), abs, digest)) + } + }; } let inputs = space.root().join("inputs"); for input in assembled.inputs() { let tree = inputs.join(input.kind.as_str()); // BORROW: explicit .as_str() - for file in &input.files { - copy_artifact(&tree, file)?; - } let abs = tree .to_str() .ok_or_else(|| ContextError::Workspace { diff --git a/crates/candler-core/src/evaluation/context/mod.rs b/crates/candler-core/src/evaluation/context/mod.rs index 0376cff3..b017930a 100644 --- a/crates/candler-core/src/evaluation/context/mod.rs +++ b/crates/candler-core/src/evaluation/context/mod.rs @@ -1,7 +1,8 @@ -//! The context of one run for one request: its assembly from a suite's needs in [`assemble()`] -//! the one file rule in `rule`, and the private workspace that copies the artifacts and the -//! digest of what was copied in [`materialise()`]. The inputs a need names are copied below -//! `inputs//` of the same workspace. +//! The context of one run for one request: its assembly from a suite's needs in [`assemble()`], +//! the one file rule in `rule`, and the private workspace that copies the chosen stored files and +//! the digest of what was copied in [`materialise()`]. The artifacts are copied below `outputs/`, +//! the files of each input below `inputs//`, the trace to `trace.jsonl`, the raw streams to +//! `raw/.jsonl.gz` and the manifest to `manifest.json` of the same workspace. use std::io; use std::path::PathBuf; @@ -15,7 +16,7 @@ mod materialise; mod rule; mod union; -pub use assemble::{Assembled, AssembledArtifact, AssembledInput, assemble}; +pub use assemble::{Assembled, AssembledFile, AssembledInput, Served, assemble}; pub use materialise::{Workspace, materialise}; pub use rule::{FileRule, file_rule_keeps}; pub use union::union_needs; @@ -55,6 +56,12 @@ pub enum ContextError { /// Why the run cannot serve it. reason: String, }, + /// A need names a part of the run that the run does not store: its trace or its raw streams. + #[error("the run stores no `{part}`")] + PartMissing { + /// The part, `trace` or `raw`. + part: &'static str, + }, /// A metadata need names a path the run manifest does not hold with a value. #[error("metadata path `{path}` {detail}")] MissingMetadata { @@ -86,7 +93,7 @@ pub enum ContextError { "the blob of `{path}` is corrupt: the store records {expected} and the copy is {actual}" )] CorruptBlob { - /// The artifact path relative to `outputs/`. + /// The path of the copy relative to the workspace. path: String, /// The digest the store records. expected: String, diff --git a/crates/candler-core/src/evaluation/context/union.rs b/crates/candler-core/src/evaluation/context/union.rs index dac45a56..60478907 100644 --- a/crates/candler-core/src/evaluation/context/union.rs +++ b/crates/candler-core/src/evaluation/context/union.rs @@ -12,6 +12,8 @@ where let mut union = Needs::default(); for more in kinds { union.trace |= more.trace; + union.raw |= more.raw; + union.manifest |= more.manifest; for artifact in &more.artifacts { if !union.artifacts.contains(artifact) { union.artifacts.push(artifact.clone()); // BORROW: the union owns its globs diff --git a/crates/candler-core/src/evaluation/refusal.rs b/crates/candler-core/src/evaluation/refusal.rs index 4a875a9b..4738da5d 100644 --- a/crates/candler-core/src/evaluation/refusal.rs +++ b/crates/candler-core/src/evaluation/refusal.rs @@ -38,6 +38,7 @@ fn context_error_path(error: &ContextError) -> Option { | ContextError::Glob { .. } | ContextError::Unsupported { .. } | ContextError::InputRefused { .. } + | ContextError::PartMissing { .. } | ContextError::MissingMetadata { .. } | ContextError::Workspace { .. } | ContextError::Io { .. } @@ -151,6 +152,12 @@ wrapper_table! { "A kind needs an input that the run does not hold, that is reserved for the image, or whose list is not in the store.", "-", ), + PartMissing { .. } => row( + "evaluation.run_part_missing", + Side::Plugin, + "A kind needs the trace or the raw streams of a run that stores none, as an imported run whose harness frames the importer could not read.", + "-", + ), MissingMetadata { .. } => row( "evaluation.metadata_missing", Side::Plugin, @@ -423,6 +430,7 @@ fn context_answer(error: &ContextError) -> &dyn Refusal { | ContextError::Glob { .. } | ContextError::Unsupported { .. } | ContextError::InputRefused { .. } + | ContextError::PartMissing { .. } | ContextError::MissingMetadata { .. } | ContextError::Workspace { .. } | ContextError::Io { .. } diff --git a/crates/candler-core/src/evaluation/registry/needs.rs b/crates/candler-core/src/evaluation/registry/needs.rs index 73693958..73e8b504 100644 --- a/crates/candler-core/src/evaluation/registry/needs.rs +++ b/crates/candler-core/src/evaluation/registry/needs.rs @@ -41,9 +41,10 @@ pub enum NeedError { }, } -/// Checks that the core can meet every need in `needs`: the trace and the metadata fields always -/// can; artifact globs must lie under `outputs/`; snapshots are refused and an input need may not name `build_inputs`; whether the run holds -/// the other kinds is checked when a run's context is assembled. +/// Checks that the core can meet every need in `needs`: the trace, the raw streams, the manifest and +/// the metadata fields always can; artifact globs must lie under `outputs/`; snapshots are refused +/// and an input need may not name `build_inputs`. Whether a run holds the trace, the raw streams +/// and the inputs is checked when its context is assembled. pub(super) fn check(needs: &Needs) -> Result<(), NeedError> { if !needs.snapshots.is_empty() { return Err(NeedError::Unsupported { need: "snapshots" }); diff --git a/docs/contract/codes.toml b/docs/contract/codes.toml index 52f5eab0..6bb305c4 100644 --- a/docs/contract/codes.toml +++ b/docs/contract/codes.toml @@ -1049,6 +1049,11 @@ side = "plugin" enum = "ContextError" variant = "InputRefused" +[evaluation."evaluation.run_part_missing"] +side = "plugin" +enum = "ContextError" +variant = "PartMissing" + [evaluation."evaluation.metadata_missing"] side = "plugin" enum = "ContextError" diff --git a/docs/contract/index.md b/docs/contract/index.md index aef0bcdf..f2c26840 100644 --- a/docs/contract/index.md +++ b/docs/contract/index.md @@ -102,6 +102,7 @@ Surfaces that name no page of their own: configuration, resolving, running, isol | `evaluation.metadata_missing` | A kind needs a metadata path that the run manifest does not hold, or holds without a value. | - | plugin | | `evaluation.need_unsupported` | The needs of a kind ask for something this version of Candler does not supply, such as snapshots. | - | plugin | | `evaluation.run_not_sealed` | A run selected for evaluation has no `run.done` seal, so it can still change. | - | environment | +| `evaluation.run_part_missing` | A kind needs the trace or the raw streams of a run that stores none, as an imported run whose harness frames the importer could not read. | - | plugin | | `evaluation.run_selection_invalid` | The selection of runs is not a glob. | - | config | | `evaluation.state_home_unset` | Neither `XDG_STATE_HOME` nor `HOME` is set, so the environments of plug-ins have no home. | - | environment | | `evaluation.suite_changed` | The suite file of an evaluate job changed between the launcher reading it and the supervisor running the job, so the job refuses to grade with another suite. | - | suite | From 385e721019ee820b012744a12cd805aa7b5f0226 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:48:57 +0900 Subject: [PATCH 48/93] reports(evaluation): close the serving of the stored run The leaf report records each guard with its base failing message and each bite's failing message, which parts a sealed run can lack and the producers that decide it, the one copy routine and its call site, and the needs-union change. Co-Authored-By: Claude Sonnet 5.5 --- .../run-context/leaves/serve_context_v0.md | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 __reports__/run-context/leaves/serve_context_v0.md diff --git a/__reports__/run-context/leaves/serve_context_v0.md b/__reports__/run-context/leaves/serve_context_v0.md new file mode 100644 index 00000000..c80477e8 --- /dev/null +++ b/__reports__/run-context/leaves/serve_context_v0.md @@ -0,0 +1,54 @@ +# Leaf report: serve_context (v0) + +Branch `leaf/run-context/serve_context`, cut from `feat/run-context` at `62038d1c`. + +## Spec deviations + +1. **The guards compile on the base through `union_needs`.** The engine's fold of a plug-in's needs was inline in `engine/run.rs::send`. The Step 1 commit moves it, unchanged and still dropping `raw` and `manifest`, into `context::union_needs`, so the serving guard declares each part through the fold the engine calls and fails on an assertion, not on a missing name. Step 2 adds `raw` and `manifest` to it. +2. **`Assembled`'s list carries two fields beyond `(source, workspace path, digest)`**: `executable` (the copy's `0555` or `0444`) and `served` (what the file is: artifact, input file, trace, raw stream, manifest), which `materialise` needs to fill the context from the list. Inputs keep a `(kind, digest)` entry, because an input with no files still has a context entry. +3. **The live vector rows record the stored files' hashes.** The corpus holds neither trace, raw frames as stored nor manifest in the form the store writes, so the generator takes the hash of each stored file from a store folder (`--store`) and records it in the row; `--check` without a store reuses the recorded hashes. The digest, the projection and the key spelling are the generator's. The guard checks each recorded hash against the file the store holds before it compares digests; the import's output was identical across two imports. +4. `docs/contract/index.md` and `__roadmap__/m3-lean-cli/refusal_scope.tsv` changed with the new code (`guard_refusal_codes` reads the tsv: `ContextError` has 11 variants). + +## Guards, each seen red on the base and under its bite + +| Guard | Base failing message | Bite and its failing message | +|---|---|---| +| `kinds_that_declare_the_run_parts_are_served_their_stored_bytes` | `the context serves the trace` (`context.trace()` is `None`) | (a) silent ignore of `needs.trace`: same message. (b) hard link: `assertion left == right failed: the mode of trace.jsonl, left: 420, right: 292` | +| `a_plug_in_cannot_write_through_to_the_store` (extended to trace, raw, manifest) | `chmod u+w: Os { code: 2, kind: NotFound }` (no copy of the trace in the workspace) | hard link: `the store blob of cont-train.json, left: sha256:7e2e..., right: sha256:9e79...` (the write reaches the store) | +| `the_live_context_digest_is_the_independent_vector` (three new `[[served]]` rows; the four existing rows untouched) | `with_skill/run-6 serving ["trace", "raw", "manifest"]`, left `sha256:8048...`, right `sha256:3407...` | (a) `trace` key always added: `with_skill/run-6` fails, left `sha256:b94f...`, right `sha256:8048...` (an existing row). (b) key left out when served: `with_skill/run-6 serving ["trace", "raw", "manifest"]`, left `sha256:492d...`, right `sha256:3407...` | +| `needs_parts_refused_when_the_run_cannot_serve_them` | `a part the run lacks is refused: Assembled { ... files: [] ...}` (served empty) | refusal removed (trace): `assertion left == right failed: trace, left: "store.io_failed", right: "evaluation.run_part_missing"` | +| union (gate 5): the four guards above under `union_needs` dropping `raw` | n/a | `needs_parts_refused...`, `kinds_that_declare...`, `a_plug_in_cannot...` and the live vector fail | + +The hard-link bite also turns `an_imported_executable_materialises_as_a_private_0555_copy` red. Existing guards (`a_corrupt_blob_is_refused_and_not_digested`, the inputs guards, the file rule, `a_workspace_that_contains_the_store_is_refused`) pass unchanged on the tip. The generator's existing output is a byte prefix of the new file. + +## Which parts a sealed run can lack + +| Part | Can a sealed run lack it? | Producer that decides | +|---|---|---| +| manifest | No | `RunWriter::create` writes `manifest.json` before the run directory is renamed into place; `seal` never removes it. `assemble` reads it for the metadata and the input needs, so a missing one is a `Store` error. No guard, no refusal of its own. | +| trace | Yes | `seal_run_observed` writes it before `run.done`, but the importers do not always: `import/raw.rs` seals a run whose reader failed or whose format is unknown with an invalid manifest and no trace, and `import/assemble.rs` (legacy folders) writes none when no reader exists or normalising fails. `seal_interrupted` seals with none. | +| raw | Yes | The runner and both importers store at least one stream, but `seal_interrupted` seals a run that has none, and `seal_run_observed` stores whatever slice it is given. | + +The refusal is `ContextError::PartMissing`, code `evaluation.run_part_missing` (side `plugin`, as for a missing input). The guard seals a run over a manifest alone with the existing `seal_with_inputs` helper (the store's own writer) and writes the code by hand. + +## The one copy routine + +`materialise.rs::copy_stored(root, &AssembledFile) -> (abs path, digest)`: create-new, `0600`, digest check, then `0444` or `0555`. Its one call site is the loop over `Assembled::files()` in `materialise`; artifacts, input files, trace, each raw stream and the manifest are entries of that list. `assemble.rs` builds the list: artifacts from the tree, input files from the list blob, and `stored_file` for the trace, each raw stream and the manifest, which hashes the file once (the store records none for them) and the copy is checked against that hash. + +## The needs union + +`context::union_needs` folds `trace`, `raw` and `manifest` as flags (any kind sets it) and the four lists as before; `engine/run.rs::send` calls it. The serving guard builds its needs from one kind per part through it. `registry/needs.rs::check` meets all three parts by construction, so its doc names them. + +## Ruling + +`__reports__/run-context/01-ruling_trace_served_v0.md` replaces the M2a ruling "trace not served". `assemble.rs`'s doc states what is served and refused. + +## What is left + +- The fresh Sonnet verifier of Step 3 is the coordinator's. +- `container-e2e` runs on the pull request, not here. +- A raw directory entry that is not `.jsonl.gz` is skipped, not refused; a sealed run holds none. + +## Checks on the tip + +`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass. `cargo nextest run --workspace --no-fail-fast`: 737 run, 732 passed. The known failure `guard_harness_facts::harness_census_equals_cf3de30_on_every_fixture` (no baseline for `streams/shell_exit_stderr_timeout`, fixed on its own branch) failed. Four more failed while the machine ran at a load average near 40 (`guard_opencode_driver::opencode_skills_land_in_the_project_skill_directory`, `guard_container_stop::stop_asks_the_daemon_and_falls_back_to_the_client`, `guard_claude_code_driver::b22_skill_tree_is_the_tag`, `guard_container_record::stopped_run_has_its_agent_recorded_before_the_hook_sweeps`); run alone, all four pass. From 06b43a8e99dbe6c4f829eb81f4fc6e066902dc5b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:58:58 +0900 Subject: [PATCH 49/93] fix(evaluation): copy stored parts by handle, name the file at fault - copy_stored sets the final mode on the open handle, so no window follows a swapped name. - A digest mismatch names the stored source file and says what is true for blobs and for the trace, raw streams and manifest alike. - PartMissing carries the run and a RunPart; assemble refuses a missing part only on NotFound and reports any other I/O error as such. - Drop the payload of Served::Input and the path text built for input files; the docs say the parts are hashed at assembly. Co-Authored-By: Claude Sonnet 5.5 --- .../src/evaluation/context/assemble.rs | 44 +++++++--- .../src/evaluation/context/materialise.rs | 81 ++++++++++--------- .../src/evaluation/context/mod.rs | 42 ++++++++-- crates/candler-core/src/evaluation/refusal.rs | 2 +- docs/contract/index.md | 2 +- 5 files changed, 108 insertions(+), 63 deletions(-) diff --git a/crates/candler-core/src/evaluation/context/assemble.rs b/crates/candler-core/src/evaluation/context/assemble.rs index 877ffa43..4f9d9218 100644 --- a/crates/candler-core/src/evaluation/context/assemble.rs +++ b/crates/candler-core/src/evaluation/context/assemble.rs @@ -13,8 +13,8 @@ use candler_schemas::primitives::{Digest, FieldPath, Name, RelPath, RunKey}; use candler_schemas::raw::StreamName; use candler_schemas::values::JsonValue; -use super::ContextError; use super::rule::FileRule; +use super::{ContextError, RunPart}; use crate::store::Store; use crate::store::blob::digest_of_file; @@ -24,8 +24,8 @@ use crate::store::blob::digest_of_file; pub enum Served { /// An artifact, named by its path relative to `outputs/`. Artifact(RelPath), - /// A file of an input, whose kind is named. - Input(Name), + /// A file of an input; the kind is the directory it lies in. + Input, /// The run's normalised trace, `trace.jsonl`. Trace, /// One raw stream of the run, `raw/.jsonl.gz`. @@ -115,16 +115,18 @@ impl Assembled { /// Chooses the stored files and the metadata of the sealed run `run` that `needs` name. /// -/// A context serves exactly what the needs declare. The artifacts are the files of the run's +/// A context serves exactly what the needs declare. The engine builds one context per plug-in +/// request from the union of its kinds' needs, so what a plug-in is served is what any of its +/// kinds declares in `describe`. The artifacts are the files of the run's /// stored `outputs/` that the file rule keeps for the artifact globs, by path relative to /// `outputs/`. There is one metadata entry per metadata need, keyed by the dotted path, holding /// the JSON leaf of the manifest's `comparable.values`. There is one input per input need: the /// kind is looked up in the manifest's `comparable.inputs` and then in its `evaluation_inputs`, /// and the files are those of the input's list blob. The trace need serves the stored /// `trace.jsonl`, the raw need serves every stored `raw/.jsonl.gz`, and the manifest need -/// serves the stored `manifest.json`; each is hashed once here, and its copy is checked against -/// that hash. A need the run cannot meet is refused and is never served empty: a trace or raw -/// need on a run that stores none, an input the run lacks, a metadata path with no value, and +/// serves the stored `manifest.json`; each is hashed here, at assembly, and its copy is checked +/// against that hash. A need the run cannot meet is refused and is never served empty: a trace or +/// raw need on a run that stores none, an input the run lacks, a metadata path with no value, and /// snapshots. A run holds its manifest from the moment its directory exists, so that need has no /// refusal of its own. An `outputs/` with no files gives no artifacts and is not an error. /// @@ -198,15 +200,31 @@ pub fn assemble(store: &Store, run: &RunKey, needs: &Needs) -> Result {} + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return Err(ContextError::PartMissing { + run: run.clone(), // BORROW: the error owns the key + part: RunPart::Trace, + }); + } + Err(error) => { + return Err(ContextError::Io { + op: "stat the trace", + path: source, + source: error, + }); + } } files.push(stored_file(source, "trace.jsonl", Served::Trace)?); } if needs.raw { let streams = stored_streams(store, run)?; if streams.is_empty() { - return Err(ContextError::PartMissing { part: "raw" }); + return Err(ContextError::PartMissing { + run: run.clone(), // BORROW: the error owns the key + part: RunPart::Raw, + }); } for stream in streams { let source = layout.raw(run, &stream); @@ -243,8 +261,8 @@ fn stored_path(text: &str) -> Result { }) } -/// A stored file that has no digest on record: its hash is taken here, once, and its copy is -/// checked against it. +/// A stored file that has no digest on record: its hash is taken here, at assembly, and its copy +/// is checked against it. fn stored_file( source: PathBuf, workspace: &str, @@ -356,7 +374,7 @@ fn assemble_input( workspace: below(&format!("inputs/{}", kind.as_str()), entry.path.as_str())?, sha256: entry.sha256.clone(), // BORROW: the result owns its digests executable: false, - served: Served::Input(kind.clone()), // BORROW: the result owns the kind + served: Served::Input, }); } files.sort_by(|a, b| a.workspace.cmp(&b.workspace)); diff --git a/crates/candler-core/src/evaluation/context/materialise.rs b/crates/candler-core/src/evaluation/context/materialise.rs index 88626ea1..a4b9b340 100644 --- a/crates/candler-core/src/evaluation/context/materialise.rs +++ b/crates/candler-core/src/evaluation/context/materialise.rs @@ -1,4 +1,5 @@ -//! Step two of a context: private copies of the chosen stored files, and the digest of what was written. +//! Step two of a context: private copies of the chosen stored files, and the digest of what was +//! written. use std::fs::{self, OpenOptions, Permissions}; use std::io; @@ -113,10 +114,10 @@ impl Workspace { } /// Copies the stored file of `file` to its path below `root` as a new file, makes it read-only -/// and returns the absolute path of the copy and the digest it was checked to have. +/// and returns the path of the copy and the digest it was checked to have. /// /// This is the only routine that copies a stored file to a workspace. -fn copy_stored(root: &Path, file: &AssembledFile) -> Result<(String, Digest), ContextError> { +fn copy_stored(root: &Path, file: &AssembledFile) -> Result<(PathBuf, Digest), ContextError> { let target = root.join(file.workspace.as_str()); // BORROW: explicit .as_str() if let Some(parent) = target.parent() { fs::create_dir_all(parent).map_err(io_error("create a served directory", parent))?; @@ -131,31 +132,35 @@ fn copy_stored(root: &Path, file: &AssembledFile) -> Result<(String, Digest), Co .open(&target) .map_err(io_error("create a served copy", &target))?; io::copy(&mut source, &mut copy).map_err(io_error("copy a stored file", &target))?; - // The copy is scratch for one request and is removed after it, so it is never synced. - drop(copy); let mode = if file.executable { READ_ONLY_EXEC } else { READ_ONLY }; - fs::set_permissions(&target, Permissions::from_mode(mode)) + // The mode is set on the open handle, so no name that was swapped in meanwhile is changed. + copy.set_permissions(Permissions::from_mode(mode)) .map_err(io_error("make a served copy read-only", &target))?; + // The copy is scratch for one request and is removed after it, so it is never synced. + drop(copy); let written = digest_of_file(&target)?; if written != file.sha256 { return Err(ContextError::CorruptBlob { - path: file.workspace.to_string(), + stored: file.source.clone(), // BORROW: the error owns the path expected: file.sha256.to_string(), actual: written.to_string(), }); } - let abs = target - .to_str() + Ok((target, written)) +} + +/// `path` as the text the context carries. +fn text_of(path: &Path) -> Result { + path.to_str() + .map(str::to_owned) // BORROW: the context owns its path text .ok_or_else(|| ContextError::Workspace { - path: target.clone(), // BORROW: the error owns the path + path: path.to_path_buf(), detail: "is not valid UTF-8", - })? - .to_owned(); // BORROW: the context owns its path text - Ok((abs, written)) + }) } /// Copies every assembled file into the workspace and builds the run's context from the files as @@ -163,7 +168,8 @@ fn copy_stored(root: &Path, file: &AssembledFile) -> Result<(String, Digest), Co /// `/inputs//`, the trace as `/trace.jsonl`, each raw stream as /// `/raw/.jsonl.gz` and the manifest as `/manifest.json`. An /// input's entry in the context holds the directory of its tree and the digest of its list; every -/// file is checked against the digest recorded when it was assembled. +/// file is checked against the digest recorded when it was assembled: the store's record for a +/// blob, the hash taken at assembly for the trace, a raw stream or the manifest. /// /// Each file is a fresh copy, never a hard link or a symbolic link to a stored file, and is made /// read-only once written. The digest of the context is computed from the hash of each written @@ -177,47 +183,42 @@ fn copy_stored(root: &Path, file: &AssembledFile) -> Result<(String, Digest), Co /// [`ContextError::Build`] when the context cannot be built. pub fn materialise(assembled: &Assembled, workspace: &Path) -> Result { let space = Workspace::prepare(workspace, assembled.store_root())?; - let root = space - .root() - .to_str() - .ok_or_else(|| ContextError::Workspace { - path: space.root().to_path_buf(), // BORROW: the error owns the path - detail: "is not valid UTF-8", - })? - .to_owned(); // BORROW: the context owns its root text + let root = text_of(space.root())?; let mut builder = RunContext::builder() .run(assembled.run().clone()) // BORROW: the context owns the key .root(root); for file in assembled.files() { - let (abs, digest) = copy_stored(space.root(), file)?; + let (copy, digest) = copy_stored(space.root(), file)?; builder = match &file.served { + // An input's files are served through the directory of its tree, below. + Served::Input => builder, Served::Artifact(path) => { // BORROW: the context owns its paths - builder.artifact(ContextArtifact::new(path.clone(), abs, digest)) - } - Served::Input(_) => builder, - Served::Trace => { - builder.trace(ContextArtifact::new(file.workspace.clone(), abs, digest)) - } - Served::Raw(stream) => builder.raw(ContextRaw::new(stream.clone(), abs, digest)), - Served::Manifest => { - builder.manifest(ContextArtifact::new(file.workspace.clone(), abs, digest)) + builder.artifact(ContextArtifact::new(path.clone(), text_of(©)?, digest)) } + Served::Trace => builder.trace(ContextArtifact::new( + file.workspace.clone(), // BORROW: the context owns its paths + text_of(©)?, + digest, + )), + Served::Raw(stream) => builder.raw(ContextRaw::new( + stream.clone(), // BORROW: the context owns its streams + text_of(©)?, + digest, + )), + Served::Manifest => builder.manifest(ContextArtifact::new( + file.workspace.clone(), // BORROW: the context owns its paths + text_of(©)?, + digest, + )), }; } let inputs = space.root().join("inputs"); for input in assembled.inputs() { let tree = inputs.join(input.kind.as_str()); // BORROW: explicit .as_str() - let abs = tree - .to_str() - .ok_or_else(|| ContextError::Workspace { - path: tree.clone(), // BORROW: the error owns the path - detail: "is not valid UTF-8", - })? - .to_owned(); // BORROW: the context owns its path text builder = builder.input(ContextRef::new( input.kind.clone(), // BORROW: the context owns its kinds - abs, + text_of(&tree)?, input.digest.clone(), // BORROW: the context owns its digests )); } diff --git a/crates/candler-core/src/evaluation/context/mod.rs b/crates/candler-core/src/evaluation/context/mod.rs index b017930a..95537436 100644 --- a/crates/candler-core/src/evaluation/context/mod.rs +++ b/crates/candler-core/src/evaluation/context/mod.rs @@ -4,10 +4,12 @@ //! the files of each input below `inputs//`, the trace to `trace.jsonl`, the raw streams to //! `raw/.jsonl.gz` and the manifest to `manifest.json` of the same workspace. +use std::fmt; use std::io; use std::path::PathBuf; use candler_schemas::evaluation::EvaluationError; +use candler_schemas::primitives::RunKey; use crate::store::StoreError; @@ -21,6 +23,25 @@ pub use materialise::{Workspace, materialise}; pub use rule::{FileRule, file_rule_keeps}; pub use union::union_needs; +/// A part of a stored run that a kind may declare and a run may lack. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum RunPart { + /// The normalised trace, `trace.jsonl`. + Trace, + /// The raw streams, `raw/.jsonl.gz`. + Raw, +} + +impl fmt::Display for RunPart { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Trace => "trace", + Self::Raw => "raw", + }) + } +} + /// Why a run's context could not be assembled or materialised. #[derive(Debug, thiserror::Error)] #[non_exhaustive] @@ -57,10 +78,12 @@ pub enum ContextError { reason: String, }, /// A need names a part of the run that the run does not store: its trace or its raw streams. - #[error("the run stores no `{part}`")] + #[error("run {run} stores no `{part}`")] PartMissing { - /// The part, `trace` or `raw`. - part: &'static str, + /// The key of the run. + run: RunKey, + /// The part the run lacks. + part: RunPart, }, /// A metadata need names a path the run manifest does not hold with a value. #[error("metadata path `{path}` {detail}")] @@ -88,14 +111,17 @@ pub enum ContextError { /// The error of the call. source: io::Error, }, - /// A copied file does not have the digest the store records for its blob. + /// A copy of a stored file does not have the digest recorded for it: the store's record for + /// a blob, the hash taken at assembly for the trace, a raw stream or the manifest. #[error( - "the blob of `{path}` is corrupt: the store records {expected} and the copy is {actual}" + "the stored file {} no longer has the digest recorded for it: \ + expected {expected}, its copy is {actual}", + stored.display() )] CorruptBlob { - /// The path of the copy relative to the workspace. - path: String, - /// The digest the store records. + /// The stored file that was copied. + stored: PathBuf, + /// The digest recorded for it. expected: String, /// The digest of the copy. actual: String, diff --git a/crates/candler-core/src/evaluation/refusal.rs b/crates/candler-core/src/evaluation/refusal.rs index 4738da5d..1102ffab 100644 --- a/crates/candler-core/src/evaluation/refusal.rs +++ b/crates/candler-core/src/evaluation/refusal.rs @@ -179,7 +179,7 @@ wrapper_table! { CorruptBlob { .. } => row( "evaluation.blob_corrupt", Side::Environment, - "A blob of the store does not have the digest the store records for it.", + "A stored file of a run does not have the digest recorded for it: a blob of the store, or the trace, a raw stream or the manifest.", "-", ), Build (..) => row( diff --git a/docs/contract/index.md b/docs/contract/index.md index f2c26840..70734707 100644 --- a/docs/contract/index.md +++ b/docs/contract/index.md @@ -90,7 +90,7 @@ Surfaces that name no page of their own: configuration, resolving, running, isol | `config.upstream_ca_invalid` | `gateway.upstream_ca` names a file that cannot be read or holds no PEM certificate. | The `gateway.upstream_ca` key in the user configuration file named in the message. | config | | `config.wrong_type` | A configuration key holds a value of the wrong type. | The key in the configuration file named in the message. | config | | `evaluation.artifact_glob_invalid` | An artifact glob in the needs of a kind is not a glob. | - | plugin | -| `evaluation.blob_corrupt` | A blob of the store does not have the digest the store records for it. | - | environment | +| `evaluation.blob_corrupt` | A stored file of a run does not have the digest recorded for it: a blob of the store, or the trace, a raw stream or the manifest. | - | environment | | `evaluation.cancelled` | The caller cancelled the request, for example by stopping the job; nothing is committed for it. | - | environment | | `evaluation.context_io_failed` | A file system call failed while the run's files were materialised for an evaluator. | - | environment | | `evaluation.dependency_cycle` | Entries of the suite depend on each other in a loop, so no order of requests serves them. | - | suite | From 95c0c379bca9ad8427d97782fb248ced2098c5a2 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:58:58 +0900 Subject: [PATCH 50/93] test(evaluation): guard a stored trace changed after assembly - The corrupt-blob guard also refuses a stored trace that changed between assemble and materialise, naming the stored file. - The serving guard compares the manifest copy's hash with the stored manifest, and the vector guard checks that the rows cover every part instead of counting them. - The part-missing refusal names the run. Co-Authored-By: Claude Sonnet 5.5 --- .../tests/it/guard_run_context.rs | 49 +++++++++++++++---- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/crates/candler-core/tests/it/guard_run_context.rs b/crates/candler-core/tests/it/guard_run_context.rs index cd9de015..d479ec80 100644 --- a/crates/candler-core/tests/it/guard_run_context.rs +++ b/crates/candler-core/tests/it/guard_run_context.rs @@ -231,7 +231,7 @@ fn kinds_that_declare_the_run_parts_are_served_their_stored_bytes() { ); } -/// Guards: R9 — the digest of a materialised live context equals the independent vector of the run's raw `outputs/` files and `experiment.json`, and a twin whose `domain.py` differs by one byte has the vector of the twin, which is not the original's. and a context that also serves the trace, the raw streams or the manifest has the vector of its `[[served]]` row, whose recorded hashes equal the hashes of the files the store holds. Oracle: `live_context_runs.toml`, written by `gen_live_context.py` with python `rfc8785` from the raw corpus and the stored files' hashes. +/// Guards: R9 — the digest of a materialised live context equals the independent vector of the run's raw `outputs/` files and `experiment.json`, and a twin whose `domain.py` differs by one byte has the vector of the twin, which is not the original's, and a context that also serves the trace, the raw streams or the manifest has the vector of its `[[served]]` row, whose recorded hashes equal the hashes of the files the store holds. Oracle: `live_context_runs.toml`, written by `gen_live_context.py` with python `rfc8785` from the raw corpus and the stored files' hashes. #[test] fn the_live_context_digest_is_the_independent_vector() { let vectors = live_vectors(); @@ -300,7 +300,16 @@ fn the_live_context_digest_is_the_independent_vector() { let vectors = toml::Value::Table(vectors); let served = tables_at(&vectors, "served"); - assert_eq!(served.len(), 3, "vector rows that serve parts"); + let mut declared: Vec<&str> = Vec::new(); + for vector in served { + declared.extend(tables_at_str(vector, "needs")); + } + for part in ["trace", "raw", "manifest"] { + assert!( + declared.contains(&part), + "the vector rows serve the {part} in some row" + ); + } for vector in served { let run = text_at(vector, "run"); let parts: Vec<&str> = tables_at_str(vector, "needs"); @@ -435,7 +444,7 @@ fn a_plug_in_cannot_write_through_to_the_store() { } } -/// Guards: R9 — the digest of a materialised context is taken from the bytes written to the workspace, and a store blob that no longer holds the bytes of its recorded sha256 is refused with `CorruptBlob` and no context. Oracle: a blob of the store overwritten here with other bytes, so the recorded sha256 and the written bytes differ. +/// Guards: R9 — the digest of a materialised context is taken from the bytes written to the workspace, and a store blob that no longer holds the bytes of its recorded sha256, or a stored trace that changed between `assemble` and `materialise`, is refused with `CorruptBlob` naming the stored file, and no context. Oracle: a blob of the store, and the stored trace of another store, each overwritten here with other bytes, so the recorded sha256 and the written bytes differ. #[test] fn a_corrupt_blob_is_refused_and_not_digested() { let (_keep, store) = mini_store(&mini()); @@ -460,8 +469,24 @@ fn a_corrupt_blob_is_refused_and_not_digested() { let assembled = assemble(&store, &run, &parity_needs()).expect("the run assembles"); let outcome = materialise(&assembled, workspace.path()); assert!( - matches!(outcome, Err(ContextError::CorruptBlob { .. })), - "a corrupt blob must be refused, got {outcome:?}" + matches!(&outcome, Err(ContextError::CorruptBlob { stored, .. }) if *stored == blob), + "a corrupt blob must be refused, naming the blob, got {outcome:?}" + ); + + // A stored file with no blob: the hash taken at assembly is the record, and the file changes + // after it. + let (_keep, store) = mini_store(&mini()); + let run = key_of(&store, 6); + let workspace = tempfile::tempdir().expect("a workspace"); + let assembled = + assemble(&store, &run, &needs_declaring(&["trace"])).expect("the run assembles"); + let trace = store.layout().trace(&run); + fs::set_permissions(&trace, fs::Permissions::from_mode(0o644)).expect("chmod u+w"); + fs::write(&trace, b"not the assembled bytes").expect("the trace is overwritten"); + let outcome = materialise(&assembled, workspace.path()); + assert!( + matches!(&outcome, Err(ContextError::CorruptBlob { stored, .. }) if *stored == trace), + "a trace changed after assembly must be refused, naming the trace, got {outcome:?}" ); } @@ -860,7 +885,7 @@ fn needs_inputs_refused_when_the_list_blob_is_not_its_digests_list() { ); } -/// Guards: R01 §Evaluator protocol — a kind that declares the trace, or the raw streams, of a run that stores none of them is refused with the code `evaluation.run_part_missing`, naming the part, and no context is made; the same run serves its manifest. Oracle: hand-written; the parts and the code are the ones written below, and the run is sealed over a manifest alone by the store's own writer. +/// Guards: R01 §Evaluator protocol — a kind that declares the trace, or the raw streams, of a run that stores none of them is refused with the code `evaluation.run_part_missing`, naming the part and the run, and no context is made; the same run serves its manifest. Oracle: hand-written; the parts and the code are the ones written below, and the run is sealed over a manifest alone by the store's own writer. #[test] fn needs_parts_refused_when_the_run_cannot_serve_them() { let (_keep, store) = mini_store(&mini()); @@ -879,8 +904,9 @@ fn needs_parts_refused_when_the_run_cannot_serve_them() { "{part}" ); assert!( - error.to_string().contains(&format!("`{part}`")), - "`{error}` names the part `{part}`" + error.to_string().contains(&format!("`{part}`")) + && error.to_string().contains(&bare.to_string()), + "`{error}` names the part `{part}` and the run" ); } let workspace = tempfile::tempdir().expect("a workspace"); @@ -890,5 +916,10 @@ fn needs_parts_refused_when_the_run_cannot_serve_them() { &needs_declaring(&["manifest"]), workspace.path(), ); - assert!(context.manifest().is_some(), "the manifest is always held"); + let manifest = context.manifest().expect("the manifest is always held"); + assert_eq!( + manifest.sha256, + sha256_of(&fs::read(store.layout().manifest(&bare)).expect("the stored manifest reads")), + "the manifest copy holds the stored manifest's bytes" + ); } From 66fe722aa00b1ae103f3c3ac855a5b292d381c09 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:06:19 +0900 Subject: [PATCH 51/93] reports(evaluation): record the review round of serve_context - The ruling note says a plug-in is served the union of what its kinds declare, and that its kinds share the process. - The leaf report states what holds for non-stream files in raw/, lists the follow-ups, and adds the review round with its evidence. Co-Authored-By: Claude Sonnet 5.5 --- .../run-context/01-ruling_trace_served_v0.md | 9 ++++++--- .../run-context/leaves/serve_context_v0.md | 20 +++++++++++++++++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/__reports__/run-context/01-ruling_trace_served_v0.md b/__reports__/run-context/01-ruling_trace_served_v0.md index b1796083..37bc63cd 100644 --- a/__reports__/run-context/01-ruling_trace_served_v0.md +++ b/__reports__/run-context/01-ruling_trace_served_v0.md @@ -13,9 +13,12 @@ digest. disk" cannot hold while a declared need for the trace is accepted and dropped. AGENTS.md calls a second, more lenient reading of a declaration a defect even when nothing reaches it yet; ignoring a declared need is that reading. -- **The declaration states what a kind sees.** Candler has no blinding concept. A kind lists its - needs in `describe`, Candler serves exactly those and refuses what it cannot serve, so what a kind - saw is on record in the kind itself. Serving the trace adds no hidden channel. +- **The declaration states what a plug-in is served.** Candler has no blinding concept. A kind + lists its needs in `describe`, and the engine builds one context per plug-in request from the + union of its kinds' needs, so what a plug-in is served is the union of what its kinds declare. + A plug-in is one process, so its kinds share what it was served. Candler serves exactly that and + refuses what it cannot serve, so what a plug-in was served is on record in its kinds' + declarations. Serving the trace adds no hidden channel. - **A sealed run never changes.** "Sealed" means complete and protected from overwrite, so the digest taken when a stored file is chosen for a context holds for the whole evaluation, and the outcome-reuse key can carry it. diff --git a/__reports__/run-context/leaves/serve_context_v0.md b/__reports__/run-context/leaves/serve_context_v0.md index c80477e8..8cb526de 100644 --- a/__reports__/run-context/leaves/serve_context_v0.md +++ b/__reports__/run-context/leaves/serve_context_v0.md @@ -33,7 +33,7 @@ The refusal is `ContextError::PartMissing`, code `evaluation.run_part_missing` ( ## The one copy routine -`materialise.rs::copy_stored(root, &AssembledFile) -> (abs path, digest)`: create-new, `0600`, digest check, then `0444` or `0555`. Its one call site is the loop over `Assembled::files()` in `materialise`; artifacts, input files, trace, each raw stream and the manifest are entries of that list. `assemble.rs` builds the list: artifacts from the tree, input files from the list blob, and `stored_file` for the trace, each raw stream and the manifest, which hashes the file once (the store records none for them) and the copy is checked against that hash. +`materialise.rs::copy_stored(root, &AssembledFile) -> (abs path, digest)`: create-new, `0600`, digest check, then `0444` or `0555`. Its one call site is the loop over `Assembled::files()` in `materialise`; artifacts, input files, trace, each raw stream and the manifest are entries of that list. `assemble.rs` builds the list: artifacts from the tree, input files from the list blob, and `stored_file` for the trace, each raw stream and the manifest, which hashes the file at assembly (the store records none for them); the copy is checked against that hash. Each part is read three times: hashed at assembly, copied, and hashed again as written. ## The needs union @@ -47,8 +47,24 @@ The refusal is `ContextError::PartMissing`, code `evaluation.run_part_missing` ( - The fresh Sonnet verifier of Step 3 is the coordinator's. - `container-e2e` runs on the pull request, not here. -- A raw directory entry that is not `.jsonl.gz` is skipped, not refused; a sealed run holds none. +- A raw directory entry that is not `.jsonl.gz` is skipped, not refused. That a sealed run holds none is not proven for an interrupted run. What holds: both producers write only `.jsonl.gz`, and a crash debris name `.tmp-...` fails `StreamName`'s pattern, so it is skipped. +- Directory modes of the workspace stay as they were (writable directories are older than this leaf). Making them read-only once the copies are written is a follow-up. +- The refusal code of a digest mismatch is still `evaluation.blob_corrupt`, though it now also covers the trace, a raw stream and the manifest; renaming a code is left to a decision of its own. ## Checks on the tip `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings` and `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps` pass. `cargo nextest run --workspace --no-fail-fast`: 737 run, 732 passed. The known failure `guard_harness_facts::harness_census_equals_cf3de30_on_every_fixture` (no baseline for `streams/shell_exit_stderr_timeout`, fixed on its own branch) failed. Four more failed while the machine ran at a load average near 40 (`guard_opencode_driver::opencode_skills_land_in_the_project_skill_directory`, `guard_container_stop::stop_asks_the_daemon_and_falls_back_to_the_client`, `guard_claude_code_driver::b22_skill_tree_is_the_tag`, `guard_container_record::stopped_run_has_its_agent_recorded_before_the_hook_sweeps`); run alone, all four pass. + +## Review round + +| Fix | Evidence | +|---|---| +| Mode set on the open handle in `copy_stored` before the handle is dropped; no `fs::set_permissions` by path. | `a_plug_in_cannot_write_through_to_the_store` and `an_imported_executable_materialises_as_a_private_0555_copy` pass. Directory modes left, listed above. | +| Digest mismatch names the stored source path and says "no longer has the digest recorded for it", true for a blob and for a stored part; code unchanged, description in `refusal.rs` and `docs/contract/index.md` widened. | `a_corrupt_blob_is_refused_and_not_digested` now checks the named path for a blob and for a trace changed after `assemble`; `guard_refusal_codes` passes. | +| `PartMissing { run: RunKey, part: RunPart }`, `RunPart` a `#[non_exhaustive]` enum (`Trace`, `Raw`); the text names the run. | `needs_parts_refused_when_the_run_cannot_serve_them` checks the part and the run in the text. | +| `assemble` refuses a missing trace only on `NotFound`; any other error is `ContextError::Io`, as `stored_streams` does. | Read; no guard (a non-`NotFound` error needs a file system fault). | +| `Served::Input` carries no payload; the path text is built only for the parts that the context records; `text_of` is the one conversion. `below` stays: it joins a directory and a name, which `stored_path` does not. | Compiles clean under clippy `-D warnings`. | +| Docs: hashed at assembly, copy checked against that hash; module line wrapped; the broken sentence of the vector guard mended. | `cargo doc` with `-D warnings`. | +| The corrupt-blob guard extended with a stored trace; the manifest copy's hash compared with the stored `manifest.json`; the `3` replaced by a check that the `[[served]]` rows cover trace, raw and manifest. | Red first: with the copy-versus-hash check removed for stored files (scratch branch, deleted), `a_corrupt_blob_is_refused_and_not_digested` failed with `a trace changed after assembly must be refused, naming the trace, got Ok(RunContext { ... })`. | +| Ruling note: a plug-in is served the union of what its kinds declare, and its kinds share the process. | `git grep -n -i "kind saw\|kind sees\|what a kind"` finds none in the files this leaf wrote. | +| Report: the claim about non-stream files in `raw/` replaced by what holds. | Above, "What is left". | From 5fd60ff0d02d1ac65e625c5dbb37557e7ec21ed6 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:07:16 +0900 Subject: [PATCH 52/93] rdm(evaluation): close the serving of the stored run Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/readers/README.md b/__roadmap__/run_context/readers/README.md index 23b26b53..e9ed84d6 100644 --- a/__roadmap__/run_context/readers/README.md +++ b/__roadmap__/run_context/readers/README.md @@ -18,7 +18,7 @@ Both trace readers record the harness's exit status, `assemble`/`materialise` se graph TD cc_reader_exit[Claude Code exit]:::done oc_reader_exit[OpenCode exit]:::done - serve_context[Serve the run]:::inprogress + serve_context[Serve the run]:::done helper_context[Helper context]:::inprogress e2e[Consumer path]:::planned classDef done fill:#166534,color:#bbf7d0 @@ -33,7 +33,7 @@ graph TD |:-----|:-----|:-------| | `cc_reader_exit.md` | 📄 Leaf Task | ✅ Done | | `oc_reader_exit.md` | 📄 Leaf Task | ✅ Done | -| `serve_context.md` | 📄 Leaf Task | 🔄 In Progress | +| `serve_context.md` | 📄 Leaf Task | ✅ Done | | `helper_context.md` | 📄 Leaf Task | 🔄 In Progress | | `e2e/` | 📁 Directory | ⬜ Planned | From 81ae2e377fbe2ddab69cf6d781176ec531f43faf Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:17:32 +0900 Subject: [PATCH 53/93] test(evaluation): record the served rows over the reader writing exit The Claude Code reader (claude-code-stream-json@0.3.0) now writes `exit` on Bash results, so the imported trace.jsonl of run-6 and run-12 changed bytes and hash. Regenerate the [[served]] rows with gen_live_context.py --store over a store the guard's mini-corpus import produced: the two trace_sha256 literals, with the projection and digest that carry them. Raw streams and the manifest are unchanged. The generator header now says the rows are regenerated whenever a reader's output changes. Co-Authored-By: Claude Sonnet 5.5 --- .../tests/oracle/vectors/gen_live_context.py | 3 ++- .../tests/oracle/vectors/live_context_runs.toml | 12 ++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/candler-core/tests/oracle/vectors/gen_live_context.py b/crates/candler-core/tests/oracle/vectors/gen_live_context.py index 0e1afd8f..7448d454 100644 --- a/crates/candler-core/tests/oracle/vectors/gen_live_context.py +++ b/crates/candler-core/tests/oracle/vectors/gen_live_context.py @@ -32,7 +32,8 @@ a store folder given with `--store` (the hash of a file is the only thing it takes from there) and records each hash in its row. Without `--store` it reuses the hashes its rows already record, so `--check` needs no store; the Rust guard compares each recorded hash with the hash of the file the -store holds before it compares digests. +store holds before it compares digests. The recorded hashes are those of the bytes a reader +writes, so the `[[served]]` rows are regenerated with `--store` whenever a reader's output changes. """ import argparse diff --git a/crates/candler-core/tests/oracle/vectors/live_context_runs.toml b/crates/candler-core/tests/oracle/vectors/live_context_runs.toml index a2580f83..c92965ee 100644 --- a/crates/candler-core/tests/oracle/vectors/live_context_runs.toml +++ b/crates/candler-core/tests/oracle/vectors/live_context_runs.toml @@ -47,19 +47,19 @@ digest = "sha256:c09cf0ea32d68a6f13fa8418a7d26844212dbe6e514c8a486829cab7af5d5fb cell = "20260806-035940_v0.2.3_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-v0.2.3" run = "with_skill/run-6" needs = ["trace", "raw", "manifest"] -trace_sha256 = "sha256:69a060902f6c8e57181e00e1168db325f161e0dc2a7c4fd5d17120adc8015d7b" +trace_sha256 = "sha256:4bea247947ddbb6e6d20e765391518318839ffb17aa70948d3efef638f48f3cf" manifest_sha256 = "sha256:0b63023ac489f555b8b43a45e67e88614cdf047d2b9f24613ddffddee0ce9bfd" raw = [{ stream = "stderr", sha256 = "sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e" }, { stream = "stdout", sha256 = "sha256:20d43143e335ec527bdbb3943aea771523bac466a366f5bc1efb114d9df676c8" }] -projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:9e79641026c088d5977727a252eccb44aa5a440399011f497b5504e82ce33e0b\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:67bc1eac7242670159d22fcfa503416b4f0874a405c206eb4c6a0d1126130b61\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:57d084dc0f9ea0b8a555d66fba8a0fc441a14675442af09964a2f1f9ef710d28\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:69a060902f6c8e57181e00e1168db325f161e0dc2a7c4fd5d17120adc8015d7b\",\"raw\":[{\"stream\":\"stderr\",\"sha256\":\"sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e\"},{\"stream\":\"stdout\",\"sha256\":\"sha256:20d43143e335ec527bdbb3943aea771523bac466a366f5bc1efb114d9df676c8\"}],\"manifest\":\"sha256:0b63023ac489f555b8b43a45e67e88614cdf047d2b9f24613ddffddee0ce9bfd\"}" -digest = "sha256:3407dcc0e38bf8d10392423e0bdb6f9b8eff44416ecdd315bcc8cf44e4bde3c6" +projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:9e79641026c088d5977727a252eccb44aa5a440399011f497b5504e82ce33e0b\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:67bc1eac7242670159d22fcfa503416b4f0874a405c206eb4c6a0d1126130b61\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:57d084dc0f9ea0b8a555d66fba8a0fc441a14675442af09964a2f1f9ef710d28\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:4bea247947ddbb6e6d20e765391518318839ffb17aa70948d3efef638f48f3cf\",\"raw\":[{\"stream\":\"stderr\",\"sha256\":\"sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e\"},{\"stream\":\"stdout\",\"sha256\":\"sha256:20d43143e335ec527bdbb3943aea771523bac466a366f5bc1efb114d9df676c8\"}],\"manifest\":\"sha256:0b63023ac489f555b8b43a45e67e88614cdf047d2b9f24613ddffddee0ce9bfd\"}" +digest = "sha256:73bf83e64b86ce32bf796088bd5468555f5f97f3e6354d63d50c9f060f59d633" [[served]] cell = "20260806-035940_v0.2.6_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-0.2.6" run = "with_skill/run-12" needs = ["trace"] -trace_sha256 = "sha256:c0f214b78374d1917a4e30a7a6d443d8cea2463ef23c5d88057b3b92df438d90" -projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:d1238cde58dc83c8a22ec512974681b3c4f30c7eeeab977d5e3096058f318552\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:12b3cddb89db9df478e0f38a2b5ae531ddb968d330c3d8b71295b101795cb83f\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:588434f85cfb10eca786c798729a2a1a315c61caa1a26d8ff0504a5a39918fd4\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:c0f214b78374d1917a4e30a7a6d443d8cea2463ef23c5d88057b3b92df438d90\"}" -digest = "sha256:913328a495dd9dc92143923bb4bb9de30eadba74dda98db986457483de7b5c13" +trace_sha256 = "sha256:777957636c8501eff59d51d7f02434587a857f0ef653e2569512503a159a60c5" +projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:d1238cde58dc83c8a22ec512974681b3c4f30c7eeeab977d5e3096058f318552\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:12b3cddb89db9df478e0f38a2b5ae531ddb968d330c3d8b71295b101795cb83f\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:588434f85cfb10eca786c798729a2a1a315c61caa1a26d8ff0504a5a39918fd4\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:777957636c8501eff59d51d7f02434587a857f0ef653e2569512503a159a60c5\"}" +digest = "sha256:44bf7ee9348d08418f380edf7cb6fa82e7da6278fcc114c1882df642414c9f44" [[served]] cell = "20260806-035940_v0.2.3_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-v0.2.3" From 93497d2615cf5f44d92df07a0b880cde6e91f9f6 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:11:12 +0900 Subject: [PATCH 54/93] test(evaluator-helper): state the stored run's parts and a typed trace Guards over hand-written wire contexts and trace lines: each served part kept with its digest, a typed trace reader that refuses an unknown field, and a describe result that never carries null for an unset need. Co-Authored-By: Claude Sonnet 5.5 --- .../tests/test_guard_context.py | 212 ++++++++++++++++++ 1 file changed, 212 insertions(+) diff --git a/python/candler-evaluator/tests/test_guard_context.py b/python/candler-evaluator/tests/test_guard_context.py index 105e8dd2..11477bb3 100644 --- a/python/candler-evaluator/tests/test_guard_context.py +++ b/python/candler-evaluator/tests/test_guard_context.py @@ -1,3 +1,12 @@ +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest +from pydantic import ValidationError + from candler_evaluator.plugin import RunContext CELL = "sha256:" + "ab" * 32 @@ -29,3 +38,206 @@ def test_a_context_with_snapshots_keeps_them(): wire["snapshots"] = [{"kind": "catalog", "path": "/s/c", "digest": CELL}] context = RunContext.from_wire(wire, "/scratch") assert [entry["kind"] for entry in context.snapshots] == ["catalog"] + + +DIGEST_A = "sha256:" + "11" * 32 +DIGEST_B = "sha256:" + "22" * 32 +DIGEST_C = "sha256:" + "33" * 32 + + +def served_wire(): + wire = wire_context() + wire["trace"] = { + "path": "trace.jsonl", + "abs": "/runs/r1/trace.jsonl", + "sha256": DIGEST_A, + } + wire["manifest"] = { + "path": "manifest.json", + "abs": "/runs/r1/manifest.json", + "sha256": DIGEST_B, + } + wire["raw"] = [ + {"stream": "stdout", "path": "/runs/r1/raw/stdout.jsonl.gz", "sha256": DIGEST_C} + ] + return wire + + +def test_a_context_keeps_the_trace_raw_and_manifest_with_their_digests(): + """Guards: `from_wire` hands a kind each served part with its path and digest. + + Oracle: the wire context is written by hand from the `RunContext`, `ContextArtifact` and + `ContextRaw` definitions of evaluator-evaluate-params.schema.json. + Bite: `from_wire` drops `manifest`, or reads `trace` as a bare path. + """ + context = RunContext.from_wire(served_wire(), "/scratch") + assert context.trace is not None and context.manifest is not None + assert (context.trace.path, context.trace.abs, context.trace.sha256) == ( + "trace.jsonl", + Path("/runs/r1/trace.jsonl"), + DIGEST_A, + ) + assert (context.manifest.path, context.manifest.abs, context.manifest.sha256) == ( + "manifest.json", + Path("/runs/r1/manifest.json"), + DIGEST_B, + ) + assert [(r["stream"], r["path"], r["sha256"]) for r in context.raw] == [ + ("stdout", "/runs/r1/raw/stdout.jsonl.gz", DIGEST_C) + ] + + +def test_a_context_without_the_parts_has_none_and_nothing(): + """Guards: a part the run does not serve is `None`, and no raw stream is an empty tuple.""" + context = RunContext.from_wire(wire_context(), "/scratch") + assert context.trace is None + assert context.manifest is None + assert context.raw == () + + +HEADER = { + "kind": "header", + "schema": "normalised-trace/1", + "reader": "claude-code-reader@0.1.0", + "raw": [{"stream": "stdout", "digest": DIGEST_C}], +} +SESSION = { + "kind": "session", + "id": "s1", + "source": { + "harness": "claude-code", + "harness_version": "2.1.0", + "reader": "claude-code-reader", + "reader_version": "0.1.0", + }, + "ended_by": {"kind": "completed"}, + "raw_ref": {"stream": "stdout", "frame": 0}, +} +CALL = { + "kind": "event", + "session": "s1", + "event": { + "seq": 0, + "kind": { + "kind": "tool_call", + "name": "mcp__fs__read", + "origin": {"kind": "mcp", "server": "fs", "tool": "read"}, + "argv": ["cat", "a.txt"], + "wrapped_calls": [], + }, + "raw_ref": {"stream": "stdout", "frame": 1}, + "ext": {}, + }, +} +RESULT = { + "kind": "event", + "session": "s1", + "event": { + "seq": 1, + "kind": { + "kind": "tool_result", + "is_error": True, + "exit": {"kind": "code", "code": 2}, + }, + "raw_ref": {"stream": "stdout", "frame": 2}, + "ext": {}, + }, +} + + +def write_trace(tmp_path, records): + path = tmp_path / "trace.jsonl" + path.write_text("".join(json.dumps(r) + "\n" for r in records)) + return path + + +def test_the_reader_yields_typed_records_with_exit_origin_and_argv(tmp_path): + """Guards: the trace reader types each line from normalised-trace.schema.json. + + Oracle: the lines are written by hand from the schema's `TraceRecord`, `EventKind`, + `ToolOrigin` and `ExitStatus`. + """ + from candler_evaluator import read_trace + + path = write_trace(tmp_path, [HEADER, SESSION, CALL, RESULT]) + records = [r.root if hasattr(r, "root") else r for r in read_trace(path)] + assert [r.kind for r in records] == ["header", "session", "event", "event"] + call, result = records[2].event.kind, records[3].event.kind + assert call.argv == ["cat", "a.txt"] + assert (call.origin.kind, call.origin.server, call.origin.tool) == ( + "mcp", + "fs", + "read", + ) + assert (result.exit.kind, result.exit.code) == ("code", 2) + + +def test_the_reader_takes_the_served_trace_of_a_context(tmp_path): + """Guards: a kind passes `context.trace` itself to the reader.""" + from candler_evaluator import read_trace + + path = write_trace(tmp_path, [HEADER, SESSION]) + wire = served_wire() + wire["trace"]["abs"] = str(path) + context = RunContext.from_wire(wire, "/scratch") + assert len(list(read_trace(context.trace))) == 2 + + +def test_the_reader_refuses_a_line_with_an_unknown_field(tmp_path): + """Guards: the schema refuses an unknown field, so the reader does. + + Oracle: `additionalProperties: false` on every object of normalised-trace.schema.json. + Bite: the generated models accept extra fields. + """ + bad = json.loads(json.dumps(RESULT)) + bad["event"]["kind"]["surprise"] = 1 + from candler_evaluator import read_trace + + path = write_trace(tmp_path, [HEADER, SESSION, bad]) + with pytest.raises(ValidationError): + list(read_trace(path)) + + +DESCRIBE_PLUGIN = """ +NAME = "demo" +VERSION = "0.1.0" +KINDS = {"k": lambda params, context, prior: {"status": "pass"}} +KIND_SPECS = {"k": {"needs": NEEDS}} +""" + + +def described_needs(tmp_path, needs, vectors): + (tmp_path / "demo_plugin.py").write_text(f"NEEDS = {needs!r}\n" + DESCRIBE_PLUGIN) + request = json.dumps( + json.loads((vectors / "valid" / "request_describe.json").read_text()) + ) + out = subprocess.run( + [sys.executable, "-m", "candler_evaluator", "demo_plugin"], + input=request + "\n", + capture_output=True, + text=True, + check=True, + env={**os.environ, "PYTHONPATH": str(tmp_path), "PYTHONDONTWRITEBYTECODE": "1"}, + timeout=60, + ).stdout + frames = [json.loads(line) for line in out.splitlines()] + (result,) = [f for f in frames if "result" in f] + return result["result"]["kinds"][0]["needs"] + + +def test_a_describe_result_never_carries_null_for_an_unset_need(tmp_path, vectors): + """Guards: `raw` and `manifest` are written as booleans or left out, never `null`. + + Oracle: response_describe_needs_raw_manifest.json shows the wire form, and + invalid/needs_raw_not_boolean.json shows the reader refusing anything but a boolean. + Bite: the writer emits `null` for an unset need. + """ + oracle = json.loads( + (vectors / "valid" / "response_describe_needs_raw_manifest.json").read_text() + )["result"]["kinds"][0]["needs"] + assert oracle["raw"] is True and oracle["manifest"] is True + for needs in ({}, {"raw": None, "manifest": None}, {"raw": True, "manifest": True}): + wrote = described_needs(tmp_path, needs, vectors) + assert None not in wrote.values() + for key in ("raw", "manifest"): + assert wrote.get(key, False) is bool(needs.get(key)) From a79435f74a74718c880a77bf8f06dc5f54ef6a26 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:13:27 +0900 Subject: [PATCH 55/93] feat(evaluator-helper): hand a kind the run's parts and a typed trace RunContext carries trace and manifest as ServedFile (path, abs, sha256); read_trace yields the trace lines as models generated from normalised-trace.schema.json and refuses a line the schema refuses. The version is bumped to 0.2.0. BREAKING CHANGE: RunContext.trace is a ServedFile, no longer a Path; read its `abs` member. Co-Authored-By: Claude Sonnet 5.5 --- docs/contract/evaluator-helper.md | 6 +- docs/contract/index.md | 2 +- python/candler-evaluator/CHANGELOG.md | 4 + python/candler-evaluator/README.md | 11 +- python/candler-evaluator/pyproject.toml | 2 +- .../candler-evaluator/scripts/gen_models.py | 3 +- .../src/candler_evaluator/__init__.py | 14 +- .../_models/normalised_trace.py | 582 ++++++++++++++++++ .../src/candler_evaluator/plugin.py | 33 +- .../src/candler_evaluator/trace.py | 27 + .../tests/test_guard_context.py | 8 +- python/candler-evaluator/uv.lock | 2 +- 12 files changed, 677 insertions(+), 17 deletions(-) create mode 100644 python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py create mode 100644 python/candler-evaluator/src/candler_evaluator/trace.py diff --git a/docs/contract/evaluator-helper.md b/docs/contract/evaluator-helper.md index 698910f9..bcf284a0 100644 --- a/docs/contract/evaluator-helper.md +++ b/docs/contract/evaluator-helper.md @@ -6,13 +6,15 @@ The Python package `candler-evaluator`, which an author of an evaluator kind use The author API (a kind's signature, `RunContext`, `KINDS`, `needs` and `params_schema`) is in the package's docstrings and README. +A kind reads the stored parts of a run from `RunContext`: `trace` and `manifest`, each a `ServedFile` with `path`, `abs` and `sha256` or `None`, and `raw`, a tuple of mappings with `stream`, `path` and `sha256`. `read_trace(context.trace)` yields the trace's records as models generated from `normalised-trace.schema.json`. + ## Version Wire tag: none. -Package: `candler-evaluator@0.1.0`. +Package: `candler-evaluator@0.2.0`. @@ -103,3 +105,5 @@ Package: `candler-evaluator@0.1.0`. - `print` in a kind goes to stderr; stdout carries the frames alone. [checked: candler-evaluator@0.1.0] - An instrument installed from a package index makes `describe` and `evaluate` fail with error -32000. [checked: candler-evaluator@0.1.0] - A module with no `KINDS` ends the process with exit 1 before it sends a frame. [checked: candler-evaluator@0.1.0] +- A part is served when any kind of the plug-in declares it in `needs`, as its kinds share one process. [checked: candler-evaluator@0.2.0] +- `read_trace` raises `ValidationError` at a line the schema refuses. [checked: candler-evaluator@0.2.0] diff --git a/docs/contract/index.md b/docs/contract/index.md index 70734707..6c18776c 100644 --- a/docs/contract/index.md +++ b/docs/contract/index.md @@ -35,7 +35,7 @@ Every row of a Fields table has one class. A `required` followed by a variant in |---|---|---| | core | `v0.16.0` | `Cargo.toml` | | wire schemas | `schemas@0.13.0` | `crates/candler-schemas/Cargo.toml` | -| evaluator helper | `candler-evaluator@0.1.0` | `python/candler-evaluator/pyproject.toml` | +| evaluator helper | `candler-evaluator@0.2.0` | `python/candler-evaluator/pyproject.toml` | ## Exit codes diff --git a/python/candler-evaluator/CHANGELOG.md b/python/candler-evaluator/CHANGELOG.md index df3c3e91..7f046d10 100644 --- a/python/candler-evaluator/CHANGELOG.md +++ b/python/candler-evaluator/CHANGELOG.md @@ -6,6 +6,10 @@ PyPI without Eliott's go. The version is bumped by hand in `pyproject.toml` from ## Unreleased +- `RunContext` carries `trace` and `manifest` as `ServedFile`s (`path`, `abs`, `sha256`) and each + `raw` stream with its `sha256`; `trace` was a bare path and is now a `ServedFile`. +- `read_trace` yields a trace's records as models generated from + `normalised-trace.schema.json`, refusing a line the schema refuses. - The wire models are generated from the published schemas by `scripts/gen_models.py`; the loop parses and builds every message through them, and the shared wire vectors decide what they accept. diff --git a/python/candler-evaluator/README.md b/python/candler-evaluator/README.md index ea41873e..12dfd1ab 100644 --- a/python/candler-evaluator/README.md +++ b/python/candler-evaluator/README.md @@ -17,11 +17,16 @@ grades one item, and may expose `NAME`, `VERSION`, `DIST`, `INSTRUMENTS`, `KIND_ `blocked`, `not_measured`, `not_applicable`) and the optional `value`, `weight`, `cause` and `evidence`. The helper checks the result against the outcome rules. - **`RunContext`** is what a kind may read of one run: `root`, `artifacts`, `metadata`, - `scratch`, `run`, `raw`, `trace`, `artifact_files`, `snapshots` and `inputs`. A kind never - imports the class; it reads the object it is given. + `scratch`, `run`, `raw`, `trace`, `manifest`, `artifact_files`, `snapshots` and `inputs`. A + kind never imports the class; it reads the object it is given. `trace` and `manifest` are a + `ServedFile` (`path`, `abs`, `sha256`) or `None`; `raw` is a tuple of mappings with `stream`, + `path` and `sha256`. `candler_evaluator.read_trace(context.trace)` yields the trace's lines as + models generated from `normalised-trace.schema.json` and raises `pydantic.ValidationError` at + a line the schema refuses. - **`KINDS`** maps each kind's name to its function. - **`needs`** says what a kind reads: `artifacts` (globs), `inputs`, `metadata` (field paths), - `snapshots` and `trace`. It is set per kind in `KIND_SPECS`. + `snapshots`, `trace`, `raw` and `manifest` (the last three are booleans). It is set per kind in + `KIND_SPECS`. - **`params_schema`** is the JSON Schema of a kind's params, also set per kind in `KIND_SPECS`. `default_deadline_ms` sits beside them. diff --git a/python/candler-evaluator/pyproject.toml b/python/candler-evaluator/pyproject.toml index b81f0d37..08e2ae0c 100644 --- a/python/candler-evaluator/pyproject.toml +++ b/python/candler-evaluator/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "candler-evaluator" -version = "0.1.0" +version = "0.2.0" description = "Helper for writing Candler evaluator plug-ins in Python" readme = "README.md" requires-python = ">=3.10" diff --git a/python/candler-evaluator/scripts/gen_models.py b/python/candler-evaluator/scripts/gen_models.py index da2511f0..6fbbad61 100644 --- a/python/candler-evaluator/scripts/gen_models.py +++ b/python/candler-evaluator/scripts/gen_models.py @@ -1,7 +1,7 @@ """Regenerate `src/candler_evaluator/_models/` from the published wire schemas. Run from `python/candler-evaluator`: `uv run --frozen python scripts/gen_models.py`. -One module per schema root: `evaluator-*.schema.json` and `outcome-record.schema.json` of +One module per schema root: `evaluator-*.schema.json`, `outcome-record.schema.json` and `normalised-trace.schema.json` of `crates/candler-schemas/schema/`. Each module's header names its schema file and the file's sha256, so a changed schema shows as a changed header. The output is deterministic; CI regenerates it and fails when it differs from what is committed. @@ -39,6 +39,7 @@ def roots() -> list[Path]: """The schema roots the helper's models come from, in a fixed order.""" found = sorted(SCHEMAS.glob("evaluator-*.schema.json")) found.append(SCHEMAS / "outcome-record.schema.json") + found.append(SCHEMAS / "normalised-trace.schema.json") return found diff --git a/python/candler-evaluator/src/candler_evaluator/__init__.py b/python/candler-evaluator/src/candler_evaluator/__init__.py index deaa96e5..1a353eae 100644 --- a/python/candler-evaluator/src/candler_evaluator/__init__.py +++ b/python/candler-evaluator/src/candler_evaluator/__init__.py @@ -4,9 +4,19 @@ from .frames import FrameWriter from .loop import main, serve -from .plugin import Outcome, Plugin +from .plugin import Outcome, Plugin, ServedFile +from .trace import read_trace -__all__ = ["FrameWriter", "Outcome", "Plugin", "__version__", "main", "serve"] +__all__ = [ + "FrameWriter", + "Outcome", + "Plugin", + "ServedFile", + "__version__", + "main", + "read_trace", + "serve", +] def __getattr__(name: str) -> Any: diff --git a/python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py b/python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py new file mode 100644 index 00000000..6bd8900a --- /dev/null +++ b/python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py @@ -0,0 +1,582 @@ +# Generated by scripts/gen_models.py; do not edit. +# schema: crates/candler-schemas/schema/normalised-trace.schema.json +# sha256: dd3d36ef8184af88ab56052328fe13194b301540e0cba1ed79e1b356cd1c94d3 + +from __future__ import annotations + +from enum import Enum +from typing import Annotated, Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, RootModel + + +class Cap(Enum): + turns = "turns" + cost = "cost" + wall = "wall" + + +class DeniedBy(Enum): + harness = "harness" + hook = "hook" + user = "user" + + +class Digest(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="A content digest: `sha256:` followed by 64 lowercase hex digits.", + pattern="^sha256:[0-9a-f]{64}(?![\\s\\S])", + ), + ] + + +class EndedBy1(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["completed"] + + +class EndedBy3(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + cap: Annotated[Cap, Field(description="The cap that was reached.")] + kind: Literal["cap"] + + +class EndedBy4(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["gateway_error"] + + +class EndedBy5(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["budget_stop"] + + +class EndedBy6(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["killed"] + + +class EndedBy7(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["interrupted"] + + +class EndedBy8(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["unknown"] + + +class EventKind1(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["user_message"] + text: Annotated[ + str | None, Field(description="The text, if the harness records it.") + ] = None + + +class EventKind2(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["assistant_message"] + text: Annotated[ + str | None, Field(description="The text, if the harness records it.") + ] = None + + +class EventKind5(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["notification"] + + +class ExitStatus1(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + code: Annotated[int, Field(description="The exit code.")] + kind: Literal["code"] + + +class ExitStatus2(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["signal"] + signal: Annotated[int, Field(description="The signal number.")] + + +class ExitStatus(RootModel[ExitStatus1 | ExitStatus2]): + root: Annotated[ + ExitStatus1 | ExitStatus2, + Field( + description="How a process ended: an object whose `kind` is `code` (with the integer `code`) or `signal` (with the integer `signal`)." + ), + ] + + +class Finite(RootModel[float]): + root: Annotated[ + float, + Field( + description="A finite real number: neither `NaN` nor infinite. Negative zero is finite." + ), + ] + + +class Name(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="A plain name, such as that of a harness, a reader, a plug-in or a treatment: non-empty, with neither `@` nor white space.", + pattern="^[^@\\t\\n\\v\\f\\r\\x20\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+(?![\\s\\S])", + ), + ] + + +class NameVersion(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="An evaluator or instrument reference, `name@version`, split at the last `@`: the name is non-empty and holds neither `@` nor white space, and the version is `SemVer` 2.0.", + pattern="^[^@\\t\\n\\v\\f\\r\\x20\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+@(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)(?:-(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\\+[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*)?(?![\\s\\S])", + ), + ] + + +class ReasonCode(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="A reason code: a lowercase letter, then lowercase letters, digits or `_`.", + pattern="^[a-z][a-z0-9_]*(?![\\s\\S])", + ), + ] + + +class SessionId(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="The id of a session: non-empty, with neither `#` nor white space, so that it reads as the session part of an `event:#` evidence reference. A child session's id is its parent's id, `/`, and the id of the call that started it.", + pattern="^[^#\\t\\n\\v\\f\\r\\x20\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+(?![\\s\\S])", + ), + ] + + +class SessionSource(BaseModel): + model_config = ConfigDict( + extra="forbid", + regex_engine="python-re", + ) + harness: Annotated[ + Name, Field(description="The name of the harness that ran the session.") + ] + harness_version: Annotated[ + str, + Field( + description="The harness version, a `SemVer` 2.0 string.", + pattern="^(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)(?:-(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\\+[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*)?(?![\\s\\S])", + ), + ] + reader: Annotated[ + Name, Field(description="The name of the reader that normalised the session.") + ] + reader_version: Annotated[ + str, + Field( + description="The reader version, a `SemVer` 2.0 string.", + pattern="^(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)(?:-(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\\+[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*)?(?![\\s\\S])", + ), + ] + + +class SpanId(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="The id of a harness call, which pairs a call with its result and names the child session the call started: non-empty, with neither `#` nor white space.", + pattern="^[^#\\t\\n\\v\\f\\r\\x20\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+(?![\\s\\S])", + ), + ] + + +class StreamName(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + description="The name of an archived stream: `stdout`, `stderr`, or the name of a collected file, matching `[a-z0-9][a-z0-9._-]*`.", + pattern="^[a-z0-9][a-z0-9._-]*(?![\\s\\S])", + ), + ] + + +class Timestamp(RootModel[str]): + model_config = ConfigDict( + regex_engine="python-re", + ) + root: Annotated[ + str, + Field( + 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])", + ), + ] + + +class ToolOrigin1(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["builtin"] + + +class ToolOrigin2(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["mcp"] + server: Annotated[str, Field(description="The name of the MCP server.")] + tool: Annotated[ + str | None, + Field( + description="The tool's name at the server, without the harness's prefix. A trace written before the\nfield existed has none." + ), + ] = None + + +class ToolOrigin3(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["other"] + + +class ToolOrigin(RootModel[ToolOrigin1 | ToolOrigin2 | ToolOrigin3]): + root: Annotated[ + ToolOrigin1 | ToolOrigin2 | ToolOrigin3, + Field( + 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`." + ), + ] + + +class UsageScope(Enum): + message = "message" + session_total = "session_total" + + +class WrappedCall(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + name: Annotated[str, Field(description="The name of the wrapped tool.")] + origin: Annotated[ + ToolOrigin, Field(description="Where the wrapped tool is served from.") + ] + + +class Denial(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + by: Annotated[DeniedBy, Field(description="Who refused the call.")] + reason: Annotated[str | None, Field(description="The reason given, if any.")] = None + + +class EndedBy2(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["agent_error"] + reason: Annotated[ + ReasonCode | None, Field(description="Why the agent failed, when it says.") + ] = None + + +class EndedBy( + RootModel[ + EndedBy1 + | EndedBy2 + | EndedBy3 + | EndedBy4 + | EndedBy5 + | EndedBy6 + | EndedBy7 + | EndedBy8 + ] +): + root: Annotated[ + EndedBy1 + | EndedBy2 + | EndedBy3 + | EndedBy4 + | EndedBy5 + | EndedBy6 + | EndedBy7 + | EndedBy8, + Field( + description="How a session ended: an object whose `kind` is `completed`, `agent_error`, `cap`, `gateway_error`, `budget_stop`, `killed`, `interrupted` or `unknown`." + ), + ] + + +class EventKind3(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + argv: Annotated[ + list[str] | None, Field(description="The command line, if the tool runs one.") + ] = None + kind: Literal["tool_call"] + name: Annotated[str, Field(description="The name of the tool.")] + origin: Annotated[ToolOrigin, Field(description="Where the tool is served from.")] + wrapped_calls: Annotated[ + list[WrappedCall], + Field( + description="The MCP calls this call bundles; an empty array when it bundles none." + ), + ] + + +class EventKind4(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + denied: Annotated[ + Denial | None, Field(description="Who refused the call, when it was refused.") + ] = None + exit: Annotated[ + ExitStatus | None, + Field( + description="How the shell call ended, as the harness reported it: `{kind: code, code}` or `{kind: signal, signal}`. Absent when the call is not a shell call, was denied, or came back without a code." + ), + ] = None + is_error: Annotated[ + bool, + Field( + description="Whether the harness marked the result as an error. A harness decides this for itself, so for a shell call it is not comparable across harnesses: read `exit` for the status." + ), + ] + kind: Literal["tool_result"] + + +class EventKind6(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + cache_creation_tokens: Annotated[ + int, Field(description="Input tokens written to the cache.", ge=0) + ] + cache_read_tokens: Annotated[ + int, Field(description="Input tokens served from the cache.", ge=0) + ] + cost_usd: Annotated[ + Finite | None, + Field( + description="The cost in US dollars, a finite number, if the harness reports it." + ), + ] = None + input_tokens: Annotated[int, Field(description="Input tokens.", ge=0)] + kind: Literal["usage"] + output_tokens: Annotated[int, Field(description="Output tokens.", ge=0)] + scope: Annotated[ + UsageScope, + Field( + description="Whether the counts are one message's or the session's running total." + ), + ] + + +class EventKind( + RootModel[ + EventKind1 | EventKind2 | EventKind3 | EventKind4 | EventKind5 | EventKind6 + ] +): + root: Annotated[ + EventKind1 | EventKind2 | EventKind3 | EventKind4 | EventKind5 | EventKind6, + Field( + description="What happened at one point of a session: an object whose `kind` is `user_message`, `assistant_message`, `tool_call`, `tool_result`, `notification` or `usage`, with the members of that kind beside it." + ), + ] + + +class RawFileRef(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + digest: Annotated[ + Digest, Field(description="The digest of the framed raw file of the stream.") + ] + stream: Annotated[StreamName, Field(description="The name of the archived stream.")] + + +class RawRef(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + frame: Annotated[int, Field(description="The index of the frame, from 0.", ge=0)] + stream: Annotated[StreamName, Field(description="The stream the frame belongs to.")] + + +class TraceRecord1(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["header"] + raw: Annotated[ + list[RawFileRef], + Field( + description="The raw files the trace was read from; every `raw_ref` of the file names one of their streams." + ), + ] + reader: Annotated[ + NameVersion, + Field( + description="The reader and its version, as `name@version` with a `SemVer` version." + ), + ] + schema_: Annotated[ + Literal["normalised-trace/1"], + Field( + alias="schema", + description="The version marker: always `normalised-trace/1`.", + ), + ] + + +class TraceRecord2(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + ended_at: Annotated[ + Timestamp | None, + Field( + description="When the session ended, if the harness or the frame times say." + ), + ] = None + ended_by: Annotated[EndedBy, Field(description="How the session ended.")] + id: Annotated[ + SessionId, + Field( + description="The id of the session: non-empty, with neither `#` nor white space; a child's id is its parent's id, `/`, and the id of the call that started it." + ), + ] + kind: Literal["session"] + model: Annotated[ + str | None, + Field( + description="The model the session ran, as the harness names it, if it says." + ), + ] = None + parent_session: Annotated[ + SessionId | None, + Field( + description="The id of the session that started this one; the session's own id is that id, `/`, and a call id." + ), + ] = None + raw_ref: Annotated[RawRef, Field(description="The frame the session starts at.")] + source: Annotated[ + SessionSource, + Field(description="The harness and the reader that produced the session."), + ] + started_at: Annotated[ + Timestamp | None, + Field( + description="When the session started, if the harness or the frame times say." + ), + ] = None + + +class Event(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + at: Annotated[ + Timestamp | None, + Field( + description="When the event happened, if the harness or the frame time says." + ), + ] = None + ext: Annotated[ + dict[str, Any], + Field( + description="Data of the harness that no other field holds: an open JSON object, empty when there is none, whose content is open, so a `null` inside it is kept and written back." + ), + ] + kind: Annotated[EventKind, Field(description="What happened.")] + raw_ref: Annotated[RawRef, Field(description="The frame the event was read from.")] + seq: Annotated[ + int, + Field( + description="The position of the event in its session, counting from 0 without gaps.", + ge=0, + ), + ] + span: Annotated[ + SpanId | None, + Field( + description="The harness's id that pairs a call with its result, if the event has one." + ), + ] = None + + +class TraceRecord3(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + event: Annotated[Event, Field(description="The event.")] + kind: Literal["event"] + session: Annotated[ + SessionId, Field(description="The id of the session the event belongs to.") + ] + + +class TraceRecord(RootModel[TraceRecord1 | TraceRecord2 | TraceRecord3]): + root: Annotated[ + TraceRecord1 | TraceRecord2 | TraceRecord3, + Field( + description="One line of a trace file: an object whose `kind` is `header`, `session` or `event`.", + title="TraceRecord", + ), + ] diff --git a/python/candler-evaluator/src/candler_evaluator/plugin.py b/python/candler-evaluator/src/candler_evaluator/plugin.py index 40b53f4a..0075a262 100644 --- a/python/candler-evaluator/src/candler_evaluator/plugin.py +++ b/python/candler-evaluator/src/candler_evaluator/plugin.py @@ -18,6 +18,7 @@ "PluginError", "Prior", "RunContext", + "ServedFile", "normalise_outcome", ] @@ -87,9 +88,32 @@ class Prior: outcome: Mapping[str, Any] +@dataclass(frozen=True) +class ServedFile: + """One stored file of the run: `path` relative to the run, `abs` where the kind reads it, + and the `sha256` digest of its bytes, written `sha256:` and 64 hex digits.""" + + path: str + abs: Path + sha256: str + + @classmethod + def from_wire(cls, served: Mapping[str, Any]) -> ServedFile: + """Build one from a `ContextArtifact` of the wire.""" + return cls( + path=served["path"], abs=Path(served["abs"]), sha256=served["sha256"] + ) + + @dataclass(frozen=True) class RunContext: - """What a kind may read of one run; kinds never import this class, they only read it.""" + """What a kind may read of one run; kinds never import this class, they only read it. + + `trace` and `manifest` are the run's normalised trace and manifest as `ServedFile`s, each + `None` when no kind of the plug-in declared it in `needs`; `raw` holds one mapping per raw + stream, with the keys `stream`, `path` and `sha256`, and is empty when none was declared. + `read_trace` reads `trace`. + """ root: Path artifacts: tuple[str, ...] @@ -97,7 +121,8 @@ class RunContext: scratch: Path run: Mapping[str, Any] = field(default_factory=dict) raw: tuple[Mapping[str, Any], ...] = () - trace: Path | None = None + trace: ServedFile | None = None + manifest: ServedFile | None = None artifact_files: tuple[Mapping[str, Any], ...] = () snapshots: tuple[Mapping[str, Any], ...] = () inputs: tuple[Mapping[str, Any], ...] = () @@ -107,6 +132,7 @@ def from_wire(cls, context: Mapping[str, Any], scratch: str) -> RunContext: """Build the duck-typed context from the `context` and `scratch` of an evaluate request.""" files = tuple(context["artifacts"]) trace = context.get("trace") + manifest = context.get("manifest") return cls( root=Path(context["root"]), artifacts=tuple(sorted(f["path"] for f in files)), @@ -114,7 +140,8 @@ def from_wire(cls, context: Mapping[str, Any], scratch: str) -> RunContext: scratch=Path(scratch), run=context["run"], raw=tuple(context["raw"]), - trace=None if trace is None else Path(trace["abs"]), + trace=None if trace is None else ServedFile.from_wire(trace), + manifest=None if manifest is None else ServedFile.from_wire(manifest), artifact_files=files, snapshots=tuple(context.get("snapshots", [])), inputs=tuple(context["inputs"]), diff --git a/python/candler-evaluator/src/candler_evaluator/trace.py b/python/candler-evaluator/src/candler_evaluator/trace.py new file mode 100644 index 00000000..d7c09f39 --- /dev/null +++ b/python/candler-evaluator/src/candler_evaluator/trace.py @@ -0,0 +1,27 @@ +"""Read a run's normalised trace as typed records.""" + +from __future__ import annotations + +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +from .plugin import ServedFile + +__all__ = ["read_trace"] + + +def read_trace(trace: ServedFile | Path | str) -> Iterator[Any]: + """Yield the records of a trace file, one per line, as the models of its schema. + + `trace` is `context.trace` or a path. A record is the header, a session or an event of + `normalised-trace.schema.json`, held by the model of its `kind`. A line that is not JSON + or that the schema refuses, an unknown field included, raises `pydantic.ValidationError` + when the iterator reaches it; the records before it have been yielded. + """ + from ._models.normalised_trace import TraceRecord + + path = trace.abs if isinstance(trace, ServedFile) else Path(trace) + with path.open(encoding="utf-8") as lines: + for line in lines: + yield TraceRecord.model_validate_json(line, strict=True).root diff --git a/python/candler-evaluator/tests/test_guard_context.py b/python/candler-evaluator/tests/test_guard_context.py index 11477bb3..5f3d3010 100644 --- a/python/candler-evaluator/tests/test_guard_context.py +++ b/python/candler-evaluator/tests/test_guard_context.py @@ -160,16 +160,16 @@ def test_the_reader_yields_typed_records_with_exit_origin_and_argv(tmp_path): from candler_evaluator import read_trace path = write_trace(tmp_path, [HEADER, SESSION, CALL, RESULT]) - records = [r.root if hasattr(r, "root") else r for r in read_trace(path)] + records = list(read_trace(path)) assert [r.kind for r in records] == ["header", "session", "event", "event"] - call, result = records[2].event.kind, records[3].event.kind + call, result = records[2].event.kind.root, records[3].event.kind.root assert call.argv == ["cat", "a.txt"] - assert (call.origin.kind, call.origin.server, call.origin.tool) == ( + assert (call.origin.root.kind, call.origin.root.server, call.origin.root.tool) == ( "mcp", "fs", "read", ) - assert (result.exit.kind, result.exit.code) == ("code", 2) + assert (result.exit.root.kind, result.exit.root.code) == ("code", 2) def test_the_reader_takes_the_served_trace_of_a_context(tmp_path): diff --git a/python/candler-evaluator/uv.lock b/python/candler-evaluator/uv.lock index 0cba0958..021b92b2 100644 --- a/python/candler-evaluator/uv.lock +++ b/python/candler-evaluator/uv.lock @@ -77,7 +77,7 @@ wheels = [ [[package]] name = "candler-evaluator" -version = "0.1.0" +version = "0.2.0" source = { editable = "." } dependencies = [ { name = "pydantic" }, From 803aebfe5d69d9289ad314670b6e3aa6d8a42692 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:14:37 +0900 Subject: [PATCH 56/93] reports(evaluator-helper): close the stored run's parts in the helper Guards seen red on the base, three bites, the reader's API and the checks. Co-Authored-By: Claude Sonnet 5.5 --- .../run-context/leaves/helper_context_v0.md | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 __reports__/run-context/leaves/helper_context_v0.md diff --git a/__reports__/run-context/leaves/helper_context_v0.md b/__reports__/run-context/leaves/helper_context_v0.md new file mode 100644 index 00000000..f08cf9da --- /dev/null +++ b/__reports__/run-context/leaves/helper_context_v0.md @@ -0,0 +1,51 @@ +# Leaf report: helper_context + +An earlier attempt by another model wrote nothing, so this branch (`leaf/run-context/helper_context`, from `feat/run-context` at `5fd60ff0`) is a fresh start. + +## Spec note + +The Step 2 commit subject in the leaf is 76 characters and the commit hook allows 72. The subject used is `feat(evaluator-helper): hand a kind the run's parts and a typed trace` (the words "stored" dropped). The commit carries a `BREAKING CHANGE:` footer, because `RunContext.trace` was a `Path` and is now a `ServedFile`. + +## The reader's API + +`RunContext` carries `trace` and `manifest` as `ServedFile(path, abs, sha256)` or `None`, and `raw` as a tuple of mappings with `stream`, `path` and `sha256` (empty when not served). `candler_evaluator.read_trace(context.trace)` (also a path) yields each line of the trace as the model of its `kind` generated from `normalised-trace.schema.json`, and raises `pydantic.ValidationError` at a line the schema refuses, an unknown field included. + +## Guards on the base (Step 1, `9292fd6f`) + +| Test | Failing message on the base | +|:--|:--| +| `test_a_context_keeps_the_trace_raw_and_manifest_with_their_digests` | `AttributeError: 'RunContext' object has no attribute 'manifest'` | +| `test_a_context_without_the_parts_has_none_and_nothing` | `AttributeError: 'RunContext' object has no attribute 'manifest'` | +| `test_the_reader_yields_typed_records_with_exit_origin_and_argv` | `ImportError: cannot import name 'read_trace' from 'candler_evaluator'` | +| `test_the_reader_takes_the_served_trace_of_a_context` | same `ImportError` | +| `test_the_reader_refuses_a_line_with_an_unknown_field` | same `ImportError` | +| `test_a_describe_result_never_carries_null_for_an_unset_need` | passes on the base (see below) | + +The describe guard is green on the base: the helper already strips `None` twice (`exclude_none=True` in `loop.py` `describe` and in `frames.py`), so no `null` reaches the wire today. It is a guard against a regression, and its bite shows it can fail. Its oracle is the shared vectors: `valid/response_describe_needs_raw_manifest.json` (the wire form of `raw`/`manifest` as booleans) and the request `valid/request_describe.json` that drives the helper process. + +## Bites (Step 3) + +| Bite (scratch branch, one wrong change) | Failing message | +|:--|:--| +| `from_wire` drops `manifest` (`manifest=None`) | `test_a_context_keeps_the_trace_raw_and_manifest_with_their_digests`: `AssertionError: assert (ServedFile(path='trace.jsonl', ...) is not None and None is not None)` | +| the generated trace models accept unknown fields (`extra="allow"`) | `test_the_reader_refuses_a_line_with_an_unknown_field`: `Failed: DID NOT RAISE ValidationError` | +| the writer emits `null` for an unset need (`exclude_none` removed from both dumps, `loop.py` and `frames.py`) | `test_a_describe_result_never_carries_null_for_an_unset_need`: `AssertionError: assert None not in dict_values([[], [], None, [], None, [], False])` | + +Removing `exclude_none` from only one of the two dumps leaves the guard green: the other still strips the `None`. Both scratch branches are deleted. + +## Checks on the final commit (from `python/candler-evaluator`) + +- `uv run pytest`: 18 passed. +- `uv run ruff check`: all checks passed; `uv run ruff format --check`: 27 files already formatted. +- `uv run --frozen python scripts/gen_models.py`: no diff (`git status` clean after it); `normalised_trace.py` is generated from `normalised-trace.schema.json`. +- `python3 scripts/contract_versions.py --check` after the bump: the blocks match `0.2.0`. +- `git grep -n confirm_ -- crates python`: prints nothing. +- The contract page's Notes hold 119 words (limit 120), each bullet stamped. +- No Rust build was needed and none was run. + +## Left + +- The mandatory Sonnet review (a wire context or trace line the helper reads differently from the Rust reader) is for the coordinator to dispatch. +- Not checked against the Rust reader: an empty line in a trace file raises `ValidationError` in `read_trace`; whether the Rust reader tolerates one is not verified. +- `candler_evaluator.__init__` also exports `ServedFile` and `read_trace`; the generated `Needs.raw`/`Needs.manifest` stay `bool | None`, as the schema generator emits them. +- The tag `candler-evaluator@0.2.0` is not cut. From 55aeb154934fc3f58ece944971d0ab862ae4b7f7 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:19:58 +0900 Subject: [PATCH 57/93] docs(evaluator-helper): state that read_trace checks lines, not order A reviewer found the docstring and the Note claimed more than the reader does: it checks each line against the generated models, not the file's order, and a null on an optional field reads as absent. Candler checks the order when it writes the trace, so a second implementation of the file rules here would only drift from the Rust one. Co-Authored-By: Claude Opus 5.5 --- docs/contract/evaluator-helper.md | 4 ++-- python/candler-evaluator/scripts/gen_models.py | 9 +++++---- .../candler-evaluator/src/candler_evaluator/trace.py | 10 ++++++++-- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/docs/contract/evaluator-helper.md b/docs/contract/evaluator-helper.md index bcf284a0..501b9630 100644 --- a/docs/contract/evaluator-helper.md +++ b/docs/contract/evaluator-helper.md @@ -6,7 +6,7 @@ The Python package `candler-evaluator`, which an author of an evaluator kind use The author API (a kind's signature, `RunContext`, `KINDS`, `needs` and `params_schema`) is in the package's docstrings and README. -A kind reads the stored parts of a run from `RunContext`: `trace` and `manifest`, each a `ServedFile` with `path`, `abs` and `sha256` or `None`, and `raw`, a tuple of mappings with `stream`, `path` and `sha256`. `read_trace(context.trace)` yields the trace's records as models generated from `normalised-trace.schema.json`. +A kind reads the stored parts of a run from `RunContext`: `trace` and `manifest`, each a `ServedFile` with `path`, `abs` and `sha256` or `None`, and `raw`, a tuple of mappings with `stream`, `path` and `sha256`. `read_trace(context.trace)` yields the trace's records as models generated from `normalised-trace.schema.json`. It raises `ValidationError` at a line those models refuse (not JSON, an unknown field, a wrong type); a `null` on an optional field reads as absent, though the schema refuses it. It checks each line, not the file's order: Candler checks the order when it writes the trace, and the served copy is pinned by its sha256. ## Version @@ -106,4 +106,4 @@ Package: `candler-evaluator@0.2.0`. - An instrument installed from a package index makes `describe` and `evaluate` fail with error -32000. [checked: candler-evaluator@0.1.0] - A module with no `KINDS` ends the process with exit 1 before it sends a frame. [checked: candler-evaluator@0.1.0] - A part is served when any kind of the plug-in declares it in `needs`, as its kinds share one process. [checked: candler-evaluator@0.2.0] -- `read_trace` raises `ValidationError` at a line the schema refuses. [checked: candler-evaluator@0.2.0] +- `read_trace` checks lines, not order; `null` reads as absent. [checked: candler-evaluator@0.2.0] diff --git a/python/candler-evaluator/scripts/gen_models.py b/python/candler-evaluator/scripts/gen_models.py index 6fbbad61..a15a34d0 100644 --- a/python/candler-evaluator/scripts/gen_models.py +++ b/python/candler-evaluator/scripts/gen_models.py @@ -1,10 +1,11 @@ """Regenerate `src/candler_evaluator/_models/` from the published wire schemas. Run from `python/candler-evaluator`: `uv run --frozen python scripts/gen_models.py`. -One module per schema root: `evaluator-*.schema.json`, `outcome-record.schema.json` and `normalised-trace.schema.json` of -`crates/candler-schemas/schema/`. Each module's header names its schema file and the file's -sha256, so a changed schema shows as a changed header. The output is deterministic; CI -regenerates it and fails when it differs from what is committed. +One module per schema root: `evaluator-*.schema.json`, `outcome-record.schema.json` and +`normalised-trace.schema.json` of `crates/candler-schemas/schema/`. Each module's header +names its schema file and the file's sha256, so a changed schema shows as a changed +header. The output is deterministic; CI regenerates it and fails when it differs from what +is committed. """ from __future__ import annotations diff --git a/python/candler-evaluator/src/candler_evaluator/trace.py b/python/candler-evaluator/src/candler_evaluator/trace.py index d7c09f39..dfaaf713 100644 --- a/python/candler-evaluator/src/candler_evaluator/trace.py +++ b/python/candler-evaluator/src/candler_evaluator/trace.py @@ -16,8 +16,14 @@ def read_trace(trace: ServedFile | Path | str) -> Iterator[Any]: `trace` is `context.trace` or a path. A record is the header, a session or an event of `normalised-trace.schema.json`, held by the model of its `kind`. A line that is not JSON - or that the schema refuses, an unknown field included, raises `pydantic.ValidationError` - when the iterator reaches it; the records before it have been yielded. + or that the models refuse (an unknown field, a wrong type) raises + `pydantic.ValidationError` when the iterator reaches it; the records before it have been + yielded. A `null` on an optional field reads as absent, although the schema refuses it. + + It checks lines, not the file's order: an empty file, a missing or second header, a + `seq` gap, an event for an undeclared session and a `raw_ref` to a stream the header + does not list all pass. Candler checks the order when it writes the trace, and the + served copy is pinned by its sha256. """ from ._models.normalised_trace import TraceRecord From 29d6c925572bd4b0f75220cc9c9ac1a9e16a5a4d Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:20:10 +0900 Subject: [PATCH 58/93] reports(evaluator-helper): record the review and the RiVault trial Adds the review verdict with the ruling on each finding, the settled empty-line question, and the first implementation trial on RiVault. Left now holds the generator-wide null gap. Co-Authored-By: Claude Opus 5.5 --- .../run-context/leaves/helper_context_v0.md | 32 +++++++++++++++++-- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/__reports__/run-context/leaves/helper_context_v0.md b/__reports__/run-context/leaves/helper_context_v0.md index f08cf9da..32c9bf9b 100644 --- a/__reports__/run-context/leaves/helper_context_v0.md +++ b/__reports__/run-context/leaves/helper_context_v0.md @@ -8,7 +8,7 @@ The Step 2 commit subject in the leaf is 76 characters and the commit hook allow ## The reader's API -`RunContext` carries `trace` and `manifest` as `ServedFile(path, abs, sha256)` or `None`, and `raw` as a tuple of mappings with `stream`, `path` and `sha256` (empty when not served). `candler_evaluator.read_trace(context.trace)` (also a path) yields each line of the trace as the model of its `kind` generated from `normalised-trace.schema.json`, and raises `pydantic.ValidationError` at a line the schema refuses, an unknown field included. +`RunContext` carries `trace` and `manifest` as `ServedFile(path, abs, sha256)` or `None`, and `raw` as a tuple of mappings with `stream`, `path` and `sha256` (empty when not served). `candler_evaluator.read_trace(context.trace)` (also a path) yields each line of the trace as the model of its `kind` generated from `normalised-trace.schema.json`, and raises `pydantic.ValidationError` at a line its models refuse (not JSON, an unknown field, a wrong type). A `null` on an optional field reads as absent. It checks lines, not the file's order. ## Guards on the base (Step 1, `9292fd6f`) @@ -43,9 +43,35 @@ Removing `exclude_none` from only one of the two dumps leaves the guard green: t - The contract page's Notes hold 119 words (limit 120), each bullet stamped. - No Rust build was needed and none was run. +## Review + +Verdict of the independent review: every gate is met; one deviation, on the adversarial question (what the helper reads differently from the Rust reader). Three findings, each with its ruling: + +| Finding | Ruling | +|:--|:--| +| `read_trace` checks each line against the generated models only. An empty file, a missing or second header, a `seq` gap, an event for an undeclared session and a `raw_ref` naming an unlisted stream pass it; `TraceFile::read` in Rust refuses each. | Not added: a second implementation of the file rules would drift from the Rust one. The docstring now says it checks lines, not the file's order, and that Candler checks the order when it writes the trace (the served copy is pinned by its sha256). | +| The docstring and the contract Note said it refuses whatever the schema refuses. The generated optional fields are `X \| None = None`, so `"exit": null` or `"argv": null` read as absent although the schema refuses null. | Every sentence now says it raises at a line its models refuse (not JSON, an unknown field, a wrong type) and that a `null` on an optional field reads as absent. The generator is not changed in this leaf. The Note stays within 120 words (119); the detail is in the page's Surface prose and the docstring. | +| `scripts/gen_models.py` had a docstring line of 121 characters. | Wrapped. | + +The empty-line question is settled. Rust strips one trailing newline, so both readers refuse a blank line, and both accept CRLF. An empty file passes `read_trace` and is refused by Rust. + +## Implementation trial + +The leaf was first run on the RiVault alias `RiVault/RiVault/Reasoning-Large` (backing model XiaomiMiMo/MiMo-V2.6-Pro-RL) through OpenCode 1.18.23. + +| Measure | Value | +|:--|:--| +| Duration | 2946 s | +| Steps | 38 | +| Tool calls | bash 62, read 2, todowrite 1 | +| Tokens | input 81,996; output 7,564; reasoning 171,456; cache read 2,069,472 | +| Result | no file written, no commit made | + +Its last step spent 31,995 reasoning tokens and ended with `finish=length`. Reasoning-Medium had shown 0 reasoning tokens through OpenCode earlier and was not run on the leaf. Verdict: fail. The leaf was then implemented by Claude Sonnet. + ## Left -- The mandatory Sonnet review (a wire context or trace line the helper reads differently from the Rust reader) is for the coordinator to dispatch. -- Not checked against the Rust reader: an empty line in a trace file raises `ValidationError` in `read_trace`; whether the Rust reader tolerates one is not verified. +- Generated optional fields across all helper models, `Needs.raw` and `Needs.manifest` included, accept `null`, which the schema refuses. Fixing it is a generator-wide change, out of this leaf. +- The describe guard goes red only when both `exclude_none` dumps are removed. - `candler_evaluator.__init__` also exports `ServedFile` and `read_trace`; the generated `Needs.raw`/`Needs.manifest` stay `bool | None`, as the schema generator emits them. - The tag `candler-evaluator@0.2.0` is not cut. From 512a4edb3948ef87620d9aa7cc26e36c2e6096e0 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:20:52 +0900 Subject: [PATCH 59/93] rdm(evaluator-helper): close the stored run's parts in the helper Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/readers/README.md b/__roadmap__/run_context/readers/README.md index e9ed84d6..3a8ec19a 100644 --- a/__roadmap__/run_context/readers/README.md +++ b/__roadmap__/run_context/readers/README.md @@ -19,7 +19,7 @@ graph TD cc_reader_exit[Claude Code exit]:::done oc_reader_exit[OpenCode exit]:::done serve_context[Serve the run]:::done - helper_context[Helper context]:::inprogress + helper_context[Helper context]:::done e2e[Consumer path]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -34,7 +34,7 @@ graph TD | `cc_reader_exit.md` | 📄 Leaf Task | ✅ Done | | `oc_reader_exit.md` | 📄 Leaf Task | ✅ Done | | `serve_context.md` | 📄 Leaf Task | ✅ Done | -| `helper_context.md` | 📄 Leaf Task | 🔄 In Progress | +| `helper_context.md` | 📄 Leaf Task | ✅ Done | | `e2e/` | 📁 Directory | ⬜ Planned | ## Amendment Log From c5aac1d1d81a0d6ce015ff28dc2be19f66d29180 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:29:45 +0900 Subject: [PATCH 60/93] reports(evaluation): record the seam review after the readers Co-Authored-By: Claude Opus 5.5 --- __reports__/run-context/02-seam_review_v0.md | 68 ++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 __reports__/run-context/02-seam_review_v0.md diff --git a/__reports__/run-context/02-seam_review_v0.md b/__reports__/run-context/02-seam_review_v0.md new file mode 100644 index 00000000..8b1701ce --- /dev/null +++ b/__reports__/run-context/02-seam_review_v0.md @@ -0,0 +1,68 @@ +# Seam review after level 2 + +The review read `git diff origin/main...feat/run-context` at `512a4edb`, after all four level-2 leaves had merged. It was read-only and was briefed without the leaves' conclusions. It covered: + +- the seams between producers and consumers; +- the wording on what a plug-in is served; +- the codebase's idioms and waste; +- whether the docs are true. + +On that tip: + +- `cargo fmt --check`, clippy and `cargo doc` pass; +- `cargo nextest run --workspace` ran 737 tests: all passed, 32 skipped; +- the helper's `pytest` passes (18 tests). + +## Seams: nothing mismatched + +Every field, key, code and path agrees on both sides of each seam: + +- **`exit` (L1).** The schema refuses `null`. Neither reader writes it, and both write `exit` only on `tool_result`. +- **Served files.** The `{path, abs, sha256}` shape `assemble` writes is the one the helper's `ServedFile.from_wire` reads. +- **Context digest.** The keys `context_digest` adds are the ones `gen_live_context.py` and `gen_vectors.py` project. +- **Refusal code.** `evaluation.run_part_missing` is the same in `refusal.rs`, `codes.toml` and `index.md`. + +## What a plug-in is served + +The plan and several docs say a kind is served what it declares. The engine serves differently: + +- It builds one context per request. +- That context is the union of the needs of the kinds of the entries the request sends (`crates/candler-core/src/evaluation/engine/run.rs:620`, over `sendable`). +- Entries that are blocked, not applicable or already finished contribute nothing. + +So: + +- a plug-in is served the union of what the kinds of its sent entries declare; +- every kind in the request can read any part another one declared. + +The plan v0 (`00-plan_run_context_v0.md`, §Settled and §What a kind can see) and the done leaf `serve_context.md` are left as written, because they record what was approved and built. This note supersedes their sentences on what "a kind sees". The current docs, doc comments, contract pages, READMEs and the ruling note are corrected in the fix leaf below. + +## Rulings + +| # | Finding | Ruling | +|---|---|---| +| 1 | The `context_digest` doc says every path, relative included, is outside the digest, but the artifact `path` is in the projection (`evaluation.rs:1721`, `architecture.md:1054`) | Fix the wording | +| 2 | The helper's generated models read `null` on an optional field as absent, where the schema and the Rust reader refuse it. AGENTS.md calls a more lenient second reading a defect | Fix at the generator if it can make the models refuse `null` where the schema does with `pytest` green, guarded by a row seen red; otherwise stop and report. Keep the unbounded `int` for `code` against Rust's `i32` as a follow-up | +| 3 | Batching and outcome reuse: a kind that needs only artifacts is refused when a sibling entry in the same request needs a part the run lacks. Its context digest, and so its I4 key, also changes with which sibling entries were sent. Artifact globs already behaved this way; the served hashes make it matter more | Docs now: a Note on `evaluator-protocol.md` states that the context and its digest cover the union of the request, and that a missing part refuses the whole request. The design question is a follow-up for the maintainer | +| 4 | "Never served empty": every run stores `trace.jsonl`. A failed reader or a silent session leaves a header-only trace (`runner/exec/mod.rs:762`), which is served. `PartMissing` covers only runs that do not store the part | Fix the wording to "a part the run does not store"; the `Needs.trace` doc says a trace can hold a header alone | +| 5 | The `ContextArtifact.path` doc says "relative to the run". For an artifact it is relative to the outputs; for the trace and manifest, to the workspace root | Fix the wording, and the `ServedFile` docstring | +| 6 | `ContextRaw.path` is absolute while `ServedFile.path` is relative, and no doc says the raw streams are gzip-compressed | State both in the docs; no change to the shape | +| 7 | `Needs` ignores an unknown key in the Rust reader (schemars `deny_unknown_fields` without serde's) | Already open with the maintainer; unchanged here | +| 8 | Stale text: `architecture.md:1036` says "hard links or clones"; the `refusal_scope.tsv` note omits the missing-part refusal; the code's text omits the interrupted-run case | Fix the wording. `CorruptBlob` keeps its name, because the code is released | +| 9 | `crates/candler-harness-claude-code/tests/fixtures/digests.toml` is read by no code and names reader 0.2.0, and READMEs still describe it as a ratchet | Delete it, and the sentences | +| 10 | The OpenCode reader spells `"shell"` three times, where the Claude Code reader has `SHELL_TOOL` | One constant | +| 11 | In `guard_context_digest.rs`, the "trace path" and "manifest path" rows vary only `abs`, so the relative path is never varied | Vary the relative path, seen red under a bite that projects it | +| 12 | `evaluator-helper.md`'s Surface section is a paragraph, where CONTRIBUTING §Contract pages asks for one sentence | Back to one sentence; the README and the docstrings carry the API, as the page already says | +| 13 | The helper `CHANGELOG.md` says `read_trace` refuses "a line the schema refuses" | Make it true | +| 14 | The served rows' hashes come from the store, so the generator is independent only in the projection | Accepted by design: the hash of a stored file is the one thing the generator reads from the store | + +## Follow-ups + +- **The batching design for outcome reuse (ruling 3).** A kind's I4 key and its refusal depend on its sibling entries in a request. This is for the maintainer. +- **`Needs` unknown keys (ruling 7).** Open with the maintainer. +- **Python `ExitStatus.code` is unbounded, while Rust's is `i32`.** +- Carried from the leaves: + - the OpenCode signal name mapping; + - Claude Code hook denials, and OpenCode `permission.rejected`, read as denials; + - a guard against a stray file in `raw/`; + - writable modes on workspace directories. From 22659e8dece4c1fb4ec57122e382b0322d683b3f Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:32:49 +0900 Subject: [PATCH 61/93] docs(schemas): say what a request is served and where a path is relative The engine builds one context per request from the union of the needs of the kinds the request sends, so a part is served when a kind of the request needs it, not when "the kind" declares it. The Needs and RunContext docs now say so. Also corrected: the context digest holds an artifact's path, and only the trace and manifest paths, the root and the absolute paths are outside it. ContextArtifact.path is relative to the outputs for an artifact and to the root for the trace and the manifest. Raw stream paths are absolute and name gzip-compressed JSON lines. A trace can hold its header alone. Co-Authored-By: Claude Opus 5.5 --- .../evaluator-describe-result.schema.json | 10 +++--- .../evaluator-evaluate-params.schema.json | 14 ++++----- .../schema/evaluator-message.schema.json | 24 +++++++------- .../schema/evaluator-request-side.schema.json | 14 ++++----- crates/candler-schemas/src/evaluation.rs | 31 ++++++++++--------- 5 files changed, 47 insertions(+), 46 deletions(-) diff --git a/crates/candler-schemas/schema/evaluator-describe-result.schema.json b/crates/candler-schemas/schema/evaluator-describe-result.schema.json index 4f1ef82d..cfb2fe55 100644 --- a/crates/candler-schemas/schema/evaluator-describe-result.schema.json +++ b/crates/candler-schemas/schema/evaluator-describe-result.schema.json @@ -151,10 +151,10 @@ }, "Needs": { "additionalProperties": false, - "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent.", + "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A request is served the union of the needs of the kinds it sends, and a part the run does not store refuses the request.", "properties": { "artifacts": { - "description": "Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced.", + "description": "Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced.", "items": { "type": "string" }, @@ -169,7 +169,7 @@ }, "manifest": { "default": false, - "description": "Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process.", + "description": "Whether the check reads the run's manifest, served as `context.manifest` when a kind of the request needs it. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process.", "type": "boolean" }, "metadata": { @@ -181,7 +181,7 @@ }, "raw": { "default": false, - "description": "Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep.", + "description": "Whether the check reads the raw streams, served as `context.raw` when a kind of the request needs it. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep, each stored as gzip-compressed JSON lines (`.jsonl.gz`).", "type": "boolean" }, "snapshots": { @@ -192,7 +192,7 @@ "type": "array" }, "trace": { - "description": "Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage.", + "description": "Whether the check reads the normalised trace, served as `context.trace` when a kind of the request needs it. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. It holds its header alone when the reader failed or the session was silent.", "type": "boolean" } }, diff --git a/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json b/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json index 780f5bd0..3b6d8077 100644 --- a/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json +++ b/crates/candler-schemas/schema/evaluator-evaluate-params.schema.json @@ -60,7 +60,7 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", + "description": "One stored file of a run that the evaluator reads: its path, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", "properties": { "abs": { "description": "The absolute path of the file, valid where the evaluator runs.", @@ -68,7 +68,7 @@ }, "path": { "$ref": "#/$defs/RelPath", - "description": "The path of the file relative to the run." + "description": "The path of the file: relative to the run's outputs for an artifact, relative to the run's `root` for the trace and the manifest." }, "sha256": { "$ref": "#/$defs/Digest", @@ -87,7 +87,7 @@ "description": "One raw stream of a run: its name, the path where the evaluator reads it and its digest, written as an object with the strings `stream`, `path` and `sha256`.", "properties": { "path": { - "description": "The absolute path of the stream, valid where the evaluator runs.", + "description": "The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`).", "type": "string" }, "sha256": { @@ -613,7 +613,7 @@ }, "RunContext": { "additionalProperties": false, - "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", + "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when a kind of the request needs them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", "properties": { "artifacts": { "description": "The artifacts of the run.", @@ -631,7 +631,7 @@ }, "manifest": { "$ref": "#/$defs/ContextArtifact", - "description": "The manifest of the run, served when the kind needs it; absent otherwise." + "description": "The manifest of the run, served when a kind of the request needs it; absent otherwise." }, "metadata": { "additionalProperties": false, @@ -652,7 +652,7 @@ "type": "object" }, "raw": { - "description": "The raw streams of the run, served when the kind needs them; empty otherwise.", + "description": "The raw streams of the run, served when a kind of the request needs them; empty otherwise.", "items": { "$ref": "#/$defs/ContextRaw" }, @@ -675,7 +675,7 @@ }, "trace": { "$ref": "#/$defs/ContextArtifact", - "description": "The normalised trace, served when the kind needs it; absent otherwise." + "description": "The normalised trace, served when a kind of the request needs it; absent otherwise." } }, "required": [ diff --git a/crates/candler-schemas/schema/evaluator-message.schema.json b/crates/candler-schemas/schema/evaluator-message.schema.json index 1343adb1..6e8b41f6 100644 --- a/crates/candler-schemas/schema/evaluator-message.schema.json +++ b/crates/candler-schemas/schema/evaluator-message.schema.json @@ -74,7 +74,7 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", + "description": "One stored file of a run that the evaluator reads: its path, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", "properties": { "abs": { "description": "The absolute path of the file, valid where the evaluator runs.", @@ -82,7 +82,7 @@ }, "path": { "$ref": "#/$defs/RelPath", - "description": "The path of the file relative to the run." + "description": "The path of the file: relative to the run's outputs for an artifact, relative to the run's `root` for the trace and the manifest." }, "sha256": { "$ref": "#/$defs/Digest", @@ -101,7 +101,7 @@ "description": "One raw stream of a run: its name, the path where the evaluator reads it and its digest, written as an object with the strings `stream`, `path` and `sha256`.", "properties": { "path": { - "description": "The absolute path of the stream, valid where the evaluator runs.", + "description": "The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`).", "type": "string" }, "sha256": { @@ -506,10 +506,10 @@ }, "Needs": { "additionalProperties": false, - "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent.", + "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A request is served the union of the needs of the kinds it sends, and a part the run does not store refuses the request.", "properties": { "artifacts": { - "description": "Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced.", + "description": "Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced.", "items": { "type": "string" }, @@ -524,7 +524,7 @@ }, "manifest": { "default": false, - "description": "Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process.", + "description": "Whether the check reads the run's manifest, served as `context.manifest` when a kind of the request needs it. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process.", "type": "boolean" }, "metadata": { @@ -536,7 +536,7 @@ }, "raw": { "default": false, - "description": "Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep.", + "description": "Whether the check reads the raw streams, served as `context.raw` when a kind of the request needs it. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep, each stored as gzip-compressed JSON lines (`.jsonl.gz`).", "type": "boolean" }, "snapshots": { @@ -547,7 +547,7 @@ "type": "array" }, "trace": { - "description": "Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage.", + "description": "Whether the check reads the normalised trace, served as `context.trace` when a kind of the request needs it. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. It holds its header alone when the reader failed or the session was silent.", "type": "boolean" } }, @@ -1172,7 +1172,7 @@ }, "RunContext": { "additionalProperties": false, - "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", + "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when a kind of the request needs them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", "properties": { "artifacts": { "description": "The artifacts of the run.", @@ -1190,7 +1190,7 @@ }, "manifest": { "$ref": "#/$defs/ContextArtifact", - "description": "The manifest of the run, served when the kind needs it; absent otherwise." + "description": "The manifest of the run, served when a kind of the request needs it; absent otherwise." }, "metadata": { "additionalProperties": false, @@ -1211,7 +1211,7 @@ "type": "object" }, "raw": { - "description": "The raw streams of the run, served when the kind needs them; empty otherwise.", + "description": "The raw streams of the run, served when a kind of the request needs them; empty otherwise.", "items": { "$ref": "#/$defs/ContextRaw" }, @@ -1234,7 +1234,7 @@ }, "trace": { "$ref": "#/$defs/ContextArtifact", - "description": "The normalised trace, served when the kind needs it; absent otherwise." + "description": "The normalised trace, served when a kind of the request needs it; absent otherwise." } }, "required": [ diff --git a/crates/candler-schemas/schema/evaluator-request-side.schema.json b/crates/candler-schemas/schema/evaluator-request-side.schema.json index 748f8107..d5b23462 100644 --- a/crates/candler-schemas/schema/evaluator-request-side.schema.json +++ b/crates/candler-schemas/schema/evaluator-request-side.schema.json @@ -60,7 +60,7 @@ }, "ContextArtifact": { "additionalProperties": false, - "description": "One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", + "description": "One stored file of a run that the evaluator reads: its path, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape.", "properties": { "abs": { "description": "The absolute path of the file, valid where the evaluator runs.", @@ -68,7 +68,7 @@ }, "path": { "$ref": "#/$defs/RelPath", - "description": "The path of the file relative to the run." + "description": "The path of the file: relative to the run's outputs for an artifact, relative to the run's `root` for the trace and the manifest." }, "sha256": { "$ref": "#/$defs/Digest", @@ -87,7 +87,7 @@ "description": "One raw stream of a run: its name, the path where the evaluator reads it and its digest, written as an object with the strings `stream`, `path` and `sha256`.", "properties": { "path": { - "description": "The absolute path of the stream, valid where the evaluator runs.", + "description": "The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`).", "type": "string" }, "sha256": { @@ -735,7 +735,7 @@ }, "RunContext": { "additionalProperties": false, - "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", + "description": "What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when a kind of the request needs them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort.", "properties": { "artifacts": { "description": "The artifacts of the run.", @@ -753,7 +753,7 @@ }, "manifest": { "$ref": "#/$defs/ContextArtifact", - "description": "The manifest of the run, served when the kind needs it; absent otherwise." + "description": "The manifest of the run, served when a kind of the request needs it; absent otherwise." }, "metadata": { "additionalProperties": false, @@ -774,7 +774,7 @@ "type": "object" }, "raw": { - "description": "The raw streams of the run, served when the kind needs them; empty otherwise.", + "description": "The raw streams of the run, served when a kind of the request needs them; empty otherwise.", "items": { "$ref": "#/$defs/ContextRaw" }, @@ -797,7 +797,7 @@ }, "trace": { "$ref": "#/$defs/ContextArtifact", - "description": "The normalised trace, served when the kind needs it; absent otherwise." + "description": "The normalised trace, served when a kind of the request needs it; absent otherwise." } }, "required": [ diff --git a/crates/candler-schemas/src/evaluation.rs b/crates/candler-schemas/src/evaluation.rs index 0d4d7596..2ee054c2 100644 --- a/crates/candler-schemas/src/evaluation.rs +++ b/crates/candler-schemas/src/evaluation.rs @@ -1332,21 +1332,21 @@ pub struct EvaluatorEnvironment { object_only!(EvaluatorEnvironment); -/// What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. +/// What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A request is served the union of the needs of the kinds it sends, and a part the run does not store refuses the request. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(remote = "Self")] #[schemars(deny_unknown_fields)] #[non_exhaustive] pub struct Needs { - /// Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. + /// Whether the check reads the normalised trace, served as `context.trace` when a kind of the request needs it. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. It holds its header alone when the reader failed or the session was silent. pub trace: bool, - /// Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep. + /// Whether the check reads the raw streams, served as `context.raw` when a kind of the request needs it. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep, each stored as gzip-compressed JSON lines (`.jsonl.gz`). #[serde(default)] pub raw: bool, - /// Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process. + /// Whether the check reads the run's manifest, served as `context.manifest` when a kind of the request needs it. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process. #[serde(default)] pub manifest: bool, - /// Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced. + /// Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced. pub artifacts: Vec, /// 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 @@ -1542,7 +1542,7 @@ impl DescribeResultBuilder { pub struct ContextRaw { /// The name of the raw stream. pub stream: StreamName, - /// The absolute path of the stream, valid where the evaluator runs. + /// The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`). pub path: String, /// The digest of the stream's bytes. pub sha256: Digest, @@ -1562,13 +1562,13 @@ impl ContextRaw { } } -/// One stored file of a run that the evaluator reads: its path relative to the run, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape. +/// One stored file of a run that the evaluator reads: its path, where the evaluator reads it and its digest, written as an object with the strings `path`, `abs` and `sha256`. The artifacts, `RunContext.trace` and `RunContext.manifest` have this shape. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(remote = "Self")] #[schemars(deny_unknown_fields)] #[non_exhaustive] pub struct ContextArtifact { - /// The path of the file relative to the run. + /// The path of the file: relative to the run's outputs for an artifact, relative to the run's `root` for the trace and the manifest. pub path: RelPath, /// The absolute path of the file, valid where the evaluator runs. pub abs: String, @@ -1610,7 +1610,7 @@ impl ContextRef { } } -/// What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort. +/// What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when a kind of the request needs them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort. #[derive(Deserialize, JsonSchema)] #[schemars(deny_unknown_fields, rename = "RunContext")] struct RawRunContext { @@ -1618,13 +1618,13 @@ struct RawRunContext { run: RunKey, /// The absolute path of the run's directory, valid where the evaluator runs. root: String, - /// The normalised trace, served when the kind needs it; absent otherwise. + /// The normalised trace, served when a kind of the request needs it; absent otherwise. #[serde(default, deserialize_with = "present")] trace: Option, - /// The manifest of the run, served when the kind needs it; absent otherwise. + /// The manifest of the run, served when a kind of the request needs it; absent otherwise. #[serde(default, deserialize_with = "present")] manifest: Option, - /// The raw streams of the run, served when the kind needs them; empty otherwise. + /// The raw streams of the run, served when a kind of the request needs them; empty otherwise. raw: Vec, /// The artifacts of the run. artifacts: Vec, @@ -1646,7 +1646,7 @@ impl TryFrom> for RunContext { } } -/// What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when the run serves them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort. +/// What an evaluator may read of one run, written as an object: the run's key and root directory, the trace and the manifest when a kind of the request needs them, the raw streams, the artifacts, the snapshots, the inputs and the metadata. Every list and the metadata are present, empty when there is nothing of that sort. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(try_from = "MapOnly")] #[non_exhaustive] @@ -1718,8 +1718,9 @@ impl RunContext { /// `raw` is `[{stream, sha256}]` sorted by `stream` by code point, present when there is a /// raw stream. /// - /// The run key, the root and the paths of every file, absolute or relative, are outside it, - /// so moving a run to another directory keeps its digest. + /// The run key, the root, every absolute path and the relative paths of the trace and the + /// manifest are outside it, so moving a run to another directory keeps its digest. An + /// artifact's `path` is inside it. #[must_use] pub fn context_digest(&self) -> Digest { // BORROW: .clone() hands out the digest computed when the context was built From ffccb3b79e83c99983cebe6470ea9292c6dfb762 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:33:40 +0900 Subject: [PATCH 62/93] docs(evaluation): say a request is served the union of its kinds' needs The context is built once per request over the entries it sends, so a part is served when a kind of the request needs it. The assemble doc and the architecture now say that, and that a part the run does not store refuses the request while a header-only trace is served as stored. Also corrected in the architecture: the served files are private copies, not hard links or clones; the digest holds an artifact's path; paths are relative to the outputs for an artifact, to the root for the trace and manifest, and absolute for a raw stream. The refusal text of evaluation.run_part_missing names a run sealed after an interruption. Co-Authored-By: Claude Opus 5.5 --- __design__/architecture.md | 16 ++++++++++------ .../src/evaluation/context/assemble.rs | 13 +++++++------ crates/candler-core/src/evaluation/refusal.rs | 2 +- docs/contract/index.md | 2 +- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/__design__/architecture.md b/__design__/architecture.md index fc91e924..a899dede 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -1026,17 +1026,20 @@ as the evaluator's log. | ↳ result | | response | `{reported: n}` | | `cancel` | core → evaluator | notification | request id; the evaluator answers `evaluate` with error `-32800` (request cancelled) | -**`needs`** = `{trace: bool, raw: bool, manifest: bool, artifacts[] (run-relative globs), +**`needs`** = `{trace: bool, raw: bool, manifest: bool, artifacts[] (globs relative to the run's outputs), snapshots[] (kinds), inputs[] (kinds), metadata[] (run-manifest field paths)}`; `raw` and `manifest` read as `false` when absent. `resolve` checks every need the core can meet without a run; an `inputs` need for `build_inputs` is refused there, by name. A need a run cannot meet, such as a kind the run holds in neither list, is refused for that run, by name. +The core builds one context per request, from the union of the needs of the kinds the request +sends; a part the run does not store refuses the whole request. **Run context:** `run` (key); `root` (a read-only, workspace-shaped view of the run: content- -addressed blobs materialised under their workspace paths by hard links or clones, so `domain.py` +addressed blobs materialised under their workspace paths as private copies, so `domain.py` sits beside `problems.py`); `trace {path, abs, sha256}` (the normalised trace file) and `manifest {path, abs, sha256}` -(the run manifest), each present only when the kind needs it; `raw[] {stream, path, sha256}`; -`artifacts[] {path (run-relative), abs, sha256}`; `snapshots[] {kind, path, digest}`; `inputs[] {kind, path, digest}` +(the run manifest), each present only when a kind of the request needs it, with `path` relative to `root`; +`raw[] {stream, path, sha256}` (`path` absolute; the stream is gzip-compressed JSON lines, `.jsonl.gz`); +`artifacts[] {path (relative to the run's outputs), abs, sha256}`; `snapshots[] {kind, path, digest}`; `inputs[] {kind, path, digest}` (a need for kind K is served from `comparable.inputs` or from `evaluation_inputs`, with `path` a read-only tree: its files read-only, its directories writable, as under `outputs/`; an input only the evaluators see never enters the isolation, I8); `metadata` (the declared manifest fields). Absolute paths are valid where the @@ -1054,8 +1057,9 @@ them as optional is released. by `(kind, digest)`, every key present (lists possibly empty). Each served part adds a key, and only when it is served: `trace` (its sha256), `raw` (`[{stream, sha256}]` sorted by `stream`) and `manifest` (its sha256), so a context that serves none of them has the digest of the - projection above. Absolute paths, run-relative paths of served files, `root` and `scratch` are - outside it: they say where the run is, not what was graded. + projection above. The run key, `root`, `scratch`, every absolute path and the relative paths + of the trace and the manifest are outside it: they say where the run is, not what was graded. + An artifact's `path` is inside it. - `suite_entry_digest` covers `{kind, params, role, depends_on, applies_to?}` of one suite entry: `depends_on` sorted, `applies_to` omitted when absent. `id`, `group`, `evaluator` and `deadline_ms` are outside it, so renaming an expectation or moving its deadline keeps its digest. diff --git a/crates/candler-core/src/evaluation/context/assemble.rs b/crates/candler-core/src/evaluation/context/assemble.rs index 4f9d9218..337e0820 100644 --- a/crates/candler-core/src/evaluation/context/assemble.rs +++ b/crates/candler-core/src/evaluation/context/assemble.rs @@ -115,9 +115,9 @@ impl Assembled { /// Chooses the stored files and the metadata of the sealed run `run` that `needs` name. /// -/// A context serves exactly what the needs declare. The engine builds one context per plug-in -/// request from the union of its kinds' needs, so what a plug-in is served is what any of its -/// kinds declares in `describe`. The artifacts are the files of the run's +/// A context serves exactly what the needs name. The engine builds one context per request, from +/// the union of the needs of the kinds of the entries the request sends, so a part is served +/// when a kind of the request needs it. The artifacts are the files of the run's /// stored `outputs/` that the file rule keeps for the artifact globs, by path relative to /// `outputs/`. There is one metadata entry per metadata need, keyed by the dotted path, holding /// the JSON leaf of the manifest's `comparable.values`. There is one input per input need: the @@ -125,9 +125,10 @@ impl Assembled { /// and the files are those of the input's list blob. The trace need serves the stored /// `trace.jsonl`, the raw need serves every stored `raw/.jsonl.gz`, and the manifest need /// serves the stored `manifest.json`; each is hashed here, at assembly, and its copy is checked -/// against that hash. A need the run cannot meet is refused and is never served empty: a trace or -/// raw need on a run that stores none, an input the run lacks, a metadata path with no value, and -/// snapshots. A run holds its manifest from the moment its directory exists, so that need has no +/// against that hash. A need the run cannot meet is refused: a trace or raw need on a run that +/// does not store that part, an input the run lacks, a metadata path with no value, and +/// snapshots. A stored trace can hold its header alone, as when the reader failed or the session +/// was silent, and it is served as stored. A run holds its manifest from the moment its directory exists, so that need has no /// refusal of its own. An `outputs/` with no files gives no artifacts and is not an error. /// /// # Errors diff --git a/crates/candler-core/src/evaluation/refusal.rs b/crates/candler-core/src/evaluation/refusal.rs index 1102ffab..dddfc05b 100644 --- a/crates/candler-core/src/evaluation/refusal.rs +++ b/crates/candler-core/src/evaluation/refusal.rs @@ -155,7 +155,7 @@ wrapper_table! { PartMissing { .. } => row( "evaluation.run_part_missing", Side::Plugin, - "A kind needs the trace or the raw streams of a run that stores none, as an imported run whose harness frames the importer could not read.", + "A kind needs the trace or the raw streams of a run that does not store them, as an imported run whose harness frames the importer could not read, or a run sealed after an interruption.", "-", ), MissingMetadata { .. } => row( diff --git a/docs/contract/index.md b/docs/contract/index.md index 6c18776c..a8eccb6b 100644 --- a/docs/contract/index.md +++ b/docs/contract/index.md @@ -102,7 +102,7 @@ Surfaces that name no page of their own: configuration, resolving, running, isol | `evaluation.metadata_missing` | A kind needs a metadata path that the run manifest does not hold, or holds without a value. | - | plugin | | `evaluation.need_unsupported` | The needs of a kind ask for something this version of Candler does not supply, such as snapshots. | - | plugin | | `evaluation.run_not_sealed` | A run selected for evaluation has no `run.done` seal, so it can still change. | - | environment | -| `evaluation.run_part_missing` | A kind needs the trace or the raw streams of a run that stores none, as an imported run whose harness frames the importer could not read. | - | plugin | +| `evaluation.run_part_missing` | A kind needs the trace or the raw streams of a run that does not store them, as an imported run whose harness frames the importer could not read, or a run sealed after an interruption. | - | plugin | | `evaluation.run_selection_invalid` | The selection of runs is not a glob. | - | config | | `evaluation.state_home_unset` | Neither `XDG_STATE_HOME` nor `HOME` is set, so the environments of plug-ins have no home. | - | environment | | `evaluation.suite_changed` | The suite file of an evaluate job changed between the launcher reading it and the supervisor running the job, so the job refuses to grade with another suite. | - | suite | From 5ae62538df08574199e1cba6e978ef953faffbd6 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:33:40 +0900 Subject: [PATCH 63/93] reports(evaluation): correct the trace ruling on who is served a part The request, not the plug-in's kinds taken alone, decides what is served: the union of the needs of the kinds the request sends. A header-only trace is stored and served, and a missing part refuses the whole request. Co-Authored-By: Claude Opus 5.5 --- .../run-context/01-ruling_trace_served_v0.md | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/__reports__/run-context/01-ruling_trace_served_v0.md b/__reports__/run-context/01-ruling_trace_served_v0.md index 37bc63cd..6df9cf7f 100644 --- a/__reports__/run-context/01-ruling_trace_served_v0.md +++ b/__reports__/run-context/01-ruling_trace_served_v0.md @@ -3,9 +3,9 @@ ## What is replaced The M2a ruling for `run_context` (`__reports__/m2a-evaluation-parity/l1/00-rulings_v0.md:75`) -accepted "`needs.trace` is ignored". That ruling is replaced. A kind that declares `needs.trace`, -`needs.raw` or `needs.manifest` is handed the stored file, and the context says which one by its -digest. +accepted "`needs.trace` is ignored". That ruling is replaced. When a kind of a request declares +`needs.trace`, `needs.raw` or `needs.manifest`, the request is handed the stored file, and the +context says which one by its digest. ## Why @@ -13,21 +13,23 @@ digest. disk" cannot hold while a declared need for the trace is accepted and dropped. AGENTS.md calls a second, more lenient reading of a declaration a defect even when nothing reaches it yet; ignoring a declared need is that reading. -- **The declaration states what a plug-in is served.** Candler has no blinding concept. A kind - lists its needs in `describe`, and the engine builds one context per plug-in request from the - union of its kinds' needs, so what a plug-in is served is the union of what its kinds declare. - A plug-in is one process, so its kinds share what it was served. Candler serves exactly that and - refuses what it cannot serve, so what a plug-in was served is on record in its kinds' - declarations. Serving the trace adds no hidden channel. +- **The declarations state what a plug-in is served.** Candler has no blinding concept. A kind + lists its needs in `describe`, and the engine builds one context per request from the union of + the needs of the kinds of the entries the request sends, so what a plug-in is served is the + union of what those kinds declare. Every kind in the request can read any part another one + declared. Candler serves exactly that and refuses what it cannot serve, so what a plug-in was + served is on record in the declarations of the kinds it was sent. Serving the trace adds no + hidden channel. - **A sealed run never changes.** "Sealed" means complete and protected from overwrite, so the digest taken when a stored file is chosen for a context holds for the whole evaluation, and the outcome-reuse key can carry it. ## What follows -- A part the run lacks (the trace or the raw streams of a run the importer could not read, or of a - run sealed after an interruption) is refused with `ContextError::PartMissing`, code - `evaluation.run_part_missing`, and never served empty. The manifest is written when the run - directory is made, so every run holds it. +- A part the run does not store (the trace or the raw streams of a run the importer could not + read, or of a run sealed after an interruption) is refused with `ContextError::PartMissing`, + code `evaluation.run_part_missing`, and the whole request is refused with it. A stored trace can + hold its header alone, when the reader failed or the session was silent, and it is served as + stored. The manifest is written when the run directory is made, so every run holds it. - Every stored file reaches a workspace through one copy routine, so a served part has the guarantees an artifact has: a private copy, `0444`, checked against its digest. From 9a40663e047eb70e13e82c4e7ca04808a168aa9c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:33:40 +0900 Subject: [PATCH 64/93] rdm(evaluation): note the missing-part refusal in the refusal scope ContextError also refuses a trace or raw need on a run that does not store the part; the scope note listed the other author-facing refusals and omitted it. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m3-lean-cli/refusal_scope.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/__roadmap__/m3-lean-cli/refusal_scope.tsv b/__roadmap__/m3-lean-cli/refusal_scope.tsv index 75c3375a..724b1849 100644 --- a/__roadmap__/m3-lean-cli/refusal_scope.tsv +++ b/__roadmap__/m3-lean-cli/refusal_scope.tsv @@ -1,6 +1,6 @@ enum file variants author side section leaf note candler_core::evaluation::client::ClientError crates/candler-core/src/evaluation/client/mod.rs 5 mixed plugin evaluation refusal_late author-facing: Spawn (evaluator will not start), Cancelled, Describe failure; internal: Pipes, Encode -candler_core::evaluation::context::ContextError crates/candler-core/src/evaluation/context/mod.rs 11 mixed plugin evaluation refusal_late author-facing: glob invalid, unsupported need, input kind, metadata path, workspace; internal: Build, Store wrappers +candler_core::evaluation::context::ContextError crates/candler-core/src/evaluation/context/mod.rs 11 mixed plugin evaluation refusal_late author-facing: glob invalid, unsupported need, input kind, metadata path, missing trace or raw part, workspace; internal: Build, Store wrappers candler_core::evaluation::engine::EvaluateError crates/candler-core/src/evaluation/engine/mod.rs 9 mixed plugin evaluation refusal_late author-facing: env not ready, Registry, suite invalid, run glob, Plan, plug-in; internal: Task; transparent Store candler_core::evaluation::engine::plan::PlanError crates/candler-core/src/evaluation/engine/plan.rs 3 yes suite evaluation refusal_late suite dependency cycle, unknown dependency candler_core::evaluation::registry::RegistryError crates/candler-core/src/evaluation/registry/mod.rs 13 yes plugin evaluation refusal_late plug-in manifest, evaluator, kind, params, no state home From 18a05a034ac300249abc9fa9c53a80968a3e6871 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:35:00 +0900 Subject: [PATCH 65/93] test(adapter-claude-code): drop the digests file no test reads digests.toml named reader 0.2.0 and the old digests, and no code reads it, so it guarded nothing. The two READMEs described it as a ratchet and the guard table listed a ratchet of trace digests; both sentences go with it. Co-Authored-By: Claude Opus 5.5 --- crates/candler-harness-claude-code/README.md | 4 ++-- .../tests/fixtures/README.md | 6 +----- .../tests/fixtures/digests.toml | 15 --------------- 3 files changed, 3 insertions(+), 22 deletions(-) delete mode 100644 crates/candler-harness-claude-code/tests/fixtures/digests.toml diff --git a/crates/candler-harness-claude-code/README.md b/crates/candler-harness-claude-code/README.md index c3fa5693..860c94b9 100644 --- a/crates/candler-harness-claude-code/README.md +++ b/crates/candler-harness-claude-code/README.md @@ -30,10 +30,10 @@ and how each session ended) and `usage` (token counts and their sums) are privat | File | Pins | |---|---| -| `tests/guard_reader.rs` | the reader against the streams of `tests/fixtures/streams/`: facts, citation, usage, the version table, replay, and the ratchet of trace digests | +| `tests/guard_reader.rs` | the reader against the streams of `tests/fixtures/streams/`: facts, citation, usage, the version table and replay | | `tests/guard_fixture_provenance.rs` | every fixture file is listed in `tests/fixtures/PROVENANCE.toml` with a hash that recomputes | -`tests/fixtures/` holds the streams, `PROVENANCE.toml`, the expected digests in `digests.toml`, the +`tests/fixtures/` holds the streams, `PROVENANCE.toml`, the scripts that select or write the streams, and its own README. ```sh diff --git a/crates/candler-harness-claude-code/tests/fixtures/README.md b/crates/candler-harness-claude-code/tests/fixtures/README.md index eac25f6f..33a4f0e0 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/README.md +++ b/crates/candler-harness-claude-code/tests/fixtures/README.md @@ -10,7 +10,7 @@ Nine streams feed `guard_reader`. Each lives in `streams//` with `expected | `mini_clean`, `mini_incomplete`, `mini_zero_mappings` | the `candler-core` mini-corpus, named by relative path in `expected.toml`; no copy here | | `synthetic_hooks`, `synthetic_mcp`, `synthetic_orphans` | `make_synthetic.py`, from Claude Code's documented stream-json shapes | -`PROVENANCE.toml` lists the sha256 of every file here except itself and `digests.toml`. +`PROVENANCE.toml` lists the sha256 of every file here except itself. `guard_fixture_provenance` recomputes each hash and refuses an unlisted file. ## Regenerate @@ -23,7 +23,3 @@ python3 make_synthetic.py # usage totals of one stream gzip -dc streams//agent_stream.jsonl.gz | jq -nrR -f usage_totals.jq > streams//usage_totals.toml ``` - -`digests.toml` is a ratchet over the trace file of each stream, blessed with -`CANDLER_BLESS_DIGESTS=1 cargo nextest run -p candler-harness-claude-code -E 'test(/^guard_reader::/)'`. -It refuses to rewrite an existing line unless the reader version changed. diff --git a/crates/candler-harness-claude-code/tests/fixtures/digests.toml b/crates/candler-harness-claude-code/tests/fixtures/digests.toml deleted file mode 100644 index 21c94c40..00000000 --- a/crates/candler-harness-claude-code/tests/fixtures/digests.toml +++ /dev/null @@ -1,15 +0,0 @@ -# Digest of the trace file each fixture stream gives ClaudeCodeReader. A ratchet against unnoticed -# change that proves nothing about correctness. Bless with CANDLER_BLESS_DIGESTS=1; blessing refuses -# to change a line unless the reader version below changed. -reader = "claude-code-stream-json@0.2.0" - -[digests] -api_error = "33a9ff0bf40b0a72c46ada690b183ea96350ff3b42f4676f4e36747a6b01875a" -mini_clean = "af830a88f54002ec6577d9230579b41ea02ed9dbd131c5571a1eea62c1e4d057" -mini_incomplete = "a09a52435d29ec7af7075c511fbb4757e59ffcf8a55684d7a9bdb91614446f04" -mini_zero_mappings = "24a8533417f8ec70796b811d1de8a47d04853ed3e6b5ca1dfe904e8c95e6d30d" -multi_init = "c44493197d669f358126d91fe23a36feb2e4d85b1ede57e9a8692c7bef2b97af" -subagent_denials = "563efaf5813fc1faa4683f8e49a6986d0ff3148113e44b9a76d5a9d3c97a9186" -synthetic_hooks = "be33b2813ead66932c4eea262c70bcecd9b5e98c1a88416ad4ccaf5bff6d2895" -synthetic_mcp = "018f342ed7717d4fa82765be16df23efb002ac84b237773fb5acf5ee248748d5" -synthetic_orphans = "666016df76ad90fb7da6b3ccc3add33e75e3e9bc1a8da1c8ad9ff75c1cb49344" From f36661fe5fc0fffaba13fbdcaa05887acb1b073c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:35:00 +0900 Subject: [PATCH 66/93] refactor(adapter-opencode): name the shell tool once The reader spelled "shell" three times and the preparer once, as the Claude Code reader has SHELL_TOOL for its own. One constant now names the tool the exit and the command line belong to. Co-Authored-By: Claude Opus 5.5 --- crates/candler-harness-opencode/src/export.rs | 9 ++++++--- crates/candler-harness-opencode/src/prepare.rs | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/candler-harness-opencode/src/export.rs b/crates/candler-harness-opencode/src/export.rs index d7853889..e6875971 100644 --- a/crates/candler-harness-opencode/src/export.rs +++ b/crates/candler-harness-opencode/src/export.rs @@ -21,6 +21,9 @@ use serde_json::{Map, Value}; use crate::{EXPORT_READER_VERSION, VALIDATED, session_source}; use candler_schemas::name; +/// The name of the shell tool, the only one whose result reports an exit. +pub(crate) const SHELL_TOOL: &str = "shell"; + /// The tools `OpenCode` offers the model by itself, as `opencode_facts` listed them. const BUILTIN_TOOLS: [&str; 12] = [ "edit", @@ -28,7 +31,7 @@ const BUILTIN_TOOLS: [&str; 12] = [ "grep", "question", "read", - "shell", + SHELL_TOOL, "skill", "subagent", "webfetch", @@ -182,7 +185,7 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>, servers: &[String] let name = text(block, "name").unwrap_or_default(); let state = field(block, "state"); let input = state.and_then(|state| field(state, "input")); - let argv = (name == "shell") + let argv = (name == SHELL_TOOL) .then(|| { input .and_then(|input| text(input, "command")) @@ -194,7 +197,7 @@ fn tool_drafts(block: &Value, message_at: Option<&Timestamp>, servers: &[String] // an error state, that reported none (a timeout reports a signal name and no code), or that is // not `shell` has none; so has one whose `exit` is not an `i32`, dropped as the reader drops // any other malformed harness field. - let exit = (name == "shell" && status == Some("completed")) + let exit = (name == SHELL_TOOL && status == Some("completed")) .then(|| { state .and_then(|state| field(state, "metadata")) diff --git a/crates/candler-harness-opencode/src/prepare.rs b/crates/candler-harness-opencode/src/prepare.rs index 271f9697..b91cac65 100644 --- a/crates/candler-harness-opencode/src/prepare.rs +++ b/crates/candler-harness-opencode/src/prepare.rs @@ -20,6 +20,8 @@ use candler_schemas::primitives::{FieldPath, RelPath}; use candler_schemas::servers::{McpServer, McpServerKind}; use serde_json::{Map, Value, json}; +use crate::export::SHELL_TOOL; + /// The provider's id in the configuration and in `-m /`. pub(crate) const PROVIDER: &str = "candler"; @@ -96,7 +98,7 @@ const EFFORT_MODEL: &str = "`OpenCode` gives a model a reasoning effort only for /// `shell.ts`, `read.ts`, `webfetch.ts`, `websearch.ts`, `subagent.ts`, `skill.ts`, `todo.ts`). /// A name with no row (`NotebookEdit`, `MultiEdit`, any other) is refused rather than guessed. const TOOLS: [(&str, &str); 11] = [ - ("Bash", "shell"), + ("Bash", SHELL_TOOL), ("Edit", "edit"), ("Write", "edit"), ("Read", "read"), From 91de6f300737dbfa516b9bb41543d52a609970ea Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:35:00 +0900 Subject: [PATCH 67/93] test(schemas): vary the relative path of the served trace and manifest The rows "trace path" and "manifest path" changed only abs, so a digest that depended on the relative path of either would have passed. Two rows now vary the relative path. Under a bite that adds the path to the projection when it differs from the usual name, the trace row fails with "changing the trace relative path keeps the digest". Co-Authored-By: Claude Opus 5.5 --- .../candler-schemas/tests/it/guard_context_digest.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/candler-schemas/tests/it/guard_context_digest.rs b/crates/candler-schemas/tests/it/guard_context_digest.rs index 9e7fce8f..4044ac2e 100644 --- a/crates/candler-schemas/tests/it/guard_context_digest.rs +++ b/crates/candler-schemas/tests/it/guard_context_digest.rs @@ -364,6 +364,8 @@ fn read_context(wire: Value) -> RunContext { /// holds the contexts that serve none of the parts. /// Bite: the trace key added when not served turns the rows of `context_digest.toml` red; the key /// left out when served turns the served rows red. +/// A relative path of the trace or the manifest added to the projection when it differs from its +/// usual name turns the rows that vary the relative path red. #[test] fn the_digest_of_a_context_adds_a_key_for_each_served_part_and_only_for_those() { let cases = vectors(SERVED_VECTORS); @@ -407,13 +409,19 @@ fn the_digest_of_a_context_adds_a_key_for_each_served_part_and_only_for_those() read_context(wire).context_digest() }; let base = read_context(wire_context(&all)).context_digest(); - let keeps: [(&str, WireEdit); 4] = [ + let keeps: [(&str, WireEdit); 6] = [ ("trace path", |w| { w["trace"]["abs"] = Value::from("/elsewhere/trace.jsonl"); }), + ("trace relative path", |w| { + w["trace"]["path"] = Value::from("elsewhere/trace.jsonl"); + }), ("manifest path", |w| { w["manifest"]["abs"] = Value::from("/elsewhere/manifest.json"); }), + ("manifest relative path", |w| { + w["manifest"]["path"] = Value::from("elsewhere/manifest.json"); + }), ("raw path", |w| { w["raw"][0]["path"] = Value::from("/elsewhere/stdout.jsonl.gz"); }), From f0c3e081535f77c85e0abfc6d89fa69778db6a1b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:35:44 +0900 Subject: [PATCH 68/93] docs(evaluator-protocol): note that a request's kinds share one context The engine builds one context per request over the kinds of the entries it sends, so a kind that needs only artifacts is refused when a sibling entry in the same request needs a part the run does not store, and its context digest follows which siblings were sent. The page now says so in one Note, within the Notes budget. Co-Authored-By: Claude Opus 5.5 --- docs/contract/evaluator-protocol.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/contract/evaluator-protocol.md b/docs/contract/evaluator-protocol.md index 0eb879e5..9ebf9a7f 100644 --- a/docs/contract/evaluator-protocol.md +++ b/docs/contract/evaluator-protocol.md @@ -538,3 +538,4 @@ Wire line: `schemas@0.13.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] +- Context and digest cover the request's kinds together; a part the run lacks refuses the request. [checked: v@0.16.0] From 6753af9bbe83484fb593ee83746d142ff0047d10 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:38:44 +0900 Subject: [PATCH 69/93] fix(evaluator-helper): refuse null on an optional field of a wire model The schema refuses null on an optional field, and so does Candler's reader, but the generated models read it as absent: read_trace took a tool_result with "exit": null. The generator now types an optional field as X | MISSING (--use-missing-sentinel), so the field can be left out and null is refused. This needs pydantic.MISSING, so the floor is pydantic 2.14, and the lock follows. A plug-in that declares null for a need is now refused with error -32000 naming it, instead of read as absent; the guard on describe needs says so. A new guard refuses a trace line with "exit": null, and fails on the old models with "DID NOT RAISE ValidationError". The README, the read_trace docstring, the changelog and the helper contract page say what a request is served and what read_trace refuses; the page's Surface is one sentence again. BREAKING CHANGE: a plug-in that declared null for a need, or fed read_trace a null on an optional field, is refused; leave the key out. Co-Authored-By: Claude Opus 5.5 --- docs/contract/evaluator-helper.md | 10 +-- python/candler-evaluator/CHANGELOG.md | 8 +- python/candler-evaluator/README.md | 14 ++-- python/candler-evaluator/pyproject.toml | 2 +- .../candler-evaluator/scripts/gen_models.py | 11 ++- .../_models/evaluator_describe_result.py | 24 +++--- .../_models/evaluator_evaluate_params.py | 49 +++++++------ .../_models/evaluator_message.py | 73 ++++++++++--------- .../_models/evaluator_notification.py | 26 +++---- .../_models/evaluator_request_side.py | 49 +++++++------ .../_models/normalised_trace.py | 64 ++++++++-------- .../_models/outcome_record.py | 26 +++---- .../src/candler_evaluator/plugin.py | 11 +-- .../src/candler_evaluator/trace.py | 6 +- .../tests/test_guard_context.py | 39 ++++++++-- python/candler-evaluator/uv.lock | 2 +- 16 files changed, 233 insertions(+), 181 deletions(-) diff --git a/docs/contract/evaluator-helper.md b/docs/contract/evaluator-helper.md index 501b9630..9d3806c0 100644 --- a/docs/contract/evaluator-helper.md +++ b/docs/contract/evaluator-helper.md @@ -2,11 +2,7 @@ ## Surface -The Python package `candler-evaluator`, which an author of an evaluator kind uses to speak the protocol; a kind returns the fields of an outcome record that Candler does not fill. - -The author API (a kind's signature, `RunContext`, `KINDS`, `needs` and `params_schema`) is in the package's docstrings and README. - -A kind reads the stored parts of a run from `RunContext`: `trace` and `manifest`, each a `ServedFile` with `path`, `abs` and `sha256` or `None`, and `raw`, a tuple of mappings with `stream`, `path` and `sha256`. `read_trace(context.trace)` yields the trace's records as models generated from `normalised-trace.schema.json`. It raises `ValidationError` at a line those models refuse (not JSON, an unknown field, a wrong type); a `null` on an optional field reads as absent, though the schema refuses it. It checks each line, not the file's order: Candler checks the order when it writes the trace, and the served copy is pinned by its sha256. +The Python package `candler-evaluator`, which an author of an evaluator kind uses to speak the protocol; a kind returns the fields of an outcome record that Candler does not fill, and the author API is in the package's docstrings and README. ## Version @@ -105,5 +101,5 @@ Package: `candler-evaluator@0.2.0`. - `print` in a kind goes to stderr; stdout carries the frames alone. [checked: candler-evaluator@0.1.0] - An instrument installed from a package index makes `describe` and `evaluate` fail with error -32000. [checked: candler-evaluator@0.1.0] - A module with no `KINDS` ends the process with exit 1 before it sends a frame. [checked: candler-evaluator@0.1.0] -- A part is served when any kind of the plug-in declares it in `needs`, as its kinds share one process. [checked: candler-evaluator@0.2.0] -- `read_trace` checks lines, not order; `null` reads as absent. [checked: candler-evaluator@0.2.0] +- A part is served when any kind in the request declares it in `needs`. [checked: candler-evaluator@0.2.0] +- `read_trace` checks lines, not order; it refuses `null` on an optional field. [checked: candler-evaluator@0.2.0] diff --git a/python/candler-evaluator/CHANGELOG.md b/python/candler-evaluator/CHANGELOG.md index 7f046d10..c4d19145 100644 --- a/python/candler-evaluator/CHANGELOG.md +++ b/python/candler-evaluator/CHANGELOG.md @@ -9,9 +9,13 @@ PyPI without Eliott's go. The version is bumped by hand in `pyproject.toml` from - `RunContext` carries `trace` and `manifest` as `ServedFile`s (`path`, `abs`, `sha256`) and each `raw` stream with its `sha256`; `trace` was a bare path and is now a `ServedFile`. - `read_trace` yields a trace's records as models generated from - `normalised-trace.schema.json`, refusing a line the schema refuses. + `normalised-trace.schema.json`, refusing a line those models refuse: not JSON, an unknown + field, a `null` on an optional field or a wrong type. It checks lines, not the file's order. - The wire models are generated from the published schemas by `scripts/gen_models.py`; the loop parses and builds every message through them, and the shared wire vectors decide what they accept. - `candler_evaluator.__version__` reads the installed package version. -- `pydantic` is the package's one runtime dependency. +- `pydantic` is the package's one runtime dependency, at 2.14 or later. +- The generated models refuse `null` where the schema does and let an optional field be left + out. A plug-in that declares `null` for a need is refused with error -32000, not read as + absent. diff --git a/python/candler-evaluator/README.md b/python/candler-evaluator/README.md index 12dfd1ab..7de3d2c9 100644 --- a/python/candler-evaluator/README.md +++ b/python/candler-evaluator/README.md @@ -19,14 +19,18 @@ grades one item, and may expose `NAME`, `VERSION`, `DIST`, `INSTRUMENTS`, `KIND_ - **`RunContext`** is what a kind may read of one run: `root`, `artifacts`, `metadata`, `scratch`, `run`, `raw`, `trace`, `manifest`, `artifact_files`, `snapshots` and `inputs`. A kind never imports the class; it reads the object it is given. `trace` and `manifest` are a - `ServedFile` (`path`, `abs`, `sha256`) or `None`; `raw` is a tuple of mappings with `stream`, - `path` and `sha256`. `candler_evaluator.read_trace(context.trace)` yields the trace's lines as - models generated from `normalised-trace.schema.json` and raises `pydantic.ValidationError` at - a line the schema refuses. + `ServedFile` (`path` relative to `root`, `abs`, `sha256`) or `None`; `raw` is a tuple of + mappings with `stream`, `path` (absolute, a gzip-compressed `.jsonl.gz` file) and `sha256`. + `candler_evaluator.read_trace(context.trace)` yields the trace's records as models generated + from `normalised-trace.schema.json` and raises `pydantic.ValidationError` at a line those + models refuse: not JSON, an unknown field, a `null` on an optional field or a wrong type. It + checks each line, not the file's order; Candler checks the order when it writes the trace, and + the served copy is pinned by its `sha256`. - **`KINDS`** maps each kind's name to its function. - **`needs`** says what a kind reads: `artifacts` (globs), `inputs`, `metadata` (field paths), `snapshots`, `trace`, `raw` and `manifest` (the last three are booleans). It is set per kind in - `KIND_SPECS`. + `KIND_SPECS`. A request is served the union of the needs of the kinds it sends, so a part is + served when a kind of the request declares it, and every kind of the request can read it. - **`params_schema`** is the JSON Schema of a kind's params, also set per kind in `KIND_SPECS`. `default_deadline_ms` sits beside them. diff --git a/python/candler-evaluator/pyproject.toml b/python/candler-evaluator/pyproject.toml index 08e2ae0c..e844d7de 100644 --- a/python/candler-evaluator/pyproject.toml +++ b/python/candler-evaluator/pyproject.toml @@ -5,7 +5,7 @@ description = "Helper for writing Candler evaluator plug-ins in Python" readme = "README.md" requires-python = ">=3.10" license = "AGPL-3.0-or-later" -dependencies = ["pydantic>=2.7"] +dependencies = ["pydantic>=2.14"] [dependency-groups] dev = [ diff --git a/python/candler-evaluator/scripts/gen_models.py b/python/candler-evaluator/scripts/gen_models.py index a15a34d0..09265c61 100644 --- a/python/candler-evaluator/scripts/gen_models.py +++ b/python/candler-evaluator/scripts/gen_models.py @@ -19,8 +19,11 @@ SCHEMAS = HELPER.parents[1] / "crates" / "candler-schemas" / "schema" MODELS = HELPER / "src" / "candler_evaluator" / "_models" -# Options that decide the shape of the output. Formatting is ruff's, so the files pass -# `ruff format --check` as committed. +# Options that decide the shape of the output. `--strict-nullable` stops a field with a default +# from admitting `null`, and `--use-missing-sentinel` types an optional field as `X | MISSING`, so +# a model refuses `null` where the schema does and still lets the field be left out; the +# sentinel needs pydantic 2.14 for `pydantic.MISSING`. Formatting is ruff's, so the files +# pass `ruff format --check` as committed. OPTIONS = [ "--input-file-type", "jsonschema", @@ -30,6 +33,10 @@ "3.10", "--use-annotated", "--use-union-operator", + "--strict-nullable", + "--use-missing-sentinel", + "--target-pydantic-version", + "2.14", "--formatters", "ruff-check", "ruff-format", 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 03c1a111..fe4ac473 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,13 +1,13 @@ # Generated by scripts/gen_models.py; do not edit. # schema: crates/candler-schemas/schema/evaluator-describe-result.schema.json -# sha256: 8feb70c5893c7633830cfad09f533a8e8f1708388903192e151939075c6b2914 +# sha256: 3b17c65c37679bad6ee2414fab11de0fc7f0479a966edb518e9c25e73c5d4593 from __future__ import annotations from enum import Enum from typing import Annotated, Any -from pydantic import BaseModel, ConfigDict, Field, RootModel +from pydantic import MISSING, BaseModel, ConfigDict, Field, RootModel class Digest(RootModel[str]): @@ -28,11 +28,11 @@ class EvaluatorEnvironment(BaseModel): extra="forbid", ) lock_digest: Annotated[ - Digest | None, + Digest | MISSING, Field( description="The digest of the lock file the environment was built from; absent when there is none." ), - ] = None + ] = MISSING packages: Annotated[ dict[str, str], Field( @@ -92,16 +92,16 @@ class Needs(BaseModel): artifacts: Annotated[ list[str], Field( - description="Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced." + description="Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced." ), ] inputs: Annotated[ list[Name], Field(description="The kinds of input the check reads.") ] manifest: Annotated[ - bool | None, + bool, Field( - description="Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process." + description="Whether the check reads the run's manifest, served as `context.manifest` when a kind of the request needs it. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process." ), ] = False metadata: Annotated[ @@ -109,9 +109,9 @@ class Needs(BaseModel): Field(description="The paths of the metadata fields the check reads."), ] raw: Annotated[ - bool | None, + bool, Field( - description="Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep." + description="Whether the check reads the raw streams, served as `context.raw` when a kind of the request needs it. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep, each stored as gzip-compressed JSON lines (`.jsonl.gz`)." ), ] = False snapshots: Annotated[ @@ -123,7 +123,7 @@ class Needs(BaseModel): trace: Annotated[ bool, Field( - description="Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage." + description="Whether the check reads the normalised trace, served as `context.trace` when a kind of the request needs it. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. It holds its header alone when the reader failed or the session was silent." ), ] @@ -232,11 +232,11 @@ class DescribeResult(BaseModel): ProtocolVersion, Field(description="The protocol version the evaluator speaks.") ] reuse: Annotated[ - str | float | bool | list[Any] | dict[str, Any] | None, + str | float | bool | list[Any] | dict[str, Any] | MISSING, Field( description="The rule that decides when an earlier verdict can be reused; absent when the evaluator has none." ), - ] = None + ] = MISSING version: Annotated[ str, Field( 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 4a9dfbe0..c70f4d50 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,13 +1,13 @@ # Generated by scripts/gen_models.py; do not edit. # schema: crates/candler-schemas/schema/evaluator-evaluate-params.schema.json -# sha256: e169785d20bc401b87b6bb74b917b9af827c1ad5ef5e917be8db8617ed533e3d +# sha256: ce5d8cc904f4796dfa1872225aa400c4ed60c9852650b7b91aabf30faa82306f from __future__ import annotations from enum import Enum from typing import Annotated, Any, Literal -from pydantic import BaseModel, ConfigDict, Field, RootModel, StringConstraints +from pydantic import MISSING, BaseModel, ConfigDict, Field, RootModel, StringConstraints from typing_extensions import TypeAliasType @@ -334,7 +334,10 @@ class ContextArtifact(BaseModel): ), ] path: Annotated[ - RelPath, Field(description="The path of the file relative to the run.") + RelPath, + Field( + description="The path of the file: relative to the run's outputs for an artifact, relative to the run's `root` for the trace and the manifest." + ), ] sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] @@ -346,7 +349,7 @@ class ContextRaw(BaseModel): path: Annotated[ str, Field( - description="The absolute path of the stream, valid where the evaluator runs." + description="The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`)." ), ] sha256: Annotated[Digest, Field(description="The digest of the stream's bytes.")] @@ -372,9 +375,9 @@ class Evidence1(BaseModel): extra="forbid", ) note: Annotated[ - str | None, + str | MISSING, Field(description="What the evidence says, a non-empty string.", min_length=1), - ] = None + ] = MISSING ref: Annotated[ EvidenceRef, Field( @@ -392,11 +395,11 @@ class Evidence2(BaseModel): Field(description="What the evidence says, a non-empty string.", min_length=1), ] ref: Annotated[ - EvidenceRef | None, + EvidenceRef | MISSING, Field( description="An evidence reference string: `event:#`, or `path:` with an optional line anchor." ), - ] = None + ] = MISSING class Evidence(RootModel[Evidence1 | Evidence2]): @@ -474,11 +477,11 @@ class OutcomeRecord(BaseModel): extra="forbid", ) cause: Annotated[ - Cause | None, + Cause | MISSING, Field( description="Why the outcome has its status; required for `blocked`, `not_measured` and `not_applicable`, absent for `pass` and `fail` unless it is the legacy cause." ), - ] = None + ] = MISSING context_digest: Annotated[ Digest, Field( @@ -510,11 +513,11 @@ class OutcomeRecord(BaseModel): ), ] probability: Annotated[ - Probability | None, + Probability | MISSING, Field( description="A calibrated probability that the expectation holds, as an object; deterministic evaluators never set it, and it is absent when the role is `gate` or `quality`." ), - ] = None + ] = MISSING request_id: Annotated[ RequestId, Field( @@ -546,17 +549,17 @@ class OutcomeRecord(BaseModel): ), ] value: Annotated[ - Value | None, + Value | MISSING, Field( description="What was measured, as a value object, if the evaluator reports one." ), - ] = None + ] = MISSING weight: Annotated[ - Weight | None, + Weight | MISSING, Field( description="The contribution to a rate; absent means the default of the status: `pass` 1/1, `fail` 0/1, `blocked` 0/1. A `pass` has `num` equal to `den`, a `fail` has `num` below `den` and a `blocked` has `num` 0. Absent for `not_measured` and `not_applicable`." ), - ] = None + ] = MISSING class RunContext(BaseModel): @@ -571,11 +574,11 @@ class RunContext(BaseModel): list[ContextRef], Field(description="The inputs the run was made from.") ] manifest: Annotated[ - ContextArtifact | None, + ContextArtifact | MISSING, Field( - description="The manifest of the run, served when the kind needs it; absent otherwise." + description="The manifest of the run, served when a kind of the request needs it; absent otherwise." ), - ] = None + ] = MISSING metadata: Annotated[ dict[ Annotated[ @@ -593,7 +596,7 @@ class RunContext(BaseModel): raw: Annotated[ list[ContextRaw], Field( - description="The raw streams of the run, served when the kind needs them; empty otherwise." + description="The raw streams of the run, served when a kind of the request needs them; empty otherwise." ), ] root: Annotated[ @@ -610,11 +613,11 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - ContextArtifact | None, + ContextArtifact | MISSING, Field( - description="The normalised trace, served when the kind needs it; absent otherwise." + description="The normalised trace, served when a kind of the request needs it; absent otherwise." ), - ] = None + ] = MISSING class EvaluateParams(BaseModel): 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 0942467c..ba5fcbc3 100644 --- a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_message.py +++ b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_message.py @@ -1,13 +1,13 @@ # Generated by scripts/gen_models.py; do not edit. # schema: crates/candler-schemas/schema/evaluator-message.schema.json -# sha256: 0e4283779332598799f3ebf26f753d358c1788f8b317a5768b19c2a82317b73b +# sha256: 042dcb6c101a5046793beec6c891b40a7d3ef83cf83478698940e1ddf13453fe from __future__ import annotations from enum import Enum from typing import Annotated, Any, Literal -from pydantic import BaseModel, ConfigDict, Field, RootModel, StringConstraints +from pydantic import MISSING, BaseModel, ConfigDict, Field, RootModel, StringConstraints from typing_extensions import TypeAliasType @@ -48,11 +48,11 @@ class EvaluatorEnvironment(BaseModel): extra="forbid", ) lock_digest: Annotated[ - Digest | None, + Digest | MISSING, Field( description="The digest of the lock file the environment was built from; absent when there is none." ), - ] = None + ] = MISSING packages: Annotated[ dict[str, str], Field( @@ -166,16 +166,16 @@ class Needs(BaseModel): artifacts: Annotated[ list[str], Field( - description="Globs, relative to the run, of the artifacts the check reads. The artifacts are the files the run produced." + description="Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced." ), ] inputs: Annotated[ list[Name], Field(description="The kinds of input the check reads.") ] manifest: Annotated[ - bool | None, + bool, Field( - description="Whether the check reads the run's manifest, served as `context.manifest`. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process." + description="Whether the check reads the run's manifest, served as `context.manifest` when a kind of the request needs it. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process." ), ] = False metadata: Annotated[ @@ -183,9 +183,9 @@ class Needs(BaseModel): Field(description="The paths of the metadata fields the check reads."), ] raw: Annotated[ - bool | None, + bool, Field( - description="Whether the check reads the raw streams, served as `context.raw`. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep." + description="Whether the check reads the raw streams, served as `context.raw` when a kind of the request needs it. The raw streams are the harness's frames as recorded, with everything the normalised trace does not keep, each stored as gzip-compressed JSON lines (`.jsonl.gz`)." ), ] = False snapshots: Annotated[ @@ -197,7 +197,7 @@ class Needs(BaseModel): trace: Annotated[ bool, Field( - description="Whether the check reads the normalised trace, served as `context.trace`. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage." + description="Whether the check reads the normalised trace, served as `context.trace` when a kind of the request needs it. The trace shows every session of the run: the messages, each tool call with its command line or its MCP `{server, tool}`, each result with its `exit`, and the usage. It holds its header alone when the reader failed or the session was silent." ), ] @@ -295,9 +295,9 @@ class RpcError(BaseModel): ) code: Annotated[int, Field(description="The error code.")] data: Annotated[ - str | float | bool | list[Any] | dict[str, Any] | None, + str | float | bool | list[Any] | dict[str, Any] | MISSING, Field(description="More about the error; absent when there is nothing more."), - ] = None + ] = MISSING message: Annotated[str, Field(description="A sentence that says what went wrong.")] @@ -531,7 +531,10 @@ class ContextArtifact(BaseModel): ), ] path: Annotated[ - RelPath, Field(description="The path of the file relative to the run.") + RelPath, + Field( + description="The path of the file: relative to the run's outputs for an artifact, relative to the run's `root` for the trace and the manifest." + ), ] sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] @@ -543,7 +546,7 @@ class ContextRaw(BaseModel): path: Annotated[ str, Field( - description="The absolute path of the stream, valid where the evaluator runs." + description="The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`)." ), ] sha256: Annotated[Digest, Field(description="The digest of the stream's bytes.")] @@ -569,9 +572,9 @@ class Evidence1(BaseModel): extra="forbid", ) note: Annotated[ - str | None, + str | MISSING, Field(description="What the evidence says, a non-empty string.", min_length=1), - ] = None + ] = MISSING ref: Annotated[ EvidenceRef, Field( @@ -589,11 +592,11 @@ class Evidence2(BaseModel): Field(description="What the evidence says, a non-empty string.", min_length=1), ] ref: Annotated[ - EvidenceRef | None, + EvidenceRef | MISSING, Field( description="An evidence reference string: `event:#`, or `path:` with an optional line anchor." ), - ] = None + ] = MISSING class Evidence(RootModel[Evidence1 | Evidence2]): @@ -694,11 +697,11 @@ class OutcomeRecord(BaseModel): extra="forbid", ) cause: Annotated[ - Cause | None, + Cause | MISSING, Field( description="Why the outcome has its status; required for `blocked`, `not_measured` and `not_applicable`, absent for `pass` and `fail` unless it is the legacy cause." ), - ] = None + ] = MISSING context_digest: Annotated[ Digest, Field( @@ -730,11 +733,11 @@ class OutcomeRecord(BaseModel): ), ] probability: Annotated[ - Probability | None, + Probability | MISSING, Field( description="A calibrated probability that the expectation holds, as an object; deterministic evaluators never set it, and it is absent when the role is `gate` or `quality`." ), - ] = None + ] = MISSING request_id: Annotated[ RequestId, Field( @@ -766,17 +769,17 @@ class OutcomeRecord(BaseModel): ), ] value: Annotated[ - Value | None, + Value | MISSING, Field( description="What was measured, as a value object, if the evaluator reports one." ), - ] = None + ] = MISSING weight: Annotated[ - Weight | None, + Weight | MISSING, Field( description="The contribution to a rate; absent means the default of the status: `pass` 1/1, `fail` 0/1, `blocked` 0/1. A `pass` has `num` equal to `den`, a `fail` has `num` below `den` and a `blocked` has `num` 0. Absent for `not_measured` and `not_applicable`." ), - ] = None + ] = MISSING class RpcNotification4(BaseModel): @@ -802,11 +805,11 @@ class RunContext(BaseModel): list[ContextRef], Field(description="The inputs the run was made from.") ] manifest: Annotated[ - ContextArtifact | None, + ContextArtifact | MISSING, Field( - description="The manifest of the run, served when the kind needs it; absent otherwise." + description="The manifest of the run, served when a kind of the request needs it; absent otherwise." ), - ] = None + ] = MISSING metadata: Annotated[ dict[ Annotated[ @@ -824,7 +827,7 @@ class RunContext(BaseModel): raw: Annotated[ list[ContextRaw], Field( - description="The raw streams of the run, served when the kind needs them; empty otherwise." + description="The raw streams of the run, served when a kind of the request needs them; empty otherwise." ), ] root: Annotated[ @@ -841,11 +844,11 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - ContextArtifact | None, + ContextArtifact | MISSING, Field( - description="The normalised trace, served when the kind needs it; absent otherwise." + description="The normalised trace, served when a kind of the request needs it; absent otherwise." ), - ] = None + ] = MISSING class DescribeResult(BaseModel): @@ -877,11 +880,11 @@ class DescribeResult(BaseModel): ProtocolVersion, Field(description="The protocol version the evaluator speaks.") ] reuse: Annotated[ - str | float | bool | list[Any] | dict[str, Any] | None, + str | float | bool | list[Any] | dict[str, Any] | MISSING, Field( description="The rule that decides when an earlier verdict can be reused; absent when the evaluator has none." ), - ] = None + ] = MISSING version: Annotated[ str, Field( diff --git a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_notification.py b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_notification.py index 10807cd3..64695ac2 100644 --- a/python/candler-evaluator/src/candler_evaluator/_models/evaluator_notification.py +++ b/python/candler-evaluator/src/candler_evaluator/_models/evaluator_notification.py @@ -7,7 +7,7 @@ from enum import Enum from typing import Annotated, Literal -from pydantic import BaseModel, ConfigDict, Field, RootModel +from pydantic import MISSING, BaseModel, ConfigDict, Field, RootModel from typing_extensions import TypeAliasType @@ -339,9 +339,9 @@ class Evidence1(BaseModel): extra="forbid", ) note: Annotated[ - str | None, + str | MISSING, Field(description="What the evidence says, a non-empty string.", min_length=1), - ] = None + ] = MISSING ref: Annotated[ EvidenceRef, Field( @@ -359,11 +359,11 @@ class Evidence2(BaseModel): Field(description="What the evidence says, a non-empty string.", min_length=1), ] ref: Annotated[ - EvidenceRef | None, + EvidenceRef | MISSING, Field( description="An evidence reference string: `event:#`, or `path:` with an optional line anchor." ), - ] = None + ] = MISSING class Evidence(RootModel[Evidence1 | Evidence2]): @@ -413,11 +413,11 @@ class OutcomeRecord(BaseModel): extra="forbid", ) cause: Annotated[ - Cause | None, + Cause | MISSING, Field( description="Why the outcome has its status; required for `blocked`, `not_measured` and `not_applicable`, absent for `pass` and `fail` unless it is the legacy cause." ), - ] = None + ] = MISSING context_digest: Annotated[ Digest, Field( @@ -449,11 +449,11 @@ class OutcomeRecord(BaseModel): ), ] probability: Annotated[ - Probability | None, + Probability | MISSING, Field( description="A calibrated probability that the expectation holds, as an object; deterministic evaluators never set it, and it is absent when the role is `gate` or `quality`." ), - ] = None + ] = MISSING request_id: Annotated[ RequestId, Field( @@ -485,17 +485,17 @@ class OutcomeRecord(BaseModel): ), ] value: Annotated[ - Value | None, + Value | MISSING, Field( description="What was measured, as a value object, if the evaluator reports one." ), - ] = None + ] = MISSING weight: Annotated[ - Weight | None, + Weight | MISSING, Field( description="The contribution to a rate; absent means the default of the status: `pass` 1/1, `fail` 0/1, `blocked` 0/1. A `pass` has `num` equal to `den`, a `fail` has `num` below `den` and a `blocked` has `num` 0. Absent for `not_measured` and `not_applicable`." ), - ] = None + ] = MISSING class Notification4(BaseModel): 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 1e2a7d99..285679ee 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,13 +1,13 @@ # Generated by scripts/gen_models.py; do not edit. # schema: crates/candler-schemas/schema/evaluator-request-side.schema.json -# sha256: 293e488295656b18da5eb3638b7cc02387711ff22f708d6840834e9f61f4cdb6 +# sha256: 70a4cd1a4899c212abf817ee095a809f56bdd8381c639805cd78897309cddd3e from __future__ import annotations from enum import Enum from typing import Annotated, Any, Literal -from pydantic import BaseModel, ConfigDict, Field, RootModel, StringConstraints +from pydantic import MISSING, BaseModel, ConfigDict, Field, RootModel, StringConstraints from typing_extensions import TypeAliasType @@ -373,7 +373,10 @@ class ContextArtifact(BaseModel): ), ] path: Annotated[ - RelPath, Field(description="The path of the file relative to the run.") + RelPath, + Field( + description="The path of the file: relative to the run's outputs for an artifact, relative to the run's `root` for the trace and the manifest." + ), ] sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] @@ -385,7 +388,7 @@ class ContextRaw(BaseModel): path: Annotated[ str, Field( - description="The absolute path of the stream, valid where the evaluator runs." + description="The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`)." ), ] sha256: Annotated[Digest, Field(description="The digest of the stream's bytes.")] @@ -411,9 +414,9 @@ class Evidence1(BaseModel): extra="forbid", ) note: Annotated[ - str | None, + str | MISSING, Field(description="What the evidence says, a non-empty string.", min_length=1), - ] = None + ] = MISSING ref: Annotated[ EvidenceRef, Field( @@ -431,11 +434,11 @@ class Evidence2(BaseModel): Field(description="What the evidence says, a non-empty string.", min_length=1), ] ref: Annotated[ - EvidenceRef | None, + EvidenceRef | MISSING, Field( description="An evidence reference string: `event:#`, or `path:` with an optional line anchor." ), - ] = None + ] = MISSING class Evidence(RootModel[Evidence1 | Evidence2]): @@ -513,11 +516,11 @@ class OutcomeRecord(BaseModel): extra="forbid", ) cause: Annotated[ - Cause | None, + Cause | MISSING, Field( description="Why the outcome has its status; required for `blocked`, `not_measured` and `not_applicable`, absent for `pass` and `fail` unless it is the legacy cause." ), - ] = None + ] = MISSING context_digest: Annotated[ Digest, Field( @@ -549,11 +552,11 @@ class OutcomeRecord(BaseModel): ), ] probability: Annotated[ - Probability | None, + Probability | MISSING, Field( description="A calibrated probability that the expectation holds, as an object; deterministic evaluators never set it, and it is absent when the role is `gate` or `quality`." ), - ] = None + ] = MISSING request_id: Annotated[ RequestId, Field( @@ -585,17 +588,17 @@ class OutcomeRecord(BaseModel): ), ] value: Annotated[ - Value | None, + Value | MISSING, Field( description="What was measured, as a value object, if the evaluator reports one." ), - ] = None + ] = MISSING weight: Annotated[ - Weight | None, + Weight | MISSING, Field( description="The contribution to a rate; absent means the default of the status: `pass` 1/1, `fail` 0/1, `blocked` 0/1. A `pass` has `num` equal to `den`, a `fail` has `num` below `den` and a `blocked` has `num` 0. Absent for `not_measured` and `not_applicable`." ), - ] = None + ] = MISSING class RunContext(BaseModel): @@ -610,11 +613,11 @@ class RunContext(BaseModel): list[ContextRef], Field(description="The inputs the run was made from.") ] manifest: Annotated[ - ContextArtifact | None, + ContextArtifact | MISSING, Field( - description="The manifest of the run, served when the kind needs it; absent otherwise." + description="The manifest of the run, served when a kind of the request needs it; absent otherwise." ), - ] = None + ] = MISSING metadata: Annotated[ dict[ Annotated[ @@ -632,7 +635,7 @@ class RunContext(BaseModel): raw: Annotated[ list[ContextRaw], Field( - description="The raw streams of the run, served when the kind needs them; empty otherwise." + description="The raw streams of the run, served when a kind of the request needs them; empty otherwise." ), ] root: Annotated[ @@ -649,11 +652,11 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - ContextArtifact | None, + ContextArtifact | MISSING, Field( - description="The normalised trace, served when the kind needs it; absent otherwise." + description="The normalised trace, served when a kind of the request needs it; absent otherwise." ), - ] = None + ] = MISSING class EvaluateParams(BaseModel): diff --git a/python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py b/python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py index 6bd8900a..c79d9f7f 100644 --- a/python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py +++ b/python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py @@ -7,7 +7,7 @@ from enum import Enum from typing import Annotated, Any, Literal -from pydantic import BaseModel, ConfigDict, Field, RootModel +from pydantic import MISSING, BaseModel, ConfigDict, Field, RootModel class Cap(Enum): @@ -91,8 +91,8 @@ class EventKind1(BaseModel): ) kind: Literal["user_message"] text: Annotated[ - str | None, Field(description="The text, if the harness records it.") - ] = None + str | MISSING, Field(description="The text, if the harness records it.") + ] = MISSING class EventKind2(BaseModel): @@ -101,8 +101,8 @@ class EventKind2(BaseModel): ) kind: Literal["assistant_message"] text: Annotated[ - str | None, Field(description="The text, if the harness records it.") - ] = None + str | MISSING, Field(description="The text, if the harness records it.") + ] = MISSING class EventKind5(BaseModel): @@ -278,11 +278,11 @@ class ToolOrigin2(BaseModel): kind: Literal["mcp"] server: Annotated[str, Field(description="The name of the MCP server.")] tool: Annotated[ - str | None, + str | MISSING, Field( description="The tool's name at the server, without the harness's prefix. A trace written before the\nfield existed has none." ), - ] = None + ] = MISSING class ToolOrigin3(BaseModel): @@ -321,7 +321,9 @@ class Denial(BaseModel): extra="forbid", ) by: Annotated[DeniedBy, Field(description="Who refused the call.")] - reason: Annotated[str | None, Field(description="The reason given, if any.")] = None + reason: Annotated[str | MISSING, Field(description="The reason given, if any.")] = ( + MISSING + ) class EndedBy2(BaseModel): @@ -330,8 +332,8 @@ class EndedBy2(BaseModel): ) kind: Literal["agent_error"] reason: Annotated[ - ReasonCode | None, Field(description="Why the agent failed, when it says.") - ] = None + ReasonCode | MISSING, Field(description="Why the agent failed, when it says.") + ] = MISSING class EndedBy( @@ -366,8 +368,9 @@ class EventKind3(BaseModel): extra="forbid", ) argv: Annotated[ - list[str] | None, Field(description="The command line, if the tool runs one.") - ] = None + list[str] | MISSING, + Field(description="The command line, if the tool runs one."), + ] = MISSING kind: Literal["tool_call"] name: Annotated[str, Field(description="The name of the tool.")] origin: Annotated[ToolOrigin, Field(description="Where the tool is served from.")] @@ -384,14 +387,15 @@ class EventKind4(BaseModel): extra="forbid", ) denied: Annotated[ - Denial | None, Field(description="Who refused the call, when it was refused.") - ] = None + Denial | MISSING, + Field(description="Who refused the call, when it was refused."), + ] = MISSING exit: Annotated[ - ExitStatus | None, + ExitStatus | MISSING, Field( description="How the shell call ended, as the harness reported it: `{kind: code, code}` or `{kind: signal, signal}`. Absent when the call is not a shell call, was denied, or came back without a code." ), - ] = None + ] = MISSING is_error: Annotated[ bool, Field( @@ -412,11 +416,11 @@ class EventKind6(BaseModel): int, Field(description="Input tokens served from the cache.", ge=0) ] cost_usd: Annotated[ - Finite | None, + Finite | MISSING, Field( description="The cost in US dollars, a finite number, if the harness reports it." ), - ] = None + ] = MISSING input_tokens: Annotated[int, Field(description="Input tokens.", ge=0)] kind: Literal["usage"] output_tokens: Annotated[int, Field(description="Output tokens.", ge=0)] @@ -490,11 +494,11 @@ class TraceRecord2(BaseModel): extra="forbid", ) ended_at: Annotated[ - Timestamp | None, + Timestamp | MISSING, Field( description="When the session ended, if the harness or the frame times say." ), - ] = None + ] = MISSING ended_by: Annotated[EndedBy, Field(description="How the session ended.")] id: Annotated[ SessionId, @@ -504,28 +508,28 @@ class TraceRecord2(BaseModel): ] kind: Literal["session"] model: Annotated[ - str | None, + str | MISSING, Field( description="The model the session ran, as the harness names it, if it says." ), - ] = None + ] = MISSING parent_session: Annotated[ - SessionId | None, + SessionId | MISSING, Field( description="The id of the session that started this one; the session's own id is that id, `/`, and a call id." ), - ] = None + ] = MISSING raw_ref: Annotated[RawRef, Field(description="The frame the session starts at.")] source: Annotated[ SessionSource, Field(description="The harness and the reader that produced the session."), ] started_at: Annotated[ - Timestamp | None, + Timestamp | MISSING, Field( description="When the session started, if the harness or the frame times say." ), - ] = None + ] = MISSING class Event(BaseModel): @@ -533,11 +537,11 @@ class Event(BaseModel): extra="forbid", ) at: Annotated[ - Timestamp | None, + Timestamp | MISSING, Field( description="When the event happened, if the harness or the frame time says." ), - ] = None + ] = MISSING ext: Annotated[ dict[str, Any], Field( @@ -554,11 +558,11 @@ class Event(BaseModel): ), ] span: Annotated[ - SpanId | None, + SpanId | MISSING, Field( description="The harness's id that pairs a call with its result, if the event has one." ), - ] = None + ] = MISSING class TraceRecord3(BaseModel): diff --git a/python/candler-evaluator/src/candler_evaluator/_models/outcome_record.py b/python/candler-evaluator/src/candler_evaluator/_models/outcome_record.py index 40288527..38f3f6a5 100644 --- a/python/candler-evaluator/src/candler_evaluator/_models/outcome_record.py +++ b/python/candler-evaluator/src/candler_evaluator/_models/outcome_record.py @@ -7,7 +7,7 @@ from enum import Enum from typing import Annotated, Literal -from pydantic import BaseModel, ConfigDict, Field, RootModel +from pydantic import MISSING, BaseModel, ConfigDict, Field, RootModel from typing_extensions import TypeAliasType @@ -302,9 +302,9 @@ class Evidence1(BaseModel): extra="forbid", ) note: Annotated[ - str | None, + str | MISSING, Field(description="What the evidence says, a non-empty string.", min_length=1), - ] = None + ] = MISSING ref: Annotated[ EvidenceRef, Field( @@ -322,11 +322,11 @@ class Evidence2(BaseModel): Field(description="What the evidence says, a non-empty string.", min_length=1), ] ref: Annotated[ - EvidenceRef | None, + EvidenceRef | MISSING, Field( description="An evidence reference string: `event:#`, or `path:` with an optional line anchor." ), - ] = None + ] = MISSING class Evidence(RootModel[Evidence1 | Evidence2]): @@ -376,11 +376,11 @@ class OutcomeRecord(BaseModel): extra="forbid", ) cause: Annotated[ - Cause | None, + Cause | MISSING, Field( description="Why the outcome has its status; required for `blocked`, `not_measured` and `not_applicable`, absent for `pass` and `fail` unless it is the legacy cause." ), - ] = None + ] = MISSING context_digest: Annotated[ Digest, Field( @@ -412,11 +412,11 @@ class OutcomeRecord(BaseModel): ), ] probability: Annotated[ - Probability | None, + Probability | MISSING, Field( description="A calibrated probability that the expectation holds, as an object; deterministic evaluators never set it, and it is absent when the role is `gate` or `quality`." ), - ] = None + ] = MISSING request_id: Annotated[ RequestId, Field( @@ -448,14 +448,14 @@ class OutcomeRecord(BaseModel): ), ] value: Annotated[ - Value | None, + Value | MISSING, Field( description="What was measured, as a value object, if the evaluator reports one." ), - ] = None + ] = MISSING weight: Annotated[ - Weight | None, + Weight | MISSING, Field( description="The contribution to a rate; absent means the default of the status: `pass` 1/1, `fail` 0/1, `blocked` 0/1. A `pass` has `num` equal to `den`, a `fail` has `num` below `den` and a `blocked` has `num` 0. Absent for `not_measured` and `not_applicable`." ), - ] = None + ] = MISSING diff --git a/python/candler-evaluator/src/candler_evaluator/plugin.py b/python/candler-evaluator/src/candler_evaluator/plugin.py index 0075a262..4d492caa 100644 --- a/python/candler-evaluator/src/candler_evaluator/plugin.py +++ b/python/candler-evaluator/src/candler_evaluator/plugin.py @@ -90,8 +90,8 @@ class Prior: @dataclass(frozen=True) class ServedFile: - """One stored file of the run: `path` relative to the run, `abs` where the kind reads it, - and the `sha256` digest of its bytes, written `sha256:` and 64 hex digits.""" + """One stored file of the run: `path` relative to the run's `root`, `abs` where the kind + reads it, and the `sha256` digest of its bytes, written `sha256:` and 64 hex digits.""" path: str abs: Path @@ -110,9 +110,10 @@ class RunContext: """What a kind may read of one run; kinds never import this class, they only read it. `trace` and `manifest` are the run's normalised trace and manifest as `ServedFile`s, each - `None` when no kind of the plug-in declared it in `needs`; `raw` holds one mapping per raw - stream, with the keys `stream`, `path` and `sha256`, and is empty when none was declared. - `read_trace` reads `trace`. + `None` when no kind of the request declared it in `needs`; `raw` holds one mapping per raw + stream, with the keys `stream`, `path` and `sha256`, and is empty when no kind of the + request declared it. A raw `path` is absolute and names gzip-compressed JSON lines + (`.jsonl.gz`). `read_trace` reads `trace`. """ root: Path diff --git a/python/candler-evaluator/src/candler_evaluator/trace.py b/python/candler-evaluator/src/candler_evaluator/trace.py index dfaaf713..b1edb0af 100644 --- a/python/candler-evaluator/src/candler_evaluator/trace.py +++ b/python/candler-evaluator/src/candler_evaluator/trace.py @@ -16,9 +16,9 @@ def read_trace(trace: ServedFile | Path | str) -> Iterator[Any]: `trace` is `context.trace` or a path. A record is the header, a session or an event of `normalised-trace.schema.json`, held by the model of its `kind`. A line that is not JSON - or that the models refuse (an unknown field, a wrong type) raises - `pydantic.ValidationError` when the iterator reaches it; the records before it have been - yielded. A `null` on an optional field reads as absent, although the schema refuses it. + or that the models refuse (an unknown field, a `null` on an optional field, a wrong type) + raises `pydantic.ValidationError` when the iterator reaches it; the records before it have + been yielded. It checks lines, not the file's order: an empty file, a missing or second header, a `seq` gap, an event for an undeclared session and a `raw_ref` to a stream the header diff --git a/python/candler-evaluator/tests/test_guard_context.py b/python/candler-evaluator/tests/test_guard_context.py index 5f3d3010..8bdc7f89 100644 --- a/python/candler-evaluator/tests/test_guard_context.py +++ b/python/candler-evaluator/tests/test_guard_context.py @@ -151,6 +151,26 @@ def write_trace(tmp_path, records): return path +def test_the_reader_refuses_a_null_on_an_optional_field(tmp_path): + """Guards: the schema refuses `null` on an optional field, so the reader does. + + Oracle: `exit` of `ToolResult` in normalised-trace.schema.json is an `ExitStatus` object + that is left out when there is none; the wire has no `null`, and Candler's reader refuses it. + Bite: the generated models read `null` as absent. + """ + from candler_evaluator import read_trace + + bad = json.loads(json.dumps(RESULT)) + bad["event"]["kind"]["exit"] = None + path = write_trace(tmp_path, [HEADER, SESSION, bad]) + with pytest.raises(ValidationError, match="exit"): + list(read_trace(path)) + absent = json.loads(json.dumps(RESULT)) + del absent["event"]["kind"]["exit"] + path = write_trace(tmp_path, [HEADER, SESSION, absent]) + assert len(list(read_trace(path))) == 3 + + def test_the_reader_yields_typed_records_with_exit_origin_and_argv(tmp_path): """Guards: the trace reader types each line from normalised-trace.schema.json. @@ -206,7 +226,7 @@ def test_the_reader_refuses_a_line_with_an_unknown_field(tmp_path): """ -def described_needs(tmp_path, needs, vectors): +def describe_frames(tmp_path, needs, vectors): (tmp_path / "demo_plugin.py").write_text(f"NEEDS = {needs!r}\n" + DESCRIBE_PLUGIN) request = json.dumps( json.loads((vectors / "valid" / "request_describe.json").read_text()) @@ -220,24 +240,31 @@ def described_needs(tmp_path, needs, vectors): env={**os.environ, "PYTHONPATH": str(tmp_path), "PYTHONDONTWRITEBYTECODE": "1"}, timeout=60, ).stdout - frames = [json.loads(line) for line in out.splitlines()] - (result,) = [f for f in frames if "result" in f] + return [json.loads(line) for line in out.splitlines()] + + +def described_needs(tmp_path, needs, vectors): + (result,) = [f for f in describe_frames(tmp_path, needs, vectors) if "result" in f] return result["result"]["kinds"][0]["needs"] def test_a_describe_result_never_carries_null_for_an_unset_need(tmp_path, vectors): - """Guards: `raw` and `manifest` are written as booleans or left out, never `null`. + """Guards: `raw` and `manifest` are written as booleans or left out, never `null`; a plug-in + that declares `null` for one is refused with error -32000 naming it. Oracle: response_describe_needs_raw_manifest.json shows the wire form, and invalid/needs_raw_not_boolean.json shows the reader refusing anything but a boolean. - Bite: the writer emits `null` for an unset need. + Bite: the writer emits `null` for an unset need, or reads a declared `null` as absent. """ oracle = json.loads( (vectors / "valid" / "response_describe_needs_raw_manifest.json").read_text() )["result"]["kinds"][0]["needs"] assert oracle["raw"] is True and oracle["manifest"] is True - for needs in ({}, {"raw": None, "manifest": None}, {"raw": True, "manifest": True}): + for needs in ({}, {"raw": True, "manifest": True}): wrote = described_needs(tmp_path, needs, vectors) assert None not in wrote.values() for key in ("raw", "manifest"): assert wrote.get(key, False) is bool(needs.get(key)) + (refusal,) = describe_frames(tmp_path, {"raw": None}, vectors) + assert refusal["error"]["code"] == -32000 + assert "needs.raw" in refusal["error"]["message"] diff --git a/python/candler-evaluator/uv.lock b/python/candler-evaluator/uv.lock index 021b92b2..72db6c8d 100644 --- a/python/candler-evaluator/uv.lock +++ b/python/candler-evaluator/uv.lock @@ -91,7 +91,7 @@ dev = [ ] [package.metadata] -requires-dist = [{ name = "pydantic", specifier = ">=2.7" }] +requires-dist = [{ name = "pydantic", specifier = ">=2.14" }] [package.metadata.requires-dev] dev = [ From 3edfb5dbda290b4e9235fb618953d009f9511074 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:48:24 +0900 Subject: [PATCH 70/93] rdm(library): start the graded run's trace Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/e2e/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/readers/e2e/README.md b/__roadmap__/run_context/readers/e2e/README.md index f3c5016d..20952ba6 100644 --- a/__roadmap__/run_context/readers/e2e/README.md +++ b/__roadmap__/run_context/readers/e2e/README.md @@ -15,7 +15,7 @@ The consumer path (run, seal, evaluate with `needs.trace`) is seen working on bo ## Status ```mermaid graph TD - graded_run_sees_trace[Graded run sees trace]:::planned + graded_run_sees_trace[Graded run sees trace]:::inprogress review[Review]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -27,7 +27,7 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `graded_run_sees_trace.md` | 📄 Leaf Task | ⬜ Planned | +| `graded_run_sees_trace.md` | 📄 Leaf Task | 🔄 In Progress | | `review/` | 📁 Directory | ⬜ Planned | ## Amendment Log From fe69541f65bcbf5c41d4fc3c118b527c467564bb Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:58:28 +0900 Subject: [PATCH 71/93] test(library): grade a real run by its trace on both harnesses A real run on Claude Code and on OpenCode, behind the production gateway and against the scripted fake model, is graded by `candler evaluate` with a plug-in kind that needs the trace and the run's answer file. The kind passes only when the trace holds the (argv, exit) pair of each of the two shell commands the script sends, the origin of the stamp call, and the served file holds the text the first command wrote. The fake model gains the model g1, which sends the commands it is given and then calls the stamp tool. The parity guard's rig is shared: the fake model's start, the shared experiment and the sealing of one run are functions both guards call. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/container-e2e.yml | 1 + assets/docker/fakemodel/fakemodel.py | 39 +++ .../graded-trace/kinds/graded_trace.py | 55 ++++ .../fixtures/plugins/graded-trace/plugin.toml | 13 + crates/candler/tests/it/guard_cli_e2e.rs | 4 + .../it/guard_cli_e2e/graded_trace_e2e.rs | 237 ++++++++++++++++++ .../tests/it/guard_cli_e2e/parity_e2e.rs | 223 +++++++++------- 7 files changed, 479 insertions(+), 93 deletions(-) create mode 100644 crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py create mode 100644 crates/candler/tests/fixtures/plugins/graded-trace/plugin.toml create mode 100644 crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs diff --git a/.github/workflows/container-e2e.yml b/.github/workflows/container-e2e.yml index 2519272f..8a97ce6c 100644 --- a/.github/workflows/container-e2e.yml +++ b/.github/workflows/container-e2e.yml @@ -72,6 +72,7 @@ jobs: egress_proxy_never_resolves_a_listed_host_to_itself \ controls_e2e_pinned_harness_passes \ parity_one_installed_server_one_traced_call \ + graded_run_sees_trace \ 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/assets/docker/fakemodel/fakemodel.py b/assets/docker/fakemodel/fakemodel.py index d238ac8a..73da496f 100644 --- a/assets/docker/fakemodel/fakemodel.py +++ b/assets/docker/fakemodel/fakemodel.py @@ -8,6 +8,7 @@ FAKE_PORT the TLS port (default 8443). FAKE_DIR where the certificates and the records go (default /tmp/fake). FAKE_OUT_TOKENS output tokens each answer reports (default 20). + FAKE_G1_COMMANDS a JSON list of two shell commands, the script of model g1 (default: none). FAKE_DELAY_SECS how long the answer to a c3 request is held, after it is recorded (default 0, at most 120). @@ -31,6 +32,10 @@ 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. + g1 must run what it is told. A first user prompt is answered with a call to the shell tool + (`Bash`, or `shell` for OpenCode) for the first command of FAKE_G1_COMMANDS, the result of + that with the second command, and the result of that with the call to the stamp tool, as + for p1. 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. @@ -123,8 +128,42 @@ def last_tool_result(messages): return ids[-1] if ids else None +SHELL_TOOLS = ("Bash", "shell") + + +def graded_blocks(state, tools, messages): + """The answer of model g1: two shell commands, then the stamp call, then text.""" + commands = json.loads(os.environ.get("FAKE_G1_COMMANDS", "[]")) + shell = next((name for name in tools if name in SHELL_TOOLS), None) + last = last_tool_result(messages) if state == "tool_result" else None + steps = ("toolu_fake_g1_0", "toolu_fake_g1_1") + + def shell_call(index): + return {"type": "tool_use", "id": steps[index], "name": shell, + "input": {"command": commands[index]}} + + if shell and len(commands) == 2: + if state == "prompt": + return [shell_call(0)], "tool_use", "g1-shell-0" + if last == steps[0]: + return [shell_call(1)], "tool_use", "g1-shell-1" + if last == steps[1]: + offered = [name for name in tools if name in PARITY_TOOLS] + if offered: + return [stamp_call(offered[0])], "tool_use", "g1-call" + if "ToolSearch" in tools: + search = {"type": "tool_use", "id": "toolu_fake_search", "name": "ToolSearch", + "input": {"query": "select:" + PARITY_TOOLS[0], "max_results": 1}} + return [search], "tool_use", "g1-search" + if last == "toolu_fake_search": + return [stamp_call(PARITY_TOOLS[0])], "tool_use", "g1-call" + return [{"type": "text", "text": "done"}], "end_turn", "g1-text" + + 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("g1"): + return graded_blocks(state, tools, messages) if model.startswith("p1"): offered = [name for name in tools if name in PARITY_TOOLS] if state == "prompt" and offered: diff --git a/crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py b/crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py new file mode 100644 index 00000000..f5226245 --- /dev/null +++ b/crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py @@ -0,0 +1,55 @@ +"""One kind that grades a run by what its trace says of the run's shell and MCP calls.""" + +from pathlib import Path + +from candler_evaluator import read_trace + +NAME = "graded-trace" +VERSION = "0.1.0" +KIND_SPECS = { + "graded_run": {"needs": {"trace": True, "artifacts": ["outputs/answer.txt"]}}, +} + + +def _verdict(problems, note): + if problems: + return {"status": "fail", "evidence": [{"note": "; ".join(problems)}]} + return {"status": "pass", "evidence": [{"note": note}]} + + +def graded_run(params, context, prior): + """Passes when the trace holds each `(argv, exit)` pair and the MCP origin that `params` + names, each as a pair or an origin of the trace and not as a substring of it, and the + artifact `params` names is served with its text.""" + if context.trace is None: + return _verdict(["the context serves no trace"], "") + argv_of = {} + pairs = [] + origins = [] + for record in read_trace(context.trace): + if record.kind != "event": + continue + body = record.event.kind.root.model_dump(mode="json") + span = record.event.span.root if hasattr(record.event.span, "root") else None + if body["kind"] == "tool_call": + origins.append(body["origin"]) + if "argv" in body: + argv_of[span] = body["argv"] + elif body["kind"] == "tool_result" and span is not None and span in argv_of and "exit" in body: + pairs.append((argv_of[span], body["exit"])) + problems = [] + for shell in params["shell"]: + want = (shell["argv"], {"kind": "code", "code": shell["exit"]}) + if pairs.count(want) != 1: + problems.append(f"{want} is held {pairs.count(want)} times among {pairs}") + if origins.count(params["origin"]) != 1: + problems.append(f"origin {params['origin']} is held {origins.count(params['origin'])} times among {origins}") + served = [f for f in context.artifact_files if f["path"] == params["artifact"]["path"]] + if len(served) != 1: + problems.append(f"{params['artifact']['path']} is not served once among {context.artifacts}") + elif Path(served[0]["abs"]).read_text(encoding="utf-8") != params["artifact"]["text"]: + problems.append(f"{params['artifact']['path']} does not hold {params['artifact']['text']!r}") + return _verdict(problems, f"pairs {pairs}; origins {origins}") + + +KINDS = {"graded_run": graded_run} diff --git a/crates/candler/tests/fixtures/plugins/graded-trace/plugin.toml b/crates/candler/tests/fixtures/plugins/graded-trace/plugin.toml new file mode 100644 index 00000000..fe85c82f --- /dev/null +++ b/crates/candler/tests/fixtures/plugins/graded-trace/plugin.toml @@ -0,0 +1,13 @@ +schema = "plugin-manifest/1" +name = "graded-trace" +version = "0.1.0" +command = ["env", "PYTHONPATH=@KINDS@", "uv", "run", "--frozen", "python", "-m", "candler_evaluator", "graded_trace"] + +[protocol] +major = 1 +minor = 0 + +[environment] +kind = "uv" +project = "env" +lock = "env/uv.lock" diff --git a/crates/candler/tests/it/guard_cli_e2e.rs b/crates/candler/tests/it/guard_cli_e2e.rs index 2dbe59de..675135f1 100644 --- a/crates/candler/tests/it/guard_cli_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e.rs @@ -810,3 +810,7 @@ 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; + +/// A plug-in grades a real run on each harness by what its trace says of the shell and MCP calls. +#[path = "guard_cli_e2e/graded_trace_e2e.rs"] +mod graded_trace_e2e; diff --git a/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs new file mode 100644 index 00000000..65da30e7 --- /dev/null +++ b/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs @@ -0,0 +1,237 @@ +//! A real run on each harness, graded by a plug-in from what its trace says. +//! +//! The rig is the parity guard's: real Claude Code and real OpenCode, each in its agent base +//! image, behind the production gateway sidecar, against the scripted fake model (model `g1`). +//! The script is two shell commands, `printf ... > answer.txt` (exit 0) and `exit 3`, then the +//! call of the tool `stamp` of the server `parity`. `candler evaluate` grades each sealed run +//! with a plug-in kind that declares `needs.trace` and `needs.artifacts = ["answer.txt"]`. +use std::fs; +use std::os::unix::fs::symlink; +use std::path::PathBuf; +use std::process::{Command, Stdio}; + +use candler_core::store::layout::StoreLayout; +use serde_json::{Value, json}; + +use super::i8_e2e::{Made, must}; +use super::parity_e2e::{SERVER, Sealed, base_experiment, records, seal, start_fake}; +use super::real_docker; +use crate::support::cli_run::World; +use crate::support::seam::{entries_under, sync_environment}; + +/// The command that writes the answer file and exits 0. +const WRITE: &str = "printf 'graded-answer-3f9a\\n' > answer.txt"; + +/// What [`WRITE`] leaves in the file. +const ANSWER: &str = "graded-answer-3f9a\n"; + +/// The command that exits 3. +const EXIT: &str = "exit 3"; + +/// The plug-in's directory below the fixtures. +fn fixture() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/plugins/graded-trace") +} + +/// The suite of one gate whose params are the script's: each command with the exit status it +/// must show in the trace, the origin of the stamp call and the answer file. +fn suite(shell: &[(&str, i32)]) -> String { + let mut parts = vec![format!( + "schema = \"suite/1\"\n\n[[expectations]]\nid = \"G1\"\nrole = \"gate\"\nkind = \"graded_run\"\n\ + depends_on = []\n\n[expectations.evaluator]\nname = \"graded-trace\"\nrange = \"^0.1\"\n\n\ + [expectations.params]\norigin = {{ kind = \"mcp\", server = \"{SERVER}\", tool = \"stamp\" }}\n" + )]; + parts.extend(shell.iter().map(|(command, code)| { + format!( + "[[expectations.params.shell]]\nargv = {}\nexit = {code}\n", + json!([command]) + ) + })); + parts.push(format!( + "[expectations.params.artifact]\npath = \"answer.txt\"\ntext = {}\n", + json!(ANSWER) + )); + parts.join("\n") +} + +/// Sets the plug-in up in the world, with the helper's project linked beside it, and returns its +/// directory and the suite. +fn plugin(world: &World) -> (PathBuf, PathBuf) { + let dir = world.root.join("graded-trace"); + fs::create_dir_all(&dir).unwrap(); + let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../python/candler-evaluator"); + symlink(helper, dir.join("env")).unwrap(); + let manifest = fs::read_to_string(fixture().join("plugin.toml")) + .unwrap() + .replace("@KINDS@", &fixture().join("kinds").display().to_string()); + fs::write(dir.join("plugin.toml"), manifest).unwrap(); + let suite_file = dir.join("suite.toml"); + fs::write(&suite_file, suite(&[(WRITE, 0), (EXIT, 3)])).unwrap(); + (dir, suite_file) +} + +/// The commands of the shell calls the fake model made in the requests after the first `skip` +/// records, in order, as the longest conversation among them holds them. +fn scripted_commands(records: &str, skip: usize) -> Vec { + let mut longest: Vec = Vec::new(); + let mut size = 0; + for line in records.lines().skip(skip) { + let Ok(record) = serde_json::from_str::(line) else { + continue; + }; + let messages = record["body"]["messages"].as_array(); + let held = messages.map_or(0, Vec::len); + let commands: Vec = messages + .into_iter() + .flatten() + .filter(|message| message["role"] == "assistant") + .flat_map(|message| message["content"].as_array().into_iter().flatten()) + .filter(|block| block["type"] == "tool_use" && block["input"]["command"].is_string()) + .filter_map(|block| block["input"]["command"].as_str().map(str::to_owned)) + .collect(); + if held >= size { + size = held; + longest = commands; + } + } + longest +} + +/// Grades the sealed run of `world` with the plug-in and returns what went wrong, one line each: +/// an evaluation that fails, or an outcome that is not one pass. +fn graded(world: &World) -> Vec { + let (dir, suite_file) = plugin(world); + sync_environment(world); + let project = world.root.join("project"); + fs::create_dir_all(&project).unwrap(); + fs::write( + project.join("candler.toml"), + format!("[plugins]\ndirs = [\"{}\"]\n", dir.display()), + ) + .unwrap(); + let evaluated = Command::new(env!("CARGO_BIN_EXE_candler")) + .arg("--store") + .arg(world.store()) + .arg("evaluate") + .arg(&suite_file) + .current_dir(&project) + .env_remove("CANDLER_STORE") + .env("HOME", world.root.join("home")) + .env("XDG_CONFIG_HOME", world.root.join("config")) + .env("XDG_STATE_HOME", &world.state) + .stdin(Stdio::null()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&evaluated.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&evaluated.stderr).into_owned(); + if !evaluated.status.success() { + return vec![format!( + "evaluate exits {:?}\nstdout: {stdout}\nstderr: {stderr}", + evaluated.status + )]; + } + let mut problems = Vec::new(); + match serde_json::from_str::(&stdout) { + Ok(report) if report["failed_requests"] == json!([]) => {} + Ok(report) => problems.push(format!("the evaluation refused a request: {report}")), + Err(error) => problems.push(format!("the report is not JSON ({error}): {stdout}")), + } + let layout = StoreLayout::new(&world.store()); + let outcomes: Vec = entries_under(&layout.outcomes_dir()) + .iter() + .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl")) + .flat_map(|path| { + fs::read_to_string(path) + .unwrap_or_default() + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .collect::>() + }) + .collect(); + if outcomes.len() != 1 || outcomes[0]["status"] != "pass" { + problems.push(format!("the kind did not pass once: {outcomes:?}")); + } + problems +} + +/// Guards: README (a run's trace is "graded" and each tool call is censused: a plug-in that +/// needs the trace sees each shell call's command and exit status and each MCP call's server and +/// tool, on every harness) -- one experiment, run with the real `candler run` on Claude Code and +/// on `OpenCode` and graded with `candler evaluate`, passes a kind that declares `needs.trace` +/// and `needs.artifacts = ["answer.txt"]` only when its trace holds, for each of the two shell +/// commands, the pair of the command's argv and its exit status, the origin of the `stamp` call, +/// and the served `answer.txt` holds the text the first command wrote. +/// +/// Oracle: the fake model's own script: the commands it sent (read back from the requests it +/// recorded), the exit statuses a shell gives them (0 and 3), and the server and tool it calls. +/// +/// Bite: `assemble` serving no trace (the kind's outcome is a fail or the evaluation a refusal), +/// or the `OpenCode` reader writing no `exit` (the `OpenCode` row fails, the Claude Code row does +/// not). +#[test] +#[ignore = "needs Docker; run with --run-ignored only"] +fn graded_run_sees_trace() { + let real = real_docker(); + let mut made = Made::default(); + let script = json!([WRITE, EXIT]).to_string(); + let fake = start_fake( + &real, + &mut made, + "graded-trace", + &[format!("FAKE_G1_COMMANDS={script}")], + ); + let base = base_experiment( + "g1", + "Run the commands you are given, call the MCP tool stamp of the server parity, then reply done.", + ); + let mut failures = Vec::new(); + let mut jobs = Vec::new(); + for harness in ["claude-code", "opencode"] { + let skip = records(&real, &fake.id).lines().count(); + let Sealed { + job, + world, + run_dir, + } = seal( + &base.replace("@HARNESS@", harness), + &fake.endpoint, + &fake.ca, + &mut made, + ); + jobs.push(job); + let sent = scripted_commands(&records(&real, &fake.id), skip); + if sent != [WRITE, EXIT] { + let seen: Vec = records(&real, &fake.id) + .lines() + .skip(skip) + .map(|line| { + let record: Value = serde_json::from_str(line).unwrap_or_default(); + format!("{}/{}", record["decision"], record["body"]["tools"]) + }) + .collect(); + failures.push(format!( + "{harness}: the model's commands were {sent:?}; requests: {seen:?}" + )); + } + if !run_dir.join("trace.jsonl").is_file() { + failures.push(format!("{harness}: the run stored no trace")); + } + failures.extend( + graded(&world) + .into_iter() + .map(|problem| format!("{harness}: {problem}")), + ); + } + drop(made); + // the containers this guard started, by their labels: the machine's other containers are not + // this guard's to count + let mut labels = vec!["candler.test=graded-trace".to_owned()]; + labels.extend(jobs.iter().map(|job| format!("candler.job={job}"))); + for label in labels { + let left = must(&real, &["ps", "-aq", "--filter", &format!("label={label}")]); + if !left.is_empty() { + failures.push(format!("containers of {label} are left behind: {left}")); + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs index e2734028..0facd729 100644 --- a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs @@ -8,7 +8,7 @@ //! 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::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; @@ -16,14 +16,14 @@ 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::cli_run::{World, 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"; +pub(super) const TOKEN: &str = "parity-fixture-token-0123456789"; /// The server the cell declares. -const SERVER: &str = "parity"; +pub(super) const SERVER: &str = "parity"; /// The text the fixture's tool returns. const STAMP: &str = "parity-stamp-5c1e"; @@ -62,7 +62,7 @@ fn stamp_answers(records: &str, skip: usize) -> Vec<(bool, String)> { } /// What the fake model has recorded so far: nothing before its first request. -fn records(real: &Path, fake: &str) -> String { +pub(super) 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() } @@ -113,16 +113,16 @@ fn call_origins(text: &str) -> Vec { found } +/// A run `candler run` sealed in its own world. +pub(super) struct Sealed { + pub(super) job: String, + pub(super) world: World, + pub(super) run_dir: PathBuf, +} + /// 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 { +/// and waits for its one run to seal. +pub(super) fn seal(text: &str, endpoint: &str, ca: &Path, made: &mut Made) -> Sealed { let world = world(); let inputs = world.root.join("inputs").join("servers"); fs::create_dir_all(&inputs).unwrap(); @@ -184,6 +184,24 @@ fn run_once( .map(|entry| entry.path()) .find(|path| path.join("run.done").is_file()) .unwrap_or_else(|| panic!("a sealed run\n{log}")); + Sealed { + job, + world, + run_dir, + } +} + +/// Runs the experiment `text` with [`seal`] 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 Sealed { world, run_dir, .. } = seal(text, endpoint, ca, made); let inspected = Command::new(env!("CARGO_BIN_EXE_candler")) .arg("inspect") .arg(&run_dir) @@ -207,23 +225,18 @@ fn run_once( } } -/// 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); +/// The scripted fake model, started for one guard. +pub(super) struct Fake { + pub(super) id: String, + pub(super) endpoint: String, + pub(super) ca: PathBuf, + _scratch: tempfile::TempDir, +} + +/// Builds the fake model's image and starts it, labelled `label` and given `env`, recording +/// both in `made`; waits for it to be ready and copies out its certificate authority. +pub(super) fn start_fake(real: &Path, made: &mut Made, label: &str, env: &[String]) -> Fake { + let host = fake_host(real); let publish = format!( "{}::8443", if cfg!(target_os = "linux") { @@ -232,46 +245,39 @@ fn parity_one_installed_server_one_traced_call() { "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 - + made.real.clone_from(&real.to_path_buf()); // 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()); + let tag = format!("candler-fakemodel:{label}-{}", std::process::id()); + let marked = format!("candler.test={label}"); must( - &real, - &[ - "build", - "-q", - "--label", - "candler.test=parity", - "-t", - &tag, - context, - ], + real, + &["build", "-q", "--label", &marked, "-t", &tag, context], ); made.images.push(must( - &real, + 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, - ], - ); + let mut args = vec![ + "run".to_owned(), + "-d".to_owned(), + "--label".to_owned(), + marked, + "-p".to_owned(), + publish, + "-e".to_owned(), + format!("FAKE_TOKEN={TOKEN}"), + "-e".to_owned(), + format!("FAKE_HOST={host}"), + ]; + for setting in env { + args.push("-e".to_owned()); + args.push(setting.clone()); // BORROW: .clone() copies the setting + } + args.push(tag); + let words: Vec<&str> = args.iter().map(String::as_str).collect(); + let fake = must(real, &words); made.containers.push(fake.clone()); // BORROW: the cleanup owns its ids - let port = must(&real, &["port", &fake, "8443/tcp"]) + let port = must(real, &["port", &fake, "8443/tcp"]) .lines() .next() .and_then(|line| line.rsplit(':').next()) @@ -279,10 +285,10 @@ fn parity_one_installed_server_one_traced_call() { .to_owned(); assert!( wait_for(Duration::from_secs(30), || { - docker(&real, &["exec", &fake, "test", "-f", "/tmp/fake/ca.pem"]) + docker(real, &["exec", &fake, "test", "-f", "/tmp/fake/ca.pem"]) .status .success() - && docker(&real, &["logs", &fake]) + && docker(real, &["logs", &fake]) .stdout .windows(5) .any(|w| w == b"ready") @@ -292,38 +298,69 @@ fn parity_one_installed_server_one_traced_call() { let scratch = tempfile::tempdir().unwrap(); let ca = scratch.path().join("ca.pem"); must( - &real, + real, &[ "cp", &format!("{fake}:/tmp/fake/ca.pem"), &ca.display().to_string(), ], ); - let endpoint = format!("https://{host}:{port}"); + Fake { + endpoint: format!("https://{host}:{port}"), + id: fake, + ca, + _scratch: scratch, + } +} + +/// The experiment both cells share, with the line `[harness]` names left as `@HARNESS@`: the +/// shape's model replaced by `model`, its prompt by `prompt`, and the server `parity` declared. +pub(super) fn base_experiment(model: &str, prompt: &str) -> String { + 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\"", &format!("\"{model}\"")) + .replace("say hello", prompt) + .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" + ) +} + +/// 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 before = must(&real, &["ps", "-aq"]); + let mut made = Made::default(); + let fake = start_fake(&real, &mut made, "parity", &[]); + let (endpoint, ca) = (fake.endpoint.as_str(), fake.ca.as_path()); // 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 base = base_experiment( + "p1", + "Call the MCP tool stamp of the server parity once, then reply done.", + ); let claude = experiment(&base, "claude-code"); let opencode = experiment(&base, "opencode"); assert_eq!( @@ -339,9 +376,9 @@ fn parity_one_installed_server_one_traced_call() { ("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); + let skip = records(&real, &fake.id).lines().count(); + let seen = run_once(text, endpoint, ca, place, &mut made); + let answers = stamp_answers(&records(&real, &fake.id), skip); if !answers .iter() .any(|(error, text)| !error && text.contains(STAMP)) From 20c190e70e1118e80facb3a236ecf8165bbeae3b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:08:47 +0900 Subject: [PATCH 72/93] reports(library): close the graded run's trace Leaf report of the guard that grades a real run on each harness by its trace: the guard, both bites with their failing messages, the local run, what the probe P0 asks that it does not cover, and the spec defects met. Co-Authored-By: Claude Opus 5.5 --- .../leaves/graded_run_sees_trace_v0.md | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 __reports__/run-context/leaves/graded_run_sees_trace_v0.md diff --git a/__reports__/run-context/leaves/graded_run_sees_trace_v0.md b/__reports__/run-context/leaves/graded_run_sees_trace_v0.md new file mode 100644 index 00000000..40e78f40 --- /dev/null +++ b/__reports__/run-context/leaves/graded_run_sees_trace_v0.md @@ -0,0 +1,57 @@ +# Leaf report: graded run sees trace + +Leaf: `__roadmap__/run_context/readers/e2e/graded_run_sees_trace.md`. Branch `leaf/run-context/graded_run_sees_trace`, cut from `feat/run-context` at `9d337922`. No pull request was opened and nothing was pushed; publishing waits on the maintainer's go. + +## The guard + +`guard_cli_e2e::graded_trace_e2e::graded_run_sees_trace`, in `crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs`, `#[ignore]` like the parity guard and named in `container-e2e.yml`'s expected-guard list. + +| Part | What it is | +|---|---| +| Rig | The parity guard's: real Claude Code and OpenCode in their base images, the production gateway, the scripted fake model. The fake model's start, the shared experiment and the sealing of one run are now functions both guards call (`start_fake`, `base_experiment`, `seal`). | +| Script | New fake-model id `g1`: the shell command `printf 'graded-answer-3f9a\n' > answer.txt` (exit 0), `exit 3`, then the `parity` server's `stamp` tool. The commands reach the fake model from the guard (`FAKE_G1_COMMANDS`), so the guard holds them once. | +| Kind | `tests/fixtures/plugins/graded-trace/`: `graded_run`, declaring `needs.trace = true` and an artifact glob, reading the trace with the helper's `read_trace`. It pairs a call's `argv` with its result's `exit` by `span`. It passes only if each expected `(argv, exit)` pair, the origin `{kind: mcp, server: parity, tool: stamp}` and the served `answer.txt` with its text are each held exactly once. Equality on whole values, no substring. | +| Oracle | The script's own commands, read back from the requests the fake model recorded; the exit statuses a shell gives them; the server and tool the script calls. | +| Grading | `candler evaluate` over the sealed run's store; the outcome record must be one `pass` and the report must refuse nothing. | + +How each real binary reports a shell call: both give `argv = [input.command]`, the whole command string as one element. Claude Code's tool is `Bash`; OpenCode's is `shell`. + +## Bites + +Each applied on a scratch branch from the guard's commit, one at a time, run with `--run-ignored only`, then the branch deleted. + +| Bite | Result | Failing message | +|---|---|---| +| (a) `assemble` serves no trace (`if needs.trace` made never true, `assemble.rs`) | both rows red | `claude-code: the kind did not pass once: [{... "evidence": [{"note": "the context serves no trace"}], "status": "fail" ...}]`, and the same line for `opencode` | +| (b) the OpenCode reader writes no `exit` (`export.rs`, `exit` replaced by none on the result) | OpenCode row red, Claude Code's green | `opencode: the kind did not pass once: [{... "note": "([\"printf 'graded-answer-3f9a\\n' > answer.txt\"], {'kind': 'code', 'code': 0}) is held 0 times among []; (['exit 3'], {'kind': 'code', 'code': 3}) is held 0 times among []" ... "status": "fail"}]`; no `claude-code:` line | + +## Local run + +On the tip, `cargo nextest run -p candler --test it -E 'test(/^guard_cli_e2e::/)' --run-ignored only --test-threads 1` gave: + +``` +PASS [ 24.728s] (1/4) candler::it guard_cli_e2e::graded_trace_e2e::graded_run_sees_trace +PASS [ 105.989s] (2/4) candler::it guard_cli_e2e::i8_e2e::i8_canary_never_reaches_the_agent +PASS [ 25.915s] (3/4) candler::it guard_cli_e2e::kill_e2e::b40_kill_all_destroys_lost_jobs_containers +PASS [ 26.240s] (4/4) candler::it guard_cli_e2e::parity_e2e::parity_one_installed_server_one_traced_call +Summary [ 182.873s] 4 tests run: 4 passed +``` + +The guard grades both harnesses in the one test, so its single PASS line covers Claude Code and OpenCode. Without `--test-threads 1` the parity and i8 guards failed on other containers of the machine, as the defect below says. + +The container-e2e PASS gate is waiting on a pull request. + +## What the guard does not cover of P0 + +The guard asks P0's question: does a kind that needs an artifact and the trace see each shell call's command and exit status and each MCP call's `{server, tool}`, on a real run. It does not cover P0's own kind or P0's suite: not their code, their params, the other kinds a request of that suite sends beside it (the engine serves a request the union of its kinds' needs), their evaluator environment, or the release HTN pins (this guard runs the workspace build). It does not cover HTN's agent task, a real model's tool use, a signalled or timed-out shell call, a denied call, or a shell call inside OpenCode's code mode. + +## Spec defects met + +- The leaf says `needs.artifacts = ["answer.txt"]`. The registry refuses it: `plugin.need_glob_outside_outputs`, "artifact glob `answer.txt` is not under `outputs/`". The kind declares `outputs/answer.txt`; the served path is `answer.txt`. The `Needs.artifacts` doc ("globs, relative to the run's outputs") says the opposite of the check. +- OpenCode's shell tool is `shell`, takes no `description` and refuses extra keys, so the script sends `{command}` alone to both harnesses. +- The parity guard's `ps -aq` equality is false on a machine other sessions share, and under parallel nextest threads. The new guard checks leftovers by its own labels and job ids instead; the parity guard is unchanged in that respect. +- Not run: the `rust-conventions` reviewer agent on the new Rust. + +## Left + +The `container-e2e` PASS line, and the coordinator's verifier. Nothing else. From 821fb4c8556eab093afa7ddf226b7912223b14af Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:17:20 +0900 Subject: [PATCH 73/93] docs(schemas): say an artifact glob starts with outputs/ The registry refuses a glob that is not under `outputs/`, where the `Needs.artifacts` doc said the globs were relative to the run's outputs. The doc now says each starts with `outputs/` and that the artifact is served at its path inside it. The schemas, the helper's models, the architecture note and the leaf's gate follow. Co-Authored-By: Claude Opus 5.5 --- __design__/architecture.md | 2 +- __roadmap__/run_context/readers/e2e/graded_run_sees_trace.md | 2 +- .../schema/evaluator-describe-result.schema.json | 2 +- crates/candler-schemas/schema/evaluator-message.schema.json | 2 +- crates/candler-schemas/src/evaluation.rs | 2 +- .../candler_evaluator/_models/evaluator_describe_result.py | 4 ++-- .../src/candler_evaluator/_models/evaluator_message.py | 4 ++-- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/__design__/architecture.md b/__design__/architecture.md index a899dede..6f407ed3 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -1026,7 +1026,7 @@ as the evaluator's log. | ↳ result | | response | `{reported: n}` | | `cancel` | core → evaluator | notification | request id; the evaluator answers `evaluate` with error `-32800` (request cancelled) | -**`needs`** = `{trace: bool, raw: bool, manifest: bool, artifacts[] (globs relative to the run's outputs), +**`needs`** = `{trace: bool, raw: bool, manifest: bool, artifacts[] (globs relative to the run, each starting with `outputs/`), snapshots[] (kinds), inputs[] (kinds), metadata[] (run-manifest field paths)}`; `raw` and `manifest` read as `false` when absent. `resolve` checks every need the core can meet without a run; an `inputs` need for `build_inputs` is refused there, by name. A need a run cannot diff --git a/__roadmap__/run_context/readers/e2e/graded_run_sees_trace.md b/__roadmap__/run_context/readers/e2e/graded_run_sees_trace.md index fb59f10c..b0a0b611 100644 --- a/__roadmap__/run_context/readers/e2e/graded_run_sees_trace.md +++ b/__roadmap__/run_context/readers/e2e/graded_run_sees_trace.md @@ -7,7 +7,7 @@ - [ ] `[nl]` Every `../` leaf is `done` and merged into `feat/run-context` - [ ] `[cmd]` `docker info` answers (never stop Docker, never prune) **Success Gates**: -- ⬜ A new guard in `crates/candler/tests/it/guard_cli_e2e/`, on the `parity_e2e.rs` rig (both real harnesses, the production gateway, the scripted fake model), runs one cell per harness whose script writes `answer.txt` with a command that exits 0, runs `exit 3`, and calls the `parity` server's `stamp` tool. It then grades each run with a plug-in kind that declares `needs.trace = true` and `needs.artifacts = ["answer.txt"]`. The kind passes only if the trace holds the pairs `(argv, exit)` for both commands and the origin `{kind: mcp, server: parity, tool: stamp}`, and `answer.txt` is served. The oracle is the fake-model script's own commands, not Candler's output +- ⬜ A new guard in `crates/candler/tests/it/guard_cli_e2e/`, on the `parity_e2e.rs` rig (both real harnesses, the production gateway, the scripted fake model), runs one cell per harness whose script writes `answer.txt` with a command that exits 0, runs `exit 3`, and calls the `parity` server's `stamp` tool. It then grades each run with a plug-in kind that declares `needs.trace = true` and `needs.artifacts = ["outputs/answer.txt"]`. The kind passes only if the trace holds the pairs `(argv, exit)` for both commands and the origin `{kind: mcp, server: parity, tool: stamp}`, and `answer.txt` is served. The oracle is the fake-model script's own commands, not Candler's output - ⬜ The guard is `#[ignore]` like the parity guard, joins `.github/workflows/container-e2e.yml`'s expected-guard list, and is listed as PASS in a `container-e2e` run on this leaf's pull request; the report quotes the PASS line - ⬜ Each of two bites turns the guard red, and the report records the failing message: (a) `assemble` serves no trace (the outcome is a fail or a refusal, not a pass); (b) the OpenCode reader writes no `exit` (the OpenCode row goes red while Claude Code's stays green) - ⬜ The guard asks the question htn-creator-eval's probe P0 asks; the report says which parts of P0 it does not cover (P0's own kind and suite) diff --git a/crates/candler-schemas/schema/evaluator-describe-result.schema.json b/crates/candler-schemas/schema/evaluator-describe-result.schema.json index cfb2fe55..18a744f4 100644 --- a/crates/candler-schemas/schema/evaluator-describe-result.schema.json +++ b/crates/candler-schemas/schema/evaluator-describe-result.schema.json @@ -154,7 +154,7 @@ "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A request is served the union of the needs of the kinds it sends, and a part the run does not store refuses the request.", "properties": { "artifacts": { - "description": "Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced.", + "description": "Globs, relative to the run, of the artifacts the check reads; each starts with `outputs/`. The artifacts are the files the run produced, each served at its path inside `outputs/`.", "items": { "type": "string" }, diff --git a/crates/candler-schemas/schema/evaluator-message.schema.json b/crates/candler-schemas/schema/evaluator-message.schema.json index 6e8b41f6..e6a1deec 100644 --- a/crates/candler-schemas/schema/evaluator-message.schema.json +++ b/crates/candler-schemas/schema/evaluator-message.schema.json @@ -509,7 +509,7 @@ "description": "What one kind of check needs from a run, written as an object: `trace`, `artifacts`, `snapshots`, `inputs` and `metadata` are present, the lists empty when the kind needs nothing of that sort, and `raw` and `manifest` are `false` when absent. A request is served the union of the needs of the kinds it sends, and a part the run does not store refuses the request.", "properties": { "artifacts": { - "description": "Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced.", + "description": "Globs, relative to the run, of the artifacts the check reads; each starts with `outputs/`. The artifacts are the files the run produced, each served at its path inside `outputs/`.", "items": { "type": "string" }, diff --git a/crates/candler-schemas/src/evaluation.rs b/crates/candler-schemas/src/evaluation.rs index 2ee054c2..4ba27208 100644 --- a/crates/candler-schemas/src/evaluation.rs +++ b/crates/candler-schemas/src/evaluation.rs @@ -1346,7 +1346,7 @@ pub struct Needs { /// Whether the check reads the run's manifest, served as `context.manifest` when a kind of the request needs it. The manifest holds the factors and provenance of the run, its usage, its tool census, how it ended and the exit of its process. #[serde(default)] pub manifest: bool, - /// Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced. + /// Globs, relative to the run, of the artifacts the check reads; each starts with `outputs/`. The artifacts are the files the run produced, each served at its path inside `outputs/`. pub artifacts: Vec, /// 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 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 fe4ac473..9e03accf 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: 3b17c65c37679bad6ee2414fab11de0fc7f0479a966edb518e9c25e73c5d4593 +# sha256: 3b3c48c7af23cc47652fd6247fee6bdc544ef22da0c372c5581e8a6aa1a82c51 from __future__ import annotations @@ -92,7 +92,7 @@ class Needs(BaseModel): artifacts: Annotated[ list[str], Field( - description="Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced." + description="Globs, relative to the run, of the artifacts the check reads; each starts with `outputs/`. The artifacts are the files the run produced, each served at its path inside `outputs/`." ), ] inputs: Annotated[ 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 ba5fcbc3..b111bab6 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: 042dcb6c101a5046793beec6c891b40a7d3ef83cf83478698940e1ddf13453fe +# sha256: 615c1cda14e917397c9e51ad4c7d17fbaefb37d79e99cf81244349b1c02b45ba from __future__ import annotations @@ -166,7 +166,7 @@ class Needs(BaseModel): artifacts: Annotated[ list[str], Field( - description="Globs, relative to the run's outputs, of the artifacts the check reads. The artifacts are the files the run produced." + description="Globs, relative to the run, of the artifacts the check reads; each starts with `outputs/`. The artifacts are the files the run produced, each served at its path inside `outputs/`." ), ] inputs: Annotated[ From 5b0ca049d92abe7d736e093353a822ad7ac482ab Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:37:16 +0900 Subject: [PATCH 74/93] test(library): share the seam helpers and clean every job `Made` keeps every job a guard started, so a failed guard no longer leaks the first harness's containers and networks. The seam helpers have one copy in `support/seam.rs`: the plug-in setup takes the fixture directory, `evaluate` takes the suite, and `outcome_records` reads the store; the input-seam, run-evaluate and graded guards use them. The graded kind pairs a call with its result by session and span, the guard reads the fake model's records once per harness and checks that the product left nothing behind before the cleanup, and its suite is rendered as TOML. Co-Authored-By: Claude Opus 5.5 --- .../graded-trace/kinds/graded_trace.py | 9 +- .../it/guard_cli_e2e/graded_trace_e2e.rs | 163 +++++++----------- .../candler/tests/it/guard_cli_e2e/i8_e2e.rs | 6 +- .../tests/it/guard_cli_e2e/parity_e2e.rs | 38 ++-- crates/candler/tests/it/guard_input_seam.rs | 21 +-- crates/candler/tests/it/guard_run_evaluate.rs | 47 +---- crates/candler/tests/it/support/seam.rs | 47 +++-- 7 files changed, 125 insertions(+), 206 deletions(-) diff --git a/crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py b/crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py index f5226245..6ed183df 100644 --- a/crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py +++ b/crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py @@ -23,7 +23,7 @@ def graded_run(params, context, prior): artifact `params` names is served with its text.""" if context.trace is None: return _verdict(["the context serves no trace"], "") - argv_of = {} + argv_of = {} # keyed by (session, span): a span is the harness's id within one session pairs = [] origins = [] for record in read_trace(context.trace): @@ -31,12 +31,13 @@ def graded_run(params, context, prior): continue body = record.event.kind.root.model_dump(mode="json") span = record.event.span.root if hasattr(record.event.span, "root") else None + key = (record.session.root, span) if body["kind"] == "tool_call": origins.append(body["origin"]) if "argv" in body: - argv_of[span] = body["argv"] - elif body["kind"] == "tool_result" and span is not None and span in argv_of and "exit" in body: - pairs.append((argv_of[span], body["exit"])) + argv_of[key] = body["argv"] + elif body["kind"] == "tool_result" and span is not None and key in argv_of and "exit" in body: + pairs.append((argv_of[key], body["exit"])) problems = [] for shell in params["shell"]: want = (shell["argv"], {"kind": "code", "code": shell["exit"]}) diff --git a/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs index 65da30e7..77c53de3 100644 --- a/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs @@ -4,20 +4,17 @@ //! image, behind the production gateway sidecar, against the scripted fake model (model `g1`). //! The script is two shell commands, `printf ... > answer.txt` (exit 0) and `exit 3`, then the //! call of the tool `stamp` of the server `parity`. `candler evaluate` grades each sealed run -//! with a plug-in kind that declares `needs.trace` and `needs.artifacts = ["answer.txt"]`. +//! with a plug-in kind that declares `needs.trace` and `needs.artifacts = ["outputs/answer.txt"]`, +//! which the context serves as `answer.txt`. use std::fs; -use std::os::unix::fs::symlink; -use std::path::PathBuf; -use std::process::{Command, Stdio}; -use candler_core::store::layout::StoreLayout; use serde_json::{Value, json}; use super::i8_e2e::{Made, must}; use super::parity_e2e::{SERVER, Sealed, base_experiment, records, seal, start_fake}; use super::real_docker; use crate::support::cli_run::World; -use crate::support::seam::{entries_under, sync_environment}; +use crate::support::seam::{self, sync_environment}; /// The command that writes the answer file and exits 0. const WRITE: &str = "printf 'graded-answer-3f9a\\n' > answer.txt"; @@ -28,46 +25,29 @@ const ANSWER: &str = "graded-answer-3f9a\n"; /// The command that exits 3. const EXIT: &str = "exit 3"; -/// The plug-in's directory below the fixtures. -fn fixture() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/plugins/graded-trace") -} - /// The suite of one gate whose params are the script's: each command with the exit status it /// must show in the trace, the origin of the stamp call and the answer file. fn suite(shell: &[(&str, i32)]) -> String { - let mut parts = vec![format!( - "schema = \"suite/1\"\n\n[[expectations]]\nid = \"G1\"\nrole = \"gate\"\nkind = \"graded_run\"\n\ - depends_on = []\n\n[expectations.evaluator]\nname = \"graded-trace\"\nrange = \"^0.1\"\n\n\ - [expectations.params]\norigin = {{ kind = \"mcp\", server = \"{SERVER}\", tool = \"stamp\" }}\n" - )]; - parts.extend(shell.iter().map(|(command, code)| { - format!( - "[[expectations.params.shell]]\nargv = {}\nexit = {code}\n", - json!([command]) - ) - })); - parts.push(format!( - "[expectations.params.artifact]\npath = \"answer.txt\"\ntext = {}\n", - json!(ANSWER) - )); - parts.join("\n") -} - -/// Sets the plug-in up in the world, with the helper's project linked beside it, and returns its -/// directory and the suite. -fn plugin(world: &World) -> (PathBuf, PathBuf) { - let dir = world.root.join("graded-trace"); - fs::create_dir_all(&dir).unwrap(); - let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../python/candler-evaluator"); - symlink(helper, dir.join("env")).unwrap(); - let manifest = fs::read_to_string(fixture().join("plugin.toml")) - .unwrap() - .replace("@KINDS@", &fixture().join("kinds").display().to_string()); - fs::write(dir.join("plugin.toml"), manifest).unwrap(); - let suite_file = dir.join("suite.toml"); - fs::write(&suite_file, suite(&[(WRITE, 0), (EXIT, 3)])).unwrap(); - (dir, suite_file) + let calls: Vec = shell + .iter() + .map(|(command, code)| json!({"argv": [command], "exit": code})) + .collect(); + let document = json!({ + "schema": "suite/1", + "expectations": [{ + "id": "G1", + "role": "gate", + "kind": "graded_run", + "depends_on": [], + "evaluator": {"name": "graded-trace", "range": "^0.1"}, + "params": { + "origin": {"kind": "mcp", "server": SERVER, "tool": "stamp"}, + "shell": calls, + "artifact": {"path": "answer.txt", "text": ANSWER}, + }, + }], + }); + toml::to_string(&document).unwrap() } /// The commands of the shell calls the fake model made in the requests after the first `skip` @@ -87,7 +67,9 @@ fn scripted_commands(records: &str, skip: usize) -> Vec { .filter(|message| message["role"] == "assistant") .flat_map(|message| message["content"].as_array().into_iter().flatten()) .filter(|block| block["type"] == "tool_use" && block["input"]["command"].is_string()) - .filter_map(|block| block["input"]["command"].as_str().map(str::to_owned)) + .filter_map(|block| { + block["input"]["command"].as_str().map(str::to_owned) // BORROW: .to_owned() makes each command owned + }) .collect(); if held >= size { size = held; @@ -100,28 +82,11 @@ fn scripted_commands(records: &str, skip: usize) -> Vec { /// Grades the sealed run of `world` with the plug-in and returns what went wrong, one line each: /// an evaluation that fails, or an outcome that is not one pass. fn graded(world: &World) -> Vec { - let (dir, suite_file) = plugin(world); + let manifest = seam::plugin(world, &seam::fixture("graded-trace")); + let suite_file = world.root.join("suite.toml"); + fs::write(&suite_file, suite(&[(WRITE, 0), (EXIT, 3)])).unwrap(); sync_environment(world); - let project = world.root.join("project"); - fs::create_dir_all(&project).unwrap(); - fs::write( - project.join("candler.toml"), - format!("[plugins]\ndirs = [\"{}\"]\n", dir.display()), - ) - .unwrap(); - let evaluated = Command::new(env!("CARGO_BIN_EXE_candler")) - .arg("--store") - .arg(world.store()) - .arg("evaluate") - .arg(&suite_file) - .current_dir(&project) - .env_remove("CANDLER_STORE") - .env("HOME", world.root.join("home")) - .env("XDG_CONFIG_HOME", world.root.join("config")) - .env("XDG_STATE_HOME", &world.state) - .stdin(Stdio::null()) - .output() - .unwrap(); + let evaluated = seam::evaluate(world, &manifest, &suite_file); let stdout = String::from_utf8_lossy(&evaluated.stdout).into_owned(); let stderr = String::from_utf8_lossy(&evaluated.stderr).into_owned(); if !evaluated.status.success() { @@ -136,18 +101,8 @@ fn graded(world: &World) -> Vec { Ok(report) => problems.push(format!("the evaluation refused a request: {report}")), Err(error) => problems.push(format!("the report is not JSON ({error}): {stdout}")), } - let layout = StoreLayout::new(&world.store()); - let outcomes: Vec = entries_under(&layout.outcomes_dir()) - .iter() - .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl")) - .flat_map(|path| { - fs::read_to_string(path) - .unwrap_or_default() - .lines() - .filter_map(|line| serde_json::from_str::(line).ok()) - .collect::>() - }) - .collect(); + let outcomes = seam::outcome_records(world); + // INDEX: `outcomes[0]` is read only when the length on the left of `||` is not 1 if outcomes.len() != 1 || outcomes[0]["status"] != "pass" { problems.push(format!("the kind did not pass once: {outcomes:?}")); } @@ -158,16 +113,16 @@ fn graded(world: &World) -> Vec { /// needs the trace sees each shell call's command and exit status and each MCP call's server and /// tool, on every harness) -- one experiment, run with the real `candler run` on Claude Code and /// on `OpenCode` and graded with `candler evaluate`, passes a kind that declares `needs.trace` -/// and `needs.artifacts = ["answer.txt"]` only when its trace holds, for each of the two shell -/// commands, the pair of the command's argv and its exit status, the origin of the `stamp` call, -/// and the served `answer.txt` holds the text the first command wrote. +/// and `needs.artifacts = ["outputs/answer.txt"]` (served as `answer.txt`) only when its trace +/// holds, for each of the two shell commands, the pair of the command's argv and its exit +/// status, the origin of the `stamp` call, and the served `answer.txt` holds the text the first +/// command wrote. The containers the job made are gone when the guard ends. /// /// Oracle: the fake model's own script: the commands it sent (read back from the requests it /// recorded), the exit statuses a shell gives them (0 and 3), and the server and tool it calls. /// -/// Bite: `assemble` serving no trace (the kind's outcome is a fail or the evaluation a refusal), -/// or the `OpenCode` reader writing no `exit` (the `OpenCode` row fails, the Claude Code row does -/// not). +/// Bite: `assemble` serving no trace (the kind's outcome is a fail), or `tool_drafts` of the +/// `OpenCode` reader writing no `exit` (the `OpenCode` row fails, the Claude Code row does not). #[test] #[ignore = "needs Docker; run with --run-ignored only"] fn graded_run_sees_trace() { @@ -185,23 +140,18 @@ fn graded_run_sees_trace() { "Run the commands you are given, call the MCP tool stamp of the server parity, then reply done.", ); let mut failures = Vec::new(); - let mut jobs = Vec::new(); + let mut skip = records(&real, &fake.id).lines().count(); for harness in ["claude-code", "opencode"] { - let skip = records(&real, &fake.id).lines().count(); - let Sealed { - job, - world, - run_dir, - } = seal( + let Sealed { world, run_dir, .. } = seal( &base.replace("@HARNESS@", harness), &fake.endpoint, &fake.ca, &mut made, ); - jobs.push(job); - let sent = scripted_commands(&records(&real, &fake.id), skip); + let recorded = records(&real, &fake.id); + let sent = scripted_commands(&recorded, skip); if sent != [WRITE, EXIT] { - let seen: Vec = records(&real, &fake.id) + let requests: Vec = recorded .lines() .skip(skip) .map(|line| { @@ -210,9 +160,10 @@ fn graded_run_sees_trace() { }) .collect(); failures.push(format!( - "{harness}: the model's commands were {sent:?}; requests: {seen:?}" + "{harness}: the model's commands were {sent:?}; requests: {requests:?}" )); } + skip = recorded.lines().count(); if !run_dir.join("trace.jsonl").is_file() { failures.push(format!("{harness}: the run stored no trace")); } @@ -222,16 +173,22 @@ fn graded_run_sees_trace() { .map(|problem| format!("{harness}: {problem}")), ); } - drop(made); - // the containers this guard started, by their labels: the machine's other containers are not - // this guard's to count - let mut labels = vec!["candler.test=graded-trace".to_owned()]; - labels.extend(jobs.iter().map(|job| format!("candler.job={job}"))); - for label in labels { - let left = must(&real, &["ps", "-aq", "--filter", &format!("label={label}")]); - if !left.is_empty() { - failures.push(format!("containers of {label} are left behind: {left}")); + // what the product left behind, by the labels of the jobs it ran: the machine's other + // containers are not this guard's to count + for job in &made.jobs { + let label = format!("label=candler.job={job}"); + for args in [["ps", "-aq"], ["network", "ls"]] { + let mut words = args.to_vec(); + if args[0] == "network" { + words.push("-q"); + } + words.extend(["--filter", &label]); + let left = must(&real, &words); + if !left.is_empty() { + failures.push(format!("{} of {label} left behind: {left}", args[0])); + } } } + drop(made); assert!(failures.is_empty(), "{failures:#?}"); } 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 601d131a..70e3e571 100644 --- a/crates/candler/tests/it/guard_cli_e2e/i8_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/i8_e2e.rs @@ -73,14 +73,14 @@ fn ere_escape(text: &str) -> String { #[derive(Default)] pub(super) struct Made { pub(super) real: PathBuf, - pub(super) job: Option, + pub(super) jobs: Vec, pub(super) containers: Vec, pub(super) images: Vec, } impl Drop for Made { fn drop(&mut self) { - if let Some(job) = &self.job { + for job in &self.jobs { let filter = format!("label=candler.job={job}"); for kind in [["ps", "-aq"], ["network", "ls"]] { let mut args: Vec<&str> = kind.to_vec(); @@ -394,7 +394,7 @@ fn i8_canary_never_reaches_the_agent() { String::from_utf8_lossy(&launched.stderr) ); let job = stdout.trim().to_owned(); - made.job = Some(job.clone()); // BORROW: the cleanup owns the job id + made.jobs.push(job.clone()); // BORROW: the cleanup owns the job id let dir = JobDir::open( &StoreLayout::new(&(world.work.join(".candler").join("store"))), &job.parse().unwrap(), diff --git a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs index 0facd729..14156a39 100644 --- a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs @@ -115,8 +115,9 @@ fn call_origins(text: &str) -> Vec { /// A run `candler run` sealed in its own world. pub(super) struct Sealed { - pub(super) job: String, + /// The world the run was made in; dropping it removes its directories. pub(super) world: World, + /// The run's directory in the world's store. pub(super) run_dir: PathBuf, } @@ -168,7 +169,7 @@ pub(super) fn seal(text: &str, endpoint: &str, ca: &Path, made: &mut Made) -> Se String::from_utf8_lossy(&launched.stderr) ); let job = stdout.trim().to_owned(); - made.job = Some(job.clone()); // BORROW: the cleanup owns the job id + made.jobs.push(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), || { @@ -184,11 +185,7 @@ pub(super) fn seal(text: &str, endpoint: &str, ca: &Path, made: &mut Made) -> Se .map(|entry| entry.path()) .find(|path| path.join("run.done").is_file()) .unwrap_or_else(|| panic!("a sealed run\n{log}")); - Sealed { - job, - world, - run_dir, - } + Sealed { world, run_dir } } /// Runs the experiment `text` with [`seal`] and reads back what the sealed run stored, the MCP @@ -227,9 +224,13 @@ fn run_once( /// The scripted fake model, started for one guard. pub(super) struct Fake { + /// The id of the fake model's container. pub(super) id: String, + /// The `https` address the gateway reaches the fake model at. pub(super) endpoint: String, + /// The path of the fake model's certificate authority, copied out of its container. pub(super) ca: PathBuf, + /// The directory that holds `ca.pem`; it keeps the file alive for as long as the fake lives. _scratch: tempfile::TempDir, } @@ -245,7 +246,7 @@ pub(super) fn start_fake(real: &Path, made: &mut Made, label: &str, env: &[Strin "127.0.0.1" } ); - made.real.clone_from(&real.to_path_buf()); // BORROW: the cleanup owns its client path + made.real = real.to_owned(); // BORROW: the cleanup owns its client path let context = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/docker/fakemodel"); let tag = format!("candler-fakemodel:{label}-{}", std::process::id()); let marked = format!("candler.test={label}"); @@ -257,24 +258,15 @@ pub(super) fn start_fake(real: &Path, made: &mut Made, label: &str, env: &[Strin real, &["image", "inspect", "--format", "{{.Id}}", &tag], )); - let mut args = vec![ - "run".to_owned(), - "-d".to_owned(), - "--label".to_owned(), - marked, - "-p".to_owned(), - publish, - "-e".to_owned(), - format!("FAKE_TOKEN={TOKEN}"), - "-e".to_owned(), - format!("FAKE_HOST={host}"), + let token = format!("FAKE_TOKEN={TOKEN}"); + let named = format!("FAKE_HOST={host}"); + let mut words = vec![ + "run", "-d", "--label", &marked, "-p", &publish, "-e", &token, "-e", &named, ]; for setting in env { - args.push("-e".to_owned()); - args.push(setting.clone()); // BORROW: .clone() copies the setting + words.extend(["-e", setting.as_str()]); } - args.push(tag); - let words: Vec<&str> = args.iter().map(String::as_str).collect(); + words.push(&tag); let fake = must(real, &words); made.containers.push(fake.clone()); // BORROW: the cleanup owns its ids let port = must(real, &["port", &fake, "8443/tcp"]) diff --git a/crates/candler/tests/it/guard_input_seam.rs b/crates/candler/tests/it/guard_input_seam.rs index 22b2bd3c..d4194d61 100644 --- a/crates/candler/tests/it/guard_input_seam.rs +++ b/crates/candler/tests/it/guard_input_seam.rs @@ -14,8 +14,8 @@ use serde_json::Value; use cli_run::world; use seam::{ - CANARY_BYTES, CANARY_NAME, declare_inputs, entries_under, evaluate, file_hashes, finish, - list_digest, occurrences, servers_tree, sync_environment, truth_tree, + CANARY_BYTES, CANARY_NAME, declare_inputs, evaluate, file_hashes, finish, list_digest, + occurrences, outcome_records, servers_tree, sync_environment, truth_tree, }; /// What the plug-in reported for one input kind. @@ -27,18 +27,7 @@ struct Seen { /// The `evidence` note of the one outcome record `evaluate` wrote, by input kind. fn reported(world: &cli_run::World) -> BTreeMap { - let layout = StoreLayout::new(&world.store()); - let records: Vec = entries_under(&layout.outcomes_dir()) - .iter() - .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl")) - .flat_map(|path| { - fs::read_to_string(path) - .unwrap() - .lines() - .map(|line| serde_json::from_str::(line).unwrap()) - .collect::>() - }) - .collect(); + let records = outcome_records(world); assert_eq!(records.len(), 1, "one outcome record: {records:?}"); let record = &records[0]; assert_eq!(record["status"], "pass", "the plug-in passed: {record}"); @@ -92,12 +81,12 @@ fn reported(world: &cli_run::World) -> BTreeMap { fn input_seam_plugin_reads_both_trees_and_the_agent_never_held_the_canary() { let world = world(); declare_inputs(&world); - let manifest = seam::plugin(&world); + let manifest = seam::plugin(&world, &seam::fixture("needs-inputs")); sync_environment(&world); let launched = world.launch(); let job = finish(&world, &launched); - let evaluated = evaluate(&world, &manifest); + let evaluated = evaluate(&world, &manifest, &seam::suite()); let stderr = String::from_utf8_lossy(&evaluated.stderr).into_owned(); assert!( evaluated.status.success(), diff --git a/crates/candler/tests/it/guard_run_evaluate.rs b/crates/candler/tests/it/guard_run_evaluate.rs index 7dd8ee98..60e3f01f 100644 --- a/crates/candler/tests/it/guard_run_evaluate.rs +++ b/crates/candler/tests/it/guard_run_evaluate.rs @@ -4,12 +4,11 @@ #![cfg(unix)] use crate::support::cli_run::{self, AGENT_BYTES, AGENT_FILE, World}; -use crate::support::seam::{entries_under, finish, shasum, sync_environment}; +use crate::support::seam::{self, finish, shasum, sync_environment}; use std::fs; use std::os::unix::fs::symlink; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output, Stdio}; +use std::path::PathBuf; use candler_core::store::layout::StoreLayout; use serde_json::Value; @@ -91,34 +90,6 @@ lock = "env/uv.lock" (manifest, suite) } -/// Runs `candler evaluate` over the store of the world with `suite`, from a project directory -/// whose `candler.toml` lists the manifest's directory under `plugins.dirs`. -fn evaluate(world: &World, manifest: &Path, suite: &Path) -> Output { - let project = world.root.join("project"); - fs::create_dir_all(&project).unwrap(); - fs::write( - project.join("candler.toml"), - format!( - "[plugins]\ndirs = [\"{}\"]\n", - manifest.parent().unwrap().display() - ), - ) - .unwrap(); - Command::new(env!("CARGO_BIN_EXE_candler")) - .arg("--store") - .arg(world.store()) - .arg("evaluate") - .arg(suite) - .current_dir(&project) - .env_remove("CANDLER_STORE") - .env("HOME", world.root.join("home")) - .env("XDG_CONFIG_HOME", world.root.join("config")) - .env("XDG_STATE_HOME", &world.state) - .stdin(Stdio::null()) - .output() - .unwrap() -} - /// The one sealed run directory of the store. fn sealed_run(layout: &StoreLayout) -> PathBuf { let runs: Vec = fs::read_dir(layout.runs_dir()) @@ -153,7 +124,7 @@ fn a_run_that_writes_a_file_is_graded_from_its_stored_bytes() { let run = sealed_run(&layout); let want = shasum(AGENT_BYTES.as_bytes()); - let evaluated = evaluate(&world, &manifest, &suite); + let evaluated = seam::evaluate(&world, &manifest, &suite); let stderr = String::from_utf8_lossy(&evaluated.stderr).into_owned(); let stdout = String::from_utf8_lossy(&evaluated.stdout).into_owned(); assert!( @@ -164,17 +135,7 @@ fn a_run_that_writes_a_file_is_graded_from_its_stored_bytes() { let report: Value = serde_json::from_slice(&evaluated.stdout).unwrap(); assert_eq!(report["failed_requests"], serde_json::json!([]), "{report}"); - let records: Vec = entries_under(&layout.outcomes_dir()) - .iter() - .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl")) - .flat_map(|path| { - fs::read_to_string(path) - .unwrap() - .lines() - .map(|line| serde_json::from_str::(line).unwrap()) - .collect::>() - }) - .collect(); + let records = seam::outcome_records(&world); assert_eq!(records.len(), 1, "one outcome record: {records:?}"); assert_eq!( records[0]["status"], "pass", diff --git a/crates/candler/tests/it/support/seam.rs b/crates/candler/tests/it/support/seam.rs index 56b26046..2e805b56 100644 --- a/crates/candler/tests/it/support/seam.rs +++ b/crates/candler/tests/it/support/seam.rs @@ -14,6 +14,7 @@ use candler_core::jobs::dir::JobDir; use candler_core::jobs::lock::{JobLock, LockState}; use candler_core::store::layout::StoreLayout; use candler_schemas::primitives::JobId; +use serde_json::Value; use super::cli_run::{World, wait_for}; @@ -114,25 +115,27 @@ fn helper() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../python/candler-evaluator") } -/// The fixture plug-in's directory. -fn fixture() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/plugins/needs-inputs") +/// The directory of the fixture plug-in `name` below `tests/fixtures/plugins`. +pub fn fixture(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/plugins") + .join(name) } -/// The fixture plug-in's suite. +/// The suite of the `needs-inputs` fixture plug-in. pub fn suite() -> PathBuf { - fixture().join("suite.toml") + fixture("needs-inputs").join("suite.toml") } -/// Sets the fixture plug-in up in the world: its manifest with the kinds directory filled in, -/// and a link to the helper's project. Returns the manifest. -pub fn plugin(world: &World) -> PathBuf { +/// Sets the fixture plug-in in `fixture` up in the world: its manifest with the kinds directory +/// filled in, and a link to the helper's project. Returns the manifest. +pub fn plugin(world: &World, fixture: &Path) -> PathBuf { let dir = world.root.join("plugin"); fs::create_dir_all(&dir).unwrap(); symlink(helper(), dir.join("env")).unwrap(); - let manifest = fs::read_to_string(fixture().join("plugin.toml")) + let manifest = fs::read_to_string(fixture.join("plugin.toml")) .unwrap() - .replace("@KINDS@", &fixture().join("kinds").display().to_string()); + .replace("@KINDS@", &fixture.join("kinds").display().to_string()); let path = dir.join("plugin.toml"); fs::write(&path, manifest).unwrap(); path @@ -163,9 +166,9 @@ pub fn sync_environment(world: &World) { fs::write(dir.join("ready"), key.digest()).unwrap(); } -/// Runs `candler evaluate` over the store of the world with the fixture plug-in and suite, from a -/// project directory whose `candler.toml` lists the manifest's directory under `plugins.dirs`. -pub fn evaluate(world: &World, manifest: &Path) -> Output { +/// Runs `candler evaluate` over the store of the world with `suite`, from a project directory +/// whose `candler.toml` lists the manifest's directory under `plugins.dirs`. +pub fn evaluate(world: &World, manifest: &Path, suite: &Path) -> Output { let project = world.root.join("project"); fs::create_dir_all(&project).unwrap(); let dir = manifest.parent().unwrap(); @@ -178,7 +181,7 @@ pub fn evaluate(world: &World, manifest: &Path) -> Output { .arg("--store") .arg(world.store()) .arg("evaluate") - .arg(suite()) + .arg(suite) .current_dir(&project) .env_remove("CANDLER_STORE") .env("HOME", world.root.join("home")) @@ -189,6 +192,22 @@ pub fn evaluate(world: &World, manifest: &Path) -> Output { .unwrap() } +/// Every outcome record of the world's store, over all its `jsonl` files. +pub fn outcome_records(world: &World) -> Vec { + let layout = StoreLayout::new(&world.store()); + entries_under(&layout.outcomes_dir()) + .iter() + .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl")) + .flat_map(|path| { + fs::read_to_string(path) + .unwrap() + .lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .collect::>() + }) + .collect() +} + /// Waits for the job `launch` printed to end and release its lock, and returns its id. pub fn finish(world: &World, out: &Output) -> JobId { let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); From da8a1dd56afb3477c64a449096634bb3a281ae3e Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:37:16 +0900 Subject: [PATCH 75/93] reports(library): record the fix round of the graded run's trace The report now says the glob doc was corrected, what the guard leaves uncovered, and that bite (a) was applied again after the refactor. Co-Authored-By: Claude Opus 5.5 --- .../run-context/leaves/graded_run_sees_trace_v0.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/__reports__/run-context/leaves/graded_run_sees_trace_v0.md b/__reports__/run-context/leaves/graded_run_sees_trace_v0.md index 40e78f40..70893551 100644 --- a/__reports__/run-context/leaves/graded_run_sees_trace_v0.md +++ b/__reports__/run-context/leaves/graded_run_sees_trace_v0.md @@ -22,7 +22,7 @@ Each applied on a scratch branch from the guard's commit, one at a time, run wit | Bite | Result | Failing message | |---|---|---| -| (a) `assemble` serves no trace (`if needs.trace` made never true, `assemble.rs`) | both rows red | `claude-code: the kind did not pass once: [{... "evidence": [{"note": "the context serves no trace"}], "status": "fail" ...}]`, and the same line for `opencode` | +| (a) `assemble` serves no trace (`if needs.trace` made never true, `assemble.rs`); applied twice, again after the fix round with the same result | both rows red | `claude-code: the kind did not pass once: [{... "evidence": [{"note": "the context serves no trace"}], "status": "fail" ...}]`, and the same line for `opencode` | | (b) the OpenCode reader writes no `exit` (`export.rs`, `exit` replaced by none on the result) | OpenCode row red, Claude Code's green | `opencode: the kind did not pass once: [{... "note": "([\"printf 'graded-answer-3f9a\\n' > answer.txt\"], {'kind': 'code', 'code': 0}) is held 0 times among []; (['exit 3'], {'kind': 'code', 'code': 3}) is held 0 times among []" ... "status": "fail"}]`; no `claude-code:` line | ## Local run @@ -47,10 +47,16 @@ The guard asks P0's question: does a kind that needs an artifact and the trace s ## Spec defects met -- The leaf says `needs.artifacts = ["answer.txt"]`. The registry refuses it: `plugin.need_glob_outside_outputs`, "artifact glob `answer.txt` is not under `outputs/`". The kind declares `outputs/answer.txt`; the served path is `answer.txt`. The `Needs.artifacts` doc ("globs, relative to the run's outputs") says the opposite of the check. +- The leaf says `needs.artifacts = ["answer.txt"]`. The registry refuses it: `plugin.need_glob_outside_outputs`, "artifact glob `answer.txt` is not under `outputs/`". The kind declares `outputs/answer.txt`; the served path is `answer.txt`. The `Needs.artifacts` doc said the globs were relative to the run's outputs; it now says each starts with `outputs/`, and the schemas, the helper's models, `architecture.md` and the leaf's gate follow (`docs(schemas)` commit). - OpenCode's shell tool is `shell`, takes no `description` and refuses extra keys, so the script sends `{command}` alone to both harnesses. - The parity guard's `ps -aq` equality is false on a machine other sessions share, and under parallel nextest threads. The new guard checks leftovers by its own labels and job ids instead; the parity guard is unchanged in that respect. -- Not run: the `rust-conventions` reviewer agent on the new Rust. + +## Not covered + +- A `seal` panic in the first harness's row stops the second row; the guard is red either way. +- The per-job `candler-env` images are not removed: they are content-addressed and reused across runs by design, as the parity guard does. The guard removes the fake model's image and container by id, and the jobs' containers and networks by label (`Made` holds every job id). +- The guard checks that the product left no container or network of its jobs, before `Made` cleans up. Parity's full `ps -aq` equality stays, since CI runs the group serially. +- A scratch root under `$HOME` that is freshly created may not be mounted in time by Docker Desktop: a run then fails at the start check of the declared servers (`bind source path does not exist`). It passes once the root has been mounted, for instance after a `docker run -v` of it. ## Left From b1771d98b988d9cba1f76268568acb7f889f12d3 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:43:35 +0900 Subject: [PATCH 76/93] rdm(library): close the graded run's trace Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/e2e/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/__roadmap__/run_context/readers/e2e/README.md b/__roadmap__/run_context/readers/e2e/README.md index 20952ba6..caaf005b 100644 --- a/__roadmap__/run_context/readers/e2e/README.md +++ b/__roadmap__/run_context/readers/e2e/README.md @@ -15,7 +15,7 @@ The consumer path (run, seal, evaluate with `needs.trace`) is seen working on bo ## Status ```mermaid graph TD - graded_run_sees_trace[Graded run sees trace]:::inprogress + graded_run_sees_trace[Graded run sees trace]:::done review[Review]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -27,7 +27,7 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `graded_run_sees_trace.md` | 📄 Leaf Task | 🔄 In Progress | +| `graded_run_sees_trace.md` | 📄 Leaf Task | ✅ Done | | `review/` | 📁 Directory | ⬜ Planned | ## Amendment Log From 297929773330b9ed5f77043c1cadf4f8187f5188 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:43:48 +0900 Subject: [PATCH 77/93] rdm(evaluation): start the adversarial review The report is numbered 03: 02 is the seam review. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/run_context/readers/e2e/review/README.md | 4 ++-- .../run_context/readers/e2e/review/adversarial_review.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/__roadmap__/run_context/readers/e2e/review/README.md b/__roadmap__/run_context/readers/e2e/review/README.md index ebd0b38a..d161196b 100644 --- a/__roadmap__/run_context/readers/e2e/review/README.md +++ b/__roadmap__/run_context/readers/e2e/review/README.md @@ -15,7 +15,7 @@ The whole diff is judged by someone with no stake in it, and every finding is fi ## Status ```mermaid graph TD - adversarial_review[Adversarial review]:::planned + adversarial_review[Adversarial review]:::inprogress classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -26,7 +26,7 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `adversarial_review.md` | 📄 Leaf Task | ⬜ Planned | +| `adversarial_review.md` | 📄 Leaf Task | 🔄 In Progress | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/run_context/readers/e2e/review/adversarial_review.md b/__roadmap__/run_context/readers/e2e/review/adversarial_review.md index cbe07f74..67b4edc6 100644 --- a/__roadmap__/run_context/readers/e2e/review/adversarial_review.md +++ b/__roadmap__/run_context/readers/e2e/review/adversarial_review.md @@ -6,7 +6,7 @@ - [ ] `[cmd]` `git merge-base --is-ancestor feat/run-context HEAD` succeeds in the reviewer's checkout - [ ] `[nl]` `../graded_run_sees_trace.md` is `done` and merged into `feat/run-context` **Success Gates**: -- ⬜ A findings report `__reports__/run-context/02-review_adversarial_v0.md` covers the whole diff `origin/main...feat/run-context`. For each finding it gives the file and line, the failure it would cause, and its class (defect, idiom, waste). It answers at least: is any stored part served by a second path; does any reader accept what the schema refuses; does the context digest change for a context serving none of the new parts; does any doc carry history or plan references; did the refactor leave `materialise` simpler, judged by its call sites, not its line count +- ⬜ A findings report `__reports__/run-context/03-review_adversarial_v0.md` covers the whole diff `origin/main...feat/run-context`. For each finding it gives the file and line, the failure it would cause, and its class (defect, idiom, waste). It answers at least: is any stored part served by a second path; does any reader accept what the schema refuses; does the context digest change for a context serving none of the new parts; does any doc carry history or plan references; did the refactor leave `materialise` simpler, judged by its call sites, not its line count - ⬜ Every finding is fixed on `feat/run-context` (the fix's commit cited) or ruled on by the coordinator with the reason recorded in the report; a finding that needs the maintainer goes to them before the pull request - ⬜ After the fixes, the project's checks pass on the tip and `container-e2e` is green on the integration pull request draft **References**: [README.md](../../../../../README.md) purpose paragraph; [AGENTS.md](../../../../../AGENTS.md); [plan](../../../../../__reports__/run-context/00-plan_run_context_v0.md); every leaf report under `__reports__/run-context/leaves/`. @@ -15,7 +15,7 @@ **Goal**: The findings report exists. **Implementation Logic**: A fresh Sonnet reviewer gets the README paragraph, AGENTS.md, the plan, and the diff; not the leaf reports' conclusions until it has read the diff once. It reads code through colgrep with absolute paths in its own checkout of `feat/run-context`. It writes findings, not fixes. -**Deliverables**: `__reports__/run-context/02-review_adversarial_v0.md` +**Deliverables**: `__reports__/run-context/03-review_adversarial_v0.md` **Consistency Checks**: the report lists every file in `git diff --stat origin/main...feat/run-context` as read or says why not (expected: PASS) **Commit**: `reports(evaluation): review the run context campaign adversarially` @@ -23,6 +23,6 @@ A fresh Sonnet reviewer gets the README paragraph, AGENTS.md, the plan, and the **Goal**: No finding is left open. **Implementation Logic**: The coordinator dispatches each fix to an implementer on its own worktree and merges it as any leaf; a finding not fixed gets a ruling in the report. Rerun the checks and `container-e2e`. -**Deliverables**: the fixes; the rulings in `02-review_adversarial_v0.md` +**Deliverables**: the fixes; the rulings in `03-review_adversarial_v0.md` **Consistency Checks**: `cargo nextest run --workspace` on the tip (expected: PASS) **Commit**: `reports(evaluation): close the adversarial review` From 375398578d38f24dc2dbe49c19d0bda02f251f05 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:49:45 +0900 Subject: [PATCH 78/93] reports(evaluation): review the run context campaign adversarially Co-Authored-By: Claude Opus 5.5 --- .../run-context/03-review_adversarial_v0.md | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 __reports__/run-context/03-review_adversarial_v0.md diff --git a/__reports__/run-context/03-review_adversarial_v0.md b/__reports__/run-context/03-review_adversarial_v0.md new file mode 100644 index 00000000..955bb4c7 --- /dev/null +++ b/__reports__/run-context/03-review_adversarial_v0.md @@ -0,0 +1,111 @@ +# Adversarial review of the run context campaign + +Read: `git diff origin/main...feat/run-context` at tip `297929773330b9ed5f77043c1cadf4f8187f5188`, through `git diff` and file reads, and `colgrep` for the call sites of the raw-stream naming rule and of trace validation. I read the diff first, then `02-seam_review_v0.md` and the leaf reports. Nothing was built, run or tested. Rulings 1 to 14 of the seam review are not re-raised. Where a finding touches a carried follow-up, it says so. + +## Answers + +**Is any stored part served by a second path, or copied by more than one routine?** +No second copy routine. `copy_stored` (`materialise.rs:389`) is the only copy, called once (`materialise.rs:495`) for artifacts, inputs, trace, raw streams and manifest. Before, `copy_artifact` was called from two sites. +There is a second *reader* of the raw naming rule: `stored_streams` (`assemble.rs:276-305`) parses `.jsonl.gz` with its own `RAW_SUFFIX`. `stream_of` (`runner/exec/mod.rs:415`) parses the same name, and `StoreLayout::raw` (`store/layout.rs:91`) builds it. The names `trace.jsonl` and `manifest.json` are also spelled in `assemble.rs:208,225`, beside `layout.trace` and `layout.manifest`. See findings 2 and 3. + +**Does any reader accept what the schema refuses?** +- Rust trace readers: `TraceFile::read` refuses `exit: null`, a bare `{code}` and a string (`guard_trace_wire.rs`, new test). It accepts an unknown event kind as `EventKind::Unknown` (`trace.rs:905`), which the six-kind schema does not list. That is older than this diff and is not raised. +- Wire readers: `Needs.raw` and `Needs.manifest` take a boolean or are absent; `null` is refused (`evaluation.rs:1342-1347`; vector `needs_raw_not_boolean`). `ContextArtifact`, `ContextRaw` and `RunContext` refuse `null` through `present`. +- Python `read_trace` (`trace.py`) accepts what the Rust reader refuses: an empty file, a missing or second header, a `seq` gap, an event for an undeclared session, a `raw_ref` to an unlisted stream. Its own docstring lists them. AGENTS.md calls a more lenient second reading a defect. Finding 4. +- Python `ExitStatus.code` is an unbounded `int` where Rust has `i32`. This was ruled in seam review 2; not re-raised. +- `stored_streams` ignores a file in `raw/` that is not `.jsonl.gz` instead of refusing the run (follow-up carried in the seam review; finding 3 shows the second parser is what makes it unguarded). + +**Does the context digest change for a context that serves none of the new parts?** +No. `context_digest` (`evaluation.rs:1805-1835`) builds the same four keys and adds `trace`, `raw` and `manifest` only when served. RFC 8785 sorts keys, so the switch from `json!` to a `Map` changes nothing. `context_digest.toml` is unchanged in the diff and `guard_context_digest.rs` still runs its rows against it; the new `context_digest_served.toml` rows are separate. The digest of a context that serves a part depends on which sibling kinds were sent (ruling 3); not re-raised. + +**Does any doc, doc comment, contract page, README or CHANGELOG carry history or plan references, or say something the code does not do?** +- No plan, milestone, leaf or roadmap reference in source, README, contract pages or `__design__`. The `CHANGELOG.md` line "`trace` was a bare path and is now a `ServedFile`" is history, which is what a changelog is for. +- Claims the code does not back: + - `READER` and `LIVE_READER`/`EXPORT_READER` docs say "the version changes whenever the reader's output does" (`claude-code/src/lib.rs:57`, `opencode/src/lib.rs:33,36`). The ratchet that enforced it (`digests.toml`) was deleted in this diff, so nothing enforces it now. Finding 7. + - `PROVENANCE.toml` (claude-code fixtures, new block) says the recorded stream came from `fakemodel.py` "with one extra script, model id sh1, kept outside the repository". The fixture cannot be regenerated from the repository. Finding 8. +- Not checked: the `Needs.manifest` doc listing what the manifest holds (`evaluation.rs:1342`), which I did not compare with `RunManifest`. + +**Did the refactor leave `materialise` simpler?** +Yes on paths: one copy routine, one call site, one `text_of` for the UTF-8 refusal that appeared three times. The cost moved. `Served` is a five-variant tag that `materialise` matches (`materialise.rs:496-518`); three arms repeat `ContextArtifact::new(.., text_of(©)?, digest)` and the `Input` arm discards the digest `copy_stored` returns. A fourth part would add an arm in `assemble`, `Served`, `materialise` and `union`. Finding 6. + +**Exit-status readers (Claude Code `Bash`, OpenCode `shell`)** +- Non-shell call getting an `exit`: + - OpenCode: gated at the source, `name == SHELL_TOOL && status == "completed"` (`export.rs:221`). The `read` row with `exit: 7` guards it. + - Claude Code: `exit_of` is computed for every result, then cleared in `Registry::emit` unless the call is a `Bash` call of the same session (`sessions.rs:158-167`). Correct today; the gate lives in a second file and the first producer gives any non-error result `Code 0` (finding 5). The shared-call-id stream guards the join. +- Shell call getting a wrong one: + - Claude Code returns `Code 0` for every non-error result with no `backgroundTaskId`, `timedOutAfterMs` or `interrupted` flag (`parse.rs:64-66`). The probe (`probe_shell_shapes_v0.md`) ran `exit 3`, `exit 2` with stderr, and a timeout. It did not run a command whose non-zero exit Claude Code's Bash tool reports as success, such as `grep` with no match or `diff` on differing files. From my knowledge of that tool, such a result is `is_error: false` with an interpretation string in `tool_use_result`, and the real exit is 1. If so, the reader writes exit 0 for a command that exited 1. I did not verify this; finding 1. + - OpenCode: a `completed` call whose `metadata.exit` is absent or not an `i32` gets none. An `error` state gets none even if the harness recorded a code. Both are documented in the comment at `export.rs:217-220`. + +**Tests: tautological, or expected values from the code under test?** +- No tautological guard found. Expected values come from outside the code under test: `jq` over the raw lines (`expected.toml`, `exits` rows), the fake model's script (`graded_trace_e2e.rs`), the store's own bytes (`guard_run_context.rs`), `rfc8785` vectors (`context_digest_served.toml`), hand-written wire lines. +- Weak points: + - `stored_parts` in `guard_run_context.rs:123-145` lists `raw/` by directory listing, as `assemble` does. A stray file in `raw/` is served by the oracle and refused by nothing. No test pins that case. + - `guard_wiring.rs` and `guard_registry.rs` hard-code `opencode-export@0.2.0`; this is a literal, not a read of the code, so the pair with `EXPORT_READER` is checked. Fine. + - The Claude Code `exits` row for the timeout comes from a backgrounded call (`backgroundTaskId`), and the `timedOutAfterMs` branch of `exit_of` has no recorded stream behind it; only the synthetic `exit_join_stream` reaches `interrupted`. + +## Findings + +| # | file:line | Finding | Failure it would cause | Class | Severity | +|---|---|---|---|---|---| +| 1 | `crates/candler-harness-claude-code/src/parse.rs:64-66` | A non-error `Bash` result is read as `Code 0`. The probe did not run a command that Claude Code's tool reports as success on a non-zero exit (`grep` no match, `diff`). | A trace that says exit 0 for a command that exited 1; a kind that grades on exit passes a failed command. Unverified: probe one such command before merge. | defect | blocking, pending that probe | +| 2 | `crates/candler-core/src/evaluation/context/assemble.rs:208,220,225,272` | The workspace names `trace.jsonl`, `manifest.json`, `raw/.jsonl.gz` and `RAW_SUFFIX` repeat what `store/layout.rs` and `runner/exec/mod.rs:415` already spell. | A rename in the layout leaves the context serving a different name from the store, or a missing file read as `PartMissing`. | waste | minor | +| 3 | `assemble.rs:276-305` | `stored_streams` is a second reader of `.jsonl.gz` and skips a file, or a name `StreamName` refuses, instead of refusing the run. | A damaged `raw/` serves fewer streams than the run stored, with a context digest that looks valid. | defect (second, lenient reader) | minor | +| 4 | `python/candler-evaluator/src/candler_evaluator/trace.py:539-558` | `read_trace` checks lines, not order. The Rust `TraceFile::read` (`trace.rs:1299-1336`) refuses an empty file, a second header, a session after an event and a duplicate session. | A hand-supplied path (the helper takes `Path | str`) is graded as a trace Candler would have refused. The served copy is sha256-pinned, so the stored trace is safe. | defect | minor | +| 5 | `parse.rs:54-66` with `sessions.rs:158-167` | Claude Code decides `exit` in two places: `exit_of` gives every non-error result of any tool `Code 0`, and `Registry::emit` clears it for non-`Bash`. OpenCode gates at the source (`export.rs:221`). | A new caller of `block_draft` that skips the registry writes `exit 0` on a `Read` result. None today. | idiom | minor | +| 6 | `materialise.rs:496-518` | Three arms repeat `ContextArtifact::new(.., text_of(©)?, digest)`; the `Input` arm drops the digest. The `Served` tag is mirrored in `assemble`, `materialise` and `union`. | A fourth served part needs edits in four places. | idiom | minor | +| 7 | `crates/candler-harness-claude-code/src/lib.rs:57`, `crates/candler-harness-opencode/src/lib.rs:33-41` | The "version changes whenever the reader's output does" claim is unenforced after `digests.toml` was deleted. `EXPORT_READER` and `EXPORT_READER_VERSION` both hold `0.2.0`; `LIVE_READER` is a bare literal. | A reader change that forgets the bump goes unseen; the two `0.2.0` copies drift. | waste | minor | +| 8 | `crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml` (new block, `shell_exit_stderr_timeout`) | The stream was recorded with a fake-model script kept outside the repository; `tests/fixtures/README.md` gives no way to record it again. | A reader change that needs a new recording cannot reproduce this stream. | waste | minor | +| 9 | `assemble.rs:192-208,261` with `materialise.rs:423` | Each served file is stat-ed (trace), hashed at assembly, copied and hashed again: three reads of every raw stream for every request of every run. | Cost grows with raw size times requests; the assembly hash only guards a store change between two steps of one request. | waste | minor | + +## Files in the diff stat + +Every file below was read in the diff unless marked. "Skim" means the diff was read for shape and for expected values, not line by line. + +| File | Status | +|---|---| +| `.github/workflows/container-e2e.yml` | read | +| `__design__/architecture.md` | read | +| `__reports__/run-context/00-plan_run_context_v0.md` | skipped: the plan, read only for the ruling on "what a kind sees" via `02` | +| `__reports__/run-context/01-ruling_trace_served_v0.md` | skipped: ruling record | +| `__reports__/run-context/02-seam_review_v0.md` | read | +| `__reports__/run-context/leaves/probe_shell_shapes_v0.md` | read (grep for the shell shapes it covers) | +| `__reports__/run-context/leaves/cc_reader_exit_v0.md`, `graded_run_sees_trace_v0.md`, `helper_context_v0.md`, `oc_reader_exit_v0.md`, `schema_exit_needs_v0.md`, `serve_context_v0.md` | skipped: leaf reports; the code and tests were judged directly | +| `__roadmap__/m3-lean-cli/refusal_scope.tsv` | read | +| `__roadmap__/run_context/README.md`, `probe_shell_shapes.md`, `readers/README.md`, `readers/cc_reader_exit.md`, `readers/e2e/README.md`, `readers/e2e/graded_run_sees_trace.md`, `readers/e2e/review/README.md`, `readers/e2e/review/adversarial_review.md`, `readers/helper_context.md`, `readers/oc_reader_exit.md`, `readers/serve_context.md`, `schema_exit_needs.md` | skipped: roadmap task files, no code or contract claim | +| `assets/docker/fakemodel/fakemodel.py` | read | +| `crates/candler-core/src/evaluation/context/assemble.rs`, `materialise.rs`, `mod.rs`, `union.rs` | read | +| `crates/candler-core/src/evaluation/engine/run.rs`, `refusal.rs`, `registry/needs.rs` | read | +| `crates/candler-core/tests/fixtures/harness_baseline/census.json`, `run_totals.json` | skipped: generated data, no logic | +| `crates/candler-core/tests/it/guard_run_context.rs` | read | +| `crates/candler-core/tests/it/guard_wiring.rs` | read | +| `crates/candler-core/tests/oracle/vectors/context_digest_served.toml` | read | +| `crates/candler-core/tests/oracle/vectors/gen_live_context.py`, `gen_vectors.py`, `live_context_runs.toml` | skipped: generators and their output; the digest rule they project was checked against `evaluation.rs` | +| `crates/candler-harness-claude-code/README.md`, `src/lib.rs`, `src/parse.rs`, `src/sessions.rs` | read | +| `crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml`, `README.md` | read | +| `crates/candler-harness-claude-code/tests/fixtures/digests.toml` | read (deletion) | +| `crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml` | read | +| `.../streams/api_error`, `mini_clean`, `mini_incomplete`, `mini_zero_mappings`, `multi_init`, `subagent_denials`, `synthetic_mcp` `expected.toml` | skim: new `exits` rows, same rule | +| `.../streams/shell_exit_stderr_timeout/agent_stream.jsonl.gz`, `usage_totals.toml` | skipped: recorded data | +| `crates/candler-harness-claude-code/tests/it/guard_reader.rs` | read | +| `crates/candler-harness-opencode/src/export.rs`, `lib.rs`, `prepare.rs` | read | +| `crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml`, `streams/shell_exit_stderr_timeout/export.json`, `stdout.jsonl` | skipped: recorded data, judged through the test that reads them | +| `crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs` | read | +| `crates/candler-schemas/schema/*.schema.json` (five files) | skipped: generated from `evaluation.rs` and `trace.rs`; the Rust source was read | +| `crates/candler-schemas/src/evaluation.rs`, `trace.rs` | read | +| `crates/candler-schemas/tests/fixtures/rpc/PROVENANCE.toml`, `README.md`, `invalid/needs_raw_not_boolean.json`, `valid/response_describe_needs_raw_manifest.json` | read (README), skim (rest) | +| `crates/candler-schemas/tests/it/guard_context_digest.rs`, `guard_trace_wire.rs` | read | +| `crates/candler-schemas/tests/it/guard_evaluator_protocol.rs`, `guard_rpc_wire.rs` | skipped: one-line version edits | +| `crates/candler-schemas/tests/vectors/field_classes.toml` | read | +| `crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py`, `plugin.toml` | read (py), skim (toml) | +| `crates/candler/tests/it/guard_cli_e2e.rs`, `guard_cli_e2e/graded_trace_e2e.rs` | read | +| `crates/candler/tests/it/guard_cli_e2e/i8_e2e.rs`, `parity_e2e.rs` | skipped: refactor of the parity rig into shared helpers; used through `graded_trace_e2e.rs` | +| `crates/candler/tests/it/guard_input_seam.rs`, `guard_registry.rs`, `guard_run_evaluate.rs`, `support/seam.rs` | read (first two), skipped (last two: helper plumbing) | +| `docs/contract/codes.toml`, `evaluator-helper.md`, `evaluator-protocol.md`, `index.md` | read | +| `python/candler-evaluator/CHANGELOG.md`, `README.md`, `pyproject.toml`, `scripts/gen_models.py` | read | +| `python/candler-evaluator/src/candler_evaluator/__init__.py`, `plugin.py`, `trace.py` | read | +| `python/candler-evaluator/src/candler_evaluator/_models/*.py` (six files) | skipped: generated; `EventKind4` and the `TraceRecord` union spot-read | +| `python/candler-evaluator/tests/test_guard_context.py` | read | +| `python/candler-evaluator/tests/test_guard_isolation.py` | skipped: two-line edit | +| `python/candler-evaluator/uv.lock` | skipped: lock file | + +Not read: the Rust workspace beyond the diff, apart from `store/layout.rs`, `store/run.rs`, `runner/exec/mod.rs`, `import/assemble.rs` and `import/raw.rs` for the trace and raw-stream rules. From c822e69ce1a476e90c9b295d3b1b6c0485f0cbcf Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 21:05:57 +0900 Subject: [PATCH 79/93] test(library): let model g1 run two or more shell commands The script took exactly two commands; a recording of more shapes in one run needs a list of any length. Co-Authored-By: Claude Opus 5.5 --- assets/docker/fakemodel/fakemodel.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/assets/docker/fakemodel/fakemodel.py b/assets/docker/fakemodel/fakemodel.py index 73da496f..a0f2edcd 100644 --- a/assets/docker/fakemodel/fakemodel.py +++ b/assets/docker/fakemodel/fakemodel.py @@ -8,7 +8,7 @@ FAKE_PORT the TLS port (default 8443). FAKE_DIR where the certificates and the records go (default /tmp/fake). FAKE_OUT_TOKENS output tokens each answer reports (default 20). - FAKE_G1_COMMANDS a JSON list of two shell commands, the script of model g1 (default: none). + FAKE_G1_COMMANDS a JSON list of two or more shell commands, the script of model g1 (default: none). FAKE_DELAY_SECS how long the answer to a c3 request is held, after it is recorded (default 0, at most 120). @@ -34,8 +34,8 @@ Anything else is answered with text. g1 must run what it is told. A first user prompt is answered with a call to the shell tool (`Bash`, or `shell` for OpenCode) for the first command of FAKE_G1_COMMANDS, the result of - that with the second command, and the result of that with the call to the stamp tool, as - for p1. Anything else is answered with text. + each with the next command, and the result of the last with the call to the stamp tool, + as for p1. 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. @@ -132,22 +132,23 @@ def last_tool_result(messages): def graded_blocks(state, tools, messages): - """The answer of model g1: two shell commands, then the stamp call, then text.""" + """The answer of model g1: each shell command in turn, then the stamp call, then text.""" commands = json.loads(os.environ.get("FAKE_G1_COMMANDS", "[]")) shell = next((name for name in tools if name in SHELL_TOOLS), None) last = last_tool_result(messages) if state == "tool_result" else None - steps = ("toolu_fake_g1_0", "toolu_fake_g1_1") + steps = [f"toolu_fake_g1_{index}" for index in range(len(commands))] def shell_call(index): return {"type": "tool_use", "id": steps[index], "name": shell, "input": {"command": commands[index]}} - if shell and len(commands) == 2: + if shell and len(commands) >= 2: if state == "prompt": return [shell_call(0)], "tool_use", "g1-shell-0" - if last == steps[0]: - return [shell_call(1)], "tool_use", "g1-shell-1" - if last == steps[1]: + if last in steps[:-1]: + following = steps.index(last) + 1 + return [shell_call(following)], "tool_use", f"g1-shell-{following}" + if last == steps[-1]: offered = [name for name in tools if name in PARITY_TOOLS] if offered: return [stamp_call(offered[0])], "tool_use", "g1-call" From a92af6661f9ba339a077bc785cfd797d226691e7 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 21:05:57 +0900 Subject: [PATCH 80/93] fix(adapter-claude-code): no exit for a nonzero result it does not flag Claude Code writes is_error false and a returnCodeInterpretation, with no code, for grep with no match, diff of two files that differ and a false test. The reader gave them code 0. They now carry no exit; the reader is 0.4.0, its version one macro invocation instead of two literals. Co-Authored-By: Claude Opus 5.5 --- .../fixtures/harness_baseline/census.json | 54 +++++++++++++++++ .../fixtures/harness_baseline/run_totals.json | 28 ++++++++- crates/candler-harness-claude-code/README.md | 5 ++ crates/candler-harness-claude-code/src/lib.rs | 17 ++++-- .../candler-harness-claude-code/src/parse.rs | 16 +++-- .../tests/fixtures/PROVENANCE.toml | 30 +++++++++ .../tests/fixtures/README.md | 35 ++++++++++- .../agent_stream.jsonl.gz | Bin 0 -> 2988 bytes .../shell_exit_semantics/expected.toml | 57 ++++++++++++++++++ .../shell_exit_semantics/usage_totals.toml | 13 ++++ 10 files changed, 245 insertions(+), 10 deletions(-) create mode 100644 crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/agent_stream.jsonl.gz create mode 100644 crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/expected.toml create mode 100644 crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/usage_totals.toml diff --git a/crates/candler-core/tests/fixtures/harness_baseline/census.json b/crates/candler-core/tests/fixtures/harness_baseline/census.json index 29daec78..0c1e3257 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/census.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/census.json @@ -382,5 +382,59 @@ "Bash", "Agent" ] + }, + "streams/shell_exit_semantics": { + "census.init_tools": [ + "Bash", + "CronCreate", + "CronDelete", + "CronList", + "DesignSync", + "Edit", + "EnterWorktree", + "ExitWorktree", + "ListAgents", + "Monitor", + "NotebookEdit", + "Read", + "ReportFindings", + "ScheduleWakeup", + "SendMessage", + "Skill", + "Task", + "TaskStop", + "ToolSearch", + "WebFetch", + "WebSearch", + "Workflow", + "Write", + "mcp__parity__stamp" + ], + "census.tools": [ + "Task", + "Bash", + "CronCreate", + "CronDelete", + "CronList", + "DesignSync", + "Edit", + "EnterWorktree", + "ExitWorktree", + "ListAgents", + "Monitor", + "NotebookEdit", + "Read", + "ReportFindings", + "ScheduleWakeup", + "SendMessage", + "Skill", + "TaskStop", + "ToolSearch", + "WebFetch", + "WebSearch", + "Workflow", + "Write", + "mcp__parity__stamp" + ] } } diff --git a/crates/candler-core/tests/fixtures/harness_baseline/run_totals.json b/crates/candler-core/tests/fixtures/harness_baseline/run_totals.json index 9000f034..6d76da01 100644 --- a/crates/candler-core/tests/fixtures/harness_baseline/run_totals.json +++ b/crates/candler-core/tests/fixtures/harness_baseline/run_totals.json @@ -208,5 +208,31 @@ "input_tokens": 7, "output_tokens": 3 } + }, + "streams/shell_exit_semantics": { + "run.cost_usd": 0.005600000000000001, + "run.num_turns": 7, + "run.usage": { + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 0 + }, + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + "fallback_credit": null, + "inference_geo": "", + "input_tokens": 700, + "iterations": [], + "output_tokens": 140, + "output_tokens_details": { + "thinking_tokens": 0 + }, + "server_tool_use": { + "web_search_requests": 0, + "web_fetch_requests": 0 + }, + "service_tier": "standard", + "speed": "standard" + } } -} \ No newline at end of file +} diff --git a/crates/candler-harness-claude-code/README.md b/crates/candler-harness-claude-code/README.md index 860c94b9..3f26db10 100644 --- a/crates/candler-harness-claude-code/README.md +++ b/crates/candler-harness-claude-code/README.md @@ -22,6 +22,11 @@ and how each session ended) and `usage` (token counts and their sums) are privat - Session roots and subagent children, each with its own event numbering. - Tool calls and results. A result the harness refused carries a denial whose reason is the `non_execution_kind` of the line's `tool_result_meta`. +- The exit of a `Bash` result, as the harness stated it and never inferred: `Exit code N` leading an + error result gives code `N`; a non-error result gives code 0, unless its `tool_use_result` carries a + `returnCodeInterpretation` (a nonzero exit such as `grep` with no match, which Claude Code does not + flag and gives no code for), a `backgroundTaskId`, a `timedOutAfterMs` or `interrupted: true`, which + give none. A result of any other tool has no exit. - Usage per message and, from the result line, per session with its cost. - Content blocks it has no event for, kept whole in a notification. - A stream with no init line, or with frames before any session, ends in `ReaderError::Incomplete`. diff --git a/crates/candler-harness-claude-code/src/lib.rs b/crates/candler-harness-claude-code/src/lib.rs index bde2885e..deb3be12 100644 --- a/crates/candler-harness-claude-code/src/lib.rs +++ b/crates/candler-harness-claude-code/src/lib.rs @@ -54,11 +54,20 @@ pub const PINNED: semver::Version = semver::Version::new(2, 1, 311); /// The name of the harness that produced the streams the reader reads. const HARNESS: &str = "claude-code"; -/// The identity of this reader as text, `claude-code-stream-json@`; the version changes whenever the reader's output does. -pub const READER: &str = "claude-code-stream-json@0.3.0"; +/// Defines [`READER`] and `READER_VERSION` from the one version written here, so the identity text and the version the +/// reader reports cannot differ. +macro_rules! reader_version { + ($major:literal, $minor:literal, $patch:literal) => { + /// The identity of this reader as text, `claude-code-stream-json@`; the version changes whenever the reader's output does. + pub const READER: &str = + concat!("claude-code-stream-json@", $major, ".", $minor, ".", $patch); -/// The version of [`READER`]. -const READER_VERSION: semver::Version = semver::Version::new(0, 3, 0); + /// The version of [`READER`]. + const READER_VERSION: semver::Version = semver::Version::new($major, $minor, $patch); + }; +} + +reader_version!(0, 4, 0); /// A frame that arrived before any session was known. struct Held { diff --git a/crates/candler-harness-claude-code/src/parse.rs b/crates/candler-harness-claude-code/src/parse.rs index 74c96b18..95035b27 100644 --- a/crates/candler-harness-claude-code/src/parse.rs +++ b/crates/candler-harness-claude-code/src/parse.rs @@ -344,11 +344,15 @@ fn denial_of(line: &Map, id: &str) -> Option { .map(|kind| Denial::new(DeniedBy::Harness, Some(kind.to_owned()))) } -/// The exit a result reports. +/// The exit a result states, as read from the result alone; the call's tool is not known here, so +/// `Registry::emit` keeps it only for a `Bash` call. /// /// A result with a `backgroundTaskId` or `timedOutAfterMs` in the line's `tool_use_result`, or with `interrupted` true, -/// has none. Of the others, an error result whose first text line is `Exit code N` has code `N` and any other error -/// text has none; a non-error result with none of those flags reads as exit 0. +/// states none. So does a non-error result whose `tool_use_result` has a `returnCodeInterpretation`: Claude Code writes +/// that text, and `is_error: false`, for a command that exited nonzero and that it does not count as a failure (`grep` +/// with no match, `diff` of two different files, a false `test`), and no field gives the code. Of the others, an error +/// result whose first text line is `Exit code N` has code `N` and any other error text has none; a non-error result +/// has code 0. fn exit_of(block: &Value, line: &Map, is_error: bool) -> Option { let report = line.get("tool_use_result").and_then(Value::as_object); let flagged = |key: &str| report.is_some_and(|report| report.contains_key(key)); @@ -360,7 +364,11 @@ fn exit_of(block: &Value, line: &Map, is_error: bool) -> Option a.txt; printf b > b.txt; diff a.txt b.txt", "test -f /missing", +# "echo fine"]: one Bash call per request in turn, then ToolSearch and the MCP call stamp of the server +# parity. The first three commands exit 1 and Claude Code reports them as is_error false with a +# returnCodeInterpretation; the fourth is the control that exits 0. The stream is the harness's stdout, +# each raw frame's text as one line (tests/fixtures/README.md, "Record a stream again"). + +[[files]] +path = "streams/shell_exit_semantics/agent_stream.jsonl.gz" +source = "real Claude Code 2.1.311 stream-json, cc_exit_semantics probe, 2026-11-25" +sha256 = "c4629520621a368f565cfccbbef35f91e4404df9ef81627ea4839eb8de06bd7c" +synthetic = false + +[[files]] +path = "streams/shell_exit_semantics/expected.toml" +source = "hand-written from jq over the raw lines" +sha256 = "2d2ca554fdf87d7ddb8992771aefef8d21b47838c0848362f9f3d12dc26260b3" +synthetic = false + +[[files]] +path = "streams/shell_exit_semantics/usage_totals.toml" +source = "usage_totals.jq" +sha256 = "f0df57b7284368d8d2141b2a76911e9eb38351f903d47efeeeeb360016eb5ea1" +synthetic = false diff --git a/crates/candler-harness-claude-code/tests/fixtures/README.md b/crates/candler-harness-claude-code/tests/fixtures/README.md index 33a4f0e0..9993e3dc 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/README.md +++ b/crates/candler-harness-claude-code/tests/fixtures/README.md @@ -1,6 +1,6 @@ # Claude Code reader fixtures -Nine streams feed `guard_reader`. Each lives in `streams//` with `expected.toml` +Eleven streams feed `guard_reader`. Each lives in `streams//` with `expected.toml` (hand-written from `jq` over the raw lines, never from Candler code) and `usage_totals.toml` (from `usage_totals.jq`). @@ -8,6 +8,7 @@ Nine streams feed `guard_reader`. Each lives in `streams//` with `expected |---|---| | `multi_init`, `subagent_denials`, `api_error` | golden suite `htn-creator-eval` 0.4.2, copied byte for byte | | `mini_clean`, `mini_incomplete`, `mini_zero_mappings` | the `candler-core` mini-corpus, named by relative path in `expected.toml`; no copy here | +| `shell_exit_stderr_timeout`, `shell_exit_semantics` | real Claude Code 2.1.311 on the parity rig; "Record a stream again" below | | `synthetic_hooks`, `synthetic_mcp`, `synthetic_orphans` | `make_synthetic.py`, from Claude Code's documented stream-json shapes | `PROVENANCE.toml` lists the sha256 of every file here except itself. @@ -23,3 +24,35 @@ python3 make_synthetic.py # usage totals of one stream gzip -dc streams//agent_stream.jsonl.gz | jq -nrR -f usage_totals.jq > streams//usage_totals.toml ``` + +## Record a stream again + +`shell_exit_stderr_timeout` and `shell_exit_semantics` are real recordings of Claude Code on the parity rig of +`crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs`: the production gateway sidecar in front of the scripted +fake model `assets/docker/fakemodel/fakemodel.py`, `bypassPermissions`, one cell. No token is spent. Docker +must be running; the agent image is the one `candler run` builds for the cell. + +1. Write a temporary `#[ignore]` test in `crates/candler/tests/it/guard_cli_e2e/` (its own `#[path]` module in + `guard_cli_e2e.rs`; `graded_trace_e2e.rs` is the model). It calls `start_fake(&real, &mut made, label, + &[format!("FAKE_G1_COMMANDS={json}")])`, builds the experiment with `base_experiment("g1", prompt)`, replaces + `@HARNESS@` by `claude-code`, calls `seal(...)` and copies the sealed run's directory out (`cp -R run_dir + `) before the `World` drops. Run it with + `cargo nextest run -p candler --test it -E 'test()' --run-ignored only --test-threads 1`. Delete the + test when the files are copied. +2. The fake-model id is `g1`: it answers a first prompt with a `Bash` call for each command of + `FAKE_G1_COMMANDS` in turn (two or more), then `ToolSearch` and the call of the tool `stamp` of the MCP + server `parity`, then "done". `shell_exit_semantics` used + `["echo hello | grep zzz", "printf a > a.txt; printf b > b.txt; diff a.txt b.txt", "test -f /missing", "echo fine"]`. +3. The fixture is the run's `raw/stdout.jsonl.gz`, one raw frame's text per line: + `gzip -dc /raw/stdout.jsonl.gz | jq -r 'select(.kind == "frame") | .data.text | rtrimstr("\n")' | gzip -n -9 > streams//agent_stream.jsonl.gz`. + Then write `expected.toml` by hand from `jq` over those lines, make `usage_totals.toml` as above, and list + all three files in `PROVENANCE.toml`. + +`shell_exit_stderr_timeout` was recorded with an earlier fake-model script `sh1`, which was not committed and +cannot be run from the repository. Its shape, to add again to `fakemodel.py` if that stream must be +re-recorded: a first prompt answered with one assistant message holding three `Bash` `tool_use` blocks, +`toolu_fake_sh_exit3` `{command: "exit 3"}`, `toolu_fake_sh_stderr` `{command: "echo oops >&2; exit 2"}` and +`toolu_fake_sh_timeout` `{command: "python3 -c 'import time; time.sleep(30)'", timeout: 1000}` (the tool's own +`timeout` field, in milliseconds; a bare `sleep 30` is refused by Claude Code), any later request answered +"done". The rig is the same; `g1` cannot stand in for it because it sends one call per request and sets no +`timeout`. diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/agent_stream.jsonl.gz b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/agent_stream.jsonl.gz new file mode 100644 index 0000000000000000000000000000000000000000..a42708223e24625421c2e6553dc77e228ad7d2ea GIT binary patch literal 2988 zcmV;d3sdwTiwFP!000021MOOEkKDEq{+?g4*iS8B-s%0tEs8dd0|c!TBj>Oi1K zYL`7pR7J|`wR``)GbE+mJKx!x#CLE}8}O|-d=Y2nnP-N(e783HL98FI^RkvrGF0lNsJ|6vemsa_drhl$_&7?d zWXFc88Yr~(RizE>hV?H_s>S$PjA*fU>z;P#3pWn!Z>X7|Yt2;O3uXi=q17}p9LD!B zUb6KSuB5nVLAF5`3}Wo0_1rTMgS6fcRO{!97**FTIHqE%>uArd!?@@abZ{XCG73Fw z!>v=62cn&OI5qUOd<#$00MCNJ9viuVHmD<;y`4}`C}6M)Sn;(KXc8^Ep>+dl>WtTj zofyes+hiD3H&~Z)#hgc5W$n*eI>BmmkkHt9LlZigts23pARMRO{UsXRM*tjRq;8R+ zoi?(+Hk{7j0ihyjN1}zXU_c2NXrRo7Mhh0P+O*1jEeEzldqCVb~s(1A}KzRU+8Kw>?+^U=DhMsNxkcXxo)qBK~dXImoP2=vD&T17c= z8tQ|<8o{+KyfCWSgaA9ZWb$~2iE^_wZZxB~lZ~S7!S|q%26G(*u!OqAsV&4IS!`(p z?TG4YMMn%Z#JWN6_Oz{T0p9H6*|f8HZs-K7fZzWv_7`&q^r{yNC@RERg~0?6g3jnH zJd49{@k{0W0)ZnMI<@BDeAt6q!t%=io4_XroR$pJI4F&h=Pm7*uxw>NLj^YG&1}Qy z|0sTbnPt}qj4?8gv<4;}64yY@7RhLmt&#mPlif1@uk*00N4G3%AbE7cjQbOpUB-WS z*<0x0l+|xeJG=zU17SpK*-9gYg@?p^Hco?q&}Kry=j+gh-YjOcXQHkCJ&8&1o1GAS zyz15NrhF83d}Sb!^{%tin+k9u*dCb6iR>tCs*aAAVyrM`wd*+y+}TuEIW=9U=9d+w zDx2Evtcq=Ezj5ivcS1D78rp&m+mP!y{5f7{UZa|11>T@e3JpDt4Lu&kXxrjsh*Hqj zRKT8<vK2r9H6!aSZpl$U9Ybwhw=pC6*{;CI6#m&lwd};RS2L7T){4dsXP+TO*fna_E4(N zi!=Q6iN%@-s|$npR84bDKHC93qb)(A>lA=T_7*>|1MaGa%1mQlxujJ=j+3v&Vm)Lb zyWkO#UVZg$E-j(X0DMrJBRXG5fz_X8{aL()~MR|7C5eIY&Hck@{FJC zz+|b}z5v^kd&MTK0ucKU_eH4eAr0VmeD;AJ!M19(6>Y0l|55DLYoF@3Q%pN~NT`x~$0!#m%1TyyoYLbrJM7z&Ot zju%+}0bResS`CjIe6^EiyXw`-Ip&WD3S9w-LV9xuzxw6Aj2Sj@ot7CTc^*-cgh5GY z+0nPM&Y29dtTDS5eZ8DU1x3Y+oQmk ze*yvb9gZHLZ2<}^e6Lm=78*jY8a4IE5xx4s+7F5)cP#O?dvxpv%kkEScew6QuvAB_cu>%;S!GA0IdE$hxzk_*ggrV%70h}vJvMA3sVQFsay4Ny9mW<^(jS^=M{a`zk0QTkn6<`PZ%p|R#5Y;RI_SiD_-@4kXJnb;=|(}l-IIUWME)Y2U$## zB+g+p1>2WpQly!H6jGdE`#elO#%rJ4MxT%+zl9aG4N!}W-_MZY=fRNigD_-t3PT#e z&x$mwb88bgo_%3I7lDHDCZ%~w(lo1KG*DoXK-E@fO_HUw2n$i35P?M$-wXRi|5Ife ztCOOPU?7je49ntO>Idf+bAz-%c;L(Z`*fvjF1mCE%1`z2{f)$hid+fcSf3p{#(z zSs2x%2~wyVOA4h9nz)IZBuwJ44wK{*!y<3r%0m8oBmCXt_FuqH2@0bOenE~V8wIcY z1%og?m5UZ{d#t&5MF32?>LUlY|4tfpB6HL{XNPA}qru zJs}XHG`kiEcSF+qflEEKbU%mxg%`U!A=QoEwX4| zlz%Elx@H@W7c;()iyh6&rmpj>A!V8ilEgeAWexc@$f7bS(|#%#OO}LjJ5l>epz_xs+{;kj;3d9ev0p+mQ5h*l$Fn`BBYyL9 zT{T==3|qj_2qp`+@2hj@O}ks*D0^QERvV%G0nG^KVt*Gv4+2kM$D4rDSZl90z&`Mf zFI3WwEN)RmvQ0t{c*kOC8O=LYxgKe^;&Z4 z{zi`4Jg1}0zo_2V6sQq%YJb_QT@TEAgUx$MTkpQ*>e~{Y%NL!W^yY@1YI`BYE@Xp4 z4|LZfbb{sb54PT|5jvaE{+f$@jT*&KbLzD)J`4;fEig!{8*}ii${{yxZOgx@s`u5r zjTsBGs`fm$}V2)^%^j62-3Pt|;3*z-bBO++{|1Vb#h`8ozqarV+zue^U4qc=v#5!yd$kJ`^#y37tHcy>pP7Iaf3(|UmOswriQJ`Hrr<(8Qx)d?j z3oiMA+f8FEKSyb_xY4ZjR%Y^VjxPz8|QI* i1Ix00r6n>}ix@o|_rB20!_m#vSN{c@xaEt_F8~0c{H4DD literal 0 HcmV?d00001 diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/expected.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/expected.toml new file mode 100644 index 00000000..b6fcea58 --- /dev/null +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/expected.toml @@ -0,0 +1,57 @@ +# Hand-written from the raw lines with jq. Recorded by real Claude Code on the parity rig: one turn +# of four Bash calls (`echo hello | grep zzz`; `printf a > a.txt; printf b > b.txt; diff a.txt b.txt`; +# `test -f /missing`; `echo fine`), then the ToolSearch and the MCP call `stamp` the fake model +# scripts after them. No denial, no subagent. The first three commands exit 1; Claude Code +# writes `is_error: false` for each and names no code, only a `returnCodeInterpretation` in the line's +# `tool_use_result` (`jq -c 'select(.type == "user") | .tool_use_result.returnCodeInterpretation'`). +stream = "agent_stream.jsonl.gz" +frames = 15 +blank_frames = [] +non_json_frames = [] +subagent_ids = [] +denials = [] +mcp_calls = [ + { tool_use_id = "toolu_fake_stamp", server = "parity" }, +] +frame_sessions = [] +cost_reporting = "running" +tokens_reporting = "per_turn" + +[[sessions]] +id = "654ac8db-b358-475c-94fc-31ff9f84be61" +ended_by = "completed" + +# Exit of each listed result, from jq over the raw lines. The rule: Bash only; "Exit code N" leading the +# content of an error result -> N; a non-error result whose `tool_use_result` has a +# `returnCodeInterpretation` (Claude Code's own text for a nonzero exit it does not flag as an error) -> no code, +# the harness states none; any other non-error result -> 0. `code` absent means no exit. +[[exits]] +tool_use_id = "toolu_fake_g1_0" +session = "654ac8db-b358-475c-94fc-31ff9f84be61" +tool = "Bash" + +[[exits]] +tool_use_id = "toolu_fake_g1_1" +session = "654ac8db-b358-475c-94fc-31ff9f84be61" +tool = "Bash" + +[[exits]] +tool_use_id = "toolu_fake_g1_2" +session = "654ac8db-b358-475c-94fc-31ff9f84be61" +tool = "Bash" + +[[exits]] +tool_use_id = "toolu_fake_g1_3" +session = "654ac8db-b358-475c-94fc-31ff9f84be61" +tool = "Bash" +code = 0 + +[[exits]] +tool_use_id = "toolu_fake_search" +session = "654ac8db-b358-475c-94fc-31ff9f84be61" +tool = "ToolSearch" + +[[exits]] +tool_use_id = "toolu_fake_stamp" +session = "654ac8db-b358-475c-94fc-31ff9f84be61" +tool = "mcp__parity__stamp" diff --git a/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/usage_totals.toml b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/usage_totals.toml new file mode 100644 index 00000000..00c0381c --- /dev/null +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/usage_totals.toml @@ -0,0 +1,13 @@ +[message."654ac8db-b358-475c-94fc-31ff9f84be61"] +input_tokens = 700 +output_tokens = 7 +cache_read_tokens = 0 +cache_creation_tokens = 0 + +[session_total."654ac8db-b358-475c-94fc-31ff9f84be61"] +input_tokens = 700 +output_tokens = 140 +cache_read_tokens = 0 +cache_creation_tokens = 0 +cost_usd = 0.005600000000000001 + From a6f3917c89438f391f8d913bc2148843ce0ffc1e Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 21:05:57 +0900 Subject: [PATCH 81/93] test(adapter-opencode): record the same three exits as the export states Co-Authored-By: Claude Opus 5.5 --- .../tests/fixtures/PROVENANCE.toml | 13 + .../streams/shell_exit_semantics/export.json | 378 ++++++++++++++++++ .../streams/shell_exit_semantics/stdout.jsonl | 19 + .../tests/it/guard_opencode_driver.rs | 15 +- 4 files changed, 424 insertions(+), 1 deletion(-) create mode 100644 crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_semantics/export.json create mode 100644 crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_semantics/stdout.jsonl diff --git a/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml b/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml index 9b8cc3b1..bf304a4d 100644 --- a/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml +++ b/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml @@ -204,3 +204,16 @@ synthetic = true model = "fake" stdout_sha256 = "40445d8d5a3ff50322f8c57f986edb5c5e26cd02ddfbbd2bba6c3be36a8addfb" export_sha256 = "ebadedd16e3bbcd6597251af0bbb2ff62c994d0aa913196fa6bb6102c7695fc1" + +# shell_exit_semantics (cc_exit_semantics probe, 2026-11-25): real OpenCode 2.2.7 on the same rig and +# image as shell_exit_stderr_timeout above (--auto; sha256:e287badacc755d5f2d0de612340f4efe8ab52b9f68ead85b8db2a5abb65b0d64). +# The fake model is the committed assets/docker/fakemodel/fakemodel.py, model id g1, with +# FAKE_G1_COMMANDS the JSON list ["echo hello | grep zzz", "printf a > a.txt; printf b > b.txt; diff a.txt b.txt", +# "test -f /missing", "echo fine"], then the MCP call stamp of the server parity. The first three +# commands exit 1 and OpenCode writes `exit: 1` for each; the fourth writes `exit: 0`. stdout.jsonl is each +# raw frame's text of the harness's stdout as one line; export.json is the text of the one frame of the +# export stream. +[stream.shell_exit_semantics] +model = "fake" +stdout_sha256 = "e7351995a187ad391ca6b0b126992621674827d1b361218fe8bee52f1f804d99" +export_sha256 = "5a6e17fa538f01adc8f31df34a053735cb09bb8c065c7aef3ee2425603da1aef" diff --git a/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_semantics/export.json b/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_semantics/export.json new file mode 100644 index 00000000..8621afd5 --- /dev/null +++ b/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_semantics/export.json @@ -0,0 +1,378 @@ +{ + "info": { + "id": "ses_ded715479ffe1zKO0tdgszEa2J", + "projectID": "bc7447dce6aa45fd13129230dddc6abeb62cb974", + "model": { + "id": "g1", + "providerID": "candler", + "variant": "default" + }, + "cost": 0, + "tokens": { + "input": 700, + "output": 140, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + }, + "outcome": "succeeded", + "time": { + "created": 1795607669644, + "updated": 1795607672199, + "busy": 1795607669977, + "idle": 1795607672201 + }, + "title": "done", + "location": { + "directory": "/work" + } + }, + "messages": [ + { + "id": "msg_2128eac64001kh6eiXI837fMUO", + "time": { + "created": 1795607670057 + }, + "text": "Run the commands you are given, call the MCP tool stamp of the server parity, then reply done.", + "files": [], + "type": "user" + }, + { + "id": "msg_2128ead33001P8Wcr3Ax2B3CvN", + "time": { + "created": 1795607671814, + "streamed": 1795607671870, + "completed": 1795607671880 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "g1", + "providerID": "candler", + "variant": "default" + }, + "content": [ + { + "type": "tool", + "id": "toolu_fake_g1_0", + "name": "shell", + "executed": false, + "state": { + "status": "completed", + "input": { + "command": "echo hello | grep zzz" + }, + "content": [ + { + "type": "text", + "text": "(no output)" + }, + { + "type": "text", + "text": "Exit code: 1" + } + ], + "metadata": { + "status": "completed", + "truncated": false, + "exit": 1 + } + }, + "time": { + "created": 1795607671863, + "ran": 1795607671866, + "completed": 1795607671878 + } + } + ], + "finish": "tool-calls", + "rawFinish": "tool_use", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_2128eb44c001AGVUJIuFCpqLWF", + "time": { + "created": 1795607671887, + "streamed": 1795607671939, + "completed": 1795607671948 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "g1", + "providerID": "candler", + "variant": "default" + }, + "content": [ + { + "type": "tool", + "id": "toolu_fake_g1_1", + "name": "shell", + "executed": false, + "state": { + "status": "completed", + "input": { + "command": "printf a > a.txt; printf b > b.txt; diff a.txt b.txt" + }, + "content": [ + { + "type": "text", + "text": "1c1\n< a\n\\ No newline at end of file\n---\n> b\n\\ No newline at end of file\n" + }, + { + "type": "text", + "text": "Exit code: 1" + } + ], + "metadata": { + "status": "completed", + "truncated": false, + "exit": 1 + } + }, + "time": { + "created": 1795607671934, + "ran": 1795607671937, + "completed": 1795607671947 + } + } + ], + "finish": "tool-calls", + "rawFinish": "tool_use", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_2128eb48f001HN2q3FjCZeyPKy", + "time": { + "created": 1795607671953, + "streamed": 1795607672007, + "completed": 1795607672013 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "g1", + "providerID": "candler", + "variant": "default" + }, + "content": [ + { + "type": "tool", + "id": "toolu_fake_g1_2", + "name": "shell", + "executed": false, + "state": { + "status": "completed", + "input": { + "command": "test -f /missing" + }, + "content": [ + { + "type": "text", + "text": "(no output)" + }, + { + "type": "text", + "text": "Exit code: 1" + } + ], + "metadata": { + "status": "completed", + "truncated": false, + "exit": 1 + } + }, + "time": { + "created": 1795607672001, + "ran": 1795607672004, + "completed": 1795607672012 + } + } + ], + "finish": "tool-calls", + "rawFinish": "tool_use", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_2128eb4d1002SEtzE35EpMYHBa", + "time": { + "created": 1795607672019, + "streamed": 1795607672072, + "completed": 1795607672077 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "g1", + "providerID": "candler", + "variant": "default" + }, + "content": [ + { + "type": "tool", + "id": "toolu_fake_g1_3", + "name": "shell", + "executed": false, + "state": { + "status": "completed", + "input": { + "command": "echo fine" + }, + "content": [ + { + "type": "text", + "text": "fine\n" + } + ], + "metadata": { + "status": "completed", + "truncated": false, + "exit": 0 + } + }, + "time": { + "created": 1795607672067, + "ran": 1795607672069, + "completed": 1795607672076 + } + } + ], + "finish": "tool-calls", + "rawFinish": "tool_use", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_2128eb511001tcCwqlR3x3loiT", + "time": { + "created": 1795607672083, + "streamed": 1795607672138, + "completed": 1795607672141 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "g1", + "providerID": "candler", + "variant": "default" + }, + "content": [ + { + "type": "tool", + "id": "toolu_fake_stamp", + "name": "parity_stamp", + "executed": false, + "state": { + "status": "completed", + "input": {}, + "content": [ + { + "type": "text", + "text": "parity-stamp-5c1e" + } + ], + "metadata": { + "truncated": false + } + }, + "time": { + "created": 1795607672130, + "ran": 1795607672134, + "completed": 1795607672140 + } + } + ], + "finish": "tool-calls", + "rawFinish": "tool_use", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_2128eb551001u68lTSO4U7SujS", + "time": { + "created": 1795607672147, + "streamed": 1795607672198, + "completed": 1795607672199 + }, + "type": "assistant", + "agent": "build", + "model": { + "id": "g1", + "providerID": "candler", + "variant": "default" + }, + "content": [ + { + "type": "text", + "text": "done" + } + ], + "finish": "stop", + "rawFinish": "end_turn", + "cost": 0, + "tokens": { + "input": 100, + "output": 20, + "reasoning": 0, + "cache": { + "read": 0, + "write": 0 + } + } + }, + { + "id": "msg_2128eb5890027Hl9vaDahovXwa", + "time": { + "created": 1795607672201 + }, + "type": "idle", + "outcome": "succeeded" + } + ] +} + diff --git a/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_semantics/stdout.jsonl b/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_semantics/stdout.jsonl new file mode 100644 index 00000000..3f4b7096 --- /dev/null +++ b/crates/candler-harness-opencode/tests/fixtures/streams/shell_exit_semantics/stdout.jsonl @@ -0,0 +1,19 @@ +{"type":"step_start","timestamp":1795607670075,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128ead3b001rEq9vO56Wb4OSg","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128ead33001P8Wcr3Ax2B3CvN","type":"step-start"}} +{"type":"retry","timestamp":1795607670077,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128ead33001P8Wcr3Ax2B3CvN","attempt":2,"nextRetryAt":1795607671793,"error":{"type":"provider.rate-limit","message":"Provider request failed with HTTP 429","status":429,"response":{"body":"\r\n429 Too Many Requests\r\n\r\n

429 Too Many Requests

\r\n
nginx/1.28.3
\r\n\r\n\r\n"}}} +{"type":"tool_use","timestamp":1795607671878,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"partID":"prt_2128eb437001KihPEQxbd3Q96V","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128ead33001P8Wcr3Ax2B3CvN","type":"tool","id":"toolu_fake_g1_0","tool":"shell","state":{"status":"completed","input":{"command":"echo hello | grep zzz"},"output":"(no output)","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":1},"content":[{"type":"text","text":"(no output)"},{"type":"text","text":"Exit code: 1"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\": \"echo hello | grep zzz\"}"},"time":{"start":1795607671863,"end":1795607671878}}}} +{"type":"step_finish","timestamp":1795607671880,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb448001MDiHNoeR57IFDD","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128ead33001P8Wcr3Ax2B3CvN","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":100,"output":20,"reasoning":0,"cache":{"read":0,"write":0}}}} +{"type":"step_start","timestamp":1795607671932,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb47c001aChban1yA40w0v","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb44c001AGVUJIuFCpqLWF","type":"step-start"}} +{"type":"tool_use","timestamp":1795607671947,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"partID":"prt_2128eb47e001gbB4knARut37Vu","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb44c001AGVUJIuFCpqLWF","type":"tool","id":"toolu_fake_g1_1","tool":"shell","state":{"status":"completed","input":{"command":"printf a > a.txt; printf b > b.txt; diff a.txt b.txt"},"output":"1c1\n< a\n\\ No newline at end of file\n---\n> b\n\\ No newline at end of file\n","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":1},"content":[{"type":"text","text":"1c1\n< a\n\\ No newline at end of file\n---\n> b\n\\ No newline at end of file\n"},{"type":"text","text":"Exit code: 1"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\": \"printf a > a.txt; printf b > b.txt; diff a.txt b.txt\"}"},"time":{"start":1795607671934,"end":1795607671947}}}} +{"type":"step_finish","timestamp":1795607671948,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb48c001oy03thKj02wQ56","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb44c001AGVUJIuFCpqLWF","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":100,"output":20,"reasoning":0,"cache":{"read":0,"write":0}}}} +{"type":"step_start","timestamp":1795607671999,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb4bf001s9tS2Zhbz9yNWR","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb48f001HN2q3FjCZeyPKy","type":"step-start"}} +{"type":"tool_use","timestamp":1795607672012,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"partID":"prt_2128eb4c1001Iduab3M6WYuWbn","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb48f001HN2q3FjCZeyPKy","type":"tool","id":"toolu_fake_g1_2","tool":"shell","state":{"status":"completed","input":{"command":"test -f /missing"},"output":"(no output)","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":1},"content":[{"type":"text","text":"(no output)"},{"type":"text","text":"Exit code: 1"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\": \"test -f /missing\"}"},"time":{"start":1795607672001,"end":1795607672012}}}} +{"type":"step_finish","timestamp":1795607672013,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb4cd001L1yKEfMUTZVzzh","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb48f001HN2q3FjCZeyPKy","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":100,"output":20,"reasoning":0,"cache":{"read":0,"write":0}}}} +{"type":"step_start","timestamp":1795607672065,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb501001NxLffnvL7O3k5X","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb4d1002SEtzE35EpMYHBa","type":"step-start"}} +{"type":"tool_use","timestamp":1795607672076,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"partID":"prt_2128eb503001Fkpzt5E509W0Yo","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb4d1002SEtzE35EpMYHBa","type":"tool","id":"toolu_fake_g1_3","tool":"shell","state":{"status":"completed","input":{"command":"echo fine"},"output":"fine\n","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":0},"content":[{"type":"text","text":"fine\n"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\": \"echo fine\"}"},"time":{"start":1795607672067,"end":1795607672076}}}} +{"type":"step_finish","timestamp":1795607672077,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb50d001tIkIdFSrZSiK9P","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb4d1002SEtzE35EpMYHBa","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":100,"output":20,"reasoning":0,"cache":{"read":0,"write":0}}}} +{"type":"step_start","timestamp":1795607672129,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb541001D3aqFZwgFqUalx","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb511001tcCwqlR3x3loiT","type":"step-start"}} +{"type":"tool_use","timestamp":1795607672140,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"partID":"prt_2128eb542001CRzvBI66IKfr3G","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb511001tcCwqlR3x3loiT","type":"tool","id":"toolu_fake_stamp","tool":"parity_stamp","state":{"status":"completed","input":{},"output":"parity-stamp-5c1e","title":"parity_stamp","metadata":{"metadata":{"truncated":false},"content":[{"type":"text","text":"parity-stamp-5c1e"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{}"},"time":{"start":1795607672130,"end":1795607672140}}}} +{"type":"step_finish","timestamp":1795607672141,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb54d001Q1BZNUIMrZwAxI","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb511001tcCwqlR3x3loiT","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":100,"output":20,"reasoning":0,"cache":{"read":0,"write":0}}}} +{"type":"step_start","timestamp":1795607672193,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb581001zegSdarNOzREG4","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb551001u68lTSO4U7SujS","type":"step-start"}} +{"type":"text","timestamp":1795607672197,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb583001B4VqUcu5zztxfa","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb551001u68lTSO4U7SujS","type":"text","text":"done","time":{"start":1795607672195,"end":1795607672197}}} +{"type":"step_finish","timestamp":1795607672199,"sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","part":{"id":"prt_2128eb587001g2eNBUWU30UKwR","sessionID":"ses_ded715479ffe1zKO0tdgszEa2J","messageID":"msg_2128eb551001u68lTSO4U7SujS","type":"step-finish","reason":"stop","cost":0,"tokens":{"input":100,"output":20,"reasoning":0,"cache":{"read":0,"write":0}}}} 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 4dd9fe4c..65e90b57 100644 --- a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs +++ b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs @@ -809,7 +809,7 @@ fn opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions() -> // state is an error, or that reported none (the timed-out call is `completed` with a signal // name and no code), carries none. Expected values come from // `jq -c '[.messages[].content[]? | select(.type == "tool") | .state.metadata.exit]'`. - let exit_rows: [(&str, Vec); 4] = [ + let exit_rows: [(&str, Vec); 5] = [ ( "shell_exit_stderr_timeout", vec![ @@ -818,6 +818,19 @@ fn opencode_export_reader_covers_trace_errors_cache_cost_and_child_sessions() -> json!({"kind": "tool_result", "is_error": false}), ], ), + ( + // `jq -c '[.. | objects | select(.type? == "tool") | [.name, .state.metadata.exit]]'` gives + // shell 1, 1, 1, 0 and parity_stamp null; + // the fifth result is the MCP `stamp` call. + "shell_exit_semantics", + vec![ + json!({"kind": "tool_result", "is_error": false, "exit": {"kind": "code", "code": 1}}), + json!({"kind": "tool_result", "is_error": false, "exit": {"kind": "code", "code": 1}}), + json!({"kind": "tool_result", "is_error": false, "exit": {"kind": "code", "code": 1}}), + json!({"kind": "tool_result", "is_error": false, "exit": {"kind": "code", "code": 0}}), + json!({"kind": "tool_result", "is_error": false}), + ], + ), ( "sigint_mid_tool", vec![json!({"kind": "tool_result", "is_error": true})], From f7e3986bd8d88a00e227447a10358f91d6917a40 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 21:06:01 +0900 Subject: [PATCH 82/93] reports(adapter-claude-code): which exit Claude Code's Bash result is Co-Authored-By: Claude Opus 5.5 --- .../leaves/cc_exit_semantics_v0.md | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 __reports__/run-context/leaves/cc_exit_semantics_v0.md diff --git a/__reports__/run-context/leaves/cc_exit_semantics_v0.md b/__reports__/run-context/leaves/cc_exit_semantics_v0.md new file mode 100644 index 00000000..b59c3207 --- /dev/null +++ b/__reports__/run-context/leaves/cc_exit_semantics_v0.md @@ -0,0 +1,100 @@ +# cc_exit_semantics: which exit Claude Code's Bash result states + +Case **(b)**: Claude Code writes `is_error: false` for three commands that exit 1, and a field tells them from a true exit 0. +The reader now gives no exit for such a result. OpenCode's reader was right and is unchanged. + +## Probe + +Question: what do real Claude Code 2.1.311 and real OpenCode 2.2.7 write for `grep` with no match, `diff` of two different +files and `test -f /missing`? Rig: `parity_e2e.rs` (`start_fake`, `base_experiment`, `seal`), fake model `g1`, one run per +harness, commands `echo hello | grep zzz`, `printf a > a.txt; printf b > b.txt; diff a.txt b.txt`, `test -f /missing`, +and the control `echo fine`. No token was spent. `g1` took exactly two commands; it now takes two or more +(`assets/docker/fakemodel/fakemodel.py`), so the recording is repeatable (see `tests/fixtures/README.md`, "Record a stream again"). +The probe's test code is deleted; the recordings are the fixtures `streams/shell_exit_semantics/` of both crates. + +### Claude Code (`agent_stream.jsonl.gz`, lines 3, 5, 7, 9; `jq` over the `user` lines) + +| command | `is_error` | content | `tool_use_result` | +|---|---|---|---| +| `grep` no match | false | `(Bash completed with no output)` | `{stdout:"", stderr:"", interrupted:false, isImage:false, returnCodeInterpretation:"No matches found", noOutputExpected:false}` | +| `diff` differs | false | the diff text | same keys, `returnCodeInterpretation:"Files differ"` | +| `test -f /missing` | false | `(Bash completed with no output)` | same keys, `returnCodeInterpretation:"Condition is false"` | +| `echo fine` (exit 0) | false | `fine` | `{stdout:"fine", stderr:"", interrupted:false, isImage:false, noOutputExpected:false}`, no `returnCodeInterpretation` | + +No field and no text carries the number 1. What distinguishes the three is the key `returnCodeInterpretation`, which +the exit-0 result does not have. + +### OpenCode (`export.json`, `state.metadata.exit`; the same in `stdout.jsonl`) + +| command | `status` | `metadata.exit` | content ends | +|---|---|---|---| +| `grep` no match | completed | 1 | `Exit code: 1` | +| `diff` differs | completed | 1 | `Exit code: 1` | +| `test -f /missing` | completed | 1 | `Exit code: 1` | +| `echo fine` | completed | 0 | no exit line | + +OpenCode states each code, and its reader (`metadata.exit`) already gives code 1, 1, 1 and 0. No change there. + +## Decision + +Case (b). `exit_of` (`crates/candler-harness-claude-code/src/parse.rs`) gives no exit to a non-error result whose +`tool_use_result` has `returnCodeInterpretation`: the harness states a nonzero exit without a number, and Candler never +infers one. A non-error result without it still gives code 0, with the existing exceptions (`backgroundTaskId`, +`timedOutAfterMs`, `interrupted`). Candler writes no code 1 for these: the interpretation text says "No matches found", +not 1. + +The reader's output changes for a recorded kind of result, so the reader version is 0.4.0. `READER` and `READER_VERSION` +are one macro invocation, `reader_version!(0, 4, 0)`, so the text and the version cannot differ (the OpenCode crate's +duplicates are another leaf's). + +### Finding #5 (one decision, at the source): not possible as written + +The spec asks `exit_of` to gate on the call's tool. At parse time the reader sees one `tool_result` block and not the +call it answers: the call is in an earlier line and its session is known only when `Registry::emit` runs (the same +call id can be held by a child session). So the tool is knowable in `emit` and nowhere earlier. The decision is made +once there, and `exit_of` no longer invents anything: it reads what the result states (code from `Exit code N`, code 0 +for an unflagged non-error result, none otherwise). The clearing in `emit` is not dead: an error result of an MCP tool +whose text starts `Exit code 4` would otherwise carry a code. Spec defect, reported; no code works around it. + +## Guard + +`guard_reader::expected_facts` (`exits` rows of `shell_exit_semantics/expected.toml`, written from `jq`, never from the reader): + +| call | tool | row | +|---|---|---| +| `toolu_fake_g1_0` grep | Bash | no code | +| `toolu_fake_g1_1` diff | Bash | no code | +| `toolu_fake_g1_2` test | Bash | no code | +| `toolu_fake_g1_3` echo fine | Bash | code 0 | +| `toolu_fake_search` | ToolSearch | no code | +| `toolu_fake_stamp` | mcp__parity__stamp | no code | + +OpenCode: `guard_opencode_driver` gains the row `shell_exit_semantics`: code 1, 1, 1, 0 for the shell calls and none for `stamp`. + +Bites (both seen red): + +1. The old rule (a non-error result gives code 0), on the fixture before the fix: + `Error: "shell_exit_semantics: exit of the result of Bash call toolu_fake_g1_0 in 654ac8db-b358-475c-94fc-31ff9f84be61 is [Some(0)], want None"` +2. The gate in `Registry::emit` off (a non-Bash result keeps its exit): + `Error: "api_error: exit of the result of Edit call toolu_01DvCBeLjPX4jbFuFuTJRphU in 50b18959-0cb5-4deb-b336-1c8c57970383 is [Some(0)], want None"` + +## Docs + +`parse.rs` (`exit_of`) and the crate README ("What the reader reads") state the rule. The crate CHANGELOG is written by +release-plz from commits and was not edited. `tests/fixtures/README.md` says how to record the streams again, with the +fake-model id `g1`, its commands and the rig; for `shell_exit_stderr_timeout` it gives the shape of the uncommitted script +`sh1` (three `Bash` calls in one message, ids, commands and the `timeout` field), since the probe report holds enough. + +## Not covered + +- A real exit 0 is still read from the absence of `returnCodeInterpretation`, as the harness states no number for it. + A Claude Code release that adds an interpretation to other commands would drop their exit to none (safe), not to a wrong code. +- Other commands Claude Code's semantics list (`rg`, `find`, `[ ]`) were not recorded; they share the field. +- A non-Bash tool whose error text starts `Exit code N` is cleared by `emit`; no recorded stream holds one. +- The OpenCode crate's duplicated reader-version constants are untouched. + +## Docker + +Before: 20 images, 3 containers. After: the same. The fake-model image the probe built was removed by the rig's own +cleanup by id; the two agent images it ran (`sha256:57f339fc3580...`, `sha256:e287badacc75...`) were already present and +are left. No image of mine remains; `candler-gateway:latest` untouched. From 5a282cfa09669a47b6cf5a1540f2339285e4f9ee Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:56:22 +0900 Subject: [PATCH 83/93] fix(evaluation): read a run's raw/ once in the store and refuse strays The store layout now owns the file names of the trace, the manifest and the raw files, and Store::raw_streams is the one reader of raw/: an entry that is not .jsonl.gz refuses with the store's Parse error rather than serving fewer streams. The context, the frame writer and the runner take their spellings from the layout. Co-Authored-By: Claude Opus 5.5 --- .../src/evaluation/context/assemble.rs | 52 ++++--------------- crates/candler-core/src/frames/mod.rs | 6 ++- crates/candler-core/src/runner/exec/mod.rs | 4 +- crates/candler-core/src/store/layout.rs | 28 ++++++++-- crates/candler-core/src/store/run.rs | 22 +++++++- .../tests/it/guard_run_context.rs | 28 ++++++++++ 6 files changed, 89 insertions(+), 51 deletions(-) diff --git a/crates/candler-core/src/evaluation/context/assemble.rs b/crates/candler-core/src/evaluation/context/assemble.rs index 337e0820..61ba0c55 100644 --- a/crates/candler-core/src/evaluation/context/assemble.rs +++ b/crates/candler-core/src/evaluation/context/assemble.rs @@ -17,6 +17,7 @@ use super::rule::FileRule; use super::{ContextError, RunPart}; use crate::store::Store; use crate::store::blob::digest_of_file; +use crate::store::layout::{MANIFEST_FILE, RAW_DIR, TRACE_FILE, raw_file_name}; /// What a stored file is in the context it is served in. #[derive(Debug, Clone, PartialEq, Eq)] @@ -137,7 +138,8 @@ impl Assembled { /// kind the manifest holds in neither list, or a kind whose list or file blobs the store lacks, /// [`ContextError::PartMissing`] when the trace or the raw streams are needed and the run stores /// none, [`ContextError::NotSealed`] when the run has no seal, [`ContextError::Glob`] for a bad -/// glob, [`ContextError::Store`] when the manifest or tree cannot be read, +/// glob, [`ContextError::Store`] when the manifest or tree cannot be read or `raw/` holds an +/// entry that is not a raw stream file, /// [`ContextError::Io`] when a stored file cannot be read, and /// [`ContextError::MissingMetadata`] when a metadata path has no value in the manifest. pub fn assemble(store: &Store, run: &RunKey, needs: &Needs) -> Result { @@ -217,10 +219,10 @@ pub fn assemble(store: &Store, run: &RunKey, needs: &Needs) -> Result Result Result { } /// A stored file that has no digest on record: its hash is taken here, at assembly, and its copy -/// is checked against it. +/// is checked against it. The workspace name is the file's name in the store, so an evaluator +/// finds `trace.jsonl`, `raw/.jsonl.gz` and `manifest.json` where a run directory holds +/// them; both take their spelling from `store::layout`. fn stored_file( source: PathBuf, workspace: &str, @@ -279,42 +283,6 @@ fn stored_file( }) } -/// The suffix of a stored raw stream's file name. -const RAW_SUFFIX: &str = ".jsonl.gz"; - -/// The streams the run stores below `raw/`, sorted by name. A file whose name is not -/// `.jsonl.gz` is not a stream. -fn stored_streams(store: &Store, run: &RunKey) -> Result, ContextError> { - let dir = store.layout().raw_dir(run); - let listing = match std::fs::read_dir(&dir) { - Ok(listing) => listing, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(source) => { - return Err(ContextError::Io { - op: "list the raw streams", - path: dir, - source, - }); - } - }; - let mut streams = Vec::new(); - for entry in listing { - let entry = entry.map_err(|source| ContextError::Io { - op: "list the raw streams", - path: dir.clone(), // BORROW: the error owns the path - source, - })?; - if let Some(name) = entry.file_name().to_str() - && let Some(stem) = name.strip_suffix(RAW_SUFFIX) - && let Ok(stream) = StreamName::from_str(stem) - { - streams.push(stream); - } - } - streams.sort(); - Ok(streams) -} - /// The entry of `kind` in a manifest list of inputs. fn held<'a>(list: &'a [DigestRef], kind: &Name) -> Option<&'a DigestRef> { list.iter().find(|entry| &entry.kind == kind) diff --git a/crates/candler-core/src/frames/mod.rs b/crates/candler-core/src/frames/mod.rs index 12d5828b..a1c928eb 100644 --- a/crates/candler-core/src/frames/mod.rs +++ b/crates/candler-core/src/frames/mod.rs @@ -25,6 +25,7 @@ use flate2::read::MultiGzDecoder; use flate2::{Compression, GzBuilder}; use sha2::{Digest as _, Sha256}; +use crate::store::layout::raw_file_name; use crate::store::sync::{sync_dir, sync_file}; /// The two bytes that open a gzip member. @@ -275,8 +276,9 @@ impl FrameWriter { /// Returns the I/O error of any of those steps; the plain file stays on disk. pub fn finish(mut self) -> io::Result { self.flush_tail()?; - let gz_path = self.dir.join(format!("{}.jsonl.gz", self.stream)); - let gz_tmp = self.dir.join(format!("{}.jsonl.gz.tmp", self.stream)); + let gz_name = raw_file_name(&self.stream); + let gz_path = self.dir.join(&gz_name); + let gz_tmp = self.dir.join(format!("{gz_name}.tmp")); let out = HashingWriter { file: File::create(&gz_tmp)?, hasher: Sha256::new(), diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index 80cf4d71..9448670a 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -58,6 +58,7 @@ use crate::jobs::model::JobCause; use crate::jobs::slots::Slot; use crate::store::StoreError; use crate::store::blob::digest_of_file; +use crate::store::layout::stream_of_raw_file; use crate::store::run::{Existing, RunWriter}; use crate::supervise::SuperviseError; use crate::supervise::git::{GitError, RecordDir, mark_executable, tree_at_commit}; @@ -414,8 +415,7 @@ async fn destroy_unstarted( /// The stream a raw file archives, from its name `.jsonl.gz`. fn stream_of(path: &Path) -> Option { - let name = path.file_name()?.to_str()?; - StreamName::from_str(name.strip_suffix(".jsonl.gz")?).ok() + stream_of_raw_file(path.file_name()?.to_str()?) } /// Millionths of a dollar in `usd`, rounded; a negative or non-finite cost counts as none. diff --git a/crates/candler-core/src/store/layout.rs b/crates/candler-core/src/store/layout.rs index ffb1ae9e..ca5f24bd 100644 --- a/crates/candler-core/src/store/layout.rs +++ b/crates/candler-core/src/store/layout.rs @@ -1,6 +1,7 @@ //! Every path of a store, built in one place. use std::path::{Path, PathBuf}; +use std::str::FromStr as _; use candler_schemas::primitives::{Digest, JobId, NameVersion, RequestId, RunKey}; use candler_schemas::raw::StreamName; @@ -9,9 +10,28 @@ use candler_schemas::raw::StreamName; const MARKER: &str = "store.json"; /// The extension of a finished outcome file. pub(crate) const OUTCOME_EXTENSION: &str = "jsonl"; +/// The file name of a run's manifest. +pub(crate) const MANIFEST_FILE: &str = "manifest.json"; +/// The file name of a run's normalised trace. +pub(crate) const TRACE_FILE: &str = "trace.jsonl"; +/// The name of the directory of a run's raw streams. +pub(crate) const RAW_DIR: &str = "raw"; +/// The suffix of a finished raw file: `.jsonl.gz`. +pub(crate) const RAW_SUFFIX: &str = ".jsonl.gz"; /// The suffix of an outcome file that is still being written. const PARTIAL_SUFFIX: &str = ".partial"; +/// The file name of the finished raw file of `stream`. +pub(crate) fn raw_file_name(stream: &StreamName) -> String { + format!("{stream}{RAW_SUFFIX}") +} + +/// The stream a finished raw file archives, from its file name; `None` when `name` is not +/// `.jsonl.gz` with a valid stream name. The inverse of [`raw_file_name`]. +pub(crate) fn stream_of_raw_file(name: &str) -> Option { + StreamName::from_str(name.strip_suffix(RAW_SUFFIX)?).ok() +} + /// The paths of a store rooted at one directory; it is the only code that builds a store path. #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] @@ -61,7 +81,7 @@ impl StoreLayout { /// The manifest of a run. #[must_use] pub fn manifest(&self, run: &RunKey) -> PathBuf { - self.run_dir(run).join("manifest.json") + self.run_dir(run).join(MANIFEST_FILE) } /// The workspace tree of a run. @@ -73,7 +93,7 @@ impl StoreLayout { /// The normalised trace of a run. #[must_use] pub fn trace(&self, run: &RunKey) -> PathBuf { - self.run_dir(run).join("trace.jsonl") + self.run_dir(run).join(TRACE_FILE) } /// The seal of a run: present once the run is complete. @@ -85,13 +105,13 @@ impl StoreLayout { /// The directory of a run's raw streams. #[must_use] pub fn raw_dir(&self, run: &RunKey) -> PathBuf { - self.run_dir(run).join("raw") + self.run_dir(run).join(RAW_DIR) } /// The finished raw file of one stream of a run. #[must_use] pub fn raw(&self, run: &RunKey, stream: &StreamName) -> PathBuf { - self.raw_dir(run).join(format!("{stream}.jsonl.gz")) + self.raw_dir(run).join(raw_file_name(stream)) } /// The directory that holds the blobs. diff --git a/crates/candler-core/src/store/run.rs b/crates/candler-core/src/store/run.rs index c399b2c9..038f65dc 100644 --- a/crates/candler-core/src/store/run.rs +++ b/crates/candler-core/src/store/run.rs @@ -11,7 +11,7 @@ use candler_schemas::trace::TraceFile; use serde_json::Value; use super::blob::{copy_synced, digest_of_file}; -use super::layout::StoreLayout; +use super::layout::{StoreLayout, stream_of_raw_file}; use super::sync::sync_file; use super::{Store, StoreError, io_error, sync_dir, temp_sibling, visible_names, write_atomic}; @@ -374,6 +374,26 @@ impl Store { }) } + /// The streams a run stores below `raw/`, in name order; a run with no `raw/` directory has + /// none. Every visible entry must be a finished raw file `.jsonl.gz`, which is all + /// the run writer puts there. + /// + /// # Errors + /// Returns [`StoreError::Io`] when the directory cannot be listed and [`StoreError::Parse`] + /// when an entry is not a raw file of a stream. + pub fn raw_streams(&self, key: &RunKey) -> Result, StoreError> { + let dir = self.layout().raw_dir(key); + visible_names(&dir)? + .iter() + .map(|name| { + stream_of_raw_file(name).ok_or_else(|| StoreError::Parse { + path: dir.join(name), + detail: "is not a raw file `.jsonl.gz` of a stream".to_owned(), + }) + }) + .collect() + } + /// The path of a run's finished raw file for `stream`, when it is stored. #[must_use] pub fn raw_path(&self, key: &RunKey, stream: &StreamName) -> Option { diff --git a/crates/candler-core/tests/it/guard_run_context.rs b/crates/candler-core/tests/it/guard_run_context.rs index d479ec80..8a1a4f58 100644 --- a/crates/candler-core/tests/it/guard_run_context.rs +++ b/crates/candler-core/tests/it/guard_run_context.rs @@ -923,3 +923,31 @@ fn needs_parts_refused_when_the_run_cannot_serve_them() { "the manifest copy holds the stored manifest's bytes" ); } + +/// Guards: R9 — an entry of a run's `raw/` directory that is not a finished raw file `.jsonl.gz` of a stream (a stray note, an unfinished `.jsonl`, a `.jsonl.gz` whose stem is no stream name) refuses the context with the code `candler.internal` naming the entry, so a damaged `raw/` is never served as fewer streams under a valid-looking digest; the run without the entry is served in full. Oracle: hand-written; the entry names and the code are the ones written below, and the entries are written into a run's `raw/` here. +#[test] +fn a_stray_entry_in_raw_refuses_the_context() { + let (_keep, store) = mini_store(&mini()); + let run = key_of(&store, 6); + let raw = store.layout().raw_dir(&run); + let stored = fs::read_dir(&raw) + .expect("the run stores raw streams") + .count(); + assert!(stored > 0, "the run stores raw streams"); + let needs = needs_declaring(&["raw"]); + assert!( + assemble(&store, &run, &needs).is_ok(), + "the run serves its streams before the stray entry is written" + ); + for stray in ["notes.txt", "agent_stream.jsonl", "Bad Name.jsonl.gz"] { + let path = raw.join(stray); + fs::write(&path, b"x").expect("the stray entry is written"); + let error = assemble(&store, &run, &needs).expect_err("a stray entry is refused"); + assert_eq!(error.code().as_str(), "candler.internal", "{stray}"); + assert!( + error.to_string().contains(stray), + "`{error}` names the entry `{stray}`" + ); + fs::remove_file(&path).expect("the stray entry is removed"); + } +} From d84165e6b01ae1ba2de3bfbb735142b9c303a077 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:57:59 +0900 Subject: [PATCH 84/93] refactor(evaluation): build a served copy's context entry in one place Co-Authored-By: Claude Opus 5.5 --- .../src/evaluation/context/materialise.rs | 36 ++++++++++--------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/crates/candler-core/src/evaluation/context/materialise.rs b/crates/candler-core/src/evaluation/context/materialise.rs index a4b9b340..9278ae5c 100644 --- a/crates/candler-core/src/evaluation/context/materialise.rs +++ b/crates/candler-core/src/evaluation/context/materialise.rs @@ -7,7 +7,7 @@ use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _}; use std::path::{Path, PathBuf}; use candler_schemas::evaluation::{ContextArtifact, ContextRaw, ContextRef, RunContext}; -use candler_schemas::primitives::Digest; +use candler_schemas::primitives::{Digest, RelPath}; use super::ContextError; use super::assemble::{Assembled, AssembledFile, Served}; @@ -153,6 +153,19 @@ fn copy_stored(root: &Path, file: &AssembledFile) -> Result<(PathBuf, Digest), C Ok((target, written)) } +/// The context's entry for the copy at `copy`, named `path` and holding `digest`. +fn artifact_of( + path: &RelPath, + copy: &Path, + digest: Digest, +) -> Result { + Ok(ContextArtifact::new( + path.clone(), // BORROW: the context owns its paths + text_of(copy)?, + digest, + )) +} + /// `path` as the text the context carries. fn text_of(path: &Path) -> Result { path.to_str() @@ -190,27 +203,18 @@ pub fn materialise(assembled: &Assembled, workspace: &Path) -> Result builder, - Served::Artifact(path) => { - // BORROW: the context owns its paths - builder.artifact(ContextArtifact::new(path.clone(), text_of(©)?, digest)) - } - Served::Trace => builder.trace(ContextArtifact::new( - file.workspace.clone(), // BORROW: the context owns its paths - text_of(©)?, - digest, - )), + Served::Artifact(path) => builder.artifact(artifact_of(path, ©, digest)?), + Served::Trace => builder.trace(artifact_of(&file.workspace, ©, digest)?), Served::Raw(stream) => builder.raw(ContextRaw::new( stream.clone(), // BORROW: the context owns its streams text_of(©)?, digest, )), - Served::Manifest => builder.manifest(ContextArtifact::new( - file.workspace.clone(), // BORROW: the context owns its paths - text_of(©)?, - digest, - )), + Served::Manifest => builder.manifest(artifact_of(&file.workspace, ©, digest)?), }; } let inputs = space.root().join("inputs"); From 6eb2e600a3c5fab0e154dec67746db210e38510c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:59:35 +0900 Subject: [PATCH 85/93] refactor(adapter-opencode): spell the export reader's version once Co-Authored-By: Claude Opus 5.5 --- crates/candler-harness-opencode/src/lib.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/candler-harness-opencode/src/lib.rs b/crates/candler-harness-opencode/src/lib.rs index 18715695..a20dee3a 100644 --- a/crates/candler-harness-opencode/src/lib.rs +++ b/crates/candler-harness-opencode/src/lib.rs @@ -33,11 +33,21 @@ pub const VALIDATED: semver::Version = semver::Version::new(2, 2, 7); /// The reader of the live NDJSON, as the trace header names it, `opencode-ndjson@`; the version changes whenever the reader's output does. pub const LIVE_READER: &str = "opencode-ndjson@0.1.0"; -/// The reader of the session export, as the trace header names it, `opencode-export@`; the version changes whenever the reader's output does. -pub const EXPORT_READER: &str = "opencode-export@0.2.0"; +/// Defines [`EXPORT_READER`] and its version from the one spelling of the version, so the two +/// cannot differ. +macro_rules! export_reader { + ($major:literal, $minor:literal, $patch:literal) => { + /// The reader of the session export, as the trace header names it, + /// `opencode-export@`; the version changes whenever the reader's output does. + pub const EXPORT_READER: &str = + concat!("opencode-export@", $major, ".", $minor, ".", $patch); -/// The version of [`EXPORT_READER`]. -const EXPORT_READER_VERSION: semver::Version = semver::Version::new(0, 2, 0); + /// The version of [`EXPORT_READER`]. + const EXPORT_READER_VERSION: semver::Version = semver::Version::new($major, $minor, $patch); + }; +} + +export_reader!(0, 2, 0); /// The stream name under which the gateway's census is stored. pub const CENSUS_STREAM: &str = "gateway_census"; From fcd6442e004a3287106175b7e8457e187b70ae22 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 21:02:16 +0900 Subject: [PATCH 86/93] fix(evaluator-helper): refuse a trace out of order like Candler's reader Co-Authored-By: Claude Opus 5.5 --- docs/contract/codes.toml | 5 ++ docs/contract/evaluator-helper.md | 3 +- python/candler-evaluator/CHANGELOG.md | 5 +- python/candler-evaluator/README.md | 5 +- .../src/candler_evaluator/__init__.py | 3 +- .../src/candler_evaluator/trace.py | 56 ++++++++++++++++--- .../tests/test_guard_codes.py | 1 + .../tests/test_guard_context.py | 32 +++++++++++ 8 files changed, 98 insertions(+), 12 deletions(-) diff --git a/docs/contract/codes.toml b/docs/contract/codes.toml index 6bb305c4..dee82a5b 100644 --- a/docs/contract/codes.toml +++ b/docs/contract/codes.toml @@ -1871,6 +1871,11 @@ side = "suite" when = "A suite entry has a deadline_ms above 2**53 - 1, which Candler passes on and the helper refuses with error -32602." at = "-" +[helper."helper.trace_out_of_order"] +side = "plugin" +when = "A trace file read by a kind is empty, has a record before its header, a second header, a session after an event or a session declared twice." +at = "-" + [resolve."isolation.egress_invalid"] side = "experiment" enum = "EgressRefusal" diff --git a/docs/contract/evaluator-helper.md b/docs/contract/evaluator-helper.md index 9d3806c0..5ec62506 100644 --- a/docs/contract/evaluator-helper.md +++ b/docs/contract/evaluator-helper.md @@ -92,6 +92,7 @@ Package: `candler-evaluator@0.2.0`. | `helper.plugin_identity_missing` | A plug-in gives no name or version, and names no distribution that supplies them. | - | plugin | | `helper.plugin_kinds_missing` | A plug-in module defines no KINDS. | - | plugin | | `helper.request_invalid` | A request Candler sent has an id but fails the protocol's models; the helper answers with error -32602. | - | candler | +| `helper.trace_out_of_order` | A trace file read by a kind is empty, has a record before its header, a second header, a session after an event or a session declared twice. | - | plugin | ## Notes @@ -102,4 +103,4 @@ Package: `candler-evaluator@0.2.0`. - An instrument installed from a package index makes `describe` and `evaluate` fail with error -32000. [checked: candler-evaluator@0.1.0] - A module with no `KINDS` ends the process with exit 1 before it sends a frame. [checked: candler-evaluator@0.1.0] - A part is served when any kind in the request declares it in `needs`. [checked: candler-evaluator@0.2.0] -- `read_trace` checks lines, not order; it refuses `null` on an optional field. [checked: candler-evaluator@0.2.0] +- `read_trace` refuses a trace out of order and `null` on an optional field. [checked: candler-evaluator@0.2.0] diff --git a/python/candler-evaluator/CHANGELOG.md b/python/candler-evaluator/CHANGELOG.md index c4d19145..cedac462 100644 --- a/python/candler-evaluator/CHANGELOG.md +++ b/python/candler-evaluator/CHANGELOG.md @@ -10,7 +10,10 @@ PyPI without Eliott's go. The version is bumped by hand in `pyproject.toml` from `raw` stream with its `sha256`; `trace` was a bare path and is now a `ServedFile`. - `read_trace` yields a trace's records as models generated from `normalised-trace.schema.json`, refusing a line those models refuse: not JSON, an unknown - field, a `null` on an optional field or a wrong type. It checks lines, not the file's order. + field, a `null` on an optional field or a wrong type, and a file out of order as Candler's + reader refuses it (an empty file, a record before the header, a second header, a session + after an event, a session declared twice) with a `TraceOrderError`, a `ValueError`. The rules that relate + records, such as `seq` gaps, are not checked. - The wire models are generated from the published schemas by `scripts/gen_models.py`; the loop parses and builds every message through them, and the shared wire vectors decide what they accept. diff --git a/python/candler-evaluator/README.md b/python/candler-evaluator/README.md index 7de3d2c9..06d12751 100644 --- a/python/candler-evaluator/README.md +++ b/python/candler-evaluator/README.md @@ -24,8 +24,9 @@ grades one item, and may expose `NAME`, `VERSION`, `DIST`, `INSTRUMENTS`, `KIND_ `candler_evaluator.read_trace(context.trace)` yields the trace's records as models generated from `normalised-trace.schema.json` and raises `pydantic.ValidationError` at a line those models refuse: not JSON, an unknown field, a `null` on an optional field or a wrong type. It - checks each line, not the file's order; Candler checks the order when it writes the trace, and - the served copy is pinned by its `sha256`. + raises `TraceOrderError`, a `ValueError`, for a file out of order, as Candler's reader refuses it: an empty file, a + record before the header, a second header, a session after an event, a session declared twice. + It does not check the rules that relate records, such as `seq` gaps. - **`KINDS`** maps each kind's name to its function. - **`needs`** says what a kind reads: `artifacts` (globs), `inputs`, `metadata` (field paths), `snapshots`, `trace`, `raw` and `manifest` (the last three are booleans). It is set per kind in diff --git a/python/candler-evaluator/src/candler_evaluator/__init__.py b/python/candler-evaluator/src/candler_evaluator/__init__.py index 1a353eae..e228def2 100644 --- a/python/candler-evaluator/src/candler_evaluator/__init__.py +++ b/python/candler-evaluator/src/candler_evaluator/__init__.py @@ -5,13 +5,14 @@ from .frames import FrameWriter from .loop import main, serve from .plugin import Outcome, Plugin, ServedFile -from .trace import read_trace +from .trace import TraceOrderError, read_trace __all__ = [ "FrameWriter", "Outcome", "Plugin", "ServedFile", + "TraceOrderError", "__version__", "main", "read_trace", diff --git a/python/candler-evaluator/src/candler_evaluator/trace.py b/python/candler-evaluator/src/candler_evaluator/trace.py index b1edb0af..382ee79d 100644 --- a/python/candler-evaluator/src/candler_evaluator/trace.py +++ b/python/candler-evaluator/src/candler_evaluator/trace.py @@ -8,7 +8,18 @@ from .plugin import ServedFile -__all__ = ["read_trace"] +__all__ = ["TraceOrderError", "read_trace"] + + +class TraceOrderError(ValueError): + """A trace file whose lines are not in the order Candler's reader accepts. + + `refusal_code` is the code of the refusal, a row of `[helper]` in `docs/contract/codes.toml`. + """ + + def __init__(self, message: str, *, refusal_code: str) -> None: + super().__init__(message) + self.refusal_code = refusal_code def read_trace(trace: ServedFile | Path | str) -> Iterator[Any]: @@ -20,14 +31,45 @@ def read_trace(trace: ServedFile | Path | str) -> Iterator[Any]: raises `pydantic.ValidationError` when the iterator reaches it; the records before it have been yielded. - It checks lines, not the file's order: an empty file, a missing or second header, a - `seq` gap, an event for an undeclared session and a `raw_ref` to a stream the header - does not list all pass. Candler checks the order when it writes the trace, and the - served copy is pinned by its sha256. + It refuses the file's order as Candler's reader does, with a `TraceOrderError`, a `ValueError`, naming the line: + an empty file, a record before the header, a second header, a session after an event and + a session declared twice. It does not check the rules that relate records: a `seq` gap, an + event for an undeclared session, a child before its parent and a `raw_ref` to a stream the + header does not list all pass. """ from ._models.normalised_trace import TraceRecord path = trace.abs if isinstance(trace, ServedFile) else Path(trace) + header_seen = False + event_seen = False + sessions: set[str] = set() with path.open(encoding="utf-8") as lines: - for line in lines: - yield TraceRecord.model_validate_json(line, strict=True).root + number = 0 + for number, line in enumerate(lines, start=1): + record = TraceRecord.model_validate_json(line, strict=True).root + problem = None + if record.kind == "header": + if header_seen: + problem = "a second header" + header_seen = True + elif not header_seen: + problem = f"{record.kind} before the header" + elif record.kind == "event": + event_seen = True + elif event_seen: + problem = f"session {record.id.root} after an event" + elif record.id.root in sessions: + problem = f"session {record.id.root} declared twice" + else: + sessions.add(record.id.root) + if problem: + raise TraceOrderError( + f"line {number}: {problem}", + refusal_code="helper.trace_out_of_order", + ) + yield record + if number == 0: + raise TraceOrderError( + "an empty trace file has no header", + refusal_code="helper.trace_out_of_order", + ) diff --git a/python/candler-evaluator/tests/test_guard_codes.py b/python/candler-evaluator/tests/test_guard_codes.py index bb8799dc..82b42ea8 100644 --- a/python/candler-evaluator/tests/test_guard_codes.py +++ b/python/candler-evaluator/tests/test_guard_codes.py @@ -22,6 +22,7 @@ "Refused", "PluginError", "_ParamsError", + "TraceOrderError", } ) diff --git a/python/candler-evaluator/tests/test_guard_context.py b/python/candler-evaluator/tests/test_guard_context.py index 8bdc7f89..052d7ba7 100644 --- a/python/candler-evaluator/tests/test_guard_context.py +++ b/python/candler-evaluator/tests/test_guard_context.py @@ -218,6 +218,38 @@ def test_the_reader_refuses_a_line_with_an_unknown_field(tmp_path): list(read_trace(path)) +def test_the_reader_refuses_a_file_out_of_order(tmp_path): + """Guards: the reader refuses the order of lines that Candler's `TraceFile::read` refuses. + + Oracle: the rules of `TraceFile::read` in `crates/candler-schemas/src/trace.rs`, applied by + hand to the lines written here: an empty file, a record before the header, a second + header, a session after an event and a session declared twice each name the line. + Bite: the reader checks each line alone; every case below is read to its end. + """ + from candler_evaluator import TraceOrderError, read_trace + + cases = { + "an empty trace file": [], + "line 1: session before the header": [SESSION, HEADER], + "line 1: event before the header": [CALL, HEADER, SESSION], + "line 2: a second header": [HEADER, HEADER, SESSION], + "line 4: session s2 after an event": [ + HEADER, + SESSION, + CALL, + {**SESSION, "id": "s2"}, + ], + "line 3: session s1 declared twice": [HEADER, SESSION, SESSION], + } + for message, records in cases.items(): + path = write_trace(tmp_path, records) + with pytest.raises(TraceOrderError, match=message) as refused: + list(read_trace(path)) + assert refused.value.refusal_code == "helper.trace_out_of_order" + ordered = write_trace(tmp_path, [HEADER, SESSION, {**SESSION, "id": "s2"}, CALL]) + assert len(list(read_trace(ordered))) == 4 + + DESCRIBE_PLUGIN = """ NAME = "demo" VERSION = "0.1.0" From 553a306b85388cb70ff4e565bcffb8686eabed3d Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 21:03:19 +0900 Subject: [PATCH 87/93] reports(evaluation): report the review fixes leaf Co-Authored-By: Claude Opus 5.5 --- .../run-context/leaves/review_fixes_v0.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 __reports__/run-context/leaves/review_fixes_v0.md diff --git a/__reports__/run-context/leaves/review_fixes_v0.md b/__reports__/run-context/leaves/review_fixes_v0.md new file mode 100644 index 00000000..97af9204 --- /dev/null +++ b/__reports__/run-context/leaves/review_fixes_v0.md @@ -0,0 +1,35 @@ +# Leaf report: review fixes (rows 2, 3, 4, 6, 7) + +Branch `leaf/run-context/review_fixes`, from `feat/run-context`. + +| Row | Result | Commit | +|---|---|---| +| 2 | Changed | `fix(evaluation): read a run's raw/ once in the store and refuse strays` | +| 3 | Changed, guarded | same commit | +| 4 | Changed, guarded | `fix(evaluator-helper): refuse a trace out of order like Candler's reader` | +| 6 | Changed (no defect found) | `refactor(evaluation): build a served copy's context entry in one place` | +| 7 | Changed | `refactor(adapter-opencode): spell the export reader's version once` | + +## #2 One spelling of the stored names +`store/layout.rs` now holds `MANIFEST_FILE`, `TRACE_FILE`, `RAW_DIR`, `RAW_SUFFIX`, `raw_file_name` and `stream_of_raw_file`; `StoreLayout::{manifest, trace, raw_dir, raw}` use them. `context/assemble.rs` takes its workspace names from them, the frame writer (`frames/mod.rs`) builds `.jsonl.gz` with `raw_file_name`, and the runner's `stream_of` (`runner/exec/mod.rs`) calls `stream_of_raw_file`. The workspace names deliberately equal the store names, so an evaluator finds each file where a run directory holds it; a doc comment on `stored_file` says so. `import/` and `jobs/orchestrate/controls.rs` still spell `manifest.json` for their own purposes (an import file name and a path join); not in scope of the row. + +## #3 `raw/` has one reader, and it refuses +No store reader of `raw/` names existed (`run.rs` only writes). New `Store::raw_streams` is the one reader: it lists the visible entries of `raw/` and returns `StoreError::Parse` for an entry that is not `.jsonl.gz` with a valid stream name. `assemble` calls it, so the refusal reaches the caller as `ContextError::Store`, code `candler.internal` (an existing code: "A stored file is not a valid record"; files of the store are Candler's own). No new code. A missing `raw/` still gives no streams, so `PartMissing` is unchanged. +Not covered: hidden entries (a leading `.`, as the writer's `.tmp-` siblings) and `*.partial` names are skipped by the store's existing `visible_names` rule; a stray with such a name is not refused. + +Guard: `a_stray_entry_in_raw_refuses_the_context` (`tests/it/guard_run_context.rs`). Oracle: hand-written entry names (`notes.txt`, `agent_stream.jsonl`, `Bad Name.jsonl.gz`) and the code `candler.internal`, written into a mini-corpus import's `raw/`; the clean run assembles first. Bite: with `raw_streams` skipping instead of refusing (`filter_map`), it failed at `a stray entry is refused: Assembled { ... }` (`expect_err` on an `Ok`). Seen red, then green. + +## #4 `read_trace` order +Rules matched from `TraceFile::read`: empty file; a session or event before the header; a second header; a session after an event; a duplicate session. Not added: the rules of `TraceFile::new` that relate records (`seq` gaps, undeclared session, child before parent, `raw_ref` stream not listed); Rust has them, but the task named five and the helper's existing fixtures hold a `seq` 1 event with no `seq` 0. The docstring, README, CHANGELOG and the page note say these still pass. +The helper requires a code on every raise (`test_d4_*`), so a new class `TraceOrderError(ValueError)` (exported) carries the new code `helper.trace_out_of_order` (side `plugin`); no existing `[helper]` code fits. Row added to `codes.toml`, page regenerated with the bless command. The page note was reworded to "`read_trace` refuses a trace out of order and `null` on an optional field." (page stays within 120 words). CHANGELOG entry in Unreleased updated; version not bumped. + +Guard: `test_the_reader_refuses_a_file_out_of_order` (`tests/test_guard_context.py`). Oracle: the rules of `TraceFile::read` applied by hand to lines written here; each case's message names the line (`line 2: a second header`, `line 4: session s2 after an event`, `line 3: session s1 declared twice`, `line 1: session before the header`, `line 1: event before the header`, `an empty trace file`) and the code. Bite: with the checks disabled it failed `DID NOT RAISE TraceOrderError` (first case, the empty file). Seen red, then green. + +## #6 `materialise` +The three repeated `ContextArtifact::new(.., text_of(©)?, digest)` arms now call one `artifact_of(path, copy, digest)`; call sites read one line each. The `Input` arm drops the digest by design, not by defect: every assembled file, input files included, goes through `copy_stored`, which hashes the copy against `file.sha256` and refuses with `CorruptBlob`; the wire for an input carries the directory of its tree and the digest of its list, no per-file digest. A comment on the arm says so. No fix needed, so no new guard (`a_corrupt_blob_is_refused_and_not_digested` and the inputs guards already own it). The `Served` tag stays mirrored; reducing it did not fall out of the change. + +## #7 OpenCode reader version +A private macro `export_reader!(0, 2, 0)` in `candler-harness-opencode/src/lib.rs` defines `EXPORT_READER` (`"opencode-export@0.2.0"`) and `EXPORT_READER_VERSION` from one spelling. Values written to stores are unchanged (the OpenCode suite passes). Claude Code crate untouched. `LIVE_READER` is left as it was (not in the task). + +## Checks +See the final message of the leaf; the full run is on the branch tip. From 1379b91078a46be2c1290a4e991b8dfb9f186455 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 21:09:36 +0900 Subject: [PATCH 88/93] reports(evaluation): close the adversarial review Co-Authored-By: Claude Opus 5.5 --- .../run-context/03-review_adversarial_v0.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/__reports__/run-context/03-review_adversarial_v0.md b/__reports__/run-context/03-review_adversarial_v0.md index 955bb4c7..48d0e8fb 100644 --- a/__reports__/run-context/03-review_adversarial_v0.md +++ b/__reports__/run-context/03-review_adversarial_v0.md @@ -109,3 +109,21 @@ Every file below was read in the diff unless marked. "Skim" means the diff was r | `python/candler-evaluator/uv.lock` | skipped: lock file | Not read: the Rust workspace beyond the diff, apart from `store/layout.rs`, `store/run.rs`, `runner/exec/mod.rs`, `import/assemble.rs` and `import/raw.rs` for the trace and raw-stream rules. + +## Rulings + +Each finding was ruled after the review, and each fix landed on its own leaf with a guard seen red under a named bite. Evidence for each is in the leaf report it names. + +| # | Ruling | Where it landed | +|---|---|---| +| 1 | Confirmed by a probe on real Claude Code 2.1.311: `grep` with no match, `diff` on files that differ and `test -f /missing` each give `is_error: false` with a `returnCodeInterpretation` key that a true exit 0 lacks, and no field carries the code. The reader now gives no exit for such a result. OpenCode states `metadata.exit: 1` for all three, and its reader was already right. Reader `claude-code-stream-json@0.4.0` | `leaves/cc_exit_semantics_v0.md`; merge `b78ed3de` | +| 2 | Fixed: `store/layout.rs` holds the trace, manifest and raw names, and `assemble`, the frame writer and the runner's `stream_of` take them from there | `leaves/review_fixes_v0.md`; merge `a612ca48` | +| 3 | Fixed: `Store::raw_streams` is the one reader of `raw/` and refuses an entry that is not a stream it writes (`candler.internal`). Hidden and `*.partial` names are still skipped by the store's `visible_names` rule | same | +| 4 | Fixed for the order rules of `TraceFile::read` (`helper.trace_out_of_order`). The relational rules (`seq` gaps, undeclared session, `raw_ref` stream) still pass in the helper, and its docstring, README and contract page say so | same | +| 5 | Accepted as written. The call's tool is known only once the result is joined to its call in `Registry::emit`, which is where the gate sits; the doc on `exit_of` says so | — | +| 6 | Fixed in part: one `artifact_of` builds a served entry. The `Input` arm drops a digest by design, because the wire carries no per-file digest for inputs; a comment says so. The `Served` tag stays mirrored | `leaves/review_fixes_v0.md` | +| 7 | Fixed: each reader's version is spelled once, from a macro in its crate | `leaves/cc_exit_semantics_v0.md`, `leaves/review_fixes_v0.md` | +| 8 | Fixed: the fake model's `g1` script takes two or more commands, and `tests/fixtures/README.md` says how to record a stream again from the repository | `leaves/cc_exit_semantics_v0.md` | +| 9 | Accepted: one copy routine with its digest check is the design, and raw streams are served only to a kind that declares `raw` | — | + +Carried as follow-ups: hidden and `*.partial` entries in `raw/` (finding 3), and the helper's relational trace rules (finding 4). From 05568c23911bb637608764ae9e6661c0960c74c0 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 21:18:07 +0900 Subject: [PATCH 89/93] test(evaluation): record the served rows over the 0.4.0 reader The Claude Code reader is claude-code-stream-json@0.4.0, so the trace the import writes for run-6 and run-12 changed bytes and hash. The [[served]] rows record each new hash, taken from the store, and gen_live_context.py recomputes their projection and digest; --check agrees. Raw streams and the manifest are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../tests/oracle/vectors/live_context_runs.toml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/candler-core/tests/oracle/vectors/live_context_runs.toml b/crates/candler-core/tests/oracle/vectors/live_context_runs.toml index c92965ee..66e5dd61 100644 --- a/crates/candler-core/tests/oracle/vectors/live_context_runs.toml +++ b/crates/candler-core/tests/oracle/vectors/live_context_runs.toml @@ -47,19 +47,19 @@ digest = "sha256:c09cf0ea32d68a6f13fa8418a7d26844212dbe6e514c8a486829cab7af5d5fb cell = "20260806-035940_v0.2.3_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-v0.2.3" run = "with_skill/run-6" needs = ["trace", "raw", "manifest"] -trace_sha256 = "sha256:4bea247947ddbb6e6d20e765391518318839ffb17aa70948d3efef638f48f3cf" +trace_sha256 = "sha256:72f4d34f3729aa987a5dc7b1bbc3120c4a3e9fa1d7d44783aeaf3d371e484c5c" manifest_sha256 = "sha256:0b63023ac489f555b8b43a45e67e88614cdf047d2b9f24613ddffddee0ce9bfd" raw = [{ stream = "stderr", sha256 = "sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e" }, { stream = "stdout", sha256 = "sha256:20d43143e335ec527bdbb3943aea771523bac466a366f5bc1efb114d9df676c8" }] -projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:9e79641026c088d5977727a252eccb44aa5a440399011f497b5504e82ce33e0b\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:67bc1eac7242670159d22fcfa503416b4f0874a405c206eb4c6a0d1126130b61\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:57d084dc0f9ea0b8a555d66fba8a0fc441a14675442af09964a2f1f9ef710d28\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:4bea247947ddbb6e6d20e765391518318839ffb17aa70948d3efef638f48f3cf\",\"raw\":[{\"stream\":\"stderr\",\"sha256\":\"sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e\"},{\"stream\":\"stdout\",\"sha256\":\"sha256:20d43143e335ec527bdbb3943aea771523bac466a366f5bc1efb114d9df676c8\"}],\"manifest\":\"sha256:0b63023ac489f555b8b43a45e67e88614cdf047d2b9f24613ddffddee0ce9bfd\"}" -digest = "sha256:73bf83e64b86ce32bf796088bd5468555f5f97f3e6354d63d50c9f060f59d633" +projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:9e79641026c088d5977727a252eccb44aa5a440399011f497b5504e82ce33e0b\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:67bc1eac7242670159d22fcfa503416b4f0874a405c206eb4c6a0d1126130b61\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:57d084dc0f9ea0b8a555d66fba8a0fc441a14675442af09964a2f1f9ef710d28\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:72f4d34f3729aa987a5dc7b1bbc3120c4a3e9fa1d7d44783aeaf3d371e484c5c\",\"raw\":[{\"stream\":\"stderr\",\"sha256\":\"sha256:cf28394a5300622c08a3a120f65ee05dacad9238ba077220f7a8805b39d3842e\"},{\"stream\":\"stdout\",\"sha256\":\"sha256:20d43143e335ec527bdbb3943aea771523bac466a366f5bc1efb114d9df676c8\"}],\"manifest\":\"sha256:0b63023ac489f555b8b43a45e67e88614cdf047d2b9f24613ddffddee0ce9bfd\"}" +digest = "sha256:42362a82bf28ceb109c09b480ff8b2b031ede002f3e22262ac362c0287d5193c" [[served]] cell = "20260806-035940_v0.2.6_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-0.2.6" run = "with_skill/run-12" needs = ["trace"] -trace_sha256 = "sha256:777957636c8501eff59d51d7f02434587a857f0ef653e2569512503a159a60c5" -projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:d1238cde58dc83c8a22ec512974681b3c4f30c7eeeab977d5e3096058f318552\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:12b3cddb89db9df478e0f38a2b5ae531ddb968d330c3d8b71295b101795cb83f\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:588434f85cfb10eca786c798729a2a1a315c61caa1a26d8ff0504a5a39918fd4\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:777957636c8501eff59d51d7f02434587a857f0ef653e2569512503a159a60c5\"}" -digest = "sha256:44bf7ee9348d08418f380edf7cb6fa82e7da6278fcc114c1882df642414c9f44" +trace_sha256 = "sha256:e9e82bdb6b4661ba8e6035d4281d2b4927f902107c273e18148db5326b71b06f" +projection = "{\"artifacts\":[{\"path\":\"cont-train.json\",\"sha256\":\"sha256:d1238cde58dc83c8a22ec512974681b3c4f30c7eeeab977d5e3096058f318552\"},{\"path\":\"domain.py\",\"sha256\":\"sha256:12b3cddb89db9df478e0f38a2b5ae531ddb968d330c3d8b71295b101795cb83f\"},{\"path\":\"problems.py\",\"sha256\":\"sha256:588434f85cfb10eca786c798729a2a1a315c61caa1a26d8ff0504a5a39918fd4\"}],\"snapshots\":[],\"inputs\":[],\"metadata\":{\"plan.prompt_domain_name\":\"cont-train\"},\"trace\":\"sha256:e9e82bdb6b4661ba8e6035d4281d2b4927f902107c273e18148db5326b71b06f\"}" +digest = "sha256:aa546fbdee822397c6cbe0a85745aabb955923c2f51c76acd781c51612ad7932" [[served]] cell = "20260806-035940_v0.2.3_claude-haiku-4-5_model-claude-haiku-4-5_skill_version-htn-creator-v0.2.3" From b4194a1076809122ec9aefb54e7d24ab23c6d234 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 22:03:55 +0900 Subject: [PATCH 90/93] reports(evaluation): record the ruling on unknown Needs keys Co-Authored-By: Claude Opus 5.5 --- __reports__/run-context/02-seam_review_v0.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/__reports__/run-context/02-seam_review_v0.md b/__reports__/run-context/02-seam_review_v0.md index 8b1701ce..498e61f0 100644 --- a/__reports__/run-context/02-seam_review_v0.md +++ b/__reports__/run-context/02-seam_review_v0.md @@ -47,7 +47,7 @@ The plan v0 (`00-plan_run_context_v0.md`, §Settled and §What a kind can see) a | 4 | "Never served empty": every run stores `trace.jsonl`. A failed reader or a silent session leaves a header-only trace (`runner/exec/mod.rs:762`), which is served. `PartMissing` covers only runs that do not store the part | Fix the wording to "a part the run does not store"; the `Needs.trace` doc says a trace can hold a header alone | | 5 | The `ContextArtifact.path` doc says "relative to the run". For an artifact it is relative to the outputs; for the trace and manifest, to the workspace root | Fix the wording, and the `ServedFile` docstring | | 6 | `ContextRaw.path` is absolute while `ServedFile.path` is relative, and no doc says the raw streams are gzip-compressed | State both in the docs; no change to the shape | -| 7 | `Needs` ignores an unknown key in the Rust reader (schemars `deny_unknown_fields` without serde's) | Already open with the maintainer; unchanged here | +| 7 | `Needs` ignores an unknown key in the Rust reader (schemars `deny_unknown_fields` without serde's) | Kept by the maintainer's decision: the Rust reader ignores an unknown key in `Needs` | | 8 | Stale text: `architecture.md:1036` says "hard links or clones"; the `refusal_scope.tsv` note omits the missing-part refusal; the code's text omits the interrupted-run case | Fix the wording. `CorruptBlob` keeps its name, because the code is released | | 9 | `crates/candler-harness-claude-code/tests/fixtures/digests.toml` is read by no code and names reader 0.2.0, and READMEs still describe it as a ratchet | Delete it, and the sentences | | 10 | The OpenCode reader spells `"shell"` three times, where the Claude Code reader has `SHELL_TOOL` | One constant | @@ -59,7 +59,6 @@ The plan v0 (`00-plan_run_context_v0.md`, §Settled and §What a kind can see) a ## Follow-ups - **The batching design for outcome reuse (ruling 3).** A kind's I4 key and its refusal depend on its sibling entries in a request. This is for the maintainer. -- **`Needs` unknown keys (ruling 7).** Open with the maintainer. - **Python `ExitStatus.code` is unbounded, while Rust's is `i32`.** - Carried from the leaves: - the OpenCode signal name mapping; From cac082b99393476ae117e59e5077d2730c84d5a3 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 22:09:59 +0900 Subject: [PATCH 91/93] reports(evaluation): note that batching couples reuse and refusal Co-Authored-By: Claude Opus 5.5 --- .../04-notice_batching_needs_v0.md | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 __reports__/run-context/04-notice_batching_needs_v0.md diff --git a/__reports__/run-context/04-notice_batching_needs_v0.md b/__reports__/run-context/04-notice_batching_needs_v0.md new file mode 100644 index 00000000..a9e87590 --- /dev/null +++ b/__reports__/run-context/04-notice_batching_needs_v0.md @@ -0,0 +1,49 @@ +# A kind's reuse key and refusal follow its batch — Notice (v0) + +Date: 2026-11-25 + +--- +type: notice +title: Make a kind's reuse key and refusal follow its own needs +tag: gap +effort: M +reversibility: engine-internal; no wire change in either idea +evidence: verified +spotted-during: the seam review after level 2 of the run context campaign (ruling 3 of `02-seam_review_v0.md`) +date: 2026-11-25 +status: open +--- + +## TL;DR +- A kind's outcome reuse key and its refusal depend on the other kinds sent with it. +- Serving trace, raw streams and manifest makes the coupling costly; artifact globs already had it. +- Either idea changes how the engine batches or keys requests, and its guards. + +## Context +The engine builds one context per request, and a request holds every applicable entry of one evaluator at one stage (`Batch`, `crates/candler-core/src/evaluation/engine/plan.rs`; `send`, `engine/run.rs`). The context is the union of those entries' needs, and its digest is part of each outcome's `I4Key` (`evaluation/selection/select.rs`). `docs/contract/evaluator-protocol.md` states this behaviour in a note; nothing changes it. + +Two effects, with a plug-in that has `domain_valid` (needs one artifact) and `shell_discipline` (needs the trace): + +| Effect | Example | +|---|---| +| Reuse misses | Suite v1 grades `domain_valid` alone, context digest D1. Suite v2 adds `shell_discipline` at the same stage, so the context is artifacts plus trace, digest D2. `domain_valid`'s key changes and it is graded again, though nothing it reads changed. An LLM judge pays again and may give a second, different grade. If `shell_discipline` is not sent because a dependency failed, the digest goes back to D1. | +| Over-refusal | On an imported run with no trace, `shell_discipline` cannot be served, so the whole request is refused with `evaluation.run_part_missing`, `domain_valid` included. | + +## Scope Delta +Two ideas; the choice between them, or neither, is left to whoever implements it. +- **Idea A: split requests by needs.** One request per distinct set of needs within an evaluator's stage. Each kind is served exactly what it declared; its digest covers only that; a missing part refuses only the kinds that need it. Cost: one more plug-in process per extra needs set; kinds with equal needs still share a request. +- **Idea B: digest and refusal per kind, one request.** Keep the union context, but compute each entry's `I4Key` digest over its own kind's declared parts, and refuse only the entries whose kind needs a missing part, sending the rest a reduced context. Cost: per-entry digest and refusal tracking in the engine; each kind still sees parts it did not declare. +- Either way: the note in `evaluator-protocol.md`, the "what a plug-in is served" wording in the docs, and guards that see reuse and refusal from one kind's side. + +## Accept / Decline + +| | Accept | Decline | +|---|---|---| +| **Benefit** | A kind's stored outcome is reused whenever what it reads is unchanged, and an artifacts-only kind is graded on a run that lacks a trace | One request per evaluator and stage keeps process count minimal, and the current behaviour is already documented and guarded | +| **Cost** | An engine change to batching (A) or keying (B), new guards, and digests of contexts that serve several needs sets change | Re-grading cost and possible grade drift when a suite adds a kind with other needs; plug-in authors must split such kinds into separate plug-ins or stages themselves | + +## If Accepted — Next Step +The coordinator assigns it to the milestone that owns evaluation; its planner picks A or B in an architecture report before any leaf. + +## If Declined — Next Step +Keep the note in `evaluator-protocol.md` as the rule, and revisit when a consumer reports a reuse miss or an over-refusal. From 3a937c9f9eaa750487c8ab43364d0a4fb0e1d95f Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Thu, 26 Nov 2026 01:04:44 +0900 Subject: [PATCH 92/93] ci(library): install uv for the graded-trace container guard graded_run_sees_trace builds the evaluator helper with `uv sync`, and the container-e2e runner had no uv, so spawning it failed with NotFound. Install it as ci.yml does, at the same pinned action. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/container-e2e.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/container-e2e.yml b/.github/workflows/container-e2e.yml index 8a97ce6c..06423176 100644 --- a/.github/workflows/container-e2e.yml +++ b/.github/workflows/container-e2e.yml @@ -45,6 +45,10 @@ jobs: uses: taiki-e/install-action@v2 with: tool: cargo-nextest + - name: Install uv, which builds the evaluator helper the graded-trace guard runs + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + enable-cache: true - name: Report the engine run: docker version && docker info --format '{{.Driver}} {{.DriverStatus}}' - name: Run the container guards From 553b9d12d365334e63d8f5475ccebc9128e6067b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Thu, 26 Nov 2026 01:46:58 +0900 Subject: [PATCH 93/93] test(evaluation): give the graded-trace guard's cleanup its docker The merge of main kept main's `start_fake`, which leaves `Made::real` to its caller, as the parity and agent-config guards do. The graded trace guard relied on the old `start_fake` setting it, so its cleanup ran an empty path and panicked with NotFound after both runs had passed. The guard now sets the cleanup's docker path itself. Co-Authored-By: Claude Opus 5.5 --- crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs index 6a9b59b0..27a8a1e8 100644 --- a/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs @@ -128,6 +128,7 @@ fn graded(world: &World) -> Vec { fn graded_run_sees_trace() { let real = real_docker(); let mut made = Made::default(); + made.real.clone_from(&real); // BORROW: the cleanup owns its client path let script = json!([WRITE, EXIT]).to_string(); let fake = start_fake( &real,