diff --git a/.github/workflows/container-e2e.yml b/.github/workflows/container-e2e.yml index 2519272f..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 @@ -72,6 +76,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/__design__/architecture.md b/__design__/architecture.md index 9883341a..584b24a3 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -1042,15 +1042,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, 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[] (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 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` -sits beside `problems.py`); `trace` (normalised trace file); `raw[]`; `artifacts[] {path -(run-relative), abs, sha256}`; `snapshots[] {kind, path, digest}`; `inputs[] {kind, path, digest}` +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 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 @@ -1065,8 +1070,12 @@ 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. 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. @@ -1252,7 +1261,7 @@ never compares an inventory with one of another source. The census names no serv ended_at?, ended_by, parent_session?, raw_ref}`; `Event {seq, at?, kind, span?, raw_ref, ext}` with kinds `context_start` (`system`, `first_message`: the run's first model request that carries tools, as the gateway received it; the root session's first event), `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. 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..7d394f33 --- /dev/null +++ b/__reports__/run-context/00-plan_run_context_v0.md @@ -0,0 +1,303 @@ +# 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. 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 + +- 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. 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..6df9cf7f --- /dev/null +++ b/__reports__/run-context/01-ruling_trace_served_v0.md @@ -0,0 +1,35 @@ +# 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. 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 + +- **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 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 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. 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..498e61f0 --- /dev/null +++ b/__reports__/run-context/02-seam_review_v0.md @@ -0,0 +1,67 @@ +# 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) | 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 | +| 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. +- **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. 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..48d0e8fb --- /dev/null +++ b/__reports__/run-context/03-review_adversarial_v0.md @@ -0,0 +1,129 @@ +# 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. + +## 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). 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. 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. 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..a108bd68 --- /dev/null +++ b/__reports__/run-context/leaves/cc_reader_exit_v0.md @@ -0,0 +1,116 @@ +# 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. + +## 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. 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..70893551 --- /dev/null +++ b/__reports__/run-context/leaves/graded_run_sees_trace_v0.md @@ -0,0 +1,63 @@ +# 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`); 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 + +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 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 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 + +The `container-e2e` PASS line, and the coordinator's verifier. Nothing else. 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..32c9bf9b --- /dev/null +++ b/__reports__/run-context/leaves/helper_context_v0.md @@ -0,0 +1,77 @@ +# 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 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`) + +| 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. + +## 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 + +- 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. 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..c1a106fa --- /dev/null +++ b/__reports__/run-context/leaves/oc_reader_exit_v0.md @@ -0,0 +1,97 @@ +# 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 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 + +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). 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/__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. 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..79577ba8 --- /dev/null +++ b/__reports__/run-context/leaves/schema_exit_needs_v0.md @@ -0,0 +1,66 @@ +# Leaf report: schema_exit_needs (v0) + +Branch `leaf/run-context/schema_exit_needs`, cut from `feat/run-context` at `abdf7c22`. + +## Spec defects, first + +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` 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) | + +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 | +| `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 + +`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. + +## 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`. 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..8cb526de --- /dev/null +++ b/__reports__/run-context/leaves/serve_context_v0.md @@ -0,0 +1,70 @@ +# 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 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 + +`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. 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". | diff --git a/__roadmap__/m3-lean-cli/refusal_scope.tsv b/__roadmap__/m3-lean-cli/refusal_scope.tsv index 1945dff6..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 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, 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 diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/meet_run_context.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/meet_run_context.md index 677052c4..497342ad 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/meet_run_context.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/meet_run_context.md @@ -7,10 +7,10 @@ - [ ] `[nl]` `adversarial_review.md` is `done`, or runs beside this leaf on the same tip **Success Gates**: - ✅ Recorded 2026-11-25: `git fetch origin`, then `feat/run-context` is not on `origin/main` (it has no remote branch, and `HEAD..origin/main` is empty), so M6.5 lands first. Every gate below is owed by M6d. -- ⬜ (owed by M6d) `feat/m6.5-agent-config` takes in `origin/main` by a merge. History is not rewritten, so the milestone branch is not rebased; that matches the leads' agreement in substance. Generated files are regenerated, not merged by hand: `KnownKind` in `crates/candler-schemas/src/trace.rs` holds both `ContextStart` and M6d's typed `tool_result.exit`. The normalised-trace schema and the trace contract page come from `CANDLER_BLESS_SCHEMAS=1 … drift` and `CANDLER_BLESS_CONTRACT=1 … contract_pages`, and both pass unblessed afterwards. -- ⬜ (owed by M6d) No version is bumped by hand. `git diff origin/main..HEAD` shows no change to any crate's `version` or to a CHANGELOG. The `feat(schemas)` commits alone set the release's single minor bump. -- ⬜ (owed by M6d) The merge commit, or a commit made with it, adds the sentence next to `needs.trace` in the evaluator-facing docs. It says that declaring `needs.trace` hands the evaluator kind the run's system text and first message verbatim (`context_start`), which may be the treatment under test. -- ⬜ (owed by M6d) `cargo nextest run --workspace` passes on the merged tip, and `docker ps -a` shows none of the leaf's containers. +- ✅ (met by M6d, 2026-11-26: `feat/run-context` took in `origin/main` at `769ebd4d` by a merge; `KnownKind` holds `ContextStart` and `tool_result.exit`; the schemas and `trace-file.md` were blessed, and `drift` and `contract_pages` pass unblessed) `feat/m6.5-agent-config` takes in `origin/main` by a merge. History is not rewritten, so the milestone branch is not rebased; that matches the leads' agreement in substance. Generated files are regenerated, not merged by hand: `KnownKind` in `crates/candler-schemas/src/trace.rs` holds both `ContextStart` and M6d's typed `tool_result.exit`. The normalised-trace schema and the trace contract page come from `CANDLER_BLESS_SCHEMAS=1 … drift` and `CANDLER_BLESS_CONTRACT=1 … contract_pages`, and both pass unblessed afterwards. +- ✅ (met by M6d: no crate `version` or CHANGELOG differs from `origin/main`; the helper's `pyproject.toml` is at 0.2.0 by hand, as CONTRIBUTING's helper line requires) No version is bumped by hand. `git diff origin/main..HEAD` shows no change to any crate's `version` or to a CHANGELOG. The `feat(schemas)` commits alone set the release's single minor bump. +- ✅ (met by M6d: the `Needs.trace` doc, hence the evaluator schemas, and the helper README; the protocol page's Notes are at their 120-word cap) The merge commit, or a commit made with it, adds the sentence next to `needs.trace` in the evaluator-facing docs. It says that declaring `needs.trace` hands the evaluator kind the run's system text and first message verbatim (`context_start`), which may be the treatment under test. +- ✅ (met by M6d: 772 passed, 38 skipped; clippy `-D warnings`, fmt and rustdoc `-D warnings` pass; no `candler.test` container left) `cargo nextest run --workspace` passes on the merged tip, and `docker ps -a` shows none of the leaf's containers. **References**: `crates/candler-schemas/src/trace.rs` (`KnownKind`); `docs/contract/trace-file.md`; M6d's `needs.trace` doc on `origin/main`; the leaf [trace_context.md](../../../trace_context.md), which added `context_start` ## Step 1: Merge and regenerate diff --git a/__roadmap__/run_context/README.md b/__roadmap__/run_context/README.md new file mode 100644 index 00000000..6f1d5fb3 --- /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) 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}`. + +## 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 +- [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 +- ⬜ `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]:::done + probe_shell_shapes[Probe: shell shapes]:::done + readers[Readers and serving]:::inprogress + 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 | ✅ Done | +| `probe_shell_shapes.md` | 📄 Leaf Task | ✅ Done | +| `readers/` | 📁 Directory | 🔄 In Progress | + +## 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..44ca8d12 --- /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(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. +**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(trace-model): 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..3a8ec19a --- /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]:::done + oc_reader_exit[OpenCode exit]:::done + serve_context[Serve the run]:::done + helper_context[Helper context]:::done + 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 | ✅ Done | +| `oc_reader_exit.md` | 📄 Leaf Task | ✅ Done | +| `serve_context.md` | 📄 Leaf Task | ✅ Done | +| `helper_context.md` | 📄 Leaf Task | ✅ Done | +| `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..4ec8c80e --- /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 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 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. 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`; +- `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), `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` + +## 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..caaf005b --- /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]:::done + 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 | ✅ Done | +| `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..b0a0b611 --- /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 = ["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) +- 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..d161196b --- /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]:::inprogress + 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 | 🔄 In Progress | + +## 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..67b4edc6 --- /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/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/`. + +## 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/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` + +## 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 `03-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..94c98603 --- /dev/null +++ b/__roadmap__/run_context/readers/helper_context.md @@ -0,0 +1,44 @@ +# 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 +- ⬜ 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` +**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..93372e8a --- /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 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.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`; +- `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..b180187e --- /dev/null +++ b/__roadmap__/run_context/readers/serve_context.md @@ -0,0 +1,46 @@ +# 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 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 +**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..ab911bc9 --- /dev/null +++ b/__roadmap__/run_context/schema_exit_needs.md @@ -0,0 +1,52 @@ +# 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 +- [ ] `[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 +- ⬜ 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, 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: +- `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` diff --git a/assets/docker/fakemodel/fakemodel.py b/assets/docker/fakemodel/fakemodel.py index fb4b1e8c..5cea329c 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 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). @@ -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 + 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. h1 must run a shell command. A first user prompt is answered with one call to the shell tool (`Bash` for Claude Code, `shell` for OpenCode) that echoes `hook-not-blocked`, so that a hook which blocks the call shows as an error answer and none as that text. Anything else @@ -127,8 +132,43 @@ 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: 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 = [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 state == "prompt": + return [shell_call(0)], "tool_use", "g1-shell-0" + 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" + 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-core/src/evaluation/context/assemble.rs b/crates/candler-core/src/evaluation/context/assemble.rs index 4a64b0ac..61ba0c55 100644 --- a/crates/candler-core/src/evaluation/context/assemble.rs +++ b/crates/candler-core/src/evaluation/context/assemble.rs @@ -1,38 +1,63 @@ //! 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 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}; -/// 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; 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`. + 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 +65,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 +91,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 +114,33 @@ 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 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 +/// 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 here, at assembly, and its copy is checked +/// 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 /// 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 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 { if !needs.snapshots.is_empty() { @@ -130,15 +166,17 @@ pub fn assemble(store: &Store, run: &RunKey, needs: &Needs) -> Result 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_FILE, Served::Trace)?); + } + if needs.raw { + let streams = store.raw_streams(run)?; + if streams.is_empty() { + 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); + let workspace = format!("{RAW_DIR}/{}", raw_file_name(&stream)); + files.push(stored_file(source, &workspace, Served::Raw(stream))?); + } + } + if needs.manifest { + files.push(stored_file( + layout.manifest(run), + MANIFEST_FILE, + Served::Manifest, + )?); } Ok(Assembled { run: run.clone(), // BORROW: the result owns the key store_root: layout.root().to_path_buf(), - artifacts, + files, inputs, metadata, }) } +/// The path `name` below the workspace directory `dir`. +fn below(dir: &str, name: &str) -> 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, at assembly, and its copy +/// 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, + served: Served, +) -> Result { + let sha256 = digest_of_file(&source)?; + Ok(AssembledFile { + source, + workspace: stored_path(workspace)?, + sha256, + executable: false, + served, + }) +} + /// 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 +337,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, }); } - 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..9278ae5c 100644 --- a/crates/candler-core/src/evaluation/context/materialise.rs +++ b/crates/candler-core/src/evaluation/context/materialise.rs @@ -1,14 +1,16 @@ -//! 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, RelPath}; 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,62 +113,81 @@ 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 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<(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 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))?; - // The copy is scratch for one request and is removed after it, so it is never synced. - drop(copy); - let mode = if artifact.executable { + .map_err(io_error("create a served copy", &target))?; + io::copy(&mut source, &mut copy).map_err(io_error("copy a stored file", &target))?; + 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))?; + // 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 != artifact.sha256 { + if written != file.sha256 { return Err(ContextError::CorruptBlob { - path: artifact.path.to_string(), - expected: artifact.sha256.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)) +} + +/// 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() + .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(ContextArtifact::new(artifact.path.clone(), abs, written)) // BORROW: the context owns the path + }) } -/// 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: 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 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,37 +196,33 @@ 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() - .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 artifact in assembled.artifacts() { - builder = builder.artifact(copy_artifact(&outputs, artifact)?); + for file in assembled.files() { + let (copy, digest) = copy_stored(space.root(), file)?; + builder = match &file.served { + // An input's files were copied and checked against the digest of their blob above; + // the context carries the directory of the input's tree and the digest of its list + // (below), and no digest per file. + Served::Input => builder, + 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(artifact_of(&file.workspace, ©, 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 { - 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 56802aae..95537436 100644 --- a/crates/candler-core/src/evaluation/context/mod.rs +++ b/crates/candler-core/src/evaluation/context/mod.rs @@ -1,22 +1,46 @@ -//! 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::fmt; use std::io; use std::path::PathBuf; use candler_schemas::evaluation::EvaluationError; +use candler_schemas::primitives::RunKey; use crate::store::StoreError; mod assemble; 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; + +/// 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)] @@ -53,6 +77,14 @@ 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("run {run} stores no `{part}`")] + PartMissing { + /// 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}")] MissingMetadata { @@ -79,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 artifact path relative to `outputs/`. - 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/context/union.rs b/crates/candler-core/src/evaluation/context/union.rs new file mode 100644 index 00000000..60478907 --- /dev/null +++ b/crates/candler-core/src/evaluation/context/union.rs @@ -0,0 +1,39 @@ +//! 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; + 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 + } + } + 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/src/evaluation/refusal.rs b/crates/candler-core/src/evaluation/refusal.rs index 4a875a9b..dddfc05b 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 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( "evaluation.metadata_missing", Side::Plugin, @@ -172,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( @@ -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/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 0ceb8768..70488a74 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::isolation::{Isolation, IsolationError, RunOutputs}; use crate::jobs::model::JobCause; use crate::jobs::slots::Slot; use crate::store::blob::digest_of_file; +use crate::store::layout::stream_of_raw_file; use crate::store::run::{Existing, RunWriter}; use crate::store::{Store, StoreError}; use crate::supervise::SuperviseError; @@ -451,8 +452,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/fixtures/harness_baseline/census.json b/crates/candler-core/tests/fixtures/harness_baseline/census.json index bfde840c..0c1e3257 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", @@ -330,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 f2503f4c..6d76da01 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, @@ -182,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-core/tests/it/guard_run_context.rs b/crates/candler-core/tests/it/guard_run_context.rs index 7f82733e..8a1a4f58 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,75 @@ 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"); + 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"); + 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 +383,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,9 +430,21 @@ 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. +/// 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()); @@ -247,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:?}" ); } @@ -375,6 +613,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 +884,70 @@ 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 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()); + 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.to_string().contains(&bare.to_string()), + "`{error}` names the part `{part}` and the run" + ); + } + let workspace = tempfile::tempdir().expect("a workspace"); + let context = context_of( + &store, + &bare, + &needs_declaring(&["manifest"]), + workspace.path(), + ); + 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" + ); +} + +/// 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"); + } +} 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-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_live_context.py b/crates/candler-core/tests/oracle/vectors/gen_live_context.py index 15b5f56d..7448d454 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,30 @@ 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. 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 +import glob import hashlib import importlib.metadata import json import os import sys +import tomllib import rfc8785 @@ -42,6 +58,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 +148,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 +271,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 +280,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/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-core/tests/oracle/vectors/live_context_runs.toml b/crates/candler-core/tests/oracle/vectors/live_context_runs.toml index 9e6ceefc..66e5dd61 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: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: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: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" +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" diff --git a/crates/candler-harness-claude-code/README.md b/crates/candler-harness-claude-code/README.md index c3fa5693..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`. @@ -30,10 +35,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/src/lib.rs b/crates/candler-harness-claude-code/src/lib.rs index ab624a43..25844893 100644 --- a/crates/candler-harness-claude-code/src/lib.rs +++ b/crates/candler-harness-claude-code/src/lib.rs @@ -53,11 +53,20 @@ pub fn supported() -> semver::VersionReq { /// The Claude Code version the base image installs, which [`supported`] accepts. pub const PINNED: semver::Version = semver::Version::new(2, 1, 311); -/// 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"; +/// 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, 2, 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 b6fbd6a4..95035b27 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,7 +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))); + 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 } @@ -337,6 +344,52 @@ fn denial_of(line: &Map, id: &str) -> Option { .map(|kind| Denial::new(DeniedBy::Harness, Some(kind.to_owned()))) } +/// 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, +/// 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)); + 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 if flagged("returnCodeInterpretation") { + None + } else { + 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.is_empty() || !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 @@ -355,9 +408,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 a16ad9de..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,6 +77,8 @@ pub(crate) struct Registry { index: HashMap, /// The session that holds each call, by call id. owner: HashMap, + /// 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. @@ -217,22 +219,35 @@ 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, 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 { .. }) { + // 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 matches!(draft.kind, EventKind::ToolResult { .. }) { + } + } 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)?; diff --git a/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml b/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml index 6c94b790..f5095e6f 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]] @@ -241,6 +241,68 @@ source = "recorded: Claude Code 2.1.311 against assets/docker/fakemodel, see ses 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 = "e9352a677f3bd42c37073c3022808b7e8e4cdf1dfacde7797a2a8a4af4ea09d5" +synthetic = false + +[[files]] +path = "streams/shell_exit_stderr_timeout/usage_totals.toml" +source = "usage_totals.jq" +sha256 = "df78975da8a46ba3ac67f3a6d64767bd0569846e0b65ac690177c79de9e68a0e" +synthetic = false + +# shell_exit_semantics (cc_exit_semantics probe, 2026-11-25): real Claude Code 2.1.311 on the same rig +# as shell_exit_stderr_timeout above (the parity rig of crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs, +# the production gateway sidecar, bypassPermissions, one cell), the same agent image +# (sha256:57f339fc3580d09e8f0c9284d2177449c476f31e8bcd092dcdc631c3b3ea2a48). Docker 29.9.2, +# Docker Desktop on macOS. No token was spent. 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"]: 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 + [[files]] path = "doctor/valid.txt" source = "recorded: `claude doctor /` 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,9 +8,10 @@ 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 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 @@ -24,6 +25,34 @@ python3 make_synthetic.py 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. +## 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/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" 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_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 00000000..a4270822 Binary files /dev/null and b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_semantics/agent_stream.jsonl.gz differ 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 + 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 00000000..43225312 Binary files /dev/null and b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/agent_stream.jsonl.gz differ 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..dfde1bba --- /dev/null +++ b/crates/candler-harness-claude-code/tests/fixtures/streams/shell_exit_stderr_timeout/expected.toml @@ -0,0 +1,37 @@ +# 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" + +# 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/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-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..1910d7eb 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,135 @@ fn stream_with(result: Option<&str>) -> Vec> { lines } +/// 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>> { + 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")?, + text(entry, "tool_use_id")?, + text(entry, "tool")?, + 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| { + if let EventKind::ToolCall { name, .. } = &record.event.kind { + Some(name.as_str()) + } else { + None + } + }) + .collect(); + 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 { + results.push(match exit { + None => None, + Some(ExitStatus::Code { code }) => Some(*code), + Some(other) => return Err(format!("{name}: {id}: unexpected {other:?}").into()), + }); + } + } + if results != [want] { + return Err(format!( + "{name}: exit of the result of {tool} call {id} in {session} is {results:?}, want {want:?}" + ) + .into()); + } + } + Ok(()) +} + +/// 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 = |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 = |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":[{}]}}}}"#, + blocks.join(",") + ) + .into_bytes() + }; + let cut = r#"{"type":"tool_use","id":"I","name":"Bash","input":{"command":"sleep 9"}}"#; + let child = r#""parent_tool_use_id":"A","#; + let mut lines = stream_with(None); + 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},"#, + &[&result("I", "partial")], + )); + lines.push(line("user", "", &[&result("no span", "")])); + 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 +442,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 +555,16 @@ fn expected_facts() -> Res<()> { .clone(); // BORROW: owned end to compare assert_eq!(got, want, "result line {result:?}"); } + let shared = run(&exit_join_stream(), false)?; + 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(()) } diff --git a/crates/candler-harness-opencode/src/export.rs b/crates/candler-harness-opencode/src/export.rs index 26ec5e6d..e6875971 100644 --- a/crates/candler-harness-opencode/src/export.rs +++ b/crates/candler-harness-opencode/src/export.rs @@ -11,15 +11,19 @@ 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, }; use serde_json::{Map, Value}; -use crate::{VALIDATED, session_source}; +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", @@ -27,7 +31,7 @@ const BUILTIN_TOOLS: [&str; 12] = [ "grep", "question", "read", - "shell", + SHELL_TOOL, "skill", "subagent", "webfetch", @@ -181,13 +185,28 @@ 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")) .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; so has one whose `exit` is not an `i32`, dropped as the reader drops + // any other malformed harness field. + let exit = (name == SHELL_TOOL && 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( @@ -206,10 +225,9 @@ 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), + EventKind::tool_result(status == Some("error"), None, exit), time("completed"), ); result.span = span; @@ -318,7 +336,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 83b56ca5..4dbaf4eb 100644 --- a/crates/candler-harness-opencode/src/lib.rs +++ b/crates/candler-harness-opencode/src/lib.rs @@ -31,11 +31,24 @@ 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"; +/// 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($major, $minor, $patch); + }; +} + +export_reader!(0, 2, 0); /// The stream name under which the export is collected. pub const EXPORT_STREAM: &str = "export"; diff --git a/crates/candler-harness-opencode/src/prepare.rs b/crates/candler-harness-opencode/src/prepare.rs index d8ae3bf5..bdab71fc 100644 --- a/crates/candler-harness-opencode/src/prepare.rs +++ b/crates/candler-harness-opencode/src/prepare.rs @@ -23,6 +23,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"; @@ -99,7 +101,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"), diff --git a/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml b/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml index 4452e4e8..ebc8a893 100644 --- a/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml +++ b/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml @@ -187,6 +187,37 @@ 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" + +# 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" + # check/: the output of the config check, `opencode run --standalone --print-logs -m probe/none x # 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/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-harness-opencode/tests/it/guard_opencode_driver.rs b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs index 22c5ff8a..db1acf65 100644 --- a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs +++ b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs @@ -744,13 +744,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")?)?; @@ -762,7 +768,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), @@ -799,6 +805,75 @@ 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); 5] = [ + ( + "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}), + ], + ), + ( + // `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})], + ), + ( + "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() diff --git a/crates/candler-schemas/schema/evaluator-describe-result.schema.json b/crates/candler-schemas/schema/evaluator-describe-result.schema.json index 3c82c676..e11e957a 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 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.", + "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" }, @@ -167,6 +167,11 @@ }, "type": "array" }, + "manifest": { + "default": false, + "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": { "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` 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": { "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` 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. Declaring it hands the kind the run's system text and first message verbatim (`context_start`), 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..3b6d8077 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, 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 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's outputs for an artifact, relative to the run's `root` for the trace and the manifest." }, "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.", + "description": "The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`).", "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 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.", @@ -624,6 +629,10 @@ }, "type": "array" }, + "manifest": { + "$ref": "#/$defs/ContextArtifact", + "description": "The manifest of the run, served when a kind of the request 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 a kind of the request 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 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 2c18715e..35e56fe5 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, 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 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's outputs for an artifact, relative to the run's `root` for the trace and the manifest." }, "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.", + "description": "The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`).", "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 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.", + "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" }, @@ -517,6 +522,11 @@ }, "type": "array" }, + "manifest": { + "default": false, + "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": { "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` 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": { "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` 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. Declaring it hands the kind the run's system text and first message verbatim (`context_start`), 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 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.", @@ -1173,6 +1188,10 @@ }, "type": "array" }, + "manifest": { + "$ref": "#/$defs/ContextArtifact", + "description": "The manifest of the run, served when a kind of the request 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 a kind of the request 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 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 95c070d3..d5b23462 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, 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 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's outputs for an artifact, relative to the run's `root` for the trace and the manifest." }, "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.", + "description": "The absolute path of the stream, valid where the evaluator runs. The file is gzip-compressed JSON lines (`.jsonl.gz`).", "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 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.", @@ -746,6 +751,10 @@ }, "type": "array" }, + "manifest": { + "$ref": "#/$defs/ContextArtifact", + "description": "The manifest of the run, served when a kind of the request 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 a kind of the request 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 a kind of the request 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 4844f8f0..bef4b5e0 100644 --- a/crates/candler-schemas/schema/normalised-trace.schema.json +++ b/crates/candler-schemas/schema/normalised-trace.schema.json @@ -340,8 +340,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": { @@ -426,6 +430,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..0327dcdf 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 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. + /// 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. Declaring it hands the kind the run's system text and first message verbatim (`context_start`), 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` 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` 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; 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 @@ -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)] @@ -1536,8 +1542,10 @@ 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, } 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, 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 artifact 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 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 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 { @@ -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 a kind of the request 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 a kind of the request needs it; absent otherwise. + #[serde(default, deserialize_with = "present")] + manifest: Option, + /// 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, @@ -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 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] @@ -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,10 +1713,14 @@ 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, - /// 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 @@ -1707,10 +1740,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 fn trace<'a>(&'a self) -> Option<&'a str> { - self.trace.as_deref() + 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 const fn manifest<'a>(&'a self) -> Option<&'a ContextArtifact> { + self.manifest.as_ref() } /// The raw streams of the run. @@ -1748,8 +1787,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 +1816,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 +1874,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 +1934,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 86920823..1839ad9a 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. @@ -791,10 +792,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] @@ -876,8 +881,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. @@ -977,7 +990,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( @@ -986,6 +999,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/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..57ee59cb 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,4 @@ 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 | 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/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..4044ac2e 100644 --- a/crates/candler-schemas/tests/it/guard_context_digest.rs +++ b/crates/candler-schemas/tests/it/guard_context_digest.rs @@ -5,17 +5,21 @@ 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; +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"); @@ -47,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)>, @@ -56,15 +58,12 @@ struct Parts { } impl Parts { - /// A context with one of each part. + /// A context with one artifact, snapshot, input and metadata value, and 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(), @@ -106,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| { @@ -133,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 @@ -169,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. @@ -205,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 @@ -316,3 +302,161 @@ 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` 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. +/// 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); + 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 = 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); + read_context(wire).context_digest() + }; + let base = read_context(wire_context(&all)).context_digest(); + 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"); + }), + ("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_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/it/guard_rpc_wire.rs b/crates/candler-schemas/tests/it/guard_rpc_wire.rs index 216b19b7..cb0ecc96 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(), 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:?}"); diff --git a/crates/candler-schemas/tests/it/guard_trace_wire.rs b/crates/candler-schemas/tests/it/guard_trace_wire.rs index b0d4086d..250c0159 100644 --- a/crates/candler-schemas/tests/it/guard_trace_wire.rs +++ b/crates/candler-schemas/tests/it/guard_trace_wire.rs @@ -422,3 +422,44 @@ 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. 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| { + 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 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" + ); + } + + 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"); + } +} 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" 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..6ed183df --- /dev/null +++ b/crates/candler/tests/fixtures/plugins/graded-trace/kinds/graded_trace.py @@ -0,0 +1,56 @@ +"""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 = {} # keyed by (session, span): a span is the harness's id within one session + 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 + key = (record.session.root, span) + if body["kind"] == "tool_call": + origins.append(body["origin"]) + if "argv" in body: + 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"]}) + 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 8c7f67f8..7af60c7a 100644 --- a/crates/candler/tests/it/guard_cli_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e.rs @@ -811,6 +811,10 @@ mod i8_e2e; #[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; + /// Instructions and hooks reach both harnesses, and the harness's own check refuses what it /// cannot read. #[path = "guard_cli_e2e/agent_config_e2e.rs"] diff --git a/crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs index 8460ee01..ada3d623 100644 --- a/crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs @@ -279,7 +279,7 @@ fn guard_agent_config_e2e() { let real = real_docker(); let mut made = Made::default(); made.real.clone_from(&real); // BORROW: the cleanup owns its client path - let model: Fake = start_fake(&real, &mut made, "agentconfig"); + let model: Fake = start_fake(&real, &mut made, "agentconfig", &[]); let text = base(&agent_config()); let mut failures = Vec::new(); @@ -304,7 +304,7 @@ fn guard_agent_config_e2e() { let experiment = text.replace("@HARNESS@", harness); let skip = records(&real, &model.container).lines().count(); let ran = run_job(&experiment, &model.endpoint, &model.ca, &mut made, |_| {}); - jobs.extend(made.job.clone()); // BORROW: the leftover check names every job + jobs.extend(made.jobs.last().cloned()); // BORROW: the leftover check names every job let config = ran.world.root.join("config"); let resolved = resolve(&ran.world, &config); if ![global, START_CC, START_OC, BLOCKED] @@ -455,7 +455,7 @@ fn guard_harness_check_refuses() { let real = real_docker(); let mut made = Made::default(); made.real.clone_from(&real); // BORROW: the cleanup owns its client path - let model: Fake = start_fake(&real, &mut made, "harnesscheck"); + let model: Fake = start_fake(&real, &mut made, "harnesscheck", &[]); let mut failures = Vec::new(); let mut jobs = Vec::new(); @@ -463,7 +463,7 @@ fn guard_harness_check_refuses() { for (label, hooks) in [("invalid", payload.invalid), ("valid", payload.valid)] { let experiment = base(hooks).replace("@HARNESS@", payload.harness); let ran = run_job(&experiment, &model.endpoint, &model.ca, &mut made, |_| {}); - let job = made.job.clone().unwrap_or_default(); // BORROW: the job id names its log + let job = made.jobs.last().cloned().unwrap_or_default(); // BORROW: the job id names its log jobs.push(job.clone()); // BORROW: the leftover check names every job let supervisor = fs::read_to_string(ran.store.join("jobs").join(&job).join("supervisor.log")) 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..27a8a1e8 --- /dev/null +++ b/crates/candler/tests/it/guard_cli_e2e/graded_trace_e2e.rs @@ -0,0 +1,195 @@ +//! 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 = ["outputs/answer.txt"]`, +//! which the context serves as `answer.txt`. +use std::fs; + +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::{self, 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 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 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` +/// 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) // BORROW: .to_owned() makes each command 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 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 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() { + 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 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:?}")); + } + 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 = ["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 `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() { + 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, + &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 skip = records(&real, &fake.container).lines().count(); + for harness in ["claude-code", "opencode"] { + let Sealed { world, run_dir, .. } = seal( + &base.replace("@HARNESS@", harness), + &fake.endpoint, + &fake.ca, + &mut made, + ); + let recorded = records(&real, &fake.container); + let sent = scripted_commands(&recorded, skip); + if sent != [WRITE, EXIT] { + let requests: Vec = recorded + .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: {requests:?}" + )); + } + skip = recorded.lines().count(); + 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}")), + ); + } + // 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 34d3176f..91a54b7e 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. 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"; @@ -71,9 +71,10 @@ pub(super) struct Fake { _dir: tempfile::TempDir, } -/// Builds the fake model's image under a tag of `label`, starts it with the fixture's token, waits -/// until it is ready and copies its CA out. The image and the container go to `made`. -pub(super) fn start_fake(real: &Path, made: &mut Made, label: &str) -> Fake { +/// Builds the fake model's image under a tag of `label`, starts it with the fixture's token and +/// the settings `env` (each `NAME=value`), waits until it is ready and copies its CA out. The image +/// and the container go to `made`. +pub(super) fn start_fake(real: &Path, made: &mut Made, label: &str, env: &[String]) -> Fake { let host = fake_host(real); let publish = format!( "{}::8443", @@ -94,22 +95,16 @@ pub(super) fn start_fake(real: &Path, made: &mut Made, label: &str) -> Fake { real, &["image", "inspect", "--format", "{{.Id}}", &tag], )); - let fake = must( - real, - &[ - "run", - "-d", - "--label", - &tagged, - "-p", - &publish, - "-e", - &format!("FAKE_TOKEN={TOKEN}"), - "-e", - &format!("FAKE_HOST={host}"), - &tag, - ], - ); + let token = format!("FAKE_TOKEN={TOKEN}"); + let named = format!("FAKE_HOST={host}"); + let mut words = vec![ + "run", "-d", "--label", &tagged, "-p", &publish, "-e", &token, "-e", &named, + ]; + for setting in env { + words.extend(["-e", setting.as_str()]); + } + 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"]) .lines() @@ -201,8 +196,8 @@ fn call_origins(text: &str) -> Vec { /// A job the real `candler run` ran to its end: its world and the store its runs are sealed in. pub(super) struct Ran { - pub(super) world: crate::support::cli_run::World, - pub(super) store: std::path::PathBuf, + pub(super) world: World, + pub(super) store: PathBuf, pub(super) log: String, } @@ -214,7 +209,7 @@ pub(super) fn run_job( endpoint: &str, ca: &Path, made: &mut Made, - stage: impl FnOnce(&crate::support::cli_run::World), + stage: impl FnOnce(&World), ) -> Ran { let world = world(); stage(&world); @@ -255,7 +250,7 @@ pub(super) fn run_job( 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), || { @@ -267,16 +262,17 @@ pub(super) fn run_job( Ran { world, store, log } } -/// Runs the experiment `text` once as [`run_job`] does 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 { +/// A run `candler run` sealed in its own world. +pub(super) struct Sealed { + /// 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, +} + +/// Runs the experiment `text` as [`run_job`] does, with the server `parity` staged as its input, +/// and returns its one sealed run. +pub(super) fn seal(text: &str, endpoint: &str, ca: &Path, made: &mut Made) -> Sealed { let Ran { world, store, log } = run_job(text, endpoint, ca, made, |world| { let inputs = world.root.join("inputs").join("servers"); fs::create_dir_all(&inputs).unwrap(); @@ -293,6 +289,20 @@ 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 { 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) @@ -316,6 +326,28 @@ fn run_once( } } +/// 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.*` @@ -335,32 +367,14 @@ fn parity_one_installed_server_one_traced_call() { let before = must(&real, &["ps", "-aq"]); let mut made = Made::default(); made.real.clone_from(&real); // BORROW: the cleanup owns its client path - let model = start_fake(&real, &mut made, "parity"); + let model = start_fake(&real, &mut made, "parity", &[]); let (fake, endpoint, ca) = (&model.container, &model.endpoint, &model.ca); // 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!( 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_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")) 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(); diff --git a/docs/contract/codes.toml b/docs/contract/codes.toml index 88afd29e..521004b8 100644 --- a/docs/contract/codes.toml +++ b/docs/contract/codes.toml @@ -1064,6 +1064,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" @@ -1881,6 +1886,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 698910f9..5ec62506 100644 --- a/docs/contract/evaluator-helper.md +++ b/docs/contract/evaluator-helper.md @@ -2,9 +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. +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 @@ -12,7 +10,7 @@ The author API (a kind's signature, `RunContext`, `KINDS`, `needs` and `params_s Wire tag: none. -Package: `candler-evaluator@0.1.0`. +Package: `candler-evaluator@0.2.0`. @@ -94,6 +92,7 @@ Package: `candler-evaluator@0.1.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 @@ -103,3 +102,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 in the request declares it in `needs`. [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/docs/contract/evaluator-protocol.md b/docs/contract/evaluator-protocol.md index 4c50a792..24063d82 100644 --- a/docs/contract/evaluator-protocol.md +++ b/docs/contract/evaluator-protocol.md @@ -36,7 +36,9 @@ Wire line: `schemas@0.14.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.14.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.14.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.14.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.14.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.14.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.14.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.14.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 | - | @@ -510,3 +538,4 @@ Wire line: `schemas@0.14.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] diff --git a/docs/contract/index.md b/docs/contract/index.md index f0b00ed1..1fa0ad19 100644 --- a/docs/contract/index.md +++ b/docs/contract/index.md @@ -36,7 +36,7 @@ Every row of a Fields table has one class. A `required` followed by a variant in |---|---|---| | core | `v0.17.0` | `Cargo.toml` | | wire schemas | `schemas@0.14.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 @@ -91,7 +91,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 | @@ -103,6 +103,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 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 | diff --git a/docs/contract/trace-file.md b/docs/contract/trace-file.md index cc7723fb..07fe4f76 100644 --- a/docs/contract/trace-file.md +++ b/docs/contract/trace-file.md @@ -78,6 +78,10 @@ Wire line: `schemas@0.14.0`. | `event.kind.denied` | `Denial` | optional | - | | `event.kind.denied.by` | `"harness" \| "hook" \| "user"` | required | - | | `event.kind.denied.reason` | `string` | optional | - | +| `event.kind.exit` | `ExitStatus` | optional | - | +| `event.kind.exit.code` | `integer` | required (event.kind.exit.kind = code) | - | +| `event.kind.exit.kind` | `"code" \| "signal"` | required | - | +| `event.kind.exit.signal` | `integer` | required (event.kind.exit.kind = signal) | - | | `event.kind.is_error` | `boolean` | required (event.kind.kind = tool_result) | - | | `event.kind.cache_creation_tokens` | `integer` | required (event.kind.kind = usage) | - | | `event.kind.cache_read_tokens` | `integer` | required (event.kind.kind = usage) | - | diff --git a/python/candler-evaluator/CHANGELOG.md b/python/candler-evaluator/CHANGELOG.md index df3c3e91..cedac462 100644 --- a/python/candler-evaluator/CHANGELOG.md +++ b/python/candler-evaluator/CHANGELOG.md @@ -6,8 +6,19 @@ 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 those models refuse: not JSON, an unknown + 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. - `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 ea41873e..4d6d6a2f 100644 --- a/python/candler-evaluator/README.md +++ b/python/candler-evaluator/README.md @@ -17,11 +17,23 @@ 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` 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 + 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` 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`. 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. + Declaring `trace` hands the kind the run's system text and first message verbatim + (`context_start`), which may be the treatment under test. - **`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..e844d7de 100644 --- a/python/candler-evaluator/pyproject.toml +++ b/python/candler-evaluator/pyproject.toml @@ -1,11 +1,11 @@ [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" 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 da2511f0..09265c61 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` and `outcome-record.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 @@ -18,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", @@ -29,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", @@ -39,6 +47,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..e228def2 100644 --- a/python/candler-evaluator/src/candler_evaluator/__init__.py +++ b/python/candler-evaluator/src/candler_evaluator/__init__.py @@ -4,9 +4,20 @@ from .frames import FrameWriter from .loop import main, serve -from .plugin import Outcome, Plugin +from .plugin import Outcome, Plugin, ServedFile +from .trace import TraceOrderError, read_trace -__all__ = ["FrameWriter", "Outcome", "Plugin", "__version__", "main", "serve"] +__all__ = [ + "FrameWriter", + "Outcome", + "Plugin", + "ServedFile", + "TraceOrderError", + "__version__", + "main", + "read_trace", + "serve", +] def __getattr__(name: str) -> Any: 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..27469f8b 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: 0e839d32e2e777f818b2f4641e89cb75e4541b0ddc9124592bbb2882b8122829 +# sha256: a4cd3955fe5bb303d7d3dfd9643bf0b48c4248b8afd12ff21686ee913c1b8068 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,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; each starts with `outputs/`. The artifacts are the files the run produced, each served at its path inside `outputs/`." ), ] inputs: Annotated[ list[Name], Field(description="The kinds of input the check reads.") ] + manifest: Annotated[ + bool, + Field( + 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[ list[FieldPath], Field(description="The paths of the metadata fields the check reads."), ] + raw: Annotated[ + bool, + Field( + 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[ 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` 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. Declaring it hands the kind the run's system text and first message verbatim (`context_start`), which may be the treatment under test." + ), ] @@ -217,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 93968be2..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: ecc2ca822aec9e321b7acc64ccca9c5598c7decba42595875d939126dfabaca4 +# 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 @@ -330,13 +330,16 @@ 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'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 artifact's bytes.")] + sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] class ContextRaw(BaseModel): @@ -346,9 +349,10 @@ 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.")] stream: Annotated[StreamName, Field(description="The name of the raw stream.")] @@ -371,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( @@ -391,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]): @@ -473,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( @@ -509,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( @@ -545,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): @@ -569,6 +573,12 @@ class RunContext(BaseModel): inputs: Annotated[ list[ContextRef], Field(description="The inputs the run was made from.") ] + manifest: Annotated[ + ContextArtifact | MISSING, + Field( + description="The manifest of the run, served when a kind of the request needs it; absent otherwise." + ), + ] = MISSING metadata: Annotated[ dict[ Annotated[ @@ -583,7 +593,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 a kind of the request needs them; empty otherwise." + ), + ] root: Annotated[ str, Field( @@ -598,11 +613,11 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - str | None, + ContextArtifact | MISSING, Field( - description="The absolute path of the normalised trace; absent when the run has none." + 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 f7da0485..a2e354e6 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: 068864918640e9ca9e683cb70df83141236e53b60454ee375ba64bc0b340684c +# sha256: d461a2b17c55da101cc78127dede14afe7eb1d2b0493e9875d835f938adbb698 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,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; each starts with `outputs/`. The artifacts are the files the run produced, each served at its path inside `outputs/`." ), ] inputs: Annotated[ list[Name], Field(description="The kinds of input the check reads.") ] + manifest: Annotated[ + bool, + Field( + 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[ list[FieldPath], Field(description="The paths of the metadata fields the check reads."), ] + raw: Annotated[ + bool, + Field( + 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[ 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` 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. Declaring it hands the kind the run's system text and first message verbatim (`context_start`), which may be the treatment under test." + ), ] @@ -280,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.")] @@ -512,13 +527,16 @@ 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'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 artifact's bytes.")] + sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] class ContextRaw(BaseModel): @@ -528,9 +546,10 @@ 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.")] stream: Annotated[StreamName, Field(description="The name of the raw stream.")] @@ -553,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( @@ -573,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]): @@ -678,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( @@ -714,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( @@ -750,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): @@ -785,6 +804,12 @@ class RunContext(BaseModel): inputs: Annotated[ list[ContextRef], Field(description="The inputs the run was made from.") ] + manifest: Annotated[ + ContextArtifact | MISSING, + Field( + description="The manifest of the run, served when a kind of the request needs it; absent otherwise." + ), + ] = MISSING metadata: Annotated[ dict[ Annotated[ @@ -799,7 +824,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 a kind of the request needs them; empty otherwise." + ), + ] root: Annotated[ str, Field( @@ -814,11 +844,11 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - str | None, + ContextArtifact | MISSING, Field( - description="The absolute path of the normalised trace; absent when the run has none." + description="The normalised trace, served when a kind of the request needs it; absent otherwise." ), - ] = None + ] = MISSING class DescribeResult(BaseModel): @@ -850,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 3ae1fbc5..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: 0f621f5ddac76a745cc1a3946d9a7d55b90e638f93f9ec13a7694771f70b3501 +# 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 @@ -369,13 +369,16 @@ 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'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 artifact's bytes.")] + sha256: Annotated[Digest, Field(description="The digest of the file's bytes.")] class ContextRaw(BaseModel): @@ -385,9 +388,10 @@ 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.")] stream: Annotated[StreamName, Field(description="The name of the raw stream.")] @@ -410,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( @@ -430,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]): @@ -512,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( @@ -548,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( @@ -584,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): @@ -608,6 +612,12 @@ class RunContext(BaseModel): inputs: Annotated[ list[ContextRef], Field(description="The inputs the run was made from.") ] + manifest: Annotated[ + ContextArtifact | MISSING, + Field( + description="The manifest of the run, served when a kind of the request needs it; absent otherwise." + ), + ] = MISSING metadata: Annotated[ dict[ Annotated[ @@ -622,7 +632,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 a kind of the request needs them; empty otherwise." + ), + ] root: Annotated[ str, Field( @@ -637,11 +652,11 @@ class RunContext(BaseModel): ), ] trace: Annotated[ - str | None, + ContextArtifact | MISSING, Field( - description="The absolute path of the normalised trace; absent when the run has none." + 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 new file mode 100644 index 00000000..4d772e44 --- /dev/null +++ b/python/candler-evaluator/src/candler_evaluator/_models/normalised_trace.py @@ -0,0 +1,609 @@ +# Generated by scripts/gen_models.py; do not edit. +# schema: crates/candler-schemas/schema/normalised-trace.schema.json +# sha256: 6df9cbbe2d200b2d50e0e38338b855d7e154e1a4d1c92808bfb3c23a929f17ac + +from __future__ import annotations + +from enum import Enum +from typing import Annotated, Any, Literal + +from pydantic import MISSING, 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", + ) + first_message: Annotated[ + str, Field(description="The first user message of the request.") + ] + kind: Literal["context_start"] + system: Annotated[str, Field(description="The system text of the request.")] + + +class EventKind2(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["user_message"] + text: Annotated[ + str | MISSING, Field(description="The text, if the harness records it.") + ] = MISSING + + +class EventKind3(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["assistant_message"] + text: Annotated[ + str | MISSING, Field(description="The text, if the harness records it.") + ] = MISSING + + +class EventKind6(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 | MISSING, + Field( + description="The tool's name at the server, without the harness's prefix. A trace written before the\nfield existed has none." + ), + ] = MISSING + + +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 | MISSING, Field(description="The reason given, if any.")] = ( + MISSING + ) + + +class EndedBy2(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: Literal["agent_error"] + reason: Annotated[ + ReasonCode | MISSING, Field(description="Why the agent failed, when it says.") + ] = MISSING + + +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 EventKind4(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + argv: Annotated[ + 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.")] + wrapped_calls: Annotated[ + list[WrappedCall], + Field( + description="The MCP calls this call bundles; an empty array when it bundles none." + ), + ] + + +class EventKind5(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + denied: Annotated[ + Denial | MISSING, + Field(description="Who refused the call, when it was refused."), + ] = MISSING + exit: Annotated[ + 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." + ), + ] = MISSING + 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 EventKind7(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 | MISSING, + Field( + description="The cost in US dollars, a finite number, if the harness reports it." + ), + ] = MISSING + 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 + | EventKind7 + ] +): + root: Annotated[ + EventKind1 + | EventKind2 + | EventKind3 + | EventKind4 + | EventKind5 + | EventKind6 + | EventKind7, + Field( + description="What happened at one point of a session: an object whose `kind` is `context_start`, `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 | MISSING, + Field( + description="When the session ended, if the harness or the frame times say." + ), + ] = MISSING + 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 | MISSING, + Field( + description="The model the session ran, as the harness names it, if it says." + ), + ] = MISSING + parent_session: Annotated[ + 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." + ), + ] = 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 | MISSING, + Field( + description="When the session started, if the harness or the frame times say." + ), + ] = MISSING + + +class Event(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + at: Annotated[ + Timestamp | MISSING, + Field( + description="When the event happened, if the harness or the frame time says." + ), + ] = MISSING + 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 | MISSING, + Field( + description="The harness's id that pairs a call with its result, if the event has one." + ), + ] = MISSING + + +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/_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 1225bc09..4d492caa 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,33 @@ class Prior: outcome: Mapping[str, Any] +@dataclass(frozen=True) +class ServedFile: + """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 + 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 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 artifacts: tuple[str, ...] @@ -97,7 +122,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 +133,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 +141,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), + 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..382ee79d --- /dev/null +++ b/python/candler-evaluator/src/candler_evaluator/trace.py @@ -0,0 +1,75 @@ +"""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__ = ["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]: + """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 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 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: + 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 105e8dd2..052d7ba7 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,265 @@ 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_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. + + 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 = list(read_trace(path)) + assert [r.kind for r in records] == ["header", "session", "event", "event"] + call, result = records[2].event.kind.root, records[3].event.kind.root + assert call.argv == ["cat", "a.txt"] + assert (call.origin.root.kind, call.origin.root.server, call.origin.root.tool) == ( + "mcp", + "fs", + "read", + ) + assert (result.exit.root.kind, result.exit.root.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)) + + +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" +KINDS = {"k": lambda params, context, prior: {"status": "pass"}} +KIND_SPECS = {"k": {"needs": NEEDS}} +""" + + +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()) + ) + 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 + 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`; 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, 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": 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/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 = { diff --git a/python/candler-evaluator/uv.lock b/python/candler-evaluator/uv.lock index 0cba0958..72db6c8d 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" }, @@ -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 = [