From c5886cf1779151ce344137bbe6bf0f5481041709 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 12:15:38 +0900 Subject: [PATCH 01/69] reports(api): plan agent configuration as data (M6.5) An arm cannot carry its own CLAUDE.md, AGENTS.md or hooks today: the experiment-wide inputs reach every arm, need a file name per harness and cannot touch the settings the driver owns. The architecture report plans instruction text and hooks as cell values, passed like mcp.servers, installed where each harness looks, and checked by the harness's own validator before the agents run; any error or warning refuses the cell. Co-Authored-By: Claude Opus 5.5 --- .../00-architecture_agent_config_v0.md | 245 ++++++++++++++++++ __reports__/agent_config/README.md | 12 + 2 files changed, 257 insertions(+) create mode 100644 __reports__/agent_config/00-architecture_agent_config_v0.md create mode 100644 __reports__/agent_config/README.md diff --git a/__reports__/agent_config/00-architecture_agent_config_v0.md b/__reports__/agent_config/00-architecture_agent_config_v0.md new file mode 100644 index 00000000..acba67ea --- /dev/null +++ b/__reports__/agent_config/00-architecture_agent_config_v0.md @@ -0,0 +1,245 @@ +# Agent configuration as data — Architecture Analysis (v0) + +M6.5 makes instruction files (`CLAUDE.md`, `AGENTS.md`) and hooks per-arm values of an experiment cell. Each driver installs them where its harness looks. Before the agents run, the harness's own check reports on what Candler installed, and any finding refuses the cell. The plan was approved on 2026-11-25. The roadmap is [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md). + +## Executive Summary + +| Question | Answer | +|---|---| +| Cause removed | Instruction files and hooks are not `AgentSetting`s. So no driver answers for them, no page says where they go, no digest covers them, and nothing refuses a cell whose harness drops them. | +| Shape | New cell values: `instructions.text`, `hooks.claude-code` and `hooks.opencode`. They are inline, exactly like `mcp.servers`. | +| Translation | None. The instruction text is the same for both harnesses and goes to each harness's own file. Each harness gets its own hooks payload, installed verbatim. | +| Boundary | Candler guarantees the installation. The harness judges the content. | +| Harness check finds an error or a warning | Refused: `experiment.harness_rejected_input`. | +| Proof | A real-harness end-to-end run against the scripted fake model. No RiVault run is needed. | +| Cost | About $55. Cap $75. | + +**Rulings taken while planning** + +| Choice | Ruling | +|---|---| +| A harness finding | Refuse errors and warnings alike. | +| Where file contents come from | Inline text in the cell. There is no file-reference mechanism. | +| Placement | A new roadmap root, M6.5. Its high-level status is kept in macOS Reminders. | + +## Current State + +Today, an `inputs` entry is the only way to put a file in front of the agent. It fails here in four ways: + +1. It applies to the whole experiment, so every arm's agent sees every arm's files. +2. The file needs a different name for each harness. +3. It lands at the workspace root, where outputs are collected, and risks `input_leak`. +4. It cannot reach `.claude/settings.json`, which the Claude Code driver renders. + +**Where each harness looks** + +| Harness (pinned) | Instruction file it reads | Hooks it runs | Evidence | +|---|---|---|---| +| Claude Code 2.1.311 | Project: `/CLAUDE.md` or `/.claude/CLAUDE.md`. User: `~/.claude/CLAUDE.md`, which does not load under the driver's `--setting-sources project,local`. | The `hooks` key of any settings file in scope. All matching hooks run, and their results merge. | Context7 `/websites/code_claude` | +| OpenCode V2 2.2.7 | `AGENTS.md` only, never `CLAUDE.md`: walking up from the cwd to `$HOME`, plus `/AGENTS.md`. | JS/TS plugins (`Plugin.define`). Local ones in `/plugins/` skip npm. | Context7 `/websites/opencode_ai/v2`; `config/plugin/instruction.ts:84-94` and `plugin/module.ts:109-110` at v2.2.7 | + +**How each harness fails on bad input** + +| Harness | A whole file is rejected | One entry is rejected | Its own check | +|---|---|---|---| +| Claude Code | A *Settings Error* (bad JSON, or a value the schema rejects): the file is not applied. | A *Settings Warning* (for example an unknown hook event): that entry is skipped and the rest applies. | `claude doctor`. Its exit code and whether it runs without a TTY are not documented, so the probe settles them. | +| OpenCode | A config document is dropped with a warning. A plugin is logged as failed and disabled. Startup continues. | Unknown config keys are ignored. | `opencode debug config` and `opencode plugin list`. `plugin check` covers package plugins only. | + +## Proposed State + +```mermaid +flowchart LR + subgraph cell[Experiment cell] + I["instructions.text"] + HC["hooks.claude-code
{settings, files}"] + HO["hooks.opencode
{plugins}"] + end + R["agent_config reader
(one reader)"] + cell --> R + R --> CC["Claude Code prepare"] + R --> OC["OpenCode prepare"] + CC --> CCF[".claude/CLAUDE.md
.claude/settings.json hooks key
.claude/hooks/*"] + OC --> OCF["$XDG_CONFIG_HOME/opencode/AGENTS.md
$XDG_CONFIG_HOME/opencode/plugins/*"] + CCF --> PF["HarnessConfigStep
(preflight, no network)"] + OCF --> PF + PF -- "finding" --> REF["experiment.harness_rejected_input"] + PF -- "clean" --> RUN["run"] + RUN --> CEN["census: instruction files loaded"] +``` + +**Where each value lands** + +| Value | Claude Code | OpenCode | Collected as output? | +|---|---|---|---| +| `instructions.text` | `/.claude/CLAUDE.md` (project scope) | `$XDG_CONFIG_HOME/opencode/AGENTS.md` (global scope, in the home) | No. `.claude/**` is excluded, and the home is not collected. | +| Hooks configuration | `hooks.settings` goes verbatim under the `hooks` key of `.claude/settings.json`. | none (OpenCode hooks are code) | No | +| Hook files | `.claude/hooks/`, mode 0755 | `$XDG_CONFIG_HOME/opencode/plugins/` | No | + +Candler's own observation hooks stay in the home `--settings` file. `InstructionsLoaded` is added to them, and that file is passed in headless mode too. Since only the `hooks` key is taken from the consumer, the consumer cannot switch the observers off. + +## Key Flows + +```mermaid +sequenceDiagram + participant C as candler resolve + participant D as driver + participant K as check container (cell image, no network) + participant H as harness check + C->>D: plan(cell) + D-->>C: prepared files + config_check() + C->>K: place prepared files + K->>H: claude doctor / opencode debug config + plugin list + H-->>C: output, exit + C->>D: read_config_check(output) + alt any error or warning + C-->>C: refuse cell, harness_rejected_input, exit 2 + else clean + C-->>C: record verdict beside harness identity + end +``` + +The check runs once for each distinct combination of harness, image, instructions and hooks, not once per run. + +## Contracts & Invariants + +**Surface** + +| Path | Type | Refusal on misuse | +|---|---|---| +| `instructions.text` | string | `experiment.document_invalid` (wrong type) | +| `hooks.` | an envelope with `deny_unknown_fields`; contents free | `experiment.cell_value_invalid` (unknown harness key) | +| `hooks.claude-code.settings` | object, verbatim | judged by the harness only | +| `hooks.claude-code.files` | map from a relative path to text | `format.rel_path_invalid` | +| `hooks.opencode.plugins` | map from a file name to text | `format.rel_path_invalid` | + +**Declaration** + +- Two new settings, `AgentSetting::Instructions` and `AgentSetting::Hooks`, which both drivers answer. +- A new `DriverFact::ConfigCheck`. +- Two new trait methods: + - `config_check(&Plan) -> Option` + - `read_config_check(output) -> CheckVerdict` + +**Error model** + +| When | Code | Side to fix | +|---|---|---| +| The cell has a `hooks` table but no entry for its own harness | `experiment.cell_value_missing` | experiment | +| The harness's own check reports an error or a warning | `experiment.harness_rejected_input` (new). Message: "Candler installed X at Y; H rejects it: «output»" | experiment | + +**Invariants** + +1. Every value is in the cell, so the cell digest, factor levels and `inspect` cover it. +2. One reader, `candler_harness::agent_config`, serves every consumer of these values. +3. No installed file appears among a run's collected outputs. +4. A cell is never run with part of its declared configuration dropped. Candler refuses the cell instead. +5. Candler's observation hooks cannot be disabled by the consumer's payload. +6. Every run's census names the instruction files the harness loaded. That includes a stray file from a fixture. + +## Alternatives Considered + +| Decision | Options | Chosen | Tradeoff accepted | +|---|---|---|---| +| Hooks payload | Shared and translated, or verbatim per harness | Verbatim per harness | An arm on two harnesses needs two payloads. Translation is impossible in general anyway: JSON plus shell on one side, JS modules on the other. | +| Where file contents come from | Inline text, file references, or `inputs` | Inline text | Long files are pasted or generated into the TOML. The alternative was a new "file value" mechanism, about $6 and one more leaf. `inputs` reach every arm. | +| A harness finding | Refuse both, refuse errors and warn on warnings, or warn only | Refuse both | A harmless deprecation notice also refuses. In exchange, an arm never runs silently without part of its hooks. | +| OpenCode scope | Workspace `AGENTS.md`, or global `/AGENTS.md` | Global | The two harnesses use different scopes (project and global). The text reaches the model the same way, and the scope is stated on the capability page. | +| Proof | A live RiVault run, or the fake model | The fake model | None. The fake model records each request, so the proof is deterministic and costs no tokens. | + +## Risks & Mitigations + +| Risk | Mitigation | +|---|---| +| `claude doctor` needs a TTY or network, or says nothing about hooks. | The level-1 probe settles it. If no check is reliable, `ConfigCheck` is `no (…)`, the page says so, and the census is the proof. | +| OpenCode's `` does not follow `XDG_CONFIG_HOME`. | The probe checks it. If it fails, install at the path OpenCode does read and state it. | +| `InstructionsLoaded` does not fire under `--print`. | The probe checks it. The fallback is the fake model's records: the text reached the model. | +| Passing `--settings` in headless mode changes behaviour. | The file holds only observe-only hooks. The guards compare headless runs before and after. | +| A consumer hook approves permission prompts and changes what `permission_mode` means. | This is the consumer's choice, stated on the experiment-file page. | +| A fixture's own `CLAUDE.md` or `AGENTS.md` also loads. | The census reports it. Nothing removes it. | + +## Roadmap Recommendation + +A new root, [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md). The tool refuses a `.` in a node name, so the directory is `m6_5`. Depth sets the order, and siblings run in parallel. + +| Level | Leaves | Owns | +|---|---|---| +| L1 | `probe_harness_checks`, `declaration` | Which harness checks are reliable. The P8 entries, schema, one reader, refusals, inspect and pages, with the answers still Refused. | +| L2 | `install_claude_code`, `install_opencode`, `preflight_check` | Installation and census in each driver, with answers flipped to Mapped. `HarnessConfigStep` and the new refusal. | +| L3 | `e2e_guard` | Both end-to-end guards on the real harnesses and the fake model. | +| L4 | `adversarial_review` | A read-only review of the merged milestone and the closing report. | + +- **Gates.** G1 to G9 of the plan. Each is an observation shown failing on the base (`8d82f63b`). They are copied into the leaves that own them. +- **Out of scope:** + - file references; + - project or user memory as a factor; + - npm plugins; + - other settings keys and other `.claude/` content; + - trace events for each hook run; + - removing a fixture's own instruction files; + - M7 and M8. M8's plugin may later use hooks. + +## Execution model + +The roadmap's leaves refer to this section. A copy of it goes into every brief. + +**Roles** + +- A coordinator dispatches the work and merges it. +- It writes no product code and never verifies its own dispatches. +- Every implementer, verifier and reviewer is a Sonnet subagent. + +**Verification, scaled to risk** + +- Every leaf gets a `spec-verifier` pass. +- `preflight_check` and `install_claude_code` also get an adversarial review before they merge. +- A seam review of the whole diff so far follows the close of L1 and of L2 ([leaf template](../../__roadmap__/leaf_template.md), convention 4). +- L4 is the final review. + +**Shared codebase, owned debt** + +Every brief opens with the same statement: + +- The codebase is shared with every agent and person who builds on it after this leaf. +- The implementer owns what the leaf leaves behind. +- A miss, a misuse, an accretion, a helper left behind, or tooling refactored without the old one cleaned up is debt that someone downstream has to handle. It breaks sustainability and scalability directly. + +So each leaf: + +- reuses the existing reader, renderer or step; +- removes, in the same leaf, whatever it made obsolete; +- leaves no scaffolding, debug helper or one-off script. + +The verifier checks these three points as gates. + +**Reviews stay in scope** + +- A finding is fixed in the leaf only if it concerns the leaf's own pieces, its gates or the code it touched. +- A finding that is unrelated, or too expensive to fix here, is filed under `__reports__/agent_config/` as an observation or a notice. The coordinator escalates it to the top coordination session, so the milestones can be re-planned around it. +- A leaf gets at most two rounds of implementing and verifying. If it would need a third, it stops and is escalated. + +**Git** + +- The integration branch is `feat/m6.5-agent-config`, cut from `origin/main` at `8d82f63b`. +- Each leaf branch is rebased on the integration branch, then merged with `--no-ff`. +- Commit messages go through `git commit -F`. +- No history is rewritten. +- Nothing is pushed and no PR is opened without Eliott. The PR to `main` waits for a green `container-e2e` (leaf template, convention 5). + +**Machine** + +- Builds use the slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`. +- At most 3 builds run at once, and a slot is never used by two worktrees at the same time. +- A leaf removes its slot when it merges. +- A leaf deletes the containers and images it starts. +- Nobody stops or prunes Docker. + +**Spend** + +- Spend is measured from host transcripts with `__reports__/agent-token-costs/scripts/spend.py`, per leaf and for the coordinator. +- The milestone cap is $75. At the cap, work stops and a report is written. + +**Status** + +- The high-level status lives in macOS Reminders, managed with the `scheduling-work` skill. +- There is one reminder for M6.5 and one for each level. +- Each reminder is updated when its level closes. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md new file mode 100644 index 00000000..2eb3108e --- /dev/null +++ b/__reports__/agent_config/README.md @@ -0,0 +1,12 @@ +# agent_config + +Instruction files and hooks as per-arm experiment data (M6.5). + +## Documents + +### Round 00 +- [00-architecture_agent_config_v0.md](00-architecture_agent_config_v0.md) — **latest**. The approved plan: cause, shape, harness check, proof, risks, roadmap. + +## Status + +The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. No leaf has been dispatched. From 8c7be6a1e2b6933f0cf749b51ec024f22bbb1fc2 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 12:15:38 +0900 Subject: [PATCH 02/69] rdm(api): open the M6.5 agent configuration root A new root, independent of M7 and M8: level 1 probes the harness checks and declares the settings with honest Refused answers; level 2 installs per harness and adds the preflight check; level 3 proves it end to end on real harnesses against the fake model; level 4 reviews and closes. Estimate $55, cap $75, measured from transcripts. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/README.md | 45 +++++++++++++++++++ __roadmap__/m6_5-agent-config/declaration.md | 29 ++++++++++++ .../m6_5-agent-config/installed/README.md | 44 ++++++++++++++++++ .../installed/install_claude_code.md | 30 +++++++++++++ .../installed/install_opencode.md | 20 +++++++++ .../installed/preflight_check.md | 20 +++++++++ .../installed/proved/README.md | 39 ++++++++++++++++ .../installed/proved/e2e_guard.md | 22 +++++++++ .../installed/proved/reviewed/README.md | 37 +++++++++++++++ .../proved/reviewed/adversarial_review.md | 19 ++++++++ .../m6_5-agent-config/probe_harness_checks.md | 24 ++++++++++ 11 files changed, 329 insertions(+) create mode 100644 __roadmap__/m6_5-agent-config/README.md create mode 100644 __roadmap__/m6_5-agent-config/declaration.md create mode 100644 __roadmap__/m6_5-agent-config/installed/README.md create mode 100644 __roadmap__/m6_5-agent-config/installed/install_claude_code.md create mode 100644 __roadmap__/m6_5-agent-config/installed/install_opencode.md create mode 100644 __roadmap__/m6_5-agent-config/installed/preflight_check.md create mode 100644 __roadmap__/m6_5-agent-config/installed/proved/README.md create mode 100644 __roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md create mode 100644 __roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md create mode 100644 __roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md create mode 100644 __roadmap__/m6_5-agent-config/probe_harness_checks.md diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md new file mode 100644 index 00000000..493a3f5b --- /dev/null +++ b/__roadmap__/m6_5-agent-config/README.md @@ -0,0 +1,45 @@ +# M6.5 Agent configuration as data + +## Context +A new root after M6c Integrity (#81, on `origin/main` at `8d82f63b`). It is independent of M7, which is blocked, and of M8, which lies below M7; M8's plugin may later use hooks. The plan is [the architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md). Every leaf runs by its §Execution model: Sonnet implementers and verifiers, a shared codebase whose debt the leaf owns, findings kept in scope or escalated, target-dir slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and a $75 cap. The status is mirrored in macOS Reminders. + +## Goal +A consumer gives each arm its own instruction text and hooks as cell values. Candler installs them where each harness looks, and refuses a cell that the harness's own check rejects. + +## Pre-conditions +- [x] `[cmd]` `git merge-base --is-ancestor 80405b5c origin/main` succeeds (M6c merged) +- [x] `[nl]` Eliott approved the plan on 2026-11-25: refuse errors and warnings, take contents inline, and make this a new root + +## Success Gates +- ⬜ G1–G9 of the [architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md) hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` +- ⬜ `probe_harness_checks.md`, `declaration.md` and `installed/` are `done` +- ⬜ The spend measured from transcripts, coordinator included, is at most $75 +- ⬜ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated + +## Status +```mermaid +graph TD + probe_harness_checks[Probe harness checks]:::planned + declaration[Declaration]:::planned + installed[Installed]:::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 | +|:-----|:-----|:-------| +| `probe_harness_checks.md` | 📄 Leaf Task | ⬜ Planned | +| `declaration.md` | 📄 Leaf Task | ⬜ Planned | +| `installed/` | 📁 Directory | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/m6_5-agent-config/declaration.md b/__roadmap__/m6_5-agent-config/declaration.md new file mode 100644 index 00000000..fb004551 --- /dev/null +++ b/__roadmap__/m6_5-agent-config/declaration.md @@ -0,0 +1,29 @@ +# Declaration + +**Goal**: An experiment can set `instructions.text`, `hooks.claude-code` and `hooks.opencode` as fixed values or factor levels. The cell digest and `inspect` cover them, every driver answers them on the generated pages, and the misuses are refused by name. (P0) +**Estimate**: Sonnet, $8, cap $16. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +**Success Gates**: +- ⬜ G1. `candler resolve` of an experiment with `[fixed] instructions.text = "…"` succeeds, and the `inspect` of a run of it shows an `instructions` member. On `8d82f63b` the resolve exits 2 with `experiment.unknown_path` at `/fixed/instructions.text`. +- ⬜ G2. Two levels of `instructions.text` plan two cells with different digests, and two levels of `hooks.claude-code.settings` do the same. On the base, both are `unknown_path`. +- ⬜ G8. `hooks.claude-code` on an OpenCode cell that has no `hooks.opencode` is refused with `experiment.cell_value_missing` at `/fixed/hooks`. A key under `hooks` that names no registered harness is refused with `experiment.cell_value_invalid` at its path. A hook file path with `..` is refused with `format.rel_path_invalid`. On the base, all three are `unknown_path`. +- ⬜ G3 (this level's half). `docs/contract/harness-capabilities.md` has the rows *instructions*, *hooks* and *config check*. Both drivers answer each with `no (…)` saying it is installed from L2, and `cargo nextest run -p candler contract_pages` passes. On the base, no such rows exist. +- ⬜ `experiment.harness_rejected_input` is declared in `docs/contract/codes.toml` with its side (experiment) and its path. No code path raises it yet. +**References**: [Architecture report](../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-schemas/src/servers.rs` (`McpServer`, the precedent); `crates/candler-harness/src/spec.rs:651` (`AgentSetting`) and `:729` (`DriverFact`); `crates/candler-core/src/resolve/paths.rs` (`CONFIGURATION_PATHS`, `settings_set_by`); `crates/candler/src/commands/inspect.rs` (`mcp_of`); `crates/candler/tests/it/guard_inspect_mcp_config.rs` + +## Step 1: Surface, schema and one reader +**Goal**: The three values exist as typed cell values, read by one reader. +**Implementation Logic**: +Add envelope types beside `McpServer` in `candler-schemas`: `Instructions {text}`, `ClaudeCodeHooks {settings: object, files: map}` and `OpenCodeHooks {plugins: map}`, each with `deny_unknown_fields`. Their contents stay free. Publish them as their own schemas, as `mcp-server.schema.json` is. Add the `instructions` and `hooks` rows to `CONFIGURATION_PATHS`; the names below `hooks` are harness ids. Add `candler_harness::agent_config::{instructions(cell), hooks(cell, harness)}`, the twin of `candler_harness::mcp::servers`, with the refusals of G8. No second reader may exist. +**Deliverables**: `crates/candler-schemas/src/agent_config.rs` (`Instructions`, `ClaudeCodeHooks`, `OpenCodeHooks`); the published schemas; `crates/candler-core/src/resolve/paths.rs` (rows); `crates/candler-harness/src/agent_config.rs` (`instructions`, `hooks`); unit guards for G2 and G8; `crates/candler-schemas/tests/vectors/manifest/hashed_paths.toml` (the new hashed paths) +**Consistency Checks**: `cargo nextest run -p candler-schemas -p candler-harness -p candler-core` (expected: PASS) +**Commit**: `feat(api): take instructions and hooks as cell values` + +## Step 2: Declaration, answers, pages and inspect +**Goal**: Every driver answers the new settings, and a run shows its values. +**Implementation Logic**: +Add `AgentSetting::Instructions`, `AgentSetting::Hooks` and `DriverFact::ConfigCheck`. Add the trait methods `config_check(&Plan) -> Option` and `read_config_check(output) -> CheckVerdict`, modelled on `version_probe` and `parse_version`. Both drivers answer `Refused` for now, so the merged level tells the truth. Declare `experiment.harness_rejected_input`. Regenerate the contract pages (`CANDLER_BLESS_CONTRACT=1 cargo nextest run -p candler contract_pages`) and the schemas (`CANDLER_BLESS_SCHEMAS=1 cargo nextest run -p candler-schemas drift`), and add a note on `experiment-file.md` that a consumer hook may approve tool calls, which changes what `permission_mode` means. Teach `inspect` to show `instructions` and `hooks` from `/comparable/values`, as `mcp_of` does, and extend `guard_inspect_mcp_config` or add a sibling guard for G1. +**Deliverables**: `crates/candler-harness/src/spec.rs`, `driver.rs`; both drivers' `answer`/`fact`; `docs/contract/codes.toml`; the regenerated contract pages; `crates/candler/src/commands/inspect.rs`; the G1 guard +**Consistency Checks**: `cargo nextest run --workspace` and `cargo nextest run -p candler contract_pages` (expected: PASS) +**Commit**: `feat(harness): declare instructions, hooks and the harness check` diff --git a/__roadmap__/m6_5-agent-config/installed/README.md b/__roadmap__/m6_5-agent-config/installed/README.md new file mode 100644 index 00000000..9c0b08b7 --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/README.md @@ -0,0 +1,44 @@ +# Installed + +## Context +L2 of M6.5. It runs after `probe_harness_checks.md` (which harness checks are reliable) and `declaration.md` (the settings, the one reader, the refusals). Its three leaves touch three separate crates: the Claude Code driver, the OpenCode driver and core. A seam review of the whole diff follows its close. + +## Goal +Each driver installs the instruction text and hooks where its harness looks, and records which instruction files loaded. Preflight refuses a cell that a harness check rejects. + +## Pre-conditions +- [ ] `[cmd]` `git merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds, after L1 has merged +- [ ] `[nl]` The probe report names each harness's check command, or `no` for a harness that has none + +## Success Gates +- ⬜ `install_claude_code.md`, `install_opencode.md`, `preflight_check.md` and `proved/` are `done` + +## Status +```mermaid +graph TD + install_claude_code[Install on Claude Code]:::planned + install_opencode[Install on OpenCode]:::planned + preflight_check[Preflight check]:::planned + proved[Proved]:::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 | +|:-----|:-----|:-------| +| `install_claude_code.md` | 📄 Leaf Task | ⬜ Planned | +| `install_opencode.md` | 📄 Leaf Task | ⬜ Planned | +| `preflight_check.md` | 📄 Leaf Task | ⬜ Planned | +| `proved/` | 📁 Directory | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md new file mode 100644 index 00000000..dd26b5d1 --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md @@ -0,0 +1,30 @@ +# Install on Claude Code + +**Goal**: On Claude Code, a cell's instruction text loads as project memory and its hooks run, and every run's census names the memory files that loaded. (P0) +**Estimate**: Sonnet, $7, cap $14. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +- [ ] `[nl]` The probe report settles (a) and (b) +**Success Gates**: +- ⬜ G3 (Claude Code). The *instructions*, *hooks* and *config check* rows show the Claude Code mapping: `.claude/CLAUDE.md`; the `hooks` key of `.claude/settings.json`, with files under `.claude/hooks/`; and the probe's check or `no (…)`. On the base, no such rows exist. +- ⬜ The plan of a cell with all three values renders `.claude/CLAUDE.md` holding the text and a `.claude/settings.json` whose `hooks` key equals the payload byte for byte as JSON. It places the files under `.claude/hooks/` with mode 0755, and the home `--settings` file holds an `InstructionsLoaded` observer in headless mode as in session mode. On the base, the plan has none of these. +- ⬜ A cell without these values renders the same `.claude/settings.json` as on the base. Only the home observers file is added. +- ⬜ The census of a run that recorded `InstructionsLoaded` lists `{path: .claude/CLAUDE.md, scope: Project}`, read from a recorded `.candler/hooks.jsonl` fixture. +- ⬜ An adversarial Sonnet review finds no way for a payload to disable Candler's observers, or to write outside `.claude/`. +**References**: [Architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-claude-code/src/prepare.rs` (`render_settings`), `session.rs` (`HOOK_EVENTS`, `hooks()`), `discovery.rs` (`EXCLUDED_DIRS`); the probe report + +## Step 1: Render and install +**Goal**: The driver writes the values where Claude Code reads them. +**Implementation Logic**: +Extend `render_settings` with the `hooks` key. Do not write a second settings renderer. Add the instructions file and the hook files as `PreparedFile`s. Move the observation hooks file so it is passed in headless mode too, and add `InstructionsLoaded` to `HOOK_EVENTS`. Remove whatever this makes obsolete. +**Deliverables**: `crates/candler-harness-claude-code/src/prepare.rs`, `session.rs`, `driver.rs` (`plan`, `answer`, `fact`); plan guards +**Consistency Checks**: `cargo nextest run -p candler-harness-claude-code` (expected: PASS) +**Commit**: `feat(harness): install instructions and hooks on Claude Code` + +## Step 2: Census and check +**Goal**: A run says which memory files loaded, and the driver supplies its harness check. +**Implementation Logic**: +Read the `InstructionsLoaded` records into the census. Implement `config_check` and `read_config_check` from the probe: any error or warning becomes a finding. Flip the answers to Mapped. +**Deliverables**: the census reader; `config_check`, `read_config_check`; the census guard +**Consistency Checks**: `cargo nextest run -p candler-harness-claude-code` and `cargo nextest run -p candler contract_pages` (expected: PASS) +**Commit**: `feat(harness): record loaded memory files on Claude Code` diff --git a/__roadmap__/m6_5-agent-config/installed/install_opencode.md b/__roadmap__/m6_5-agent-config/installed/install_opencode.md new file mode 100644 index 00000000..df017db8 --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/install_opencode.md @@ -0,0 +1,20 @@ +# Install on OpenCode + +**Goal**: On OpenCode, a cell's instruction text loads as the global `AGENTS.md` and its plugins load locally, and every run's census names the instruction files that loaded. (P0) +**Estimate**: Sonnet, $6, cap $12. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +- [ ] `[nl]` The probe report settles (c) and (d) +**Success Gates**: +- ⬜ G3 (OpenCode). The *instructions*, *hooks* and *config check* rows show the OpenCode mapping: `$XDG_CONFIG_HOME/opencode/AGENTS.md`; local plugins in `$XDG_CONFIG_HOME/opencode/plugins/`; and the probe's check or `no (…)`. On the base, no such rows exist. +- ⬜ The plan of a cell with `instructions.text` and `hooks.opencode` places `AGENTS.md` and each plugin in the home, byte for byte, and nothing in the workspace. On the base, the plan has neither. +- ⬜ The census lists each `Instructions from: ` block of the first request the gateway saw, read from a recorded request fixture. +**References**: [Architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-opencode/src/prepare.rs` (`render_config`, `PreparedFile::in_home`); the OpenCode V2 evidence in the report + +## Step 1: Install, census and check +**Goal**: The driver writes the values where OpenCode reads them, and a run says what loaded. +**Implementation Logic**: +Add the instructions file and the plugin files as home `PreparedFile`s next to `render_config`, in the same config directory. Extend the census source (the first request) with the instruction blocks. Implement `config_check` and `read_config_check` from the probe. Flip the answers to Mapped. +**Deliverables**: `crates/candler-harness-opencode/src/prepare.rs`, `driver.rs`, the census reader; plan and census guards +**Consistency Checks**: `cargo nextest run -p candler-harness-opencode` and `cargo nextest run -p candler contract_pages` (expected: PASS) +**Commit**: `feat(harness): install instructions and plugins on OpenCode` diff --git a/__roadmap__/m6_5-agent-config/installed/preflight_check.md b/__roadmap__/m6_5-agent-config/installed/preflight_check.md new file mode 100644 index 00000000..e3e71693 --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/preflight_check.md @@ -0,0 +1,20 @@ +# Preflight check + +**Goal**: Before any run, `candler resolve` runs each harness's own check on what Candler installed. It refuses a cell with any finding, quoting the harness, and records a clean verdict. (P0) +**Estimate**: Sonnet, $7, cap $14. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +**Success Gates**: +- ⬜ With a driver whose check reports a finding, `candler resolve` exits 2 with `experiment.harness_rejected_input`. The message names what was installed, where, the harness, and the harness's output. On the base, no such step exists, and the same experiment is refused earlier with `unknown_path`. +- ⬜ With a clean check, the verdict is stored beside the harness identity in the run's provenance. With a driver whose `config_check` is `None`, the cell is not refused and nothing is stored as checked. +- ⬜ Cells that share a harness, image, instructions and hooks run the check once, which is counted on the step's image service. +- ⬜ An adversarial Sonnet review finds no path where a finding lets the cell run, and no check container that outlives the step. +**References**: [Architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-core/src/resolve/steps/` (`HarnessIdentityStep`, the precedent); `ImageService` + +## Step 1: The step +**Goal**: A preflight step that asks the harness and refuses on its answer. +**Implementation Logic**: +Add `HarnessConfigStep` next to `HarnessIdentityStep`, reusing its image-service path. It dedupes by (harness, image, instructions, hooks). For each distinct entry it starts a no-network container from the cell's image, places the driver's prepared files there, runs `config_check`, reads the verdict with `read_config_check`, and removes the container. Use a fake driver in the core guards; the real harnesses are L3's. +**Deliverables**: `crates/candler-core/src/resolve/steps/config_check.rs` (`HarnessConfigStep`); the provenance field; core guards +**Consistency Checks**: `cargo nextest run -p candler-core` (expected: PASS) +**Commit**: `feat(api): refuse a cell its harness rejects` diff --git a/__roadmap__/m6_5-agent-config/installed/proved/README.md b/__roadmap__/m6_5-agent-config/installed/proved/README.md new file mode 100644 index 00000000..75bdb58a --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/proved/README.md @@ -0,0 +1,39 @@ +# Proved + +## Context +L3 of M6.5. It runs after both drivers install the values and the preflight step refuses. It proves the feature end to end on the real harnesses, against the scripted fake model, with no RiVault run. + +## Goal +One experiment shows, on both harnesses, the arm's own instructions reaching the model, a consumer hook acting on a tool call, the census naming the loaded file, and an invalid payload refused before the run. + +## Pre-conditions +- [ ] `[cmd]` `git merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds, after L2 has merged + +## Success Gates +- ⬜ `e2e_guard.md` and `reviewed/` are `done` + +## Status +```mermaid +graph TD + e2e_guard[E2E guard]:::planned + reviewed[Reviewed]:::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 | +|:-----|:-----|:-------| +| `e2e_guard.md` | 📄 Leaf Task | ⬜ Planned | +| `reviewed/` | 📁 Directory | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md new file mode 100644 index 00000000..ea1b8b21 --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md @@ -0,0 +1,22 @@ +# E2E guard + +**Goal**: The real `candler run` on real Claude Code and real OpenCode, against the scripted fake model, shows the README's promise for instructions and hooks on both harnesses. (P0) +**Estimate**: Sonnet, $8, cap $16. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +**Success Gates**: +- ⬜ G4. On each harness, the fake model's recorded requests for arm A hold text A and never text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. +- ⬜ G5. The scripted tool call is answered with an error carrying the hook's marker: a Claude Code PreToolUse script exits 2, and an OpenCode plugin throws in `execute.before`. On the base, there is no hook and the call succeeds. +- ⬜ G6. On real images, an invalid payload (a Claude Code hooks entry on an unknown event; an OpenCode plugin with no default export) is refused at `resolve` with `experiment.harness_rejected_input`, quoting the harness, and the valid payload passes. On the base, it is `unknown_path`. +- ⬜ G7. Each run's census lists the installed instruction file: `.claude/CLAUDE.md` (Project), and the global `AGENTS.md`. +- ⬜ G9. No installed file is among any run's collected outputs, and no run is sealed `input_leak`. +- ⬜ The guards run in a pass that lists them as passed, not skipped (leaf template, convention 3). `docker ps -a` shows none of their containers afterwards. +**References**: [Architecture report](../../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs` (`parity_one_installed_server_one_traced_call`, the model to follow); `assets/docker/fakemodel` + +## Step 1: The guards +**Goal**: Two guards that read what a consumer reads. +**Implementation Logic**: +`guard_agent_config_e2e` runs one experiment with two arms (text A or B) and one hook per harness on both harnesses. It reads `inspect`'s members, the rendered files in the run, the fake model's records and the stored census. `guard_harness_check_refuses` runs `resolve` on real images with no model. Reuse the parity e2e's helpers; do not copy them. The check's output must list both guards as passed. +**Deliverables**: `crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs`; the fake model's script for the blocked call +**Consistency Checks**: `cargo nextest run -p candler --run-ignored all -E 'test(agent_config) | test(harness_check)'` (expected: PASS) +**Commit**: `test(cli): prove instructions and hooks on both harnesses` diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md new file mode 100644 index 00000000..73e18c4b --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md @@ -0,0 +1,37 @@ +# Reviewed + +## Context +L4 of M6.5, the last level. A read-only, adversarial review of the merged milestone, followed by the closing report. + +## Goal +A reviewer who did not build the milestone finds no gate that passes for the wrong reason, and no debt left behind. + +## Pre-conditions +- [ ] `[cmd]` `git merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds, after L3 has merged + +## Success Gates +- ⬜ `adversarial_review.md` is `done` + +## Status +```mermaid +graph TD + adversarial_review[Adversarial review]:::planned + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `adversarial_review.md` | 📄 Leaf Task | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md new file mode 100644 index 00000000..d622b423 --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md @@ -0,0 +1,19 @@ +# Adversarial review + +**Goal**: A Sonnet reviewer, who did not build M6.5, reads the milestone's whole diff against the consumer interface, and the closing report says what holds and what does not. (P1) +**Estimate**: Sonnet, $4, cap $8. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +**Success Gates**: +- ⬜ `__reports__/agent_config/02-review_m6_5_v0.md` names each gate G1–G9 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. +- ⬜ The report lists any debt left behind (a second reader, a duplicated helper, dead code, a leftover script), each fixed in this leaf or filed as a notice. An out-of-scope finding is filed as an observation and escalated. +- ⬜ `__reports__/agent_config/03-knowledge_transfer_m6_5_v0.md` records the spend measured per leaf against the $75 cap. +**References**: [Architecture report](../../../../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model + +## Step 1: Review and close +**Goal**: An independent verdict, and the milestone's record. +**Implementation Logic**: +The review is read-only. A finding is fixed here only if it is in M6.5's scope and small, at most two rounds. Anything else is filed and escalated. Then write the knowledge transfer report, and update the Reminders status. +**Deliverables**: the two reports; `__reports__/agent_config/README.md` +**Consistency Checks**: `bash ~/.claude/plugins/cache/cracking-shells/managing-roadmaps/1.3.0/skills/managing-roadmaps/scripts/dirtree-rdm.sh validate __roadmap__/m6_5-agent-config` (expected: PASS) +**Commit**: `reports(api): close M6.5 agent configuration` diff --git a/__roadmap__/m6_5-agent-config/probe_harness_checks.md b/__roadmap__/m6_5-agent-config/probe_harness_checks.md new file mode 100644 index 00000000..7b04b62a --- /dev/null +++ b/__roadmap__/m6_5-agent-config/probe_harness_checks.md @@ -0,0 +1,24 @@ +# Probe harness checks + +**Goal**: The plan names, for each harness, a command that reports whether Candler's install of instructions and hooks is valid, and says what that command does without a TTY and without network. Where no such command exists, the plan says `no`. (P0, it decides L2) +**Estimate**: Sonnet, $3, cap $6. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +**Success Gates**: +- ⬜ `__reports__/agent_config/01-findings_probe_harness_checks_v0.md` answers every question of Step 1. Each answer quotes the command, its exit code and its output, captured in the `base` image (Claude Code 2.1.311) or the `base-opencode` image (OpenCode 2.2.7). +- ⬜ For each harness, the report names the command that L2 wires into `config_check`, and what in its output counts as an error or a warning. If no command is reliable, the report says `no` and why. +- ⬜ `docker ps -a --filter label=m6_5-probe -q` prints nothing at the leaf's close. +**References**: [Architecture report](../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model + +## Step 1: Probe the checks +**Goal**: Measured answers, not documentation, for each check the plan relies on. +**Implementation Logic**: +Use throwaway containers labelled `m6_5-probe`, with network `none`. Write three installs by hand: a valid one, an error one (bad JSON in `.claude/settings.json`; an OpenCode plugin with no default export) and a warning one (a Claude Code hook on an unknown event). They are the files L2 will render. Ask: +(a) Does `claude doctor` run without a TTY and without network? What is its exit code? Does it report errors and warnings in the project settings' hooks? +(b) Does `InstructionsLoaded` fire under `claude --print --setting-sources project,local` for `.claude/CLAUDE.md`, and what does its payload hold? Use a gateway that refuses the request, so no model is needed. +(c) Do `opencode debug config` and `opencode plugin list` need a server or network? Do they show a rejected config and a failed local plugin? +(d) Does OpenCode's `` directory follow `XDG_CONFIG_HOME`, so that `$XDG_CONFIG_HOME/opencode/AGENTS.md` and `$XDG_CONFIG_HOME/opencode/plugins/` load? +This step changes no product code. +**Deliverables**: `__reports__/agent_config/01-findings_probe_harness_checks_v0.md`, written with `writing-reports`, type findings +**Consistency Checks**: `test -s __reports__/agent_config/01-findings_probe_harness_checks_v0.md` (expected: PASS) +**Commit**: `reports(api): probe the harness checks for instructions and hooks` From 834356214f54d373470558f08187eeacb273d950 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 12:17:08 +0900 Subject: [PATCH 03/69] reports(api): check the HTN lane's requirements against M6.5 The HTN eval lane named four requirements an instruction-file arm would need. The plan meets the digest, placement and record requirements; placement is deliberately not the workspace root, which is collected as outputs. Evaluator blinding is not covered: any comparable value a metadata need names is served, so the notice puts the choice to Eliott. Co-Authored-By: Claude Opus 5.5 --- .../00-notice_consumer_requirements_v0.md | 34 +++++++++++++++++++ __reports__/agent_config/README.md | 3 +- 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 __reports__/agent_config/00-notice_consumer_requirements_v0.md diff --git a/__reports__/agent_config/00-notice_consumer_requirements_v0.md b/__reports__/agent_config/00-notice_consumer_requirements_v0.md new file mode 100644 index 00000000..77bdff5a --- /dev/null +++ b/__reports__/agent_config/00-notice_consumer_requirements_v0.md @@ -0,0 +1,34 @@ +# Notice: the HTN eval lane's requirements against the M6.5 plan + +**Source.** The Candler milestone coordination session passed on the current positions of the HTN eval lane, Candler's main outside consumer. That lane's plan is not approved yet. No planned HTN experiment needs instruction files or hooks: its treatment is a skill directory at a tag, and the container already confines the agent the way hooks otherwise would. If it ever adds an instruction-file arm, it would need the four things below. + +**Checked against.** [`00-architecture_agent_config_v0.md`](00-architecture_agent_config_v0.md) and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md), as committed in 8c7be6a1. + +## Verdict per requirement + +| # | Requirement | Plan | Status | +|---|---|---|---| +| a | The file's bytes are a factor level, hashed into the cell digest, so two arms differ only by those bytes. | `instructions.text` is a cell value, so it sits in `comparable.values`, which the digest hashes. Gate G2: two levels give two digests. | **Met** | +| b | It is installed at the workspace root, where each harness reads it. | Claude Code: `/.claude/CLAUDE.md`, which Claude Code loads as project memory just as it loads the root `CLAUDE.md`. OpenCode: `$XDG_CONFIG_HOME/opencode/AGENTS.md`, the global file OpenCode always reads. | **Met in intent, not literally.** See below. | +| c | Every run records it in its provenance or manifest. | The text is in the manifest's `comparable.values`. Gate G7 adds the files the harness actually loaded to the census. | **Met**, and also proven loaded. | +| d | The evaluator cannot see it, as `request.treatment` is hidden today. | Not covered. An evaluator that names `instructions.text` or `hooks.*` among its metadata needs gets the value: `assemble` (`crates/candler-core/src/evaluation/context/assemble.rs:92`) serves any `comparable.values` leaf a need names. `treatment` is hidden only because it is its own root, outside `values`. | **Gap** | + +## Why (b) does not follow the workspace root + +The plan avoids the root deliberately: + +- `/CLAUDE.md` and `/AGENTS.md` are collected as outputs. An installed file there would be graded as the agent's work, or seal the run `input_leak`; G9 guards against exactly this. +- A fixture may ship its own root `CLAUDE.md` or `AGENTS.md`. Writing to the root would overwrite it silently. The plan leaves it in place and the census reports it. + +The consumer's need is the harness reading the file, and both placements meet it. No change is proposed. + +## The decision for (d) + +This is a design choice, not a defect: an evaluator grading "did the agent follow its instructions" may legitimately want the text. + +| Option | What changes | Cost | +|---|---|---| +| **Blind, like the treatment (recommended)** | The evaluator registry's need check refuses a metadata need at or below `instructions` or `hooks`. One gate, G10, joins `declaration.md`, the leaf that owns the paths. | Small: one refusal, one unit guard. | +| Visible on request | Nothing changes. The page states that an evaluator naming the path receives the value. | None, but the blinding the HTN lane expects does not hold. | + +The roadmap is unchanged until Eliott rules. If he picks the first option, G10 is added to `declaration.md` as an amendment, and every consumer of the gate list (the root's gates, the reminder `candler-M6.5-L1`) is updated in the same amendment. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 2eb3108e..0938cab8 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -6,7 +6,8 @@ Instruction files and hooks as per-arm experiment data (M6.5). ### Round 00 - [00-architecture_agent_config_v0.md](00-architecture_agent_config_v0.md) — **latest**. The approved plan: cause, shape, harness check, proof, risks, roadmap. +- [00-notice_consumer_requirements_v0.md](00-notice_consumer_requirements_v0.md) — **latest**. The HTN eval lane's four requirements checked against the plan: three met, evaluator blinding (d) open for Eliott. ## Status -The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. No leaf has been dispatched. +The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. No leaf has been dispatched. Open decision: whether an evaluator may read `instructions` and `hooks` values (notice above). From 0d9f78df981f119423e47e4d1939f0b0dbb27935 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 12:51:34 +0900 Subject: [PATCH 04/69] reports(api): plan two instruction scopes for M6.5 (v1) The plan's v1 applies the two rulings on the HTN lane's notice. Instructions come as a global file per harness, set for the whole experiment, and a workspace file per arm. The workspace file is mounted read-only at the workspace root as CLAUDE.md or AGENTS.md through the existing input mount, so it is neither collected nor editable, and an input at the same path is refused. Evaluator access to these values is deferred until a consumer needs it. The notice is revised to match. Co-Authored-By: Claude Opus 5.5 --- .../01-architecture_agent_config_v1.md | 296 ++++++++++++++++++ .../01-notice_consumer_requirements_v1.md | 19 ++ __reports__/agent_config/README.md | 10 +- 3 files changed, 322 insertions(+), 3 deletions(-) create mode 100644 __reports__/agent_config/01-architecture_agent_config_v1.md create mode 100644 __reports__/agent_config/01-notice_consumer_requirements_v1.md diff --git a/__reports__/agent_config/01-architecture_agent_config_v1.md b/__reports__/agent_config/01-architecture_agent_config_v1.md new file mode 100644 index 00000000..4256f6bb --- /dev/null +++ b/__reports__/agent_config/01-architecture_agent_config_v1.md @@ -0,0 +1,296 @@ +# Agent configuration as data — Architecture Analysis (v1) + +M6.5 makes instruction files (`CLAUDE.md`, `AGENTS.md`) and hooks values of an experiment cell. Each driver installs them where its harness looks. Before the agents run, the harness's own check reports on what Candler installed, and any finding refuses the cell. The plan was approved on 2026-11-25. The roadmap is [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md). + +**What changed since v0.** Eliott ruled on two points the [consumer notice](00-notice_consumer_requirements_v0.md) raised: + +- Instructions come in **two scopes**. A *global* file per harness is set for the whole experiment. A *workspace* file is set per arm and is installed at the workspace root on both harnesses, where it overrides or complements the global one. v0 had one value, installed at `.claude/CLAUDE.md` on Claude Code and at the global `AGENTS.md` on OpenCode. +- **Evaluator access is deferred.** The consumer writes the evaluator and already knows which instructions the box holds, so no evaluator needs to read them back. No gate is added; the item sits under Out of scope until a consumer brings a reason. + +The sections below are v0 with these two rulings applied. §Execution model is unchanged. + +## Executive Summary + +| Question | Answer | +|---|---| +| Cause removed | Instruction files and hooks are not `AgentSetting`s. So no driver answers for them, no page says where they go, no digest covers them, and nothing refuses a cell whose harness drops them. | +| Shape | New cell values: `instructions.global.`, `instructions.workspace`, `hooks.claude-code` and `hooks.opencode`. All are inline, exactly like `mcp.servers`. | +| Two scopes | `instructions.global` is meant for `[fixed]`: one text per harness, shared by every arm. `instructions.workspace` is meant to be a factor: one text per arm, the same on both harnesses, installed as the workspace's root `CLAUDE.md` or `AGENTS.md`. | +| Translation | None. The workspace text goes verbatim to each harness's own file name. Each harness gets its own global text and its own hooks payload, installed verbatim. | +| Boundary | Candler guarantees the installation. The harness judges the content. | +| Harness check finds an error or a warning | Refused: `experiment.harness_rejected_input`. | +| Proof | A real-harness end-to-end run against the scripted fake model. No RiVault run is needed. | +| Cost | About $60. Cap $75. | + +**Rulings** + +| Choice | Ruling | +|---|---| +| A harness finding | Refuse errors and warnings alike. | +| Where file contents come from | Inline text in the cell. There is no file-reference mechanism. | +| Placement of the work | A new roadmap root, M6.5. Its high-level status is kept in macOS Reminders. | +| Instruction scopes (2026-11-25, after the notice) | A global file per harness for the experiment, and a workspace-root file per arm that overrides or complements it, on both harnesses. | +| Evaluator access (2026-11-25, after the notice) | Deferred. No evaluator has a reason to read the instructions back from the box. | + +**Reading of "inputs".** Eliott wrote that the global files belong in Candler's *inputs*. This plan reads that as "set once for the whole experiment", and makes `instructions.global` a cell value written in `[fixed]`, not an `inputs` entry. Three reasons: an `inputs` entry lands in the workspace and is collected, which is where the global file must not be; it is not part of `comparable.values`, so the digest and `inspect` would not cover it; and the inline ruling already covers file contents. Nothing refuses varying `instructions.global` as a factor, since a consumer may want that. + +## Current State + +Today, an `inputs` entry is the only way to put a file in front of the agent. It fails here in four ways: + +1. It applies to the whole experiment, so every arm's agent sees every arm's files. +2. The file needs a different name for each harness. +3. A file at the workspace root is collected as an output, so it is graded as the agent's work, and the agent can edit it. +4. It cannot reach `.claude/settings.json`, which the Claude Code driver renders. + +**Where each harness looks** + +| Harness (pinned) | Instruction files it reads | Hooks it runs | Evidence | +|---|---|---|---| +| Claude Code 2.1.311 | Project: `/CLAUDE.md` or `/.claude/CLAUDE.md`, and `CLAUDE.md` in each parent directory. User: `~/.claude/CLAUDE.md`, which loads only with `user` among the setting sources; the driver passes `--setting-sources project,local`. | The `hooks` key of any settings file in scope. All matching hooks run, and their results merge. | Context7 `/websites/code_claude` | +| OpenCode V2 2.2.7 | `AGENTS.md` only, never `CLAUDE.md`: walking up from the cwd to `$HOME`, plus the global `/AGENTS.md`. | JS/TS plugins (`Plugin.define`). Local ones in `/plugins/` skip npm. | Context7 `/websites/opencode_ai/v2`; `config/plugin/instruction.ts:84-94` and `plugin/module.ts:109-110` at v2.2.7 | + +**How each harness fails on bad input** + +| Harness | A whole file is rejected | One entry is rejected | Its own check | +|---|---|---|---| +| Claude Code | A *Settings Error* (bad JSON, or a value the schema rejects): the file is not applied. | A *Settings Warning* (for example an unknown hook event): that entry is skipped and the rest applies. | `claude doctor`. Its exit code and whether it runs without a TTY are not documented, so the probe settles them. | +| OpenCode | A config document is dropped with a warning. A plugin is logged as failed and disabled. Startup continues. | Unknown config keys are ignored. | `opencode debug config` and `opencode plugin list`. `plugin check` covers package plugins only. | + +**What the core already does for a workspace-root file.** `mount_inputs` (`crates/candler-core/src/runner/exec/mod.rs:146`) bind-mounts each input file read-only into the workspace and re-checks the whole mount list. The output tree builder lists no path under a read-only mount point, so such a file is never collected. `input_leak` (`crates/candler-core/src/runner/evidence/leak.rs:10`) seals a run only when an output's digest equals an input's. The workspace instruction file reuses this path, so it is neither collected nor editable. + +## Proposed State + +```mermaid +flowchart LR + subgraph cell[Experiment cell] + IG["instructions.global.<harness>
(fixed, per harness)"] + IW["instructions.workspace
(factor, per arm)"] + HC["hooks.claude-code
{settings, files}"] + HO["hooks.opencode
{plugins}"] + end + R["agent_config reader
(one reader)"] + cell --> R + R --> CC["Claude Code prepare"] + R --> OC["OpenCode prepare"] + CC --> CCF["global: home, scope set by the probe
.claude/settings.json hooks key
.claude/hooks/*"] + OC --> OCF["global: $XDG_CONFIG_HOME/opencode/AGENTS.md
$XDG_CONFIG_HOME/opencode/plugins/*"] + CC --> WF["read-only file at the workspace root
CLAUDE.md or AGENTS.md"] + OC --> WF + WF --> MI["core: mount_inputs
(the existing read-only mount)"] + CCF --> PF["HarnessConfigStep
(preflight, no network)"] + OCF --> PF + MI --> PF + PF -- "finding" --> REF["experiment.harness_rejected_input"] + PF -- "clean" --> RUN["run"] + RUN --> CEN["census: instruction files loaded, with scope"] +``` + +**Where each value lands** + +| Value | Claude Code | OpenCode | Collected as output? | +|---|---|---|---| +| `instructions.global.` | `~/.claude/CLAUDE.md` in the run's home, with `user` added to the setting sources, if the probe shows that loads nothing else from that home; else the parent directory of the workspace, which Claude Code walks. | `$XDG_CONFIG_HOME/opencode/AGENTS.md` (global scope, in the home) | No. The home and the workspace's parent are not collected. | +| `instructions.workspace` | `/CLAUDE.md` | `/AGENTS.md` | No. It is a read-only mount, which the tree builder skips. | +| Hooks configuration | `hooks.settings` goes verbatim under the `hooks` key of `.claude/settings.json`. | none (OpenCode hooks are code) | No | +| Hook files | `.claude/hooks/`, mode 0755 | `$XDG_CONFIG_HOME/opencode/plugins/` | No | + +**How the workspace file reaches the root.** The driver does not write it into the workspace. Its plan lists it as a read-only workspace file: a name (`CLAUDE.md` or `AGENTS.md`) and its text. The core stores the text and mounts it through `mount_inputs`, beside the declared inputs, so one mount path and one re-check cover both. The plan field and the trait method that names the file are declared in L1; the drivers fill them in L2; the core mounts them in L2. + +**Override or complement.** Both harnesses load the global file and the workspace file together. Which one the model reads as overriding is each harness's own rule: Claude Code ranks project memory over user memory, and OpenCode concatenates the files it finds. The probe records the order in which each harness puts the two texts in front of the model, and the capability page states it. + +Candler's own observation hooks stay in the home `--settings` file. `InstructionsLoaded` is added to them, and that file is passed in headless mode too. Since only the `hooks` key is taken from the consumer, the consumer cannot switch the observers off. + +## Key Flows + +```mermaid +sequenceDiagram + participant C as candler resolve + participant D as driver + participant K as check container (cell image, no network) + participant H as harness check + C->>D: plan(cell) + D-->>C: prepared files, read-only workspace file, config_check() + C->>C: the workspace file's path collides with an input's? refuse + C->>K: place prepared files, mount the workspace file read-only + K->>H: claude doctor / opencode debug config + plugin list + H-->>C: output, exit + C->>D: read_config_check(output) + alt any error or warning + C-->>C: refuse cell, harness_rejected_input, exit 2 + else clean + C-->>C: record verdict beside harness identity + end +``` + +The check runs once for each distinct combination of harness, image and prepared files, not once per run. + +## Contracts & Invariants + +**Surface** + +| Path | Type | Refusal on misuse | +|---|---|---| +| `instructions.global` | a table keyed by harness id; each value a string | `experiment.cell_value_invalid` (unknown harness key); `experiment.cell_value_missing` (no key for the cell's harness) | +| `instructions.workspace` | string | `experiment.document_invalid` (wrong type) | +| `hooks.` | an envelope with `deny_unknown_fields`; contents free | `experiment.cell_value_invalid` (unknown harness key); `experiment.cell_value_missing` (no key for the cell's harness) | +| `hooks.claude-code.settings` | object, verbatim | judged by the harness only | +| `hooks.claude-code.files` | map from a relative path to text | `format.rel_path_invalid` | +| `hooks.opencode.plugins` | map from a file name to text | `format.rel_path_invalid` | + +**Declaration** + +- Two new settings, `AgentSetting::Instructions(scope)` with the scopes global and workspace, and `AgentSetting::Hooks`. Both drivers answer each. +- A new `DriverFact::ConfigCheck`. +- New trait methods: + - `config_check(&Plan) -> Option` + - `read_config_check(output) -> CheckVerdict` + - the name of the workspace instruction file (`CLAUDE.md` or `AGENTS.md`) +- A `Plan` field for read-only workspace files, which the core mounts. + +**Error model** + +| When | Code | Side to fix | +|---|---|---| +| The cell has a `hooks` or `instructions.global` table but no entry for its own harness | `experiment.cell_value_missing` | experiment | +| `instructions.workspace` is set and a declared input also mounts a file at the workspace instruction file's path | `experiment.instructions_collide` (new), at `/fixed/instructions.workspace` or the factor's path, naming the input. The file is refused, never shadowed. | experiment | +| The harness's own check reports an error or a warning | `experiment.harness_rejected_input` (new). Message: "Candler installed X at Y; H rejects it: «output»" | experiment | + +**Invariants** + +1. Every value is in the cell, so the cell digest, factor levels and `inspect` cover it. +2. One reader, `candler_harness::agent_config`, serves every consumer of these values. +3. No installed file appears among a run's collected outputs. The workspace file is a read-only mount, and every other file lives under `.claude/` or the home. +4. The agent cannot change either instruction file. +5. A cell is never run with part of its declared configuration dropped or shadowed. Candler refuses the cell instead. +6. Candler's observation hooks cannot be disabled by the consumer's payload. +7. Every run's census names the instruction files the harness loaded, with their scope. That includes a fixture's own file when no workspace text is set. + +## Alternatives Considered + +| Decision | Options | Chosen | Tradeoff accepted | +|---|---|---|---| +| Hooks payload | Shared and translated, or verbatim per harness | Verbatim per harness | An arm on two harnesses needs two payloads. Translation is impossible in general anyway: JSON plus shell on one side, JS modules on the other. | +| Where file contents come from | Inline text, file references, or `inputs` | Inline text | Long files are pasted or generated into the TOML. The alternative was a new "file value" mechanism, about $6 and one more leaf. `inputs` reach every arm. | +| A harness finding | Refuse both, refuse errors and warn on warnings, or warn only | Refuse both | A harmless deprecation notice also refuses. In exchange, an arm never runs silently without part of its hooks. | +| Instruction scopes | One value (v0), or a global value per harness plus a workspace value per arm | Two scopes (Eliott) | Two values to learn. In exchange, the shared part is written once, and each arm's part sits where both harnesses read a project file. | +| Global file as an `inputs` entry or a cell value | `inputs`, or `instructions.global` in `[fixed]` | Cell value | It is not written in the `inputs` array. In exchange, the digest covers it and it never lands in the workspace. | +| Workspace file written or mounted | Written by the driver into the workspace, or mounted read-only by the core | Mounted | The core gains a source of mounts besides inputs. In exchange, the file is not collected, not graded, not editable, and a collision is found by the existing re-check. | +| Proof | A live RiVault run, or the fake model | The fake model | None. The fake model records each request, so the proof is deterministic and costs no tokens. | + +## Risks & Mitigations + +| Risk | Mitigation | +|---|---| +| `claude doctor` needs a TTY or network, or says nothing about hooks. | The level-1 probe settles it. If no check is reliable, `ConfigCheck` is `no (…)`, the page says so, and the census is the proof. | +| Adding `user` to Claude Code's setting sources also loads user settings from the run's home. | The probe checks what `user` loads. If anything beyond `~/.claude/CLAUDE.md` loads, the global file goes to the workspace's parent directory instead, and the page states that scope. | +| A single-file read-only bind mount at the workspace root is not read by a harness. | The probe mounts one on each harness. If one does not read it, the plan returns for a ruling before L2. | +| OpenCode's `` does not follow `XDG_CONFIG_HOME`. | The probe checks it. If it fails, install at the path OpenCode does read and state it. | +| `InstructionsLoaded` does not fire under `--print`. | The probe checks it. The fallback is the fake model's records: the text reached the model. | +| Passing `--settings` in headless mode changes behaviour. | The file holds only observe-only hooks. The guards compare headless runs before and after. | +| A consumer hook approves permission prompts and changes what `permission_mode` means. | This is the consumer's choice, stated on the experiment-file page. | +| An agent copies the workspace file into its outputs, and the run is sealed `input_leak`. | The same holds for any input today. The guard's agent does not copy it, and G9 checks no run is sealed. | +| A fixture's own root `CLAUDE.md` or `AGENTS.md`. | With `instructions.workspace` set, a declared input at that path is refused (`experiment.instructions_collide`). Without it, the fixture's file stays and the census reports it. | + +## Roadmap Recommendation + +A new root, [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md). The tool refuses a `.` in a node name, so the directory is `m6_5`. Depth sets the order, and siblings run in parallel. + +| Level | Leaves | Owns | +|---|---|---| +| L1 | `probe_harness_checks`, `declaration` | Which harness checks are reliable, where Claude Code's global file loads, and whether a read-only root mount is read. The P8 entries, schema, one reader, refusals, inspect, pages and the read-only workspace file in `Plan`, with the answers still Refused. | +| L2 | `install_claude_code`, `install_opencode`, `preflight_check` | Installation and census in each driver, with answers flipped to Mapped. In core: `HarnessConfigStep`, the new refusals, and the workspace file's mount through `mount_inputs`. | +| L3 | `e2e_guard` | Both end-to-end guards on the real harnesses and the fake model. | +| L4 | `adversarial_review` | A read-only review of the merged milestone and the closing report. | + +**Gates.** Each is an observation shown failing on the base (`8d82f63b`), copied into the leaf that owns it. + +| # | Observation after | On the base | Leaf | +|---|---|---|---| +| G1 | `candler resolve` of `[fixed] instructions.workspace = "…"` succeeds, and `inspect` shows an `instructions` member. | exit 2 `experiment.unknown_path` at `/fixed/instructions.workspace` | declaration | +| G2 | Two levels of `instructions.workspace` give two cells with different digests; so do two levels of `hooks.claude-code.settings`. | `unknown_path` | declaration | +| G3 | `harness-capabilities.md` has the rows *instructions: global*, *instructions: workspace*, *hooks* and *config check*, mapped on both harnesses. | no such rows | declaration, then both install leaves | +| G4 | e2e: on each harness, the fake model's recorded requests hold the global text and the arm's workspace text, and never the other arm's workspace text. | `unknown_path` | e2e_guard | +| G5 | e2e: the scripted tool call is answered with an error carrying the hook's marker. On Claude Code a PreToolUse script exits 2; on OpenCode a plugin throws in `execute.before`. | the call succeeds; no hook | e2e_guard | +| G6 | An invalid payload (a Claude Code hooks entry with an unknown event; an OpenCode plugin with no default export) is refused at `resolve` with `experiment.harness_rejected_input`, quoting the harness's output. The valid payload passes. | `unknown_path` | preflight_check (fake driver), e2e_guard (real images) | +| G7 | Each run's census lists both installed instruction files with their scope, on each harness. | no field | both install leaves, e2e_guard | +| G8 | `hooks.claude-code` on an OpenCode cell with no `hooks.opencode` is `experiment.cell_value_missing` at `/fixed/hooks`; likewise `instructions.global` with no key for the cell's harness, at `/fixed/instructions.global`. | `unknown_path` | declaration | +| G9 | The workspace instruction file is not among a run's collected outputs, an agent's write to it fails, and no run is sealed `input_leak`. | not reachable | preflight_check, e2e_guard | +| G10 | With `instructions.workspace` set, an input declared at the workspace instruction file's path is refused at `resolve` with `experiment.instructions_collide`, naming the input. | `unknown_path` | preflight_check | + +**Out of scope:** + +- file references; +- instruction scopes beyond global and workspace, such as files in subdirectories; +- npm plugins; +- other settings keys and other `.claude/` content; +- trace events for each hook run; +- removing a fixture's own instruction file when no workspace text is set (the census reports it); +- evaluator access to the instruction and hook values. Deferred until a consumer brings a reason: the consumer who writes the evaluator already knows the values. Today an evaluator that names one of these paths among its metadata needs receives it, like any cell value; +- M7 and M8. M8's plugin may later use hooks. + +## Execution model + +The roadmap's leaves refer to this section. A copy of it goes into every brief. + +**Roles** + +- A coordinator dispatches the work and merges it. +- It writes no product code and never verifies its own dispatches. +- Every implementer, verifier and reviewer is a Sonnet subagent. + +**Verification, scaled to risk** + +- Every leaf gets a `spec-verifier` pass. +- `preflight_check` and `install_claude_code` also get an adversarial review before they merge. +- A seam review of the whole diff so far follows the close of L1 and of L2 ([leaf template](../../__roadmap__/leaf_template.md), convention 4). +- L4 is the final review. + +**Shared codebase, owned debt** + +Every brief opens with the same statement: + +- The codebase is shared with every agent and person who builds on it after this leaf. +- The implementer owns what the leaf leaves behind. +- A miss, a misuse, an accretion, a helper left behind, or tooling refactored without the old one cleaned up is debt that someone downstream has to handle. It breaks sustainability and scalability directly. + +So each leaf: + +- reuses the existing reader, renderer or step; +- removes, in the same leaf, whatever it made obsolete; +- leaves no scaffolding, debug helper or one-off script. + +The verifier checks these three points as gates. + +**Reviews stay in scope** + +- A finding is fixed in the leaf only if it concerns the leaf's own pieces, its gates or the code it touched. +- A finding that is unrelated, or too expensive to fix here, is filed under `__reports__/agent_config/` as an observation or a notice. The coordinator escalates it to the top coordination session, so the milestones can be re-planned around it. +- A leaf gets at most two rounds of implementing and verifying. If it would need a third, it stops and is escalated. + +**Git** + +- The integration branch is `feat/m6.5-agent-config`, cut from `origin/main` at `8d82f63b`. +- Each leaf branch is rebased on the integration branch, then merged with `--no-ff`. +- Commit messages go through `git commit -F`. +- No history is rewritten. +- Nothing is pushed and no PR is opened without Eliott. The PR to `main` waits for a green `container-e2e` (leaf template, convention 5). + +**Machine** + +- Builds use the slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`. +- At most 3 builds run at once, and a slot is never used by two worktrees at the same time. +- A leaf removes its slot when it merges. +- A leaf deletes the containers and images it starts. +- Nobody stops or prunes Docker. + +**Spend** + +- Spend is measured from host transcripts with `__reports__/agent-token-costs/scripts/spend.py`, per leaf and for the coordinator. +- The milestone cap is $75. At the cap, work stops and a report is written. + +**Status** + +- The high-level status lives in macOS Reminders, managed with the `scheduling-work` skill. +- There is one reminder for M6.5 and one for each level. +- Each reminder is updated when its level closes. diff --git a/__reports__/agent_config/01-notice_consumer_requirements_v1.md b/__reports__/agent_config/01-notice_consumer_requirements_v1.md new file mode 100644 index 00000000..a85cebbc --- /dev/null +++ b/__reports__/agent_config/01-notice_consumer_requirements_v1.md @@ -0,0 +1,19 @@ +# Notice: the HTN eval lane's requirements against the M6.5 plan (v1) + +**Source.** The Candler milestone coordination session passed on the HTN eval lane's positions. No planned HTN experiment needs instruction files or hooks. If one ever adds an instruction-file arm, it would need the four things below. v0 of this notice put two of them to Eliott; he ruled on both on 2026-11-25. + +**Checked against.** [`01-architecture_agent_config_v1.md`](01-architecture_agent_config_v1.md) and the amended roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md). + +## Verdict per requirement + +| # | Requirement | Plan (v1) | Status | +|---|---|---|---| +| a | The file's bytes are a factor level, hashed into the cell digest, so two arms differ only by those bytes. | `instructions.workspace` is a cell value, so it sits in `comparable.values`, which the digest hashes. Gate G2: two levels give two digests. | **Met** | +| b | It is installed at the workspace root, where each harness reads it. | `instructions.workspace` is mounted read-only at `/CLAUDE.md` on Claude Code and `/AGENTS.md` on OpenCode. A global file per harness, `instructions.global.`, is set once for the experiment, and the workspace file overrides or complements it. The mount keeps the file out of the collected outputs and out of the agent's reach (G9), and an input at the same path is refused (G10). | **Met** (was "met in intent" in v0) | +| c | Every run records it in its provenance or manifest. | Both texts are in the manifest's `comparable.values`. Gate G7 adds the files the harness actually loaded, with their scope, to the census. | **Met**, and also proven loaded. | +| d | The evaluator cannot see it, as `request.treatment` is hidden today. | Deferred. The consumer writes the evaluator and knows which instructions the box holds, so no evaluator needs to read them back. Today an evaluator that names one of these paths among its metadata needs receives it, like any cell value. | **Deferred**, until a consumer brings a reason | + +## What changed from v0 + +- (b): v0 argued against the workspace root because a root file is collected as an output and may overwrite a fixture's file. A read-only mount through the existing `mount_inputs` answers both: the tree builder skips it, and a collision is refused rather than shadowed. +- (d): v0 recommended blinding with a gate G10. There is no blinding work. G10 now names the collision refusal. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 0938cab8..fabe429a 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -5,9 +5,13 @@ Instruction files and hooks as per-arm experiment data (M6.5). ## Documents ### Round 00 -- [00-architecture_agent_config_v0.md](00-architecture_agent_config_v0.md) — **latest**. The approved plan: cause, shape, harness check, proof, risks, roadmap. -- [00-notice_consumer_requirements_v0.md](00-notice_consumer_requirements_v0.md) — **latest**. The HTN eval lane's four requirements checked against the plan: three met, evaluator blinding (d) open for Eliott. +- [00-architecture_agent_config_v0.md](00-architecture_agent_config_v0.md) — superseded by v1. The approved plan: cause, shape, harness check, proof, risks, roadmap. +- [00-notice_consumer_requirements_v0.md](00-notice_consumer_requirements_v0.md) — superseded by v1. The HTN eval lane's four requirements checked against the plan: three met, evaluator blinding (d) open for Eliott. + +### Round 01 +- [01-architecture_agent_config_v1.md](01-architecture_agent_config_v1.md) — **latest**. The plan with Eliott's two rulings on the notice: a global instruction file per harness plus a read-only workspace-root file per arm, and evaluator access deferred. Gates G1–G10. +- [01-notice_consumer_requirements_v1.md](01-notice_consumer_requirements_v1.md) — **latest**. The HTN lane's four requirements against v1: three met, evaluator access (d) deferred. ## Status -The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. No leaf has been dispatched. Open decision: whether an evaluator may read `instructions` and `hooks` values (notice above). +The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended for two instruction scopes on 2026-11-25. No leaf has been dispatched, and no decision is open. From 66c0950d4365db56b0df7cb3d6c2ee9c68a4ed5c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 12:51:34 +0900 Subject: [PATCH 05/69] rdm(api): amend M6.5 for the two instruction scopes The leaves now set instructions.global and instructions.workspace in place of instructions.text. The probe also settles where Claude Code's global file loads and whether a read-only root mount is read. The core leaf gains the workspace mount and the collision refusal, which is the new gate G10. Every leaf points at the v1 report. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/README.md | 7 ++++--- __roadmap__/m6_5-agent-config/declaration.md | 19 +++++++++--------- .../m6_5-agent-config/installed/README.md | 2 +- .../installed/install_claude_code.md | 14 ++++++------- .../installed/install_opencode.md | 12 +++++------ .../installed/preflight_check.md | 20 ++++++++++++++----- .../installed/proved/README.md | 2 +- .../installed/proved/e2e_guard.md | 10 +++++----- .../proved/reviewed/adversarial_review.md | 4 ++-- .../m6_5-agent-config/probe_harness_checks.md | 15 ++++++++------ 10 files changed, 60 insertions(+), 45 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index 493a3f5b..4397a3d8 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -1,17 +1,18 @@ # M6.5 Agent configuration as data ## Context -A new root after M6c Integrity (#81, on `origin/main` at `8d82f63b`). It is independent of M7, which is blocked, and of M8, which lies below M7; M8's plugin may later use hooks. The plan is [the architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md). Every leaf runs by its §Execution model: Sonnet implementers and verifiers, a shared codebase whose debt the leaf owns, findings kept in scope or escalated, target-dir slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and a $75 cap. The status is mirrored in macOS Reminders. +A new root after M6c Integrity (#81, on `origin/main` at `8d82f63b`). It is independent of M7, which is blocked, and of M8, which lies below M7; M8's plugin may later use hooks. The plan is [the architecture report, v1](../../__reports__/agent_config/01-architecture_agent_config_v1.md), which applies Eliott's two rulings on the HTN lane's notice to the approved v0. Every leaf runs by its §Execution model: Sonnet implementers and verifiers, a shared codebase whose debt the leaf owns, findings kept in scope or escalated, target-dir slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and a $75 cap. The status is mirrored in macOS Reminders. ## Goal -A consumer gives each arm its own instruction text and hooks as cell values. Candler installs them where each harness looks, and refuses a cell that the harness's own check rejects. +A consumer gives the experiment a global instruction file per harness, each arm its own workspace instruction file and hooks, all as cell values. Candler installs them where each harness looks, the workspace file read-only at the workspace root, and refuses a cell that the harness's own check rejects. ## Pre-conditions - [x] `[cmd]` `git merge-base --is-ancestor 80405b5c origin/main` succeeds (M6c merged) - [x] `[nl]` Eliott approved the plan on 2026-11-25: refuse errors and warnings, take contents inline, and make this a new root +- [x] `[nl]` Eliott ruled on the HTN lane's notice on 2026-11-25: instructions come in two scopes (a global file per harness, and a workspace-root file per arm on both harnesses), and evaluator access to them is deferred ## Success Gates -- ⬜ G1–G9 of the [architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md) hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` +- ⬜ G1–G10 of the [architecture report, v1](../../__reports__/agent_config/01-architecture_agent_config_v1.md) hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` - ⬜ `probe_harness_checks.md`, `declaration.md` and `installed/` are `done` - ⬜ The spend measured from transcripts, coordinator included, is at most $75 - ⬜ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated diff --git a/__roadmap__/m6_5-agent-config/declaration.md b/__roadmap__/m6_5-agent-config/declaration.md index fb004551..1d749378 100644 --- a/__roadmap__/m6_5-agent-config/declaration.md +++ b/__roadmap__/m6_5-agent-config/declaration.md @@ -1,21 +1,22 @@ # Declaration -**Goal**: An experiment can set `instructions.text`, `hooks.claude-code` and `hooks.opencode` as fixed values or factor levels. The cell digest and `inspect` cover them, every driver answers them on the generated pages, and the misuses are refused by name. (P0) +**Goal**: An experiment can set `instructions.global.`, `instructions.workspace`, `hooks.claude-code` and `hooks.opencode` as fixed values or factor levels. The cell digest and `inspect` cover them, every driver answers them on the generated pages, and the misuses are refused by name. (P0) **Estimate**: Sonnet, $8, cap $16. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G1. `candler resolve` of an experiment with `[fixed] instructions.text = "…"` succeeds, and the `inspect` of a run of it shows an `instructions` member. On `8d82f63b` the resolve exits 2 with `experiment.unknown_path` at `/fixed/instructions.text`. -- ⬜ G2. Two levels of `instructions.text` plan two cells with different digests, and two levels of `hooks.claude-code.settings` do the same. On the base, both are `unknown_path`. -- ⬜ G8. `hooks.claude-code` on an OpenCode cell that has no `hooks.opencode` is refused with `experiment.cell_value_missing` at `/fixed/hooks`. A key under `hooks` that names no registered harness is refused with `experiment.cell_value_invalid` at its path. A hook file path with `..` is refused with `format.rel_path_invalid`. On the base, all three are `unknown_path`. -- ⬜ G3 (this level's half). `docs/contract/harness-capabilities.md` has the rows *instructions*, *hooks* and *config check*. Both drivers answer each with `no (…)` saying it is installed from L2, and `cargo nextest run -p candler contract_pages` passes. On the base, no such rows exist. -- ⬜ `experiment.harness_rejected_input` is declared in `docs/contract/codes.toml` with its side (experiment) and its path. No code path raises it yet. -**References**: [Architecture report](../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-schemas/src/servers.rs` (`McpServer`, the precedent); `crates/candler-harness/src/spec.rs:651` (`AgentSetting`) and `:729` (`DriverFact`); `crates/candler-core/src/resolve/paths.rs` (`CONFIGURATION_PATHS`, `settings_set_by`); `crates/candler/src/commands/inspect.rs` (`mcp_of`); `crates/candler/tests/it/guard_inspect_mcp_config.rs` +- ⬜ G1. `candler resolve` of an experiment with `[fixed] instructions.workspace = "…"` succeeds, and the `inspect` of a run of it shows an `instructions` member. On `8d82f63b` the resolve exits 2 with `experiment.unknown_path` at `/fixed/instructions.workspace`. +- ⬜ G2. Two levels of `instructions.workspace` plan two cells with different digests, and two levels of `hooks.claude-code.settings` do the same. On the base, both are `unknown_path`. +- ⬜ G8. `hooks.claude-code` on an OpenCode cell that has no `hooks.opencode` is refused with `experiment.cell_value_missing` at `/fixed/hooks`, and `instructions.global` with no key for the cell's harness at `/fixed/instructions.global`. A key under `hooks` or `instructions.global` that names no registered harness is refused with `experiment.cell_value_invalid` at its path. A hook file path with `..` is refused with `format.rel_path_invalid`. On the base, all three are `unknown_path`. +- ⬜ G3 (this level's half). `docs/contract/harness-capabilities.md` has the rows *instructions: global*, *instructions: workspace*, *hooks* and *config check*. Both drivers answer each with `no (…)` saying it is installed from L2, and `cargo nextest run -p candler contract_pages` passes. On the base, no such rows exist. +- ⬜ `experiment.harness_rejected_input` and `experiment.instructions_collide` are declared in `docs/contract/codes.toml` with their side (experiment) and their path. No code path raises them yet. +- ⬜ `Plan` has a field for read-only workspace files, and the trait names each driver's workspace instruction file (`CLAUDE.md`, `AGENTS.md`). Both drivers leave the field empty, so no run changes. +**References**: [Architecture report, v1](../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-schemas/src/servers.rs` (`McpServer`, the precedent); `crates/candler-harness/src/spec.rs:651` (`AgentSetting`) and `:729` (`DriverFact`); `crates/candler-core/src/resolve/paths.rs` (`CONFIGURATION_PATHS`, `settings_set_by`); `crates/candler/src/commands/inspect.rs` (`mcp_of`); `crates/candler/tests/it/guard_inspect_mcp_config.rs` ## Step 1: Surface, schema and one reader **Goal**: The three values exist as typed cell values, read by one reader. **Implementation Logic**: -Add envelope types beside `McpServer` in `candler-schemas`: `Instructions {text}`, `ClaudeCodeHooks {settings: object, files: map}` and `OpenCodeHooks {plugins: map}`, each with `deny_unknown_fields`. Their contents stay free. Publish them as their own schemas, as `mcp-server.schema.json` is. Add the `instructions` and `hooks` rows to `CONFIGURATION_PATHS`; the names below `hooks` are harness ids. Add `candler_harness::agent_config::{instructions(cell), hooks(cell, harness)}`, the twin of `candler_harness::mcp::servers`, with the refusals of G8. No second reader may exist. +Add envelope types beside `McpServer` in `candler-schemas`: `Instructions {global: map, workspace: text}`, `ClaudeCodeHooks {settings: object, files: map}` and `OpenCodeHooks {plugins: map}`, each with `deny_unknown_fields`. Their contents stay free. Publish them as their own schemas, as `mcp-server.schema.json` is. Add the `instructions` and `hooks` rows to `CONFIGURATION_PATHS`; the names below `hooks` and `instructions.global` are harness ids. Add `candler_harness::agent_config::{instructions(cell), hooks(cell, harness)}`, the twin of `candler_harness::mcp::servers`, with the refusals of G8. No second reader may exist. **Deliverables**: `crates/candler-schemas/src/agent_config.rs` (`Instructions`, `ClaudeCodeHooks`, `OpenCodeHooks`); the published schemas; `crates/candler-core/src/resolve/paths.rs` (rows); `crates/candler-harness/src/agent_config.rs` (`instructions`, `hooks`); unit guards for G2 and G8; `crates/candler-schemas/tests/vectors/manifest/hashed_paths.toml` (the new hashed paths) **Consistency Checks**: `cargo nextest run -p candler-schemas -p candler-harness -p candler-core` (expected: PASS) **Commit**: `feat(api): take instructions and hooks as cell values` @@ -23,7 +24,7 @@ Add envelope types beside `McpServer` in `candler-schemas`: `Instructions {text} ## Step 2: Declaration, answers, pages and inspect **Goal**: Every driver answers the new settings, and a run shows its values. **Implementation Logic**: -Add `AgentSetting::Instructions`, `AgentSetting::Hooks` and `DriverFact::ConfigCheck`. Add the trait methods `config_check(&Plan) -> Option` and `read_config_check(output) -> CheckVerdict`, modelled on `version_probe` and `parse_version`. Both drivers answer `Refused` for now, so the merged level tells the truth. Declare `experiment.harness_rejected_input`. Regenerate the contract pages (`CANDLER_BLESS_CONTRACT=1 cargo nextest run -p candler contract_pages`) and the schemas (`CANDLER_BLESS_SCHEMAS=1 cargo nextest run -p candler-schemas drift`), and add a note on `experiment-file.md` that a consumer hook may approve tool calls, which changes what `permission_mode` means. Teach `inspect` to show `instructions` and `hooks` from `/comparable/values`, as `mcp_of` does, and extend `guard_inspect_mcp_config` or add a sibling guard for G1. +Add `AgentSetting::Instructions(scope)` with the scopes global and workspace, `AgentSetting::Hooks` and `DriverFact::ConfigCheck`. Add the trait methods `config_check(&Plan) -> Option` and `read_config_check(output) -> CheckVerdict`, modelled on `version_probe` and `parse_version`, and the method that names the workspace instruction file. Add the `Plan` field for read-only workspace files, which L2's core leaf mounts. Both drivers answer `Refused` for now and leave the field empty, so the merged level tells the truth. Declare `experiment.harness_rejected_input` and `experiment.instructions_collide`. Regenerate the contract pages (`CANDLER_BLESS_CONTRACT=1 cargo nextest run -p candler contract_pages`) and the schemas (`CANDLER_BLESS_SCHEMAS=1 cargo nextest run -p candler-schemas drift`), and add a note on `experiment-file.md` that a consumer hook may approve tool calls, which changes what `permission_mode` means. Teach `inspect` to show `instructions` and `hooks` from `/comparable/values`, as `mcp_of` does, and extend `guard_inspect_mcp_config` or add a sibling guard for G1. **Deliverables**: `crates/candler-harness/src/spec.rs`, `driver.rs`; both drivers' `answer`/`fact`; `docs/contract/codes.toml`; the regenerated contract pages; `crates/candler/src/commands/inspect.rs`; the G1 guard **Consistency Checks**: `cargo nextest run --workspace` and `cargo nextest run -p candler contract_pages` (expected: PASS) **Commit**: `feat(harness): declare instructions, hooks and the harness check` diff --git a/__roadmap__/m6_5-agent-config/installed/README.md b/__roadmap__/m6_5-agent-config/installed/README.md index 9c0b08b7..fd2f91a1 100644 --- a/__roadmap__/m6_5-agent-config/installed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/README.md @@ -4,7 +4,7 @@ L2 of M6.5. It runs after `probe_harness_checks.md` (which harness checks are reliable) and `declaration.md` (the settings, the one reader, the refusals). Its three leaves touch three separate crates: the Claude Code driver, the OpenCode driver and core. A seam review of the whole diff follows its close. ## Goal -Each driver installs the instruction text and hooks where its harness looks, and records which instruction files loaded. Preflight refuses a cell that a harness check rejects. +Each driver installs the global instruction text and hooks where its harness looks, and names the workspace instruction file, which the core mounts read-only at the workspace root. Each run records which instruction files loaded. Preflight refuses a cell that a harness check rejects, or whose workspace file collides with an input. ## Pre-conditions - [ ] `[cmd]` `git merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds, after L1 has merged diff --git a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md index dd26b5d1..9ba3a964 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md +++ b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md @@ -1,22 +1,22 @@ # Install on Claude Code -**Goal**: On Claude Code, a cell's instruction text loads as project memory and its hooks run, and every run's census names the memory files that loaded. (P0) +**Goal**: On Claude Code, the global text loads from where the probe settled, the workspace text loads as the root `CLAUDE.md`, and the hooks run, and every run's census names the memory files that loaded. (P0) **Estimate**: Sonnet, $7, cap $14. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds -- [ ] `[nl]` The probe report settles (a) and (b) +- [ ] `[nl]` The probe report settles (a), (b), (e) and (f) **Success Gates**: -- ⬜ G3 (Claude Code). The *instructions*, *hooks* and *config check* rows show the Claude Code mapping: `.claude/CLAUDE.md`; the `hooks` key of `.claude/settings.json`, with files under `.claude/hooks/`; and the probe's check or `no (…)`. On the base, no such rows exist. -- ⬜ The plan of a cell with all three values renders `.claude/CLAUDE.md` holding the text and a `.claude/settings.json` whose `hooks` key equals the payload byte for byte as JSON. It places the files under `.claude/hooks/` with mode 0755, and the home `--settings` file holds an `InstructionsLoaded` observer in headless mode as in session mode. On the base, the plan has none of these. +- ⬜ G3 (Claude Code). The *instructions*, *hooks* and *config check* rows show the Claude Code mapping: the global file's place from the probe, and the workspace's root `CLAUDE.md`, read-only; the `hooks` key of `.claude/settings.json`, with files under `.claude/hooks/`; and the probe's check or `no (…)`. On the base, no such rows exist. +- ⬜ The plan of a cell with all four values places the global text where the probe settled, lists `CLAUDE.md` with the workspace text among its read-only workspace files and writes no `CLAUDE.md` itself, and renders a `.claude/settings.json` whose `hooks` key equals the payload byte for byte as JSON. It places the files under `.claude/hooks/` with mode 0755, and the home `--settings` file holds an `InstructionsLoaded` observer in headless mode as in session mode. On the base, the plan has none of these. - ⬜ A cell without these values renders the same `.claude/settings.json` as on the base. Only the home observers file is added. -- ⬜ The census of a run that recorded `InstructionsLoaded` lists `{path: .claude/CLAUDE.md, scope: Project}`, read from a recorded `.candler/hooks.jsonl` fixture. +- ⬜ The census of a run that recorded `InstructionsLoaded` lists the global file (User, or Project for the parent directory) and `{path: CLAUDE.md, scope: Project}`, read from a recorded `.candler/hooks.jsonl` fixture. - ⬜ An adversarial Sonnet review finds no way for a payload to disable Candler's observers, or to write outside `.claude/`. -**References**: [Architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-claude-code/src/prepare.rs` (`render_settings`), `session.rs` (`HOOK_EVENTS`, `hooks()`), `discovery.rs` (`EXCLUDED_DIRS`); the probe report +**References**: [Architecture report, v1](../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-claude-code/src/prepare.rs` (`render_settings`), `session.rs` (`HOOK_EVENTS`, `hooks()`), `discovery.rs` (`EXCLUDED_DIRS`); the probe report ## Step 1: Render and install **Goal**: The driver writes the values where Claude Code reads them. **Implementation Logic**: -Extend `render_settings` with the `hooks` key. Do not write a second settings renderer. Add the instructions file and the hook files as `PreparedFile`s. Move the observation hooks file so it is passed in headless mode too, and add `InstructionsLoaded` to `HOOK_EVENTS`. Remove whatever this makes obsolete. +Extend `render_settings` with the `hooks` key. Do not write a second settings renderer. Add the global file and the hook files as `PreparedFile`s, and the workspace text as the plan's read-only workspace file. If the probe chose the home, add `user` to the setting sources. Move the observation hooks file so it is passed in headless mode too, and add `InstructionsLoaded` to `HOOK_EVENTS`. Remove whatever this makes obsolete. **Deliverables**: `crates/candler-harness-claude-code/src/prepare.rs`, `session.rs`, `driver.rs` (`plan`, `answer`, `fact`); plan guards **Consistency Checks**: `cargo nextest run -p candler-harness-claude-code` (expected: PASS) **Commit**: `feat(harness): install instructions and hooks on Claude Code` diff --git a/__roadmap__/m6_5-agent-config/installed/install_opencode.md b/__roadmap__/m6_5-agent-config/installed/install_opencode.md index df017db8..4aafad5e 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_opencode.md +++ b/__roadmap__/m6_5-agent-config/installed/install_opencode.md @@ -1,20 +1,20 @@ # Install on OpenCode -**Goal**: On OpenCode, a cell's instruction text loads as the global `AGENTS.md` and its plugins load locally, and every run's census names the instruction files that loaded. (P0) +**Goal**: On OpenCode, the global text loads as the global `AGENTS.md`, the workspace text as the root `AGENTS.md`, and the plugins load locally, and every run's census names the instruction files that loaded. (P0) **Estimate**: Sonnet, $6, cap $12. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds -- [ ] `[nl]` The probe report settles (c) and (d) +- [ ] `[nl]` The probe report settles (c), (d) and (f) **Success Gates**: -- ⬜ G3 (OpenCode). The *instructions*, *hooks* and *config check* rows show the OpenCode mapping: `$XDG_CONFIG_HOME/opencode/AGENTS.md`; local plugins in `$XDG_CONFIG_HOME/opencode/plugins/`; and the probe's check or `no (…)`. On the base, no such rows exist. -- ⬜ The plan of a cell with `instructions.text` and `hooks.opencode` places `AGENTS.md` and each plugin in the home, byte for byte, and nothing in the workspace. On the base, the plan has neither. +- ⬜ G3 (OpenCode). The *instructions*, *hooks* and *config check* rows show the OpenCode mapping: `$XDG_CONFIG_HOME/opencode/AGENTS.md`, and the workspace's root `AGENTS.md`, read-only; local plugins in `$XDG_CONFIG_HOME/opencode/plugins/`; and the probe's check or `no (…)`. On the base, no such rows exist. +- ⬜ The plan of a cell with `instructions.global.opencode`, `instructions.workspace` and `hooks.opencode` places the global `AGENTS.md` and each plugin in the home, byte for byte, lists `AGENTS.md` with the workspace text among its read-only workspace files, and writes nothing in the workspace itself. On the base, the plan has none of these. - ⬜ The census lists each `Instructions from: ` block of the first request the gateway saw, read from a recorded request fixture. -**References**: [Architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-opencode/src/prepare.rs` (`render_config`, `PreparedFile::in_home`); the OpenCode V2 evidence in the report +**References**: [Architecture report, v1](../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-opencode/src/prepare.rs` (`render_config`, `PreparedFile::in_home`); the OpenCode V2 evidence in the report ## Step 1: Install, census and check **Goal**: The driver writes the values where OpenCode reads them, and a run says what loaded. **Implementation Logic**: -Add the instructions file and the plugin files as home `PreparedFile`s next to `render_config`, in the same config directory. Extend the census source (the first request) with the instruction blocks. Implement `config_check` and `read_config_check` from the probe. Flip the answers to Mapped. +Add the global file and the plugin files as home `PreparedFile`s, and the workspace text as the plan's read-only workspace file, next to `render_config`, in the same config directory. Extend the census source (the first request) with the instruction blocks. Implement `config_check` and `read_config_check` from the probe. Flip the answers to Mapped. **Deliverables**: `crates/candler-harness-opencode/src/prepare.rs`, `driver.rs`, the census reader; plan and census guards **Consistency Checks**: `cargo nextest run -p candler-harness-opencode` and `cargo nextest run -p candler contract_pages` (expected: PASS) **Commit**: `feat(harness): install instructions and plugins on OpenCode` diff --git a/__roadmap__/m6_5-agent-config/installed/preflight_check.md b/__roadmap__/m6_5-agent-config/installed/preflight_check.md index e3e71693..c6fcb27e 100644 --- a/__roadmap__/m6_5-agent-config/installed/preflight_check.md +++ b/__roadmap__/m6_5-agent-config/installed/preflight_check.md @@ -1,20 +1,30 @@ # Preflight check -**Goal**: Before any run, `candler resolve` runs each harness's own check on what Candler installed. It refuses a cell with any finding, quoting the harness, and records a clean verdict. (P0) -**Estimate**: Sonnet, $7, cap $14. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Goal**: Before any run, `candler resolve` runs each harness's own check on what Candler installed. It refuses a cell with any finding, quoting the harness, and records a clean verdict. The core also mounts each plan's read-only workspace file through `mount_inputs`, and refuses one that collides with a declared input. (P0) +**Estimate**: Sonnet, $9, cap $18. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: - ⬜ With a driver whose check reports a finding, `candler resolve` exits 2 with `experiment.harness_rejected_input`. The message names what was installed, where, the harness, and the harness's output. On the base, no such step exists, and the same experiment is refused earlier with `unknown_path`. - ⬜ With a clean check, the verdict is stored beside the harness identity in the run's provenance. With a driver whose `config_check` is `None`, the cell is not refused and nothing is stored as checked. -- ⬜ Cells that share a harness, image, instructions and hooks run the check once, which is counted on the step's image service. +- ⬜ Cells that share a harness, image and prepared files run the check once, which is counted on the step's image service. +- ⬜ G9 (core half). With a fake driver whose plan lists a read-only workspace file, the run's workspace holds it at the root, a write to it fails, it is not among the collected outputs, and the run is not sealed `input_leak`. On the base, `Plan` has no such field. +- ⬜ G10. With `instructions.workspace` set, an input declared at the workspace instruction file's path is refused at `resolve` with `experiment.instructions_collide`, naming the input. On the base, the experiment is refused earlier with `unknown_path`. - ⬜ An adversarial Sonnet review finds no path where a finding lets the cell run, and no check container that outlives the step. -**References**: [Architecture report](../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-core/src/resolve/steps/` (`HarnessIdentityStep`, the precedent); `ImageService` +**References**: [Architecture report, v1](../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-core/src/resolve/steps/` (`HarnessIdentityStep`, the precedent); `ImageService` ## Step 1: The step **Goal**: A preflight step that asks the harness and refuses on its answer. **Implementation Logic**: -Add `HarnessConfigStep` next to `HarnessIdentityStep`, reusing its image-service path. It dedupes by (harness, image, instructions, hooks). For each distinct entry it starts a no-network container from the cell's image, places the driver's prepared files there, runs `config_check`, reads the verdict with `read_config_check`, and removes the container. Use a fake driver in the core guards; the real harnesses are L3's. +Add `HarnessConfigStep` next to `HarnessIdentityStep`, reusing its image-service path. It dedupes by (harness, image, digest of the prepared files). For each distinct entry it starts a no-network container from the cell's image, places the driver's prepared files there and mounts the read-only workspace file, runs `config_check`, reads the verdict with `read_config_check`, and removes the container. Use a fake driver in the core guards; the real harnesses are L3's. **Deliverables**: `crates/candler-core/src/resolve/steps/config_check.rs` (`HarnessConfigStep`); the provenance field; core guards **Consistency Checks**: `cargo nextest run -p candler-core` (expected: PASS) **Commit**: `feat(api): refuse a cell its harness rejects` + +## Step 2: The workspace file +**Goal**: The plan's read-only workspace file reaches the workspace root the way an input does. +**Implementation Logic**: +Store each read-only workspace file's text and add it to the mount list that `mount_inputs` builds, so the existing re-check covers it with the inputs. Do not write a second mount path. Before planning the runs, compare the file's path with every path the declared inputs mount, and refuse a match with `experiment.instructions_collide`. Use a fake driver in the core guards. +**Deliverables**: `crates/candler-core/src/runner/exec/mod.rs` (`mount_inputs`); the collision check in resolve; core guards for G9 and G10 +**Consistency Checks**: `cargo nextest run -p candler-core` (expected: PASS) +**Commit**: `feat(api): mount the workspace instruction file read-only` diff --git a/__roadmap__/m6_5-agent-config/installed/proved/README.md b/__roadmap__/m6_5-agent-config/installed/proved/README.md index 75bdb58a..54e0eafc 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/README.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/README.md @@ -4,7 +4,7 @@ L3 of M6.5. It runs after both drivers install the values and the preflight step refuses. It proves the feature end to end on the real harnesses, against the scripted fake model, with no RiVault run. ## Goal -One experiment shows, on both harnesses, the arm's own instructions reaching the model, a consumer hook acting on a tool call, the census naming the loaded file, and an invalid payload refused before the run. +One experiment shows, on both harnesses, the global and the arm's own workspace instructions reaching the model, a consumer hook acting on a tool call, the census naming both loaded files, and an invalid payload refused before the run. ## Pre-conditions - [ ] `[cmd]` `git merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds, after L2 has merged diff --git a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md index ea1b8b21..a201aa32 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md @@ -5,18 +5,18 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G4. On each harness, the fake model's recorded requests for arm A hold text A and never text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. +- ⬜ G4. On each harness, the fake model's recorded requests for arm A hold the global text and workspace text A, and never workspace text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. - ⬜ G5. The scripted tool call is answered with an error carrying the hook's marker: a Claude Code PreToolUse script exits 2, and an OpenCode plugin throws in `execute.before`. On the base, there is no hook and the call succeeds. - ⬜ G6. On real images, an invalid payload (a Claude Code hooks entry on an unknown event; an OpenCode plugin with no default export) is refused at `resolve` with `experiment.harness_rejected_input`, quoting the harness, and the valid payload passes. On the base, it is `unknown_path`. -- ⬜ G7. Each run's census lists the installed instruction file: `.claude/CLAUDE.md` (Project), and the global `AGENTS.md`. -- ⬜ G9. No installed file is among any run's collected outputs, and no run is sealed `input_leak`. +- ⬜ G7. Each run's census lists both installed instruction files with their scope: on Claude Code the global file where the probe settled and the root `CLAUDE.md` (Project); on OpenCode the global `AGENTS.md` and the root `AGENTS.md`. +- ⬜ G9. No installed file, the root instruction file included, is among any run's collected outputs, and no run is sealed `input_leak`. - ⬜ The guards run in a pass that lists them as passed, not skipped (leaf template, convention 3). `docker ps -a` shows none of their containers afterwards. -**References**: [Architecture report](../../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs` (`parity_one_installed_server_one_traced_call`, the model to follow); `assets/docker/fakemodel` +**References**: [Architecture report, v1](../../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs` (`parity_one_installed_server_one_traced_call`, the model to follow); `assets/docker/fakemodel` ## Step 1: The guards **Goal**: Two guards that read what a consumer reads. **Implementation Logic**: -`guard_agent_config_e2e` runs one experiment with two arms (text A or B) and one hook per harness on both harnesses. It reads `inspect`'s members, the rendered files in the run, the fake model's records and the stored census. `guard_harness_check_refuses` runs `resolve` on real images with no model. Reuse the parity e2e's helpers; do not copy them. The check's output must list both guards as passed. +`guard_agent_config_e2e` runs one experiment with a global text per harness, two arms (workspace text A or B) and one hook per harness on both harnesses. It reads `inspect`'s members, the rendered files in the run, the fake model's records and the stored census. `guard_harness_check_refuses` runs `resolve` on real images with no model. Reuse the parity e2e's helpers; do not copy them. The check's output must list both guards as passed. **Deliverables**: `crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs`; the fake model's script for the blocked call **Consistency Checks**: `cargo nextest run -p candler --run-ignored all -E 'test(agent_config) | test(harness_check)'` (expected: PASS) **Commit**: `test(cli): prove instructions and hooks on both harnesses` diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md index d622b423..1a4b937a 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md @@ -5,10 +5,10 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ `__reports__/agent_config/02-review_m6_5_v0.md` names each gate G1–G9 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. +- ⬜ `__reports__/agent_config/03-review_m6_5_v0.md` names each gate G1–G10 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. - ⬜ The report lists any debt left behind (a second reader, a duplicated helper, dead code, a leftover script), each fixed in this leaf or filed as a notice. An out-of-scope finding is filed as an observation and escalated. - ⬜ `__reports__/agent_config/03-knowledge_transfer_m6_5_v0.md` records the spend measured per leaf against the $75 cap. -**References**: [Architecture report](../../../../../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model +**References**: [Architecture report, v1](../../../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model ## Step 1: Review and close **Goal**: An independent verdict, and the milestone's record. diff --git a/__roadmap__/m6_5-agent-config/probe_harness_checks.md b/__roadmap__/m6_5-agent-config/probe_harness_checks.md index 7b04b62a..7c29f97c 100644 --- a/__roadmap__/m6_5-agent-config/probe_harness_checks.md +++ b/__roadmap__/m6_5-agent-config/probe_harness_checks.md @@ -1,24 +1,27 @@ # Probe harness checks -**Goal**: The plan names, for each harness, a command that reports whether Candler's install of instructions and hooks is valid, and says what that command does without a TTY and without network. Where no such command exists, the plan says `no`. (P0, it decides L2) +**Goal**: The plan names, for each harness, a command that reports whether Candler's install of instructions and hooks is valid, and says what that command does without a TTY and without network. Where no such command exists, the plan says `no`. It also settles where Claude Code's global file loads, and whether both harnesses read a read-only file mounted at the workspace root. (P0, it decides L2) **Estimate**: Sonnet, $3, cap $6. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ `__reports__/agent_config/01-findings_probe_harness_checks_v0.md` answers every question of Step 1. Each answer quotes the command, its exit code and its output, captured in the `base` image (Claude Code 2.1.311) or the `base-opencode` image (OpenCode 2.2.7). +- ⬜ `__reports__/agent_config/02-findings_probe_harness_checks_v0.md` answers every question of Step 1. Each answer quotes the command, its exit code and its output, captured in the `base` image (Claude Code 2.1.311) or the `base-opencode` image (OpenCode 2.2.7). +- ⬜ The report names where L2 installs Claude Code's global file (the run's home with `user` among the setting sources, or the workspace's parent directory) and why, and the order in which each harness puts the global and the workspace text in front of the model. - ⬜ For each harness, the report names the command that L2 wires into `config_check`, and what in its output counts as an error or a warning. If no command is reliable, the report says `no` and why. - ⬜ `docker ps -a --filter label=m6_5-probe -q` prints nothing at the leaf's close. -**References**: [Architecture report](../__reports__/agent_config/00-architecture_agent_config_v0.md) — the shapes, the error model, the invariants and §Execution model +**References**: [Architecture report, v1](../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model ## Step 1: Probe the checks **Goal**: Measured answers, not documentation, for each check the plan relies on. **Implementation Logic**: Use throwaway containers labelled `m6_5-probe`, with network `none`. Write three installs by hand: a valid one, an error one (bad JSON in `.claude/settings.json`; an OpenCode plugin with no default export) and a warning one (a Claude Code hook on an unknown event). They are the files L2 will render. Ask: (a) Does `claude doctor` run without a TTY and without network? What is its exit code? Does it report errors and warnings in the project settings' hooks? -(b) Does `InstructionsLoaded` fire under `claude --print --setting-sources project,local` for `.claude/CLAUDE.md`, and what does its payload hold? Use a gateway that refuses the request, so no model is needed. +(b) Does `InstructionsLoaded` fire under `claude --print --setting-sources project,local` for the workspace's `CLAUDE.md`, and what does its payload hold? Use a gateway that refuses the request, so no model is needed. (c) Do `opencode debug config` and `opencode plugin list` need a server or network? Do they show a rejected config and a failed local plugin? (d) Does OpenCode's `` directory follow `XDG_CONFIG_HOME`, so that `$XDG_CONFIG_HOME/opencode/AGENTS.md` and `$XDG_CONFIG_HOME/opencode/plugins/` load? +(e) Under `--setting-sources user,project,local` with a home that holds only `~/.claude/CLAUDE.md` and Candler's files, does that file load, and does `user` load anything else? Does a `CLAUDE.md` in the workspace's parent directory load instead? +(f) Is a single file bind-mounted read-only at the workspace root (`/work/CLAUDE.md`, `/work/AGENTS.md`) read by each harness, as `InstructionsLoaded` or an `Instructions from:` block shows? In which order do the global and the workspace text reach the model? This step changes no product code. -**Deliverables**: `__reports__/agent_config/01-findings_probe_harness_checks_v0.md`, written with `writing-reports`, type findings -**Consistency Checks**: `test -s __reports__/agent_config/01-findings_probe_harness_checks_v0.md` (expected: PASS) +**Deliverables**: `__reports__/agent_config/02-findings_probe_harness_checks_v0.md`, written with `writing-reports`, type findings +**Consistency Checks**: `test -s __reports__/agent_config/02-findings_probe_harness_checks_v0.md` (expected: PASS) **Commit**: `reports(api): probe the harness checks for instructions and hooks` From 3a245da18748eaca3d74000c87d125c4408ecb86 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 13:20:07 +0900 Subject: [PATCH 06/69] reports(api): plan a live, trace-read proof for M6.5 (v2) The proof reads the trace, as a consumer does: a context_start event from the gateway's first request shows both instruction texts and a session-start hook marker, against the fake model and live on RiVault. Gates G11-G13; cap $85. Co-Authored-By: Claude Opus 5.5 --- .../02-architecture_agent_config_v2.md | 347 ++++++++++++++++++ __reports__/agent_config/README.md | 7 +- 2 files changed, 352 insertions(+), 2 deletions(-) create mode 100644 __reports__/agent_config/02-architecture_agent_config_v2.md diff --git a/__reports__/agent_config/02-architecture_agent_config_v2.md b/__reports__/agent_config/02-architecture_agent_config_v2.md new file mode 100644 index 00000000..683f40df --- /dev/null +++ b/__reports__/agent_config/02-architecture_agent_config_v2.md @@ -0,0 +1,347 @@ +# Agent configuration as data — Architecture Analysis (v2) + +M6.5 makes instruction files (`CLAUDE.md`, `AGENTS.md`) and hooks values of an experiment cell. Each driver installs them where its harness looks. Before the agents run, the harness's own check reports on what Candler installed, and any finding refuses the cell. The plan was approved on 2026-11-25. The roadmap is [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md). + +**What changed since v1.** Eliott ruled on how the feature is proved: + +- **Instructions.** A live run's trace must show the exact global and workspace texts in the agent's starting system prompt. +- **Hooks.** A hook sure to fire, at session start, must show in the same live trace. + +Today's trace cannot show either, so v2 adds a harness-neutral trace event, `context_start`, recorded by the gateway from each run's first model request, a new L1 leaf that builds it, gates G11–G13, and a live RiVault confirmation run in L3. See §Live trace proof. + +**What changed from v0 to v1.** Eliott ruled on two points the [consumer notice](00-notice_consumer_requirements_v0.md) raised: + +- Instructions come in **two scopes**. A *global* file per harness is set for the whole experiment. A *workspace* file is set per arm and is installed at the workspace root on both harnesses, where it overrides or complements the global one. v0 had one value, installed at `.claude/CLAUDE.md` on Claude Code and at the global `AGENTS.md` on OpenCode. +- **Evaluator access is deferred.** The consumer writes the evaluator and already knows which instructions the box holds, so no evaluator needs to read them back. No gate is added; the item sits under Out of scope until a consumer brings a reason. + +The sections below are v0 with all these rulings applied. §Execution model is unchanged except for the cap and the leaves that get an adversarial review. + +## Executive Summary + +| Question | Answer | +|---|---| +| Cause removed | Instruction files and hooks are not `AgentSetting`s. So no driver answers for them, no page says where they go, no digest covers them, and nothing refuses a cell whose harness drops them. | +| Shape | New cell values: `instructions.global.`, `instructions.workspace`, `hooks.claude-code` and `hooks.opencode`. All are inline, exactly like `mcp.servers`. | +| Two scopes | `instructions.global` is meant for `[fixed]`: one text per harness, shared by every arm. `instructions.workspace` is meant to be a factor: one text per arm, the same on both harnesses, installed as the workspace's root `CLAUDE.md` or `AGENTS.md`. | +| Translation | None. The workspace text goes verbatim to each harness's own file name. Each harness gets its own global text and its own hooks payload, installed verbatim. | +| Boundary | Candler guarantees the installation. The harness judges the content. | +| Harness check finds an error or a warning | Refused: `experiment.harness_rejected_input`. | +| Proof | From the trace, as a consumer reads it: a guard on the real harnesses against the scripted fake model, then a live confirmation run on RiVault. Both find the exact instruction texts and a session-start hook's marker in the trace's `context_start` event. | +| Cost | About $72. Cap $85. | + +**Rulings** + +| Choice | Ruling | +|---|---| +| A harness finding | Refuse errors and warnings alike. | +| Where file contents come from | Inline text in the cell. There is no file-reference mechanism. | +| Placement of the work | A new roadmap root, M6.5. Its high-level status is kept in macOS Reminders. | +| Instruction scopes (2026-11-25, after the notice) | A global file per harness for the experiment, and a workspace-root file per arm that overrides or complements it, on both harnesses. | +| Evaluator access (2026-11-25, after the notice) | Deferred. No evaluator has a reason to read the instructions back from the box. | +| Proof (2026-11-25, on the v1 plan) | Live, from the trace: both exact instruction texts in the starting system prompt, and a session-start hook's marker. | + +**Reading of "inputs".** Eliott wrote that the global files belong in Candler's *inputs*. This plan reads that as "set once for the whole experiment", and makes `instructions.global` a cell value written in `[fixed]`, not an `inputs` entry. Three reasons: an `inputs` entry lands in the workspace and is collected, which is where the global file must not be; it is not part of `comparable.values`, so the digest and `inspect` would not cover it; and the inline ruling already covers file contents. Nothing refuses varying `instructions.global` as a factor, since a consumer may want that. + +## Current State + +Today, an `inputs` entry is the only way to put a file in front of the agent. It fails here in four ways: + +1. It applies to the whole experiment, so every arm's agent sees every arm's files. +2. The file needs a different name for each harness. +3. A file at the workspace root is collected as an output, so it is graded as the agent's work, and the agent can edit it. +4. It cannot reach `.claude/settings.json`, which the Claude Code driver renders. + +**Where each harness looks** + +| Harness (pinned) | Instruction files it reads | Hooks it runs | Evidence | +|---|---|---|---| +| Claude Code 2.1.311 | Project: `/CLAUDE.md` or `/.claude/CLAUDE.md`, and `CLAUDE.md` in each parent directory. User: `~/.claude/CLAUDE.md`, which loads only with `user` among the setting sources; the driver passes `--setting-sources project,local`. | The `hooks` key of any settings file in scope. All matching hooks run, and their results merge. | Context7 `/websites/code_claude` | +| OpenCode V2 2.2.7 | `AGENTS.md` only, never `CLAUDE.md`: walking up from the cwd to `$HOME`, plus the global `/AGENTS.md`. | JS/TS plugins (`Plugin.define`). Local ones in `/plugins/` skip npm. | Context7 `/websites/opencode_ai/v2`; `config/plugin/instruction.ts:84-94` and `plugin/module.ts:109-110` at v2.2.7 | + +**How each harness fails on bad input** + +| Harness | A whole file is rejected | One entry is rejected | Its own check | +|---|---|---|---| +| Claude Code | A *Settings Error* (bad JSON, or a value the schema rejects): the file is not applied. | A *Settings Warning* (for example an unknown hook event): that entry is skipped and the rest applies. | `claude doctor`. Its exit code and whether it runs without a TTY are not documented, so the probe settles them. | +| OpenCode | A config document is dropped with a warning. A plugin is logged as failed and disabled. Startup continues. | Unknown config keys are ignored. | `opencode debug config` and `opencode plugin list`. `plugin check` covers package plugins only. | + +**What the core already does for a workspace-root file.** `mount_inputs` (`crates/candler-core/src/runner/exec/mod.rs:146`) bind-mounts each input file read-only into the workspace and re-checks the whole mount list. The output tree builder lists no path under a read-only mount point, so such a file is never collected. `input_leak` (`crates/candler-core/src/runner/evidence/leak.rs:10`) seals a run only when an output's digest equals an input's. The workspace instruction file reuses this path, so it is neither collected nor editable. + +## Proposed State + +```mermaid +flowchart LR + subgraph cell[Experiment cell] + IG["instructions.global.<harness>
(fixed, per harness)"] + IW["instructions.workspace
(factor, per arm)"] + HC["hooks.claude-code
{settings, files}"] + HO["hooks.opencode
{plugins}"] + end + R["agent_config reader
(one reader)"] + cell --> R + R --> CC["Claude Code prepare"] + R --> OC["OpenCode prepare"] + CC --> CCF["global: home, scope set by the probe
.claude/settings.json hooks key
.claude/hooks/*"] + OC --> OCF["global: $XDG_CONFIG_HOME/opencode/AGENTS.md
$XDG_CONFIG_HOME/opencode/plugins/*"] + CC --> WF["read-only file at the workspace root
CLAUDE.md or AGENTS.md"] + OC --> WF + WF --> MI["core: mount_inputs
(the existing read-only mount)"] + CCF --> PF["HarnessConfigStep
(preflight, no network)"] + OCF --> PF + MI --> PF + PF -- "finding" --> REF["experiment.harness_rejected_input"] + PF -- "clean" --> RUN["run"] + RUN --> CEN["census: instruction files loaded, with scope"] +``` + +**Where each value lands** + +| Value | Claude Code | OpenCode | Collected as output? | +|---|---|---|---| +| `instructions.global.` | `~/.claude/CLAUDE.md` in the run's home, with `user` added to the setting sources, if the probe shows that loads nothing else from that home; else the parent directory of the workspace, which Claude Code walks. | `$XDG_CONFIG_HOME/opencode/AGENTS.md` (global scope, in the home) | No. The home and the workspace's parent are not collected. | +| `instructions.workspace` | `/CLAUDE.md` | `/AGENTS.md` | No. It is a read-only mount, which the tree builder skips. | +| Hooks configuration | `hooks.settings` goes verbatim under the `hooks` key of `.claude/settings.json`. | none (OpenCode hooks are code) | No | +| Hook files | `.claude/hooks/`, mode 0755 | `$XDG_CONFIG_HOME/opencode/plugins/` | No | + +**How the workspace file reaches the root.** The driver does not write it into the workspace. Its plan lists it as a read-only workspace file: a name (`CLAUDE.md` or `AGENTS.md`) and its text. The core stores the text and mounts it through `mount_inputs`, beside the declared inputs, so one mount path and one re-check cover both. The plan field and the trait method that names the file are declared in L1; the drivers fill them in L2; the core mounts them in L2. + +**Override or complement.** Both harnesses load the global file and the workspace file together. Which one the model reads as overriding is each harness's own rule: Claude Code ranks project memory over user memory, and OpenCode concatenates the files it finds. The probe records the order in which each harness puts the two texts in front of the model, and the capability page states it. + +Candler's own observation hooks stay in the home `--settings` file. `InstructionsLoaded` is added to them, and that file is passed in headless mode too. Since only the `hooks` key is taken from the consumer, the consumer cannot switch the observers off. + +## Key Flows + +```mermaid +sequenceDiagram + participant C as candler resolve + participant D as driver + participant K as check container (cell image, no network) + participant H as harness check + C->>D: plan(cell) + D-->>C: prepared files, read-only workspace file, config_check() + C->>C: the workspace file's path collides with an input's? refuse + C->>K: place prepared files, mount the workspace file read-only + K->>H: claude doctor / opencode debug config + plugin list + H-->>C: output, exit + C->>D: read_config_check(output) + alt any error or warning + C-->>C: refuse cell, harness_rejected_input, exit 2 + else clean + C-->>C: record verdict beside harness identity + end +``` + +The check runs once for each distinct combination of harness, image and prepared files, not once per run. + +## Live trace proof + +**The gap.** The normalised trace has no place for the agent's starting context. Its event kinds (`crates/candler-schemas/src/trace.rs:901`, `KnownKind`) are `user_message`, `assistant_message`, `tool_call`, `tool_result`, `notification` and `usage`. Claude Code's stream-json does not carry the system prompt, and the gateway logs only the sequence number and the tool names of each request (`crates/candler-core/tests/it/guard_census_gateway.rs`). No trace today can show that an instruction reached the model. + +**The event.** The gateway sees every request of every harness, so it is the neutral source, as it already is for OpenCode's census. + +```mermaid +flowchart LR + H["harness (either)"] -- "first model request" --> G["gateway"] + G -- "log: run, tag, seq 0,
system text, first message" --> L["gateway log"] + L --> RD["core: the one gateway-log reader
(the census reader, extended)"] + RD --> T["trace: context_start {system, first_message},
the session's first event"] +``` + +| Member | Holds | +|---|---| +| `system` | The system text of the run's first model request, verbatim. | +| `first_message` | The first message of that request, verbatim. Claude Code places some hook output there. | + +- One event per session, from the first request only. +- The change is additive to the trace schema, so it is a minor wire bump, and a trace written before it still reads. +- One reader of the gateway log serves both the census and this event. A second reader is debt. + +**What the proof reads.** + +| Proof | Read from the trace | Arms | +|---|---|---| +| Instructions | `context_start.system` contains the global text and the arm's workspace text verbatim, and never the other arm's workspace text. | two arms, workspace text A or B | +| Hooks | A session-start hook prints a fixed marker. The marker is in `context_start`, in the system text or the first message, as the harness places it. | every arm | + +On Claude Code the hook is `SessionStart`. On OpenCode it is a plugin hook that adds to the system text, or the nearest session-start hook. The probe's question (g) settles which hook fires in a headless run and where its output lands. If a harness has none whose output reaches the first request, the plan returns to Eliott before L2. + +**Twice.** The guard `guard_agent_config_e2e` reads the stored trace against the fake model, so the proof is deterministic. Then one live `candler run` on RiVault, on both harnesses with two arms and one replicate each, reads the same members from its stored traces. Reasoning-Small is enough because the run tests reachability, not scores. A findings report quotes the excerpts. + +## Contracts & Invariants + +**Surface** + +| Path | Type | Refusal on misuse | +|---|---|---| +| `instructions.global` | a table keyed by harness id; each value a string | `experiment.cell_value_invalid` (unknown harness key); `experiment.cell_value_missing` (no key for the cell's harness) | +| `instructions.workspace` | string | `experiment.document_invalid` (wrong type) | +| `hooks.` | an envelope with `deny_unknown_fields`; contents free | `experiment.cell_value_invalid` (unknown harness key); `experiment.cell_value_missing` (no key for the cell's harness) | +| `hooks.claude-code.settings` | object, verbatim | judged by the harness only | +| `hooks.claude-code.files` | map from a relative path to text | `format.rel_path_invalid` | +| `hooks.opencode.plugins` | map from a file name to text | `format.rel_path_invalid` | + +**Declaration** + +- Two new settings, `AgentSetting::Instructions(scope)` with the scopes global and workspace, and `AgentSetting::Hooks`. Both drivers answer each. +- A new `DriverFact::ConfigCheck`. +- New trait methods: + - `config_check(&Plan) -> Option` + - `read_config_check(output) -> CheckVerdict` + - the name of the workspace instruction file (`CLAUDE.md` or `AGENTS.md`) +- A `Plan` field for read-only workspace files, which the core mounts. + +**Error model** + +| When | Code | Side to fix | +|---|---|---| +| The cell has a `hooks` or `instructions.global` table but no entry for its own harness | `experiment.cell_value_missing` | experiment | +| `instructions.workspace` is set and a declared input also mounts a file at the workspace instruction file's path | `experiment.instructions_collide` (new), at `/fixed/instructions.workspace` or the factor's path, naming the input. The file is refused, never shadowed. | experiment | +| The harness's own check reports an error or a warning | `experiment.harness_rejected_input` (new). Message: "Candler installed X at Y; H rejects it: «output»" | experiment | + +**Invariants** + +1. Every value is in the cell, so the cell digest, factor levels and `inspect` cover it. +2. One reader, `candler_harness::agent_config`, serves every consumer of these values. +3. No installed file appears among a run's collected outputs. The workspace file is a read-only mount, and every other file lives under `.claude/` or the home. +4. The agent cannot change either instruction file. +5. A cell is never run with part of its declared configuration dropped or shadowed. Candler refuses the cell instead. +6. Candler's observation hooks cannot be disabled by the consumer's payload. +7. Every run's census names the instruction files the harness loaded, with their scope. That includes a fixture's own file when no workspace text is set. +8. Every session's trace begins with `context_start`, holding the first request's system text and first message as the gateway saw them. + +## Alternatives Considered + +| Decision | Options | Chosen | Tradeoff accepted | +|---|---|---|---| +| Hooks payload | Shared and translated, or verbatim per harness | Verbatim per harness | An arm on two harnesses needs two payloads. Translation is impossible in general anyway: JSON plus shell on one side, JS modules on the other. | +| Where file contents come from | Inline text, file references, or `inputs` | Inline text | Long files are pasted or generated into the TOML. The alternative was a new "file value" mechanism, about $6 and one more leaf. `inputs` reach every arm. | +| A harness finding | Refuse both, refuse errors and warn on warnings, or warn only | Refuse both | A harmless deprecation notice also refuses. In exchange, an arm never runs silently without part of its hooks. | +| Instruction scopes | One value (v0), or a global value per harness plus a workspace value per arm | Two scopes (Eliott) | Two values to learn. In exchange, the shared part is written once, and each arm's part sits where both harnesses read a project file. | +| Global file as an `inputs` entry or a cell value | `inputs`, or `instructions.global` in `[fixed]` | Cell value | It is not written in the `inputs` array. In exchange, the digest covers it and it never lands in the workspace. | +| Workspace file written or mounted | Written by the driver into the workspace, or mounted read-only by the core | Mounted | The core gains a source of mounts besides inputs. In exchange, the file is not collected, not graded, not editable, and a collision is found by the existing re-check. | +| Where the proof reads | The fake model's records, the census, or the trace | The trace (Eliott) | A new trace event and a gateway change. In exchange, the proof reads what a consumer reads. | +| Source of the starting context | Each harness's own stream, or the gateway | The gateway | The gateway log grows by one request's text per run. In exchange, both harnesses give the same event, and Claude Code's stream does not carry the system prompt anyway. | +| Proof run | The fake model, a live RiVault run, or both | Both | One live run of about $3. In exchange, the guard stays deterministic and the live run confirms it on a real model. | + +## Risks & Mitigations + +| Risk | Mitigation | +|---|---| +| `claude doctor` needs a TTY or network, or says nothing about hooks. | The level-1 probe settles it. If no check is reliable, `ConfigCheck` is `no (…)`, the page says so, and the census is the proof. | +| Adding `user` to Claude Code's setting sources also loads user settings from the run's home. | The probe checks what `user` loads. If anything beyond `~/.claude/CLAUDE.md` loads, the global file goes to the workspace's parent directory instead, and the page states that scope. | +| A single-file read-only bind mount at the workspace root is not read by a harness. | The probe mounts one on each harness. If one does not read it, the plan returns for a ruling before L2. | +| OpenCode's `` does not follow `XDG_CONFIG_HOME`. | The probe checks it. If it fails, install at the path OpenCode does read and state it. | +| `InstructionsLoaded` does not fire under `--print`. | The probe checks it. The fallback for the census is `context_start.system`: the text reached the model. | +| Passing `--settings` in headless mode changes behaviour. | The file holds only observe-only hooks. The guards compare headless runs before and after. | +| A consumer hook approves permission prompts and changes what `permission_mode` means. | This is the consumer's choice, stated on the experiment-file page. | +| An agent copies the workspace file into its outputs, and the run is sealed `input_leak`. | The same holds for any input today. The guard's agent does not copy it, and G9 checks no run is sealed. | +| The system text is tens of kilobytes, and the gateway's log line becomes large. | Only the first request of a run is recorded. `trace_context` measures the line on both harnesses and states the size on the trace page. | +| No session-start hook on a harness reaches the first request. | The probe's question (g) settles it before L2, and the plan returns to Eliott if so. | +| A fixture's own root `CLAUDE.md` or `AGENTS.md`. | With `instructions.workspace` set, a declared input at that path is refused (`experiment.instructions_collide`). Without it, the fixture's file stays and the census reports it. | + +## Roadmap Recommendation + +A new root, [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md). The tool refuses a `.` in a node name, so the directory is `m6_5`. Depth sets the order, and siblings run in parallel. + +| Level | Leaves | Owns | +|---|---|---| +| L1 | `probe_harness_checks`, `declaration`, `trace_context` | `trace_context`: the gateway records the first request, and the trace gains `context_start`. The others: which harness checks are reliable, which session-start hook reaches the first request, where Claude Code's global file loads, and whether a read-only root mount is read. The P8 entries, schema, one reader, refusals, inspect, pages and the read-only workspace file in `Plan`, with the answers still Refused. | +| L2 | `install_claude_code`, `install_opencode`, `preflight_check` | Installation and census in each driver, with answers flipped to Mapped. In core: `HarnessConfigStep`, the new refusals, and the workspace file's mount through `mount_inputs`. | +| L3 | `e2e_guard` | Both end-to-end guards on the real harnesses and the fake model, reading the trace; then the live RiVault run. | +| L4 | `adversarial_review` | A read-only review of the merged milestone and the closing report. | + +**Gates.** Each is an observation shown failing on the base (`8d82f63b`), copied into the leaf that owns it. + +| # | Observation after | On the base | Leaf | +|---|---|---|---| +| G1 | `candler resolve` of `[fixed] instructions.workspace = "…"` succeeds, and `inspect` shows an `instructions` member. | exit 2 `experiment.unknown_path` at `/fixed/instructions.workspace` | declaration | +| G2 | Two levels of `instructions.workspace` give two cells with different digests; so do two levels of `hooks.claude-code.settings`. | `unknown_path` | declaration | +| G3 | `harness-capabilities.md` has the rows *instructions: global*, *instructions: workspace*, *hooks* and *config check*, mapped on both harnesses. | no such rows | declaration, then both install leaves | +| G4 | From the trace: on each harness, the run's `context_start.system` holds the global text and the arm's workspace text verbatim, and never the other arm's workspace text. | `unknown_path` | e2e_guard (fake model, then live) | +| G5 | e2e: the scripted tool call is answered with an error carrying the hook's marker. On Claude Code a PreToolUse script exits 2; on OpenCode a plugin throws in `execute.before`. | the call succeeds; no hook | e2e_guard | +| G6 | An invalid payload (a Claude Code hooks entry with an unknown event; an OpenCode plugin with no default export) is refused at `resolve` with `experiment.harness_rejected_input`, quoting the harness's output. The valid payload passes. | `unknown_path` | preflight_check (fake driver), e2e_guard (real images) | +| G7 | Each run's census lists both installed instruction files with their scope, on each harness. | no field | both install leaves, e2e_guard | +| G8 | `hooks.claude-code` on an OpenCode cell with no `hooks.opencode` is `experiment.cell_value_missing` at `/fixed/hooks`; likewise `instructions.global` with no key for the cell's harness, at `/fixed/instructions.global`. | `unknown_path` | declaration | +| G9 | The workspace instruction file is not among a run's collected outputs, an agent's write to it fails, and no run is sealed `input_leak`. | not reachable | preflight_check, e2e_guard | +| G10 | With `instructions.workspace` set, an input declared at the workspace instruction file's path is refused at `resolve` with `experiment.instructions_collide`, naming the input. | `unknown_path` | preflight_check | +| G11 | From the trace: on each harness, the session-start hook's marker is in `context_start`. | `unknown_path` | e2e_guard (fake model, then live) | +| G12 | Every session of a run on either harness begins with a `context_start` event whose `system` equals the system text the gateway saw. A trace written before the change still reads. | no such event | trace_context | +| G13 | Live on RiVault: one experiment on both harnesses, two arms, one replicate each, shows G4 and G11 in its stored traces, and `04-findings_live_confirmation_v0.md` quotes the excerpts. | no such event | e2e_guard | + +**Out of scope:** + +- file references; +- instruction scopes beyond global and workspace, such as files in subdirectories; +- npm plugins; +- other settings keys and other `.claude/` content; +- a trace event for every hook run (the session-start marker in `context_start` is the hook proof); +- the context of later requests (only the first request is recorded); +- removing a fixture's own instruction file when no workspace text is set (the census reports it); +- evaluator access to the instruction and hook values. Deferred until a consumer brings a reason: the consumer who writes the evaluator already knows the values. Today an evaluator that names one of these paths among its metadata needs receives it, like any cell value; +- M7 and M8. M8's plugin may later use hooks. + +## Execution model + +The roadmap's leaves refer to this section. A copy of it goes into every brief. + +**Roles** + +- A coordinator dispatches the work and merges it. +- It writes no product code and never verifies its own dispatches. +- Every implementer, verifier and reviewer is a Sonnet subagent. + +**Verification, scaled to risk** + +- Every leaf gets a `spec-verifier` pass. +- `preflight_check`, `install_claude_code` and `trace_context` also get an adversarial review before they merge. +- A seam review of the whole diff so far follows the close of L1 and of L2 ([leaf template](../../__roadmap__/leaf_template.md), convention 4). +- L4 is the final review. + +**Shared codebase, owned debt** + +Every brief opens with the same statement: + +- The codebase is shared with every agent and person who builds on it after this leaf. +- The implementer owns what the leaf leaves behind. +- A miss, a misuse, an accretion, a helper left behind, or tooling refactored without the old one cleaned up is debt that someone downstream has to handle. It breaks sustainability and scalability directly. + +So each leaf: + +- reuses the existing reader, renderer or step; +- removes, in the same leaf, whatever it made obsolete; +- leaves no scaffolding, debug helper or one-off script. + +The verifier checks these three points as gates. + +**Reviews stay in scope** + +- A finding is fixed in the leaf only if it concerns the leaf's own pieces, its gates or the code it touched. +- A finding that is unrelated, or too expensive to fix here, is filed under `__reports__/agent_config/` as an observation or a notice. The coordinator escalates it to the top coordination session, so the milestones can be re-planned around it. +- A leaf gets at most two rounds of implementing and verifying. If it would need a third, it stops and is escalated. + +**Git** + +- The integration branch is `feat/m6.5-agent-config`, cut from `origin/main` at `8d82f63b`. +- Each leaf branch is rebased on the integration branch, then merged with `--no-ff`. +- Commit messages go through `git commit -F`. +- No history is rewritten. +- Nothing is pushed and no PR is opened without Eliott. The PR to `main` waits for a green `container-e2e` (leaf template, convention 5). + +**Machine** + +- Builds use the slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`. +- At most 3 builds run at once, and a slot is never used by two worktrees at the same time. +- A leaf removes its slot when it merges. +- A leaf deletes the containers and images it starts. +- Nobody stops or prunes Docker. + +**Spend** + +- Spend is measured from host transcripts with `__reports__/agent-token-costs/scripts/spend.py`, per leaf and for the coordinator. +- The milestone cap is $85 (raised from $75 in v2 for the trace leaf and the live run). At the cap, work stops and a report is written. + +**Status** + +- The high-level status lives in macOS Reminders, managed with the `scheduling-work` skill. +- There is one reminder for M6.5 and one for each level. +- Each reminder is updated when its level closes. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index fabe429a..3173529d 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -9,9 +9,12 @@ Instruction files and hooks as per-arm experiment data (M6.5). - [00-notice_consumer_requirements_v0.md](00-notice_consumer_requirements_v0.md) — superseded by v1. The HTN eval lane's four requirements checked against the plan: three met, evaluator blinding (d) open for Eliott. ### Round 01 -- [01-architecture_agent_config_v1.md](01-architecture_agent_config_v1.md) — **latest**. The plan with Eliott's two rulings on the notice: a global instruction file per harness plus a read-only workspace-root file per arm, and evaluator access deferred. Gates G1–G10. +- [01-architecture_agent_config_v1.md](01-architecture_agent_config_v1.md) — superseded by v2. The plan with Eliott's two rulings on the notice: a global instruction file per harness plus a read-only workspace-root file per arm, and evaluator access deferred. Gates G1–G10. - [01-notice_consumer_requirements_v1.md](01-notice_consumer_requirements_v1.md) — **latest**. The HTN lane's four requirements against v1: three met, evaluator access (d) deferred. +### Round 02 +- [02-architecture_agent_config_v2.md](02-architecture_agent_config_v2.md) — **latest**. v1 plus Eliott's ruling that the proof is live and read from the trace: a new `context_start` trace event from the gateway's first request, a new L1 leaf `trace_context`, a session-start hook marker, and a live RiVault confirmation run. Gates G1–G13, cap $85. + ## Status -The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended for two instruction scopes on 2026-11-25. No leaf has been dispatched, and no decision is open. +The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended on 2026-11-25 for two instruction scopes (v1), then for a live, trace-read proof (v2). No leaf has been dispatched, and no decision is open. From 8a32ae85cbb8e474e6e7ff9b176fee2da1ad8151 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 13:20:08 +0900 Subject: [PATCH 07/69] rdm(api): amend M6.5 for the live trace proof Add the L1 leaf trace_context, probe question (g), the live step of e2e_guard, gates G1-G13, renumbered reports and the $85 cap. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/README.md | 6 ++++-- __roadmap__/m6_5-agent-config/declaration.md | 2 +- .../installed/install_claude_code.md | 2 +- .../installed/install_opencode.md | 2 +- .../installed/preflight_check.md | 2 +- .../installed/proved/e2e_guard.md | 20 ++++++++++++++----- .../proved/reviewed/adversarial_review.md | 6 +++--- .../m6_5-agent-config/probe_harness_checks.md | 12 ++++++----- .../m6_5-agent-config/trace_context.md | 20 +++++++++++++++++++ 9 files changed, 53 insertions(+), 19 deletions(-) create mode 100644 __roadmap__/m6_5-agent-config/trace_context.md diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index 4397a3d8..e045d0bb 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -1,7 +1,7 @@ # M6.5 Agent configuration as data ## Context -A new root after M6c Integrity (#81, on `origin/main` at `8d82f63b`). It is independent of M7, which is blocked, and of M8, which lies below M7; M8's plugin may later use hooks. The plan is [the architecture report, v1](../../__reports__/agent_config/01-architecture_agent_config_v1.md), which applies Eliott's two rulings on the HTN lane's notice to the approved v0. Every leaf runs by its §Execution model: Sonnet implementers and verifiers, a shared codebase whose debt the leaf owns, findings kept in scope or escalated, target-dir slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and a $75 cap. The status is mirrored in macOS Reminders. +A new root after M6c Integrity (#81, on `origin/main` at `8d82f63b`). It is independent of M7, which is blocked, and of M8, which lies below M7; M8's plugin may later use hooks. The plan is [the architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), which adds to the approved plan Eliott's rulings on the HTN lane's notice (v1) and on a live, trace-read proof (v2). Every leaf runs by its §Execution model: Sonnet implementers and verifiers, a shared codebase whose debt the leaf owns, findings kept in scope or escalated, target-dir slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and an $85 cap. The status is mirrored in macOS Reminders. ## Goal A consumer gives the experiment a global instruction file per harness, each arm its own workspace instruction file and hooks, all as cell values. Candler installs them where each harness looks, the workspace file read-only at the workspace root, and refuses a cell that the harness's own check rejects. @@ -12,7 +12,7 @@ A consumer gives the experiment a global instruction file per harness, each arm - [x] `[nl]` Eliott ruled on the HTN lane's notice on 2026-11-25: instructions come in two scopes (a global file per harness, and a workspace-root file per arm on both harnesses), and evaluator access to them is deferred ## Success Gates -- ⬜ G1–G10 of the [architecture report, v1](../../__reports__/agent_config/01-architecture_agent_config_v1.md) hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` +- ⬜ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` - ⬜ `probe_harness_checks.md`, `declaration.md` and `installed/` are `done` - ⬜ The spend measured from transcripts, coordinator included, is at most $75 - ⬜ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated @@ -23,6 +23,7 @@ graph TD probe_harness_checks[Probe harness checks]:::planned declaration[Declaration]:::planned installed[Installed]:::planned + trace_context[trace_context]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -36,6 +37,7 @@ graph TD | `probe_harness_checks.md` | 📄 Leaf Task | ⬜ Planned | | `declaration.md` | 📄 Leaf Task | ⬜ Planned | | `installed/` | 📁 Directory | ⬜ Planned | +| `trace_context.md` | 📄 Leaf Task | ⬜ Planned | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/m6_5-agent-config/declaration.md b/__roadmap__/m6_5-agent-config/declaration.md index 1d749378..70851737 100644 --- a/__roadmap__/m6_5-agent-config/declaration.md +++ b/__roadmap__/m6_5-agent-config/declaration.md @@ -11,7 +11,7 @@ - ⬜ G3 (this level's half). `docs/contract/harness-capabilities.md` has the rows *instructions: global*, *instructions: workspace*, *hooks* and *config check*. Both drivers answer each with `no (…)` saying it is installed from L2, and `cargo nextest run -p candler contract_pages` passes. On the base, no such rows exist. - ⬜ `experiment.harness_rejected_input` and `experiment.instructions_collide` are declared in `docs/contract/codes.toml` with their side (experiment) and their path. No code path raises them yet. - ⬜ `Plan` has a field for read-only workspace files, and the trait names each driver's workspace instruction file (`CLAUDE.md`, `AGENTS.md`). Both drivers leave the field empty, so no run changes. -**References**: [Architecture report, v1](../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-schemas/src/servers.rs` (`McpServer`, the precedent); `crates/candler-harness/src/spec.rs:651` (`AgentSetting`) and `:729` (`DriverFact`); `crates/candler-core/src/resolve/paths.rs` (`CONFIGURATION_PATHS`, `settings_set_by`); `crates/candler/src/commands/inspect.rs` (`mcp_of`); `crates/candler/tests/it/guard_inspect_mcp_config.rs` +**References**: [Architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-schemas/src/servers.rs` (`McpServer`, the precedent); `crates/candler-harness/src/spec.rs:651` (`AgentSetting`) and `:729` (`DriverFact`); `crates/candler-core/src/resolve/paths.rs` (`CONFIGURATION_PATHS`, `settings_set_by`); `crates/candler/src/commands/inspect.rs` (`mcp_of`); `crates/candler/tests/it/guard_inspect_mcp_config.rs` ## Step 1: Surface, schema and one reader **Goal**: The three values exist as typed cell values, read by one reader. diff --git a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md index 9ba3a964..3e2e6282 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md +++ b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md @@ -11,7 +11,7 @@ - ⬜ A cell without these values renders the same `.claude/settings.json` as on the base. Only the home observers file is added. - ⬜ The census of a run that recorded `InstructionsLoaded` lists the global file (User, or Project for the parent directory) and `{path: CLAUDE.md, scope: Project}`, read from a recorded `.candler/hooks.jsonl` fixture. - ⬜ An adversarial Sonnet review finds no way for a payload to disable Candler's observers, or to write outside `.claude/`. -**References**: [Architecture report, v1](../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-claude-code/src/prepare.rs` (`render_settings`), `session.rs` (`HOOK_EVENTS`, `hooks()`), `discovery.rs` (`EXCLUDED_DIRS`); the probe report +**References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-claude-code/src/prepare.rs` (`render_settings`), `session.rs` (`HOOK_EVENTS`, `hooks()`), `discovery.rs` (`EXCLUDED_DIRS`); the probe report ## Step 1: Render and install **Goal**: The driver writes the values where Claude Code reads them. diff --git a/__roadmap__/m6_5-agent-config/installed/install_opencode.md b/__roadmap__/m6_5-agent-config/installed/install_opencode.md index 4aafad5e..d908ec3d 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_opencode.md +++ b/__roadmap__/m6_5-agent-config/installed/install_opencode.md @@ -9,7 +9,7 @@ - ⬜ G3 (OpenCode). The *instructions*, *hooks* and *config check* rows show the OpenCode mapping: `$XDG_CONFIG_HOME/opencode/AGENTS.md`, and the workspace's root `AGENTS.md`, read-only; local plugins in `$XDG_CONFIG_HOME/opencode/plugins/`; and the probe's check or `no (…)`. On the base, no such rows exist. - ⬜ The plan of a cell with `instructions.global.opencode`, `instructions.workspace` and `hooks.opencode` places the global `AGENTS.md` and each plugin in the home, byte for byte, lists `AGENTS.md` with the workspace text among its read-only workspace files, and writes nothing in the workspace itself. On the base, the plan has none of these. - ⬜ The census lists each `Instructions from: ` block of the first request the gateway saw, read from a recorded request fixture. -**References**: [Architecture report, v1](../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-opencode/src/prepare.rs` (`render_config`, `PreparedFile::in_home`); the OpenCode V2 evidence in the report +**References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-opencode/src/prepare.rs` (`render_config`, `PreparedFile::in_home`); the OpenCode V2 evidence in the report ## Step 1: Install, census and check **Goal**: The driver writes the values where OpenCode reads them, and a run says what loaded. diff --git a/__roadmap__/m6_5-agent-config/installed/preflight_check.md b/__roadmap__/m6_5-agent-config/installed/preflight_check.md index c6fcb27e..3ed683c4 100644 --- a/__roadmap__/m6_5-agent-config/installed/preflight_check.md +++ b/__roadmap__/m6_5-agent-config/installed/preflight_check.md @@ -11,7 +11,7 @@ - ⬜ G9 (core half). With a fake driver whose plan lists a read-only workspace file, the run's workspace holds it at the root, a write to it fails, it is not among the collected outputs, and the run is not sealed `input_leak`. On the base, `Plan` has no such field. - ⬜ G10. With `instructions.workspace` set, an input declared at the workspace instruction file's path is refused at `resolve` with `experiment.instructions_collide`, naming the input. On the base, the experiment is refused earlier with `unknown_path`. - ⬜ An adversarial Sonnet review finds no path where a finding lets the cell run, and no check container that outlives the step. -**References**: [Architecture report, v1](../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-core/src/resolve/steps/` (`HarnessIdentityStep`, the precedent); `ImageService` +**References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-core/src/resolve/steps/` (`HarnessIdentityStep`, the precedent); `ImageService` ## Step 1: The step **Goal**: A preflight step that asks the harness and refuses on its answer. diff --git a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md index a201aa32..583d7a79 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md @@ -1,22 +1,32 @@ # E2E guard -**Goal**: The real `candler run` on real Claude Code and real OpenCode, against the scripted fake model, shows the README's promise for instructions and hooks on both harnesses. (P0) -**Estimate**: Sonnet, $8, cap $16. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Goal**: The real `candler run` on real Claude Code and real OpenCode, against the scripted fake model and then live on RiVault, shows from the stored trace the README's promise for instructions and hooks on both harnesses. (P0) +**Estimate**: Sonnet, $11, cap $22 (the live run included). At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G4. On each harness, the fake model's recorded requests for arm A hold the global text and workspace text A, and never workspace text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. +- ⬜ G4. From the trace: on each harness, the `context_start.system` of arm A's run holds the global text and workspace text A, and never workspace text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. - ⬜ G5. The scripted tool call is answered with an error carrying the hook's marker: a Claude Code PreToolUse script exits 2, and an OpenCode plugin throws in `execute.before`. On the base, there is no hook and the call succeeds. - ⬜ G6. On real images, an invalid payload (a Claude Code hooks entry on an unknown event; an OpenCode plugin with no default export) is refused at `resolve` with `experiment.harness_rejected_input`, quoting the harness, and the valid payload passes. On the base, it is `unknown_path`. - ⬜ G7. Each run's census lists both installed instruction files with their scope: on Claude Code the global file where the probe settled and the root `CLAUDE.md` (Project); on OpenCode the global `AGENTS.md` and the root `AGENTS.md`. - ⬜ G9. No installed file, the root instruction file included, is among any run's collected outputs, and no run is sealed `input_leak`. +- ⬜ G11. From the trace: on each harness, the session-start hook's marker is in `context_start`, where the probe's question (g) says it lands. On the base, there is no such event. +- ⬜ G13. Live on RiVault (Reasoning-Small): one experiment on both harnesses, two arms, one replicate each, shows G4 and G11 in its stored traces, and `__reports__/agent_config/04-findings_live_confirmation_v0.md` quotes the trace excerpts. - ⬜ The guards run in a pass that lists them as passed, not skipped (leaf template, convention 3). `docker ps -a` shows none of their containers afterwards. -**References**: [Architecture report, v1](../../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs` (`parity_one_installed_server_one_traced_call`, the model to follow); `assets/docker/fakemodel` +**References**: [Architecture report, v2](../../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs` (`parity_one_installed_server_one_traced_call`, the model to follow); `assets/docker/fakemodel` ## Step 1: The guards **Goal**: Two guards that read what a consumer reads. **Implementation Logic**: -`guard_agent_config_e2e` runs one experiment with a global text per harness, two arms (workspace text A or B) and one hook per harness on both harnesses. It reads `inspect`'s members, the rendered files in the run, the fake model's records and the stored census. `guard_harness_check_refuses` runs `resolve` on real images with no model. Reuse the parity e2e's helpers; do not copy them. The check's output must list both guards as passed. +`guard_agent_config_e2e` runs one experiment with a global text per harness, two arms (workspace text A or B) and one blocking hook and one session-start hook per harness on both harnesses. It reads `inspect`'s members, the rendered files in the run, the stored trace's `context_start` and the stored census, as a consumer does, not the fake model's records. `guard_harness_check_refuses` runs `resolve` on real images with no model. Reuse the parity e2e's helpers; do not copy them. The check's output must list both guards as passed. **Deliverables**: `crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs`; the fake model's script for the blocked call **Consistency Checks**: `cargo nextest run -p candler --run-ignored all -E 'test(agent_config) | test(harness_check)'` (expected: PASS) **Commit**: `test(cli): prove instructions and hooks on both harnesses` + +## Step 2: The live confirmation +**Goal**: The same proof on a real model. +**Implementation Logic**: +Run the guard's experiment once with `candler run` against RiVault's Reasoning-Small, which tests reachability, not scores, on both harnesses with two arms and one replicate each. Read G4 and G11 from the stored traces with the same reader the guard uses. Quote the `context_start` excerpts that show each text and the marker. No product code changes in this step. +**Deliverables**: `__reports__/agent_config/04-findings_live_confirmation_v0.md`, written with `writing-reports`, type findings +**Consistency Checks**: `test -s __reports__/agent_config/04-findings_live_confirmation_v0.md` (expected: PASS) +**Commit**: `reports(api): confirm instructions and hooks live from the trace` diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md index 1a4b937a..8a65d1f2 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md @@ -5,10 +5,10 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ `__reports__/agent_config/03-review_m6_5_v0.md` names each gate G1–G10 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. +- ⬜ `__reports__/agent_config/05-review_m6_5_v0.md` names each gate G1–G13 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. - ⬜ The report lists any debt left behind (a second reader, a duplicated helper, dead code, a leftover script), each fixed in this leaf or filed as a notice. An out-of-scope finding is filed as an observation and escalated. -- ⬜ `__reports__/agent_config/03-knowledge_transfer_m6_5_v0.md` records the spend measured per leaf against the $75 cap. -**References**: [Architecture report, v1](../../../../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model +- ⬜ `__reports__/agent_config/05-knowledge_transfer_m6_5_v0.md` records the spend measured per leaf against the $85 cap. +**References**: [Architecture report, v2](../../../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model ## Step 1: Review and close **Goal**: An independent verdict, and the milestone's record. diff --git a/__roadmap__/m6_5-agent-config/probe_harness_checks.md b/__roadmap__/m6_5-agent-config/probe_harness_checks.md index 7c29f97c..a332032a 100644 --- a/__roadmap__/m6_5-agent-config/probe_harness_checks.md +++ b/__roadmap__/m6_5-agent-config/probe_harness_checks.md @@ -1,15 +1,16 @@ # Probe harness checks -**Goal**: The plan names, for each harness, a command that reports whether Candler's install of instructions and hooks is valid, and says what that command does without a TTY and without network. Where no such command exists, the plan says `no`. It also settles where Claude Code's global file loads, and whether both harnesses read a read-only file mounted at the workspace root. (P0, it decides L2) +**Goal**: The plan names, for each harness, a command that reports whether Candler's install of instructions and hooks is valid, and says what that command does without a TTY and without network. Where no such command exists, the plan says `no`. It also settles where Claude Code's global file loads, whether both harnesses read a read-only file mounted at the workspace root, and which session-start hook fires headless. (P0, it decides L2) **Estimate**: Sonnet, $3, cap $6. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ `__reports__/agent_config/02-findings_probe_harness_checks_v0.md` answers every question of Step 1. Each answer quotes the command, its exit code and its output, captured in the `base` image (Claude Code 2.1.311) or the `base-opencode` image (OpenCode 2.2.7). +- ⬜ `__reports__/agent_config/03-findings_probe_harness_checks_v0.md` answers every question of Step 1. Each answer quotes the command, its exit code and its output, captured in the `base` image (Claude Code 2.1.311) or the `base-opencode` image (OpenCode 2.2.7). - ⬜ The report names where L2 installs Claude Code's global file (the run's home with `user` among the setting sources, or the workspace's parent directory) and why, and the order in which each harness puts the global and the workspace text in front of the model. - ⬜ For each harness, the report names the command that L2 wires into `config_check`, and what in its output counts as an error or a warning. If no command is reliable, the report says `no` and why. +- ⬜ For each harness, the report names the session-start hook L3 uses and where its output lands in the first model request (system text or first message). If none reaches the first request, the report says so, and the plan returns to Eliott before L2. - ⬜ `docker ps -a --filter label=m6_5-probe -q` prints nothing at the leaf's close. -**References**: [Architecture report, v1](../../__reports__/agent_config/01-architecture_agent_config_v1.md) — the shapes, the error model, the invariants and §Execution model +**References**: [Architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model ## Step 1: Probe the checks **Goal**: Measured answers, not documentation, for each check the plan relies on. @@ -21,7 +22,8 @@ Use throwaway containers labelled `m6_5-probe`, with network `none`. Write three (d) Does OpenCode's `` directory follow `XDG_CONFIG_HOME`, so that `$XDG_CONFIG_HOME/opencode/AGENTS.md` and `$XDG_CONFIG_HOME/opencode/plugins/` load? (e) Under `--setting-sources user,project,local` with a home that holds only `~/.claude/CLAUDE.md` and Candler's files, does that file load, and does `user` load anything else? Does a `CLAUDE.md` in the workspace's parent directory load instead? (f) Is a single file bind-mounted read-only at the workspace root (`/work/CLAUDE.md`, `/work/AGENTS.md`) read by each harness, as `InstructionsLoaded` or an `Instructions from:` block shows? In which order do the global and the workspace text reach the model? +(g) On each harness, which session-start hook fires in a headless run (Claude Code `SessionStart` with `--print`; an OpenCode plugin hook that adds to the system text, or the nearest one), and does its output reach the first model request, in the system text or the first message? Read the request at a gateway that records it. This step changes no product code. -**Deliverables**: `__reports__/agent_config/02-findings_probe_harness_checks_v0.md`, written with `writing-reports`, type findings -**Consistency Checks**: `test -s __reports__/agent_config/02-findings_probe_harness_checks_v0.md` (expected: PASS) +**Deliverables**: `__reports__/agent_config/03-findings_probe_harness_checks_v0.md`, written with `writing-reports`, type findings +**Consistency Checks**: `test -s __reports__/agent_config/03-findings_probe_harness_checks_v0.md` (expected: PASS) **Commit**: `reports(api): probe the harness checks for instructions and hooks` diff --git a/__roadmap__/m6_5-agent-config/trace_context.md b/__roadmap__/m6_5-agent-config/trace_context.md new file mode 100644 index 00000000..9214feec --- /dev/null +++ b/__roadmap__/m6_5-agent-config/trace_context.md @@ -0,0 +1,20 @@ +# Trace context + +**Goal**: Every session's normalised trace begins with a `context_start` event that holds the system text and the first message of the run's first model request, verbatim, as the gateway saw them, on both harnesses. It is what lets L3 prove from the trace that the instructions and the session-start hook reached the model. (P0, L3 reads it) +**Estimate**: Sonnet, $8, cap $16. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. An adversarial review follows the spec-verifier pass. +**Pre-conditions**: +- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +**Success Gates**: +- ⬜ G12. In a run on Claude Code and in a run on OpenCode against the fake model, the session's first trace event is `context_start`, and its `system` equals the system text of the first request the gateway logged. On the base, there is no such event. +- ⬜ A trace written before the change still reads, and the schema's version bump is minor. +- ⬜ One reader of the gateway log serves both the census and `context_start`; no second reader exists. The trace contract page documents the event, and states the measured size of the gateway's log line on both harnesses. +- ⬜ The guards run in a pass that lists them as passed, not skipped. `docker ps -a` shows none of their containers afterwards. +**References**: [Architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) — §Live trace proof, invariant 8 and §Execution model; `crates/candler-schemas/src/trace.rs` (`KnownKind`); `crates/candler-core/src/isolation/gateway.rs` and its njs script; `crates/candler-core/tests/it/guard_census_gateway.rs` (the census reader of the gateway log) + +## Step 1: Record the first request and emit the event +**Goal**: The gateway's first-request text becomes the trace's first event. +**Implementation Logic**: +The gateway already logs each request's sequence number and tool names per run and tag. It also logs, for sequence 0 only, the request's system text and first message. The core's existing gateway-log reader, the one the census uses, reads them, and the trace normaliser places `context_start {system, first_message}` before the session's first event. The kind is additive to `KnownKind`, so the schema bump is minor and old traces read unchanged. Regenerate only this leaf's own schemas and pages. The codebase is shared: extend the reader, do not copy it, and leave no scaffolding. This leaf touches no file that `declaration` touches. +**Deliverables**: `crates/candler-schemas/src/trace.rs` (`KnownKind::ContextStart`, its payload type); `crates/candler-core/src/isolation/gateway.rs` and its njs script (the first-request record); the gateway-log reader (the `context_start` event); the trace contract page; a guard `guard_trace_context_start` beside `guard_census_gateway.rs` +**Consistency Checks**: `cargo nextest run -p candler-core --run-ignored all -E 'test(trace_context) | test(census_gateway)'` (expected: PASS) +**Commit**: `feat(core): record each run's starting context in the trace` From ac45262c9d5ed29a1ed09d740c9d4ee4c58c2370 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 13:43:30 +0900 Subject: [PATCH 08/69] rdm(api): start M6.5 level 1 and sweep the root gates The root's gates name trace_context among the leaves that must be done, and the spend cap of $85 that plan v2 set. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index e045d0bb..e9ae49fd 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -13,17 +13,17 @@ A consumer gives the experiment a global instruction file per harness, each arm ## Success Gates - ⬜ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` -- ⬜ `probe_harness_checks.md`, `declaration.md` and `installed/` are `done` -- ⬜ The spend measured from transcripts, coordinator included, is at most $75 +- ⬜ `probe_harness_checks.md`, `declaration.md`, `trace_context.md` and `installed/` are `done` +- ⬜ The spend measured from transcripts, coordinator included, is at most $85 - ⬜ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated ## Status ```mermaid graph TD - probe_harness_checks[Probe harness checks]:::planned - declaration[Declaration]:::planned + probe_harness_checks[Probe harness checks]:::inprogress + declaration[Declaration]:::inprogress installed[Installed]:::planned - trace_context[trace_context]:::planned + trace_context[trace_context]:::inprogress classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -34,10 +34,10 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `probe_harness_checks.md` | 📄 Leaf Task | ⬜ Planned | -| `declaration.md` | 📄 Leaf Task | ⬜ Planned | +| `probe_harness_checks.md` | 📄 Leaf Task | 🔄 In Progress | +| `declaration.md` | 📄 Leaf Task | 🔄 In Progress | | `installed/` | 📁 Directory | ⬜ Planned | -| `trace_context.md` | 📄 Leaf Task | ⬜ Planned | +| `trace_context.md` | 📄 Leaf Task | 🔄 In Progress | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | From 48f287cd060a0c5f9cd837206f89c3fe672d9843 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 13:57:21 +0900 Subject: [PATCH 09/69] feat(schemas): add the context_start trace event Co-Authored-By: Claude Sonnet 5.5 --- .../schema/normalised-trace.schema.json | 26 ++++++++++++++- crates/candler-schemas/src/trace.rs | 33 +++++++++++++++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/candler-schemas/schema/normalised-trace.schema.json b/crates/candler-schemas/schema/normalised-trace.schema.json index bb8e824b..2b82cdb7 100644 --- a/crates/candler-schemas/schema/normalised-trace.schema.json +++ b/crates/candler-schemas/schema/normalised-trace.schema.json @@ -231,8 +231,32 @@ "type": "object" }, "EventKind": { - "description": "What happened at one point of a session: an object whose `kind` is `user_message`, `assistant_message`, `tool_call`, `tool_result`, `notification` or `usage`, with the members of that kind beside it.", + "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.", "oneOf": [ + { + "additionalProperties": false, + "description": "What the model was given at the start of the run: the system text and the first message of the run's first model request, as the gateway received them.", + "properties": { + "first_message": { + "description": "The first message of the request, verbatim.", + "type": "string" + }, + "kind": { + "const": "context_start", + "type": "string" + }, + "system": { + "description": "The system text of the request, verbatim.", + "type": "string" + } + }, + "required": [ + "kind", + "system", + "first_message" + ], + "type": "object" + }, { "additionalProperties": false, "description": "The user said something.", diff --git a/crates/candler-schemas/src/trace.rs b/crates/candler-schemas/src/trace.rs index 9384ebd4..f2b209ad 100644 --- a/crates/candler-schemas/src/trace.rs +++ b/crates/candler-schemas/src/trace.rs @@ -754,6 +754,15 @@ pub enum UsageScope { #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] pub enum EventKind { + /// What the model was given at the start of the run: the system text and the first message of + /// the run's first model request, as the gateway received them. + #[non_exhaustive] + ContextStart { + /// The system text of the request, verbatim. + system: String, + /// The first message of the request, verbatim. + first_message: String, + }, /// The user said something. #[non_exhaustive] UserMessage { @@ -816,7 +825,8 @@ pub enum EventKind { } /// The kinds this version knows, as written. -const KNOWN_KINDS: [&str; 6] = [ +const KNOWN_KINDS: [&str; 7] = [ + "context_start", "user_message", "assistant_message", "tool_call", @@ -826,6 +836,15 @@ const KNOWN_KINDS: [&str; 6] = [ ]; impl EventKind { + /// The starting context of a run. + #[must_use] + pub const fn context_start(system: String, first_message: String) -> Self { + Self::ContextStart { + system, + first_message, + } + } + /// A user message. #[must_use] pub const fn user_message(text: Option) -> Self { @@ -907,11 +926,18 @@ impl EventKind { } } -/// What happened at one point of a session: an object whose `kind` is `user_message`, `assistant_message`, `tool_call`, `tool_result`, `notification` or `usage`, with the members of that kind beside it. +/// 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. #[derive(Serialize, Deserialize, JsonSchema)] #[serde(remote = "EventKind", tag = "kind", rename_all = "snake_case")] #[schemars(deny_unknown_fields, rename = "EventKind")] enum KnownKind { + /// What the model was given at the start of the run: the system text and the first message of the run's first model request, as the gateway received them. + ContextStart { + /// The system text of the request, verbatim. + system: String, + /// The first message of the request, verbatim. + first_message: String, + }, /// The user said something. UserMessage { /// The text, if the harness records it. @@ -1005,7 +1031,8 @@ impl Serialize for EventKind { } map.end() } - Self::UserMessage { .. } + Self::ContextStart { .. } + | Self::UserMessage { .. } | Self::AssistantMessage { .. } | Self::ToolCall { .. } | Self::ToolResult { .. } From 3ad571769bee90f69e02161076d27bd3dfd06d44 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 13:57:45 +0900 Subject: [PATCH 10/69] feat(schemas): type the instructions and hooks of a cell Co-Authored-By: Claude Sonnet 5.5 --- .../schema/claude-code-hooks.schema.json | 25 +++++++ .../schema/instructions.schema.json | 21 ++++++ .../schema/opencode-hooks.schema.json | 20 ++++++ crates/candler-schemas/src/agent_config.rs | 72 +++++++++++++++++++ crates/candler-schemas/src/execution/paths.rs | 9 +++ crates/candler-schemas/src/generate.rs | 1 + crates/candler-schemas/src/lib.rs | 3 +- 7 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 crates/candler-schemas/schema/claude-code-hooks.schema.json create mode 100644 crates/candler-schemas/schema/instructions.schema.json create mode 100644 crates/candler-schemas/schema/opencode-hooks.schema.json create mode 100644 crates/candler-schemas/src/agent_config.rs diff --git a/crates/candler-schemas/schema/claude-code-hooks.schema.json b/crates/candler-schemas/schema/claude-code-hooks.schema.json new file mode 100644 index 00000000..9820dd5d --- /dev/null +++ b/crates/candler-schemas/schema/claude-code-hooks.schema.json @@ -0,0 +1,25 @@ +{ + "$id": "urn:candler:schemas:claude-code-hooks", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The hooks a cell gives Claude Code: the `hooks` configuration and the files it runs.\n\nTheir contents are free; Claude Code judges them.", + "properties": { + "files": { + "additionalProperties": false, + "description": "The hook files, each at its path under `.claude/hooks/`.", + "patternProperties": { + "^(?!\\.\\.?(?:/|(?![\\s\\S])))[^/\\\\\\x00]+(?:/(?!\\.\\.?(?:/|(?![\\s\\S])))[^/\\\\\\x00]+)*(?![\\s\\S])": { + "type": "string" + } + }, + "type": "object" + }, + "settings": { + "additionalProperties": true, + "description": "The object that goes under the `hooks` key of `.claude/settings.json`, verbatim.", + "type": "object" + } + }, + "title": "ClaudeCodeHooks", + "type": "object" +} diff --git a/crates/candler-schemas/schema/instructions.schema.json b/crates/candler-schemas/schema/instructions.schema.json new file mode 100644 index 00000000..50298d2f --- /dev/null +++ b/crates/candler-schemas/schema/instructions.schema.json @@ -0,0 +1,21 @@ +{ + "$id": "urn:candler:schemas:instructions", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The instruction texts of a cell: one global text per harness and one text for the workspace.\n\nThe global text is the one the harness reads from the agent's home; the workspace text is the\none it reads at the root of the workspace. Their contents are free.", + "properties": { + "global": { + "additionalProperties": { + "type": "string" + }, + "description": "The global text of each harness, by harness id.", + "type": "object" + }, + "workspace": { + "description": "The text at the root of the workspace.", + "type": "string" + } + }, + "title": "Instructions", + "type": "object" +} diff --git a/crates/candler-schemas/schema/opencode-hooks.schema.json b/crates/candler-schemas/schema/opencode-hooks.schema.json new file mode 100644 index 00000000..5f7047a5 --- /dev/null +++ b/crates/candler-schemas/schema/opencode-hooks.schema.json @@ -0,0 +1,20 @@ +{ + "$id": "urn:candler:schemas:opencode-hooks", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The hooks a cell gives `OpenCode`: its plugins, which are code.\n\nTheir contents are free; `OpenCode` judges them.", + "properties": { + "plugins": { + "additionalProperties": false, + "description": "The plugin files, each by its file name.", + "patternProperties": { + "^(?!\\.\\.?(?:/|(?![\\s\\S])))[^/\\\\\\x00]+(?:/(?!\\.\\.?(?:/|(?![\\s\\S])))[^/\\\\\\x00]+)*(?![\\s\\S])": { + "type": "string" + } + }, + "type": "object" + } + }, + "title": "OpenCodeHooks", + "type": "object" +} diff --git a/crates/candler-schemas/src/agent_config.rs b/crates/candler-schemas/src/agent_config.rs new file mode 100644 index 00000000..5729d8bd --- /dev/null +++ b/crates/candler-schemas/src/agent_config.rs @@ -0,0 +1,72 @@ +//! The instruction texts and hooks an experiment declares for the agent, in the shape the drivers +//! read them. +//! +//! An experiment states them as leaves of the cell, because a `[fixed]` table or a factor level +//! is flattened to leaves whose keys are field-path segments, and a hook configuration, a file +//! path or a harness id such as `claude-code` is not one: `instructions.global.` is a +//! text, `hooks..settings` is the text of a JSON object, and the files of a harness are a +//! list of `{path, text}` entries. A harness id is written with `_` where it has `-`. The reader +//! (`candler_harness::agent_config`) puts the leaves together as the types of this module, each +//! published as its own schema as `mcp-server` is, and refuses what does not fit them. + +use std::collections::BTreeMap; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +use crate::generate::GeneratedSchema; +use crate::primitives::RelPath; + +/// The wire root schemas this module publishes. +#[must_use] +pub(crate) fn roots() -> Vec { + vec![ + GeneratedSchema::of::("instructions"), + GeneratedSchema::of::("claude-code-hooks"), + GeneratedSchema::of::("opencode-hooks"), + ] +} + +/// The instruction texts of a cell: one global text per harness and one text for the workspace. +/// +/// The global text is the one the harness reads from the agent's home; the workspace text is the +/// one it reads at the root of the workspace. Their contents are free. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct Instructions { + /// The global text of each harness, by harness id. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub global: BTreeMap, + /// The text at the root of the workspace. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub workspace: Option, +} + +/// The hooks a cell gives Claude Code: the `hooks` configuration and the files it runs. +/// +/// Their contents are free; Claude Code judges them. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct ClaudeCodeHooks { + /// The object that goes under the `hooks` key of `.claude/settings.json`, verbatim. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub settings: Option>, + /// The hook files, each at its path under `.claude/hooks/`. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub files: BTreeMap, +} + +/// The hooks a cell gives `OpenCode`: its plugins, which are code. +/// +/// Their contents are free; `OpenCode` judges them. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct OpenCodeHooks { + /// The plugin files, each by its file name. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub plugins: BTreeMap, +} diff --git a/crates/candler-schemas/src/execution/paths.rs b/crates/candler-schemas/src/execution/paths.rs index f437663f..e5f28ce5 100644 --- a/crates/candler-schemas/src/execution/paths.rs +++ b/crates/candler-schemas/src/execution/paths.rs @@ -27,6 +27,15 @@ pub const ENV: &str = "env"; /// The root of the MCP server configuration, a cell value. pub const MCP: &str = "mcp"; +/// A cell value: the global instruction text of each harness, a table keyed by harness id. +pub const INSTRUCTIONS_GLOBAL: &str = "instructions.global"; + +/// A cell value: the instruction text at the root of the workspace. +pub const INSTRUCTIONS_WORKSPACE: &str = "instructions.workspace"; + +/// The root of the hooks of each harness, a cell value. +pub const HOOKS: &str = "hooks"; + /// A cell value: the permission mode. pub const PERMISSION_MODE: &str = "permission_mode"; diff --git a/crates/candler-schemas/src/generate.rs b/crates/candler-schemas/src/generate.rs index a004297c..3cc303d7 100644 --- a/crates/candler-schemas/src/generate.rs +++ b/crates/candler-schemas/src/generate.rs @@ -70,6 +70,7 @@ pub fn generated_schemas() -> Vec { crate::raw::roots(), crate::trace::roots(), crate::servers::roots(), + crate::agent_config::roots(), crate::execution::roots(), crate::evaluation::roots(), crate::refusal::roots(), diff --git a/crates/candler-schemas/src/lib.rs b/crates/candler-schemas/src/lib.rs index 29aaf6dd..dc915d34 100644 --- a/crates/candler-schemas/src/lib.rs +++ b/crates/candler-schemas/src/lib.rs @@ -3,7 +3,7 @@ //! record in [`outcome`], resolved values in [`values`], //! canonical JSON in [`canonical`], process records in [`process`], container records in //! [`container`], raw frames in [`raw`], the normalised trace in [`trace`], execution records in -//! [`execution`], the MCP servers in [`servers`], evaluator protocol records in [`evaluation`], stable refusal codes in [`refusal`], and in [`generate`] the JSON Schema +//! [`execution`], the MCP servers in [`servers`], the instructions and hooks in [`agent_config`], evaluator protocol records in [`evaluation`], stable refusal codes in [`refusal`], and in [`generate`] the JSON Schema //! files generated from these types, committed under `schema/`, with the check that keeps them in //! step with the types. //! @@ -12,6 +12,7 @@ #![deny(clippy::allow_attributes)] +pub mod agent_config; pub mod analysis; pub mod canonical; pub mod container; From 10f49ae82643e1d084ec9784ac7e7483594b91f9 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 13:59:56 +0900 Subject: [PATCH 11/69] reports(api): probe the harness checks for instructions and hooks Co-Authored-By: Claude Sonnet 5.5 --- .../03-findings_probe_harness_checks_v0.md | 121 ++++++++++++++++++ __reports__/agent_config/README.md | 5 +- 2 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 __reports__/agent_config/03-findings_probe_harness_checks_v0.md diff --git a/__reports__/agent_config/03-findings_probe_harness_checks_v0.md b/__reports__/agent_config/03-findings_probe_harness_checks_v0.md new file mode 100644 index 00000000..c8d88cc1 --- /dev/null +++ b/__reports__/agent_config/03-findings_probe_harness_checks_v0.md @@ -0,0 +1,121 @@ +# Harness checks for instructions and hooks — Findings (v0) + +Date: 2026-11-25 + +--- +type: findings +topic: agent_config +date: 2026-11-25 +version: v0 +prior-version: none +key-metric: questions answered by measurement: 7 of 7 (prior: N/A, delta: N/A) +decision-required: confirm +--- + +**Session-start hooks: both harnesses have one that reaches the model, so the plan does not return to Eliott for that reason.** It does return on two points that change the v2 wording of G4 and `context_start` (the first two rows of the Contradictions section): on Claude Code the instruction texts land in the first message, never in the system text, and on OpenCode the gateway's first request is a title request that carries neither instructions nor hook output. + +## Headline Result + +metric: probe questions answered by measurement (a)–(g) +value: 7 +unit: questions of 7 +prior: N/A (first run) +direction: new + +## Verdict per question + +| Q | Answer | What L2 / L3 does with it | +|---|---|---| +| a | `claude doctor` runs with no TTY and no network, exit **0** in every case, valid or not. Errors and warnings in project settings (bad JSON, unknown hook event) print under one `Invalid settings` heading. A section of 4 install-method warnings always prints in the cell image, so a warning count is useless. | `config_check` for Claude Code is `claude doctor`. A finding is the presence of an `Invalid settings` heading. Ignore the exit code and the `N warnings found` block. | +| b | `InstructionsLoaded` fires under `--print --setting-sources project,local` and carries `file_path`, `memory_type` (`Project` or `User`), `load_reason` (`session_start`), `cwd`, `session_id`, `transcript_path`. | Census reads it. It works with the hook set in the home `--settings` file. | +| c | `opencode debug config` and `opencode plugin list` need no server and no network, exit 0 always. `debug config` shows a rejected `opencode.json` only by the document being absent from the list, with no message. `plugin list` prints `No plugins found` even with a valid local plugin installed. | Neither is a usable check. OpenCode's `config_check` is the standalone start below. | +| d | Yes. With `XDG_CONFIG_HOME=/home/agent/.xdg/config`, `…/opencode/AGENTS.md` and `…/opencode/plugins/good.ts` both load (`opencode debug paths`: `config /home/agent/.xdg/config/opencode`; request shows `Instructions from: /home/agent/.xdg/config/opencode/AGENTS.md`; log `loading plugin`). | Install OpenCode's global file and plugins there, as v2 says. | +| e | With `user` and a home holding only `~/.claude/CLAUDE.md` (Candler's `--settings` file is passed by flag, not read as `user`), exactly that one file loads, as `memory_type: User`. If the home also holds `~/.claude/settings.json` or `~/.claude/rules/*.md`, `user` loads both (the decoy hook fired and the rule text reached the model). A parent-directory `CLAUDE.md` also loads, but as `Project`, with no `user` needed. | **Claude Code global file: the run's home, `~/.claude/CLAUDE.md`, with `user` added to the setting sources.** See Placement below. | +| f | Yes on both. A single file bind-mounted read-only at `/work/CLAUDE.md` (Claude Code) or `/work/AGENTS.md` (OpenCode) is read. Order on both: global first, workspace second. | The read-only workspace mount of v2 works on both harnesses. | +| g | Claude Code: `SessionStart` fires with `--print`; its output is in the **first message**. OpenCode: a local plugin `session.hook("context", …)` adds a system block; it is in the **system text**, after the instructions. | L3's hook is `SessionStart` on Claude Code and a `context` plugin hook on OpenCode. Both reach the model. | + +## Results Tables + +### Where each text lands (recorded first agent request, gateway recorder answering 400) + +| Harness | Global file | Workspace file | Hook output | Order in the request | +|---|---|---|---|---| +| Claude Code 2.1.311 | first message, in one `` block headed `Contents of /home/agent/.claude/CLAUDE.md (user's private global instructions …)` | same block, `Contents of /work/CLAUDE.md (project instructions …)` | its own `` block, `SessionStart:startup hook success: SESSIONSTART_OBS_MARKER_S2`, earlier in the message than the instruction block | hook block, then global, then workspace. The `system` text holds none of the three (searched for each marker: not found). | +| OpenCode 2.2.7 | system text, `Instructions from: /home/agent/.xdg/config/opencode/AGENTS.md` | system text, `Instructions from: /work/AGENTS.md`, directly after the global | system text, a separate trailing block `PLUGIN_CONTEXT_MARKER_S3` | global, workspace, then the date and environment, then the hook block. The first message is the prompt only. | + +### The three installs, run through each check (network `none`, image of the harness) + +| Install | Claude Code: `claude doctor` | OpenCode: `opencode run --standalone --print-logs -m probe/none x` | +|---|---|---| +| Valid | exit 0; no `Invalid settings` heading | exit 1; stderr has no `WARN` and only the expected `ERROR … Failed to drain Session … ModelUnavailableError` | +| Error | `.claude/settings.json` bad JSON: exit 0; `Invalid settings` / `/work/.claude/settings.json: Invalid or malformed JSON`. OpenCode: `opencode.json` bad JSON: `WARN … configuration normalization diagnostic … kind=invalid action="rejected malformed JSON or JSONC document"`; plugin with no default export: `WARN … failed to load plugin target=…/bad.ts … Plugin must export a default definition with an id and an effect or setup function` | as the left column | +| Warning | hook on an unknown event: exit 0; `Invalid settings` / `hooks.NoSuchEvent: Unknown hook event "NoSuchEvent" was ignored. Valid events: …` | An unknown config key and an unknown provider setting produce no `WARN`; `debug config` shows the provider setting kept. OpenCode has no warning class for these. | + +### Requests the gateway saw (OpenCode) + +| seq | Tools | System text | Holds the markers? | +|---|---|---|---| +| 0 | 0 | 1,806 chars (title generator) | no | +| 1 | 12 | 9,098 chars | global, workspace and plugin markers | + +Claude Code sent six requests: the first three with 12 tools, the rest with 26. All six carry the same first message, so any of them holds the markers. + +## Observations + +| Signal | Baseline / Expected | Observed | Interpretation | +|---|---|---|---| +| Claude Code instructions in `system` | v2 G4: `context_start.system` holds both texts | markers absent from `system`, present in message 0 `[source: runs R1, R4, scratch]` | G4 must read `system` or `first_message`, per harness. | +| OpenCode seq 0 | v2: the gateway's first request is the agent's context | seq 0 is a title request with no tools `[source: O1_valid]` | The event must come from the first request that carries the tools. | +| `claude doctor` exit code | non-zero on a finding | 0 on a malformed file and on an unknown event `[source: a]` | `read_config_check` parses output. | +| `user` source scope | loads only `CLAUDE.md` | also `settings.json` hooks and `rules/*.md` of the home `[source: R2 vs R2b]` | Safe only because Candler's home holds nothing else there. | +| OpenCode config rejection | an error | exit 0, document silently missing from `debug config` `[source: c]` | `debug config` cannot gate. | +| Global file via parent directory | scope `User` | `Project` `[source: R3, R5]` | The census would label the global file as project scope. | + +## Placement and checks L2 uses + +### Claude Code's global file: the run's home + +**L2 installs it at `~/.claude/CLAUDE.md` in the run's home and adds `user` to `--setting-sources` (`user,project,local`).** Why: + +- The v2 rule is met: with Candler's home, `user` loads only that file (R2b). Candler's observation hooks go in by `--settings`, not through `user`. +- The census scope stays truthful: the harness reports it `User`. Through the parent directory it reports `Project`, indistinguishable from the workspace file, and the workspace's parent is a Candler mount point that does not exist today. +- Read order is unchanged either way: global first, workspace second. + +The cost to state on the capability page: `user` loads whatever else sits in `~/.claude/` (settings hooks, rules). Candler's home must stay free of anything else there, and a consumer who plants such files through a future home mechanism would reach the agent. Not probed: `~/.claude/skills`, `~/.claude/agents`, `~/.claude.json` under `user`. + +### `config_check` per harness + +| Harness | Command (network `none`, no TTY) | An error or warning is | Ignore | +|---|---|---|---| +| Claude Code | `claude doctor`, cwd the workspace | a line `Invalid settings` and the bullets under it (covers a rejected file and a skipped entry alike) | exit code (always 0); the `N warnings found` block; `Remote Control`, `Managed settings`, `Organization policy` lines | +| OpenCode | `opencode run --standalone --print-logs -m probe/none x`, with a throwaway `XDG_DATA_HOME` | any stderr line with `level=WARN` | exit code (always 1); the one `ERROR … Failed to drain Session … ModelUnavailableError` line; `INFO` lines. `opencode debug config` and `opencode plugin list` are not used. | + +The OpenCode command starts a session without a model request, so it needs no model and no network. It starts the same server and plugin loader a real run does, so it is the only measured way to see a failed local plugin. Not probed: the fixed model name `probe/none` against a future OpenCode version that rejects it before loading plugins; the check output must still be read as evidence in the guard. + +### Session-start hook per harness (L3) + +| Harness | Hook | Where its output lands in the first agent request | +|---|---|---| +| Claude Code | `SessionStart` (works under `--print`) | first message, own `` block, before the instructions block | +| OpenCode | plugin `session.hook("context", e => e.system.push({type:"text", text}))` | system text, last block, after the instructions and environment | + +## Contradictions & Surprises + +- **G4 as written fails on Claude Code.** Neither instruction text is in `system`. Read both from `system` and `first_message`, per harness. +- **`context_start` as written records the wrong request on OpenCode.** Seq 0 is a title request. The event needs "the first request with tools" (or the first request of the agent loop). The ADR sentence "one event per session, from the first request only" changes accordingly. +- `claude doctor` never fails by exit code, and OpenCode's two named checks cannot see a bad plugin. Only output parsing and a standalone start work. +- OpenCode's plugin import `@opencode/plugin` resolved for a local file plugin without installing a package. + +## Steering Questions + +- [now] Does Eliott accept the amended proof wording: instruction texts and the Claude Code hook marker read from `system` or `first_message` per harness, and `context_start` taken from the first request that carries the agent's tools? `trace_context` and `e2e_guard` follow it. +- [now] Does Eliott accept the home placement with `user` for the Claude Code global file, given that `user` also loads other files of the home? +- [next run] Should L2 probe `~/.claude/skills`, `agents` and `~/.claude.json` under `user` before it merges the placement? +- [later] Should OpenCode's unknown-key silence be stated on the capability page as a limit of its check? + +## Pointers + +- [02-architecture_agent_config_v2.md](02-architecture_agent_config_v2.md): §Where each value lands, §Live trace proof, gates G4, G11, G12 +- [probe_harness_checks.md](../../__roadmap__/m6_5-agent-config/probe_harness_checks.md): the leaf +- Images: `candler-base:src-83c18228eddb` (Claude Code 2.1.311), `candler-base:src-b062c666af0a` (OpenCode v2.2.7) +- Raw runs (removed at the close): `$HOME/m6_5-probe-scratch/runs/` diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 3173529d..3031aac6 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -13,7 +13,10 @@ Instruction files and hooks as per-arm experiment data (M6.5). - [01-notice_consumer_requirements_v1.md](01-notice_consumer_requirements_v1.md) — **latest**. The HTN lane's four requirements against v1: three met, evaluator access (d) deferred. ### Round 02 -- [02-architecture_agent_config_v2.md](02-architecture_agent_config_v2.md) — **latest**. v1 plus Eliott's ruling that the proof is live and read from the trace: a new `context_start` trace event from the gateway's first request, a new L1 leaf `trace_context`, a session-start hook marker, and a live RiVault confirmation run. Gates G1–G13, cap $85. +- [02-architecture_agent_config_v2.md](02-architecture_agent_config_v2.md) — latest architecture. v1 plus Eliott's ruling that the proof is live and read from the trace: a new `context_start` trace event from the gateway's first request, a new L1 leaf `trace_context`, a session-start hook marker, and a live RiVault confirmation run. Gates G1–G13, cap $85. + +### Round 03 +- [03-findings_probe_harness_checks_v0.md](03-findings_probe_harness_checks_v0.md) — **latest**. The level-1 probe, measured in the real images: the check command for each harness, where Claude Code's global file loads, the order and place (system or first message) in which instructions and session-start hooks reach the model. Two points amend v2's proof wording. ## Status From d93e579d1d66ee4c9863bafe1feaba0ee0145557 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 14:02:16 +0900 Subject: [PATCH 12/69] reports(api): give the probe's evidence per question Co-Authored-By: Claude Sonnet 5.5 --- .../03-findings_probe_harness_checks_v0.md | 48 +++++++++++++------ 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/__reports__/agent_config/03-findings_probe_harness_checks_v0.md b/__reports__/agent_config/03-findings_probe_harness_checks_v0.md index c8d88cc1..eb9f4476 100644 --- a/__reports__/agent_config/03-findings_probe_harness_checks_v0.md +++ b/__reports__/agent_config/03-findings_probe_harness_checks_v0.md @@ -1,7 +1,3 @@ -# Harness checks for instructions and hooks — Findings (v0) - -Date: 2026-11-25 - --- type: findings topic: agent_config @@ -12,6 +8,10 @@ key-metric: questions answered by measurement: 7 of 7 (prior: N/A, delta: N/A) decision-required: confirm --- +# Harness checks for instructions and hooks — Findings (v0) + +Date: 2026-11-25 + **Session-start hooks: both harnesses have one that reaches the model, so the plan does not return to Eliott for that reason.** It does return on two points that change the v2 wording of G4 and `context_start` (the first two rows of the Contradictions section): on Claude Code the instruction texts land in the first message, never in the system text, and on OpenCode the gateway's first request is a title request that carries neither instructions nor hook output. ## Headline Result @@ -34,6 +34,25 @@ direction: new | f | Yes on both. A single file bind-mounted read-only at `/work/CLAUDE.md` (Claude Code) or `/work/AGENTS.md` (OpenCode) is read. Order on both: global first, workspace second. | The read-only workspace mount of v2 works on both harnesses. | | g | Claude Code: `SessionStart` fires with `--print`; its output is in the **first message**. OpenCode: a local plugin `session.hook("context", …)` adds a system block; it is in the **system text**, after the instructions. | L3's hook is `SessionStart` on Claude Code and a `context` plugin hook on OpenCode. Both reach the model. | +## Evidence per question + +Each row is one run. `home_g` holds only `~/.claude/CLAUDE.md` (`GLOBAL_CC_MARKER_G1`) and an observation `--settings` file `obs.json` (an `InstructionsLoaded` writer and a `SessionStart` echo). `home_g2` is `home_g` plus decoy `~/.claude/settings.json` (a `SessionStart` hook echoing `DECOY_USER_SETTINGS_HOOK_D1`) and `~/.claude/rules/decoy.md`. `oc_*` homes hold `$XDG_CONFIG_HOME/opencode/{opencode.json, AGENTS.md, plugins/good.ts}`; `oc_errcfg` has a bad-JSON `opencode.json`, `oc_errplug` adds `bad.ts` with no default export, `oc_warn` adds an unknown key and an unknown provider setting. "Recorder" is a Python HTTP server on the `--internal` network `m6_5-probe-net` that writes each request body and answers 400, so claude exits 1 and no model runs. All containers ran as user `agent`, `--rm`, label `m6_5-probe`. CC image `candler-base:src-83c18228eddb`; OC image `candler-base:src-b062c666af0a`. + +| Id | Q | Command (what matters) | Exit | Key output line | +|---|---|---|---|---| +| E1 | a | CC, `--network none`, `home_g`, cwd `/work` = `w_valid` / `w_err` / `w_warn`: `claude doctor Date: Wed, 25 Nov 2026 14:02:51 +0900 Subject: [PATCH 13/69] rdm(api): mark the M6.5 probe done Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/README.md | 4 ++-- .../m6_5-agent-config/probe_harness_checks.md | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index e9ae49fd..d4c01d2b 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -20,7 +20,7 @@ A consumer gives the experiment a global instruction file per harness, each arm ## Status ```mermaid graph TD - probe_harness_checks[Probe harness checks]:::inprogress + probe_harness_checks[Probe harness checks]:::done declaration[Declaration]:::inprogress installed[Installed]:::planned trace_context[trace_context]:::inprogress @@ -34,7 +34,7 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `probe_harness_checks.md` | 📄 Leaf Task | 🔄 In Progress | +| `probe_harness_checks.md` | 📄 Leaf Task | ✅ Done | | `declaration.md` | 📄 Leaf Task | 🔄 In Progress | | `installed/` | 📁 Directory | ⬜ Planned | | `trace_context.md` | 📄 Leaf Task | 🔄 In Progress | diff --git a/__roadmap__/m6_5-agent-config/probe_harness_checks.md b/__roadmap__/m6_5-agent-config/probe_harness_checks.md index a332032a..0324f952 100644 --- a/__roadmap__/m6_5-agent-config/probe_harness_checks.md +++ b/__roadmap__/m6_5-agent-config/probe_harness_checks.md @@ -3,13 +3,13 @@ **Goal**: The plan names, for each harness, a command that reports whether Candler's install of instructions and hooks is valid, and says what that command does without a TTY and without network. Where no such command exists, the plan says `no`. It also settles where Claude Code's global file loads, whether both harnesses read a read-only file mounted at the workspace root, and which session-start hook fires headless. (P0, it decides L2) **Estimate**: Sonnet, $3, cap $6. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: -- [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds +- [x] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ `__reports__/agent_config/03-findings_probe_harness_checks_v0.md` answers every question of Step 1. Each answer quotes the command, its exit code and its output, captured in the `base` image (Claude Code 2.1.311) or the `base-opencode` image (OpenCode 2.2.7). -- ⬜ The report names where L2 installs Claude Code's global file (the run's home with `user` among the setting sources, or the workspace's parent directory) and why, and the order in which each harness puts the global and the workspace text in front of the model. -- ⬜ For each harness, the report names the command that L2 wires into `config_check`, and what in its output counts as an error or a warning. If no command is reliable, the report says `no` and why. -- ⬜ For each harness, the report names the session-start hook L3 uses and where its output lands in the first model request (system text or first message). If none reaches the first request, the report says so, and the plan returns to Eliott before L2. -- ⬜ `docker ps -a --filter label=m6_5-probe -q` prints nothing at the leaf's close. +- ✅ `__reports__/agent_config/03-findings_probe_harness_checks_v0.md` answers every question of Step 1. Each answer quotes the command, its exit code and its output, captured in the `base` image (Claude Code 2.1.311) or the `base-opencode` image (OpenCode 2.2.7). +- ✅ The report names where L2 installs Claude Code's global file (the run's home with `user` among the setting sources, or the workspace's parent directory) and why, and the order in which each harness puts the global and the workspace text in front of the model. +- ✅ For each harness, the report names the command that L2 wires into `config_check`, and what in its output counts as an error or a warning. If no command is reliable, the report says `no` and why. +- ✅ For each harness, the report names the session-start hook L3 uses and where its output lands in the first model request (system text or first message). If none reaches the first request, the report says so, and the plan returns to Eliott before L2. +- ✅ `docker ps -a --filter label=m6_5-probe -q` prints nothing at the leaf's close. **References**: [Architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model ## Step 1: Probe the checks From 0ce705e3c1f2e0d3797cb3d01d79b2872e2f52e0 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 14:18:05 +0900 Subject: [PATCH 14/69] feat(api): take instructions and hooks as cell values Co-Authored-By: Claude Sonnet 5.5 --- .../src/jobs/orchestrate/controls.rs | 1 + .../candler-core/src/jobs/orchestrate/mod.rs | 1 + crates/candler-core/src/jobs/runtime/mod.rs | 2 + .../candler-core/src/jobs/runtime/session.rs | 1 + crates/candler-core/src/resolve/paths.rs | 40 ++- crates/candler-core/src/runner/mod.rs | 2 + crates/candler-core/src/runner/plan.rs | 20 +- .../tests/it/guard_agent_config.rs | 191 ++++++++++++++ .../it/guard_container_e2e/controls_e2e.rs | 1 + .../tests/it/guard_egress_setting.rs | 1 + .../tests/it/guard_job_runtime.rs | 1 + crates/candler-core/tests/it/guard_session.rs | 1 + crates/candler-core/tests/it/main.rs | 1 + .../tests/it/support/job_orchestrate.rs | 1 + .../tests/it/support/job_runtime.rs | 1 + .../candler-core/tests/it/support/run_plan.rs | 1 + crates/candler-harness/src/agent_config.rs | 245 ++++++++++++++++++ crates/candler-harness/src/lib.rs | 2 + crates/candler-harness/src/refusal.rs | 11 +- .../tests/it/guard_agent_config.rs | 104 ++++++++ crates/candler-harness/tests/it/main.rs | 1 + crates/candler/src/commands/resolve.rs | 8 +- crates/candler/src/commands/run.rs | 1 + crates/candler/src/commands/supervise.rs | 1 + .../candler/tests/it/guard_cli_kill_live.rs | 1 + .../candler/tests/it/guard_golden_design.rs | 1 + docs/contract/configuration-paths.md | 3 + docs/contract/driver-traits.md | 2 +- docs/contract/experiment-file.md | 2 +- 29 files changed, 628 insertions(+), 20 deletions(-) create mode 100644 crates/candler-core/tests/it/guard_agent_config.rs create mode 100644 crates/candler-harness/src/agent_config.rs create mode 100644 crates/candler-harness/tests/it/guard_agent_config.rs diff --git a/crates/candler-core/src/jobs/orchestrate/controls.rs b/crates/candler-core/src/jobs/orchestrate/controls.rs index a4d1d691..159944a1 100644 --- a/crates/candler-core/src/jobs/orchestrate/controls.rs +++ b/crates/candler-core/src/jobs/orchestrate/controls.rs @@ -663,6 +663,7 @@ impl DockerControlRunner { gateway: None, job: job.clone(), // BORROW: the runtime owns its job id driver: Arc::clone(&rt.driver), + harnesses: rt.harnesses.clone(), // BORROW: the runtime owns its list cells: std::collections::BTreeMap::new(), eval_infra: rt.eval_infra.clone(), // BORROW: the runtime owns its build identity }; diff --git a/crates/candler-core/src/jobs/orchestrate/mod.rs b/crates/candler-core/src/jobs/orchestrate/mod.rs index 63cd72c6..4ec5fa89 100644 --- a/crates/candler-core/src/jobs/orchestrate/mod.rs +++ b/crates/candler-core/src/jobs/orchestrate/mod.rs @@ -122,6 +122,7 @@ async fn run_job( experiment_lock: rt.store.layout().experiment_lock(&fresh), secrets_present: secrets.present(), driver: Some(Arc::clone(&rt.driver)), + harnesses: rt.harnesses.clone(), // BORROW: the context owns its list }; let force = if spec.force { Force::Yes } else { Force::No }; let outcome = match plan_runs( diff --git a/crates/candler-core/src/jobs/runtime/mod.rs b/crates/candler-core/src/jobs/runtime/mod.rs index ff05f060..dd2ae201 100644 --- a/crates/candler-core/src/jobs/runtime/mod.rs +++ b/crates/candler-core/src/jobs/runtime/mod.rs @@ -48,6 +48,8 @@ pub struct JobServices { // TRAIT_OBJECT: the harness's driver, or a recording fake in tests /// What the runner needs from the harness, as data. pub driver: Arc, + /// The ids of the registered harnesses. + pub harnesses: Vec, /// Which build of the evaluation infrastructure runs the job. pub eval_infra: EvalInfra, } diff --git a/crates/candler-core/src/jobs/runtime/session.rs b/crates/candler-core/src/jobs/runtime/session.rs index b9e17ad2..9fe47288 100644 --- a/crates/candler-core/src/jobs/runtime/session.rs +++ b/crates/candler-core/src/jobs/runtime/session.rs @@ -354,6 +354,7 @@ async fn serve( gateway: None, job: job.clone(), // BORROW: the runtime owns its job id driver: services.driver, + harnesses: services.harnesses, cells: BTreeMap::new(), eval_infra: services.eval_infra, }; diff --git a/crates/candler-core/src/resolve/paths.rs b/crates/candler-core/src/resolve/paths.rs index 3e34b0af..031a51e7 100644 --- a/crates/candler-core/src/resolve/paths.rs +++ b/crates/candler-core/src/resolve/paths.rs @@ -7,14 +7,15 @@ use candler_harness::mcp; use candler_harness::spec::{AgentSetting, Answer, Cell, EffortLevel, PermissionMode}; use candler_schemas::execution::paths::{ BUDGET_PER_RUN_MAX_COST_USD, BUDGET_PER_RUN_TURNS, BUDGET_PER_RUN_WALL_S, ENV, ENVIRONMENTS, - HARNESS, INPUTS, ISOLATION_BUILD_CONTEXT, ISOLATION_BUILD_DOCKERFILE, ISOLATION_BUILD_LOCK, - ISOLATION_BUILD_PLUGIN, ISOLATION_BUILD_PRUNE, ISOLATION_BUILD_REQUIREMENTS, ISOLATION_EGRESS, - ISOLATION_ENV_LOCK, ISOLATION_IMAGE, ISOLATION_LIMITS, ISOLATION_LIMITS_CPUS, - ISOLATION_LIMITS_MEMORY, ISOLATION_LIMITS_PIDS, ISOLATION_NETWORK, ISOLATION_RECORD_PACKAGES, - MCP, MODEL_EFFORT, MODEL_ENDPOINT, MODEL_ID, MODEL_TOKEN_SECRET, PERMISSION_MODE, PLUGINS_DIRS, - PROMPT_TEMPLATE, PROMPT_VALUES, REQUEST_HARNESS, REQUEST_INPUTS, REQUEST_TREATMENT, - RUNNER_IDLE_S, RUNNER_MODE, SLOTS_COUNT, SLOTS_EVALUATORS, STORE_ROOT, TOOLS_ALLOWED, - TOOLS_DISALLOWED, TREATMENT, TREATMENT_SOURCE_PREFIX, + HARNESS, HOOKS, INPUTS, INSTRUCTIONS_GLOBAL, INSTRUCTIONS_WORKSPACE, ISOLATION_BUILD_CONTEXT, + ISOLATION_BUILD_DOCKERFILE, ISOLATION_BUILD_LOCK, ISOLATION_BUILD_PLUGIN, + ISOLATION_BUILD_PRUNE, ISOLATION_BUILD_REQUIREMENTS, ISOLATION_EGRESS, ISOLATION_ENV_LOCK, + ISOLATION_IMAGE, ISOLATION_LIMITS, ISOLATION_LIMITS_CPUS, ISOLATION_LIMITS_MEMORY, + ISOLATION_LIMITS_PIDS, ISOLATION_NETWORK, ISOLATION_RECORD_PACKAGES, MCP, MODEL_EFFORT, + MODEL_ENDPOINT, MODEL_ID, MODEL_TOKEN_SECRET, PERMISSION_MODE, PLUGINS_DIRS, PROMPT_TEMPLATE, + PROMPT_VALUES, REQUEST_HARNESS, REQUEST_INPUTS, REQUEST_TREATMENT, RUNNER_IDLE_S, RUNNER_MODE, + SLOTS_COUNT, SLOTS_EVALUATORS, STORE_ROOT, TOOLS_ALLOWED, TOOLS_DISALLOWED, TREATMENT, + TREATMENT_SOURCE_PREFIX, }; use candler_schemas::primitives::FieldPath; use candler_schemas::servers::McpServerKind; @@ -152,7 +153,7 @@ const fn key(path: &'static str, kind: Kind, file: ConfigFile, meaning: &'static } /// Every path the configuration surface names. -pub const CONFIGURATION_PATHS: [PathRow; 48] = [ +pub const CONFIGURATION_PATHS: [PathRow; 51] = [ row( MODEL_ID, Kind::Leaf, @@ -213,6 +214,27 @@ pub const CONFIGURATION_PATHS: [PathRow; 48] = [ ]), "The MCP servers of a run; the names below are free.", ), + row( + INSTRUCTIONS_GLOBAL, + Kind::Subtree, + Class::Value, + Reach::CandlerOnly, + "The global instruction text of each harness: a table of harness id (written with `_` for `-`) to text.", + ), + row( + INSTRUCTIONS_WORKSPACE, + Kind::Leaf, + Class::Value, + Reach::CandlerOnly, + "The instruction text at the root of the workspace.", + ), + row( + HOOKS, + Kind::Subtree, + Class::Value, + Reach::CandlerOnly, + "The hooks of each harness: a table of harness id (written with `_` for `-`) to its `settings` or `files`, or its `plugins`.", + ), row( PERMISSION_MODE, Kind::Leaf, diff --git a/crates/candler-core/src/runner/mod.rs b/crates/candler-core/src/runner/mod.rs index f36a293b..4d3c6a5b 100644 --- a/crates/candler-core/src/runner/mod.rs +++ b/crates/candler-core/src/runner/mod.rs @@ -65,6 +65,8 @@ pub struct Runtime { // TRAIT_OBJECT: the driver is the harness's, or a recording fake in tests /// What the runner needs from the harness, as data. pub driver: Arc, + /// The ids of the registered harnesses. + pub harnesses: Vec, /// What each cell of the job is, by its digest. pub cells: BTreeMap>, /// The build of the evaluation infrastructure that runs the job. diff --git a/crates/candler-core/src/runner/plan.rs b/crates/candler-core/src/runner/plan.rs index 085d8467..7dec2d32 100644 --- a/crates/candler-core/src/runner/plan.rs +++ b/crates/candler-core/src/runner/plan.rs @@ -10,6 +10,7 @@ use std::io; use std::path::{Path, PathBuf}; use std::sync::Arc; +use candler_harness::agent_config; use candler_harness::driver::{DriverError, HarnessDriver}; use candler_harness::spec::{AgentSetting, Cell}; @@ -56,6 +57,9 @@ pub struct PlanCtx { /// it cannot honour; `None` when the caller has none, and both are then left unchecked. // TRAIT_OBJECT: the binary selects the driver at runtime pub driver: Option>, + /// The ids of the registered harnesses, which the keys of a cell's `hooks` and + /// `instructions.global` must name. + pub harnesses: Vec, } /// Whether a forced plan may accept a differing re-check. @@ -149,7 +153,7 @@ pub fn experiment_of<'a>( file: &ExperimentFile, levels: impl Into>, ) -> Result { - let cells = fresh_cells(file, &levels.into(), None)?; + let cells = fresh_cells(file, &levels.into(), None, &[])?; let digests: Vec = cells.iter().map(|cell| cell.comparable.digest()).collect(); // BORROW: explicit .as_slice() instead of Deref coercion Ok(experiment_digest(digests.as_slice())) @@ -165,10 +169,11 @@ pub fn check_cells<'a>( file: &ExperimentFile, levels: impl Into>, driver: &dyn HarnessDriver, // TRAIT_OBJECT: the registry's driver, selected at run time + harnesses: &[String], ) -> Result<(), PlanError> { let levels = levels.into(); levels.replicates(file)?; - fresh_cells(file, &levels, Some(driver)).map(drop) + fresh_cells(file, &levels, Some(driver), harnesses).map(drop) } /// A deviation as `path {stored: , observed: }`, for a message; a value that was @@ -623,6 +628,7 @@ fn fresh_cells<'r>( file: &ExperimentFile, levels: &Levels<'r>, driver: Option<&dyn HarnessDriver>, + harnesses: &[String], ) -> Result>, PlanError> { let session_capable = driver.map(|driver| !driver.answer(AgentSetting::SessionMode).is_refused()); @@ -762,6 +768,9 @@ fn fresh_cells<'r>( if let Some(driver) = driver { for cell in &cells { let view = Cell::new(cell.comparable.values()); + let harness = driver.id().to_string(); // BORROW: .to_string() gives owned text + agent_config::instructions(&view, harness.as_str(), harnesses)?; // BORROW: explicit .as_str() + agent_config::hooks(&view, harness.as_str(), harnesses)?; // BORROW: explicit .as_str() refuse_unanswered(driver, &view)?; driver.check_settings(&view)?; } @@ -1189,7 +1198,12 @@ pub fn plan_runs<'a>( None } }; - let cells = fresh_cells(file, &levels, ctx.driver.as_deref())?; + let cells = fresh_cells( + file, + &levels, + ctx.driver.as_deref(), + ctx.harnesses.as_slice(), + )?; let ledger = read_ledger(&ctx.store)?; // BORROW: explicit .as_slice() instead of Deref coercion let matched = match_stored(cells.as_slice(), ledger.groups.as_slice())?; diff --git a/crates/candler-core/tests/it/guard_agent_config.rs b/crates/candler-core/tests/it/guard_agent_config.rs new file mode 100644 index 00000000..8a31f379 --- /dev/null +++ b/crates/candler-core/tests/it/guard_agent_config.rs @@ -0,0 +1,191 @@ +#![cfg(test)] +//! Guards for the instruction texts and hooks of a cell: the experiment can vary them, the cell +//! digest follows them, and the misuses are refused by name when the cells are planned. +//! +//! The values go through the real resolver and `plan_runs`; the expected codes and pointers are +//! written by hand. + +use std::collections::BTreeSet; +use std::path::Path; +use std::sync::Arc; + +use candler_core::resolve::config::{Config, UserConfig}; +use candler_core::resolve::layers::{FileValues, ResolveInput}; +use candler_core::resolve::preflight::Resolver; +use candler_core::runner::plan::{Force, PlanCtx, PlanError, PlanMode, plan_runs}; +use candler_harness::driver::HarnessDriver; +use candler_harness_claude_code::driver::ClaudeCodeDriver; +use candler_harness_opencode::driver::OpenCodeDriver; +use candler_schemas::execution::ExperimentFile; +use candler_schemas::primitives::Digest; +use candler_schemas::refusal::Refusal; +use candler_schemas::values::{JsonValue, ResolvedValue}; +use serde_json::{Value, json}; + +use crate::support; + +/// The experiment text with the factors `factors` (already TOML) and no `[fixed]` value. +fn experiment_with(factors: &str) -> ExperimentFile { + let text = format!( + "schema = \"experiment/1\"\nreplicates = 1\n\n{factors}\n[budget.per_run]\nwall_s = 60\n\n\ + [harness]\nname = \"claude-code\"\n\n[treatment]\nname = \"t\"\n" + ); + ExperimentFile::from_toml_str(&text).expect("an experiment") +} + +/// The digests of the cells `file` plans over the resolution of `fixed`, on `driver` when there +/// is one, with both shipped harnesses registered. +async fn planned( + file: &ExperimentFile, + fixed: &[(&str, Value)], + driver: Option>, +) -> Result, PlanError> { + let mut all = vec![ + ( + "harness", + json!({"name": "claude-code", "version": "2.1.311"}), + ), + ("treatment", json!({"name": "t"})), + ]; + all.extend(fixed.iter().map(|(path, value)| (*path, value.clone()))); + let cwd = Path::new("/work"); + let config = Arc::new(Config::new( + cwd.to_owned(), + None, + UserConfig::default(), + Some(cwd.join("state")), + )); + let values = all + .iter() + .map(|(path, value)| { + ( + path.parse().expect("a field path"), + JsonValue::new(value.clone()).expect("a JSON value"), + ) + }) + .collect(); + let mut resolution = Resolver::new(config) + .resolve(ResolveInput::new(Vec::new()).file(FileValues::new(values))) + .await + .expect("the fixed values resolve"); + resolution.settings.push(ResolvedValue::recorded( + "request.treatment".parse().expect("a field path"), + JsonValue::new(json!({"name": "t"})).expect("a JSON value"), + )); + let (_dir, store, lock) = support::run_plan::fresh_store(); + let ctx = PlanCtx { + store, + experiment_lock: lock, + secrets_present: BTreeSet::new(), + driver, + harnesses: vec!["claude-code".to_owned(), "opencode".to_owned()], + }; + let outcome = plan_runs(&ctx, file, &resolution, Force::No, PlanMode::Check)?; + Ok(outcome.plans.iter().map(|plan| plan.cell.clone()).collect()) +} + +/// Guards: two levels of `instructions.workspace`, and two levels of the settings of a harness's +/// hooks, plan two cells with two digests; one level plans one. +/// Oracle: the levels are written by hand; the count of digests is the count of cells. +/// Bite: leave the values out of the cell (both levels plan one cell, one digest). +#[tokio::test] +async fn two_levels_of_instructions_or_hooks_plan_two_cells() { + let levels = [ + ("instructions.workspace", ["\"text A\"", "\"text B\""]), + ( + "hooks.claude_code.settings", + ["'{\"SessionStart\": []}'", "'{\"Stop\": []}'"], + ), + ]; + for (path, [first, second]) in levels { + let two = experiment_with(&format!( + "[[factors]]\npath = \"{path}\"\nlevels = [{first}, {second}]\n" + )); + let cells = planned(&two, &[], None).await.expect("two levels plan"); + assert_eq!(cells.len(), 2, "{path}: two levels, two digests"); + let one = experiment_with(&format!( + "[[factors]]\npath = \"{path}\"\nlevels = [{first}]\n" + )); + let single = planned(&one, &[], None).await.expect("one level plans"); + assert_eq!(single.len(), 1, "{path}: one level, one digest"); + assert!(single.is_subset(&cells), "{path}: a level keeps its digest"); + } +} + +/// One misuse: the driver the cell meets, the value, and the refusal it earns. +struct Case { + name: &'static str, + driver: Arc, + fixed: (&'static str, Value), + code: &'static str, + pointer: Option<&'static str>, +} + +/// Guards: a hooks table with no entry for the cell's harness is refused as +/// `experiment.cell_value_missing` at `/fixed/hooks`, a global instruction table with none as the +/// same code at `/fixed/instructions.global`, a key that names no registered harness as +/// `experiment.cell_value_invalid`, and a hook file path with `..` as the same code at the file list. +/// Oracle: the codes and pointers are written by hand from the surface. +/// Bite: skip the reader at plan time (each cell plans). +#[tokio::test] +async fn misused_hooks_and_instructions_are_refused_by_name() { + let file = experiment_with(""); + let opencode: Arc = Arc::new(OpenCodeDriver::new()); + let claude: Arc = Arc::new(ClaudeCodeDriver::new()); + let case = |name, driver, fixed, code, pointer| Case { + name, + driver, + fixed, + code, + pointer, + }; + let cases = [ + case( + "hooks of another harness", + Arc::clone(&opencode), + ("hooks.claude_code.settings", json!("{}")), + "experiment.cell_value_missing", + Some("/fixed/hooks"), + ), + case( + "global text of another harness", + opencode, + ("instructions.global.claude_code", json!("text")), + "experiment.cell_value_missing", + Some("/fixed/instructions.global"), + ), + case( + "an unregistered harness key", + Arc::clone(&claude), + ("hooks.nosuch.settings", json!("{}")), + "experiment.cell_value_invalid", + Some("/hooks"), + ), + case( + "a hook file path with `..`", + claude, + ( + "hooks.claude_code.files", + json!([{"path": "../evil.sh", "text": "x"}]), + ), + "experiment.cell_value_invalid", + Some("/hooks/claude_code/files"), + ), + ]; + for Case { + name, + driver, + fixed, + code, + pointer, + } in cases + { + match planned(&file, &[fixed], Some(driver)).await { + Err(error) => { + assert_eq!(Refusal::code(&error).as_str(), code, "{name}"); + assert_eq!(Refusal::path(&error).as_deref(), pointer, "{name}"); + } + Ok(_) => panic!("{name}: planned"), + } + } +} diff --git a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs index c7cbb8d7..a0fc1bf9 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs @@ -145,6 +145,7 @@ async fn controls_e2e_pinned_harness_passes() { gateway: None, job: rig.job.clone(), driver: Arc::new(ClaudeCodeDriver::new()), + harnesses: Vec::new(), cells: std::collections::BTreeMap::new(), eval_infra: EvalInfra::default(), }; diff --git a/crates/candler-core/tests/it/guard_egress_setting.rs b/crates/candler-core/tests/it/guard_egress_setting.rs index 772e7f67..b7b979cf 100644 --- a/crates/candler-core/tests/it/guard_egress_setting.rs +++ b/crates/candler-core/tests/it/guard_egress_setting.rs @@ -445,6 +445,7 @@ async fn planned( experiment_lock: lock, secrets_present: BTreeSet::new(), driver: Some(Arc::new(ClaudeCodeDriver::new())), + harnesses: Vec::new(), }; let outcome = plan_runs(&ctx, file, &resolution, Force::No, PlanMode::Check)?; let spec = JobSpec { diff --git a/crates/candler-core/tests/it/guard_job_runtime.rs b/crates/candler-core/tests/it/guard_job_runtime.rs index 7d20b72a..6a43a7e4 100644 --- a/crates/candler-core/tests/it/guard_job_runtime.rs +++ b/crates/candler-core/tests/it/guard_job_runtime.rs @@ -375,6 +375,7 @@ fn reap_child() { gateway: None, job: own.clone(), // BORROW: the runtime owns its job id driver: Arc::new(QuietDriver), + harnesses: Vec::new(), cells: BTreeMap::new(), eval_infra: EvalInfra::default(), }; diff --git a/crates/candler-core/tests/it/guard_session.rs b/crates/candler-core/tests/it/guard_session.rs index 3f9ee5da..9b0a3b97 100644 --- a/crates/candler-core/tests/it/guard_session.rs +++ b/crates/candler-core/tests/it/guard_session.rs @@ -300,6 +300,7 @@ async fn planned( } else { Arc::new(OpenCodeDriver::new()) }), + harnesses: Vec::new(), }; let outcome = plan_runs(&ctx, file, &resolution, Force::No, PlanMode::Check)?; let spec = JobSpec { diff --git a/crates/candler-core/tests/it/main.rs b/crates/candler-core/tests/it/main.rs index 887d250e..25408e11 100644 --- a/crates/candler-core/tests/it/main.rs +++ b/crates/candler-core/tests/it/main.rs @@ -4,6 +4,7 @@ mod oracle; mod support; +mod guard_agent_config; mod guard_analysis_report; mod guard_analysis_summary; mod guard_assert_clean; diff --git a/crates/candler-core/tests/it/support/job_orchestrate.rs b/crates/candler-core/tests/it/support/job_orchestrate.rs index 5ccfeec5..a48226fe 100644 --- a/crates/candler-core/tests/it/support/job_orchestrate.rs +++ b/crates/candler-core/tests/it/support/job_orchestrate.rs @@ -658,6 +658,7 @@ impl Rig { gateway: None, job: self.job.clone(), driver: Arc::new(QuietDriver), + harnesses: Vec::new(), cells: BTreeMap::new(), eval_infra: EvalInfra::default(), } diff --git a/crates/candler-core/tests/it/support/job_runtime.rs b/crates/candler-core/tests/it/support/job_runtime.rs index c5ea1d22..ac48cd2c 100644 --- a/crates/candler-core/tests/it/support/job_runtime.rs +++ b/crates/candler-core/tests/it/support/job_runtime.rs @@ -69,6 +69,7 @@ pub fn services() -> JobServices { JobServices { // TRAIT_OBJECT: the driver is the harness's real one, which a guard never calls driver: Arc::new(ClaudeCodeDriver::new()), + harnesses: Vec::new(), eval_infra: EvalInfra::default(), } } diff --git a/crates/candler-core/tests/it/support/run_plan.rs b/crates/candler-core/tests/it/support/run_plan.rs index e1253fbf..21a1321e 100644 --- a/crates/candler-core/tests/it/support/run_plan.rs +++ b/crates/candler-core/tests/it/support/run_plan.rs @@ -228,6 +228,7 @@ pub fn plan_ctx(store: &Store, lock: &Path, facts: &Facts) -> PlanCtx { .map(|name| name.parse::().expect("a secret name")) .collect::>(), driver: None, + harnesses: Vec::new(), } } diff --git a/crates/candler-harness/src/agent_config.rs b/crates/candler-harness/src/agent_config.rs new file mode 100644 index 00000000..1e390195 --- /dev/null +++ b/crates/candler-harness/src/agent_config.rs @@ -0,0 +1,245 @@ +//! The instruction texts and hooks of a cell, as the harness the cell runs reads them. +//! +//! [`instructions`] and [`hooks`] are the one reader of `instructions.*` and `hooks`: both +//! drivers and the core read the values through them, and each refuses what it does not +//! understand. The cell holds the values as leaves (see [`candler_schemas::agent_config`]); a +//! harness id is written with `_` where it has `-`, and every id below `instructions.global` and +//! `hooks` is checked against the harnesses the caller says are registered. + +use std::str::FromStr as _; + +use candler_schemas::agent_config::{ClaudeCodeHooks, Instructions, OpenCodeHooks}; +use candler_schemas::execution::paths::{HOOKS, INSTRUCTIONS_GLOBAL}; +use candler_schemas::field_path; +use candler_schemas::primitives::{FieldPath, RelPath}; +use serde::Deserialize; +use serde_json::{Map, Value}; + +use crate::driver::DriverError; +use crate::spec::Cell; + +/// The id of the Claude Code harness. +const CLAUDE_CODE: &str = "claude-code"; +/// The id of the `OpenCode` harness. +const OPENCODE: &str = "opencode"; + +/// The hooks the cell gives the harness it runs. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum Hooks { + /// The hooks of a Claude Code cell. + ClaudeCode(ClaudeCodeHooks), + /// The hooks of an `OpenCode` cell. + OpenCode(OpenCodeHooks), +} + +/// One file of a hook list: where it goes and what it holds. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct HookFile { + path: String, + text: String, +} + +/// How a harness id is written as a key of a cell value. +fn spelled(id: &str) -> String { + id.replace('-', "_") +} + +/// The field path `text`, or `root` when `text` is not one. +fn at(text: &str, root: &FieldPath) -> FieldPath { + FieldPath::from_str(text).unwrap_or_else(|_| root.clone()) // BORROW: the error owns the path +} + +fn invalid(path: &FieldPath, detail: impl Into) -> DriverError { + DriverError::InvalidValue { + path: path.clone(), // BORROW: the error owns the path + detail: detail.into(), + } +} + +/// The registered harness whose key is `key`. +fn registered_id<'a>( + key: &str, + registered: &'a [String], + root: &FieldPath, +) -> Result<&'a str, DriverError> { + registered + .iter() + .find(|id| spelled(id) == key) + .map(String::as_str) // BORROW: explicit .as_str() instead of Deref coercion + .ok_or_else(|| { + let names: Vec = registered.iter().map(|id| spelled(id)).collect(); + invalid( + root, + format!( + "`{key}` names no registered harness; the registered ones are {}", + names.join(", ") + ), + ) + }) +} + +fn object<'v>(value: &'v Value, path: &FieldPath) -> Result<&'v Map, DriverError> { + value + .as_object() + .ok_or_else(|| invalid(path, "is not a table")) +} + +fn text<'v>(value: &'v Value, path: &FieldPath) -> Result<&'v str, DriverError> { + value.as_str().ok_or_else(|| invalid(path, "is not text")) +} + +/// A list of `{path, text}` entries as the object from path to text. +/// +/// # Errors +/// [`DriverError::InvalidValue`] for an entry that is not `{path, text}`, a path that is not a +/// relative path, or a path that repeats. +fn files(value: &Value, at_path: &FieldPath) -> Result { + let Value::Array(items) = value else { + return Err(invalid(at_path, "is not a list of `{path, text}` entries")); + }; + let mut out = Map::new(); + for item in items { + let entry: HookFile = serde_json::from_value(item.clone()) // BORROW: .clone() copies the entry out of the cell + .map_err(|error| invalid(at_path, error.to_string()))?; // BORROW: .to_string() gives owned text + RelPath::from_str(&entry.path).map_err(|error| invalid(at_path, error.to_string()))?; // BORROW: .to_string() gives owned text + if out + .insert(entry.path.clone(), Value::String(entry.text)) + .is_some() + { + // BORROW: .clone() keeps the path for the message + return Err(invalid( + at_path, + format!("holds the path `{}` twice", entry.path), + )); + } + } + Ok(Value::Object(out)) +} + +/// The entry of one harness shaped as the object its envelope reads: `settings` read as the JSON +/// object its text holds, the list named `list` as an object from path to text. +fn shaped( + entry: &Value, + entry_path: &str, + root: &FieldPath, + list: &str, + settings: bool, +) -> Result { + let entry_at = at(entry_path, root); + let mut out = Map::new(); + for (member, value) in object(entry, &entry_at)? { + let member_at = at(&format!("{entry_path}.{member}"), root); + if settings && member == "settings" { + let parsed: Value = serde_json::from_str(text(value, &member_at)?) + .map_err(|error| invalid(&member_at, format!("is not JSON: {error}")))?; + if !parsed.is_object() { + return Err(invalid(&member_at, "is not the text of a JSON object")); + } + out.insert(member.clone(), parsed); // BORROW: the object owns its key + } else if member == list { + out.insert(member.clone(), files(value, &member_at)?); // BORROW: the object owns its key + } else { + return Err(invalid( + &member_at, + format!( + "is not a member of the hooks of this harness; they are `{list}`{}", + if settings { " and `settings`" } else { "" } + ), + )); + } + } + Ok(Value::Object(out)) +} + +/// The instruction texts of a cell, with the global text of every harness it names. `None` when +/// the cell sets none. +/// +/// `harness` is the id of the harness the cell runs and `registered` the ids of every harness +/// that is registered. +/// +/// # Errors +/// [`DriverError::InvalidValue`] when a value is not text or a key names no registered harness, +/// and [`DriverError::MissingValue`] when the cell sets a global text and none for `harness`. +pub fn instructions( + cell: &Cell<'_>, + harness: &str, + registered: &[String], +) -> Result, DriverError> { + let Some(table) = cell.table_at(&field_path!("instructions"))? else { + return Ok(None); + }; + let global_path = field_path!("instructions.global"); + let mut shaped = Map::new(); + for (member, value) in &table { + match member.as_str() { + "global" => { + let mut by_id = Map::new(); + for (key, text_value) in object(value, &global_path)? { + let id = registered_id(key, registered, &global_path)?; + let own = at(&format!("{INSTRUCTIONS_GLOBAL}.{key}"), &global_path); + text(text_value, &own)?; + by_id.insert(id.to_owned(), text_value.clone()); // BORROW: the object owns its key and text + } + if !by_id.contains_key(harness) { + return Err(DriverError::MissingValue { path: global_path }); + } + shaped.insert(member.clone(), Value::Object(by_id)); // BORROW: the object owns its key + } + "workspace" => { + text(value, &field_path!("instructions.workspace"))?; + shaped.insert(member.clone(), value.clone()); // BORROW: the object owns its key and value + } + _ => { + return Err(invalid( + &at( + &format!("instructions.{member}"), + &field_path!("instructions"), + ), + "is not an instruction text; they are `global` and `workspace`", + )); + } + } + } + serde_json::from_value(Value::Object(shaped)) + .map(Some) + .map_err(|error| invalid(&field_path!("instructions"), error.to_string())) // BORROW: .to_string() gives owned text +} + +/// The hooks of a cell for `harness`. `None` when the cell sets none. +/// +/// # Errors +/// [`DriverError::InvalidValue`] when a key names no registered harness or the entry of `harness` +/// does not fit its envelope (a hook file whose path is not a relative path included), and +/// [`DriverError::MissingValue`] when the cell sets hooks and none for `harness`. +pub fn hooks( + cell: &Cell<'_>, + harness: &str, + registered: &[String], +) -> Result, DriverError> { + let root = field_path!("hooks"); + let Some(table) = cell.table_at(&root)? else { + return Ok(None); + }; + for key in table.keys() { + registered_id(key, registered, &root)?; + } + let key = spelled(harness); + let Some(entry) = table.get(&key) else { + return Err(DriverError::MissingValue { path: root }); + }; + let entry_path = format!("{HOOKS}.{key}"); + match harness { + CLAUDE_CODE => serde_json::from_value(shaped(entry, &entry_path, &root, "files", true)?) + .map(|found| Some(Hooks::ClaudeCode(found))) + .map_err(|error| invalid(&at(&entry_path, &root), error.to_string())), // BORROW: .to_string() gives owned text + OPENCODE => serde_json::from_value(shaped(entry, &entry_path, &root, "plugins", false)?) + .map(|found| Some(Hooks::OpenCode(found))) + .map_err(|error| invalid(&at(&entry_path, &root), error.to_string())), // BORROW: .to_string() gives owned text + other => Err(invalid( + &at(&entry_path, &root), + format!("`{other}` has no hooks"), + )), + } +} diff --git a/crates/candler-harness/src/lib.rs b/crates/candler-harness/src/lib.rs index 709ef70d..8a1dd928 100644 --- a/crates/candler-harness/src/lib.rs +++ b/crates/candler-harness/src/lib.rs @@ -7,11 +7,13 @@ //! //! - [`spec`] holds the data a driver returns to the core. //! - [`driver`] holds [`driver::HarnessDriver`] and its error. +//! - [`agent_config`] holds the one reader of a cell's instruction texts and hooks. //! - [`skills`] holds [`skills::SkillTree`], where a harness reads its skills. //! - [`reader`] holds [`reader::TraceReader`], its frame input and its error. #![deny(clippy::allow_attributes)] +pub mod agent_config; #[cfg(feature = "conformance")] pub mod conformance; pub mod driver; diff --git a/crates/candler-harness/src/refusal.rs b/crates/candler-harness/src/refusal.rs index 24de5124..390d8006 100644 --- a/crates/candler-harness/src/refusal.rs +++ b/crates/candler-harness/src/refusal.rs @@ -22,12 +22,13 @@ fn no_path(_error: &E) -> Option { fn driver_error_path(error: &DriverError) -> Option { match error { DriverError::Command(inner) => Refusal::path(inner), + DriverError::MissingValue { path } => { + Some(pointer_of(["fixed", path.to_string().as_str()])) + } // BORROW: .to_string() gives owned text DriverError::Unsupported { path, .. } => Some(path.clone()), // BORROW: the path owns its text DriverError::InvalidValue { path, .. } => Some(pointer_of(path.segments())), DriverError::AmbiguousServers { .. } => Some("/mcp/servers".to_owned()), // BORROW: .to_owned() makes the owned pointer - DriverError::MissingValue { .. } - | DriverError::VersionOutput { .. } - | DriverError::Record { .. } => None, + DriverError::VersionOutput { .. } | DriverError::Record { .. } => None, } } @@ -36,8 +37,8 @@ refusal_table! { MissingValue { .. } => row( "experiment.cell_value_missing", Side::Experiment, - "A cell lacks a value that the harness driver needs.", - "-", + "A cell lacks a value that the harness driver needs, such as a hooks table that has no entry for the cell's harness.", + "The key of `[fixed]` that holds the value, such as `/fixed/hooks`.", ), InvalidValue { .. } => row( "experiment.cell_value_invalid", diff --git a/crates/candler-harness/tests/it/guard_agent_config.rs b/crates/candler-harness/tests/it/guard_agent_config.rs new file mode 100644 index 00000000..bbcf4944 --- /dev/null +++ b/crates/candler-harness/tests/it/guard_agent_config.rs @@ -0,0 +1,104 @@ +//! The instruction texts and hooks of a cell, read as the harness's own envelope. +#![cfg(test)] + +use std::str::FromStr as _; + +use candler_harness::agent_config::{Hooks, hooks, instructions}; +use candler_harness::driver::DriverError; +use candler_harness::spec::Cell; +use candler_schemas::primitives::FieldPath; +use candler_schemas::values::{JsonValue, ResolvedValue}; +use serde_json::{Value, json}; + +type Res = Result>; + +fn registered() -> Vec { + vec!["claude-code".to_owned(), "opencode".to_owned()] +} + +fn cell(entries: &[(&str, Value)]) -> Res> { + entries + .iter() + .map(|(path, value)| { + Ok(ResolvedValue::recorded( + FieldPath::from_str(path)?, + JsonValue::new(value.clone())?, + )) + }) + .collect() +} + +/// Guards: the hooks of a Claude Code cell are read as the settings object its text holds and the +/// files it lists, and the global and workspace texts as their envelope. +/// Oracle: the values are written by hand. +/// Bite: read `settings` as text, or the file list as a list (the typed envelopes differ). +#[test] +fn a_cell_gives_each_harness_its_own_envelope() -> Res<()> { + let values = cell(&[ + ("hooks.claude_code.settings", json!("{\"Stop\": []}")), + ( + "hooks.claude_code.files", + json!([{"path": "guard.sh", "text": "#!/bin/sh"}]), + ), + ( + "hooks.opencode.plugins", + json!([{"path": "p.js", "text": "x"}]), + ), + ("instructions.global.claude_code", json!("global")), + ("instructions.workspace", json!("workspace")), + ])?; + let view = Cell::new(&values); + let Some(Hooks::ClaudeCode(found)) = hooks(&view, "claude-code", ®istered())? else { + return Err("claude code hooks".into()); + }; + assert_eq!(found.settings.map(Value::Object), Some(json!({"Stop": []}))); + assert_eq!(found.files.len(), 1); + let Some(Hooks::OpenCode(found)) = hooks(&view, "opencode", ®istered())? else { + return Err("opencode hooks".into()); + }; + assert_eq!(found.plugins.len(), 1); + let Some(text) = instructions(&view, "claude-code", ®istered())? else { + return Err("instructions".into()); + }; + assert_eq!( + text.global.get("claude-code").map(String::as_str), + Some("global") + ); + assert_eq!(text.workspace.as_deref(), Some("workspace")); + Ok(()) +} + +/// Guards: an entry that is not an envelope member, settings that are not a JSON object, and a +/// file path that appears twice are each refused at the value. +/// Oracle: the refused values are written by hand. +/// Bite: ignore unknown members, or parse the settings leniently. +#[test] +fn an_entry_that_does_not_fit_its_envelope_is_refused() -> Res<()> { + let refused = |entries: &[(&str, Value)]| -> Res { + let values = cell(entries)?; + match hooks(&Cell::new(&values), "claude-code", ®istered()) { + Err(DriverError::InvalidValue { path, .. }) => Ok(path.to_string()), + other => Err(format!("expected an invalid value, got {other:?}").into()), + } + }; + assert_eq!( + refused(&[("hooks.claude_code.plugins", json!([]))])?, + "hooks.claude_code.plugins" + ); + assert_eq!( + refused(&[("hooks.claude_code.settings", json!("[1]"))])?, + "hooks.claude_code.settings" + ); + assert_eq!( + refused(&[("hooks.claude_code.settings", json!("not json"))])?, + "hooks.claude_code.settings" + ); + assert_eq!( + refused(&[( + "hooks.claude_code.files", + json!([{"path": "a", "text": "x"}, {"path": "a", "text": "y"}]) + )])?, + "hooks.claude_code.files" + ); + Ok(()) +} diff --git a/crates/candler-harness/tests/it/main.rs b/crates/candler-harness/tests/it/main.rs index 274e9fd3..b9b8a4a2 100644 --- a/crates/candler-harness/tests/it/main.rs +++ b/crates/candler-harness/tests/it/main.rs @@ -5,5 +5,6 @@ mod support; #[cfg(feature = "conformance")] mod conformance_shapes; +mod guard_agent_config; mod guard_mcp_names; mod guard_session_id; diff --git a/crates/candler/src/commands/resolve.rs b/crates/candler/src/commands/resolve.rs index d1b3f6f0..10995e85 100644 --- a/crates/candler/src/commands/resolve.rs +++ b/crates/candler/src/commands/resolve.rs @@ -309,7 +309,13 @@ pub async fn run(args: Args, store: Option<&Path>) -> Result { let Some(resolution) = levels.first().cloned() else { return Ok(Exit::Success); }; - check_cells(&file, levels.as_slice(), driver.as_ref()).map_err(CliError::refused_by)?; // BORROW: explicit .as_slice() + check_cells( + &file, + levels.as_slice(), + driver.as_ref(), + Registry::builtin().names().as_slice(), + ) + .map_err(CliError::refused_by)?; // BORROW: explicit .as_slice() if text { for line in render_values(&resolution, Paint::detect()) { writeln!(stdout, "{line}").map_err(failed_here)?; diff --git a/crates/candler/src/commands/run.rs b/crates/candler/src/commands/run.rs index 3251c118..1cfb4069 100644 --- a/crates/candler/src/commands/run.rs +++ b/crates/candler/src/commands/run.rs @@ -271,6 +271,7 @@ fn plan_job( experiment_lock: store.layout().experiment_lock(&experiment), secrets_present: EnvSecrets::new(file.secrets()).present(), driver: Some(driver), + harnesses: Registry::builtin().names(), }; let mode = if force { Force::Yes } else { Force::No }; let outcome = plan_runs(&ctx, file, levels.as_slice(), mode, PlanMode::Check) // BORROW: explicit .as_slice() diff --git a/crates/candler/src/commands/supervise.rs b/crates/candler/src/commands/supervise.rs index 5c5334b1..1400198b 100644 --- a/crates/candler/src/commands/supervise.rs +++ b/crates/candler/src/commands/supervise.rs @@ -191,6 +191,7 @@ async fn run_job(store: Store, job: JobId, spec: JobSpec) -> Result` on the command line; permission mode: acceptEdits: `--permission-mode ` on the command line; permission mode: plan: `--permission-mode ` on the command line; permission mode: bypassPermissions: `--permission-mode ` on the command line; permission mode: auto: `--permission-mode ` on the command line; permission mode: dontAsk: `--permission-mode ` on the command line | permission mode: default: no (Claude Code's default mode allows reads and a built-in, non-configurable set of read-only shell commands that its own parser decides, and denies the rest in a headless run. OpenCode without `--auto` also rejects what no rule allows, but its shell rows are wildcards on the text of each parsed command, which approximate that set without being it); permission mode: acceptEdits: no (Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, rm, rmdir, mv, cp and sed, inside the working directory only. OpenCode's shell resource is the command's text, which knows no working directory, so "inside it" cannot be written as a rule); permission mode: plan: no (Claude Code's plan mode reads and runs read-only shell commands (a built-in, non-configurable set its own parser decides). The OpenCode ruleset that is certainly read-only (the `explore` agent's: deny everything, allow read, glob, grep, webfetch, websearch, skill) denies the shell altogether, and a wildcard on command text cannot express the read-only set; the stock `plan` agent is not read-only once a global rule follows it (the last match wins) and its `subagent` child can edit); permission mode: bypassPermissions: `--auto` on the command line: every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` answers the one pending ask (`.env` reads) with once, which a headless run needs; permission mode: auto: no (Claude Code's auto mode has a model classifier review each action, such as a shell command or a network request, before it runs. OpenCode has no classifier, and a ruleset decides by the action's text alone); permission mode: dontAsk: no (Claude Code's dontAsk mode denies every call that would prompt, so it allows the allow rules plus reads and the built-in, non-configurable set of read-only shell commands its own parser decides. OpenCode's shell rows are wildcards on the text of each parsed command, which approximate that set without being it) | | `request.harness` | the path | request key | The harness the run uses. | Candler only | Candler only | | `request.treatment` | the path | request key | The treatment the run applies. | Candler only | Candler only | diff --git a/docs/contract/driver-traits.md b/docs/contract/driver-traits.md index 316c109f..f3bf6f52 100644 --- a/docs/contract/driver-traits.md +++ b/docs/contract/driver-traits.md @@ -61,7 +61,7 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | Code | When | Path at fault | Side to fix | |---|---|---|---| | `experiment.cell_value_invalid` | A cell value cannot be used by the harness driver. | The field of the value, such as `/mcp/servers/fs/command`. | experiment | -| `experiment.cell_value_missing` | A cell lacks a value that the harness driver needs. | - | experiment | +| `experiment.cell_value_missing` | A cell lacks a value that the harness driver needs, such as a hooks table that has no entry for the cell's harness. | The key of `[fixed]` that holds the value, such as `/fixed/hooks`. | experiment | | `experiment.mcp_server_prefix_ambiguous` | Two MCP servers of a cell have names that make one tool name read two ways: the name of one, then `_`, is a prefix of the other's name, so a tool of the longer-named server cannot be told from a tool of the shorter-named one. | The table of servers, `/mcp/servers`. | experiment | | `experiment.setting_unsupported` | The experiment sets a setting that the harness has no way to honour, such as a turn cap for a harness with no turn limit; the run is refused rather than the setting dropped. | The setting in the experiment file: a field under `/budget`, or the key of `[fixed]` that holds it, such as `/fixed/model.effort`. | experiment | | `harness.session_record_unreadable` | A session record that the harness wrote, such as a hook payload or a stream event, cannot be read by the driver's tracker. | - | environment | diff --git a/docs/contract/experiment-file.md b/docs/contract/experiment-file.md index 10823b03..be6ae56c 100644 --- a/docs/contract/experiment-file.md +++ b/docs/contract/experiment-file.md @@ -65,7 +65,7 @@ Wire line: `schemas@0.13.0`. | `canonical.syntax_invalid` | A text is not valid JSON. | - | experiment | | `experiment.absolute_path` | A value holds an absolute path as a string, and a file enters a cell as an input digest. | - | experiment | | `experiment.cell_value_invalid` | A cell value cannot be used by the harness driver. | The field of the value, such as `/mcp/servers/fs/command`. | experiment | -| `experiment.cell_value_missing` | A cell lacks a value that the harness driver needs. | - | experiment | +| `experiment.cell_value_missing` | A cell lacks a value that the harness driver needs, such as a hooks table that has no entry for the cell's harness. | The key of `[fixed]` that holds the value, such as `/fixed/hooks`. | experiment | | `experiment.cost_not_positive` | A cost cap is not a finite number above 0. | - | experiment | | `experiment.count_zero` | A count, duration or process id that must be at least 1 is 0. | The field when it is `replicates` or one under `budget`; none otherwise. | experiment | | `experiment.document_invalid` | The TOML is not an experiment file: a field is missing, has the wrong type or breaks the format of its own. | The field at fault, or its parent table when a field is missing; none at the root. | experiment | From 514c7db13ff0249bf1e448dde38e6d2a43e5b836 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 14:19:14 +0900 Subject: [PATCH 15/69] feat(schemas): show the instructions and hooks of an inspected run Co-Authored-By: Claude Sonnet 5.5 --- .../candler-schemas/schema/inspect-run.schema.json | 12 ++++++++++++ crates/candler-schemas/src/inspect.rs | 5 +++++ 2 files changed, 17 insertions(+) diff --git a/crates/candler-schemas/schema/inspect-run.schema.json b/crates/candler-schemas/schema/inspect-run.schema.json index 98273ae2..dada46cc 100644 --- a/crates/candler-schemas/schema/inspect-run.schema.json +++ b/crates/candler-schemas/schema/inspect-run.schema.json @@ -46,12 +46,22 @@ "experiment": { "description": "The digest of the experiment the run belongs to." }, + "hooks": { + "additionalProperties": true, + "description": "The resolved `hooks.*` values the cell hashes, by path: the hooks the run was given.", + "type": "object" + }, "host": { "description": "The host the run was made on." }, "import": { "description": "What the run was imported from, for an imported run." }, + "instructions": { + "additionalProperties": true, + "description": "The resolved `instructions.*` values the cell hashes, by path: the instruction texts the\nrun was given.", + "type": "object" + }, "integrity": { "description": "The integrity verdict of the manifest." }, @@ -102,6 +112,8 @@ "run", "sealed", "mcp", + "instructions", + "hooks", "provenance", "measured", "outcomes" diff --git a/crates/candler-schemas/src/inspect.rs b/crates/candler-schemas/src/inspect.rs index a33c1949..077cf5be 100644 --- a/crates/candler-schemas/src/inspect.rs +++ b/crates/candler-schemas/src/inspect.rs @@ -73,6 +73,11 @@ pub struct InspectRun { /// The resolved `mcp.*` values the cell hashes, by path: the MCP configuration the run was /// installed with. pub mcp: BTreeMap, + /// The resolved `instructions.*` values the cell hashes, by path: the instruction texts the + /// run was given. + pub instructions: BTreeMap, + /// The resolved `hooks.*` values the cell hashes, by path: the hooks the run was given. + pub hooks: BTreeMap, /// The measured values under `provenance.`, by path. pub provenance: BTreeMap, /// The other measured values, by path. From 6e9f4fc41a8e1678a3b542436c1a618b8b73c465 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 14:19:55 +0900 Subject: [PATCH 16/69] feat(runner): record each run's starting context in the trace Co-Authored-By: Claude Sonnet 5.5 --- __design__/architecture.md | 3 +- assets/docker/gateway/gw.js | 75 +++++- assets/docker/gateway/nginx.conf.template | 7 + crates/candler-core/src/isolation/gateway.rs | 107 ++++++-- .../src/jobs/orchestrate/controls.rs | 64 ++++- crates/candler-core/src/runner/exec/gather.rs | 28 +- crates/candler-core/src/runner/exec/mod.rs | 40 ++- .../tests/it/guard_container_e2e.rs | 2 +- .../it/guard_container_e2e/controls_e2e.rs | 254 +++++++++++------- .../it/guard_container_e2e/gateway_e2e.rs | 130 ++++++++- .../tests/it/guard_trace_context_start.rs | 246 +++++++++++++++++ crates/candler-core/tests/it/main.rs | 1 + .../tests/it/support/contract_pages/pages.rs | 12 +- docs/contract/index.md | 1 + docs/contract/trace-file.md | 108 ++++++++ 15 files changed, 928 insertions(+), 150 deletions(-) create mode 100644 crates/candler-core/tests/it/guard_trace_context_start.rs create mode 100644 docs/contract/trace-file.md diff --git a/__design__/architecture.md b/__design__/architecture.md index 95a62328..81dab704 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -1234,7 +1234,8 @@ never compares an inventory with one of another source. The census names no serv `Session {id, source{harness, harness_version, reader, reader_version}, model, started_at?, ended_at?, ended_by, parent_session?, raw_ref}`; `Event {seq, at?, kind, span?, raw_ref, ext}` with -kinds `user_message`, `assistant_message`, `tool_call` (`origin`, `argv?`, `wrapped_calls[]?` for a +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` (`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/assets/docker/gateway/gw.js b/assets/docker/gateway/gw.js index 54202ab6..4651178a 100644 --- a/assets/docker/gateway/gw.js +++ b/assets/docker/gateway/gw.js @@ -108,4 +108,77 @@ function census(r) { + " seq=" + r.variables.gw_n + " tools=" + JSON.stringify(names); } -export default { authentic, strip, seq, census }; +// The text of a message `content` or of a `system` value: the string itself, or the `text` of +// each block of a list, joined by a newline. Anything else is "". +function textOf(content) { + if (typeof content === "string") { + return content; + } + if (!Array.isArray(content)) { + return ""; + } + const parts = []; + for (let i = 0; i < content.length; i++) { + const block = content[i]; + if (block !== null && typeof block === "object" && typeof block.text === "string") { + parts.push(block.text); + } + } + return parts.join("\n"); +} + +// The starting context of a run: its first request that carries tools, taken in the order the +// requests began. A request is recorded when no request of its run with a lower sequence number +// has been recorded, so a run records the first tooled request, and one more only when a request +// that began earlier ends later. The reader keeps the lowest. +// +// `system` is the system text: the top-level `system` of the Anthropic form (a string, or a list +// of blocks) followed by the `system` and `developer` messages of the OpenAI form. `first_message` +// is the first `user` message, every content block of it. Block texts are joined by a newline. +// The line is `run= tag= seq= body=`, with the JSON as the last field. "" for +// a request that is not authentic, carries no tools, or is not lower than one recorded. +function context(r) { + if (authentic(r) !== "1") { + return ""; + } + let body; + try { + body = JSON.parse(r.variables.request_body); + } catch (e) { + return ""; + } + if (body === null || typeof body !== "object" || Array.isArray(body)) { + return ""; + } + const tools = Array.isArray(body.tools) ? body.tools : []; + if (!tools.some((entry) => toolName(entry) !== undefined)) { + return ""; + } + const run = r.variables.gw_run; + const n = Number(r.variables.gw_n); + const lowest = ngx.shared.gwctx.get(run); + if (lowest !== undefined && lowest <= n) { + return ""; + } + ngx.shared.gwctx.set(run, n); + const messages = Array.isArray(body.messages) ? body.messages : []; + const system = body.system === undefined ? [] : [textOf(body.system)]; + let first = ""; + let found = false; + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + if (message === null || typeof message !== "object") { + continue; + } + if (message.role === "system" || message.role === "developer") { + system.push(textOf(message.content)); + } else if (message.role === "user" && !found) { + first = textOf(message.content); + found = true; + } + } + return "run=" + run + " tag=" + r.variables.gw_tag + " seq=" + r.variables.gw_n + + " body=" + JSON.stringify({ system: system.join("\n"), first_message: first }); +} + +export default { authentic, strip, seq, census, context }; diff --git a/assets/docker/gateway/nginx.conf.template b/assets/docker/gateway/nginx.conf.template index 3835ac77..13507a5b 100644 --- a/assets/docker/gateway/nginx.conf.template +++ b/assets/docker/gateway/nginx.conf.template @@ -10,9 +10,13 @@ http { js_import gw from /etc/gw/gw.js; # The count of model requests per run key, for the census line. js_shared_dict_zone zone=gwseq:256k timeout=24h type=number evict; + # The lowest sequence number per run key whose starting context is recorded. + js_shared_dict_zone zone=gwctx:256k timeout=24h type=number evict; # The census line of a model request: run, tag, sequence number and the names of its tools. js_set $gw_seq gw.seq; js_set $gw_census gw.census; + # The starting context of a run: its first request that carries tools, in full. + js_set $gw_context gw.context; # "1" when the request holds the job's dummy token and no other credential. js_set $gw_authentic gw.authentic; # The model name, unquoted-regex form of a map key. @@ -35,6 +39,8 @@ http { log_format gw escape=json 'ts=$time_iso8601 run=$gw_run tag=$gw_tag method=$request_method status=$status up_status=$upstream_status req_ms=$request_time up_ms=$upstream_response_time req_bytes=$request_length resp_bytes=$bytes_sent model=$gw_model path="$uri"'; # One line per model request, after the access log's: the tool names and nothing else of the body. log_format census escape=none 'census $gw_census'; + # One line per run's first tooled request: its system text and first message, JSON-escaped. + log_format context escape=none 'context $gw_context'; limit_conn_zone "all" zone=gw:1m; client_body_buffer_size 8m; client_max_body_size 64m; @@ -42,6 +48,7 @@ http { listen 8080; access_log /dev/stdout gw; access_log /dev/stdout census if=$gw_census; + access_log /dev/stdout context if=$gw_context; location = /healthz { access_log off; default_type text/plain; diff --git a/crates/candler-core/src/isolation/gateway.rs b/crates/candler-core/src/isolation/gateway.rs index 073e812e..8068d168 100644 --- a/crates/candler-core/src/isolation/gateway.rs +++ b/crates/candler-core/src/isolation/gateway.rs @@ -14,6 +14,7 @@ use candler_harness::spec::{CensusSource, InitReport}; use candler_schemas::container::{ContainerLabels, ContainerRecord, ContainerRole}; use candler_schemas::primitives::{ContainerId, Digest, JobId, Marker, RunKey}; use candler_schemas::process::ExitStatus; +use candler_schemas::trace::EventKind; use futures::future::BoxFuture; use url::Url; @@ -262,11 +263,14 @@ pub trait Gateway: Send + Sync { since: SystemTime, ) -> BoxFuture<'a, Result, GatewayError>>; - /// The model requests the gateway relayed for the run `run`, one JSON line each: + /// What the gateway recorded of the model requests it relayed for the run `run`, one JSON + /// line each, in the order the lines were written: for each request /// `{"seq":,"tools":["",...]}`, the tool names of the request and nothing else of - /// it, in the order the requests began. A gateway that records none answers no bytes. Only - /// what the gateway wrote since `since`, the start of the run's attempt, is read; a log cut - /// short is an error, never an empty census. + /// it, and for the run's first request that carries tools, + /// `{"seq":,"context":{"system":..,"first_message":..}}`, its system text and first + /// message. A gateway that records none answers no bytes. Only what the gateway wrote since + /// `since`, the start of the run's attempt, is read; a log cut short is an error, never an + /// empty census. /// /// # Errors /// [`GatewayError`] when the gateway cannot be asked or its log is cut short. @@ -984,7 +988,8 @@ impl Gateway for DockerGateway { } /// Reads the sidecar's logs: the access log (method, path, status, model, run; never the -/// `Authorization` header or a prompt) and nginx's error log. +/// `Authorization` header or a prompt), the census and context lines of the model requests, and +/// nginx's error log. #[derive(Clone)] pub struct GatewayLogs { runner: Runner, @@ -1215,12 +1220,24 @@ fn signals_of(log: &str, run: &RunKey, tag: &str) -> Vec { signals } -/// The census of the run `run` under its tag `tag`, from the sidecar's log: one line -/// `{"seq":,"tools":[...]}` for each census line of the gateway whose `run=` and `tag=` fields -/// equal these. A census line is `census run= tag= seq= tools=`; the -/// array is the last field and must be a list of strings, so what an agent writes in a tool name -/// cannot become a field. Only the sequence number and the names are kept: whatever else a line -/// carries is dropped, and a line that is not exactly that shape is dropped whole. +/// The members of a context line: the system text and the first message of a request. +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ContextBody { + system: String, + first_message: String, +} + +/// What the sidecar's log says of the run `run` under its tag `tag`: one JSON line for each census +/// line and each context line of the gateway whose `run=` and `tag=` fields equal these. +/// +/// A census line is `census run= tag= seq= tools=`, kept as +/// `{"seq":,"tools":[...]}`; the array is the last field and must be a list of strings, so what +/// an agent writes in a tool name cannot become a field. A context line is +/// `context run= tag= seq= body=`, kept as +/// `{"seq":,"context":{"system":..,"first_message":..}}`; the object is the last field and holds +/// exactly those two strings. Whatever else a line carries is dropped, and a line that is not +/// exactly one of these shapes is dropped whole. #[must_use] pub fn census_of(log: &str, run: &RunKey, tag: &str) -> Vec { let wanted_run = format!("run={run}"); @@ -1228,13 +1245,20 @@ pub fn census_of(log: &str, run: &RunKey, tag: &str) -> Vec { let mut out = Vec::new(); for line in log.lines() { let mut parts = line.splitn(5, ' '); - let (Some("census"), Some(found_run), Some(found_tag), Some(found_seq), Some(rest)) = ( + let ( + Some(kind @ ("census" | "context")), + Some(found_run), + Some(found_tag), + Some(found_seq), + Some(rest), + ) = ( parts.next(), parts.next(), parts.next(), parts.next(), parts.next(), - ) else { + ) + else { continue; }; if found_run != wanted_run || found_tag != wanted_tag { @@ -1246,21 +1270,60 @@ pub fn census_of(log: &str, run: &RunKey, tag: &str) -> Vec { else { continue; }; - let Some(tools) = rest - .strip_prefix("tools=") - .and_then(|text| serde_json::from_str::>(text).ok()) - else { - continue; + let record = if kind == "census" { + rest.strip_prefix("tools=") + .and_then(|text| serde_json::from_str::>(text).ok()) + .map(|tools| serde_json::json!({"seq": seq, "tools": tools})) + } else { + rest.strip_prefix("body=") + .and_then(|text| serde_json::from_str::(text).ok()) + .map(|body| { + serde_json::json!({ + "seq": seq, + "context": {"system": body.system, "first_message": body.first_message}, + }) + }) }; - if let Ok(mut record) = serde_json::to_vec(&serde_json::json!({"seq": seq, "tools": tools})) - { - record.push(b'\n'); - out.extend(record); + if let Some(mut bytes) = record.and_then(|record| serde_json::to_vec(&record).ok()) { + bytes.push(b'\n'); + out.extend(bytes); } } out } +/// The starting context of a census stream: the context line of the lowest sequence number, as a +/// `context_start` event kind, with the index of its line in the stream. A run none of whose +/// requests carried tools has none. +#[must_use] +pub fn census_context(stream: &[u8]) -> Option<(u64, EventKind)> { + #[derive(serde::Deserialize)] + struct Record { + seq: u64, + context: ContextBody, + } + stream + .split(|byte| *byte == b'\n') + .enumerate() + .filter_map(|(frame, line)| { + serde_json::from_slice::(line) + .ok() + .map(|record| (frame, record)) + }) + .min_by_key(|(_, record)| record.seq) + .and_then(|(frame, record)| { + u64::try_from(frame).ok().map(|frame| { + ( + frame, + EventKind::context_start(record.context.system, record.context.first_message), + ) + }) + }) +} + +/// The stream name the gateway's record is stored under when the driver names none. +pub const GATEWAY_STREAM: &str = "gateway_log"; + /// The tool inventory of a census stream: the names of the first request, by sequence number, /// that carries any, labelled as the gateway's. A request with no tools says nothing; a run none /// of whose requests carry tools has no inventory, never an empty one. diff --git a/crates/candler-core/src/jobs/orchestrate/controls.rs b/crates/candler-core/src/jobs/orchestrate/controls.rs index a4d1d691..71928c99 100644 --- a/crates/candler-core/src/jobs/orchestrate/controls.rs +++ b/crates/candler-core/src/jobs/orchestrate/controls.rs @@ -615,20 +615,48 @@ impl DockerControlRunner { std::process::id(), nanos() )); - let mut world = World { work, fake: None }; let outcome = self - .drive(rt, identity, harness, control, cancel, &mut world) + .run_in( + rt, + identity, + harness, + &Scripted { + script: control.name(), + idle_s: Some(control.idle_s()), + }, + cancel, + work.clone(), // BORROW: the path is removed below + ) .await; - drop(std::fs::remove_dir_all(&world.work)); + drop(std::fs::remove_dir_all(&work)); outcome } + /// Runs `scripted` through the harness with its scratch store below `work`. The directory is + /// left in place, so that the caller can read what the run stored; the caller removes it. + /// + /// # Errors + /// The step that failed, in words. + pub async fn run_in( + &self, + rt: &Runtime, + identity: &Identity, + harness: &Value, + scripted: &Scripted<'_>, + cancel: watch::Receiver>, + work: PathBuf, + ) -> Result { + let mut world = World { work, fake: None }; + self.drive(rt, identity, harness, scripted, cancel, &mut world) + .await + } + async fn drive( &self, rt: &Runtime, identity: &Identity, harness: &Value, - control: Control, + scripted: &Scripted<'_>, cancel: watch::Receiver>, world: &mut World, ) -> Result { @@ -652,7 +680,7 @@ impl DockerControlRunner { let docker: Arc = Arc::new(docker_cli); // TRAIT_OBJECT: the runtime reads docker through the client // the control's own runtime, over a scratch store - let (cell, plan) = control_cell(identity, harness, control)?; + let (cell, plan) = control_cell(identity, harness, scripted)?; let mut crt = Runtime { supervisor: Arc::clone(&rt.supervisor), store: store.clone(), // BORROW: the runtime owns its handle on the store @@ -854,22 +882,34 @@ pub fn fake_spec(image: &str, token: &str) -> ControlSpec { ) } -/// The cell of a control and its plan: a session over the base image with the fake model's -/// script `control` as the model, the control's own `idle_s` and the harness `harness`. +/// What the fake model plays for a run, and how the run is driven. +#[derive(Debug, Clone, Copy)] +pub struct Scripted<'a> { + /// The fake model's script, which is the model id of the cell. + pub script: &'a str, + /// The seconds after which a session closes; none runs a single prompt. + pub idle_s: Option, +} + +/// The cell of a run of `scripted` and its plan: over the base image with the harness `harness`, +/// a session when the script has an `idle_s`, a single prompt otherwise. fn control_cell( identity: &Identity, harness: &Value, - control: Control, + scripted: &Scripted<'_>, ) -> Result<(CellRun, RunPlan), String> { - let values: Vec<(&str, Value)> = vec![ + let (script, idle_s) = (scripted.script, scripted.idle_s); + let mut values: Vec<(&str, Value)> = vec![ ("budget.per_run.wall_s", json!(WALL_S)), ("isolation.image", json!(identity.base_id)), - ("model.id", json!(control.name())), + ("model.id", json!(script)), ("permission_mode", json!("bypassPermissions")), ("prompt.template", json!("go")), - ("runner.idle_s", json!(control.idle_s())), - ("runner.mode", json!("session")), ]; + if let Some(idle_s) = idle_s { + values.push(("runner.idle_s", json!(idle_s))); + values.push(("runner.mode", json!("session"))); + } let entries: Vec = values .iter() .map(|(path, value)| json!({"path": path, "value": value})) diff --git a/crates/candler-core/src/runner/exec/gather.rs b/crates/candler-core/src/runner/exec/gather.rs index e1a24d9a..ab55f2ef 100644 --- a/crates/candler-core/src/runner/exec/gather.rs +++ b/crates/candler-core/src/runner/exec/gather.rs @@ -13,7 +13,7 @@ use candler_harness::spec::{ }; use candler_schemas::outcome::Finite; use candler_schemas::raw::{Clock, RawRef, StreamName}; -use candler_schemas::trace::{EventKind, Session, SessionEvent, SessionId, UsageScope}; +use candler_schemas::trace::{Event, EventKind, Session, SessionEvent, SessionId, UsageScope}; use regex::Regex; use serde_json::{Value, json}; @@ -27,6 +27,32 @@ use crate::store::blob::digest_of_file; use crate::tree::{Links, Names, Walk}; use candler_schemas::primitives::Digest; +/// `events` with `kind` placed before the first event of the root session, read from the frame +/// `raw` of a stored stream; the root session's own events follow it, counted on by one. A trace +/// with no session is returned as it is. +#[must_use] +pub fn with_context_start( + sessions: &[Session], + mut events: Vec, + raw: RawRef, + kind: EventKind, +) -> Vec { + let Some(root) = sessions.first() else { + return events; + }; + let id = root.id(); + for entry in &mut events { + if entry.session == *id { + entry.event.seq = entry.event.seq.saturating_add(1); + } + } + events.insert( + 0, + SessionEvent::new(id.clone(), Event::new(0, kind, raw)), // BORROW: the event owns its session id + ); + events +} + /// The tokens and cost a trace reports. #[derive(Debug, Clone, Copy, Default, PartialEq)] #[non_exhaustive] diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index 80cf4d71..bf9109bf 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -25,7 +25,7 @@ use candler_schemas::container::ContainerRole; use candler_schemas::execution::{EventPayload, Integrity, InvalidReason, RunManifest, RunTree}; use candler_schemas::primitives::{ContainerId, Digest, Marker, RunKey}; use candler_schemas::process::ExitStatus; -use candler_schemas::raw::StreamName; +use candler_schemas::raw::{RawRef, StreamName}; use candler_schemas::trace::{RawFileRef, TraceFile, TraceHeader}; use futures::future::BoxFuture; use tokio::sync::watch; @@ -35,6 +35,7 @@ use self::collect::finish_attempt; use self::ends::{EndInput, TraceFacts, classify_end}; use self::gather::{ collect_commands, collect_outputs, read_stream, resolved_record, spent, store_stream, + with_context_start, }; use self::seal::{RawStreamFile, seal_run}; use self::session::{SessionHandle, SessionRun, monotonic_clock, session_config}; @@ -50,7 +51,7 @@ use super::plan::RunPlan; use super::{RunControl, RunOutcome, RunStatus, Runtime}; use crate::isolation::container::agent_home; use crate::isolation::container::mounts::{MountMode, MountRoots, MountSpec, mounts}; -use crate::isolation::gateway::census_init; +use crate::isolation::gateway::{GATEWAY_STREAM, census_context, census_init}; use crate::isolation::layout; use crate::isolation::model::ContainerPlan; use crate::isolation::{Isolation, IsolationError, RunOutputs}; @@ -714,24 +715,34 @@ async fn drive( // EXPLICIT: with no offline sessions the live reader's failure is the run's reader_failed = reader_failed || live_failed; } - // The census of a harness with no init event, read from what the gateway relayed. + // What the gateway relayed: the census of a harness with no init event, and the starting + // context of every run. A record that cannot be read or stored whole is a collect failure and + // never an absent one; a run whose requests carry no tools records neither. let mut gateway_init = None; - // A census that cannot be read or stored whole is a collect failure and never an absent - // census; a run whose requests carry no tools records no census value. - if let (Some(name), Some(gateway)) = (rt.driver.census_stream(), &rt.gateway) { - let stored = match gateway + let mut context = None; + if let Some(gateway) = &rt.gateway { + let census_stream = rt.driver.census_stream(); + let name = census_stream + .clone() // BORROW: the driver's name is kept to tell whether it has a census + .or_else(|| GATEWAY_STREAM.parse::().ok()); + let relayed = gateway .service .run_census(&gateway.handle, &plan.key, attempt_wall) .await - { - Ok(bytes) => store_stream(&frames, &name, Framing::Lines, &bytes) + .ok(); + let stored = match (name, relayed) { + (Some(name), Some(bytes)) => store_stream(&frames, &name, Framing::Lines, &bytes) .ok() - .map(|file| (census_init(&bytes), file)), - Err(_) => None, + .map(|file| (name, bytes, file)), + _ => None, }; match stored { - Some((init, file)) => { - gateway_init = init; + Some((name, bytes, file)) => { + if census_stream.is_some() { + gateway_init = census_init(&bytes); + } + context = + census_context(&bytes).map(|(frame, kind)| (RawRef::new(name, frame), kind)); extra.push(file); } None => collect_ok = false, @@ -758,6 +769,9 @@ async fn drive( }, )?, }; + if let Some((raw, kind)) = context { + events = with_context_start(&sessions, events, raw, kind); + } let header = TraceHeader::new(reader_name, raw_refs); // Records the trace rules refuse are a reader error, and the run keeps an empty trace. // BORROW: the header is cloned because the failure arm builds the empty trace from it diff --git a/crates/candler-core/tests/it/guard_container_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e.rs index 3a0e30dd..5eaafd08 100644 --- a/crates/candler-core/tests/it/guard_container_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e.rs @@ -13,7 +13,7 @@ mod container_stop_e2e; #[path = "guard_container_e2e/control_e2e.rs"] mod control_e2e; #[path = "guard_container_e2e/controls_e2e.rs"] -mod controls_e2e_runs; +pub(crate) mod controls_e2e_runs; #[path = "guard_container_e2e/create_e2e.rs"] mod create_e2e; #[path = "guard_container_e2e/egress_e2e.rs"] diff --git a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs index c7cbb8d7..55a1ca2a 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs @@ -9,7 +9,7 @@ use std::path::PathBuf; use std::sync::Arc; -use candler_harness::driver::HarnessDriver as _; +use candler_harness::driver::HarnessDriver; use candler_core::isolation::docker::{ClientEnv, DockerCli}; use candler_core::isolation::image::{DockerImageService, ImageAssets, context_digest}; @@ -50,7 +50,10 @@ pub(super) fn image_id(reference: &str) -> Option { /// The agent base image of `context`, found or built by the core's image service, as a job's /// image step finds or builds it. -async fn base_image(context: &str) -> ImageRef { +async fn base_image( + driver: Arc, // TRAIT_OBJECT: the driver is chosen at run time + context: &str, +) -> ImageRef { let tmp = tempfile::tempdir().expect("a scratch directory"); // TRAIT_OBJECT: the supervisor takes its sink as a trait object let sink: Arc = Arc::new(NullSink); @@ -71,18 +74,158 @@ async fn base_image(context: &str) -> ImageRef { env_context: tmp.path().join("env"), store_root: tmp.path().join("store"), }, - Arc::new(ClaudeCodeDriver::new()), + driver, ); service.base().await.expect("the agent base image builds") } /// The sorted lines `docker` prints for `args`. -fn listed(args: &[&str]) -> Vec { +pub(crate) fn listed(args: &[&str]) -> Vec { let mut lines: Vec = docker(args).out.lines().map(str::to_owned).collect(); lines.sort(); lines } +/// The production controls' world for one harness: the agent base image, the fake model's image, +/// the production gateway sidecar's image, and a runtime and job over them. [`ControlWorld::finish`] +/// removes, by exact id, the images this world made and checks that no container of its job is left. +pub(crate) struct ControlWorld { + pub rig: Rig, + pub rt: Runtime, + pub job: candler_core::jobs::model::JobSpec, + pub runner: DockerControlRunner, + sidecar: TestImage, + fake_tag: String, + fake_made: bool, + base: ImageRef, + base_made: bool, +} + +impl ControlWorld { + /// Builds the world for `driver`, whose base image is built from `base_dir` below `assets/docker`. + pub(crate) async fn new( + driver: Arc, // TRAIT_OBJECT: the driver is chosen at run time + base_dir: &str, + ) -> Self { + let base_context = format!( + "{}/../../assets/docker/{base_dir}", + env!("CARGO_MANIFEST_DIR") + ); + let fake_context = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/docker/fakemodel"); + // The production gateway reads the sidecar under its own tag. + let sidecar = TestImage::tagged(SIDECAR_CONTEXT, SIDECAR_TAG); + let fake_tag = format!( + "candler-fakemodel:src-{}", + context_digest(std::path::Path::new(fake_context)) + .expect("the fake's digest") + .get(..12) + .expect("twelve digits") + ); + let fake_made = image_id(&fake_tag).is_none(); + let base_args = driver.base_image().build_args; + let base_tag = candler_core::isolation::image::base_tag( + std::path::Path::new(&base_context), + &base_args, + ) + .expect("a tag"); + let base_made = image_id(&base_tag).is_none(); + let base = base_image(Arc::clone(&driver), &base_context).await; + let version = docker(&[ + "image", + "inspect", + "--format", + "{{index .Config.Labels \"candler.cc_version\"}}", + &base.id.0, + ]) + .must("the agent base image's harness label") + .trim() + .to_owned(); + + let rig = Rig::new(0); + let sink: Arc = Arc::new(NullSink); + let supervisor = Arc::new(Supervisor::new(Arc::clone(&sink))); + let records = rig.dir.path().join("records"); + std::fs::create_dir_all(&records).expect("a directory"); + let cli = DockerCli::new(Arc::clone(&supervisor), ClientEnv::from_process(), records) + .expect("a docker client"); + let slots = rig.dir.path().join("slots"); + std::fs::create_dir_all(&slots).expect("a directory"); + let rt = Runtime { + supervisor, + store: rig.store.clone(), + sink, + slots: Slots::open(&slots, 2).expect("the slots"), + docker: Arc::new(cli), + isolation: None, + gateway: None, + job: rig.job.clone(), + driver: Arc::clone(&driver), + cells: std::collections::BTreeMap::new(), + eval_infra: EvalInfra::default(), + }; + let facts = Facts { + secrets: Vec::new(), + ..Facts::base() + }; + let mut job = spec(&["m"], &facts, 600, 1); + let harness = json!({"name": driver.id().to_string(), "version": version}); + let mut resolved = serde_json::to_value(&job.resolution).expect("a resolution"); + for value in resolved["values"].as_array_mut().expect("values") { + if value["path"] == "harness" { + value["value"] = harness.clone(); + } + } + job.resolution = serde_json::from_value(resolved).expect("a resolution"); + let runner = DockerControlRunner::new(ControlContexts { + base: base_context.into(), + base_build_args: base_args, + fakemodel: fake_context.into(), + }); + Self { + rig, + rt, + job, + runner, + sidecar, + fake_tag, + fake_made, + base, + base_made, + } + } + + /// The harness value of the job's resolution. + pub(crate) fn harness(&self) -> Value { + self.job + .resolution + .values + .iter() + .find(|value| value.path().as_str() == "harness") + .and_then(|value| value.value()) + .map(|value| value.as_value().clone()) + .expect("the resolution names a harness") + } + + /// Removes what the world made, by exact id, and checks that no container is left behind. + pub(crate) fn finish(self) { + if self.fake_made + && let Some(id) = image_id(&self.fake_tag) + { + docker(&["image", "rm", &id]).must("removing the fake model's image"); + } + drop(self.sidecar); + if self.base_made { + docker(&["image", "rm", &self.base.id.0]).must("removing the agent base image"); + } + let job_label = format!("label=candler.job={}", self.rig.job); + assert_eq!( + listed(&["ps", "-aq", "--filter", &job_label]), + Vec::::new(), + "no container of the job is left behind" + ); + } +} + /// Guards: R01 §Session runner — the real controls pass on the pinned Claude Code in the /// agent base image: C1 waits for its background job and closes, C2 stops once it has answered, /// the passing record is written below the store's `controls/` and names both controls, and the @@ -94,98 +237,22 @@ fn listed(args: &[&str]) -> Vec { #[tokio::test(flavor = "multi_thread")] #[ignore = "needs Docker; run with --run-ignored only"] async fn controls_e2e_pinned_harness_passes() { - let base_context = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/docker/base"); - let fake_context = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/docker/fakemodel"); - let containers = listed(&["ps", "-aq"]); - // The production gateway reads the sidecar under its own tag. - let sidecar = TestImage::tagged(SIDECAR_CONTEXT, SIDECAR_TAG); - let fake_tag = format!( - "candler-fakemodel:src-{}", - context_digest(std::path::Path::new(fake_context)) - .expect("the fake's digest") - .get(..12) - .expect("twelve digits") - ); - let fake_made = image_id(&fake_tag).is_none(); - - let base_tag = candler_core::isolation::image::base_tag( - std::path::Path::new(base_context), - &ClaudeCodeDriver::new().base_image().build_args, - ) - .expect("a tag"); - let base_made = image_id(&base_tag).is_none(); - let base = base_image(base_context).await; - let version = docker(&[ - "image", - "inspect", - "--format", - "{{index .Config.Labels \"candler.cc_version\"}}", - &base.id.0, - ]) - .must("the agent base image's harness label") - .trim() - .to_owned(); - - let rig = Rig::new(0); - let sink: Arc = Arc::new(NullSink); - let supervisor = Arc::new(Supervisor::new(Arc::clone(&sink))); - let records = rig.dir.path().join("records"); - std::fs::create_dir_all(&records).expect("a directory"); - let cli = DockerCli::new(Arc::clone(&supervisor), ClientEnv::from_process(), records) - .expect("a docker client"); - let slots = rig.dir.path().join("slots"); - std::fs::create_dir_all(&slots).expect("a directory"); - let rt = Runtime { - supervisor, - store: rig.store.clone(), - sink, - slots: Slots::open(&slots, 2).expect("the slots"), - docker: Arc::new(cli), - isolation: None, - gateway: None, - job: rig.job.clone(), - driver: Arc::new(ClaudeCodeDriver::new()), - cells: std::collections::BTreeMap::new(), - eval_infra: EvalInfra::default(), - }; - let facts = Facts { - secrets: Vec::new(), - ..Facts::base() - }; - let mut job = spec(&["m"], &facts, 600, 1); - let harness = json!({"name": "claude-code", "version": version}); - let mut resolved = serde_json::to_value(&job.resolution).expect("a resolution"); - for value in resolved["values"].as_array_mut().expect("values") { - if value["path"] == "harness" { - value["value"] = harness.clone(); - } - } - job.resolution = serde_json::from_value(resolved).expect("a resolution"); - - let runner = DockerControlRunner::new(ControlContexts { - base: base_context.into(), - base_build_args: ClaudeCodeDriver::new().base_image().build_args, - fakemodel: fake_context.into(), - }); + let world = ControlWorld::new(Arc::new(ClaudeCodeDriver::new()), "base").await; let ctl = JobControl { cancel: Arc::new(tokio::sync::watch::channel(None).0), }; - let result = ensure(&rt, &job, &runner, &ctl).await; - - // what the test made goes, by exact id, whatever the result was - if fake_made && let Some(id) = image_id(&fake_tag) { - docker(&["image", "rm", &id]).must("removing the fake model's image"); - } - drop(sidecar); - if base_made { - docker(&["image", "rm", &base.id.0]).must("removing the agent base image"); - } + let result = ensure(&world.rt, &world.job, &world.runner, &ctl).await; + let record_path = result + .as_ref() + .ok() + .map(|reference| world.rig.store.layout().root().join(&reference.path)); + let record = record_path.map(|path| std::fs::read(path).expect("the record")); + world.finish(); let reference = result.unwrap_or_else(|error| panic!("the controls did not pass: {error}")); - let record: Value = serde_json::from_slice( - &std::fs::read(rig.store.layout().root().join(&reference.path)).expect("the record"), - ) - .expect("a record"); + drop(reference); + let record: Value = + serde_json::from_slice(&record.expect("the record bytes")).expect("a record"); let names: Vec<&str> = record["results"] .as_array() .expect("results") @@ -193,9 +260,4 @@ async fn controls_e2e_pinned_harness_passes() { .filter_map(|result| result["control"].as_str()) .collect(); assert_eq!(names, ["c1", "c2"], "the record names both controls"); - assert_eq!( - listed(&["ps", "-aq"]), - containers, - "no container is left behind" - ); } diff --git a/crates/candler-core/tests/it/guard_container_e2e/gateway_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/gateway_e2e.rs index 47dc73ef..c9cb79d9 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/gateway_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/gateway_e2e.rs @@ -19,7 +19,7 @@ use candler_core::isolation::docker::{ClientEnv, DockerCli as DockerClient, Dock use candler_core::isolation::driver::{DestroyDriver, DockerDriver}; use candler_core::isolation::gateway::{ ChildRecorder, DockerGateway, Gateway, GatewaySignal, GatewayStart, SecretError, SecretSource, - SecretValue, UpstreamConfig, assert_clean, + SecretValue, UpstreamConfig, assert_clean, census_context, census_of, }; use candler_core::isolation::model::{GatewayHandle, LabelSel, NetworkName, SweepScope}; use candler_core::isolation::testing::{AllowlistDriver, FakeJobView}; @@ -28,6 +28,7 @@ use candler_core::supervise::{EventSink, Supervisor}; use candler_schemas::container::{ContainerRecord, ContainerRole}; use candler_schemas::execution::EventPayload; use candler_schemas::primitives::{Digest, JobId, RunKey}; +use candler_schemas::trace::EventKind; // The helpers the supervision gates share. use crate::support::gateway as gateway_support; @@ -1067,3 +1068,130 @@ exec sleep 600 "the untrusted upstream got an Authorization header" ); } + +/// The agent's side of one POST through the gateway: `post `. +const AGENT_POST: &str = r#" +post() { + L=$(wc -c < "$3") + { printf 'POST %s HTTP/1.0\r\nHost: gateway\r\nAuthorization: Bearer %s\r\nx-api-key: %s\r\nContent-Type: application/json\r\nContent-Length: %s\r\n\r\n' "$1$2" "$ANTHROPIC_API_KEY" "$ANTHROPIC_API_KEY" "$L"; cat "$3"; sleep 2; } | nc -w 5 gateway 8080 > /dev/null +} +"#; + +/// Guards: the gateway's record of a run's starting context — of the requests a run sends, in the +/// Anthropic form with a system list and a message of two blocks, and in the `OpenAI` form with a +/// `system` and a `developer` message, the gateway logs for the first request that carries tools, +/// and for no other, its system text and first message as the agent sent them, through quotes, +/// newlines, backslashes, non-ASCII text and a 60,000-character block; the core's reader gives +/// back exactly those texts, for the run and tag asked about only. +/// Oracle: the request bodies the test writes, and the one rule of the texts: the text of each +/// block, joined by a newline. +/// Bite: record the first request instead of the first request with tools (the first is the +/// tool-less one below); read `system` only from the top-level member; keep only the last block. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs Docker; run with --run-ignored only"] +async fn trace_context_gateway_records_the_first_request_with_tools_verbatim() { + use serde_json::json; + let rig = Rig::new(); + let token = canary(); + let world = up(&rig, &token).await; + let handle = &world.handle; + let (run, other) = (run_key(1), run_key(2)); + let tools = + json!([{"name": "Read", "description": "reads", "input_schema": {"type": "object"}}]); + let long = "A".repeat(60_000); + let system_blocks = [ + format!("You are \"quoted\"\nline two \\ back \u{e9} \u{2713} \u{1f642} {long}"), + String::from("second block"), + ]; + let first_blocks = [ + String::from("\nhook says \"hi\"\n"), + String::from("go"), + ]; + let bodies = [ + // the title request: first, and without tools + json!({"model": "m", "system": "title", "messages": [{"role": "user", "content": "t"}]}), + // the first request with tools + json!({ + "model": "m", + "system": [ + {"type": "text", "text": system_blocks[0], "cache_control": {"type": "ephemeral"}}, + {"type": "text", "text": system_blocks[1]}, + ], + "messages": [ + {"role": "user", "content": [ + {"type": "text", "text": first_blocks[0]}, + {"type": "text", "text": first_blocks[1]}, + ]}, + {"role": "assistant", "content": "later"}, + ], + "tools": tools, + }), + // a later request with tools, which is not the starting context + json!({"model": "m", "system": "later", "messages": [{"role": "user", "content": "l"}], "tools": tools}), + ]; + let other_body = json!({ + "model": "m", + "messages": [ + {"role": "system", "content": "Be brief \\ \"x\""}, + {"role": "developer", "content": [{"type": "text", "text": "dev"}]}, + {"role": "user", "content": "hi there"}, + {"role": "user", "content": "second"}, + ], + "tools": [{"type": "function", "function": {"name": "read", "parameters": {}}}], + }); + let steps: Vec = bodies + .iter() + .enumerate() + .map(|(index, body)| { + format!( + "echo '{}' | base64 -d > /workspace/b{index}\npost \"$P\" /v1/messages /workspace/b{index}\n", + base64_of(&body.to_string()) + ) + }) + .collect(); + let script = format!( + "{AGENT_POST}\nP=${{ANTHROPIC_BASE_URL#http://gateway:8080}}\nQ=${{OTHER_URL#http://gateway:8080}}\n{}echo '{}' | base64 -d > /workspace/o\npost \"$Q\" /v1/chat/completions /workspace/o\necho done > /workspace/done\nexec sleep 600\n", + steps.concat(), + base64_of(&other_body.to_string()) + ); + let other_url = handle.run_base_url(&other); + let agent = start_agent( + &rig, + handle, + &run, + &AgentSpec { + api_key: &handle.dummy_token, + extra_env: &[("OTHER_URL", other_url.as_str())], + extra_networks: &[], + script: &script, + }, + ); + wait_done(&agent); + let logs = world + .gw + .logs() + .read_since(handle, std::time::UNIX_EPOCH) + .await + .expect("the gateway logs"); + + let stream = census_of(&logs, &run, &handle.run_tag(&run)); + let (_, kind) = census_context(&stream).expect("the run's starting context"); + assert_eq!( + kind, + EventKind::context_start(system_blocks.join("\n"), first_blocks.join("\n")) + ); + let contexts = String::from_utf8_lossy(&stream) + .lines() + .filter(|line| line.contains("\"context\"")) + .count(); + assert_eq!(contexts, 1, "one context line for the run"); + let stream = census_of(&logs, &other, &handle.run_tag(&other)); + let (_, kind) = census_context(&stream).expect("the other run's starting context"); + assert_eq!( + kind, + EventKind::context_start( + String::from("Be brief \\ \"x\"\ndev"), + String::from("hi there") + ) + ); +} diff --git a/crates/candler-core/tests/it/guard_trace_context_start.rs b/crates/candler-core/tests/it/guard_trace_context_start.rs new file mode 100644 index 00000000..a2e5a992 --- /dev/null +++ b/crates/candler-core/tests/it/guard_trace_context_start.rs @@ -0,0 +1,246 @@ +#![cfg(test)] +//! Guards of the trace's starting context: the first event of a run's trace is the first model +//! request's system text and first message as the gateway saw them, on Claude Code and on +//! `OpenCode`, and a trace stored without the event still reads. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use candler_core::frames::FrameReader; +use candler_core::isolation::gateway::{census_context, census_of}; +use candler_core::jobs::orchestrate::controls::{ControlRunner as _, Scripted}; +use candler_harness::driver::HarnessDriver; +use candler_harness_claude_code::driver::ClaudeCodeDriver; +use candler_harness_opencode::driver::OpenCodeDriver; +use candler_schemas::primitives::RunKey; +use candler_schemas::raw::FrameData; +use candler_schemas::trace::{EventKind, TraceFile}; +use serde_json::Value; + +use crate::guard_container_e2e::controls_e2e_runs::ControlWorld; +use crate::support::wiring::{Scenario, run}; + +/// The files named `name` below `dir`. +fn files_below(dir: &Path, name: &str) -> Vec { + let mut found = Vec::new(); + for entry in std::fs::read_dir(dir) + .expect("a readable directory") + .flatten() + { + let path = entry.path(); + if path.is_dir() { + found.extend(files_below(&path, name)); + } else if path.file_name().is_some_and(|found| found == name) { + found.push(path); + } + } + found +} + +/// A stored trace and the lines of the gateway stream its first event points into. +struct Stored { + trace: TraceFile, + lines: Vec, +} + +/// The trace the production run loop stores for the fake model's script `c2` through `driver`, run +/// behind the real gateway against the scripted fake model, with the gateway's stored lines. +async fn stored_trace( + driver: Arc, // TRAIT_OBJECT: the driver is chosen at run time + base_dir: &str, + session: bool, +) -> Stored { + let world = ControlWorld::new(driver, base_dir).await; + let identity = world + .runner + .identify(&world.rt) + .await + .expect("the base image is identified"); + let work = world.rig.dir.path().join("trace-work"); + let (_cancel, watch) = tokio::sync::watch::channel(None); + let ran = world + .runner + .run_in( + &world.rt, + &identity, + &world.harness(), + &Scripted { + script: "c2", + idle_s: session.then_some(2), + }, + watch, + work.clone(), + ) + .await; + let traces = files_below(&work, "trace.jsonl"); + let bytes = traces + .first() + .map(|path| std::fs::read(path).expect("the trace")); + let trace = bytes + .as_deref() + .map(|bytes| TraceFile::read(bytes).expect("the stored trace reads")); + let lines = trace + .as_ref() + .and_then(|trace| trace.events().first()) + .map(|first| { + let stream = format!("{}.jsonl.gz", first.event.raw_ref.stream); + let file = files_below(&work, &stream); + FrameReader::open(file.first().expect("the gateway stream is stored")) + .expect("the stream opens") + .map(|frame| { + let FrameData::Text { text } = frame.expect("a frame").data else { + panic!("a frame that is not text"); + }; + serde_json::from_str(&text).expect("a JSON line") + }) + .collect::>() + }) + .unwrap_or_default(); + world.finish(); + ran.expect("the control ran"); + Stored { + trace: trace.expect("the run stored a trace"), + lines, + } +} + +/// The problems with the stored trace's first event: it is not `context_start`, not seq 0, not the +/// gateway's line of the lowest sequence number among the requests with tools, different from that +/// line, or empty or not ending in the prompt. +fn check(harness: &str, stored: &Stored) -> Vec { + let Some(first) = stored.trace.events().first() else { + return vec![format!("{harness}: the trace has no events")]; + }; + let EventKind::ContextStart { + system, + first_message, + .. + } = &first.event.kind + else { + return vec![format!( + "{harness}: the first event is not context_start: {:?}", + first.event.kind + )]; + }; + let mut problems = Vec::new(); + let frame = usize::try_from(first.event.raw_ref.frame).expect("a small frame index"); + let line = stored.lines.get(frame); + let tooled = stored + .lines + .iter() + .filter(|line| { + line["tools"] + .as_array() + .is_some_and(|tools| !tools.is_empty()) + }) + .filter_map(|line| line["seq"].as_u64()) + .min(); + if first.event.seq != 0 { + problems.push(format!( + "{harness}: the first event has seq {}", + first.event.seq + )); + } + if line.and_then(|line| line["seq"].as_u64()) != tooled || tooled.is_none() { + problems.push(format!( + "{harness}: the event is the gateway's line {line:?}, not the first request with tools ({tooled:?})" + )); + } + let context = line.map(|line| &line["context"]); + if context.and_then(|context| context["system"].as_str()) != Some(system.as_str()) + || context.and_then(|context| context["first_message"].as_str()) + != Some(first_message.as_str()) + { + problems.push(format!( + "{harness}: the event differs from the gateway's line" + )); + } + if system.is_empty() || !first_message.ends_with("go") { + problems.push(format!( + "{harness}: system {} chars, first message {first_message:.100}", + system.len() + )); + } + problems +} + +/// Guards: the live trace proof — a run of the real Claude Code and a run of the real `OpenCode`, +/// each behind the real gateway against the scripted fake model, store a trace whose first event is +/// `context_start`, equal to the line the gateway recorded for the run's first request that +/// carries tools (on `OpenCode` that is not its title request) and ending in the prompt. The two +/// harnesses run one after the other, because both use the one fake model image. +/// Oracle: the gateway's stored census lines of the same run, read from the run's raw file, and the +/// prompt `go` the cell sent. +/// Bite: record the first request instead of the first request with tools (`OpenCode`'s title +/// request has no tools), or leave the event out of the trace. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs Docker; run with --run-ignored only"] +async fn trace_context_first_event_is_the_first_request_with_tools_on_both_harnesses() { + let claude = stored_trace(Arc::new(ClaudeCodeDriver::new()), "base", true).await; + let opencode = stored_trace(Arc::new(OpenCodeDriver::new()), "base-opencode", false).await; + let mut problems = check("claude-code", &claude); + problems.extend(check("opencode", &opencode)); + assert!(problems.is_empty(), "{problems:#?}"); +} + +/// Guards: a trace stored without a `context_start` still reads — the run of the wiring (the +/// `OpenCode` driver over the fake docker client and the recorded gateway log, which holds no +/// context line) makes its trace through the production run loop, the trace file reads as it is +/// stored, holds no `context_start`, and counts its events from 0 without a gap. +/// Oracle: the recorded log, which has census lines only. +/// Bite: make `context_start` a kind a reader must find, or place the event with no log line. +#[test] +fn trace_context_a_trace_stored_without_the_event_still_reads() { + let ran = run(&Scenario::exited("completed_o1"), |_, _| {}); + let bytes = std::fs::read(ran.dir.join("trace.jsonl")).expect("the stored trace"); + let trace = TraceFile::read(&bytes).expect("a trace without the event reads"); + assert!(!trace.events().is_empty(), "the run has events"); + assert!( + trace + .events() + .iter() + .all(|entry| !matches!(entry.event.kind, EventKind::ContextStart { .. })), + "no event is context_start" + ); + assert_eq!( + trace.write(), + bytes, + "reading and writing gives the file back" + ); +} + +/// Guards: the reader of the gateway log takes the context line of the run and tag it is asked +/// about, the lowest sequence number of them, with the line's index in the stream; it drops a line +/// of another run or tag, a body with a member beside the two, a body that is not JSON and a +/// context line with no sequence number, and leaves the census lines as they were. +/// Oracle: the log written here, by the shape the gateway's script writes. +/// Bite: take the last context line instead of the lowest, or ignore the run. +#[test] +fn trace_context_reader_takes_the_lowest_line_of_the_run() { + let key = |text: &str| -> RunKey { text.parse().expect("a run key") }; + let cell = "1".repeat(64); + let (mine, theirs) = (format!("{cell}-r1-a1"), format!("{cell}-r2-a1")); + let tag = "b".repeat(32); + let body = |system: &str| format!("{{\"system\":\"{system}\",\"first_message\":\"m\"}}"); + let log = [ + format!("census run={mine} tag={tag} seq=1 tools=[]"), + format!("context run={mine} tag={tag} seq=4 body={}", body("late")), + format!("context run={theirs} tag={tag} seq=1 body={}", body("other run")), + format!("context run={mine} tag={} seq=1 body={}", "c".repeat(32), body("other tag")), + format!("context run={mine} tag={tag} seq=0 body={{\"system\":\"x\",\"first_message\":\"m\",\"tools\":[]}}"), + format!("context run={mine} tag={tag} seq=2 body=not json"), + format!("context run={mine} tag={tag} seq=x body={}", body("no seq")), + format!("census run={mine} tag={tag} seq=2 tools=[\"read\"]"), + format!("context run={mine} tag={tag} seq=2 body={}", body("first")), + ] + .join("\n"); + let stream = census_of(&log, &key(&mine), &tag); + let text = String::from_utf8(stream.clone()).expect("text"); + assert_eq!(text.lines().count(), 4, "{text}"); + let (frame, kind) = census_context(&stream).expect("a context"); + assert_eq!(frame, 3, "the line of seq 2 is the fourth of the stream"); + assert_eq!( + kind, + EventKind::context_start(String::from("first"), String::from("m")) + ); +} diff --git a/crates/candler-core/tests/it/main.rs b/crates/candler-core/tests/it/main.rs index 887d250e..650f5984 100644 --- a/crates/candler-core/tests/it/main.rs +++ b/crates/candler-core/tests/it/main.rs @@ -59,6 +59,7 @@ mod guard_stats_exact; mod guard_stats_resampling; mod guard_store; mod guard_supervise; +mod guard_trace_context_start; mod guard_transcript; mod guard_treatment_context; mod guard_treatment_source; diff --git a/crates/candler/tests/it/support/contract_pages/pages.rs b/crates/candler/tests/it/support/contract_pages/pages.rs index 859b2c12..1e3ead34 100644 --- a/crates/candler/tests/it/support/contract_pages/pages.rs +++ b/crates/candler/tests/it/support/contract_pages/pages.rs @@ -25,8 +25,8 @@ pub struct Page { pub helper: bool, } -/// The six pages, in the order of the index. -pub const PAGES: [Page; 6] = [ +/// The seven pages, in the order of the index. +pub const PAGES: [Page; 7] = [ Page { file: "plugin-manifest.md", title: "Plug-in manifest", @@ -73,6 +73,14 @@ pub const PAGES: [Page; 6] = [ roots: &["experiment"], helper: false, }, + Page { + file: "trace-file.md", + title: "Normalised trace", + writer: "Candler, from a harness's output", + surface: "The normalised trace Candler stores for each run: a header, the sessions and their events, read from the harness's raw output and from what the gateway relayed, by an evaluator or an analyst.", + roots: &["normalised-trace"], + helper: false, + }, Page { file: "evaluator-helper.md", title: "Evaluator helper", diff --git a/docs/contract/index.md b/docs/contract/index.md index aef0bcdf..f6af1cc7 100644 --- a/docs/contract/index.md +++ b/docs/contract/index.md @@ -11,6 +11,7 @@ One page per surface an author writes or a plug-in speaks. Each page holds the s | [evaluator-protocol.md](evaluator-protocol.md) | Evaluator protocol | Candler and the evaluator plug-in | none | | [outcome-record.md](outcome-record.md) | Outcome record | evaluator plug-in; Candler fills the rest | none | | [experiment-file.md](experiment-file.md) | Experiment file | experimenter | `experiment/1` | +| [trace-file.md](trace-file.md) | Normalised trace | Candler, from a harness's output | none | | [evaluator-helper.md](evaluator-helper.md) | Evaluator helper | evaluator kind author | none | | [driver-traits.md](driver-traits.md) | Driver traits | driver author | none | | [harness-capabilities.md](harness-capabilities.md) | Harness capabilities | experimenter, reading | none | diff --git a/docs/contract/trace-file.md b/docs/contract/trace-file.md new file mode 100644 index 00000000..1de783bb --- /dev/null +++ b/docs/contract/trace-file.md @@ -0,0 +1,108 @@ +# Normalised trace + +## Surface + +The normalised trace Candler stores for each run: a header, the sessions and their events, read from the harness's raw output and from what the gateway relayed, by an evaluator or an analyst. + +## Version + + +Wire tag: none. + + +Wire line: `schemas@0.13.0`. + + + +## Fields + + +### `kind = "header"` + +| Path | Type | Class | Default | +|---|---|---|---| +| `kind` | `"header"` | required | - | +| `raw` | `array of RawFileRef` | required | - | +| `raw[].digest` | `Digest` | required | - | +| `raw[].stream` | `StreamName` | required | - | +| `reader` | `NameVersion` | required | - | +| `schema` | `"normalised-trace/1"` | required | - | + +### `kind = "session"` + +| Path | Type | Class | Default | +|---|---|---|---| +| `ended_at` | `Timestamp` | optional | - | +| `ended_by` | `EndedBy` | required | - | +| `ended_by.kind` | `"completed" \| "agent_error" \| "cap" \| "gateway_error" \| "budget_stop" \| "killed" \| "interrupted" \| "unknown"` | required | - | +| `ended_by.reason` | `ReasonCode` | optional | - | +| `ended_by.cap` | `"turns" \| "cost" \| "wall"` | required (ended_by.kind = cap) | - | +| `id` | `SessionId` | required | - | +| `kind` | `"session"` | required | - | +| `model` | `string` | optional | - | +| `parent_session` | `SessionId` | optional | - | +| `raw_ref` | `RawRef` | required | - | +| `raw_ref.frame` | `integer` | required | - | +| `raw_ref.stream` | `StreamName` | required | - | +| `source` | `SessionSource` | required | - | +| `source.harness` | `Name` | required | - | +| `source.harness_version` | `string` | required | - | +| `source.reader` | `Name` | required | - | +| `source.reader_version` | `string` | required | - | +| `started_at` | `Timestamp` | optional | - | + +### `kind = "event"` + +| Path | Type | Class | Default | +|---|---|---|---| +| `event` | `Event` | required | - | +| `event.at` | `Timestamp` | optional | - | +| `event.ext` | `map` | required | - | +| `event.kind` | `EventKind` | required | - | +| `event.kind.first_message` | `string` | required (event.kind.kind = context_start) | - | +| `event.kind.kind` | `"context_start" \| "user_message" \| "assistant_message" \| "tool_call" \| "tool_result" \| "notification" \| "usage"` | required | - | +| `event.kind.system` | `string` | required (event.kind.kind = context_start) | - | +| `event.kind.text` | `string` | optional | - | +| `event.kind.argv` | `array of string` | optional | - | +| `event.kind.name` | `string` | required (event.kind.kind = tool_call) | - | +| `event.kind.origin` | `ToolOrigin` | required (event.kind.kind = tool_call) | - | +| `event.kind.origin.kind` | `"builtin" \| "mcp" \| "other"` | required | - | +| `event.kind.origin.server` | `string` | required (event.kind.origin.kind = mcp) | - | +| `event.kind.origin.tool` | `string` | optional | - | +| `event.kind.wrapped_calls` | `array of WrappedCall` | required (event.kind.kind = tool_call) | - | +| `event.kind.wrapped_calls[].name` | `string` | required | - | +| `event.kind.wrapped_calls[].origin` | `ToolOrigin` | required | - | +| `event.kind.wrapped_calls[].origin.kind` | `"builtin" \| "mcp" \| "other"` | required | - | +| `event.kind.wrapped_calls[].origin.server` | `string` | required (event.kind.wrapped_calls[].origin.kind = mcp) | - | +| `event.kind.wrapped_calls[].origin.tool` | `string` | optional | - | +| `event.kind.denied` | `Denial` | optional | - | +| `event.kind.denied.by` | `"harness" \| "hook" \| "user"` | required | - | +| `event.kind.denied.reason` | `string` | optional | - | +| `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) | - | +| `event.kind.cost_usd` | `Finite` | optional | - | +| `event.kind.input_tokens` | `integer` | required (event.kind.kind = usage) | - | +| `event.kind.output_tokens` | `integer` | required (event.kind.kind = usage) | - | +| `event.kind.scope` | `"message" \| "session_total"` | required (event.kind.kind = usage) | - | +| `event.raw_ref` | `RawRef` | required | - | +| `event.raw_ref.frame` | `integer` | required | - | +| `event.raw_ref.stream` | `StreamName` | required | - | +| `event.seq` | `integer` | required | - | +| `event.span` | `SpanId` | optional | - | +| `kind` | `"event"` | required | - | +| `session` | `SessionId` | required | - | + + + +## Refusals + + +No refusal of this surface has a code. + + +## Notes + +- `context_start` is the root session's first event when the gateway saw a request that carries tools: it holds the run's first such request, `system` and `first_message`, as the gateway received them. A trace stored without it still reads. [checked: schemas@0.13.0] +- A list of blocks is the blocks' text joined by a newline. An OpenAI request's `system` and `developer` messages are `system`, its first `user` message `first_message`. Claude Code puts instruction files and hook output in `first_message`, OpenCode in `system`. [checked: schemas@0.13.0] +- The gateway's log line for it is 15,500 bytes on Claude Code and 8,943 on OpenCode (fake model, no instruction files), one per run. [checked: schemas@0.13.0] From 05c912d2f9965643b74dff3b98bdfacfa22cf84c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 14:27:54 +0900 Subject: [PATCH 17/69] docs(schemas): say what context_start holds Co-Authored-By: Claude Sonnet 5.5 --- .../schema/normalised-trace.schema.json | 6 +++--- crates/candler-schemas/src/trace.rs | 15 ++++++++------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/candler-schemas/schema/normalised-trace.schema.json b/crates/candler-schemas/schema/normalised-trace.schema.json index 2b82cdb7..4844f8f0 100644 --- a/crates/candler-schemas/schema/normalised-trace.schema.json +++ b/crates/candler-schemas/schema/normalised-trace.schema.json @@ -235,10 +235,10 @@ "oneOf": [ { "additionalProperties": false, - "description": "What the model was given at the start of the run: the system text and the first message of the run's first model request, as the gateway received them.", + "description": "What the model was given at the start of the run: the system text and the first user message of the run's first model request that carries tools, as the gateway received them: the text blocks of each, joined by a newline, with other blocks dropped.", "properties": { "first_message": { - "description": "The first message of the request, verbatim.", + "description": "The first user message of the request.", "type": "string" }, "kind": { @@ -246,7 +246,7 @@ "type": "string" }, "system": { - "description": "The system text of the request, verbatim.", + "description": "The system text of the request.", "type": "string" } }, diff --git a/crates/candler-schemas/src/trace.rs b/crates/candler-schemas/src/trace.rs index f2b209ad..86920823 100644 --- a/crates/candler-schemas/src/trace.rs +++ b/crates/candler-schemas/src/trace.rs @@ -754,13 +754,14 @@ pub enum UsageScope { #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] pub enum EventKind { - /// What the model was given at the start of the run: the system text and the first message of - /// the run's first model request, as the gateway received them. + /// What the model was given at the start of the run: the system text and the first user + /// message of the run's first model request that carries tools, as the gateway received them: + /// the text blocks of each, joined by a newline, with other blocks dropped. #[non_exhaustive] ContextStart { - /// The system text of the request, verbatim. + /// The system text of the request. system: String, - /// The first message of the request, verbatim. + /// The first user message of the request. first_message: String, }, /// The user said something. @@ -931,11 +932,11 @@ impl EventKind { #[serde(remote = "EventKind", tag = "kind", rename_all = "snake_case")] #[schemars(deny_unknown_fields, rename = "EventKind")] enum KnownKind { - /// What the model was given at the start of the run: the system text and the first message of the run's first model request, as the gateway received them. + /// What the model was given at the start of the run: the system text and the first user message of the run's first model request that carries tools, as the gateway received them: the text blocks of each, joined by a newline, with other blocks dropped. ContextStart { - /// The system text of the request, verbatim. + /// The system text of the request. system: String, - /// The first message of the request, verbatim. + /// The first user message of the request. first_message: String, }, /// The user said something. From ea23a16e11501b0171a588cbbbd562ad86e3bba3 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 14:33:31 +0900 Subject: [PATCH 18/69] feat(api): declare instructions, hooks and the harness check Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/resolve/paths.rs | 12 +++-- .../candler-harness-claude-code/src/driver.rs | 10 ++++ crates/candler-harness-opencode/src/driver.rs | 3 ++ .../candler-harness-opencode/src/prepare.rs | 3 ++ crates/candler-harness/src/agent_config.rs | 1 + crates/candler-harness/src/driver.rs | 54 +++++++++++++++++-- crates/candler-harness/src/refusal.rs | 21 ++++++-- crates/candler-harness/src/spec.rs | 40 +++++++++++++- crates/candler/src/commands/inspect.rs | 17 ++++-- .../tests/it/guard_inspect_mcp_config.rs | 49 +++++++++++++++++ .../it/support/contract_pages/capabilities.rs | 1 + .../tests/it/support/contract_pages/mod.rs | 5 +- .../tests/it/support/contract_pages/pages.rs | 2 +- docs/contract/codes.toml | 10 ++++ docs/contract/configuration-paths.md | 6 +-- docs/contract/driver-traits.md | 5 ++ docs/contract/experiment-file.md | 2 + docs/contract/harness-capabilities.md | 4 ++ 18 files changed, 223 insertions(+), 22 deletions(-) diff --git a/crates/candler-core/src/resolve/paths.rs b/crates/candler-core/src/resolve/paths.rs index 031a51e7..611cd0ef 100644 --- a/crates/candler-core/src/resolve/paths.rs +++ b/crates/candler-core/src/resolve/paths.rs @@ -4,7 +4,9 @@ use candler_harness::driver::{DriverError, HarnessDriver}; use candler_harness::mcp; -use candler_harness::spec::{AgentSetting, Answer, Cell, EffortLevel, PermissionMode}; +use candler_harness::spec::{ + AgentSetting, Answer, Cell, EffortLevel, InstructionScope, PermissionMode, +}; use candler_schemas::execution::paths::{ BUDGET_PER_RUN_MAX_COST_USD, BUDGET_PER_RUN_TURNS, BUDGET_PER_RUN_WALL_S, ENV, ENVIRONMENTS, HARNESS, HOOKS, INPUTS, INSTRUCTIONS_GLOBAL, INSTRUCTIONS_WORKSPACE, ISOLATION_BUILD_CONTEXT, @@ -218,21 +220,21 @@ pub const CONFIGURATION_PATHS: [PathRow; 51] = [ INSTRUCTIONS_GLOBAL, Kind::Subtree, Class::Value, - Reach::CandlerOnly, + Reach::Agent(&[AgentSetting::Instructions(InstructionScope::Global)]), "The global instruction text of each harness: a table of harness id (written with `_` for `-`) to text.", ), row( INSTRUCTIONS_WORKSPACE, Kind::Leaf, Class::Value, - Reach::CandlerOnly, + Reach::Agent(&[AgentSetting::Instructions(InstructionScope::Workspace)]), "The instruction text at the root of the workspace.", ), row( HOOKS, Kind::Subtree, Class::Value, - Reach::CandlerOnly, + Reach::Agent(&[AgentSetting::Hooks]), "The hooks of each harness: a table of harness id (written with `_` for `-`) to its `settings` or `files`, or its `plugins`.", ), row( @@ -603,6 +605,8 @@ pub fn settings_set_by(cell: &Cell<'_>) -> Result | AgentSetting::ToolsDisallowed | AgentSetting::Env | AgentSetting::Inputs + | AgentSetting::Instructions(_) + | AgentSetting::Hooks | AgentSetting::WallBudget | AgentSetting::TurnBudget | AgentSetting::CostBudget => found.push(*family), diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index 868da7fe..619963b3 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -278,6 +278,9 @@ impl HarnessDriver for ClaudeCodeDriver { AgentSetting::SessionMode => Answer::Mapped { construct: "stream-json over an open stdin, one turn per message", }, + AgentSetting::Instructions(_) | AgentSetting::Hooks => Answer::Refused { + reason: "this driver installs no instruction text or hook", + }, } } @@ -298,12 +301,19 @@ impl HarnessDriver for ClaudeCodeDriver { DriverFact::Census => Answer::Mapped { construct: "Claude Code's `system/init` event lists the tools", }, + DriverFact::ConfigCheck => Answer::Refused { + reason: "this driver installs no configuration file to check", + }, DriverFact::UnsetPermissionMode => Answer::Mapped { construct: "`--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it", }, } } + fn workspace_instruction_file(&self) -> &'static str { + "CLAUDE.md" + } + fn gateway(&self) -> Option { Some(GatewayEnv::new( // BORROW: .to_owned() makes the owned names the spec keeps diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index 8fbd89bb..99c17087 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -176,6 +176,9 @@ impl HarnessDriver for OpenCodeDriver { DriverFact::Census => Answer::Candler { how: "the tools the gateway offered the model in its first request", }, + DriverFact::ConfigCheck => Answer::Refused { + reason: "this driver installs no configuration file to check", + }, DriverFact::UnsetPermissionMode => Answer::Candler { how: "the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode", }, diff --git a/crates/candler-harness-opencode/src/prepare.rs b/crates/candler-harness-opencode/src/prepare.rs index 271f9697..fda43ac2 100644 --- a/crates/candler-harness-opencode/src/prepare.rs +++ b/crates/candler-harness-opencode/src/prepare.rs @@ -191,6 +191,9 @@ pub(crate) const fn answer(setting: AgentSetting) -> Answer { AgentSetting::SessionMode => Answer::Refused { reason: "OpenCode runs no session: its trace comes from the export after the run", }, + AgentSetting::Instructions(_) | AgentSetting::Hooks => Answer::Refused { + reason: "this driver installs no instruction text or hook", + }, } } diff --git a/crates/candler-harness/src/agent_config.rs b/crates/candler-harness/src/agent_config.rs index 1e390195..7d0ad3cc 100644 --- a/crates/candler-harness/src/agent_config.rs +++ b/crates/candler-harness/src/agent_config.rs @@ -174,6 +174,7 @@ pub fn instructions( let mut shaped = Map::new(); for (member, value) in &table { match member.as_str() { + // BORROW: explicit .as_str() instead of Deref coercion "global" => { let mut by_id = Map::new(); for (key, text_value) in object(value, &global_path)? { diff --git a/crates/candler-harness/src/driver.rs b/crates/candler-harness/src/driver.rs index 6b09037a..597e8314 100644 --- a/crates/candler-harness/src/driver.rs +++ b/crates/candler-harness/src/driver.rs @@ -12,9 +12,9 @@ use candler_schemas::trace::{EndedBy, Session}; use crate::reader::TraceReader; use crate::skills::SkillTree; use crate::spec::{ - AgentSetting, Answer, BaseImage, Cell, CollectSpec, CommandSpec, CommandSpecError, DriverFact, - GatewayEnv, HarnessId, Observed, Prepared, ProcessExit, SessionSpec, SessionTracker, StatePath, - StopSpec, Workspace, + AgentSetting, Answer, BaseImage, Cell, CheckVerdict, CollectSpec, CommandSpec, + CommandSpecError, DriverFact, GatewayEnv, HarnessId, Observed, Prepared, PreparedFile, + ProcessExit, SessionSpec, SessionTracker, StatePath, StopSpec, Workspace, }; /// Why a driver could not answer. @@ -63,6 +63,30 @@ pub enum DriverError { /// A command the driver could not build. #[error(transparent)] Command(#[from] CommandSpecError), + /// The harness's own check rejects a file Candler installed for the cell. + #[error("Candler installed {installed} at {at}; {harness} rejects it: {output}")] + HarnessRejectedInput { + /// The pointer into the experiment file of the setting the file comes from. + path: String, + /// What Candler installed. + installed: String, + /// Where Candler installed it. + at: String, + /// The harness's name, as its users write it. + harness: String, + /// What the harness's check printed. + output: String, + }, + /// The workspace instruction text and a declared input mount a file at one path. + #[error("`{path}` and the input `{input}` both mount a file at `{file}`")] + InstructionsCollide { + /// The pointer into the experiment file of the instruction text. + path: String, + /// The input that mounts the same path. + input: String, + /// The path both mount. + file: String, + }, /// A record of a session that a tracker cannot read. #[error("session record cannot be read: {detail}")] Record { @@ -103,6 +127,9 @@ pub struct Plan { pub command: CommandSpec, /// How the harness runs the cell as a session, or `None` for a harness that runs none. pub session: Option, + /// The files the core mounts read-only at the workspace root, each by name: the instruction + /// text of the workspace. Empty when the cell sets none. + pub workspace_files: Vec, } impl Plan { @@ -113,6 +140,7 @@ impl Plan { prepared, command, session: None, + workspace_files: Vec::new(), } } @@ -143,6 +171,26 @@ pub trait HarnessDriver: Send + Sync { /// Returns [`DriverError::VersionOutput`] if `output` names no version. fn parse_version(&self, output: &[u8]) -> Result; + /// The command that has the harness check the configuration files `plan` installs, run in the + /// cell's image without network. The default is `None`, for a harness with no check. + fn config_check(&self, plan: &Plan) -> Option { + let _ = plan; + None + } + + /// What the output of [`HarnessDriver::config_check`] says of the files. The default reads + /// every output as clean, for a harness with no check. + fn read_config_check(&self, output: &[u8]) -> CheckVerdict { + let _ = output; + CheckVerdict::Clean + } + + /// The name of the file the harness reads at the root of the workspace as instructions. The + /// default is `AGENTS.md`, the name shared by the harnesses that have none of their own. + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } + /// How the driver meets `setting`: what the harness does for it, what Candler does in its /// place, or why nobody does. Every key has an answer; there is no default. fn answer(&self, setting: AgentSetting) -> Answer; diff --git a/crates/candler-harness/src/refusal.rs b/crates/candler-harness/src/refusal.rs index 390d8006..1e36bf19 100644 --- a/crates/candler-harness/src/refusal.rs +++ b/crates/candler-harness/src/refusal.rs @@ -23,9 +23,12 @@ fn driver_error_path(error: &DriverError) -> Option { match error { DriverError::Command(inner) => Refusal::path(inner), DriverError::MissingValue { path } => { - Some(pointer_of(["fixed", path.to_string().as_str()])) - } // BORROW: .to_string() gives owned text - DriverError::Unsupported { path, .. } => Some(path.clone()), // BORROW: the path owns its text + let text = path.to_string(); // BORROW: .to_string() gives owned text + Some(pointer_of(["fixed", text.as_str()])) // BORROW: explicit .as_str() instead of Deref coercion + } + DriverError::Unsupported { path, .. } + | DriverError::HarnessRejectedInput { path, .. } + | DriverError::InstructionsCollide { path, .. } => Some(path.clone()), // BORROW: the path owns its text DriverError::InvalidValue { path, .. } => Some(pointer_of(path.segments())), DriverError::AmbiguousServers { .. } => Some("/mcp/servers".to_owned()), // BORROW: .to_owned() makes the owned pointer DriverError::VersionOutput { .. } | DriverError::Record { .. } => None, @@ -52,6 +55,18 @@ refusal_table! { "The experiment sets a setting that the harness has no way to honour, such as a turn cap for a harness with no turn limit; the run is refused rather than the setting dropped.", "The setting in the experiment file: a field under `/budget`, or the key of `[fixed]` that holds it, such as `/fixed/model.effort`.", ), + HarnessRejectedInput { .. } => row( + "experiment.harness_rejected_input", + Side::Experiment, + "The harness's own check reports an error or a warning for a file Candler installed for the cell, such as a hook configuration the harness cannot read.", + "The setting in the experiment file that the file comes from, such as `/fixed/hooks`.", + ), + InstructionsCollide { .. } => row( + "experiment.instructions_collide", + Side::Experiment, + "The workspace instruction text and a declared input mount a file at the same path, the harness's workspace instruction file; the text is refused, never shadowed.", + "The workspace instruction text in the experiment file, `/fixed/instructions.workspace` or the factor that sets it.", + ), AmbiguousServers { .. } => row( "experiment.mcp_server_prefix_ambiguous", Side::Experiment, diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index 000a4b70..e766c292 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -641,6 +641,32 @@ impl PermissionMode { } } +/// Where an instruction text is read: from the agent's home, or from the workspace root. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[expect( + clippy::exhaustive_enums, + reason = "EXHAUSTIVE: the drivers live in other crates and answer each scope; a new scope must break each of them." +)] +pub enum InstructionScope { + /// The text the harness reads for every project, from the agent's home. + Global, + /// The text the harness reads at the root of the workspace. + Workspace, +} + +/// What the harness's own check says of the files Candler installed. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum CheckVerdict { + /// The check reports no error and no warning. + Clean, + /// The check reports an error or a warning. + Rejected { + /// What the check printed. + output: String, + }, +} + /// What an experiment sets that reaches the agent. A key whose values form a closed set carries /// the value, so a new value is a compile error in every driver. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -681,11 +707,15 @@ pub enum AgentSetting { CostBudget, /// `runner.mode`. SessionMode, + /// An instruction text, at one scope. + Instructions(InstructionScope), + /// `hooks`. + Hooks, } impl AgentSetting { /// Every key, each closed value once. - pub const ALL: [Self; 31] = [ + pub const ALL: [Self; 34] = [ Self::ModelId, Self::ModelEndpoint, Self::Effort(EffortLevel::Low), @@ -717,6 +747,9 @@ impl AgentSetting { Self::TurnBudget, Self::CostBudget, Self::SessionMode, + Self::Instructions(InstructionScope::Global), + Self::Instructions(InstructionScope::Workspace), + Self::Hooks, ]; } @@ -739,17 +772,20 @@ pub enum DriverFact { Census, /// What the harness does when the experiment sets no permission mode. UnsetPermissionMode, + /// The harness has a check of its own for the configuration files Candler installs. + ConfigCheck, } impl DriverFact { /// Every fact. - pub const ALL: [Self; 6] = [ + pub const ALL: [Self; 7] = [ Self::GracefulStop, Self::LiveEvents, Self::InHarnessGuard, Self::ExecutionOutsideChild, Self::Census, Self::UnsetPermissionMode, + Self::ConfigCheck, ]; } diff --git a/crates/candler/src/commands/inspect.rs b/crates/candler/src/commands/inspect.rs index 08ebe535..b918108d 100644 --- a/crates/candler/src/commands/inspect.rs +++ b/crates/candler/src/commands/inspect.rs @@ -211,9 +211,9 @@ fn outcome_of(record: &OutcomeRecord) -> Result { }) } -/// The resolved `mcp.*` values of the cell, by path: the MCP configuration the run was installed -/// with. -fn mcp_of(whole: &Value) -> BTreeMap { +/// The resolved values of the cell at `root` or below it, by path: the configuration of that +/// family the run was installed with. +fn values_under(whole: &Value, root: &str) -> BTreeMap { whole .pointer("/comparable/values") .and_then(Value::as_array) @@ -222,7 +222,10 @@ fn mcp_of(whole: &Value) -> BTreeMap { .filter_map(|entry| { let path = entry.get("path").and_then(Value::as_str)?; let value = entry.get("value")?; - (path == "mcp" || path.starts_with("mcp.")).then(|| (path.to_owned(), value.clone())) // BORROW: the record owns its copy + let below = path + .strip_prefix(root) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('.')); + below.then(|| (path.to_owned(), value.clone())) // BORROW: the record owns its copy }) .collect() } @@ -286,7 +289,9 @@ pub fn render_run(store: &Store, key: &RunKey) -> Result { ended_at: field("ended_at"), host: field("host"), import: field("import"), - mcp: mcp_of(&whole), + mcp: values_under(&whole, "mcp"), + instructions: values_under(&whole, "instructions"), + hooks: values_under(&whole, "hooks"), provenance, measured, outcomes, @@ -376,6 +381,8 @@ fn text_of_run(run: &InspectRun) -> String { for (path, value) in run .mcp .iter() + .chain(run.instructions.iter()) + .chain(run.hooks.iter()) .chain(run.provenance.iter()) .chain(run.measured.iter()) { diff --git a/crates/candler/tests/it/guard_inspect_mcp_config.rs b/crates/candler/tests/it/guard_inspect_mcp_config.rs index 2c9bf460..2240ecc6 100644 --- a/crates/candler/tests/it/guard_inspect_mcp_config.rs +++ b/crates/candler/tests/it/guard_inspect_mcp_config.rs @@ -111,3 +111,52 @@ fn a_cell_from_resolve_is_stored_and_hashed_without_snapshots() { "the run is keyed by the digest of the cell as stored" ); } + +/// Guards: a cell that sets an instruction text is refused by name while a driver answers it +/// `no`, at the key of `[fixed]` that holds it and not as an unknown path; and the run of a cell +/// that sets neither instructions nor hooks shows both members, empty, through `inspect`. +/// +/// Oracle: the code and the pointer are written by hand from the surface; the run is made by +/// `candler run`. +/// +/// Bite: drop the `instructions` and `hooks` members from what `inspect` shows (the record has +/// no such member); let the driver answer `Mapped` (the run launches). +#[test] +fn instructions_are_refused_by_name_and_inspect_shows_the_members() { + let world = world(); + let refused = world.launch_with(&["--set", "instructions.workspace=read the plan"]); + let stderr = String::from_utf8(refused.stderr).unwrap(); + assert!(!refused.status.success(), "the run is refused: {stderr}"); + assert!( + stderr.contains("\"code\":\"experiment.setting_unsupported\"") + && stderr.contains("\"path\":\"/fixed/instructions.workspace\""), + "refused as an unsupported setting, not an unknown path: {stderr}" + ); + + let launched = world.launch(); + finish(&world, &launched); + world.assert_sealed(1); + let runs = world.store().join("runs"); + let run_dir = fs::read_dir(&runs) + .unwrap() + .flatten() + .map(|entry| entry.path()) + .find(|path| path.join("run.done").is_file()) + .expect("a sealed run"); + let out = Command::new(env!("CARGO_BIN_EXE_candler")) + .arg("inspect") + .arg(&run_dir) + .current_dir(&world.work) + .env_clear() + .output() + .unwrap(); + assert!(out.status.success(), "inspect exits 0: {out:?}"); + let record: Value = serde_json::from_slice(&out.stdout).unwrap(); + for member in ["instructions", "hooks"] { + assert_eq!( + record[member], + serde_json::json!({}), + "the record shows the {member} the run was given: {record}" + ); + } +} diff --git a/crates/candler/tests/it/support/contract_pages/capabilities.rs b/crates/candler/tests/it/support/contract_pages/capabilities.rs index 0ebadbe7..4f419138 100644 --- a/crates/candler/tests/it/support/contract_pages/capabilities.rs +++ b/crates/candler/tests/it/support/contract_pages/capabilities.rs @@ -42,6 +42,7 @@ const fn fact_label(fact: DriverFact) -> &'static str { DriverFact::ExecutionOutsideChild => "execution outside the child", DriverFact::Census => "census source", DriverFact::UnsetPermissionMode => "permission mode when none is set", + DriverFact::ConfigCheck => "config check", } } diff --git a/crates/candler/tests/it/support/contract_pages/mod.rs b/crates/candler/tests/it/support/contract_pages/mod.rs index 3937cf12..1b354be6 100644 --- a/crates/candler/tests/it/support/contract_pages/mod.rs +++ b/crates/candler/tests/it/support/contract_pages/mod.rs @@ -17,7 +17,7 @@ pub mod versions; use std::fs; use std::path::{Path, PathBuf}; -use candler_harness::spec::{AgentSetting, Answer, EffortLevel, PermissionMode}; +use candler_harness::spec::{AgentSetting, Answer, EffortLevel, InstructionScope, PermissionMode}; use candler_schemas::servers::McpServerKind; /// The environment variable that makes the guards write the pages instead of comparing them. @@ -102,5 +102,8 @@ pub const fn setting_label(setting: AgentSetting) -> &'static str { AgentSetting::TurnBudget => "turn cap", AgentSetting::CostBudget => "cost cap", AgentSetting::SessionMode => "session mode", + AgentSetting::Instructions(InstructionScope::Global) => "instructions: global", + AgentSetting::Instructions(InstructionScope::Workspace) => "instructions: workspace", + AgentSetting::Hooks => "hooks", } } diff --git a/crates/candler/tests/it/support/contract_pages/pages.rs b/crates/candler/tests/it/support/contract_pages/pages.rs index 859b2c12..5c2a9732 100644 --- a/crates/candler/tests/it/support/contract_pages/pages.rs +++ b/crates/candler/tests/it/support/contract_pages/pages.rs @@ -69,7 +69,7 @@ pub const PAGES: [Page; 6] = [ file: "experiment-file.md", title: "Experiment file", writer: "experimenter", - surface: "The experiment file an experimenter writes to fix the values, factors, replicates, budget, harness and treatment of a set of runs; Candler reads it to plan and run the cells.", + surface: "The experiment file an experimenter writes to fix the values, factors, replicates, budget, harness and treatment of a set of runs; Candler reads it to plan and run the cells. Instruction texts and hooks are leaves of `[fixed]` or of a factor level: `instructions.global.`, `instructions.workspace`, `hooks..settings` (the text of a JSON object) and `hooks..files` or `hooks..plugins` (a list of `{path, text}`), with `_` where the harness id has `-`. A hook a consumer gives the agent may approve tool calls, which changes what `permission_mode` means for that cell.", roots: &["experiment"], helper: false, }, diff --git a/docs/contract/codes.toml b/docs/contract/codes.toml index 52f5eab0..39bb2a32 100644 --- a/docs/contract/codes.toml +++ b/docs/contract/codes.toml @@ -762,6 +762,16 @@ side = "experiment" enum = "DriverError" variant = "InvalidValue" +[harness."experiment.harness_rejected_input"] +side = "experiment" +enum = "DriverError" +variant = "HarnessRejectedInput" + +[harness."experiment.instructions_collide"] +side = "experiment" +enum = "DriverError" +variant = "InstructionsCollide" + [harness."experiment.mcp_server_prefix_ambiguous"] side = "experiment" enum = "DriverError" diff --git a/docs/contract/configuration-paths.md b/docs/contract/configuration-paths.md index 1c349269..317c0b18 100644 --- a/docs/contract/configuration-paths.md +++ b/docs/contract/configuration-paths.md @@ -25,9 +25,9 @@ Core line: `v0.16.0`. | `tools.disallowed` | the path | experiment value | The tools the harness may not use. | tools disallowed: `permissions.deny` of `.claude/settings.json` | tools disallowed: a permission row {action, *, deny} per name, written after the allow rows | | `env` | the path | experiment value | The environment of the harness process: a table of variable name to text. | env: Candler: the core sets the cell's variables on the agent's process | env: Candler: the core sets the cell's variables on the agent's process | | `mcp` | the path and every path below it | experiment value | The MCP servers of a run; the names below are free. | MCP transport: stdio: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: local: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: http: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP transport: sse: an entry of `mcpServers` in `.mcp.json`, of type `sse`; MCP transport: remote: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP codemode: off: no key: Claude Code offers the server's tools directly; MCP codemode: on: no (Claude Code offers MCP tools directly; it has no code mode); MCP server name: the key of the server's `.mcp.json` entry | MCP transport: stdio: an `mcp` entry of type `local`; MCP transport: local: an `mcp` entry of type `local`; MCP transport: http: an `mcp` entry of type `remote`; MCP transport: sse: no (OpenCode documents no SSE transport; its `remote` is Streamable HTTP); MCP transport: remote: an `mcp` entry of type `remote`; MCP codemode: off: the `codemode` key of the `mcp` entry, `false`: the server's tools are direct tools; MCP codemode: on: the `codemode` key of the `mcp` entry, `true`: the server's tools are reached through `execute`, whose calls the trace records with empty `wrapped_calls`, so MCP calls made inside `execute` are not attributed and do not compare with Claude Code; MCP server name: the key of the `mcp` entry | -| `instructions.global` | the path and every path below it | experiment value | The global instruction text of each harness: a table of harness id (written with `_` for `-`) to text. | Candler only | Candler only | -| `instructions.workspace` | the path | experiment value | The instruction text at the root of the workspace. | Candler only | Candler only | -| `hooks` | the path and every path below it | experiment value | The hooks of each harness: a table of harness id (written with `_` for `-`) to its `settings` or `files`, or its `plugins`. | Candler only | Candler only | +| `instructions.global` | the path and every path below it | experiment value | The global instruction text of each harness: a table of harness id (written with `_` for `-`) to text. | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | +| `instructions.workspace` | the path | experiment value | The instruction text at the root of the workspace. | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | +| `hooks` | the path and every path below it | experiment value | The hooks of each harness: a table of harness id (written with `_` for `-`) to its `settings` or `files`, or its `plugins`. | hooks: no (this driver installs no instruction text or hook) | hooks: no (this driver installs no instruction text or hook) | | `permission_mode` | the path | experiment value | The permission mode the harness runs in. | permission mode: default: `--permission-mode ` on the command line; permission mode: acceptEdits: `--permission-mode ` on the command line; permission mode: plan: `--permission-mode ` on the command line; permission mode: bypassPermissions: `--permission-mode ` on the command line; permission mode: auto: `--permission-mode ` on the command line; permission mode: dontAsk: `--permission-mode ` on the command line | permission mode: default: no (Claude Code's default mode allows reads and a built-in, non-configurable set of read-only shell commands that its own parser decides, and denies the rest in a headless run. OpenCode without `--auto` also rejects what no rule allows, but its shell rows are wildcards on the text of each parsed command, which approximate that set without being it); permission mode: acceptEdits: no (Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, rm, rmdir, mv, cp and sed, inside the working directory only. OpenCode's shell resource is the command's text, which knows no working directory, so "inside it" cannot be written as a rule); permission mode: plan: no (Claude Code's plan mode reads and runs read-only shell commands (a built-in, non-configurable set its own parser decides). The OpenCode ruleset that is certainly read-only (the `explore` agent's: deny everything, allow read, glob, grep, webfetch, websearch, skill) denies the shell altogether, and a wildcard on command text cannot express the read-only set; the stock `plan` agent is not read-only once a global rule follows it (the last match wins) and its `subagent` child can edit); permission mode: bypassPermissions: `--auto` on the command line: every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` answers the one pending ask (`.env` reads) with once, which a headless run needs; permission mode: auto: no (Claude Code's auto mode has a model classifier review each action, such as a shell command or a network request, before it runs. OpenCode has no classifier, and a ruleset decides by the action's text alone); permission mode: dontAsk: no (Claude Code's dontAsk mode denies every call that would prompt, so it allows the allow rules plus reads and the built-in, non-configurable set of read-only shell commands its own parser decides. OpenCode's shell rows are wildcards on the text of each parsed command, which approximate that set without being it) | | `request.harness` | the path | request key | The harness the run uses. | Candler only | Candler only | | `request.treatment` | the path | request key | The treatment the run applies. | Candler only | Candler only | diff --git a/docs/contract/driver-traits.md b/docs/contract/driver-traits.md index f3bf6f52..9beacd64 100644 --- a/docs/contract/driver-traits.md +++ b/docs/contract/driver-traits.md @@ -23,6 +23,9 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | `HarnessDriver::supported` | `(&self) -> semver::VersionReq` | required | - | | `HarnessDriver::version_probe` | `(&self) -> CommandSpec` | required | - | | `HarnessDriver::parse_version` | `(&self, output: &[u8]) -> Result` | required | - | +| `HarnessDriver::config_check` | `(&self, plan: &Plan) -> Option` | optional | `None` | +| `HarnessDriver::read_config_check` | `(&self, output: &[u8]) -> CheckVerdict` | optional | `CheckVerdict::Clean` | +| `HarnessDriver::workspace_instruction_file` | `(&self) -> &'static str` | optional | `"AGENTS.md"` | | `HarnessDriver::answer` | `(&self, setting: AgentSetting) -> Answer` | required | - | | `HarnessDriver::fact` | `(&self, fact: DriverFact) -> Answer` | required | - | | `HarnessDriver::plan` | `(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result` | required | - | @@ -62,6 +65,8 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. |---|---|---|---| | `experiment.cell_value_invalid` | A cell value cannot be used by the harness driver. | The field of the value, such as `/mcp/servers/fs/command`. | experiment | | `experiment.cell_value_missing` | A cell lacks a value that the harness driver needs, such as a hooks table that has no entry for the cell's harness. | The key of `[fixed]` that holds the value, such as `/fixed/hooks`. | experiment | +| `experiment.harness_rejected_input` | The harness's own check reports an error or a warning for a file Candler installed for the cell, such as a hook configuration the harness cannot read. | The setting in the experiment file that the file comes from, such as `/fixed/hooks`. | experiment | +| `experiment.instructions_collide` | The workspace instruction text and a declared input mount a file at the same path, the harness's workspace instruction file; the text is refused, never shadowed. | The workspace instruction text in the experiment file, `/fixed/instructions.workspace` or the factor that sets it. | experiment | | `experiment.mcp_server_prefix_ambiguous` | Two MCP servers of a cell have names that make one tool name read two ways: the name of one, then `_`, is a prefix of the other's name, so a tool of the longer-named server cannot be told from a tool of the shorter-named one. | The table of servers, `/mcp/servers`. | experiment | | `experiment.setting_unsupported` | The experiment sets a setting that the harness has no way to honour, such as a turn cap for a harness with no turn limit; the run is refused rather than the setting dropped. | The setting in the experiment file: a field under `/budget`, or the key of `[fixed]` that holds it, such as `/fixed/model.effort`. | experiment | | `harness.session_record_unreadable` | A session record that the harness wrote, such as a hook payload or a stream event, cannot be read by the driver's tracker. | - | environment | diff --git a/docs/contract/experiment-file.md b/docs/contract/experiment-file.md index be6ae56c..1cc91e14 100644 --- a/docs/contract/experiment-file.md +++ b/docs/contract/experiment-file.md @@ -76,9 +76,11 @@ Wire line: `schemas@0.13.0`. | `experiment.env_source` | A `[fixed]` key, a factor or a `--set` names the path `env`; the `[env]` table is its only source. | The path that was written. | experiment | | `experiment.env_token_secret` | An entry of the `env` table is named like `model.token_secret`, the secret that holds the gateway token, whose value reaches the gateway only. | The key of the entry in the `env` table. | experiment | | `experiment.factor_without_levels` | A factor has no level, so the experiment would have no cell. | - | experiment | +| `experiment.harness_rejected_input` | The harness's own check reports an error or a warning for a file Candler installed for the cell, such as a hook configuration the harness cannot read. | The setting in the experiment file that the file comes from, such as `/fixed/hooks`. | experiment | | `experiment.input_invalid` | An input declaration uses the kind the wire reserves, or mounts under an empty, absolute or escaping directory. | `/inputs`, the list that holds the declaration. | experiment | | `experiment.input_not_stored` | A declared input file or list could not be copied into the store. | The `inputs` array of the experiment file. | experiment | | `experiment.input_unusable` | A declared input cannot be used as written, for example a missing file or a directory where a file is needed. | The `inputs` array of the experiment file. | experiment | +| `experiment.instructions_collide` | The workspace instruction text and a declared input mount a file at the same path, the harness's workspace instruction file; the text is refused, never shadowed. | The workspace instruction text in the experiment file, `/fixed/instructions.workspace` or the factor that sets it. | experiment | | `experiment.mcp_server_prefix_ambiguous` | Two MCP servers of a cell have names that make one tool name read two ways: the name of one, then `_`, is a prefix of the other's name, so a tool of the longer-named server cannot be told from a tool of the shorter-named one. | The table of servers, `/mcp/servers`. | experiment | | `experiment.name_collision` | Two names under one root map to the same deviation path, so a deviation there would be ambiguous. | - | experiment | | `experiment.path_overlap` | Two paths set by the fixed values and the factors are the same, or one lies below the other. | - | experiment | diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index 7e2ce681..421c4613 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -48,6 +48,9 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | turn cap | `--max-turns` on the command line | no (`agents..steps` makes the last request a tool-less one with an injected prompt and ends the run as completed (the `oc_step_cap` fixture), where Claude Code ends the run with `error_max_turns`, so the cap class would be lost and the model's last turn changed) | | cost cap | `--max-budget-usd` on the command line | no (OpenCode has no cost cap) | | session mode | stream-json over an open stdin, one turn per message | no (OpenCode runs no session: its trace comes from the export after the run) | +| instructions: global | no (this driver installs no instruction text or hook) | no (this driver installs no instruction text or hook) | +| instructions: workspace | no (this driver installs no instruction text or hook) | no (this driver installs no instruction text or hook) | +| hooks | no (this driver installs no instruction text or hook) | no (this driver installs no instruction text or hook) | | gateway route | Candler: gateway, address in `ANTHROPIC_BASE_URL` | Candler: gateway, address in `CANDLER_GATEWAY_URL` | | authoritative trace | yes | Candler: collects `export` after the run | | graceful stop | SIGTERM ends the sessions cleanly | an interrupt request to the `serve` child, then SIGTERM to the client | @@ -56,6 +59,7 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | execution outside the child | no (tools run in the child process) | tools run in the `serve` child, which the stop interrupts first | | census source | Claude Code's `system/init` event lists the tools | Candler: the tools the gateway offered the model in its first request | | permission mode when none is set | `--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it | Candler: the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode | +| config check | no (this driver installs no configuration file to check) | no (this driver installs no configuration file to check) | ## Refusals From 18b7f65599a828d5334d0bedffd47393a474c6a9 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 14:37:31 +0900 Subject: [PATCH 19/69] fix(runner): tag the sidecar image by its sources, keep one stream Co-Authored-By: Claude Sonnet 5.5 --- assets/docker/gateway/gw.js | 39 ++++++++++++------- crates/candler-core/src/isolation/gateway.rs | 3 -- crates/candler-core/src/isolation/image.rs | 15 +++++++ .../src/jobs/orchestrate/controls.rs | 28 ++++++------- .../src/jobs/orchestrate/session.rs | 28 +++++++++---- crates/candler-core/src/runner/exec/mod.rs | 13 +++---- .../it/guard_container_e2e/controls_e2e.rs | 13 ++++--- .../it/guard_container_e2e/gateway_e2e.rs | 19 +++++---- crates/candler-harness-opencode/src/driver.rs | 8 ++-- crates/candler-harness-opencode/src/lib.rs | 3 -- crates/candler-harness/src/driver.rs | 4 +- crates/candler-harness/src/spec.rs | 4 ++ crates/candler/src/commands/run.rs | 15 +++---- crates/candler/src/commands/supervise.rs | 1 + docs/contract/trace-file.md | 4 +- 15 files changed, 120 insertions(+), 77 deletions(-) diff --git a/assets/docker/gateway/gw.js b/assets/docker/gateway/gw.js index 4651178a..52120a17 100644 --- a/assets/docker/gateway/gw.js +++ b/assets/docker/gateway/gw.js @@ -108,8 +108,8 @@ function census(r) { + " seq=" + r.variables.gw_n + " tools=" + JSON.stringify(names); } -// The text of a message `content` or of a `system` value: the string itself, or the `text` of -// each block of a list, joined by a newline. Anything else is "". +// The text of a message `content` or of a `system` value: the string itself, or the non-empty +// `text` of each block of a list, joined by a newline. Anything else is "". function textOf(content) { if (typeof content === "string") { return content; @@ -120,7 +120,8 @@ function textOf(content) { const parts = []; for (let i = 0; i < content.length; i++) { const block = content[i]; - if (block !== null && typeof block === "object" && typeof block.text === "string") { + if (block !== null && typeof block === "object" && typeof block.text === "string" + && block.text !== "") { parts.push(block.text); } } @@ -133,10 +134,12 @@ function textOf(content) { // that began earlier ends later. The reader keeps the lowest. // // `system` is the system text: the top-level `system` of the Anthropic form (a string, or a list -// of blocks) followed by the `system` and `developer` messages of the OpenAI form. `first_message` -// is the first `user` message, every content block of it. Block texts are joined by a newline. -// The line is `run= tag= seq= body=`, with the JSON as the last field. "" for -// a request that is not authentic, carries no tools, or is not lower than one recorded. +// of blocks) followed by the `system` and `developer` messages of the OpenAI form, the empty ones +// left out. `first_message` is the first `user` message and no other. Of a list of blocks the text +// blocks are kept, joined by a newline, and the others are dropped. The line is +// `run= tag= seq= body=`, with the JSON as the last field. "" for a request that +// is not authentic, carries no tools, is not lower than one recorded, or holds neither a system +// text nor a first message. function context(r) { if (authentic(r) !== "1") { return ""; @@ -156,13 +159,11 @@ function context(r) { } const run = r.variables.gw_run; const n = Number(r.variables.gw_n); - const lowest = ngx.shared.gwctx.get(run); - if (lowest !== undefined && lowest <= n) { - return ""; - } - ngx.shared.gwctx.set(run, n); const messages = Array.isArray(body.messages) ? body.messages : []; - const system = body.system === undefined ? [] : [textOf(body.system)]; + const system = []; + if (body.system !== undefined && textOf(body.system) !== "") { + system.push(textOf(body.system)); + } let first = ""; let found = false; for (let i = 0; i < messages.length; i++) { @@ -171,12 +172,22 @@ function context(r) { continue; } if (message.role === "system" || message.role === "developer") { - system.push(textOf(message.content)); + if (textOf(message.content) !== "") { + system.push(textOf(message.content)); + } } else if (message.role === "user" && !found) { first = textOf(message.content); found = true; } } + if (system.length === 0 && first === "") { + return ""; + } + const lowest = ngx.shared.gwctx.get(run); + if (lowest !== undefined && lowest <= n) { + return ""; + } + ngx.shared.gwctx.set(run, n); return "run=" + run + " tag=" + r.variables.gw_tag + " seq=" + r.variables.gw_n + " body=" + JSON.stringify({ system: system.join("\n"), first_message: first }); } diff --git a/crates/candler-core/src/isolation/gateway.rs b/crates/candler-core/src/isolation/gateway.rs index 8068d168..9e0da00e 100644 --- a/crates/candler-core/src/isolation/gateway.rs +++ b/crates/candler-core/src/isolation/gateway.rs @@ -1321,9 +1321,6 @@ pub fn census_context(stream: &[u8]) -> Option<(u64, EventKind)> { }) } -/// The stream name the gateway's record is stored under when the driver names none. -pub const GATEWAY_STREAM: &str = "gateway_log"; - /// The tool inventory of a census stream: the names of the first request, by sequence number, /// that carries any, labelled as the gateway's. A request with no tools says nothing; a run none /// of whose requests carry tools has no inventory, never an empty one. diff --git a/crates/candler-core/src/isolation/image.rs b/crates/candler-core/src/isolation/image.rs index 48c74ce0..345f7451 100644 --- a/crates/candler-core/src/isolation/image.rs +++ b/crates/candler-core/src/isolation/image.rs @@ -43,6 +43,9 @@ const PROBE_OUTPUT_LIMIT: usize = 4 * 1024; /// The repository of the base image. const BASE_REPO: &str = "candler-base"; +/// The repository of the gateway's sidecar images. +const SIDECAR_REPO: &str = "candler-gateway"; + /// The repository of the env images. const ENV_REPO: &str = "candler-env"; @@ -843,6 +846,18 @@ pub fn base_tag(dir: &Path, build_args: &[(String, String)]) -> Result`, the first digits of the context's digest, so the tag names the +/// image the sources make and an image built from other sources is never found under it. +/// +/// # Errors +/// [`std::io::Error`] when a file of the context cannot be read. +pub fn sidecar_tag(dir: &Path) -> Result { + let mut hex = context_digest(dir)?; + hex.truncate(SOURCE_DIGITS); + Ok(format!("{SIDECAR_REPO}:src-{hex}")) +} + /// The base tag of sources whose digest is `sources`, built with `build_args`: /// `candler-base:src-`, the first digits of the sha256 of `sources` and a NUL, then each /// argument's name, a NUL, its value and a NUL. diff --git a/crates/candler-core/src/jobs/orchestrate/controls.rs b/crates/candler-core/src/jobs/orchestrate/controls.rs index 71928c99..3b1a51b6 100644 --- a/crates/candler-core/src/jobs/orchestrate/controls.rs +++ b/crates/candler-core/src/jobs/orchestrate/controls.rs @@ -30,7 +30,7 @@ use crate::isolation::control::{ControlNetwork, ControlSpec}; use crate::isolation::driver::DockerDriver; use crate::isolation::gateway::{SecretError, SecretSource, SecretValue, UpstreamConfig}; use crate::isolation::hardening::HardLimits; -use crate::isolation::image::{base_tag, context_digest}; +use crate::isolation::image::{base_tag, context_digest, sidecar_tag}; use crate::isolation::model::{BuildRequest, Labels, NetworkName, SweepScope}; use crate::jobs::dir::JobDir; use crate::jobs::model::{JobCause, JobControl, JobSpec}; @@ -480,6 +480,8 @@ pub struct ControlContexts { pub base_build_args: Vec<(String, String)>, /// The build context of the fake model's image. pub fakemodel: PathBuf, + /// The build context of the gateway's sidecar image. + pub gateway: PathBuf, } /// Runs the controls in docker: the fake model in a container of its own, the production gateway @@ -615,20 +617,15 @@ impl DockerControlRunner { std::process::id(), nanos() )); + let scripted = Scripted { + script: control.name(), + idle_s: Some(control.idle_s()), + }; + let mut world = World { work, fake: None }; let outcome = self - .run_in( - rt, - identity, - harness, - &Scripted { - script: control.name(), - idle_s: Some(control.idle_s()), - }, - cancel, - work.clone(), // BORROW: the path is removed below - ) + .drive(rt, identity, harness, &scripted, cancel, &mut world) .await; - drop(std::fs::remove_dir_all(&work)); + drop(std::fs::remove_dir_all(&world.work)); outcome } @@ -637,6 +634,7 @@ impl DockerControlRunner { /// /// # Errors /// The step that failed, in words. + #[cfg(any(test, feature = "test-support"))] pub async fn run_in( &self, rt: &Runtime, @@ -718,7 +716,9 @@ impl DockerControlRunner { .ca_pem(ca) .build() .map_err(|e| err("the upstream", &e))?; - let gateway = sidecar_gateway(&crt, upstream, 4, control_marker()) + let tag = + sidecar_tag(&self.contexts.gateway).map_err(|e| err("the gateway's files", &e))?; + let gateway = sidecar_gateway(&crt, &tag, upstream, 4, control_marker()) .await .map_err(|e| e.to_string())?; diff --git a/crates/candler-core/src/jobs/orchestrate/session.rs b/crates/candler-core/src/jobs/orchestrate/session.rs index 1d44e9d1..6348ba16 100644 --- a/crates/candler-core/src/jobs/orchestrate/session.rs +++ b/crates/candler-core/src/jobs/orchestrate/session.rs @@ -31,7 +31,7 @@ use crate::isolation::gateway::{ DockerGateway, EgressProxy, EgressStart, Gateway, GatewayError, GatewayStart, GatewayStatus, SecretError, SecretSource, SecretValue, UpstreamConfig, }; -use crate::isolation::image::{PackageProbe, PackageReadings}; +use crate::isolation::image::{PackageProbe, PackageReadings, sidecar_tag}; use crate::isolation::model::{ContainerRef, ImageRef, NetworkName, SweepScope}; use crate::jobs::dir::JobDir; use crate::jobs::model::JobSpec; @@ -52,8 +52,6 @@ use candler_schemas::execution::paths::{ /// The roots of a cell that hold typed records; their sources are not value paths. const TYPED_ROOTS: [&str; 4] = [HARNESS, TREATMENT, INPUTS, ENVIRONMENTS]; -/// The tag the gateway's sidecar image is looked up by. -pub(super) const SIDECAR_TAG: &str = "candler-gateway:latest"; /// The marker the gateway's docker commands carry. const GATEWAY_MARKER: &str = "gateway"; /// How long a sweep of the job's containers may take. @@ -217,10 +215,11 @@ pub trait JobHost: Send + Sync { } /// The host of a real job: the `docker` on `PATH` and a [`DockerGateway`] from the sidecar image -/// docker holds under the tag `candler-gateway:latest`. +/// docker holds under the tag of the gateway's build context, when the host knows that context. #[derive(Debug, Clone)] pub struct DockerHost { controls: Result, + sidecar: Option, upstream_ca: Option>, } @@ -235,6 +234,7 @@ impl DockerHost { #[must_use] pub fn with_controls(contexts: ControlContexts) -> Self { Self { + sidecar: sidecar_tag(&contexts.gateway).ok(), controls: Ok(contexts), upstream_ca: None, } @@ -245,10 +245,18 @@ impl DockerHost { pub fn without_controls(why: &str) -> Self { Self { controls: Err(why.to_owned()), // BORROW: the host owns its reason + sidecar: None, upstream_ca: None, } } + /// The host whose gateway runs from the sidecar image docker holds under `tag`. + #[must_use] + pub fn with_sidecar(mut self, tag: String) -> Self { + self.sidecar = Some(tag); + self + } + /// The host whose gateway trusts the certificates of the PEM `ca` for the model upstream, in /// place of the system bundle; `None` keeps the system bundle. #[must_use] @@ -331,7 +339,7 @@ fn upstream_of(endpoint: &str, ca: Option<&[u8]>) -> Result) -> Result().ok()); + let name = GATEWAY_STREAM.parse::().ok(); let relayed = gateway .service .run_census(&gateway.handle, &plan.key, attempt_wall) @@ -738,7 +735,7 @@ async fn drive( }; match stored { Some((name, bytes, file)) => { - if census_stream.is_some() { + if rt.driver.census_stream().is_some() { gateway_init = census_init(&bytes); } context = diff --git a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs index 55a1ca2a..3a2e8c44 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs @@ -12,7 +12,9 @@ use std::sync::Arc; use candler_harness::driver::HarnessDriver; use candler_core::isolation::docker::{ClientEnv, DockerCli}; -use candler_core::isolation::image::{DockerImageService, ImageAssets, context_digest}; +use candler_core::isolation::image::{ + DockerImageService, ImageAssets, context_digest, sidecar_tag, +}; use candler_core::isolation::model::ImageRef; use candler_core::jobs::model::JobControl; use candler_core::jobs::orchestrate::controls::{ControlContexts, DockerControlRunner, ensure}; @@ -32,9 +34,6 @@ use crate::support::run_plan::Facts; use crate::support::test_image::{SIDECAR_CONTEXT, TestImage}; use gateway_support::docker; -/// The sidecar's tag, as the binary builds it. -const SIDECAR_TAG: &str = "candler-gateway:latest"; - /// Discards every event. struct NullSink; @@ -112,8 +111,9 @@ impl ControlWorld { env!("CARGO_MANIFEST_DIR") ); let fake_context = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/docker/fakemodel"); - // The production gateway reads the sidecar under its own tag. - let sidecar = TestImage::tagged(SIDECAR_CONTEXT, SIDECAR_TAG); + // The production gateway reads the sidecar under the tag of its build context. + let sidecar_tag = sidecar_tag(std::path::Path::new(SIDECAR_CONTEXT)).expect("a tag"); + let sidecar = TestImage::tagged(SIDECAR_CONTEXT, &sidecar_tag); let fake_tag = format!( "candler-fakemodel:src-{}", context_digest(std::path::Path::new(fake_context)) @@ -180,6 +180,7 @@ impl ControlWorld { base: base_context.into(), base_build_args: base_args, fakemodel: fake_context.into(), + gateway: SIDECAR_CONTEXT.into(), }); Self { rig, diff --git a/crates/candler-core/tests/it/guard_container_e2e/gateway_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/gateway_e2e.rs index c9cb79d9..d2e40bac 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/gateway_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/gateway_e2e.rs @@ -1080,16 +1080,17 @@ post() { /// Guards: the gateway's record of a run's starting context — of the requests a run sends, in the /// Anthropic form with a system list and a message of two blocks, and in the `OpenAI` form with a /// `system` and a `developer` message, the gateway logs for the first request that carries tools, -/// and for no other, its system text and first message as the agent sent them, through quotes, -/// newlines, backslashes, non-ASCII text and a 60,000-character block; the core's reader gives -/// back exactly those texts, for the run and tag asked about only. -/// Oracle: the request bodies the test writes, and the one rule of the texts: the text of each -/// block, joined by a newline. +/// and for no other, its system text and first user message as the agent sent them, through +/// quotes, newlines, backslashes, non-ASCII text and a 60,000-character block; a tooled request +/// with neither a system text nor a user message is not recorded and does not stand for the run; +/// the core's reader gives back exactly those texts, for the run and tag asked about only. +/// Oracle: the request bodies the test writes, and the one rule of the texts: the text blocks, +/// the empty ones and the other kinds left out, joined by a newline. /// Bite: record the first request instead of the first request with tools (the first is the /// tool-less one below); read `system` only from the top-level member; keep only the last block. #[tokio::test(flavor = "multi_thread")] #[ignore = "needs Docker; run with --run-ignored only"] -async fn trace_context_gateway_records_the_first_request_with_tools_verbatim() { +async fn trace_context_gateway_records_the_first_request_with_tools_that_holds_a_context() { use serde_json::json; let rig = Rig::new(); let token = canary(); @@ -1110,16 +1111,20 @@ async fn trace_context_gateway_records_the_first_request_with_tools_verbatim() { let bodies = [ // the title request: first, and without tools json!({"model": "m", "system": "title", "messages": [{"role": "user", "content": "t"}]}), - // the first request with tools + // a request with tools that holds no system text and no user message: nothing to record + json!({"model": "m", "messages": [{"role": "assistant", "content": "x"}], "tools": tools}), + // the first request with tools that holds a context; its empty system block is left out json!({ "model": "m", "system": [ + {"type": "text", "text": ""}, {"type": "text", "text": system_blocks[0], "cache_control": {"type": "ephemeral"}}, {"type": "text", "text": system_blocks[1]}, ], "messages": [ {"role": "user", "content": [ {"type": "text", "text": first_blocks[0]}, + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AA=="}}, {"type": "text", "text": first_blocks[1]}, ]}, {"role": "assistant", "content": "later"}, diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index 8fbd89bb..8dd53647 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -12,8 +12,8 @@ use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ Action, AgentSetting, Answer, BaseImage, Cell, CollectSpec, CommandSpec, DriverFact, - GatewayEnv, HarnessId, Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, - StopSpec, Workspace, + GATEWAY_STREAM, GatewayEnv, HarnessId, Observed, Prepared, ProcessExit, StateKind, StatePath, + StopSignal, StopSpec, Workspace, }; use candler_schemas::name; use candler_schemas::primitives::{RelPath, plain_arg}; @@ -24,7 +24,7 @@ use semver::{Version, VersionReq}; use crate::export::{OpenCodeExportReader, ended_by_of_observed, export_stream}; use crate::live::OpenCodeLiveReader; use crate::prepare::{self, model_id}; -use crate::{CENSUS_STREAM, EXPORT_READER, VALIDATED}; +use crate::{EXPORT_READER, VALIDATED}; const PROGRAM: &str = "opencode"; @@ -339,7 +339,7 @@ fn ambiguous_prefixes(names: &[String]) -> Result<(), DriverError> { /// The stream the gateway's census is stored as. fn census_stream() -> Option { - CENSUS_STREAM.parse().ok() + GATEWAY_STREAM.parse().ok() } /// The placeholder the core fills with the root session id. diff --git a/crates/candler-harness-opencode/src/lib.rs b/crates/candler-harness-opencode/src/lib.rs index 4951256e..e0513a7d 100644 --- a/crates/candler-harness-opencode/src/lib.rs +++ b/crates/candler-harness-opencode/src/lib.rs @@ -36,9 +36,6 @@ pub const LIVE_READER: &str = "opencode-ndjson@0.1.0"; /// The reader of the session export, as the trace header names it. pub const EXPORT_READER: &str = "opencode-export@0.1.0"; -/// The stream name under which the gateway's census is stored. -pub const CENSUS_STREAM: &str = "gateway_census"; - /// The name of the harness. pub const HARNESS: &str = "opencode"; diff --git a/crates/candler-harness/src/driver.rs b/crates/candler-harness/src/driver.rs index 6b09037a..b91545eb 100644 --- a/crates/candler-harness/src/driver.rs +++ b/crates/candler-harness/src/driver.rs @@ -193,8 +193,8 @@ pub trait HarnessDriver: Send + Sync { Vec::new() } - /// The raw stream the gateway's census is stored under when the harness has no init event, or - /// `None` when the census comes from the live reader's init report. The core reads the tool + /// [`crate::spec::GATEWAY_STREAM`] when the harness has no init event, or `None` when the + /// census comes from the live reader's init report. The core reads the tool /// names the gateway saw in the model requests and reports them as the inventory, labelled /// [`crate::spec::CensusSource::Gateway`]; a run none of whose requests carry tools leaves it /// unrecorded, never an empty set. diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index 000a4b70..e91ee0d6 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -874,6 +874,10 @@ impl Observed { } } +/// The raw stream the core stores the gateway's record of a run under: the tool names of each +/// model request and the run's starting context. +pub const GATEWAY_STREAM: &str = "gateway_census"; + /// Where an inventory of tools came from. Two inventories from different sources are never the /// same observation, and neither equals an unrecorded one. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/crates/candler/src/commands/run.rs b/crates/candler/src/commands/run.rs index 3251c118..41d84f34 100644 --- a/crates/candler/src/commands/run.rs +++ b/crates/candler/src/commands/run.rs @@ -22,6 +22,7 @@ use std::sync::Arc; use candler_core::experiment::inputs::{ResolvedInputs, resolve_input_groups}; use candler_core::isolation::docker::DockerCli; use candler_core::isolation::driver::DockerDriver as _; +use candler_core::isolation::image::sidecar_tag; use candler_core::isolation::model::{BuildRequest, Labels}; use candler_core::jobs::dir::JobDir; use candler_core::jobs::model::JobSpec; @@ -65,10 +66,6 @@ const ENV_ALLOWLIST: [&str; 6] = [ "DOCKER_CONTEXT", ]; -/// The tag the gateway's sidecar image is looked up by. The tag is not a pin: an image another -/// build left under it is the one the jobs use. -const SIDECAR_TAG: &str = "candler-gateway:latest"; - /// The arguments of `candler run`. #[derive(Debug, clap::Args)] pub struct Args { @@ -96,12 +93,16 @@ fn parse_field(text: &str) -> Result<(FieldPath, String), String> { } /// Builds the gateway's sidecar image from the gateway's assets, through the supervised docker -/// client. Docker's layer cache makes the build a lookup when the context is unchanged, so an -/// image another build left under the tag is never the one a job uses. +/// client, under the tag of the assets' digest, unless docker already holds that tag: an image +/// built from other sources is never the one a job uses. async fn ensure_sidecar(cli: &DockerCli, context: PathBuf) -> Result<(), CliError> { + let tag = sidecar_tag(&context).map_err(failed)?; + if cli.image_inspect(&tag).await.map_err(failed)?.is_some() { + return Ok(()); + } let request = BuildRequest { context, - tag: SIDECAR_TAG.to_owned(), // BORROW: the request owns its tag + tag, build_args: Vec::new(), labels: Labels::new(), }; diff --git a/crates/candler/src/commands/supervise.rs b/crates/candler/src/commands/supervise.rs index 5c5334b1..33923b38 100644 --- a/crates/candler/src/commands/supervise.rs +++ b/crates/candler/src/commands/supervise.rs @@ -147,6 +147,7 @@ fn control_contexts(rt: &Runtime, spec: &JobSpec) -> Result Date: Wed, 25 Nov 2026 15:29:49 +0900 Subject: [PATCH 20/69] rdm(api): amend the M6.5 gates for the proof and the surface Eliott ruled that the proof reads the starting context, system text or first message, from the first request that offers tools, and that consumers write hooks and global instructions in the harness's own shape. The leaves now word G1, G4, G8, G11 and G12 accordingly; the end-to-end half of G1 moves to the e2e guard. Co-Authored-By: Claude Opus 5.5 --- __reports__/agent_config/README.md | 8 +++++++- __roadmap__/m6_5-agent-config/README.md | 2 +- __roadmap__/m6_5-agent-config/declaration.md | 12 ++++++------ .../m6_5-agent-config/installed/install_opencode.md | 2 +- .../m6_5-agent-config/installed/proved/e2e_guard.md | 5 +++-- __roadmap__/m6_5-agent-config/trace_context.md | 6 +++--- 6 files changed, 21 insertions(+), 14 deletions(-) diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 3031aac6..9dcd157e 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -20,4 +20,10 @@ Instruction files and hooks as per-arm experiment data (M6.5). ## Status -The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended on 2026-11-25 for two instruction scopes (v1), then for a live, trace-read proof (v2). No leaf has been dispatched, and no decision is open. +The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended on 2026-11-25 for two instruction scopes (v1), then for a live, trace-read proof (v2). Level 1 is dispatched, and the probe is done. + +On 2026-11-25 Eliott ruled on the two points that round 03 raised. The roadmap's leaves carry the amended gates: +- The proof reads the whole starting context. `context_start` comes from the run's first request that offers tools. G4 and G11 pass when each text is found in its `system` or its `first_message`, since Claude Code puts CLAUDE.md texts and SessionStart output in the first message. +- Consumers write `hooks` and `instructions.global` in the harness's own shape and keys (`claude-code`, `SessionStart`, `start.sh`). The experiment surface takes them as opaque subtrees. + +No decision is open. diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index d4c01d2b..3ea53153 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -12,7 +12,7 @@ A consumer gives the experiment a global instruction file per harness, each arm - [x] `[nl]` Eliott ruled on the HTN lane's notice on 2026-11-25: instructions come in two scopes (a global file per harness, and a workspace-root file per arm on both harnesses), and evaluator access to them is deferred ## Success Gates -- ⬜ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` +- ⬜ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), as the leaves word them after the 2026-11-25 amendment (G1, G4, G8, G11, G12), hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` - ⬜ `probe_harness_checks.md`, `declaration.md`, `trace_context.md` and `installed/` are `done` - ⬜ The spend measured from transcripts, coordinator included, is at most $85 - ⬜ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated diff --git a/__roadmap__/m6_5-agent-config/declaration.md b/__roadmap__/m6_5-agent-config/declaration.md index 70851737..f81b50ce 100644 --- a/__roadmap__/m6_5-agent-config/declaration.md +++ b/__roadmap__/m6_5-agent-config/declaration.md @@ -5,10 +5,10 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G1. `candler resolve` of an experiment with `[fixed] instructions.workspace = "…"` succeeds, and the `inspect` of a run of it shows an `instructions` member. On `8d82f63b` the resolve exits 2 with `experiment.unknown_path` at `/fixed/instructions.workspace`. +- ⬜ G1 (this level's half). `candler resolve` of an experiment with `[fixed] instructions.workspace = "…"` is refused by name, with `experiment.setting_unsupported` at `/fixed/instructions.workspace`, since both drivers answer `Refused`. The `inspect` of a run shows `instructions` and `hooks` members. On `8d82f63b` the resolve exits 2 with `experiment.unknown_path` at that path. The end-to-end half, a resolve that succeeds and an `inspect` that shows the values, is gated in `installed/proved/e2e_guard.md`. - ⬜ G2. Two levels of `instructions.workspace` plan two cells with different digests, and two levels of `hooks.claude-code.settings` do the same. On the base, both are `unknown_path`. -- ⬜ G8. `hooks.claude-code` on an OpenCode cell that has no `hooks.opencode` is refused with `experiment.cell_value_missing` at `/fixed/hooks`, and `instructions.global` with no key for the cell's harness at `/fixed/instructions.global`. A key under `hooks` or `instructions.global` that names no registered harness is refused with `experiment.cell_value_invalid` at its path. A hook file path with `..` is refused with `format.rel_path_invalid`. On the base, all three are `unknown_path`. -- ⬜ G3 (this level's half). `docs/contract/harness-capabilities.md` has the rows *instructions: global*, *instructions: workspace*, *hooks* and *config check*. Both drivers answer each with `no (…)` saying it is installed from L2, and `cargo nextest run -p candler contract_pages` passes. On the base, no such rows exist. +- ⬜ G8. `hooks.claude-code` on an OpenCode cell that has no `hooks.opencode` is refused with `experiment.cell_value_missing` at `/fixed/hooks`, and `instructions.global` with no key for the cell's harness at `/fixed/instructions.global`. A key under `hooks` or `instructions.global` that names no registered harness is refused with `experiment.cell_value_invalid` at its path. A hook file path with `..` is refused with `experiment.cell_value_invalid` at its path, naming the path's own fault. On the base, all three are `unknown_path`. +- ⬜ G3 (this level's half). `docs/contract/harness-capabilities.md` has the rows *instructions: global*, *instructions: workspace*, *hooks* and *config check*. Both drivers answer each with `no (…)` saying why, and `cargo nextest run -p candler contract_pages` passes. On the base, no such rows exist. - ⬜ `experiment.harness_rejected_input` and `experiment.instructions_collide` are declared in `docs/contract/codes.toml` with their side (experiment) and their path. No code path raises them yet. - ⬜ `Plan` has a field for read-only workspace files, and the trait names each driver's workspace instruction file (`CLAUDE.md`, `AGENTS.md`). Both drivers leave the field empty, so no run changes. **References**: [Architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-schemas/src/servers.rs` (`McpServer`, the precedent); `crates/candler-harness/src/spec.rs:651` (`AgentSetting`) and `:729` (`DriverFact`); `crates/candler-core/src/resolve/paths.rs` (`CONFIGURATION_PATHS`, `settings_set_by`); `crates/candler/src/commands/inspect.rs` (`mcp_of`); `crates/candler/tests/it/guard_inspect_mcp_config.rs` @@ -16,8 +16,8 @@ ## Step 1: Surface, schema and one reader **Goal**: The three values exist as typed cell values, read by one reader. **Implementation Logic**: -Add envelope types beside `McpServer` in `candler-schemas`: `Instructions {global: map, workspace: text}`, `ClaudeCodeHooks {settings: object, files: map}` and `OpenCodeHooks {plugins: map}`, each with `deny_unknown_fields`. Their contents stay free. Publish them as their own schemas, as `mcp-server.schema.json` is. Add the `instructions` and `hooks` rows to `CONFIGURATION_PATHS`; the names below `hooks` and `instructions.global` are harness ids. Add `candler_harness::agent_config::{instructions(cell), hooks(cell, harness)}`, the twin of `candler_harness::mcp::servers`, with the refusals of G8. No second reader may exist. -**Deliverables**: `crates/candler-schemas/src/agent_config.rs` (`Instructions`, `ClaudeCodeHooks`, `OpenCodeHooks`); the published schemas; `crates/candler-core/src/resolve/paths.rs` (rows); `crates/candler-harness/src/agent_config.rs` (`instructions`, `hooks`); unit guards for G2 and G8; `crates/candler-schemas/tests/vectors/manifest/hashed_paths.toml` (the new hashed paths) +Add envelope types beside `McpServer` in `candler-schemas`: `Instructions {global: map, workspace: text}`, `ClaudeCodeHooks {settings: object, files: map}` and `OpenCodeHooks {plugins: map}`, each with `deny_unknown_fields`. Their contents stay free. Publish them as their own schemas, as `mcp-server.schema.json` is. Add the `instructions` and `hooks` rows to `CONFIGURATION_PATHS`; the names below `hooks` and `instructions.global` are harness ids, spelled as registered (`claude-code`). On the experiment surface, `hooks` and `instructions.global` are opaque subtrees: the flattener stops at them, so a consumer writes them in the harness's own shape and keys (`SessionStart`, `start.sh`), in `[fixed]` and as factor levels, and every other path keeps the key rule (Eliott, 2026-11-25). `settings` is a table, `files` and `plugins` are tables of path to text, as the envelopes say. Add `candler_harness::agent_config::{instructions(cell), hooks(cell, harness)}`, the twin of `candler_harness::mcp::servers`, with the refusals of G8. No second reader may exist. +**Deliverables**: `crates/candler-schemas/src/agent_config.rs` (`Instructions`, `ClaudeCodeHooks`, `OpenCodeHooks`); the published schemas; `crates/candler-core/src/resolve/paths.rs` (rows); `crates/candler-harness/src/agent_config.rs` (`instructions`, `hooks`); unit guards for G2 and G8 **Consistency Checks**: `cargo nextest run -p candler-schemas -p candler-harness -p candler-core` (expected: PASS) **Commit**: `feat(api): take instructions and hooks as cell values` @@ -27,4 +27,4 @@ Add envelope types beside `McpServer` in `candler-schemas`: `Instructions {globa Add `AgentSetting::Instructions(scope)` with the scopes global and workspace, `AgentSetting::Hooks` and `DriverFact::ConfigCheck`. Add the trait methods `config_check(&Plan) -> Option` and `read_config_check(output) -> CheckVerdict`, modelled on `version_probe` and `parse_version`, and the method that names the workspace instruction file. Add the `Plan` field for read-only workspace files, which L2's core leaf mounts. Both drivers answer `Refused` for now and leave the field empty, so the merged level tells the truth. Declare `experiment.harness_rejected_input` and `experiment.instructions_collide`. Regenerate the contract pages (`CANDLER_BLESS_CONTRACT=1 cargo nextest run -p candler contract_pages`) and the schemas (`CANDLER_BLESS_SCHEMAS=1 cargo nextest run -p candler-schemas drift`), and add a note on `experiment-file.md` that a consumer hook may approve tool calls, which changes what `permission_mode` means. Teach `inspect` to show `instructions` and `hooks` from `/comparable/values`, as `mcp_of` does, and extend `guard_inspect_mcp_config` or add a sibling guard for G1. **Deliverables**: `crates/candler-harness/src/spec.rs`, `driver.rs`; both drivers' `answer`/`fact`; `docs/contract/codes.toml`; the regenerated contract pages; `crates/candler/src/commands/inspect.rs`; the G1 guard **Consistency Checks**: `cargo nextest run --workspace` and `cargo nextest run -p candler contract_pages` (expected: PASS) -**Commit**: `feat(harness): declare instructions, hooks and the harness check` +**Commit**: `feat(api): declare instructions, hooks and the harness check` diff --git a/__roadmap__/m6_5-agent-config/installed/install_opencode.md b/__roadmap__/m6_5-agent-config/installed/install_opencode.md index d908ec3d..3bfa37b5 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_opencode.md +++ b/__roadmap__/m6_5-agent-config/installed/install_opencode.md @@ -8,7 +8,7 @@ **Success Gates**: - ⬜ G3 (OpenCode). The *instructions*, *hooks* and *config check* rows show the OpenCode mapping: `$XDG_CONFIG_HOME/opencode/AGENTS.md`, and the workspace's root `AGENTS.md`, read-only; local plugins in `$XDG_CONFIG_HOME/opencode/plugins/`; and the probe's check or `no (…)`. On the base, no such rows exist. - ⬜ The plan of a cell with `instructions.global.opencode`, `instructions.workspace` and `hooks.opencode` places the global `AGENTS.md` and each plugin in the home, byte for byte, lists `AGENTS.md` with the workspace text among its read-only workspace files, and writes nothing in the workspace itself. On the base, the plan has none of these. -- ⬜ The census lists each `Instructions from: ` block of the first request the gateway saw, read from a recorded request fixture. +- ⬜ The census lists each `Instructions from: ` block of the run's first request that offers tools, read from a recorded request fixture. **References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-opencode/src/prepare.rs` (`render_config`, `PreparedFile::in_home`); the OpenCode V2 evidence in the report ## Step 1: Install, census and check diff --git a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md index 583d7a79..5fe75c0e 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md @@ -5,12 +5,13 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G4. From the trace: on each harness, the `context_start.system` of arm A's run holds the global text and workspace text A, and never workspace text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. +- ⬜ G4. From the trace: on each harness, the `context_start` of arm A's run holds the global text and workspace text A, verbatim, in its `system` or its `first_message`, and neither holds workspace text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. - ⬜ G5. The scripted tool call is answered with an error carrying the hook's marker: a Claude Code PreToolUse script exits 2, and an OpenCode plugin throws in `execute.before`. On the base, there is no hook and the call succeeds. - ⬜ G6. On real images, an invalid payload (a Claude Code hooks entry on an unknown event; an OpenCode plugin with no default export) is refused at `resolve` with `experiment.harness_rejected_input`, quoting the harness, and the valid payload passes. On the base, it is `unknown_path`. - ⬜ G7. Each run's census lists both installed instruction files with their scope: on Claude Code the global file where the probe settled and the root `CLAUDE.md` (Project); on OpenCode the global `AGENTS.md` and the root `AGENTS.md`. - ⬜ G9. No installed file, the root instruction file included, is among any run's collected outputs, and no run is sealed `input_leak`. -- ⬜ G11. From the trace: on each harness, the session-start hook's marker is in `context_start`, where the probe's question (g) says it lands. On the base, there is no such event. +- ⬜ G1 (end to end). `candler resolve` of the guard's experiment succeeds, and the `inspect` of one of its runs shows `instructions` and `hooks` with the arm's values. +- ⬜ G11. From the trace: on each harness, the session-start hook's marker is in `context_start`: in `first_message` on Claude Code, in `system` on OpenCode, as the probe measured. On the base, there is no such event. - ⬜ G13. Live on RiVault (Reasoning-Small): one experiment on both harnesses, two arms, one replicate each, shows G4 and G11 in its stored traces, and `__reports__/agent_config/04-findings_live_confirmation_v0.md` quotes the trace excerpts. - ⬜ The guards run in a pass that lists them as passed, not skipped (leaf template, convention 3). `docker ps -a` shows none of their containers afterwards. **References**: [Architecture report, v2](../../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs` (`parity_one_installed_server_one_traced_call`, the model to follow); `assets/docker/fakemodel` diff --git a/__roadmap__/m6_5-agent-config/trace_context.md b/__roadmap__/m6_5-agent-config/trace_context.md index 9214feec..5723d3ae 100644 --- a/__roadmap__/m6_5-agent-config/trace_context.md +++ b/__roadmap__/m6_5-agent-config/trace_context.md @@ -1,11 +1,11 @@ # Trace context -**Goal**: Every session's normalised trace begins with a `context_start` event that holds the system text and the first message of the run's first model request, verbatim, as the gateway saw them, on both harnesses. It is what lets L3 prove from the trace that the instructions and the session-start hook reached the model. (P0, L3 reads it) +**Goal**: Every session's normalised trace begins with a `context_start` event that holds the system text and the first message of the run's first model request that offers tools, verbatim, as the gateway saw them, on both harnesses. It is what lets L3 prove from the trace that the instructions and the session-start hook reached the model. (P0, L3 reads it) **Estimate**: Sonnet, $8, cap $16. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. An adversarial review follows the spec-verifier pass. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G12. In a run on Claude Code and in a run on OpenCode against the fake model, the session's first trace event is `context_start`, and its `system` equals the system text of the first request the gateway logged. On the base, there is no such event. +- ⬜ G12. In a run on Claude Code and in a run on OpenCode against the fake model, the session's first trace event is `context_start`, and its `system` equals the system text of the run's first request that offers tools, as the gateway logged it. On the base, there is no such event. - ⬜ A trace written before the change still reads, and the schema's version bump is minor. - ⬜ One reader of the gateway log serves both the census and `context_start`; no second reader exists. The trace contract page documents the event, and states the measured size of the gateway's log line on both harnesses. - ⬜ The guards run in a pass that lists them as passed, not skipped. `docker ps -a` shows none of their containers afterwards. @@ -14,7 +14,7 @@ ## Step 1: Record the first request and emit the event **Goal**: The gateway's first-request text becomes the trace's first event. **Implementation Logic**: -The gateway already logs each request's sequence number and tool names per run and tag. It also logs, for sequence 0 only, the request's system text and first message. The core's existing gateway-log reader, the one the census uses, reads them, and the trace normaliser places `context_start {system, first_message}` before the session's first event. The kind is additive to `KnownKind`, so the schema bump is minor and old traces read unchanged. Regenerate only this leaf's own schemas and pages. The codebase is shared: extend the reader, do not copy it, and leave no scaffolding. This leaf touches no file that `declaration` touches. +The gateway already logs each request's sequence number and tool names per run and tag. It also logs, for the run's first request that offers tools and carries a context, the request's system text and first message (OpenCode's sequence 0 is a title request with no tools). The core's existing gateway-log reader, the one the census uses, reads them, and the trace normaliser places `context_start {system, first_message}` before the session's first event. The kind is additive to `KnownKind`, so the schema bump is minor and old traces read unchanged. Regenerate only this leaf's own schemas and pages. The codebase is shared: extend the reader, do not copy it, and leave no scaffolding. This leaf touches no file that `declaration` touches. **Deliverables**: `crates/candler-schemas/src/trace.rs` (`KnownKind::ContextStart`, its payload type); `crates/candler-core/src/isolation/gateway.rs` and its njs script (the first-request record); the gateway-log reader (the `context_start` event); the trace contract page; a guard `guard_trace_context_start` beside `guard_census_gateway.rs` **Consistency Checks**: `cargo nextest run -p candler-core --run-ignored all -E 'test(trace_context) | test(census_gateway)'` (expected: PASS) **Commit**: `feat(core): record each run's starting context in the trace` From 2c243634310c692efbdb953af502669565735b27 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 15:33:32 +0900 Subject: [PATCH 21/69] feat(schemas): keep the keys of the hooks and global instruction tables Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-schemas/src/agent_config.rs | 13 +++-- crates/candler-schemas/src/execution.rs | 45 ++++++++++++++--- .../tests/it/guard_experiment_file.rs | 49 +++++++++++++++++++ 3 files changed, 93 insertions(+), 14 deletions(-) diff --git a/crates/candler-schemas/src/agent_config.rs b/crates/candler-schemas/src/agent_config.rs index 5729d8bd..e7ce62c7 100644 --- a/crates/candler-schemas/src/agent_config.rs +++ b/crates/candler-schemas/src/agent_config.rs @@ -1,13 +1,12 @@ //! The instruction texts and hooks an experiment declares for the agent, in the shape the drivers //! read them. //! -//! An experiment states them as leaves of the cell, because a `[fixed]` table or a factor level -//! is flattened to leaves whose keys are field-path segments, and a hook configuration, a file -//! path or a harness id such as `claude-code` is not one: `instructions.global.` is a -//! text, `hooks..settings` is the text of a JSON object, and the files of a harness are a -//! list of `{path, text}` entries. A harness id is written with `_` where it has `-`. The reader -//! (`candler_harness::agent_config`) puts the leaves together as the types of this module, each -//! published as its own schema as `mcp-server` is, and refuses what does not fit them. +//! An experiment writes them as tables at `instructions.global` and `hooks`, in `[fixed]` or as +//! factor levels, and the keys below those two paths are the harness's own words: a harness id +//! such as `claude-code`, a hook event such as `SessionStart`, a file name such as `start.sh` +//! (see [`crate::execution::FREE_KEY_PATHS`]). The reader (`candler_harness::agent_config`) +//! reads the tables as the types of this module, each published as its own schema as +//! `mcp-server` is, and refuses what does not fit them. use std::collections::BTreeMap; diff --git a/crates/candler-schemas/src/execution.rs b/crates/candler-schemas/src/execution.rs index 9b4f11bf..23362b4d 100644 --- a/crates/candler-schemas/src/execution.rs +++ b/crates/candler-schemas/src/execution.rs @@ -658,7 +658,21 @@ impl From for TreatmentSpec { } /// The paths whose values are tables kept whole: everything written at or below one reaches a cell as one object at that path, where any other table flattens into one value per leaf. -pub const TABLE_VALUED_PATHS: [&str; 1] = [paths::PROMPT_VALUES]; +pub const TABLE_VALUED_PATHS: [&str; 3] = [ + paths::PROMPT_VALUES, + paths::HOOKS, + paths::INSTRUCTIONS_GLOBAL, +]; + +/// The table-valued paths whose keys are free: a key below one is the harness's own word (a harness id, a hook event, a file name), so the key rule of a field path does not apply to it, and a table there reaches a cell whole. +pub const FREE_KEY_PATHS: [&str; 2] = [paths::HOOKS, paths::INSTRUCTIONS_GLOBAL]; + +/// Whether `path` is, or lies below, a path whose keys are free. +fn free_keys(path: &FieldPath) -> bool { + FREE_KEY_PATHS + .into_iter() + .any(|root| path.relative_to(root).is_some()) +} /// The table-valued path that `path` is or lies below, if any. fn table_root(path: &FieldPath) -> Option<&'static str> { @@ -674,7 +688,7 @@ fn leaves_of( out: &mut Vec, ) -> Result<(), ExecutionError> { match value { - Value::Object(table) if table_root(path).is_some() => { + Value::Object(table) if table_root(path).is_some() && !free_keys(path) => { if table.is_empty() { return Err(ExecutionError::EmptyTable { path: path.to_string(), @@ -835,13 +849,17 @@ impl Level { /// A level that is a table whose leaves fill paths. /// + /// The keys are read against the factor's path when the factor's cells are built: below a path + /// of [`FREE_KEY_PATHS`] they are free, anywhere else each must be a field path segment. + /// /// # Errors - /// Returns [`ExecutionError::EmptyTable`] if the table, or a table inside it, holds no value; - /// [`ExecutionError::Format`] if a key is not a field path segment; and - /// [`ExecutionError::Values`] if a leaf is `null` or cannot be hashed. + /// Returns [`ExecutionError::EmptyTable`] if the table holds no value. pub fn fill(table: Map) -> Result { - let probe = FieldPath::from_str("level")?; - fill_leaves(&table, &probe, &mut Vec::new())?; + if table.is_empty() { + return Err(ExecutionError::EmptyTable { + path: String::from("level"), + }); + } Ok(Self::Fill(table)) } @@ -877,6 +895,13 @@ fn fill_leaves( path: base.to_string(), }); } + if free_keys(base) { + // BORROW: .clone() gives the cell its own copy of the table + let whole = JsonValue::new(Value::Object(table.clone()))?; + // BORROW: .clone() gives the cell its own path + out.push(ResolvedValue::recorded(base.clone(), whole)); + return Ok(()); + } for (key, value) in table { // BORROW: explicit .as_str() instead of Deref coercion let path = base.join(key.as_str())?; @@ -1644,6 +1669,12 @@ fn flatten_into( if inner.is_empty() { return Err(ExecutionError::EmptyTable { path }); } + if FREE_KEY_PATHS.contains(&path.as_str()) { + // BORROW: explicit .as_str() instead of Deref coercion + let json = toml_to_json(toml::Value::Table(inner), path.as_str())?; + out.push((path, json)); + continue; + } // BORROW: explicit .as_str() instead of Deref coercion flatten_into(inner, format!("{path}.").as_str(), out)?; } diff --git a/crates/candler-schemas/tests/it/guard_experiment_file.rs b/crates/candler-schemas/tests/it/guard_experiment_file.rs index 9636ae68..8ccd5504 100644 --- a/crates/candler-schemas/tests/it/guard_experiment_file.rs +++ b/crates/candler-schemas/tests/it/guard_experiment_file.rs @@ -314,3 +314,52 @@ fn table_value_empty_and_overlapping_tables_are_refused() { Some(&json!({"a": 1, "b": 1})) ); } + +/// The experiment text with `fixed` (already TOML) and `factors` (already TOML). +fn with_tables(fixed: &str, factors: &str) -> String { + format!( + "schema = \"experiment/1\"\nreplicates = 1\n\n[fixed]\n{fixed}\n{factors}\n[budget.per_run]\nwall_s = 60\n\n[harness]\nname = \"claude-code\"\n\n[treatment]\nname = \"t\"\n" + ) +} + +/// Guards: the tables at `hooks` and `instructions.global` keep the keys the harness gives them +/// (a harness id with `-`, a hook event, a file name) in `[fixed]` and in a factor level, and +/// reach the cell as one table at that path; a table anywhere else keeps the key rule. +/// Oracle: the tables are written by hand; the expected cell values are the same tables. +/// Bite: apply the key rule below `hooks` (the document is refused). +#[test] +fn free_key_tables_reach_the_cell_whole() { + let fixed = "[fixed.instructions.global]\nclaude-code = \"Global\"\n[fixed.hooks.claude-code.settings]\nSessionStart = [1]\n[fixed.hooks.claude-code.files]\n\"start.sh\" = \"echo\"\n"; + let text = with_tables("", "").replace("[fixed]\n", fixed); + let file = ExperimentFile::from_toml_str(&text).expect("free keys parse"); + let cells = file.cells(); + let cell = cells.first().expect("one cell"); + let value = |path: &str| { + cell.iter() + .find(|held| held.path().as_str() == path) + .and_then(|held| held.value().map(|json| json.as_value().clone())) + }; + assert_eq!( + value("hooks"), + Some( + serde_json::json!({"claude-code": {"settings": {"SessionStart": [1]}, "files": {"start.sh": "echo"}}}) + ) + ); + assert_eq!( + value("instructions.global"), + Some(serde_json::json!({"claude-code": "Global"})) + ); + + let levels = with_tables( + "", + "[[factors]]\npath = \"hooks\"\nlevels = [{claude-code = {settings = {Stop = [1]}}}, {opencode = {plugins = {\"a.js\" = \"x\"}}}]\n", + ); + let file = ExperimentFile::from_toml_str(&levels).expect("free keys in levels parse"); + assert_eq!(file.cells().len(), 2); + + let refused = with_tables("", "").replace("[fixed]\n", "[fixed.model.Odd]\nx = 1\n"); + assert!( + ExperimentFile::from_toml_str(&refused).is_err(), + "a table elsewhere keeps the key rule" + ); +} From c53d9c3b96134ceaccfd59aff6d803fb1f703de0 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 15:38:34 +0900 Subject: [PATCH 22/69] fix(runner): drop the dead sidecar and prompt-only branches Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/isolation/control.rs | 21 ++++++++++++-- crates/candler-core/src/isolation/layout.rs | 4 +++ .../src/jobs/orchestrate/controls.rs | 28 +++++++++---------- .../src/jobs/orchestrate/session.rs | 14 ++++------ .../it/guard_container_e2e/controls_e2e.rs | 14 ++++++---- .../tests/it/guard_container_run.rs | 20 +++++++++++-- .../tests/it/guard_trace_context_start.rs | 18 ++++++++---- crates/candler-harness-opencode/src/driver.rs | 7 +---- 8 files changed, 81 insertions(+), 45 deletions(-) diff --git a/crates/candler-core/src/isolation/control.rs b/crates/candler-core/src/isolation/control.rs index 38a9bd3e..19dfd646 100644 --- a/crates/candler-core/src/isolation/control.rs +++ b/crates/candler-core/src/isolation/control.rs @@ -4,14 +4,16 @@ //! //! A [`ControlSpec`] is every control container's flags in one place: it removes itself, wears the //! label `candler.role=control` and no job label (so no sweep meets it and the guard never -//! destroys it), carries [`hardening`] over the limits its kind needs, and has a network chosen by +//! destroys it; a control that runs for a job names it in `candler.control_job`), carries [`hardening`] over the limits its kind needs, and has a network chosen by //! its kind. [`outcome`] is the one reading of how it ended. use candler_schemas::process::ExitStatus; use super::docker::DockerError; use super::hardening::{HardLimits, Role, hardening}; -use super::layout::LABEL_ROLE; +use candler_schemas::primitives::JobId; + +use super::layout::{LABEL_CONTROL_JOB, LABEL_ROLE}; use crate::supervise::stop::{Captured, Ended}; /// The exit code of coreutils `timeout` when the command it runs overran. @@ -42,6 +44,7 @@ pub struct ControlSpec { detach: bool, user: Option<(u32, u32)>, workdir: Option, + job: Option, entrypoint: Option, env: Vec, mounts: Vec, @@ -59,6 +62,7 @@ impl ControlSpec { detach: false, user: None, workdir: None, + job: None, entrypoint: None, env: Vec::new(), mounts: Vec::new(), @@ -87,6 +91,13 @@ impl ControlSpec { self } + /// The same container, labelled with the job it runs for in [`LABEL_CONTROL_JOB`]. + #[must_use] + pub fn for_job(mut self, job: &JobId) -> Self { + self.job = Some(job.to_string()); + self + } + /// The same container, with `dir` as its working directory. #[must_use] pub fn workdir(mut self, dir: String) -> Self { @@ -149,6 +160,12 @@ impl ControlSpec { String::from("--label"), format!("{LABEL_ROLE}={}", Role::Control.label()), ]); + if let Some(job) = &self.job { + args.extend([ + String::from("--label"), + format!("{LABEL_CONTROL_JOB}={job}"), + ]); + } if let Some(program) = &self.entrypoint { args.extend([String::from("--entrypoint"), program.clone()]); // BORROW: the argv owns its text } diff --git a/crates/candler-core/src/isolation/layout.rs b/crates/candler-core/src/isolation/layout.rs index a4b45772..3bb942f2 100644 --- a/crates/candler-core/src/isolation/layout.rs +++ b/crates/candler-core/src/isolation/layout.rs @@ -45,6 +45,10 @@ pub const LABEL_RUN: &str = "candler.run"; /// The label that names the experiment digest. pub const LABEL_EXPERIMENT: &str = "candler.experiment"; +/// The label that names the job a control container runs for. It is not [`LABEL_JOB`]: no sweep +/// selects a control container, and the guard never destroys it. +pub const LABEL_CONTROL_JOB: &str = "candler.control_job"; + /// The label that names the container's role. pub const LABEL_ROLE: &str = "candler.role"; diff --git a/crates/candler-core/src/jobs/orchestrate/controls.rs b/crates/candler-core/src/jobs/orchestrate/controls.rs index 3b1a51b6..36207aa6 100644 --- a/crates/candler-core/src/jobs/orchestrate/controls.rs +++ b/crates/candler-core/src/jobs/orchestrate/controls.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use std::time::Duration; use candler_schemas::execution::{Comparable, EventPayload, JobRecord, JobState, SecretPresence}; -use candler_schemas::primitives::{Digest, RunKey}; +use candler_schemas::primitives::{Digest, JobId, RunKey}; use candler_schemas::values::SourceEntry; use futures::future::BoxFuture; use serde::{Deserialize, Serialize}; @@ -619,7 +619,10 @@ impl DockerControlRunner { )); let scripted = Scripted { script: control.name(), - idle_s: Some(control.idle_s()), + settings: vec![ + ("runner.idle_s", json!(control.idle_s())), + ("runner.mode", json!("session")), + ], }; let mut world = World { work, fake: None }; let outcome = self @@ -700,7 +703,7 @@ impl DockerControlRunner { let image = fake_image(&*docker, &self.contexts.fakemodel, &digest).await?; let token = format!("candler-control-{}-{}", std::process::id(), nanos()); let started = docker - .capture(fake_spec(&image, &token).args(), CALL) + .capture(fake_spec(&image, &token, &job).args(), CALL) .await .map_err(|e| err("starting the fake model", &e))?; let fake = String::from_utf8_lossy(&started).trim().to_owned(); // BORROW: the world keeps the container id @@ -856,7 +859,7 @@ async fn authority( /// is on docker's default network so that the egress network can be joined once the gateway has /// made it. #[must_use] -pub fn fake_spec(image: &str, token: &str) -> ControlSpec { +pub fn fake_spec(image: &str, token: &str, job: &JobId) -> ControlSpec { let limits = HardLimits { pids_limit: 64, memory: String::from("256m"), @@ -867,6 +870,7 @@ pub fn fake_spec(image: &str, token: &str) -> ControlSpec { ControlSpec::new(image, limits) .network(ControlNetwork::Default) .detached() + .for_job(job) .entrypoint("timeout") .env(vec![ format!("FAKE_TOKEN={token}"), @@ -883,22 +887,21 @@ pub fn fake_spec(image: &str, token: &str) -> ControlSpec { } /// What the fake model plays for a run, and how the run is driven. -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] pub struct Scripted<'a> { /// The fake model's script, which is the model id of the cell. pub script: &'a str, - /// The seconds after which a session closes; none runs a single prompt. - pub idle_s: Option, + /// The settings the cell holds besides the common ones, such as the session mode. + pub settings: Vec<(&'static str, Value)>, } -/// The cell of a run of `scripted` and its plan: over the base image with the harness `harness`, -/// a session when the script has an `idle_s`, a single prompt otherwise. +/// The cell of a run of `scripted` and its plan: over the base image with the harness `harness`. fn control_cell( identity: &Identity, harness: &Value, scripted: &Scripted<'_>, ) -> Result<(CellRun, RunPlan), String> { - let (script, idle_s) = (scripted.script, scripted.idle_s); + let script = scripted.script; let mut values: Vec<(&str, Value)> = vec![ ("budget.per_run.wall_s", json!(WALL_S)), ("isolation.image", json!(identity.base_id)), @@ -906,10 +909,7 @@ fn control_cell( ("permission_mode", json!("bypassPermissions")), ("prompt.template", json!("go")), ]; - if let Some(idle_s) = idle_s { - values.push(("runner.idle_s", json!(idle_s))); - values.push(("runner.mode", json!("session"))); - } + values.extend(scripted.settings.iter().cloned()); let entries: Vec = values .iter() .map(|(path, value)| json!({"path": path, "value": value})) diff --git a/crates/candler-core/src/jobs/orchestrate/session.rs b/crates/candler-core/src/jobs/orchestrate/session.rs index 6348ba16..b733bd47 100644 --- a/crates/candler-core/src/jobs/orchestrate/session.rs +++ b/crates/candler-core/src/jobs/orchestrate/session.rs @@ -215,7 +215,9 @@ pub trait JobHost: Send + Sync { } /// The host of a real job: the `docker` on `PATH` and a [`DockerGateway`] from the sidecar image -/// docker holds under the tag of the gateway's build context, when the host knows that context. +/// docker holds under the tag of the gateway's build context. Only a host made by +/// [`DockerHost::with_controls`] knows that context; any other refuses a job that needs a gateway +/// with `sidecar_image_missing`. #[derive(Debug, Clone)] pub struct DockerHost { controls: Result, @@ -240,7 +242,8 @@ impl DockerHost { } } - /// The host that cannot run session controls, for the reason `why`. + /// The host that cannot run session controls, for the reason `why`. It knows no gateway build + /// context either, so it refuses every job that needs a gateway. #[must_use] pub fn without_controls(why: &str) -> Self { Self { @@ -250,13 +253,6 @@ impl DockerHost { } } - /// The host whose gateway runs from the sidecar image docker holds under `tag`. - #[must_use] - pub fn with_sidecar(mut self, tag: String) -> Self { - self.sidecar = Some(tag); - self - } - /// The host whose gateway trusts the certificates of the PEM `ca` for the model upstream, in /// place of the system bundle; `None` keeps the system bundle. #[must_use] diff --git a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs index 3a2e8c44..e882fd60 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs @@ -218,12 +218,14 @@ impl ControlWorld { if self.base_made { docker(&["image", "rm", &self.base.id.0]).must("removing the agent base image"); } - let job_label = format!("label=candler.job={}", self.rig.job); - assert_eq!( - listed(&["ps", "-aq", "--filter", &job_label]), - Vec::::new(), - "no container of the job is left behind" - ); + for key in ["candler.job", "candler.control_job"] { + let label = format!("label={key}={}", self.rig.job); + assert_eq!( + listed(&["ps", "-aq", "--filter", &label]), + Vec::::new(), + "no container of the job is left behind ({key})" + ); + } } } diff --git a/crates/candler-core/tests/it/guard_container_run.rs b/crates/candler-core/tests/it/guard_container_run.rs index 3ff4e095..585ae4dc 100644 --- a/crates/candler-core/tests/it/guard_container_run.rs +++ b/crates/candler-core/tests/it/guard_container_run.rs @@ -223,7 +223,11 @@ fn kinds(root: &std::path::Path) -> Vec { }, Kind { name: "fake model", - args: args(fake_spec("sha256:abc", "token")), + args: args(fake_spec( + "sha256:abc", + "token", + &JobId::from_str("01900000-0000-7000-8000-000000000000").expect("a job id"), + )), network: None, tmpfs: &["/fake:rw,mode=1777,size=1m,noexec,nosuid"], pids: "64", @@ -235,7 +239,8 @@ fn kinds(root: &std::path::Path) -> Vec { } /// Guards: R01 §Process supervision (control containers) — every control container removes -/// itself, wears `candler.role=control` and no job label, has a read-only root, no capabilities +/// itself, wears `candler.role=control` and no job label (the fake model also names the job it +/// runs for, in a label no sweep selects), has a read-only root, no capabilities /// and no new privileges, and keeps its own network and limits: the probes 64 pids and 256m, the /// compile 256 pids and 2g on the bridge, the collect its caller's limits with a /// cpu cap, and the fake model no network flag. @@ -269,11 +274,20 @@ fn control_kind_flags_and_limits() { ["no-new-privileges"], "{name}: privileges" ); + let labels = values_of(args, "--label"); + let (owners, others): (Vec<&str>, Vec<&str>) = labels + .iter() + .partition(|label| label.starts_with("candler.control_job=")); assert_eq!( - values_of(args, "--label"), + others, ["candler.role=control"], "{name}: the one label, with no job" ); + assert_eq!( + owners.len(), + usize::from(name == "fake model"), + "{name}: only the fake model names the job it runs for" + ); assert_eq!( values_of(args, "--network"), kind.network.into_iter().collect::>(), diff --git a/crates/candler-core/tests/it/guard_trace_context_start.rs b/crates/candler-core/tests/it/guard_trace_context_start.rs index a2e5a992..44b5233c 100644 --- a/crates/candler-core/tests/it/guard_trace_context_start.rs +++ b/crates/candler-core/tests/it/guard_trace_context_start.rs @@ -15,7 +15,7 @@ use candler_harness_opencode::driver::OpenCodeDriver; use candler_schemas::primitives::RunKey; use candler_schemas::raw::FrameData; use candler_schemas::trace::{EventKind, TraceFile}; -use serde_json::Value; +use serde_json::{Value, json}; use crate::guard_container_e2e::controls_e2e_runs::ControlWorld; use crate::support::wiring::{Scenario, run}; @@ -48,7 +48,7 @@ struct Stored { async fn stored_trace( driver: Arc, // TRAIT_OBJECT: the driver is chosen at run time base_dir: &str, - session: bool, + settings: Vec<(&'static str, Value)>, ) -> Stored { let world = ControlWorld::new(driver, base_dir).await; let identity = world @@ -66,7 +66,7 @@ async fn stored_trace( &world.harness(), &Scripted { script: "c2", - idle_s: session.then_some(2), + settings, }, watch, work.clone(), @@ -176,8 +176,16 @@ fn check(harness: &str, stored: &Stored) -> Vec { #[tokio::test(flavor = "multi_thread")] #[ignore = "needs Docker; run with --run-ignored only"] async fn trace_context_first_event_is_the_first_request_with_tools_on_both_harnesses() { - let claude = stored_trace(Arc::new(ClaudeCodeDriver::new()), "base", true).await; - let opencode = stored_trace(Arc::new(OpenCodeDriver::new()), "base-opencode", false).await; + let claude = stored_trace( + Arc::new(ClaudeCodeDriver::new()), + "base", + vec![ + ("runner.idle_s", json!(2)), + ("runner.mode", json!("session")), + ], + ) + .await; + let opencode = stored_trace(Arc::new(OpenCodeDriver::new()), "base-opencode", Vec::new()).await; let mut problems = check("claude-code", &claude); problems.extend(check("opencode", &opencode)); assert!(problems.is_empty(), "{problems:#?}"); diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index 8dd53647..a53dcc9b 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -254,7 +254,7 @@ impl HarnessDriver for OpenCodeDriver { } fn census_stream(&self) -> Option { - census_stream() + GATEWAY_STREAM.parse().ok() } fn offline_reader( @@ -337,10 +337,5 @@ fn ambiguous_prefixes(names: &[String]) -> Result<(), DriverError> { Ok(()) } -/// The stream the gateway's census is stored as. -fn census_stream() -> Option { - GATEWAY_STREAM.parse().ok() -} - /// The placeholder the core fills with the root session id. const SESSION_ID: &str = candler_harness::spec::SESSION_ID_PLACEHOLDER; From 124b1b8cd5fb53316d6a87f83dfd2619fb5e852c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 15:43:54 +0900 Subject: [PATCH 23/69] feat(api): read hooks and instructions as the harness writes them Co-Authored-By: Claude Sonnet 5.5 --- .../src/jobs/orchestrate/controls.rs | 1 - .../candler-core/src/jobs/orchestrate/mod.rs | 1 - crates/candler-core/src/jobs/runtime/mod.rs | 2 - .../candler-core/src/jobs/runtime/session.rs | 1 - crates/candler-core/src/resolve/paths.rs | 4 +- crates/candler-core/src/runner/mod.rs | 2 - crates/candler-core/src/runner/plan.rs | 20 +- .../tests/it/guard_agent_config.rs | 32 ++- .../it/guard_container_e2e/controls_e2e.rs | 1 - .../tests/it/guard_egress_setting.rs | 1 - .../tests/it/guard_job_runtime.rs | 1 - crates/candler-core/tests/it/guard_session.rs | 1 - .../tests/it/support/job_orchestrate.rs | 1 - .../tests/it/support/job_runtime.rs | 1 - .../candler-core/tests/it/support/run_plan.rs | 1 - .../candler-harness-claude-code/src/driver.rs | 9 +- crates/candler-harness-opencode/src/driver.rs | 7 +- crates/candler-harness/src/agent_config.rs | 223 +++--------------- crates/candler-harness/src/refusal.rs | 9 +- crates/candler-harness/src/spec.rs | 19 ++ .../tests/it/guard_agent_config.rs | 73 +++--- crates/candler/src/commands/resolve.rs | 8 +- crates/candler/src/commands/run.rs | 1 - crates/candler/src/commands/supervise.rs | 1 - .../candler/tests/it/guard_cli_kill_live.rs | 1 - .../candler/tests/it/guard_driver_answers.rs | 16 ++ .../candler/tests/it/guard_golden_design.rs | 1 - .../tests/it/support/contract_pages/pages.rs | 2 +- docs/contract/configuration-paths.md | 4 +- docs/contract/experiment-file.md | 2 +- 30 files changed, 151 insertions(+), 295 deletions(-) diff --git a/crates/candler-core/src/jobs/orchestrate/controls.rs b/crates/candler-core/src/jobs/orchestrate/controls.rs index 159944a1..a4d1d691 100644 --- a/crates/candler-core/src/jobs/orchestrate/controls.rs +++ b/crates/candler-core/src/jobs/orchestrate/controls.rs @@ -663,7 +663,6 @@ impl DockerControlRunner { gateway: None, job: job.clone(), // BORROW: the runtime owns its job id driver: Arc::clone(&rt.driver), - harnesses: rt.harnesses.clone(), // BORROW: the runtime owns its list cells: std::collections::BTreeMap::new(), eval_infra: rt.eval_infra.clone(), // BORROW: the runtime owns its build identity }; diff --git a/crates/candler-core/src/jobs/orchestrate/mod.rs b/crates/candler-core/src/jobs/orchestrate/mod.rs index 4ec5fa89..63cd72c6 100644 --- a/crates/candler-core/src/jobs/orchestrate/mod.rs +++ b/crates/candler-core/src/jobs/orchestrate/mod.rs @@ -122,7 +122,6 @@ async fn run_job( experiment_lock: rt.store.layout().experiment_lock(&fresh), secrets_present: secrets.present(), driver: Some(Arc::clone(&rt.driver)), - harnesses: rt.harnesses.clone(), // BORROW: the context owns its list }; let force = if spec.force { Force::Yes } else { Force::No }; let outcome = match plan_runs( diff --git a/crates/candler-core/src/jobs/runtime/mod.rs b/crates/candler-core/src/jobs/runtime/mod.rs index dd2ae201..ff05f060 100644 --- a/crates/candler-core/src/jobs/runtime/mod.rs +++ b/crates/candler-core/src/jobs/runtime/mod.rs @@ -48,8 +48,6 @@ pub struct JobServices { // TRAIT_OBJECT: the harness's driver, or a recording fake in tests /// What the runner needs from the harness, as data. pub driver: Arc, - /// The ids of the registered harnesses. - pub harnesses: Vec, /// Which build of the evaluation infrastructure runs the job. pub eval_infra: EvalInfra, } diff --git a/crates/candler-core/src/jobs/runtime/session.rs b/crates/candler-core/src/jobs/runtime/session.rs index 9fe47288..b9e17ad2 100644 --- a/crates/candler-core/src/jobs/runtime/session.rs +++ b/crates/candler-core/src/jobs/runtime/session.rs @@ -354,7 +354,6 @@ async fn serve( gateway: None, job: job.clone(), // BORROW: the runtime owns its job id driver: services.driver, - harnesses: services.harnesses, cells: BTreeMap::new(), eval_infra: services.eval_infra, }; diff --git a/crates/candler-core/src/resolve/paths.rs b/crates/candler-core/src/resolve/paths.rs index 611cd0ef..7aff99db 100644 --- a/crates/candler-core/src/resolve/paths.rs +++ b/crates/candler-core/src/resolve/paths.rs @@ -221,7 +221,7 @@ pub const CONFIGURATION_PATHS: [PathRow; 51] = [ Kind::Subtree, Class::Value, Reach::Agent(&[AgentSetting::Instructions(InstructionScope::Global)]), - "The global instruction text of each harness: a table of harness id (written with `_` for `-`) to text.", + "The global instruction text of each harness: a table of harness id, as registered, to text; the keys are free.", ), row( INSTRUCTIONS_WORKSPACE, @@ -235,7 +235,7 @@ pub const CONFIGURATION_PATHS: [PathRow; 51] = [ Kind::Subtree, Class::Value, Reach::Agent(&[AgentSetting::Hooks]), - "The hooks of each harness: a table of harness id (written with `_` for `-`) to its `settings` or `files`, or its `plugins`.", + "The hooks of each harness: a table of harness id, as registered, to its `settings` table and `files` table (Claude Code) or its `plugins` table (OpenCode); the keys are free.", ), row( PERMISSION_MODE, diff --git a/crates/candler-core/src/runner/mod.rs b/crates/candler-core/src/runner/mod.rs index 4d3c6a5b..f36a293b 100644 --- a/crates/candler-core/src/runner/mod.rs +++ b/crates/candler-core/src/runner/mod.rs @@ -65,8 +65,6 @@ pub struct Runtime { // TRAIT_OBJECT: the driver is the harness's, or a recording fake in tests /// What the runner needs from the harness, as data. pub driver: Arc, - /// The ids of the registered harnesses. - pub harnesses: Vec, /// What each cell of the job is, by its digest. pub cells: BTreeMap>, /// The build of the evaluation infrastructure that runs the job. diff --git a/crates/candler-core/src/runner/plan.rs b/crates/candler-core/src/runner/plan.rs index 7dec2d32..6da3d514 100644 --- a/crates/candler-core/src/runner/plan.rs +++ b/crates/candler-core/src/runner/plan.rs @@ -57,9 +57,6 @@ pub struct PlanCtx { /// it cannot honour; `None` when the caller has none, and both are then left unchecked. // TRAIT_OBJECT: the binary selects the driver at runtime pub driver: Option>, - /// The ids of the registered harnesses, which the keys of a cell's `hooks` and - /// `instructions.global` must name. - pub harnesses: Vec, } /// Whether a forced plan may accept a differing re-check. @@ -153,7 +150,7 @@ pub fn experiment_of<'a>( file: &ExperimentFile, levels: impl Into>, ) -> Result { - let cells = fresh_cells(file, &levels.into(), None, &[])?; + let cells = fresh_cells(file, &levels.into(), None)?; let digests: Vec = cells.iter().map(|cell| cell.comparable.digest()).collect(); // BORROW: explicit .as_slice() instead of Deref coercion Ok(experiment_digest(digests.as_slice())) @@ -169,11 +166,10 @@ pub fn check_cells<'a>( file: &ExperimentFile, levels: impl Into>, driver: &dyn HarnessDriver, // TRAIT_OBJECT: the registry's driver, selected at run time - harnesses: &[String], ) -> Result<(), PlanError> { let levels = levels.into(); levels.replicates(file)?; - fresh_cells(file, &levels, Some(driver), harnesses).map(drop) + fresh_cells(file, &levels, Some(driver)).map(drop) } /// A deviation as `path {stored: , observed: }`, for a message; a value that was @@ -628,7 +624,6 @@ fn fresh_cells<'r>( file: &ExperimentFile, levels: &Levels<'r>, driver: Option<&dyn HarnessDriver>, - harnesses: &[String], ) -> Result>, PlanError> { let session_capable = driver.map(|driver| !driver.answer(AgentSetting::SessionMode).is_refused()); @@ -769,8 +764,8 @@ fn fresh_cells<'r>( for cell in &cells { let view = Cell::new(cell.comparable.values()); let harness = driver.id().to_string(); // BORROW: .to_string() gives owned text - agent_config::instructions(&view, harness.as_str(), harnesses)?; // BORROW: explicit .as_str() - agent_config::hooks(&view, harness.as_str(), harnesses)?; // BORROW: explicit .as_str() + agent_config::instructions(&view, harness.as_str())?; // BORROW: explicit .as_str() + agent_config::hooks(&view, harness.as_str())?; // BORROW: explicit .as_str() refuse_unanswered(driver, &view)?; driver.check_settings(&view)?; } @@ -1198,12 +1193,7 @@ pub fn plan_runs<'a>( None } }; - let cells = fresh_cells( - file, - &levels, - ctx.driver.as_deref(), - ctx.harnesses.as_slice(), - )?; + let cells = fresh_cells(file, &levels, ctx.driver.as_deref())?; let ledger = read_ledger(&ctx.store)?; // BORROW: explicit .as_slice() instead of Deref coercion let matched = match_stored(cells.as_slice(), ledger.groups.as_slice())?; diff --git a/crates/candler-core/tests/it/guard_agent_config.rs b/crates/candler-core/tests/it/guard_agent_config.rs index 8a31f379..d6f143b5 100644 --- a/crates/candler-core/tests/it/guard_agent_config.rs +++ b/crates/candler-core/tests/it/guard_agent_config.rs @@ -78,7 +78,6 @@ async fn planned( experiment_lock: lock, secrets_present: BTreeSet::new(), driver, - harnesses: vec!["claude-code".to_owned(), "opencode".to_owned()], }; let outcome = plan_runs(&ctx, file, &resolution, Force::No, PlanMode::Check)?; Ok(outcome.plans.iter().map(|plan| plan.cell.clone()).collect()) @@ -93,8 +92,11 @@ async fn two_levels_of_instructions_or_hooks_plan_two_cells() { let levels = [ ("instructions.workspace", ["\"text A\"", "\"text B\""]), ( - "hooks.claude_code.settings", - ["'{\"SessionStart\": []}'", "'{\"Stop\": []}'"], + "hooks", + [ + "{claude-code = {settings = {SessionStart = []}}}", + "{claude-code = {settings = {Stop = []}}}", + ], ), ]; for (path, [first, second]) in levels { @@ -143,21 +145,31 @@ async fn misused_hooks_and_instructions_are_refused_by_name() { case( "hooks of another harness", Arc::clone(&opencode), - ("hooks.claude_code.settings", json!("{}")), + ("hooks", json!({"claude-code": {"settings": {"Stop": []}}})), "experiment.cell_value_missing", Some("/fixed/hooks"), ), case( "global text of another harness", opencode, - ("instructions.global.claude_code", json!("text")), + ("instructions.global", json!({"claude-code": "text"})), "experiment.cell_value_missing", Some("/fixed/instructions.global"), ), case( - "an unregistered harness key", + "an unregistered key of the global texts", Arc::clone(&claude), - ("hooks.nosuch.settings", json!("{}")), + ( + "instructions.global", + json!({"nosuch": "x", "claude-code": "y"}), + ), + "experiment.cell_value_invalid", + Some("/instructions/global"), + ), + case( + "an unregistered key of the hooks", + Arc::clone(&claude), + ("hooks", json!({"nosuch": {}})), "experiment.cell_value_invalid", Some("/hooks"), ), @@ -165,11 +177,11 @@ async fn misused_hooks_and_instructions_are_refused_by_name() { "a hook file path with `..`", claude, ( - "hooks.claude_code.files", - json!([{"path": "../evil.sh", "text": "x"}]), + "hooks", + json!({"claude-code": {"files": {"../evil.sh": "x"}}}), ), "experiment.cell_value_invalid", - Some("/hooks/claude_code/files"), + Some("/hooks"), ), ]; for Case { diff --git a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs index a0fc1bf9..c7cbb8d7 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/controls_e2e.rs @@ -145,7 +145,6 @@ async fn controls_e2e_pinned_harness_passes() { gateway: None, job: rig.job.clone(), driver: Arc::new(ClaudeCodeDriver::new()), - harnesses: Vec::new(), cells: std::collections::BTreeMap::new(), eval_infra: EvalInfra::default(), }; diff --git a/crates/candler-core/tests/it/guard_egress_setting.rs b/crates/candler-core/tests/it/guard_egress_setting.rs index b7b979cf..772e7f67 100644 --- a/crates/candler-core/tests/it/guard_egress_setting.rs +++ b/crates/candler-core/tests/it/guard_egress_setting.rs @@ -445,7 +445,6 @@ async fn planned( experiment_lock: lock, secrets_present: BTreeSet::new(), driver: Some(Arc::new(ClaudeCodeDriver::new())), - harnesses: Vec::new(), }; let outcome = plan_runs(&ctx, file, &resolution, Force::No, PlanMode::Check)?; let spec = JobSpec { diff --git a/crates/candler-core/tests/it/guard_job_runtime.rs b/crates/candler-core/tests/it/guard_job_runtime.rs index 6a43a7e4..7d20b72a 100644 --- a/crates/candler-core/tests/it/guard_job_runtime.rs +++ b/crates/candler-core/tests/it/guard_job_runtime.rs @@ -375,7 +375,6 @@ fn reap_child() { gateway: None, job: own.clone(), // BORROW: the runtime owns its job id driver: Arc::new(QuietDriver), - harnesses: Vec::new(), cells: BTreeMap::new(), eval_infra: EvalInfra::default(), }; diff --git a/crates/candler-core/tests/it/guard_session.rs b/crates/candler-core/tests/it/guard_session.rs index 9b0a3b97..3f9ee5da 100644 --- a/crates/candler-core/tests/it/guard_session.rs +++ b/crates/candler-core/tests/it/guard_session.rs @@ -300,7 +300,6 @@ async fn planned( } else { Arc::new(OpenCodeDriver::new()) }), - harnesses: Vec::new(), }; let outcome = plan_runs(&ctx, file, &resolution, Force::No, PlanMode::Check)?; let spec = JobSpec { diff --git a/crates/candler-core/tests/it/support/job_orchestrate.rs b/crates/candler-core/tests/it/support/job_orchestrate.rs index a48226fe..5ccfeec5 100644 --- a/crates/candler-core/tests/it/support/job_orchestrate.rs +++ b/crates/candler-core/tests/it/support/job_orchestrate.rs @@ -658,7 +658,6 @@ impl Rig { gateway: None, job: self.job.clone(), driver: Arc::new(QuietDriver), - harnesses: Vec::new(), cells: BTreeMap::new(), eval_infra: EvalInfra::default(), } diff --git a/crates/candler-core/tests/it/support/job_runtime.rs b/crates/candler-core/tests/it/support/job_runtime.rs index ac48cd2c..c5ea1d22 100644 --- a/crates/candler-core/tests/it/support/job_runtime.rs +++ b/crates/candler-core/tests/it/support/job_runtime.rs @@ -69,7 +69,6 @@ pub fn services() -> JobServices { JobServices { // TRAIT_OBJECT: the driver is the harness's real one, which a guard never calls driver: Arc::new(ClaudeCodeDriver::new()), - harnesses: Vec::new(), eval_infra: EvalInfra::default(), } } diff --git a/crates/candler-core/tests/it/support/run_plan.rs b/crates/candler-core/tests/it/support/run_plan.rs index 21a1321e..e1253fbf 100644 --- a/crates/candler-core/tests/it/support/run_plan.rs +++ b/crates/candler-core/tests/it/support/run_plan.rs @@ -228,7 +228,6 @@ pub fn plan_ctx(store: &Store, lock: &Path, facts: &Facts) -> PlanCtx { .map(|name| name.parse::().expect("a secret name")) .collect::>(), driver: None, - harnesses: Vec::new(), } } diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index 619963b3..5dacc79c 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -10,12 +10,11 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ - AgentSetting, Answer, BaseImage, Cell, CollectSpec, CommandSpec, DriverFact, EffortLevel, - GatewayEnv, HarnessId, Observed, PermissionMode, Prepared, ProcessExit, SessionTracker, - StopSignal, StopSpec, Workspace, + AgentSetting, Answer, BaseImage, CLAUDE_CODE, Cell, CollectSpec, CommandSpec, DriverFact, + EffortLevel, GatewayEnv, HarnessId, Observed, PermissionMode, Prepared, ProcessExit, + SessionTracker, StopSignal, StopSpec, Workspace, }; use candler_schemas::execution::paths; -use candler_schemas::name; use candler_schemas::primitives::FieldPath; use candler_schemas::raw::StreamName; use candler_schemas::servers::McpServerKind; @@ -147,7 +146,7 @@ impl ClaudeCodeDriver { #[must_use] pub fn new() -> Self { Self { - id: HarnessId::new(name!("claude-code")), + id: HarnessId::listed(CLAUDE_CODE), // BORROW: .to_owned() makes owned arguments probe: CommandSpec::new(PROGRAM.to_owned(), vec!["--version".to_owned()]), } diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index 99c17087..4677d2d4 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -12,10 +12,9 @@ use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ Action, AgentSetting, Answer, BaseImage, Cell, CollectSpec, CommandSpec, DriverFact, - GatewayEnv, HarnessId, Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, - StopSpec, Workspace, + GatewayEnv, HarnessId, OPENCODE, Observed, Prepared, ProcessExit, StateKind, StatePath, + StopSignal, StopSpec, Workspace, }; -use candler_schemas::name; use candler_schemas::primitives::{RelPath, plain_arg}; use candler_schemas::raw::StreamName; use candler_schemas::trace::{EndedBy, Session}; @@ -84,7 +83,7 @@ impl OpenCodeDriver { #[must_use] pub fn new() -> Self { Self { - id: HarnessId::new(name!("opencode")), + id: HarnessId::listed(OPENCODE), probe: CommandSpec::new(PROGRAM.to_owned(), argv(&["--version"])), // BORROW: .to_owned() makes the owned program } } diff --git a/crates/candler-harness/src/agent_config.rs b/crates/candler-harness/src/agent_config.rs index 7d0ad3cc..6e5f2410 100644 --- a/crates/candler-harness/src/agent_config.rs +++ b/crates/candler-harness/src/agent_config.rs @@ -1,27 +1,18 @@ //! The instruction texts and hooks of a cell, as the harness the cell runs reads them. //! -//! [`instructions`] and [`hooks`] are the one reader of `instructions.*` and `hooks`: both -//! drivers and the core read the values through them, and each refuses what it does not -//! understand. The cell holds the values as leaves (see [`candler_schemas::agent_config`]); a -//! harness id is written with `_` where it has `-`, and every id below `instructions.global` and -//! `hooks` is checked against the harnesses the caller says are registered. - -use std::str::FromStr as _; +//! [`instructions`] and [`hooks`] are the one reader of `instructions.*` and `hooks`: the core's +//! plan reads the values through them and each refuses what it does not understand. The cell +//! holds `instructions.global` and `hooks` as tables whose keys are harness ids, spelled as +//! registered, and every such key must be one of [`HARNESS_IDS`]. use candler_schemas::agent_config::{ClaudeCodeHooks, Instructions, OpenCodeHooks}; -use candler_schemas::execution::paths::{HOOKS, INSTRUCTIONS_GLOBAL}; use candler_schemas::field_path; -use candler_schemas::primitives::{FieldPath, RelPath}; -use serde::Deserialize; -use serde_json::{Map, Value}; +use candler_schemas::primitives::FieldPath; +use serde::de::DeserializeOwned; +use serde_json::Value; use crate::driver::DriverError; -use crate::spec::Cell; - -/// The id of the Claude Code harness. -const CLAUDE_CODE: &str = "claude-code"; -/// The id of the `OpenCode` harness. -const OPENCODE: &str = "opencode"; +use crate::spec::{CLAUDE_CODE, Cell, HARNESS_IDS, OPENCODE}; /// The hooks the cell gives the harness it runs. #[derive(Debug, Clone, PartialEq, Eq)] @@ -33,24 +24,6 @@ pub enum Hooks { OpenCode(OpenCodeHooks), } -/// One file of a hook list: where it goes and what it holds. -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct HookFile { - path: String, - text: String, -} - -/// How a harness id is written as a key of a cell value. -fn spelled(id: &str) -> String { - id.replace('-', "_") -} - -/// The field path `text`, or `root` when `text` is not one. -fn at(text: &str, root: &FieldPath) -> FieldPath { - FieldPath::from_str(text).unwrap_or_else(|_| root.clone()) // BORROW: the error owns the path -} - fn invalid(path: &FieldPath, detail: impl Into) -> DriverError { DriverError::InvalidValue { path: path.clone(), // BORROW: the error owns the path @@ -58,154 +31,49 @@ fn invalid(path: &FieldPath, detail: impl Into) -> DriverError { } } -/// The registered harness whose key is `key`. -fn registered_id<'a>( - key: &str, - registered: &'a [String], - root: &FieldPath, -) -> Result<&'a str, DriverError> { - registered - .iter() - .find(|id| spelled(id) == key) - .map(String::as_str) // BORROW: explicit .as_str() instead of Deref coercion - .ok_or_else(|| { - let names: Vec = registered.iter().map(|id| spelled(id)).collect(); - invalid( - root, - format!( - "`{key}` names no registered harness; the registered ones are {}", - names.join(", ") - ), - ) - }) -} - -fn object<'v>(value: &'v Value, path: &FieldPath) -> Result<&'v Map, DriverError> { - value - .as_object() - .ok_or_else(|| invalid(path, "is not a table")) -} - -fn text<'v>(value: &'v Value, path: &FieldPath) -> Result<&'v str, DriverError> { - value.as_str().ok_or_else(|| invalid(path, "is not text")) +/// `value` read as a `T`, a refusal at `path` naming the member at fault. +fn read(value: Value, path: &FieldPath) -> Result { + serde_path_to_error::deserialize(value) + .map_err(|error| invalid(path, format!("`{}`: {}", error.path(), error.inner()))) } -/// A list of `{path, text}` entries as the object from path to text. -/// -/// # Errors -/// [`DriverError::InvalidValue`] for an entry that is not `{path, text}`, a path that is not a -/// relative path, or a path that repeats. -fn files(value: &Value, at_path: &FieldPath) -> Result { - let Value::Array(items) = value else { - return Err(invalid(at_path, "is not a list of `{path, text}` entries")); - }; - let mut out = Map::new(); - for item in items { - let entry: HookFile = serde_json::from_value(item.clone()) // BORROW: .clone() copies the entry out of the cell - .map_err(|error| invalid(at_path, error.to_string()))?; // BORROW: .to_string() gives owned text - RelPath::from_str(&entry.path).map_err(|error| invalid(at_path, error.to_string()))?; // BORROW: .to_string() gives owned text - if out - .insert(entry.path.clone(), Value::String(entry.text)) - .is_some() - { - // BORROW: .clone() keeps the path for the message - return Err(invalid( - at_path, - format!("holds the path `{}` twice", entry.path), - )); - } - } - Ok(Value::Object(out)) -} - -/// The entry of one harness shaped as the object its envelope reads: `settings` read as the JSON -/// object its text holds, the list named `list` as an object from path to text. -fn shaped( - entry: &Value, - entry_path: &str, - root: &FieldPath, - list: &str, - settings: bool, -) -> Result { - let entry_at = at(entry_path, root); - let mut out = Map::new(); - for (member, value) in object(entry, &entry_at)? { - let member_at = at(&format!("{entry_path}.{member}"), root); - if settings && member == "settings" { - let parsed: Value = serde_json::from_str(text(value, &member_at)?) - .map_err(|error| invalid(&member_at, format!("is not JSON: {error}")))?; - if !parsed.is_object() { - return Err(invalid(&member_at, "is not the text of a JSON object")); - } - out.insert(member.clone(), parsed); // BORROW: the object owns its key - } else if member == list { - out.insert(member.clone(), files(value, &member_at)?); // BORROW: the object owns its key - } else { +/// Refuses a key of the table at `path` that is not the id of a built-in harness. +fn listed<'k>(keys: impl Iterator, path: &FieldPath) -> Result<(), DriverError> { + for key in keys { + if !HARNESS_IDS.contains(&key.as_str()) { + // BORROW: explicit .as_str() instead of Deref coercion return Err(invalid( - &member_at, + path, format!( - "is not a member of the hooks of this harness; they are `{list}`{}", - if settings { " and `settings`" } else { "" } + "`{key}` names no registered harness; the registered ones are {}", + HARNESS_IDS.join(", ") ), )); } } - Ok(Value::Object(out)) + Ok(()) } /// The instruction texts of a cell, with the global text of every harness it names. `None` when /// the cell sets none. /// -/// `harness` is the id of the harness the cell runs and `registered` the ids of every harness -/// that is registered. +/// `harness` is the id of the harness the cell runs. /// /// # Errors /// [`DriverError::InvalidValue`] when a value is not text or a key names no registered harness, /// and [`DriverError::MissingValue`] when the cell sets a global text and none for `harness`. -pub fn instructions( - cell: &Cell<'_>, - harness: &str, - registered: &[String], -) -> Result, DriverError> { - let Some(table) = cell.table_at(&field_path!("instructions"))? else { +pub fn instructions(cell: &Cell<'_>, harness: &str) -> Result, DriverError> { + let root = field_path!("instructions"); + let Some(table) = cell.table_at(&root)? else { return Ok(None); }; - let global_path = field_path!("instructions.global"); - let mut shaped = Map::new(); - for (member, value) in &table { - match member.as_str() { - // BORROW: explicit .as_str() instead of Deref coercion - "global" => { - let mut by_id = Map::new(); - for (key, text_value) in object(value, &global_path)? { - let id = registered_id(key, registered, &global_path)?; - let own = at(&format!("{INSTRUCTIONS_GLOBAL}.{key}"), &global_path); - text(text_value, &own)?; - by_id.insert(id.to_owned(), text_value.clone()); // BORROW: the object owns its key and text - } - if !by_id.contains_key(harness) { - return Err(DriverError::MissingValue { path: global_path }); - } - shaped.insert(member.clone(), Value::Object(by_id)); // BORROW: the object owns its key - } - "workspace" => { - text(value, &field_path!("instructions.workspace"))?; - shaped.insert(member.clone(), value.clone()); // BORROW: the object owns its key and value - } - _ => { - return Err(invalid( - &at( - &format!("instructions.{member}"), - &field_path!("instructions"), - ), - "is not an instruction text; they are `global` and `workspace`", - )); - } - } + let found: Instructions = read(Value::Object(table), &root)?; + let global = field_path!("instructions.global"); + listed(found.global.keys(), &global)?; + if !found.global.is_empty() && !found.global.contains_key(harness) { + return Err(DriverError::MissingValue { path: global }); } - serde_json::from_value(Value::Object(shaped)) - .map(Some) - .map_err(|error| invalid(&field_path!("instructions"), error.to_string())) // BORROW: .to_string() gives owned text + Ok(Some(found)) } /// The hooks of a cell for `harness`. `None` when the cell sets none. @@ -214,33 +82,20 @@ pub fn instructions( /// [`DriverError::InvalidValue`] when a key names no registered harness or the entry of `harness` /// does not fit its envelope (a hook file whose path is not a relative path included), and /// [`DriverError::MissingValue`] when the cell sets hooks and none for `harness`. -pub fn hooks( - cell: &Cell<'_>, - harness: &str, - registered: &[String], -) -> Result, DriverError> { +pub fn hooks(cell: &Cell<'_>, harness: &str) -> Result, DriverError> { let root = field_path!("hooks"); let Some(table) = cell.table_at(&root)? else { return Ok(None); }; - for key in table.keys() { - registered_id(key, registered, &root)?; - } - let key = spelled(harness); - let Some(entry) = table.get(&key) else { + listed(table.keys(), &root)?; + let Some(entry) = table.get(harness) else { return Err(DriverError::MissingValue { path: root }); }; - let entry_path = format!("{HOOKS}.{key}"); + // BORROW: .clone() copies the entry out of the table + let entry = entry.clone(); match harness { - CLAUDE_CODE => serde_json::from_value(shaped(entry, &entry_path, &root, "files", true)?) - .map(|found| Some(Hooks::ClaudeCode(found))) - .map_err(|error| invalid(&at(&entry_path, &root), error.to_string())), // BORROW: .to_string() gives owned text - OPENCODE => serde_json::from_value(shaped(entry, &entry_path, &root, "plugins", false)?) - .map(|found| Some(Hooks::OpenCode(found))) - .map_err(|error| invalid(&at(&entry_path, &root), error.to_string())), // BORROW: .to_string() gives owned text - other => Err(invalid( - &at(&entry_path, &root), - format!("`{other}` has no hooks"), - )), + CLAUDE_CODE => read(entry, &root).map(|found| Some(Hooks::ClaudeCode(found))), + OPENCODE => read(entry, &root).map(|found| Some(Hooks::OpenCode(found))), + other => Err(invalid(&root, format!("`{other}` has no hooks"))), } } diff --git a/crates/candler-harness/src/refusal.rs b/crates/candler-harness/src/refusal.rs index 1e36bf19..834e322e 100644 --- a/crates/candler-harness/src/refusal.rs +++ b/crates/candler-harness/src/refusal.rs @@ -23,8 +23,13 @@ fn driver_error_path(error: &DriverError) -> Option { match error { DriverError::Command(inner) => Refusal::path(inner), DriverError::MissingValue { path } => { - let text = path.to_string(); // BORROW: .to_string() gives owned text - Some(pointer_of(["fixed", text.as_str()])) // BORROW: explicit .as_str() instead of Deref coercion + // A cap lives under `/budget`, every other value is a key of `[fixed]` (or a factor). + if path.segments().next() == Some("budget") { + Some(pointer_of(path.segments())) + } else { + let text = path.to_string(); // BORROW: .to_string() gives owned text + Some(pointer_of(["fixed", text.as_str()])) // BORROW: explicit .as_str() instead of Deref coercion + } } DriverError::Unsupported { path, .. } | DriverError::HarnessRejectedInput { path, .. } diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index e766c292..b010b766 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -1224,6 +1224,19 @@ pub enum Framing { Document, } +/// The id of the Claude Code harness. +pub const CLAUDE_CODE: &str = "claude-code"; +/// The id of the `OpenCode` harness. +pub const OPENCODE: &str = "opencode"; +/// The ids of the harnesses this workspace ships a driver for: every driver's id is one of them, +/// and the keys below a cell's `hooks` and `instructions.global` are checked against them. +pub const HARNESS_IDS: [&str; 2] = [CLAUDE_CODE, OPENCODE]; + +const _: () = { + assert!(candler_schemas::primitives::is_ascii_name(CLAUDE_CODE)); + assert!(candler_schemas::primitives::is_ascii_name(OPENCODE)); +}; + /// The identity of a harness: its plain name, the value `comparable.harness.name` and the experiment's harness request hold. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] @@ -1236,6 +1249,12 @@ impl HarnessId { Self(name) } + /// The id of the built-in harness `id`, one of [`HARNESS_IDS`], whose text is a valid name. + #[must_use] + pub fn listed(id: &'static str) -> Self { + Self(Name::from_checked_literal(id)) + } + /// The harness name. #[must_use] pub const fn as_name<'a>(&'a self) -> &'a Name { diff --git a/crates/candler-harness/tests/it/guard_agent_config.rs b/crates/candler-harness/tests/it/guard_agent_config.rs index bbcf4944..eae7a057 100644 --- a/crates/candler-harness/tests/it/guard_agent_config.rs +++ b/crates/candler-harness/tests/it/guard_agent_config.rs @@ -12,10 +12,6 @@ use serde_json::{Value, json}; type Res = Result>; -fn registered() -> Vec { - vec!["claude-code".to_owned(), "opencode".to_owned()] -} - fn cell(entries: &[(&str, Value)]) -> Res> { entries .iter() @@ -28,36 +24,35 @@ fn cell(entries: &[(&str, Value)]) -> Res> { .collect() } -/// Guards: the hooks of a Claude Code cell are read as the settings object its text holds and the -/// files it lists, and the global and workspace texts as their envelope. +/// Guards: the hooks of a Claude Code cell are read as the settings table and the files it +/// lists, those of an `OpenCode` cell as its plugins, and the global and workspace texts as their +/// envelope. /// Oracle: the values are written by hand. -/// Bite: read `settings` as text, or the file list as a list (the typed envelopes differ). +/// Bite: read the cell's hooks as one harness's whatever the harness. #[test] fn a_cell_gives_each_harness_its_own_envelope() -> Res<()> { let values = cell(&[ - ("hooks.claude_code.settings", json!("{\"Stop\": []}")), - ( - "hooks.claude_code.files", - json!([{"path": "guard.sh", "text": "#!/bin/sh"}]), - ), ( - "hooks.opencode.plugins", - json!([{"path": "p.js", "text": "x"}]), + "hooks", + json!({ + "claude-code": {"settings": {"Stop": []}, "files": {"guard.sh": "#!/bin/sh"}}, + "opencode": {"plugins": {"p.js": "x"}} + }), ), - ("instructions.global.claude_code", json!("global")), + ("instructions.global", json!({"claude-code": "global"})), ("instructions.workspace", json!("workspace")), ])?; let view = Cell::new(&values); - let Some(Hooks::ClaudeCode(found)) = hooks(&view, "claude-code", ®istered())? else { + let Some(Hooks::ClaudeCode(found)) = hooks(&view, "claude-code")? else { return Err("claude code hooks".into()); }; assert_eq!(found.settings.map(Value::Object), Some(json!({"Stop": []}))); assert_eq!(found.files.len(), 1); - let Some(Hooks::OpenCode(found)) = hooks(&view, "opencode", ®istered())? else { + let Some(Hooks::OpenCode(found)) = hooks(&view, "opencode")? else { return Err("opencode hooks".into()); }; assert_eq!(found.plugins.len(), 1); - let Some(text) = instructions(&view, "claude-code", ®istered())? else { + let Some(text) = instructions(&view, "claude-code")? else { return Err("instructions".into()); }; assert_eq!( @@ -68,37 +63,27 @@ fn a_cell_gives_each_harness_its_own_envelope() -> Res<()> { Ok(()) } -/// Guards: an entry that is not an envelope member, settings that are not a JSON object, and a -/// file path that appears twice are each refused at the value. +/// Guards: a member that is not part of the envelope, settings that are not a table, and a file +/// path that is not a relative path are each refused at `hooks`, naming the member at fault. /// Oracle: the refused values are written by hand. -/// Bite: ignore unknown members, or parse the settings leniently. +/// Bite: ignore unknown members, or accept any path. #[test] fn an_entry_that_does_not_fit_its_envelope_is_refused() -> Res<()> { - let refused = |entries: &[(&str, Value)]| -> Res { - let values = cell(entries)?; - match hooks(&Cell::new(&values), "claude-code", ®istered()) { - Err(DriverError::InvalidValue { path, .. }) => Ok(path.to_string()), + let refused = |hooks_value: Value| -> Res { + let values = cell(&[("hooks", hooks_value)])?; + match hooks(&Cell::new(&values), "claude-code") { + Err(DriverError::InvalidValue { path, detail }) => { + assert_eq!(path.to_string(), "hooks"); + Ok(detail) + } other => Err(format!("expected an invalid value, got {other:?}").into()), } }; - assert_eq!( - refused(&[("hooks.claude_code.plugins", json!([]))])?, - "hooks.claude_code.plugins" - ); - assert_eq!( - refused(&[("hooks.claude_code.settings", json!("[1]"))])?, - "hooks.claude_code.settings" - ); - assert_eq!( - refused(&[("hooks.claude_code.settings", json!("not json"))])?, - "hooks.claude_code.settings" - ); - assert_eq!( - refused(&[( - "hooks.claude_code.files", - json!([{"path": "a", "text": "x"}, {"path": "a", "text": "y"}]) - )])?, - "hooks.claude_code.files" - ); + let unknown = refused(json!({"claude-code": {"plugins": {}}}))?; + assert!(unknown.contains("plugins"), "{unknown}"); + let settings = refused(json!({"claude-code": {"settings": "[1]"}}))?; + assert!(settings.contains("settings"), "{settings}"); + let path = refused(json!({"claude-code": {"files": {"../a": "x"}}}))?; + assert!(path.contains("../a"), "{path}"); Ok(()) } diff --git a/crates/candler/src/commands/resolve.rs b/crates/candler/src/commands/resolve.rs index 10995e85..d1b3f6f0 100644 --- a/crates/candler/src/commands/resolve.rs +++ b/crates/candler/src/commands/resolve.rs @@ -309,13 +309,7 @@ pub async fn run(args: Args, store: Option<&Path>) -> Result { let Some(resolution) = levels.first().cloned() else { return Ok(Exit::Success); }; - check_cells( - &file, - levels.as_slice(), - driver.as_ref(), - Registry::builtin().names().as_slice(), - ) - .map_err(CliError::refused_by)?; // BORROW: explicit .as_slice() + check_cells(&file, levels.as_slice(), driver.as_ref()).map_err(CliError::refused_by)?; // BORROW: explicit .as_slice() if text { for line in render_values(&resolution, Paint::detect()) { writeln!(stdout, "{line}").map_err(failed_here)?; diff --git a/crates/candler/src/commands/run.rs b/crates/candler/src/commands/run.rs index 1cfb4069..3251c118 100644 --- a/crates/candler/src/commands/run.rs +++ b/crates/candler/src/commands/run.rs @@ -271,7 +271,6 @@ fn plan_job( experiment_lock: store.layout().experiment_lock(&experiment), secrets_present: EnvSecrets::new(file.secrets()).present(), driver: Some(driver), - harnesses: Registry::builtin().names(), }; let mode = if force { Force::Yes } else { Force::No }; let outcome = plan_runs(&ctx, file, levels.as_slice(), mode, PlanMode::Check) // BORROW: explicit .as_slice() diff --git a/crates/candler/src/commands/supervise.rs b/crates/candler/src/commands/supervise.rs index 1400198b..5c5334b1 100644 --- a/crates/candler/src/commands/supervise.rs +++ b/crates/candler/src/commands/supervise.rs @@ -191,7 +191,6 @@ async fn run_job(store: Store, job: JobId, spec: JobSpec) -> Result = candler_harness::spec::HARNESS_IDS + .into_iter() + .map(str::to_owned) + .collect(); + listed.sort(); + assert_eq!(registered, listed); +} diff --git a/crates/candler/tests/it/guard_golden_design.rs b/crates/candler/tests/it/guard_golden_design.rs index 9f632f34..f90c6b01 100644 --- a/crates/candler/tests/it/guard_golden_design.rs +++ b/crates/candler/tests/it/guard_golden_design.rs @@ -148,7 +148,6 @@ fn gd_plan_twelve_cells() { experiment_lock: dir.path().join("experiments").join("x").join("lock"), secrets_present: BTreeSet::new(), driver: None, - harnesses: Vec::new(), }; let out = plan_runs( &ctx, diff --git a/crates/candler/tests/it/support/contract_pages/pages.rs b/crates/candler/tests/it/support/contract_pages/pages.rs index 5c2a9732..2ce3ecd5 100644 --- a/crates/candler/tests/it/support/contract_pages/pages.rs +++ b/crates/candler/tests/it/support/contract_pages/pages.rs @@ -69,7 +69,7 @@ pub const PAGES: [Page; 6] = [ file: "experiment-file.md", title: "Experiment file", writer: "experimenter", - surface: "The experiment file an experimenter writes to fix the values, factors, replicates, budget, harness and treatment of a set of runs; Candler reads it to plan and run the cells. Instruction texts and hooks are leaves of `[fixed]` or of a factor level: `instructions.global.`, `instructions.workspace`, `hooks..settings` (the text of a JSON object) and `hooks..files` or `hooks..plugins` (a list of `{path, text}`), with `_` where the harness id has `-`. A hook a consumer gives the agent may approve tool calls, which changes what `permission_mode` means for that cell.", + surface: "The experiment file an experimenter writes to fix the values, factors, replicates, budget, harness and treatment of a set of runs; Candler reads it to plan and run the cells. Instruction texts and hooks are tables whose keys are the harness's own words: `instructions.global` (harness id to text), `instructions.workspace` (a text), and `hooks` (harness id to `settings` and `files` for `claude-code`, or `plugins` for `opencode`), in `[fixed]` or as factor levels. A hook a consumer gives the agent may approve tool calls, which changes what `permission_mode` means for that cell.", roots: &["experiment"], helper: false, }, diff --git a/docs/contract/configuration-paths.md b/docs/contract/configuration-paths.md index 317c0b18..24ed6658 100644 --- a/docs/contract/configuration-paths.md +++ b/docs/contract/configuration-paths.md @@ -25,9 +25,9 @@ Core line: `v0.16.0`. | `tools.disallowed` | the path | experiment value | The tools the harness may not use. | tools disallowed: `permissions.deny` of `.claude/settings.json` | tools disallowed: a permission row {action, *, deny} per name, written after the allow rows | | `env` | the path | experiment value | The environment of the harness process: a table of variable name to text. | env: Candler: the core sets the cell's variables on the agent's process | env: Candler: the core sets the cell's variables on the agent's process | | `mcp` | the path and every path below it | experiment value | The MCP servers of a run; the names below are free. | MCP transport: stdio: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: local: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: http: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP transport: sse: an entry of `mcpServers` in `.mcp.json`, of type `sse`; MCP transport: remote: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP codemode: off: no key: Claude Code offers the server's tools directly; MCP codemode: on: no (Claude Code offers MCP tools directly; it has no code mode); MCP server name: the key of the server's `.mcp.json` entry | MCP transport: stdio: an `mcp` entry of type `local`; MCP transport: local: an `mcp` entry of type `local`; MCP transport: http: an `mcp` entry of type `remote`; MCP transport: sse: no (OpenCode documents no SSE transport; its `remote` is Streamable HTTP); MCP transport: remote: an `mcp` entry of type `remote`; MCP codemode: off: the `codemode` key of the `mcp` entry, `false`: the server's tools are direct tools; MCP codemode: on: the `codemode` key of the `mcp` entry, `true`: the server's tools are reached through `execute`, whose calls the trace records with empty `wrapped_calls`, so MCP calls made inside `execute` are not attributed and do not compare with Claude Code; MCP server name: the key of the `mcp` entry | -| `instructions.global` | the path and every path below it | experiment value | The global instruction text of each harness: a table of harness id (written with `_` for `-`) to text. | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | +| `instructions.global` | the path and every path below it | experiment value | The global instruction text of each harness: a table of harness id, as registered, to text; the keys are free. | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | | `instructions.workspace` | the path | experiment value | The instruction text at the root of the workspace. | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | -| `hooks` | the path and every path below it | experiment value | The hooks of each harness: a table of harness id (written with `_` for `-`) to its `settings` or `files`, or its `plugins`. | hooks: no (this driver installs no instruction text or hook) | hooks: no (this driver installs no instruction text or hook) | +| `hooks` | the path and every path below it | experiment value | The hooks of each harness: a table of harness id, as registered, to its `settings` table and `files` table (Claude Code) or its `plugins` table (OpenCode); the keys are free. | hooks: no (this driver installs no instruction text or hook) | hooks: no (this driver installs no instruction text or hook) | | `permission_mode` | the path | experiment value | The permission mode the harness runs in. | permission mode: default: `--permission-mode ` on the command line; permission mode: acceptEdits: `--permission-mode ` on the command line; permission mode: plan: `--permission-mode ` on the command line; permission mode: bypassPermissions: `--permission-mode ` on the command line; permission mode: auto: `--permission-mode ` on the command line; permission mode: dontAsk: `--permission-mode ` on the command line | permission mode: default: no (Claude Code's default mode allows reads and a built-in, non-configurable set of read-only shell commands that its own parser decides, and denies the rest in a headless run. OpenCode without `--auto` also rejects what no rule allows, but its shell rows are wildcards on the text of each parsed command, which approximate that set without being it); permission mode: acceptEdits: no (Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, rm, rmdir, mv, cp and sed, inside the working directory only. OpenCode's shell resource is the command's text, which knows no working directory, so "inside it" cannot be written as a rule); permission mode: plan: no (Claude Code's plan mode reads and runs read-only shell commands (a built-in, non-configurable set its own parser decides). The OpenCode ruleset that is certainly read-only (the `explore` agent's: deny everything, allow read, glob, grep, webfetch, websearch, skill) denies the shell altogether, and a wildcard on command text cannot express the read-only set; the stock `plan` agent is not read-only once a global rule follows it (the last match wins) and its `subagent` child can edit); permission mode: bypassPermissions: `--auto` on the command line: every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` answers the one pending ask (`.env` reads) with once, which a headless run needs; permission mode: auto: no (Claude Code's auto mode has a model classifier review each action, such as a shell command or a network request, before it runs. OpenCode has no classifier, and a ruleset decides by the action's text alone); permission mode: dontAsk: no (Claude Code's dontAsk mode denies every call that would prompt, so it allows the allow rules plus reads and the built-in, non-configurable set of read-only shell commands its own parser decides. OpenCode's shell rows are wildcards on the text of each parsed command, which approximate that set without being it) | | `request.harness` | the path | request key | The harness the run uses. | Candler only | Candler only | | `request.treatment` | the path | request key | The treatment the run applies. | Candler only | Candler only | diff --git a/docs/contract/experiment-file.md b/docs/contract/experiment-file.md index 1cc91e14..ba78cf3f 100644 --- a/docs/contract/experiment-file.md +++ b/docs/contract/experiment-file.md @@ -2,7 +2,7 @@ ## Surface -The experiment file an experimenter writes to fix the values, factors, replicates, budget, harness and treatment of a set of runs; Candler reads it to plan and run the cells. +The experiment file an experimenter writes to fix the values, factors, replicates, budget, harness and treatment of a set of runs; Candler reads it to plan and run the cells. Instruction texts and hooks are tables whose keys are the harness's own words: `instructions.global` (harness id to text), `instructions.workspace` (a text), and `hooks` (harness id to `settings` and `files` for `claude-code`, or `plugins` for `opencode`), in `[fixed]` or as factor levels. A hook a consumer gives the agent may approve tool calls, which changes what `permission_mode` means for that cell. ## Version From fca583ae793e5e1997fef4e9d7a64cb9f97221d6 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 15:44:47 +0900 Subject: [PATCH 24/69] rdm(api): mark the M6.5 trace context done Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/README.md | 4 ++-- __roadmap__/m6_5-agent-config/trace_context.md | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index 3ea53153..7dee3174 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -23,7 +23,7 @@ graph TD probe_harness_checks[Probe harness checks]:::done declaration[Declaration]:::inprogress installed[Installed]:::planned - trace_context[trace_context]:::inprogress + trace_context[trace_context]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -37,7 +37,7 @@ graph TD | `probe_harness_checks.md` | 📄 Leaf Task | ✅ Done | | `declaration.md` | 📄 Leaf Task | 🔄 In Progress | | `installed/` | 📁 Directory | ⬜ Planned | -| `trace_context.md` | 📄 Leaf Task | 🔄 In Progress | +| `trace_context.md` | 📄 Leaf Task | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/m6_5-agent-config/trace_context.md b/__roadmap__/m6_5-agent-config/trace_context.md index 5723d3ae..d4544843 100644 --- a/__roadmap__/m6_5-agent-config/trace_context.md +++ b/__roadmap__/m6_5-agent-config/trace_context.md @@ -5,10 +5,10 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G12. In a run on Claude Code and in a run on OpenCode against the fake model, the session's first trace event is `context_start`, and its `system` equals the system text of the run's first request that offers tools, as the gateway logged it. On the base, there is no such event. -- ⬜ A trace written before the change still reads, and the schema's version bump is minor. -- ⬜ One reader of the gateway log serves both the census and `context_start`; no second reader exists. The trace contract page documents the event, and states the measured size of the gateway's log line on both harnesses. -- ⬜ The guards run in a pass that lists them as passed, not skipped. `docker ps -a` shows none of their containers afterwards. +- ✅ G12. In a run on Claude Code and in a run on OpenCode against the fake model, the session's first trace event is `context_start`, and its `system` equals the system text of the run's first request that offers tools, as the gateway logged it. On the base, there is no such event. +- ✅ A trace written before the change still reads, and the schema's version bump is minor. +- ✅ One reader of the gateway log serves both the census and `context_start`; no second reader exists. The trace contract page documents the event, and states the measured size of the gateway's log line on both harnesses. +- ✅ The guards run in a pass that lists them as passed, not skipped. `docker ps -a` shows none of their containers afterwards. **References**: [Architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) — §Live trace proof, invariant 8 and §Execution model; `crates/candler-schemas/src/trace.rs` (`KnownKind`); `crates/candler-core/src/isolation/gateway.rs` and its njs script; `crates/candler-core/tests/it/guard_census_gateway.rs` (the census reader of the gateway log) ## Step 1: Record the first request and emit the event From 16d0beab3442e66757e474c1c7885a5f8ce9f76d Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 15:50:53 +0900 Subject: [PATCH 25/69] feat(api): make every driver state its harness check Co-Authored-By: Claude Sonnet 5.5 --- .../tests/it/guard_declared_inputs.rs | 19 ++++ .../tests/it/guard_harness_facts.rs | 19 ++++ .../tests/it/support/job_orchestrate.rs | 38 ++++++++ .../tests/it/support/session_rig.rs | 19 ++++ .../candler-core/tests/it/support/wiring.rs | 19 ++++ .../candler-harness-claude-code/src/driver.rs | 16 +++- crates/candler-harness-opencode/src/driver.rs | 20 +++- crates/candler-harness/src/conformance.rs | 22 +++++ crates/candler-harness/src/driver.rs | 25 ++--- .../tests/it/conformance_shapes.rs | 91 +++++++++++++++++++ .../candler-harness/tests/it/support/mod.rs | 57 ++++++++++++ docs/contract/driver-traits.md | 6 +- 12 files changed, 326 insertions(+), 25 deletions(-) diff --git a/crates/candler-core/tests/it/guard_declared_inputs.rs b/crates/candler-core/tests/it/guard_declared_inputs.rs index 206658ce..e407f755 100644 --- a/crates/candler-core/tests/it/guard_declared_inputs.rs +++ b/crates/candler-core/tests/it/guard_declared_inputs.rs @@ -542,6 +542,25 @@ fn sha(bytes: &[u8]) -> String { struct Collecting(support::job_orchestrate::QuietDriver); impl HarnessDriver for Collecting { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } diff --git a/crates/candler-core/tests/it/guard_harness_facts.rs b/crates/candler-core/tests/it/guard_harness_facts.rs index ca826df6..6f78a380 100644 --- a/crates/candler-core/tests/it/guard_harness_facts.rs +++ b/crates/candler-core/tests/it/guard_harness_facts.rs @@ -90,6 +90,25 @@ impl FakeHarness { } impl HarnessDriver for FakeHarness { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } diff --git a/crates/candler-core/tests/it/support/job_orchestrate.rs b/crates/candler-core/tests/it/support/job_orchestrate.rs index 5ccfeec5..6d95064a 100644 --- a/crates/candler-core/tests/it/support/job_orchestrate.rs +++ b/crates/candler-core/tests/it/support/job_orchestrate.rs @@ -325,6 +325,25 @@ pub fn quiet_gateway() -> GatewayEnv { pub struct QuietDriver; impl HarnessDriver for QuietDriver { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } @@ -428,6 +447,25 @@ impl HarnessDriver for QuietDriver { pub struct ObservingDriver(pub QuietDriver); impl HarnessDriver for ObservingDriver { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } diff --git a/crates/candler-core/tests/it/support/session_rig.rs b/crates/candler-core/tests/it/support/session_rig.rs index e369f799..88f34b36 100644 --- a/crates/candler-core/tests/it/support/session_rig.rs +++ b/crates/candler-core/tests/it/support/session_rig.rs @@ -208,6 +208,25 @@ impl Driver { } impl HarnessDriver for Driver { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } diff --git a/crates/candler-core/tests/it/support/wiring.rs b/crates/candler-core/tests/it/support/wiring.rs index b7bff5df..4fd73454 100644 --- a/crates/candler-core/tests/it/support/wiring.rs +++ b/crates/candler-core/tests/it/support/wiring.rs @@ -112,6 +112,25 @@ pub const CONFIG_TEXT: &str = r#"{"providers":{"candler":{"settings":{"apiKey":"{env:CANDLER_GATEWAY_TOKEN}"}}}}"#; impl HarnessDriver for WiringDriver { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index 5dacc79c..5445d60e 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -10,9 +10,9 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ - AgentSetting, Answer, BaseImage, CLAUDE_CODE, Cell, CollectSpec, CommandSpec, DriverFact, - EffortLevel, GatewayEnv, HarnessId, Observed, PermissionMode, Prepared, ProcessExit, - SessionTracker, StopSignal, StopSpec, Workspace, + AgentSetting, Answer, BaseImage, CLAUDE_CODE, Cell, CheckVerdict, CollectSpec, CommandSpec, + DriverFact, EffortLevel, GatewayEnv, HarnessId, Observed, PermissionMode, Prepared, + ProcessExit, SessionTracker, StopSignal, StopSpec, Workspace, }; use candler_schemas::execution::paths; use candler_schemas::primitives::FieldPath; @@ -309,6 +309,16 @@ impl HarnessDriver for ClaudeCodeDriver { } } + fn config_check(&self, plan: &Plan) -> Option { + let _ = plan; + None + } + + fn read_config_check(&self, output: &[u8]) -> CheckVerdict { + let _ = output; + CheckVerdict::Clean + } + fn workspace_instruction_file(&self) -> &'static str { "CLAUDE.md" } diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index 4677d2d4..65cd88c2 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -11,9 +11,9 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ - Action, AgentSetting, Answer, BaseImage, Cell, CollectSpec, CommandSpec, DriverFact, - GatewayEnv, HarnessId, OPENCODE, Observed, Prepared, ProcessExit, StateKind, StatePath, - StopSignal, StopSpec, Workspace, + Action, AgentSetting, Answer, BaseImage, Cell, CheckVerdict, CollectSpec, CommandSpec, + DriverFact, GatewayEnv, HarnessId, OPENCODE, Observed, Prepared, ProcessExit, StateKind, + StatePath, StopSignal, StopSpec, Workspace, }; use candler_schemas::primitives::{RelPath, plain_arg}; use candler_schemas::raw::StreamName; @@ -184,6 +184,20 @@ impl HarnessDriver for OpenCodeDriver { } } + fn config_check(&self, plan: &Plan) -> Option { + let _ = plan; + None + } + + fn read_config_check(&self, output: &[u8]) -> CheckVerdict { + let _ = output; + CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } + fn gateway(&self) -> Option { Some(GatewayEnv::new( // BORROW: .to_owned() makes the owned names the spec keeps diff --git a/crates/candler-harness/src/conformance.rs b/crates/candler-harness/src/conformance.rs index 7fe0d667..a9c89b4b 100644 --- a/crates/candler-harness/src/conformance.rs +++ b/crates/candler-harness/src/conformance.rs @@ -685,6 +685,27 @@ fn check_answers( Ok(()) } +/// Checks that the driver's statement of [`DriverFact::ConfigCheck`] agrees with its +/// `config_check`: a refused fact has no command and a stated one has a command, so a driver +/// cannot claim a check that runs nothing. +fn check_config_check( + driver: &dyn HarnessDriver, // TRAIT_OBJECT: the suite checks any driver + plan: &Plan, +) -> Result<(), Failure> { + let stated = !driver.fact(DriverFact::ConfigCheck).is_refused(); + match (stated, driver.config_check(plan)) { + (false, Some(_)) => Err(driver_failure( + "config check", + "the fact ConfigCheck is refused and config_check returns a command".to_owned(), // BORROW: .to_owned() makes the owned text + )), + (true, None) => Err(driver_failure( + "config check", + "the fact ConfigCheck is stated and config_check returns no command".to_owned(), // BORROW: .to_owned() makes the owned text + )), + (false, None) | (true, Some(_)) => Ok(()), + } +} + /// Checks the capability rules and the session surface. fn check_capabilities( driver: &dyn HarnessDriver, // TRAIT_OBJECT: the suite checks any driver @@ -1304,6 +1325,7 @@ pub fn run( check_names(driver)?; check_answers(driver)?; let plan = driven("plan", driver.plan(setup.cell, setup.workspace))?; + check_config_check(driver, &plan)?; check_capabilities(driver, &plan, setup, cases, &owned)?; check_builds(driver, &plan, setup, &owned)?; for case in cases { diff --git a/crates/candler-harness/src/driver.rs b/crates/candler-harness/src/driver.rs index 597e8314..d5dfab68 100644 --- a/crates/candler-harness/src/driver.rs +++ b/crates/candler-harness/src/driver.rs @@ -172,24 +172,17 @@ pub trait HarnessDriver: Send + Sync { fn parse_version(&self, output: &[u8]) -> Result; /// The command that has the harness check the configuration files `plan` installs, run in the - /// cell's image without network. The default is `None`, for a harness with no check. - fn config_check(&self, plan: &Plan) -> Option { - let _ = plan; - None - } + /// cell's image without network, or `None` for a harness with no check. The answer agrees + /// with [`DriverFact::ConfigCheck`]: a driver that states the fact refused returns `None`, + /// and one that states it mapped returns a command. + fn config_check(&self, plan: &Plan) -> Option; - /// What the output of [`HarnessDriver::config_check`] says of the files. The default reads - /// every output as clean, for a harness with no check. - fn read_config_check(&self, output: &[u8]) -> CheckVerdict { - let _ = output; - CheckVerdict::Clean - } + /// What the output of [`HarnessDriver::config_check`] says of the files; a driver with no + /// check reads every output as clean. + fn read_config_check(&self, output: &[u8]) -> CheckVerdict; - /// The name of the file the harness reads at the root of the workspace as instructions. The - /// default is `AGENTS.md`, the name shared by the harnesses that have none of their own. - fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" - } + /// The name of the file the harness reads at the root of the workspace as instructions. + fn workspace_instruction_file(&self) -> &'static str; /// How the driver meets `setting`: what the harness does for it, what Candler does in its /// place, or why nobody does. Every key has an answer; there is no default. diff --git a/crates/candler-harness/tests/it/conformance_shapes.rs b/crates/candler-harness/tests/it/conformance_shapes.rs index 1dc6e64a..798f0bd5 100644 --- a/crates/candler-harness/tests/it/conformance_shapes.rs +++ b/crates/candler-harness/tests/it/conformance_shapes.rs @@ -455,6 +455,7 @@ struct Patched { host_collect: bool, state_override: Option>, gateway_override: Option, + config_fact: Option, } impl Patched { @@ -472,6 +473,7 @@ impl Patched { host_collect: false, state_override: None, gateway_override: None, + config_fact: None, } } } @@ -518,6 +520,25 @@ impl TraceReader for EagerCensus { } impl HarnessDriver for Patched { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } @@ -555,6 +576,11 @@ impl HarnessDriver for Patched { } fn fact(&self, fact: DriverFact) -> Answer { + if let Some(answer) = self.config_fact + && fact == DriverFact::ConfigCheck + { + return answer; + } self.inner.fact(fact) } fn gateway(&self) -> Option { @@ -679,6 +705,25 @@ struct Keeps { } impl HarnessDriver for Keeps { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } @@ -826,6 +871,17 @@ fn conformance_refuses_a_broken_driver() -> TestResult { "{message}" ); + // A harness check stated in the facts with no command behind it is refused. + let mut broken = Patched::new(); + broken.config_fact = Some(Answer::Mapped { + construct: "test stand-in", + }); + let message = refusal(&broken, &cases)?; + assert!( + message.contains("ConfigCheck is stated and config_check returns no command"), + "{message}" + ); + // A census capability with neither a census stream nor an init report is refused. let mut broken = Patched::new(); broken.census_stream_removed = true; @@ -1130,6 +1186,25 @@ fn conformance_refuses_a_broken_driver() -> TestResult { struct Silent(LinesDriver); impl HarnessDriver for Silent { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } @@ -1231,6 +1306,22 @@ fn conformance_session_surface_on_a_fake() -> TestResult { } struct Sessioned(Patched); impl HarnessDriver for Sessioned { + fn config_check( + &self, + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } diff --git a/crates/candler-harness/tests/it/support/mod.rs b/crates/candler-harness/tests/it/support/mod.rs index d65b2125..3a9e6414 100644 --- a/crates/candler-harness/tests/it/support/mod.rs +++ b/crates/candler-harness/tests/it/support/mod.rs @@ -218,6 +218,25 @@ impl TraceReader for LinesReader { pub struct LinesDriver; impl HarnessDriver for LinesDriver { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } @@ -468,6 +487,25 @@ impl TraceReader for DocumentReader { pub struct DocumentDriver; impl HarnessDriver for DocumentDriver { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } @@ -809,6 +847,25 @@ session.interrupt --param sessionID={session_id}"; pub struct OpenShapedDriver(pub DocumentDriver); impl HarnessDriver for OpenShapedDriver { + fn config_check( + &self, + + plan: &candler_harness::driver::Plan, + ) -> Option { + let _ = plan; + + None + } + + fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { + let _ = output; + + candler_harness::spec::CheckVerdict::Clean + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") } diff --git a/docs/contract/driver-traits.md b/docs/contract/driver-traits.md index 9beacd64..52f91d40 100644 --- a/docs/contract/driver-traits.md +++ b/docs/contract/driver-traits.md @@ -23,9 +23,9 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | `HarnessDriver::supported` | `(&self) -> semver::VersionReq` | required | - | | `HarnessDriver::version_probe` | `(&self) -> CommandSpec` | required | - | | `HarnessDriver::parse_version` | `(&self, output: &[u8]) -> Result` | required | - | -| `HarnessDriver::config_check` | `(&self, plan: &Plan) -> Option` | optional | `None` | -| `HarnessDriver::read_config_check` | `(&self, output: &[u8]) -> CheckVerdict` | optional | `CheckVerdict::Clean` | -| `HarnessDriver::workspace_instruction_file` | `(&self) -> &'static str` | optional | `"AGENTS.md"` | +| `HarnessDriver::config_check` | `(&self, plan: &Plan) -> Option` | required | - | +| `HarnessDriver::read_config_check` | `(&self, output: &[u8]) -> CheckVerdict` | required | - | +| `HarnessDriver::workspace_instruction_file` | `(&self) -> &'static str` | required | - | | `HarnessDriver::answer` | `(&self, setting: AgentSetting) -> Answer` | required | - | | `HarnessDriver::fact` | `(&self, fact: DriverFact) -> Answer` | required | - | | `HarnessDriver::plan` | `(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result` | required | - | From 446a223620893c5b99ba3df3c8809d3f3a8887a3 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 16:05:13 +0900 Subject: [PATCH 26/69] feat(schemas): hold the free-key fact in one list A bad key of a factor level is refused at the level's pointer again. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-schemas/src/agent_config.rs | 2 +- crates/candler-schemas/src/execution.rs | 61 +++++++++++++------ crates/candler-schemas/src/primitives.rs | 4 +- .../tests/it/guard_experiment_file.rs | 13 ++++ 4 files changed, 57 insertions(+), 23 deletions(-) diff --git a/crates/candler-schemas/src/agent_config.rs b/crates/candler-schemas/src/agent_config.rs index e7ce62c7..109e6e58 100644 --- a/crates/candler-schemas/src/agent_config.rs +++ b/crates/candler-schemas/src/agent_config.rs @@ -4,7 +4,7 @@ //! An experiment writes them as tables at `instructions.global` and `hooks`, in `[fixed]` or as //! factor levels, and the keys below those two paths are the harness's own words: a harness id //! such as `claude-code`, a hook event such as `SessionStart`, a file name such as `start.sh` -//! (see [`crate::execution::FREE_KEY_PATHS`]). The reader (`candler_harness::agent_config`) +//! (see [`crate::execution::TABLE_VALUED_PATHS`]). The reader (`candler_harness::agent_config`) //! reads the tables as the types of this module, each published as its own schema as //! `mcp-server` is, and refuses what does not fit them. diff --git a/crates/candler-schemas/src/execution.rs b/crates/candler-schemas/src/execution.rs index 23362b4d..74bac147 100644 --- a/crates/candler-schemas/src/execution.rs +++ b/crates/candler-schemas/src/execution.rs @@ -657,27 +657,27 @@ impl From for TreatmentSpec { } } -/// The paths whose values are tables kept whole: everything written at or below one reaches a cell as one object at that path, where any other table flattens into one value per leaf. -pub const TABLE_VALUED_PATHS: [&str; 3] = [ - paths::PROMPT_VALUES, - paths::HOOKS, - paths::INSTRUCTIONS_GLOBAL, +/// The paths whose values are tables kept whole, each with whether its keys are free: everything written at or below one reaches a cell as one object at that path, where any other table flattens into one value per leaf. A key below a path with free keys is the harness's own word (a harness id, a hook event, a file name), so the key rule of a field path does not apply to it. +pub const TABLE_VALUED_PATHS: [(&str, bool); 3] = [ + (paths::PROMPT_VALUES, false), + (paths::HOOKS, true), + (paths::INSTRUCTIONS_GLOBAL, true), ]; -/// The table-valued paths whose keys are free: a key below one is the harness's own word (a harness id, a hook event, a file name), so the key rule of a field path does not apply to it, and a table there reaches a cell whole. -pub const FREE_KEY_PATHS: [&str; 2] = [paths::HOOKS, paths::INSTRUCTIONS_GLOBAL]; - -/// Whether `path` is, or lies below, a path whose keys are free. -fn free_keys(path: &FieldPath) -> bool { - FREE_KEY_PATHS - .into_iter() - .any(|root| path.relative_to(root).is_some()) +/// Whether the path text `path` is, or lies below, a table-valued path whose keys are free. +fn free_keys(path: &str) -> bool { + TABLE_VALUED_PATHS.into_iter().any(|(root, free)| { + free && path + .strip_prefix(root) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('.')) + }) } /// The table-valued path that `path` is or lies below, if any. fn table_root(path: &FieldPath) -> Option<&'static str> { TABLE_VALUED_PATHS .into_iter() + .map(|(root, _)| root) .find(|root| path.relative_to(root).is_some()) } @@ -688,7 +688,7 @@ fn leaves_of( out: &mut Vec, ) -> Result<(), ExecutionError> { match value { - Value::Object(table) if table_root(path).is_some() && !free_keys(path) => { + Value::Object(table) if table_root(path).is_some() && !free_keys(path.as_str()) => { if table.is_empty() { return Err(ExecutionError::EmptyTable { path: path.to_string(), @@ -745,7 +745,7 @@ fn fold_tables( list: &'static str, ) -> Result, ExecutionError> { let mut values = values; - for root in TABLE_VALUED_PATHS { + for (root, _) in TABLE_VALUED_PATHS { let under: Vec<(usize, &ResolvedValue)> = values .iter() .enumerate() @@ -850,7 +850,7 @@ impl Level { /// A level that is a table whose leaves fill paths. /// /// The keys are read against the factor's path when the factor's cells are built: below a path - /// of [`FREE_KEY_PATHS`] they are free, anywhere else each must be a field path segment. + /// of [`TABLE_VALUED_PATHS`] with free keys they are free, anywhere else each must be a field path segment. /// /// # Errors /// Returns [`ExecutionError::EmptyTable`] if the table holds no value. @@ -884,6 +884,22 @@ impl Level { } } +/// A fault of a level's keys or values, as a fault of the document at the level's pointer; any +/// other error is returned as it is. +fn level_fault(error: ExecutionError, factor: usize, level: usize) -> ExecutionError { + if matches!( + error, + ExecutionError::Format(_) | ExecutionError::Values(_) | ExecutionError::Canonical(_) + ) { + ExecutionError::Document { + detail: error.to_string(), + path: format!("/factors/{factor}/levels/{level}"), + } + } else { + error + } +} + /// Collects the leaves of `table` as values at `base` followed by their keys. fn fill_leaves( table: &Map, @@ -895,7 +911,7 @@ fn fill_leaves( path: base.to_string(), }); } - if free_keys(base) { + if free_keys(base.as_str()) { // BORROW: .clone() gives the cell its own copy of the table let whole = JsonValue::new(Value::Object(table.clone()))?; // BORROW: .clone() gives the cell its own path @@ -1309,7 +1325,7 @@ impl ExperimentFile { let mut footprints: Vec> = vec![footprint( fixed.iter().map(|(path, value)| (path, value.as_value())), )?]; - for factor in &factors { + for (factor_at, factor) in factors.iter().enumerate() { if factor.levels.is_empty() { return Err(ExecutionError::NoLevels { // BORROW: .clone() keeps the factor's path in the error @@ -1319,7 +1335,12 @@ impl ExperimentFile { let filled = factor .levels .iter() - .map(|level| level.fills(&factor.path)) + .enumerate() + .map(|(at, level)| { + level + .fills(&factor.path) + .map_err(|error| level_fault(error, factor_at, at)) + }) .collect::, _>>()?; footprints.push(footprint(filled.iter().flatten().filter_map(|value| { value.value().map(|json| (value.path(), json.as_value())) @@ -1669,7 +1690,7 @@ fn flatten_into( if inner.is_empty() { return Err(ExecutionError::EmptyTable { path }); } - if FREE_KEY_PATHS.contains(&path.as_str()) { + if free_keys(path.as_str()) { // BORROW: explicit .as_str() instead of Deref coercion let json = toml_to_json(toml::Value::Table(inner), path.as_str())?; out.push((path, json)); diff --git a/crates/candler-schemas/src/primitives.rs b/crates/candler-schemas/src/primitives.rs index 601cbf3a..d5c2b212 100644 --- a/crates/candler-schemas/src/primitives.rs +++ b/crates/candler-schemas/src/primitives.rs @@ -1122,11 +1122,11 @@ impl Name { } } -/// A [`Name`] from a literal, which the compiler rejects when it is empty or holds `@`, white +/// A [`Name`] from a constant text, which the compiler rejects when it is empty or holds `@`, white /// space or a byte outside ASCII. The value cannot fail at run time. #[macro_export] macro_rules! name { - ($text:literal) => {{ + ($text:expr) => {{ const { assert!($crate::primitives::is_ascii_name($text)) }; $crate::primitives::Name::from_checked_literal($text) }}; diff --git a/crates/candler-schemas/tests/it/guard_experiment_file.rs b/crates/candler-schemas/tests/it/guard_experiment_file.rs index 8ccd5504..3bd23b22 100644 --- a/crates/candler-schemas/tests/it/guard_experiment_file.rs +++ b/crates/candler-schemas/tests/it/guard_experiment_file.rs @@ -363,3 +363,16 @@ fn free_key_tables_reach_the_cell_whole() { "a table elsewhere keeps the key rule" ); } + +/// Guards: a key of a factor level that breaks the key rule is refused as a fault of the document +/// at the level's own pointer, as a table elsewhere is, and the same key below `hooks` is not. +/// Oracle: the pointer is written by hand from the factor and level indices. +/// Bite: leave the pointer out of the refusal (the path is empty). +#[test] +fn a_level_key_that_breaks_the_rule_is_refused_at_the_level() { + let factors = "[[factors]]\npath = \"model.id\"\nlevels = [\"m\"]\n[[factors]]\npath = \"env\"\nlevels = [{Odd-Var = \"x\"}]\n"; + match ExperimentFile::from_toml_str(&with_tables("", factors)) { + Err(ExecutionError::Document { path, .. }) => assert_eq!(path, "/factors/1/levels/0"), + other => panic!("expected a document fault at the level, got {other:?}"), + } +} From 874fdf4fc706a0e2dd178089be45d270490c7281 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 16:09:20 +0900 Subject: [PATCH 27/69] feat(api): drop the harness-id scaffolding and forward the check Co-Authored-By: Claude Sonnet 5.5 --- .../tests/it/guard_agent_config.rs | 2 +- .../tests/it/guard_declared_inputs.rs | 11 ++----- .../tests/it/support/job_orchestrate.rs | 11 ++----- .../tests/it/support/session_rig.rs | 11 ++----- .../candler-core/tests/it/support/wiring.rs | 11 ++----- .../candler-harness-claude-code/src/driver.rs | 3 +- crates/candler-harness-opencode/src/driver.rs | 3 +- crates/candler-harness/src/refusal.rs | 9 ++---- crates/candler-harness/src/spec.rs | 11 ------- .../tests/it/conformance_shapes.rs | 30 ++++++------------- .../candler-harness/tests/it/support/mod.rs | 11 ++----- 11 files changed, 31 insertions(+), 82 deletions(-) diff --git a/crates/candler-core/tests/it/guard_agent_config.rs b/crates/candler-core/tests/it/guard_agent_config.rs index d6f143b5..a6ca6a2b 100644 --- a/crates/candler-core/tests/it/guard_agent_config.rs +++ b/crates/candler-core/tests/it/guard_agent_config.rs @@ -126,7 +126,7 @@ struct Case { /// Guards: a hooks table with no entry for the cell's harness is refused as /// `experiment.cell_value_missing` at `/fixed/hooks`, a global instruction table with none as the /// same code at `/fixed/instructions.global`, a key that names no registered harness as -/// `experiment.cell_value_invalid`, and a hook file path with `..` as the same code at the file list. +/// `experiment.cell_value_invalid`, and a hook file path with `..` as the same code at `/hooks`, naming the member. /// Oracle: the codes and pointers are written by hand from the surface. /// Bite: skip the reader at plan time (each cell plans). #[tokio::test] diff --git a/crates/candler-core/tests/it/guard_declared_inputs.rs b/crates/candler-core/tests/it/guard_declared_inputs.rs index e407f755..de64cc53 100644 --- a/crates/candler-core/tests/it/guard_declared_inputs.rs +++ b/crates/candler-core/tests/it/guard_declared_inputs.rs @@ -544,22 +544,17 @@ struct Collecting(support::job_orchestrate::QuietDriver); impl HarnessDriver for Collecting { fn config_check( &self, - plan: &candler_harness::driver::Plan, ) -> Option { - let _ = plan; - - None + self.0.config_check(plan) } fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { - let _ = output; - - candler_harness::spec::CheckVerdict::Clean + self.0.read_config_check(output) } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + self.0.workspace_instruction_file() } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") diff --git a/crates/candler-core/tests/it/support/job_orchestrate.rs b/crates/candler-core/tests/it/support/job_orchestrate.rs index 6d95064a..42048f67 100644 --- a/crates/candler-core/tests/it/support/job_orchestrate.rs +++ b/crates/candler-core/tests/it/support/job_orchestrate.rs @@ -449,22 +449,17 @@ pub struct ObservingDriver(pub QuietDriver); impl HarnessDriver for ObservingDriver { fn config_check( &self, - plan: &candler_harness::driver::Plan, ) -> Option { - let _ = plan; - - None + self.0.config_check(plan) } fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { - let _ = output; - - candler_harness::spec::CheckVerdict::Clean + self.0.read_config_check(output) } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + self.0.workspace_instruction_file() } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") diff --git a/crates/candler-core/tests/it/support/session_rig.rs b/crates/candler-core/tests/it/support/session_rig.rs index 88f34b36..64891540 100644 --- a/crates/candler-core/tests/it/support/session_rig.rs +++ b/crates/candler-core/tests/it/support/session_rig.rs @@ -210,22 +210,17 @@ impl Driver { impl HarnessDriver for Driver { fn config_check( &self, - plan: &candler_harness::driver::Plan, ) -> Option { - let _ = plan; - - None + self.inner.config_check(plan) } fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { - let _ = output; - - candler_harness::spec::CheckVerdict::Clean + self.inner.read_config_check(output) } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + self.inner.workspace_instruction_file() } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") diff --git a/crates/candler-core/tests/it/support/wiring.rs b/crates/candler-core/tests/it/support/wiring.rs index 4fd73454..7d7e49ac 100644 --- a/crates/candler-core/tests/it/support/wiring.rs +++ b/crates/candler-core/tests/it/support/wiring.rs @@ -114,22 +114,17 @@ pub const CONFIG_TEXT: &str = impl HarnessDriver for WiringDriver { fn config_check( &self, - plan: &candler_harness::driver::Plan, ) -> Option { - let _ = plan; - - None + self.0.config_check(plan) } fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { - let _ = output; - - candler_harness::spec::CheckVerdict::Clean + self.0.read_config_check(output) } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + self.0.workspace_instruction_file() } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index 5445d60e..cd0a68e7 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -15,6 +15,7 @@ use candler_harness::spec::{ ProcessExit, SessionTracker, StopSignal, StopSpec, Workspace, }; use candler_schemas::execution::paths; +use candler_schemas::name; use candler_schemas::primitives::FieldPath; use candler_schemas::raw::StreamName; use candler_schemas::servers::McpServerKind; @@ -146,7 +147,7 @@ impl ClaudeCodeDriver { #[must_use] pub fn new() -> Self { Self { - id: HarnessId::listed(CLAUDE_CODE), + id: HarnessId::new(name!(CLAUDE_CODE)), // BORROW: .to_owned() makes owned arguments probe: CommandSpec::new(PROGRAM.to_owned(), vec!["--version".to_owned()]), } diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index 65cd88c2..86c9e70c 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -15,6 +15,7 @@ use candler_harness::spec::{ DriverFact, GatewayEnv, HarnessId, OPENCODE, Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, StopSpec, Workspace, }; +use candler_schemas::name; use candler_schemas::primitives::{RelPath, plain_arg}; use candler_schemas::raw::StreamName; use candler_schemas::trace::{EndedBy, Session}; @@ -83,7 +84,7 @@ impl OpenCodeDriver { #[must_use] pub fn new() -> Self { Self { - id: HarnessId::listed(OPENCODE), + id: HarnessId::new(name!(OPENCODE)), probe: CommandSpec::new(PROGRAM.to_owned(), argv(&["--version"])), // BORROW: .to_owned() makes the owned program } } diff --git a/crates/candler-harness/src/refusal.rs b/crates/candler-harness/src/refusal.rs index 834e322e..1e36bf19 100644 --- a/crates/candler-harness/src/refusal.rs +++ b/crates/candler-harness/src/refusal.rs @@ -23,13 +23,8 @@ fn driver_error_path(error: &DriverError) -> Option { match error { DriverError::Command(inner) => Refusal::path(inner), DriverError::MissingValue { path } => { - // A cap lives under `/budget`, every other value is a key of `[fixed]` (or a factor). - if path.segments().next() == Some("budget") { - Some(pointer_of(path.segments())) - } else { - let text = path.to_string(); // BORROW: .to_string() gives owned text - Some(pointer_of(["fixed", text.as_str()])) // BORROW: explicit .as_str() instead of Deref coercion - } + let text = path.to_string(); // BORROW: .to_string() gives owned text + Some(pointer_of(["fixed", text.as_str()])) // BORROW: explicit .as_str() instead of Deref coercion } DriverError::Unsupported { path, .. } | DriverError::HarnessRejectedInput { path, .. } diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index b010b766..e7eb1657 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -1232,11 +1232,6 @@ pub const OPENCODE: &str = "opencode"; /// and the keys below a cell's `hooks` and `instructions.global` are checked against them. pub const HARNESS_IDS: [&str; 2] = [CLAUDE_CODE, OPENCODE]; -const _: () = { - assert!(candler_schemas::primitives::is_ascii_name(CLAUDE_CODE)); - assert!(candler_schemas::primitives::is_ascii_name(OPENCODE)); -}; - /// The identity of a harness: its plain name, the value `comparable.harness.name` and the experiment's harness request hold. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] @@ -1249,12 +1244,6 @@ impl HarnessId { Self(name) } - /// The id of the built-in harness `id`, one of [`HARNESS_IDS`], whose text is a valid name. - #[must_use] - pub fn listed(id: &'static str) -> Self { - Self(Name::from_checked_literal(id)) - } - /// The harness name. #[must_use] pub const fn as_name<'a>(&'a self) -> &'a Name { diff --git a/crates/candler-harness/tests/it/conformance_shapes.rs b/crates/candler-harness/tests/it/conformance_shapes.rs index 798f0bd5..5d5b2e4f 100644 --- a/crates/candler-harness/tests/it/conformance_shapes.rs +++ b/crates/candler-harness/tests/it/conformance_shapes.rs @@ -522,22 +522,17 @@ impl TraceReader for EagerCensus { impl HarnessDriver for Patched { fn config_check( &self, - plan: &candler_harness::driver::Plan, ) -> Option { - let _ = plan; - - None + self.inner.config_check(plan) } fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { - let _ = output; - - candler_harness::spec::CheckVerdict::Clean + self.inner.read_config_check(output) } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + self.inner.workspace_instruction_file() } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") @@ -1188,22 +1183,17 @@ struct Silent(LinesDriver); impl HarnessDriver for Silent { fn config_check( &self, - plan: &candler_harness::driver::Plan, ) -> Option { - let _ = plan; - - None + self.0.config_check(plan) } fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { - let _ = output; - - candler_harness::spec::CheckVerdict::Clean + self.0.read_config_check(output) } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + self.0.workspace_instruction_file() } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") @@ -1310,17 +1300,15 @@ fn conformance_session_surface_on_a_fake() -> TestResult { &self, plan: &candler_harness::driver::Plan, ) -> Option { - let _ = plan; - None + self.0.config_check(plan) } fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { - let _ = output; - candler_harness::spec::CheckVerdict::Clean + self.0.read_config_check(output) } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + self.0.workspace_instruction_file() } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") diff --git a/crates/candler-harness/tests/it/support/mod.rs b/crates/candler-harness/tests/it/support/mod.rs index 3a9e6414..b30a03f0 100644 --- a/crates/candler-harness/tests/it/support/mod.rs +++ b/crates/candler-harness/tests/it/support/mod.rs @@ -849,22 +849,17 @@ pub struct OpenShapedDriver(pub DocumentDriver); impl HarnessDriver for OpenShapedDriver { fn config_check( &self, - plan: &candler_harness::driver::Plan, ) -> Option { - let _ = plan; - - None + self.0.config_check(plan) } fn read_config_check(&self, output: &[u8]) -> candler_harness::spec::CheckVerdict { - let _ = output; - - candler_harness::spec::CheckVerdict::Clean + self.0.read_config_check(output) } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + self.0.workspace_instruction_file() } fn skills(&self) -> candler_harness::skills::SkillTree { candler_harness::skills::SkillTree::new(".claude/skills", ".claude/skills") From f929c3cc41147cf954da71273ead7af617dadb7c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 16:19:09 +0900 Subject: [PATCH 28/69] feat(schemas): one document fault for a bad level and a bad file An empty table inside a level is refused at the level's pointer again. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-schemas/src/execution.rs | 40 ++++++++++--------- .../tests/it/guard_experiment_file.rs | 35 +++++++++++----- 2 files changed, 47 insertions(+), 28 deletions(-) diff --git a/crates/candler-schemas/src/execution.rs b/crates/candler-schemas/src/execution.rs index 74bac147..95017766 100644 --- a/crates/candler-schemas/src/execution.rs +++ b/crates/candler-schemas/src/execution.rs @@ -884,17 +884,27 @@ impl Level { } } -/// A fault of a level's keys or values, as a fault of the document at the level's pointer; any -/// other error is returned as it is. -fn level_fault(error: ExecutionError, factor: usize, level: usize) -> ExecutionError { - if matches!( +/// Whether `error` is a fault of a document's shape: a format, value or canonical fault. +fn is_shape_fault(error: &ExecutionError) -> bool { + matches!( error, ExecutionError::Format(_) | ExecutionError::Values(_) | ExecutionError::Canonical(_) - ) { - ExecutionError::Document { - detail: error.to_string(), - path: format!("/factors/{factor}/levels/{level}"), - } + ) +} + +/// `error` as a fault of the document at the pointer `path`. +fn document_fault(error: &ExecutionError, path: String) -> ExecutionError { + ExecutionError::Document { + detail: error.to_string(), + path, + } +} + +/// A fault of a level's keys or values, or an empty table in it, as a fault of the document at +/// the level's pointer; any other error is returned as it is. +fn level_fault(error: ExecutionError, factor: usize, level: usize) -> ExecutionError { + if is_shape_fault(&error) || matches!(error, ExecutionError::EmptyTable { .. }) { + document_fault(&error, format!("/factors/{factor}/levels/{level}")) } else { error } @@ -1442,16 +1452,8 @@ impl ExperimentFile { })?; Self::try_from(MapOnly(raw)).map_err(|error| { // A format, value or canonical fault is a fault of the document's shape. - if matches!( - error, - ExecutionError::Format(_) - | ExecutionError::Values(_) - | ExecutionError::Canonical(_) - ) { - ExecutionError::Document { - detail: error.to_string(), - path: String::new(), - } + if is_shape_fault(&error) { + document_fault(&error, String::new()) } else { error } diff --git a/crates/candler-schemas/tests/it/guard_experiment_file.rs b/crates/candler-schemas/tests/it/guard_experiment_file.rs index 3bd23b22..83e4455f 100644 --- a/crates/candler-schemas/tests/it/guard_experiment_file.rs +++ b/crates/candler-schemas/tests/it/guard_experiment_file.rs @@ -364,15 +364,32 @@ fn free_key_tables_reach_the_cell_whole() { ); } -/// Guards: a key of a factor level that breaks the key rule is refused as a fault of the document -/// at the level's own pointer, as a table elsewhere is, and the same key below `hooks` is not. -/// Oracle: the pointer is written by hand from the factor and level indices. -/// Bite: leave the pointer out of the refusal (the path is empty). +/// Guards: a key of a factor level that breaks the key rule, and an empty table inside a level, +/// are refused as faults of the document at the level's own pointer, and the same key below +/// `hooks` is not refused. +/// Oracle: the pointers are written by hand from the factor and level indices. +/// Bite: leave the pointer out of the refusal (the path is empty), or apply the key rule below +/// `hooks`. #[test] fn a_level_key_that_breaks_the_rule_is_refused_at_the_level() { - let factors = "[[factors]]\npath = \"model.id\"\nlevels = [\"m\"]\n[[factors]]\npath = \"env\"\nlevels = [{Odd-Var = \"x\"}]\n"; - match ExperimentFile::from_toml_str(&with_tables("", factors)) { - Err(ExecutionError::Document { path, .. }) => assert_eq!(path, "/factors/1/levels/0"), - other => panic!("expected a document fault at the level, got {other:?}"), - } + let refused = |level: &str| { + let factors = format!( + "[[factors]]\npath = \"model.id\"\nlevels = [\"m\"]\n[[factors]]\npath = \"env\"\nlevels = [{level}]\n" + ); + match ExperimentFile::from_toml_str(&with_tables("", &factors)) { + Err(ExecutionError::Document { path, .. }) => path, + other => panic!("expected a document fault at the level, got {other:?}"), + } + }; + assert_eq!(refused("{Odd-Var = \"x\"}"), "/factors/1/levels/0"); + assert_eq!(refused("{x = {}}"), "/factors/1/levels/0"); + + let free = with_tables( + "", + "[[factors]]\npath = \"hooks\"\nlevels = [{Odd-Key = {Event = \"x\"}}]\n", + ); + assert!( + ExperimentFile::from_toml_str(&free).is_ok(), + "the same key below hooks is free" + ); } From 9e007aa76c7269422ee334319f6b48765970a0e4 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 16:31:40 +0900 Subject: [PATCH 29/69] reports(api): file the M6.5 level 1 observations Eight findings that lie outside the level 1 leaves, each written for a cold start. Co-Authored-By: Claude Opus 5.5 --- .../04-observation_level1_out_of_scope_v0.md | 122 ++++++++++++++++++ __reports__/agent_config/README.md | 3 + 2 files changed, 125 insertions(+) create mode 100644 __reports__/agent_config/04-observation_level1_out_of_scope_v0.md diff --git a/__reports__/agent_config/04-observation_level1_out_of_scope_v0.md b/__reports__/agent_config/04-observation_level1_out_of_scope_v0.md new file mode 100644 index 00000000..4c1a1c6a --- /dev/null +++ b/__reports__/agent_config/04-observation_level1_out_of_scope_v0.md @@ -0,0 +1,122 @@ +# Level 1 of M6.5: what was found outside its scope (v0) + +Date: 2026-11-25 + +Eight findings from M6.5's level 1 leaves (the probe, `declaration`, `trace_context`) and from their verifiers. Each one lies outside the leaf that found it, so no leaf fixed it. Each section below is one observation, written so that a fresh agent can pick it up cold. The front matter is shared, and the urgency differs per item. + +--- +type: observation +topic: agent_config +spotted-during: implementing and verifying the M6.5 level 1 leaves (probe_harness_checks, declaration, trace_context) +date: 2026-11-25 +domain: code +confidence: confirmed (O1–O5, O7); plausible (O6, O8) +urgency: per item, below +deferred-because: each lies outside the topic of the leaf that met it; the leaf rules forbid fixing it there +--- + +## Summary + +| # | Observation | Urgency | Where | +|---|---|---|---| +| O1 | Every gateway run's log read is capped at 4 MiB | medium | `read_since`, `OUTPUT_LIMIT` | +| O2 | Images are built after an inspect, with no lock, in the fake-model path and in the test helper | medium | `fake_image`, `test_image_as` | +| O3 | Commit `514c7db1` does not build alone | low | history of `feat/m6.5-agent-config` | +| O4 | OpenCode's own check does not see unknown config keys | medium | the probe, E-table | +| O5 | `mcp.servers` names must match the key rule | low (notice) | `CONFIGURATION_PATHS`, `McpServer.name` | +| O6 | A timing guard fails under load | low | `guard_container_stop` | +| O7 | `candler-gateway:latest` is left on the machine, and no code uses it | low | local Docker images | +| O8 | A run's child is sometimes not identified for signalling | medium | `supervise/spawn.rs` | + +## O1. The gateway log read is capped at 4 MiB for every run + +**What was noticed.** The core reads the sidecar's `docker logs` through `read_since`, capped at `OUTPUT_LIMIT` (4 MiB). The census used to read that log on OpenCode only. Since `trace_context`, every gateway run on both harnesses reads it for `context_start`. One context line measured 15,500 B on Claude Code and 8,943 B on OpenCode, so a long session with many requests nears the cap. Past it, the earliest lines may be the ones dropped, and those are the ones `context_start` needs. + +**Location map.** +- `crates/candler-core/src/isolation/gateway.rs` (`census_of`, the reader) +- the `read_since` / `OUTPUT_LIMIT` definition, reached from `census_of` +- `docs/contract/trace-file.md` (the measured line sizes) + +**Hand-off questions.** +- Does `read_since` keep the head or the tail when it truncates? +- What log size does a 200-turn session reach? +- Working theory, if any: record the context once in its own stream, or stream the log instead of buffering it. + +**Scope boundary.** Do not change the `context_start` event or its schema. + +## O2. Images are built after an inspect, with no lock + +**What was noticed.** `fake_image` (`crates/candler-core/src/jobs/orchestrate/controls.rs`) and the test helper `test_image_as` (`crates/candler-core/tests/it/support/test_image.rs`) inspect a tag and then build it, with no lock between the two. When two tests in one nextest invocation build the same tag, one of them fails. `ensure_base` (`crates/candler-core/src/isolation/image.rs`) takes `lock_tag(&tag)` first and does not race. The race predates M6.5: `git log -S"Built::Found"` gives 1c009bee, and `git log -S"async fn fake_image"` gives dd4f3308. + +**Re-observation.** Run `controls_e2e` and the `trace_context` guards in one `cargo nextest run --run-ignored all` invocation. + +**Hand-off questions.** +- Can both sites reuse `lock_tag`? +- Is the production `fake_image` reached concurrently in real use, or only in tests? + +**Scope boundary.** Do not change image tagging (`sidecar_tag`, `base_tag`). + +## O3. Commit `514c7db1` does not build alone + +**What was noticed.** `514c7db1 feat(schemas): show the instructions and hooks of an inspected run` fails `cargo check --workspace --all-targets` with E0063: the fields `hooks` and `instructions` are missing in `InspectRun` at `crates/candler/src/commands/inspect.rs:278`. The next commit, `ea23a16e`, builds. History is never rewritten here, so the hazard stays, and `git bisect` must skip this commit. + +**Hand-off questions.** +- Should the commit rules (AGENTS.md) require a schema commit's consumers to compile at that commit? Such a commit may touch only `candler-schemas`. + +**Scope boundary.** Do not rewrite history. + +## O4. OpenCode's own check does not see unknown config keys + +**What was noticed.** The probe ran `opencode run --standalone --print-logs -m probe/none x`. It warns on bad values, but it says nothing about a key it does not know. So the harness check that L2 adds for OpenCode refuses errors and warnings, but lets a misspelled key through silently. Claude Code's `claude doctor` reports `Invalid settings`. + +**Location map.** `__reports__/agent_config/03-findings_probe_harness_checks_v0.md`, the evidence table. + +**Hand-off questions.** +- Does OpenCode publish its config schema, so Candler could validate against it? +- Is that worth doing, or is it OpenCode's defect to report upstream? + +**Scope boundary.** Do not change `preflight_check`'s refusal rule (errors and warnings). + +## O5. `mcp.servers` names must match the key rule (notice) + +**What was noticed.** `hooks` and `instructions.global` now take free keys on the experiment surface. `mcp.servers` still does not, so a server cannot be named `my-server`; this is why `McpServer` carries a `name` leaf. The free-key flag on `TABLE_VALUED_PATHS` (`crates/candler-schemas/src/execution.rs`) would lift the limit. + +**Hand-off questions.** +- Does any consumer want hyphenated server names? +- Would the change alter the digest of existing experiments? (There are no external users.) + +**Scope boundary.** Do not touch `hooks` or `instructions`. + +## O6. A timing guard fails under load + +**What was noticed.** `guard_container_stop::stop_asks_the_daemon_and_falls_back_to_the_client` failed once in a full workspace run on a loaded machine (257 s) and passed alone. A c1 timing assertion in `controls_e2e` also failed once under the same load. + +**Hand-off questions.** +- Which deadline does each test assert? +- Is that deadline wall-clock where it should be relative? + +**Scope boundary.** Observation only; no fix is scoped. + +## O7. `candler-gateway:latest` is left on the machine + +**What was noticed.** The gateway sidecar is now tagged `candler-gateway:src-<12 digits>`, from its build context. The local image `candler-gateway:latest` (`17f734223887`, created 2026-11-17, by an earlier milestone) is used by no code. M6.5 did not create it, so it did not delete it. + +**Hand-off questions.** +- Does Eliott want it removed? + +**Scope boundary.** Never prune Docker. Remove this one image by name only on Eliott's word. + +## O8. A run's child is sometimes not identified for signalling + +**What was noticed.** On the merged L1 tip, in a full workspace run, `guard_known_truth::kt_two_levels_end_to_end` failed once. Of its 48 runs, 47 ran; run `246ad5d5…-r2-a1` failed with "cannot read the start time of the child: the child could not be identified for signalling". The test passed three times alone, and the next full run passed 743 of 743. No M6.5 leaf touches the file that raises the error. + +**Location map.** +- `crates/candler-core/src/supervise/spawn.rs` (the error text) +- `crates/candler-core/tests/it/guard_known_truth.rs:594` (the assertion) + +**Hand-off questions.** +- Does the supervisor read the child's start time after the child may already have exited? +- Is the failure a lost run in real use, or only in tests? +- Working theory, if any: a race between a fast child exit and the start-time read, under load. + +**Scope boundary.** Do not change the known-truth guards' statistics. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 9dcd157e..5428fe20 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -18,6 +18,9 @@ Instruction files and hooks as per-arm experiment data (M6.5). ### Round 03 - [03-findings_probe_harness_checks_v0.md](03-findings_probe_harness_checks_v0.md) — **latest**. The level-1 probe, measured in the real images: the check command for each harness, where Claude Code's global file loads, the order and place (system or first message) in which instructions and session-start hooks reach the model. Two points amend v2's proof wording. +### Round 04 +- [04-observation_level1_out_of_scope_v0.md](04-observation_level1_out_of_scope_v0.md) — **latest**. Eight findings from level 1 that lie outside its leaves: the 4 MiB gateway log read, an unlocked image build, a commit that does not build alone, OpenCode's silence on unknown keys, `mcp.servers` names, a timing guard, an unused image, a child not identified for signalling. + ## Status The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended on 2026-11-25 for two instruction scopes (v1), then for a live, trace-read proof (v2). Level 1 is dispatched, and the probe is done. From 971c2e50aebaef9df4d5e9815231cd2d6ee4eeed Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 16:31:40 +0900 Subject: [PATCH 30/69] rdm(api): mark the M6.5 declaration done Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/README.md | 4 ++-- __roadmap__/m6_5-agent-config/declaration.md | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index 7dee3174..c219450a 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -21,7 +21,7 @@ A consumer gives the experiment a global instruction file per harness, each arm ```mermaid graph TD probe_harness_checks[Probe harness checks]:::done - declaration[Declaration]:::inprogress + declaration[Declaration]:::done installed[Installed]:::planned trace_context[trace_context]:::done classDef done fill:#166534,color:#bbf7d0 @@ -35,7 +35,7 @@ graph TD | Node | Type | Status | |:-----|:-----|:-------| | `probe_harness_checks.md` | 📄 Leaf Task | ✅ Done | -| `declaration.md` | 📄 Leaf Task | 🔄 In Progress | +| `declaration.md` | 📄 Leaf Task | ✅ Done | | `installed/` | 📁 Directory | ⬜ Planned | | `trace_context.md` | 📄 Leaf Task | ✅ Done | diff --git a/__roadmap__/m6_5-agent-config/declaration.md b/__roadmap__/m6_5-agent-config/declaration.md index f81b50ce..f92877cb 100644 --- a/__roadmap__/m6_5-agent-config/declaration.md +++ b/__roadmap__/m6_5-agent-config/declaration.md @@ -5,12 +5,12 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G1 (this level's half). `candler resolve` of an experiment with `[fixed] instructions.workspace = "…"` is refused by name, with `experiment.setting_unsupported` at `/fixed/instructions.workspace`, since both drivers answer `Refused`. The `inspect` of a run shows `instructions` and `hooks` members. On `8d82f63b` the resolve exits 2 with `experiment.unknown_path` at that path. The end-to-end half, a resolve that succeeds and an `inspect` that shows the values, is gated in `installed/proved/e2e_guard.md`. -- ⬜ G2. Two levels of `instructions.workspace` plan two cells with different digests, and two levels of `hooks.claude-code.settings` do the same. On the base, both are `unknown_path`. -- ⬜ G8. `hooks.claude-code` on an OpenCode cell that has no `hooks.opencode` is refused with `experiment.cell_value_missing` at `/fixed/hooks`, and `instructions.global` with no key for the cell's harness at `/fixed/instructions.global`. A key under `hooks` or `instructions.global` that names no registered harness is refused with `experiment.cell_value_invalid` at its path. A hook file path with `..` is refused with `experiment.cell_value_invalid` at its path, naming the path's own fault. On the base, all three are `unknown_path`. -- ⬜ G3 (this level's half). `docs/contract/harness-capabilities.md` has the rows *instructions: global*, *instructions: workspace*, *hooks* and *config check*. Both drivers answer each with `no (…)` saying why, and `cargo nextest run -p candler contract_pages` passes. On the base, no such rows exist. -- ⬜ `experiment.harness_rejected_input` and `experiment.instructions_collide` are declared in `docs/contract/codes.toml` with their side (experiment) and their path. No code path raises them yet. -- ⬜ `Plan` has a field for read-only workspace files, and the trait names each driver's workspace instruction file (`CLAUDE.md`, `AGENTS.md`). Both drivers leave the field empty, so no run changes. +- ✅ G1 (this level's half). `candler resolve` of an experiment with `[fixed] instructions.workspace = "…"` is refused by name, with `experiment.setting_unsupported` at `/fixed/instructions.workspace`, since both drivers answer `Refused`. The `inspect` of a run shows `instructions` and `hooks` members. On `8d82f63b` the resolve exits 2 with `experiment.unknown_path` at that path. The end-to-end half, a resolve that succeeds and an `inspect` that shows the values, is gated in `installed/proved/e2e_guard.md`. +- ✅ G2. Two levels of `instructions.workspace` plan two cells with different digests, and two levels of `hooks.claude-code.settings` do the same. On the base, both are `unknown_path`. +- ✅ G8. `hooks.claude-code` on an OpenCode cell that has no `hooks.opencode` is refused with `experiment.cell_value_missing` at `/fixed/hooks`, and `instructions.global` with no key for the cell's harness at `/fixed/instructions.global`. A key under `hooks` or `instructions.global` that names no registered harness is refused with `experiment.cell_value_invalid` at its path. A hook file path with `..` is refused with `experiment.cell_value_invalid` at its path, naming the path's own fault. On the base, all three are `unknown_path`. +- ✅ G3 (this level's half). `docs/contract/harness-capabilities.md` has the rows *instructions: global*, *instructions: workspace*, *hooks* and *config check*. Both drivers answer each with `no (…)` saying why, and `cargo nextest run -p candler contract_pages` passes. On the base, no such rows exist. +- ✅ `experiment.harness_rejected_input` and `experiment.instructions_collide` are declared in `docs/contract/codes.toml` with their side (experiment) and their path. No code path raises them yet. +- ✅ `Plan` has a field for read-only workspace files, and the trait names each driver's workspace instruction file (`CLAUDE.md`, `AGENTS.md`). Both drivers leave the field empty, so no run changes. **References**: [Architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-schemas/src/servers.rs` (`McpServer`, the precedent); `crates/candler-harness/src/spec.rs:651` (`AgentSetting`) and `:729` (`DriverFact`); `crates/candler-core/src/resolve/paths.rs` (`CONFIGURATION_PATHS`, `settings_set_by`); `crates/candler/src/commands/inspect.rs` (`mcp_of`); `crates/candler/tests/it/guard_inspect_mcp_config.rs` ## Step 1: Surface, schema and one reader From 002ba02768affd3b2cdb51a4b5720c303a646ec4 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 16:34:07 +0900 Subject: [PATCH 31/69] rdm(api): name the later M6.5 reports by the next free round Round 04 now holds the level 1 observations, so the live findings, the review and the knowledge transfer take the next free round. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md | 6 +++--- .../installed/proved/reviewed/adversarial_review.md | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md index 5fe75c0e..b1f91e38 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md @@ -12,7 +12,7 @@ - ⬜ G9. No installed file, the root instruction file included, is among any run's collected outputs, and no run is sealed `input_leak`. - ⬜ G1 (end to end). `candler resolve` of the guard's experiment succeeds, and the `inspect` of one of its runs shows `instructions` and `hooks` with the arm's values. - ⬜ G11. From the trace: on each harness, the session-start hook's marker is in `context_start`: in `first_message` on Claude Code, in `system` on OpenCode, as the probe measured. On the base, there is no such event. -- ⬜ G13. Live on RiVault (Reasoning-Small): one experiment on both harnesses, two arms, one replicate each, shows G4 and G11 in its stored traces, and `__reports__/agent_config/04-findings_live_confirmation_v0.md` quotes the trace excerpts. +- ⬜ G13. Live on RiVault (Reasoning-Small): one experiment on both harnesses, two arms, one replicate each, shows G4 and G11 in its stored traces, and `__reports__/agent_config/-findings_live_confirmation_v0.md` quotes the trace excerpts, where `` is the next free round. - ⬜ The guards run in a pass that lists them as passed, not skipped (leaf template, convention 3). `docker ps -a` shows none of their containers afterwards. **References**: [Architecture report, v2](../../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs` (`parity_one_installed_server_one_traced_call`, the model to follow); `assets/docker/fakemodel` @@ -28,6 +28,6 @@ **Goal**: The same proof on a real model. **Implementation Logic**: Run the guard's experiment once with `candler run` against RiVault's Reasoning-Small, which tests reachability, not scores, on both harnesses with two arms and one replicate each. Read G4 and G11 from the stored traces with the same reader the guard uses. Quote the `context_start` excerpts that show each text and the marker. No product code changes in this step. -**Deliverables**: `__reports__/agent_config/04-findings_live_confirmation_v0.md`, written with `writing-reports`, type findings -**Consistency Checks**: `test -s __reports__/agent_config/04-findings_live_confirmation_v0.md` (expected: PASS) +**Deliverables**: `__reports__/agent_config/-findings_live_confirmation_v0.md` at the next free round, written with `writing-reports`, type findings +**Consistency Checks**: `ls -s __reports__/agent_config/*-findings_live_confirmation_v0.md` lists one non-empty file (expected: PASS) **Commit**: `reports(api): confirm instructions and hooks live from the trace` diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md index 8a65d1f2..e8ad8113 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md @@ -5,9 +5,9 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ `__reports__/agent_config/05-review_m6_5_v0.md` names each gate G1–G13 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. +- ⬜ `__reports__/agent_config/-review_m6_5_v0.md`, at the next free round after the live findings, names each gate G1–G13 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. - ⬜ The report lists any debt left behind (a second reader, a duplicated helper, dead code, a leftover script), each fixed in this leaf or filed as a notice. An out-of-scope finding is filed as an observation and escalated. -- ⬜ `__reports__/agent_config/05-knowledge_transfer_m6_5_v0.md` records the spend measured per leaf against the $85 cap. +- ⬜ `__reports__/agent_config/-knowledge_transfer_m6_5_v0.md`, in the same round as the review, records the spend measured per leaf against the $85 cap. **References**: [Architecture report, v2](../../../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model ## Step 1: Review and close From 6266caf9a4ffc41f098d7b10cc02af61f5bb5b4b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 16:55:22 +0900 Subject: [PATCH 32/69] rdm(api): raise the M6.5 cap to $125 Level 1 measured $55.40 against the $85 cap, so the later levels would not fit. Eliott raised the cap on 2026-11-25. Co-Authored-By: Claude Opus 5.5 --- __reports__/agent_config/README.md | 2 ++ __roadmap__/m6_5-agent-config/README.md | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 5428fe20..f3824153 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -29,4 +29,6 @@ On 2026-11-25 Eliott ruled on the two points that round 03 raised. The roadmap's - The proof reads the whole starting context. `context_start` comes from the run's first request that offers tools. G4 and G11 pass when each text is found in its `system` or its `first_message`, since Claude Code puts CLAUDE.md texts and SessionStart output in the first message. - Consumers write `hooks` and `instructions.global` in the harness's own shape and keys (`claude-code`, `SessionStart`, `start.sh`). The experiment surface takes them as opaque subtrees. +Level 1 is done and merged locally. On 2026-11-25 Eliott raised the cap from $85 to $125, after level 1 measured $55.40: planning $14, build $41. Level 2 runs on closed-scope briefs and a fresh agent for each fix round. + No decision is open. diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index c219450a..914663e7 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -1,7 +1,7 @@ # M6.5 Agent configuration as data ## Context -A new root after M6c Integrity (#81, on `origin/main` at `8d82f63b`). It is independent of M7, which is blocked, and of M8, which lies below M7; M8's plugin may later use hooks. The plan is [the architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), which adds to the approved plan Eliott's rulings on the HTN lane's notice (v1) and on a live, trace-read proof (v2). Every leaf runs by its §Execution model: Sonnet implementers and verifiers, a shared codebase whose debt the leaf owns, findings kept in scope or escalated, target-dir slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and an $85 cap. The status is mirrored in macOS Reminders. +A new root after M6c Integrity (#81, on `origin/main` at `8d82f63b`). It is independent of M7, which is blocked, and of M8, which lies below M7; M8's plugin may later use hooks. The plan is [the architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), which adds to the approved plan Eliott's rulings on the HTN lane's notice (v1) and on a live, trace-read proof (v2). Every leaf runs by its §Execution model: Sonnet implementers and verifiers, a shared codebase whose debt the leaf owns, findings kept in scope or escalated, target-dir slots `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and a $125 cap (raised from $85 by Eliott on 2026-11-25, after level 1 measured $55). The status is mirrored in macOS Reminders. ## Goal A consumer gives the experiment a global instruction file per harness, each arm its own workspace instruction file and hooks, all as cell values. Candler installs them where each harness looks, the workspace file read-only at the workspace root, and refuses a cell that the harness's own check rejects. @@ -14,7 +14,7 @@ A consumer gives the experiment a global instruction file per harness, each arm ## Success Gates - ⬜ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), as the leaves word them after the 2026-11-25 amendment (G1, G4, G8, G11, G12), hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` - ⬜ `probe_harness_checks.md`, `declaration.md`, `trace_context.md` and `installed/` are `done` -- ⬜ The spend measured from transcripts, coordinator included, is at most $85 +- ⬜ The spend measured from transcripts, coordinator included, is at most $125 - ⬜ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated ## Status From a0cbe0f0d809d63008893dccdc12f9688f25e5f2 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 16:57:09 +0900 Subject: [PATCH 33/69] rdm(api): order the M6.5 installs by the census channel Both drivers report loaded instruction files, so Claude Code, the reference harness, defines the one channel and OpenCode starts once it has merged. The leaves hand back a question instead of stopping at a cap. Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/installed/README.md | 2 +- .../m6_5-agent-config/installed/install_claude_code.md | 4 ++-- __roadmap__/m6_5-agent-config/installed/install_opencode.md | 3 ++- __roadmap__/m6_5-agent-config/installed/preflight_check.md | 2 +- __roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md | 2 +- .../installed/proved/reviewed/adversarial_review.md | 2 +- 6 files changed, 8 insertions(+), 7 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/installed/README.md b/__roadmap__/m6_5-agent-config/installed/README.md index fd2f91a1..a50285fb 100644 --- a/__roadmap__/m6_5-agent-config/installed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/README.md @@ -1,7 +1,7 @@ # Installed ## Context -L2 of M6.5. It runs after `probe_harness_checks.md` (which harness checks are reliable) and `declaration.md` (the settings, the one reader, the refusals). Its three leaves touch three separate crates: the Claude Code driver, the OpenCode driver and core. A seam review of the whole diff follows its close. +L2 of M6.5. It runs after `probe_harness_checks.md` (which harness checks are reliable) and `declaration.md` (the settings, the one reader, the refusals). Its three leaves touch three separate crates: the Claude Code driver, the OpenCode driver and core. `install_claude_code` defines the census channel for loaded instruction files, as the reference harness, and `install_opencode` starts once that channel has merged, so the two drivers fill one channel. `preflight_check` runs alongside `install_claude_code`. A seam review of the whole diff follows its close. ## Goal Each driver installs the global instruction text and hooks where its harness looks, and names the workspace instruction file, which the core mounts read-only at the workspace root. Each run records which instruction files loaded. Preflight refuses a cell that a harness check rejects, or whose workspace file collides with an input. diff --git a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md index 3e2e6282..cbeac9a1 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md +++ b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md @@ -1,7 +1,7 @@ # Install on Claude Code **Goal**: On Claude Code, the global text loads from where the probe settled, the workspace text loads as the root `CLAUDE.md`, and the hooks run, and every run's census names the memory files that loaded. (P0) -**Estimate**: Sonnet, $7, cap $14. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Estimate**: Sonnet, $7, cap $14. If the work outgrows the leaf or meets a question its brief does not answer, hand back with the question, the evidence and what is green. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds - [ ] `[nl]` The probe report settles (a), (b), (e) and (f) @@ -24,7 +24,7 @@ Extend `render_settings` with the `hooks` key. Do not write a second settings re ## Step 2: Census and check **Goal**: A run says which memory files loaded, and the driver supplies its harness check. **Implementation Logic**: -Read the `InstructionsLoaded` records into the census. Implement `config_check` and `read_config_check` from the probe: any error or warning becomes a finding. Flip the answers to Mapped. +Read the `InstructionsLoaded` records into the census through one harness-neutral channel (a list of loaded files, each with its path and its scope, `user` or `project`) that the core records as a census value; `install_opencode` fills the same channel. Implement `config_check` and `read_config_check` from the probe: any error or warning becomes a finding. Flip the answers to Mapped. **Deliverables**: the census reader; `config_check`, `read_config_check`; the census guard **Consistency Checks**: `cargo nextest run -p candler-harness-claude-code` and `cargo nextest run -p candler contract_pages` (expected: PASS) **Commit**: `feat(harness): record loaded memory files on Claude Code` diff --git a/__roadmap__/m6_5-agent-config/installed/install_opencode.md b/__roadmap__/m6_5-agent-config/installed/install_opencode.md index 3bfa37b5..100590b5 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_opencode.md +++ b/__roadmap__/m6_5-agent-config/installed/install_opencode.md @@ -1,10 +1,11 @@ # Install on OpenCode **Goal**: On OpenCode, the global text loads as the global `AGENTS.md`, the workspace text as the root `AGENTS.md`, and the plugins load locally, and every run's census names the instruction files that loaded. (P0) -**Estimate**: Sonnet, $6, cap $12. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Estimate**: Sonnet, $6, cap $12. If the work outgrows the leaf or meets a question its brief does not answer, hand back with the question, the evidence and what is green. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds - [ ] `[nl]` The probe report settles (c), (d) and (f) +- [ ] `[nl]` `install_claude_code`'s census channel for loaded instruction files is merged into `feat/m6.5-agent-config` **Success Gates**: - ⬜ G3 (OpenCode). The *instructions*, *hooks* and *config check* rows show the OpenCode mapping: `$XDG_CONFIG_HOME/opencode/AGENTS.md`, and the workspace's root `AGENTS.md`, read-only; local plugins in `$XDG_CONFIG_HOME/opencode/plugins/`; and the probe's check or `no (…)`. On the base, no such rows exist. - ⬜ The plan of a cell with `instructions.global.opencode`, `instructions.workspace` and `hooks.opencode` places the global `AGENTS.md` and each plugin in the home, byte for byte, lists `AGENTS.md` with the workspace text among its read-only workspace files, and writes nothing in the workspace itself. On the base, the plan has none of these. diff --git a/__roadmap__/m6_5-agent-config/installed/preflight_check.md b/__roadmap__/m6_5-agent-config/installed/preflight_check.md index 3ed683c4..98771f5a 100644 --- a/__roadmap__/m6_5-agent-config/installed/preflight_check.md +++ b/__roadmap__/m6_5-agent-config/installed/preflight_check.md @@ -1,7 +1,7 @@ # Preflight check **Goal**: Before any run, `candler resolve` runs each harness's own check on what Candler installed. It refuses a cell with any finding, quoting the harness, and records a clean verdict. The core also mounts each plan's read-only workspace file through `mount_inputs`, and refuses one that collides with a declared input. (P0) -**Estimate**: Sonnet, $9, cap $18. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Estimate**: Sonnet, $9, cap $18. If the work outgrows the leaf or meets a question its brief does not answer, hand back with the question, the evidence and what is green. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: diff --git a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md index b1f91e38..a1bb7acf 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md @@ -1,7 +1,7 @@ # E2E guard **Goal**: The real `candler run` on real Claude Code and real OpenCode, against the scripted fake model and then live on RiVault, shows from the stored trace the README's promise for instructions and hooks on both harnesses. (P0) -**Estimate**: Sonnet, $11, cap $22 (the live run included). At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Estimate**: Sonnet, $11, cap $22 (the live run included). If the work outgrows the leaf or meets a question its brief does not answer, hand back with the question, the evidence and what is green. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md index e8ad8113..f7e481cd 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md @@ -1,7 +1,7 @@ # Adversarial review **Goal**: A Sonnet reviewer, who did not build M6.5, reads the milestone's whole diff against the consumer interface, and the closing report says what holds and what does not. (P1) -**Estimate**: Sonnet, $4, cap $8. At the cap, stop, commit what is green, and list what is left in the leaf report. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. +**Estimate**: Sonnet, $4, cap $8. If the work outgrows the leaf or meets a question its brief does not answer, hand back with the question, the evidence and what is green. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: From b05b29de05f63711df63a1a0fef1050a4b8bd6fb Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:05:25 +0900 Subject: [PATCH 34/69] rdm(api): run the M6.5 harness check at job start A resolve step sees the request's resolution, not a cell, and the harness check needs each cell's plan. The check now runs beside the start check of the declared servers, before the job's first run, and the collision of the workspace file with an input is refused when the runs are planned. G6 and G10 are worded accordingly. Co-Authored-By: Claude Opus 5.5 --- __reports__/agent_config/README.md | 2 ++ __roadmap__/m6_5-agent-config/README.md | 2 +- .../installed/preflight_check.md | 22 +++++++++---------- .../installed/proved/e2e_guard.md | 4 ++-- 4 files changed, 16 insertions(+), 14 deletions(-) diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index f3824153..0c94dd05 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -31,4 +31,6 @@ On 2026-11-25 Eliott ruled on the two points that round 03 raised. The roadmap's Level 1 is done and merged locally. On 2026-11-25 Eliott raised the cap from $85 to $125, after level 1 measured $55.40: planning $14, build $41. Level 2 runs on closed-scope briefs and a fresh agent for each fix round. +On 2026-11-25 level 2 found that a resolve step cannot reach a cell's plan, which the harness check needs. The check moved beside the start check of the declared servers (`check_servers`, before the job's first run), and the collision check moved to planning. G6 and G10 are worded accordingly; the check still runs before any agent. + No decision is open. diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index 914663e7..70464744 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -12,7 +12,7 @@ A consumer gives the experiment a global instruction file per harness, each arm - [x] `[nl]` Eliott ruled on the HTN lane's notice on 2026-11-25: instructions come in two scopes (a global file per harness, and a workspace-root file per arm on both harnesses), and evaluator access to them is deferred ## Success Gates -- ⬜ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), as the leaves word them after the 2026-11-25 amendment (G1, G4, G8, G11, G12), hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` +- ⬜ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), as the leaves word them after the 2026-11-25 amendments (G1, G4, G8, G11, G12; then G6 and G10, checked at job start and at planning instead of at `resolve`), hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` - ⬜ `probe_harness_checks.md`, `declaration.md`, `trace_context.md` and `installed/` are `done` - ⬜ The spend measured from transcripts, coordinator included, is at most $125 - ⬜ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated diff --git a/__roadmap__/m6_5-agent-config/installed/preflight_check.md b/__roadmap__/m6_5-agent-config/installed/preflight_check.md index 98771f5a..1345ae78 100644 --- a/__roadmap__/m6_5-agent-config/installed/preflight_check.md +++ b/__roadmap__/m6_5-agent-config/installed/preflight_check.md @@ -1,30 +1,30 @@ # Preflight check -**Goal**: Before any run, `candler resolve` runs each harness's own check on what Candler installed. It refuses a cell with any finding, quoting the harness, and records a clean verdict. The core also mounts each plan's read-only workspace file through `mount_inputs`, and refuses one that collides with a declared input. (P0) +**Goal**: Before a job's first run, the core runs each harness's own check on what Candler installed, beside the start check of the declared servers. It refuses a cell with any finding, quoting the harness, and records a clean verdict. The core also mounts each plan's read-only workspace file through `mount_inputs`, and refuses, when the runs are planned, one that collides with a declared input. (P0) **Estimate**: Sonnet, $9, cap $18. If the work outgrows the leaf or meets a question its brief does not answer, hand back with the question, the evidence and what is green. Builds use one slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, and the leaf removes it when it merges. The leaf deletes the containers it starts. **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ With a driver whose check reports a finding, `candler resolve` exits 2 with `experiment.harness_rejected_input`. The message names what was installed, where, the harness, and the harness's output. On the base, no such step exists, and the same experiment is refused earlier with `unknown_path`. +- ⬜ With a driver whose check reports a finding, the job is refused before its first run with `experiment.harness_rejected_input`, the way a declared server that exits at start is refused. The message names what was installed, where, the harness, and the harness's output. No run starts and no check container is left. On the base, the job runs. - ⬜ With a clean check, the verdict is stored beside the harness identity in the run's provenance. With a driver whose `config_check` is `None`, the cell is not refused and nothing is stored as checked. -- ⬜ Cells that share a harness, image and prepared files run the check once, which is counted on the step's image service. +- ⬜ Cells that share a harness, image and prepared files run the check once, counted on the isolation the check uses. - ⬜ G9 (core half). With a fake driver whose plan lists a read-only workspace file, the run's workspace holds it at the root, a write to it fails, it is not among the collected outputs, and the run is not sealed `input_leak`. On the base, `Plan` has no such field. -- ⬜ G10. With `instructions.workspace` set, an input declared at the workspace instruction file's path is refused at `resolve` with `experiment.instructions_collide`, naming the input. On the base, the experiment is refused earlier with `unknown_path`. +- ⬜ G10. With `instructions.workspace` set, an input declared at the workspace instruction file's path is refused when the runs are planned, before any container starts, with `experiment.instructions_collide`, naming the input. On the base, the job runs. - ⬜ An adversarial Sonnet review finds no path where a finding lets the cell run, and no check container that outlives the step. -**References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-core/src/resolve/steps/` (`HarnessIdentityStep`, the precedent); `ImageService` +**References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-core/src/jobs/orchestrate/servers.rs` (`check_servers`, the precedent, called from `run_job`); `crates/candler-core/src/runner/plan.rs` (`plan_runs`) -## Step 1: The step -**Goal**: A preflight step that asks the harness and refuses on its answer. +## Step 1: The check +**Goal**: A start check that asks the harness and refuses on its answer. **Implementation Logic**: -Add `HarnessConfigStep` next to `HarnessIdentityStep`, reusing its image-service path. It dedupes by (harness, image, digest of the prepared files). For each distinct entry it starts a no-network container from the cell's image, places the driver's prepared files there and mounts the read-only workspace file, runs `config_check`, reads the verdict with `read_config_check`, and removes the container. Use a fake driver in the core guards; the real harnesses are L3's. -**Deliverables**: `crates/candler-core/src/resolve/steps/config_check.rs` (`HarnessConfigStep`); the provenance field; core guards +Add `check_config` beside `check_servers` and call it from `run_job` next to it, reusing its grouping, container and scratch-removal path. For each planned run it asks the driver for the cell's plan, skips a driver whose `config_check` is `None`, and dedupes by (harness, image, digest of the prepared files). For each distinct entry it starts a no-network container from the cell's image, places the driver's prepared files there and mounts the read-only workspace file, runs `config_check`, reads the verdict with `read_config_check`, and removes the container. Use a fake driver in the core guards; the real harnesses are L3's. +**Deliverables**: `check_config` in `crates/candler-core/src/jobs/orchestrate/`; the provenance field; core guards **Consistency Checks**: `cargo nextest run -p candler-core` (expected: PASS) **Commit**: `feat(api): refuse a cell its harness rejects` ## Step 2: The workspace file **Goal**: The plan's read-only workspace file reaches the workspace root the way an input does. **Implementation Logic**: -Store each read-only workspace file's text and add it to the mount list that `mount_inputs` builds, so the existing re-check covers it with the inputs. Do not write a second mount path. Before planning the runs, compare the file's path with every path the declared inputs mount, and refuse a match with `experiment.instructions_collide`. Use a fake driver in the core guards. -**Deliverables**: `crates/candler-core/src/runner/exec/mod.rs` (`mount_inputs`); the collision check in resolve; core guards for G9 and G10 +Store each read-only workspace file's text and add it to the mount list that `mount_inputs` builds, so the existing re-check covers it with the inputs. Do not write a second mount path. When the runs are planned, compare the file's path with every path the declared inputs mount, and refuse a match with `experiment.instructions_collide`. Use a fake driver in the core guards. +**Deliverables**: `crates/candler-core/src/runner/exec/mod.rs` (`mount_inputs`); the collision check in planning; core guards for G9 and G10 **Consistency Checks**: `cargo nextest run -p candler-core` (expected: PASS) **Commit**: `feat(api): mount the workspace instruction file read-only` diff --git a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md index a1bb7acf..d8db02fc 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md @@ -7,7 +7,7 @@ **Success Gates**: - ⬜ G4. From the trace: on each harness, the `context_start` of arm A's run holds the global text and workspace text A, verbatim, in its `system` or its `first_message`, and neither holds workspace text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. - ⬜ G5. The scripted tool call is answered with an error carrying the hook's marker: a Claude Code PreToolUse script exits 2, and an OpenCode plugin throws in `execute.before`. On the base, there is no hook and the call succeeds. -- ⬜ G6. On real images, an invalid payload (a Claude Code hooks entry on an unknown event; an OpenCode plugin with no default export) is refused at `resolve` with `experiment.harness_rejected_input`, quoting the harness, and the valid payload passes. On the base, it is `unknown_path`. +- ⬜ G6. On real images, an invalid payload (a Claude Code hooks entry on an unknown event; an OpenCode plugin with no default export) is refused before the job's first run with `experiment.harness_rejected_input`, quoting the harness, and the valid payload passes. On the base, the job runs. - ⬜ G7. Each run's census lists both installed instruction files with their scope: on Claude Code the global file where the probe settled and the root `CLAUDE.md` (Project); on OpenCode the global `AGENTS.md` and the root `AGENTS.md`. - ⬜ G9. No installed file, the root instruction file included, is among any run's collected outputs, and no run is sealed `input_leak`. - ⬜ G1 (end to end). `candler resolve` of the guard's experiment succeeds, and the `inspect` of one of its runs shows `instructions` and `hooks` with the arm's values. @@ -19,7 +19,7 @@ ## Step 1: The guards **Goal**: Two guards that read what a consumer reads. **Implementation Logic**: -`guard_agent_config_e2e` runs one experiment with a global text per harness, two arms (workspace text A or B) and one blocking hook and one session-start hook per harness on both harnesses. It reads `inspect`'s members, the rendered files in the run, the stored trace's `context_start` and the stored census, as a consumer does, not the fake model's records. `guard_harness_check_refuses` runs `resolve` on real images with no model. Reuse the parity e2e's helpers; do not copy them. The check's output must list both guards as passed. +`guard_agent_config_e2e` runs one experiment with a global text per harness, two arms (workspace text A or B) and one blocking hook and one session-start hook per harness on both harnesses. It reads `inspect`'s members, the rendered files in the run, the stored trace's `context_start` and the stored census, as a consumer does, not the fake model's records. `guard_harness_check_refuses` starts a job on real images with no model and reads its refusal. Reuse the parity e2e's helpers; do not copy them. The check's output must list both guards as passed. **Deliverables**: `crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs`; the fake model's script for the blocked call **Consistency Checks**: `cargo nextest run -p candler --run-ignored all -E 'test(agent_config) | test(harness_check)'` (expected: PASS) **Commit**: `test(cli): prove instructions and hooks on both harnesses` From 3cebec0623a5052a837658575d98b2275c0bd7f3 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:23:53 +0900 Subject: [PATCH 35/69] feat(api): install instructions and hooks on Claude Code The global text goes to .claude/CLAUDE.md in the run's home and is read through the user setting source, which a cell adds only when it sets that text. The workspace text is the plan's read-only CLAUDE.md. The hooks key of .claude/settings.json and the hook files under .claude/hooks/ come from the cell's hooks. The observation settings file is a plan file now, passed with --settings in headless mode as in session mode, and watches InstructionsLoaded too. HookSpec no longer carries files. The hooks reader is generic over the harness's envelope, and the drivers name their harness by the spec constants. Co-Authored-By: Claude Sonnet 5.5 --- .../candler-core/src/runner/exec/session.rs | 19 +-- crates/candler-core/src/runner/plan.rs | 3 +- .../tests/it/guard_harness_facts.rs | 5 +- crates/candler-core/tests/it/guard_session.rs | 16 +- .../tests/it/support/session_rig.rs | 12 +- .../candler-harness-claude-code/src/driver.rs | 46 +++-- crates/candler-harness-claude-code/src/lib.rs | 9 +- .../src/prepare.rs | 86 +++++++++- .../src/session.rs | 41 ++--- .../tests/it/conformance.rs | 44 ++--- .../tests/it/guard_claude_code_driver.rs | 158 +++++++++++++++++- crates/candler-harness-opencode/src/lib.rs | 6 +- crates/candler-harness/src/agent_config.rs | 31 ++-- crates/candler-harness/src/conformance.rs | 22 +-- crates/candler-harness/src/spec.rs | 11 +- .../tests/it/guard_agent_config.rs | 9 +- docs/contract/configuration-paths.md | 6 +- docs/contract/harness-capabilities.md | 6 +- 18 files changed, 378 insertions(+), 152 deletions(-) diff --git a/crates/candler-core/src/runner/exec/session.rs b/crates/candler-core/src/runner/exec/session.rs index 948a65ce..658b917a 100644 --- a/crates/candler-core/src/runner/exec/session.rs +++ b/crates/candler-core/src/runner/exec/session.rs @@ -17,7 +17,7 @@ use std::time::{Duration, Instant}; use candler_harness::driver::HarnessDriver; use candler_harness::spec::{ - Cell, FileRoot, Framing, PendingState, SessionClose, SessionRecord, SessionSpec, SessionTracker, + Cell, Framing, PendingState, SessionClose, SessionRecord, SessionSpec, SessionTracker, }; use candler_schemas::raw::{Clock as FrameClock, ClockAnchor, StreamName}; use candler_schemas::trace::{Cap, EndedBy}; @@ -427,7 +427,7 @@ impl HookLog { // One session run. // --------------------------------------------------------------------------------------------- -/// A session that is prepared and not yet started: the hooks are installed, the watch exists. +/// A session that is prepared and not yet started: the hook log is open, the watch exists. pub struct SessionRun { watch: Arc, input: Vec, @@ -461,14 +461,13 @@ impl std::fmt::Debug for SessionWatch { } impl SessionRun { - /// Installs the hooks of `spec` under `home` and prepares the watch. + /// Opens the hook log of `spec` under `home` and prepares the watch. /// /// The tracker is `harness`'s. The hook log is archived as a raw stream under `frames`. /// /// # Errors /// [`IsolationError::Plan`] when the driver declares a session it gives no tracker for, closes - /// it by an action (which the runner does not run), or when a hook file or the archive cannot - /// be made. + /// it by an action (which the runner does not run), or when the archive cannot be made. pub fn prepare( harness: &dyn HarnessDriver, // TRAIT_OBJECT: the driver is the binary's choice, or a fake in tests spec: &SessionSpec, @@ -490,16 +489,6 @@ impl SessionRun { })?; let mut log = None; if let Some(hooks) = &spec.hooks { - for file in &hooks.files { - if file.root != FileRoot::Home { - return Err(plan_error(format!( - "the hook file {} is not rooted at the agent's home", - file.path - ))); - } - super::write_file(home, file) - .map_err(|error| plan_error(format!("cannot write a hook file: {error}")))?; - } let anchor = ClockAnchor::new( now().map_err(|error| plan_error(error.to_string()))?, // BORROW: .to_string() gives owned text 0, diff --git a/crates/candler-core/src/runner/plan.rs b/crates/candler-core/src/runner/plan.rs index 6da3d514..c3fe9adf 100644 --- a/crates/candler-core/src/runner/plan.rs +++ b/crates/candler-core/src/runner/plan.rs @@ -765,7 +765,8 @@ fn fresh_cells<'r>( let view = Cell::new(cell.comparable.values()); let harness = driver.id().to_string(); // BORROW: .to_string() gives owned text agent_config::instructions(&view, harness.as_str())?; // BORROW: explicit .as_str() - agent_config::hooks(&view, harness.as_str())?; // BORROW: explicit .as_str() + // The envelope is the driver's to read: here only the keys and the harness's entry. + agent_config::hooks::(&view, harness.as_str())?; // BORROW: explicit .as_str() refuse_unanswered(driver, &view)?; driver.check_settings(&view)?; } diff --git a/crates/candler-core/tests/it/guard_harness_facts.rs b/crates/candler-core/tests/it/guard_harness_facts.rs index 6f78a380..c304101e 100644 --- a/crates/candler-core/tests/it/guard_harness_facts.rs +++ b/crates/candler-core/tests/it/guard_harness_facts.rs @@ -413,7 +413,10 @@ fn harness_env_claude_code_argv_equals_cf3de30() { let driver = ClaudeCodeDriver::new(); let argv = facts::agent_argv(&scene, &driver, &facts::reference_command()).expect("an argv"); let baseline = recorded("argv.json"); - assert_eq!(argv, words(&baseline["headless_run"])); + // The baseline's command line, then the observers' settings file the driver has added since. + let mut expected = words(&baseline["headless_run"]); + expected.extend(["--settings", "/home/agent/.candler/settings.json"].map(str::to_owned)); // BORROW: str::to_owned makes the owned words + assert_eq!(argv, expected); } /// Guards: R01 §Process supervision — the supervised client attaches to the created container diff --git a/crates/candler-core/tests/it/guard_session.rs b/crates/candler-core/tests/it/guard_session.rs index 3f9ee5da..958fc88d 100644 --- a/crates/candler-core/tests/it/guard_session.rs +++ b/crates/candler-core/tests/it/guard_session.rs @@ -1331,18 +1331,20 @@ fn hook_commands() -> Vec<(String, String)> { .map(|(path, value)| candler_schemas::values::ResolvedValue::recorded(fp(path), js(value))) .collect(); let driver = ClaudeCodeDriver::new(); - let spec = driver + let plan = driver .plan( &Cell::new(&resolved), &Workspace::new(Path::new("/work/run")), ) - .expect("a plan") - .session - .expect("a session spec"); - let hooks = spec.hooks.expect("the driver installs hooks"); - assert_eq!(hooks.files.len(), 1, "one settings file"); + .expect("a plan"); + let file = plan + .prepared + .files + .iter() + .find(|file| file.path.as_str() == ".candler/settings.json") + .expect("the observers' settings file"); let settings: serde_json::Value = - serde_json::from_slice(&hooks.files[0].contents).expect("settings JSON"); + serde_json::from_slice(&file.contents).expect("settings JSON"); let mut commands = Vec::new(); for (event, entries) in settings["hooks"].as_object().expect("hooks") { for entry in entries.as_array().expect("entries") { diff --git a/crates/candler-core/tests/it/support/session_rig.rs b/crates/candler-core/tests/it/support/session_rig.rs index 64891540..73fdb57d 100644 --- a/crates/candler-core/tests/it/support/session_rig.rs +++ b/crates/candler-core/tests/it/support/session_rig.rs @@ -255,10 +255,14 @@ impl HarnessDriver for Driver { } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { let mut plan = self.inner.plan(cell, workspace)?; - if !self.hooks - && let Some(found) = plan.session.as_mut() - { - found.hooks = None; + if !self.hooks { + if let Some(found) = plan.session.as_mut() { + found.hooks = None; + } + // The observers' settings file is part of the hooks. + plan.prepared + .files + .retain(|file| file.path.as_str() != ".candler/settings.json"); } Ok(plan) } diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index cd0a68e7..c38dc62c 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -11,8 +11,8 @@ use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ AgentSetting, Answer, BaseImage, CLAUDE_CODE, Cell, CheckVerdict, CollectSpec, CommandSpec, - DriverFact, EffortLevel, GatewayEnv, HarnessId, Observed, PermissionMode, Prepared, - ProcessExit, SessionTracker, StopSignal, StopSpec, Workspace, + DriverFact, EffortLevel, GatewayEnv, HarnessId, InstructionScope, Observed, PermissionMode, + Prepared, ProcessExit, SessionTracker, StopSignal, StopSpec, Workspace, }; use candler_schemas::execution::paths; use candler_schemas::name; @@ -84,8 +84,9 @@ pub(crate) enum Launch { } /// The command line of a cell: the program and `--print` with the prompt or the stdin format, the -/// model, the stream output, the setting sources, the permission mode, and the effort and caps the -/// cell sets. +/// model, the stream output, the setting sources (with `user` when the cell sets a global text), +/// the permission mode, the effort and caps the cell sets, and the observation hooks' settings +/// file. pub(crate) fn argv(cell: &Cell<'_>, launch: Launch) -> Result, DriverError> { let model = cell.model()?; let mode = cell.permission_mode()?; @@ -105,10 +106,17 @@ pub(crate) fn argv(cell: &Cell<'_>, launch: Launch) -> Result, Drive argv.extend(["--model", model].map(str::to_owned)); // BORROW: str::to_owned makes the owned arguments } } + // `user` also loads the home's `settings.json` and `rules/`, so only a cell that needs the + // home's `CLAUDE.md` adds it. + let sources = if prepare::has_global(cell)? { + "user,project,local" + } else { + "project,local" + }; argv.extend( [ "--setting-sources", - "project,local", + sources, "--permission-mode", mode.as_str(), ] @@ -129,6 +137,8 @@ pub(crate) fn argv(cell: &Cell<'_>, launch: Launch) -> Result, Drive // Only the servers of the cell: no other MCP configuration reaches the agent. argv.extend(["--mcp-config", prepare::MCP_FILE, "--strict-mcp-config"].map(str::to_owned)); // BORROW: str::to_owned makes the owned arguments } + argv.push("--settings".to_owned()); // BORROW: .to_owned() makes the owned argument + argv.push(session::settings_argument()); Ok(argv) } @@ -278,8 +288,14 @@ impl HarnessDriver for ClaudeCodeDriver { AgentSetting::SessionMode => Answer::Mapped { construct: "stream-json over an open stdin, one turn per message", }, - AgentSetting::Instructions(_) | AgentSetting::Hooks => Answer::Refused { - reason: "this driver installs no instruction text or hook", + AgentSetting::Instructions(InstructionScope::Global) => Answer::Mapped { + construct: "`.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither)", + }, + AgentSetting::Instructions(InstructionScope::Workspace) => Answer::Mapped { + construct: "`CLAUDE.md` at the workspace root, mounted read-only", + }, + AgentSetting::Hooks => Answer::Mapped { + construct: "the `hooks` key of `.claude/settings.json`, with the hook files under `.claude/hooks/`", }, } } @@ -340,20 +356,30 @@ impl HarnessDriver for ClaudeCodeDriver { fn check_settings(&self, cell: &Cell<'_>) -> Result<(), DriverError> { cap_text(cell, paths::BUDGET_PER_RUN_TURNS, true)?; cap_text(cell, paths::BUDGET_PER_RUN_MAX_COST_USD, false)?; + candler_harness::agent_config::hooks::( + cell, + CLAUDE_CODE, + )?; + prepare::has_global(cell)?; candler_harness::mcp::servers(cell).map(|_| ()) } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { let _ = workspace; self.check_settings(cell)?; - let mut files = vec![prepare::render_settings(cell)?]; + let mut files = vec![prepare::render_settings(cell)?, session::observers()?]; files.extend(prepare::render_mcp(cell)?); + files.extend(prepare::render_hook_files(cell)?); + let (global, workspace_file) = prepare::render_instructions(cell)?; + files.extend(global); let argv = argv(cell, Launch::Headless(cell.prompt()?))?; - Ok(Plan::new( + let mut plan = Plan::new( Prepared::new(files, Vec::new()), CommandSpec::builder().argv(argv).build()?, ) - .with_session(session::spec(cell)?)) + .with_session(session::spec(cell)?); + plan.workspace_files.extend(workspace_file); + Ok(plan) } fn stop(&self) -> StopSpec { diff --git a/crates/candler-harness-claude-code/src/lib.rs b/crates/candler-harness-claude-code/src/lib.rs index 06bfb4fb..ab624a43 100644 --- a/crates/candler-harness-claude-code/src/lib.rs +++ b/crates/candler-harness-claude-code/src/lib.rs @@ -16,7 +16,9 @@ mod sessions; mod usage; use candler_harness::reader::{FrameIn, ReaderError, TraceReader}; -use candler_harness::spec::{Confidence, FormatVersion, Framing, InitReport, Observed, RunTotals}; +use candler_harness::spec::{ + CLAUDE_CODE, Confidence, FormatVersion, Framing, InitReport, Observed, RunTotals, +}; use candler_schemas::name; use candler_schemas::primitives::{Name, NameVersion, Timestamp}; use candler_schemas::raw::RawRef; @@ -51,9 +53,6 @@ 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 name of the harness that produced the streams the reader reads. -const HARNESS: &str = "claude-code"; - /// The identity of this reader as text, `claude-code-stream-json@`; the version changes whenever the reader's output does. pub const READER: &str = "claude-code-stream-json@0.2.0"; @@ -257,7 +256,7 @@ impl TraceReader for ClaudeCodeReader { }; let reader = self.identity; let source = SessionSource::new( - name(HARNESS)?, + name(CLAUDE_CODE)?, version, name(reader.name())?, // BORROW: .clone() copies the reader version diff --git a/crates/candler-harness-claude-code/src/prepare.rs b/crates/candler-harness-claude-code/src/prepare.rs index 1466e6d3..3da3a5f7 100644 --- a/crates/candler-harness-claude-code/src/prepare.rs +++ b/crates/candler-harness-claude-code/src/prepare.rs @@ -1,12 +1,14 @@ -//! The files the driver asks the core to write into the workspace: the settings and the MCP -//! configuration. +//! The files the driver asks the core to write: the settings, the hook files, the MCP +//! configuration and the instruction texts. //! //! Nothing here touches the file system or runs a process. use std::str::FromStr as _; +use candler_harness::agent_config::{hooks, instructions}; use candler_harness::driver::DriverError; -use candler_harness::spec::{Cell, PreparedFile}; +use candler_harness::spec::{CLAUDE_CODE, Cell, PreparedFile}; +use candler_schemas::agent_config::ClaudeCodeHooks; use candler_schemas::execution::paths::{TOOLS_ALLOWED, TOOLS_DISALLOWED}; use candler_schemas::field_path; use candler_schemas::primitives::RelPath; @@ -53,8 +55,10 @@ fn json_file(path: &str, value: &Value) -> Result { Ok(PreparedFile::new(rel, text.into_bytes(), false)) } -/// The `.claude/settings.json` file of a cell: `permissions.allow` from `tools.allowed` and -/// `permissions.deny` from `tools.disallowed`, each only when the cell sets it. +/// The `.claude/settings.json` file of a cell: `permissions.allow` from `tools.allowed`, +/// `permissions.deny` from `tools.disallowed` and `hooks` from the `settings` of the cell's Claude +/// Code hooks, each only when the cell sets it. Nothing else of the hooks is taken, so they cannot +/// set another key. /// /// # Errors /// [`DriverError`] when a value of the cell cannot be used. @@ -81,9 +85,81 @@ pub fn render_settings(cell: &Cell<'_>) -> Result { // BORROW: .to_owned() makes the owned key root.insert("permissions".to_owned(), Value::Object(permissions)); } + if let Some(settings) = + hooks::(cell, CLAUDE_CODE)?.and_then(|found| found.settings) + { + // BORROW: .to_owned() makes the owned key + root.insert("hooks".to_owned(), Value::Object(settings)); + } json_file(".claude/settings.json", &Value::Object(root)) } +/// The directory the hook files of a cell go under, relative to the workspace. +const HOOK_DIR: &str = ".claude/hooks"; + +/// The hook files of a cell, each under `.claude/hooks/` and executable. +/// +/// # Errors +/// [`DriverError`] when the cell's hooks do not fit their envelope or a path cannot be used. +pub fn render_hook_files(cell: &Cell<'_>) -> Result, DriverError> { + let Some(found) = hooks::(cell, CLAUDE_CODE)? else { + return Ok(Vec::new()); + }; + found + .files + .iter() + .map(|(path, text)| { + let at = format!("{HOOK_DIR}/{path}"); + let rel = + RelPath::from_str(&at).map_err(|error| invalid("hooks", error.to_string()))?; // BORROW: .to_string() gives owned text + Ok(PreparedFile::new(rel, text.as_bytes().to_vec(), true)) // BORROW: .to_vec() copies the text into the file + }) + .collect() +} + +/// The instruction files of a cell: the global text as `.claude/CLAUDE.md` in the agent's home, and +/// the workspace text as `CLAUDE.md`, each only when the cell sets it. The workspace file is +/// mounted read-only by the core and written by no driver, so it is the plan's workspace file. +/// +/// # Errors +/// [`DriverError`] when the cell's instructions cannot be used. +pub fn render_instructions( + cell: &Cell<'_>, +) -> Result<(Option, Option), DriverError> { + let Some(found) = instructions(cell, CLAUDE_CODE)? else { + return Ok((None, None)); + }; + let file = + |path: &str| RelPath::from_str(path).map_err(|error| invalid(path, error.to_string())); // BORROW: .to_string() gives owned text + let global_path = file(GLOBAL_FILE)?; + let workspace_path = file(WORKSPACE_FILE)?; + let global = found.global.get(CLAUDE_CODE).map(|text| { + // BORROW: .to_vec() copies the text into the file + PreparedFile::in_home(global_path, text.as_bytes().to_vec(), false) + }); + let workspace = found.workspace.as_ref().map(|text| { + // BORROW: .to_vec() copies the text into the file + PreparedFile::new(workspace_path, text.as_bytes().to_vec(), false) + }); + Ok((global, workspace)) +} + +/// Whether the cell sets a global text for Claude Code, which only the `user` setting source reads. +/// +/// # Errors +/// [`DriverError`] when the cell's instructions cannot be used. +pub fn has_global(cell: &Cell<'_>) -> Result { + Ok( + instructions(cell, CLAUDE_CODE)? + .is_some_and(|found| found.global.contains_key(CLAUDE_CODE)), + ) +} + +/// The global instruction file, relative to the agent's home. +const GLOBAL_FILE: &str = ".claude/CLAUDE.md"; +/// The workspace instruction file, at the workspace root. +pub(crate) const WORKSPACE_FILE: &str = "CLAUDE.md"; + /// The file the MCP configuration is written to, and that the agent command names. pub(crate) const MCP_FILE: &str = ".mcp.json"; diff --git a/crates/candler-harness-claude-code/src/session.rs b/crates/candler-harness-claude-code/src/session.rs index f7011b9f..c23e033d 100644 --- a/crates/candler-harness-claude-code/src/session.rs +++ b/crates/candler-harness-claude-code/src/session.rs @@ -43,14 +43,15 @@ use crate::driver::{Launch, argv, invalid}; /// The home directory the core gives every agent container. const AGENT_HOME: &str = "/home/agent"; -/// The settings file that installs the hooks, relative to the agent's home. +/// The settings file that installs the hooks, relative to the agent's home. It lies outside +/// `.claude/`, which the `user` setting source reads. const SETTINGS: &str = ".candler/settings.json"; /// The file the hooks append to, relative to the agent's home. const HOOK_LOG: &str = ".candler/hooks.jsonl"; /// The name of the raw stream that archives the hook log. const HOOK_STREAM: &str = "hooks"; /// The hook events the driver installs. -const HOOK_EVENTS: [&str; 2] = ["Stop", "SessionEnd"]; +const HOOK_EVENTS: [&str; 3] = ["InstructionsLoaded", "Stop", "SessionEnd"]; /// The hook command: appends the payload, with the container's clock, as one JSON line to the log. /// It prints nothing on stdout or stderr, whatever the log does, never fails and never decides, so @@ -75,37 +76,37 @@ fn settings_json() -> Value { json!({ "hooks": hooks }) } -/// The hook spec: the settings file and where the log goes. -fn hooks() -> Result { - let rel = |text: &str| { - RelPath::from_str(text).map_err(|error| invalid(text, error.to_string())) // BORROW: .to_string() gives owned text - }; +/// The settings file that installs the observation hooks, in the agent's home, for a headless run +/// and a session alike. +pub(crate) fn observers() -> Result { let mut text = serde_json::to_string_pretty(&settings_json()) .map_err(|error| invalid(SETTINGS, error.to_string()))?; // BORROW: .to_string() gives owned text text.push('\n'); + let rel = RelPath::from_str(SETTINGS).map_err(|error| invalid(SETTINGS, error.to_string()))?; // BORROW: .to_string() gives owned text + Ok(PreparedFile::in_home(rel, text.into_bytes(), false)) +} + +/// The argument of `--settings`: the observation hooks' file, by its path in the container. +pub(crate) fn settings_argument() -> String { + format!("{AGENT_HOME}/{SETTINGS}") +} + +/// The hook spec: where the log goes and the stream that archives it. +fn hooks() -> Result { + let log = RelPath::from_str(HOOK_LOG).map_err(|error| invalid(HOOK_LOG, error.to_string()))?; // BORROW: .to_string() gives owned text let stream = StreamName::from_str(HOOK_STREAM) .map_err(|error| invalid(HOOK_STREAM, error.to_string()))?; // BORROW: .to_string() gives owned text - Ok(HookSpec::new( - vec![PreparedFile::in_home( - rel(SETTINGS)?, - text.into_bytes(), - false, - )], - rel(HOOK_LOG)?, - stream, - )) + Ok(HookSpec::new(log, stream)) } /// The session of a cell: stdin open, the prompt as the first message, closed by end of input, with -/// the observation hooks installed from a settings file outside the workspace. +/// the observation hooks of the command line's settings file logging to the hook log. /// /// # Errors /// [`DriverError`] when a value of the cell is missing or cannot be used. pub fn spec(cell: &candler_harness::spec::Cell<'_>) -> Result { let prompt = cell.prompt()?; - let mut argv = argv(cell, Launch::Session)?; - argv.push("--settings".to_owned()); // BORROW: .to_owned() makes the owned argument - argv.push(format!("{AGENT_HOME}/{SETTINGS}")); + let argv = argv(cell, Launch::Session)?; let command = CommandSpec::builder().argv(argv).build()?; let message = json!({ "type": "user", diff --git a/crates/candler-harness-claude-code/tests/it/conformance.rs b/crates/candler-harness-claude-code/tests/it/conformance.rs index 5c220e71..ecb0eb2d 100644 --- a/crates/candler-harness-claude-code/tests/it/conformance.rs +++ b/crates/candler-harness-claude-code/tests/it/conformance.rs @@ -360,7 +360,8 @@ fn conformance_claude_session_spec() -> Res<()> { let driver = ClaudeCodeDriver::new(); let values = values()?; let workspace = Workspace::new(Path::new(".")); - let Some(spec) = driver.plan(&Cell::new(&values), &workspace)?.session else { + let plan = driver.plan(&Cell::new(&values), &workspace)?; + let Some(spec) = plan.session else { return Err("the driver returns no session spec".into()); }; assert_eq!( @@ -395,11 +396,16 @@ fn conformance_claude_session_spec() -> Res<()> { return Err("the session has no hooks".into()); }; assert_eq!(hooks.log.as_str(), ".candler/hooks.jsonl"); - let [file] = hooks.files.as_slice() else { - return Err("expected one settings file".into()); + let homed: Vec<&PreparedFile> = plan + .prepared + .files + .iter() + .filter(|file| file.root == FileRoot::Home) + .collect(); + let [file] = homed.as_slice() else { + return Err("expected one home file, the observers' settings".into()); }; assert_eq!(file.path.as_str(), ".candler/settings.json"); - assert_eq!(file.root, FileRoot::Home); let settings: Value = serde_json::from_slice(&file.contents)?; let events: Vec<&str> = settings["hooks"] .as_object() @@ -407,7 +413,7 @@ fn conformance_claude_session_spec() -> Res<()> { .keys() .map(String::as_str) .collect(); - assert_eq!(events, ["SessionEnd", "Stop"]); + assert_eq!(events, ["InstructionsLoaded", "SessionEnd", "Stop"]); for event in events { let command = settings["hooks"][event][0]["hooks"][0]["command"] .as_str() @@ -427,12 +433,18 @@ fn conformance_claude_hook_command_observes_without_deciding() -> Res<()> { let driver = ClaudeCodeDriver::new(); let values = values()?; let workspace = Workspace::new(Path::new(".")); - let Some(spec) = driver.plan(&Cell::new(&values), &workspace)?.session else { - return Err("the driver returns no session spec".into()); - }; - let hooks = spec.hooks.ok_or("the session has no hooks")?; - let settings: Value = - serde_json::from_slice(&hooks.files.first().ok_or("no settings file")?.contents)?; + let plan = driver.plan(&Cell::new(&values), &workspace)?; + let hooks = plan + .session + .and_then(|spec| spec.hooks) + .ok_or("the session has no hooks")?; + let file = plan + .prepared + .files + .iter() + .find(|file| file.path.as_str() == ".candler/settings.json") + .ok_or("no settings file")?; + let settings: Value = serde_json::from_slice(&file.contents)?; let command = settings["hooks"]["Stop"][0]["hooks"][0]["command"] .as_str() .ok_or("no hook command")?; @@ -731,15 +743,7 @@ fn conformance_claude_session_command_keeps_the_headless_arguments() -> Res<()> .ok_or_else(|| format!("the session command lost `{arg}`"))?; extras.remove(at); } - assert_eq!( - extras, - [ - "--input-format", - "stream-json", - "--settings", - "/home/agent/.candler/settings.json" - ] - ); + assert_eq!(extras, ["--input-format", "stream-json",]); Ok(()) } diff --git a/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs b/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs index 0f20d086..b9c50644 100644 --- a/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs +++ b/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs @@ -10,7 +10,9 @@ use std::process::Command; use std::str::FromStr as _; use candler_harness::driver::HarnessDriver; -use candler_harness::spec::{Cell, CollectSpec, EnvValue, Observed, StopSignal, Workspace}; +use candler_harness::spec::{ + Cell, CollectSpec, EnvValue, FileRoot, Observed, StopSignal, Workspace, +}; use candler_harness_claude_code::driver::ClaudeCodeDriver; use candler_schemas::execution::{GitCommit, TreatmentRef}; use candler_schemas::primitives::{FieldPath, Name}; @@ -105,6 +107,12 @@ fn b21_reference_command_line() -> Res<()> { }); } } + // The one addition to the reference: the observation hooks' settings file, which the + // census of loaded instruction files reads. + argv.extend([ + "--settings".to_owned(), + "/home/agent/.candler/settings.json".to_owned(), + ]); Ok(argv) }; let root = Path::new("/work/run"); @@ -589,3 +597,151 @@ fn claude_code_refuses_codemode_true() -> Res<()> { assert_eq!(refusal_of(Some(json!(false)))?, None); Ok(()) } + +/// The cell of `values("default")` with `extra` values set. +fn values_with(extra: &[(&str, serde_json::Value)]) -> Res> { + let mut all = values("default")?; + for (path, value) in extra { + all.push(ResolvedValue::recorded( + FieldPath::from_str(path)?, + JsonValue::new(value.clone())?, // BORROW: .clone() copies the test's value + )); + } + Ok(all) +} + +/// Guards: G3 plan — a cell with the four values installs the global text in the home as +/// `.claude/CLAUDE.md` and reads it through the `user` source, lists the workspace text as the +/// read-only `CLAUDE.md` and writes none, renders `hooks` of `.claude/settings.json` equal to the +/// payload, places the hook files under `.claude/hooks/` executable, and passes the observers' +/// settings file, with `InstructionsLoaded`, to the headless command as to the session's. +/// Oracle: the payload and texts written here by hand. +/// Bite: leave `user` out of the sources, write `CLAUDE.md` into the prepared files, or pass the +/// observers only in session mode. +#[test] +fn a_cell_with_the_four_values_installs_them_where_claude_code_reads_them() -> Res<()> { + let hooks = json!({"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": ".claude/hooks/guard.sh"}]}]}); + let cell = values_with(&[ + ("instructions.global", json!({"claude-code": "global text"})), + ("instructions.workspace", json!("workspace text")), + ( + "hooks", + json!({"claude-code": {"settings": hooks, "files": {"guard.sh": "#!/bin/sh\nexit 0\n"}}}), + ), + ])?; + let plan = + ClaudeCodeDriver::new().plan(&Cell::new(&cell), &Workspace::new(Path::new("/work/run")))?; + let find = |path: &str| { + plan.prepared + .files + .iter() + .find(|file| file.path.as_str() == path) + }; + + let global = find(".claude/CLAUDE.md").ok_or("no global file")?; + assert_eq!(global.root, FileRoot::Home); + assert_eq!(global.contents, b"global text"); + assert!( + find("CLAUDE.md").is_none(), + "the driver never writes the workspace file" + ); + let [workspace] = plan.workspace_files.as_slice() else { + return Err("expected one workspace file".into()); + }; + assert_eq!(workspace.path.as_str(), "CLAUDE.md"); + assert_eq!(workspace.root, FileRoot::Workspace); + assert_eq!(workspace.contents, b"workspace text"); + + let settings: serde_json::Value = + serde_json::from_slice(&find(".claude/settings.json").ok_or("no settings")?.contents)?; + assert_eq!(settings["hooks"], hooks); + let script = find(".claude/hooks/guard.sh").ok_or("no hook file")?; + assert!(script.executable); + assert_eq!(script.contents, b"#!/bin/sh\nexit 0\n"); + + let observers: serde_json::Value = serde_json::from_slice( + &find(".candler/settings.json") + .ok_or("no observers")? + .contents, + )?; + assert!(observers["hooks"]["InstructionsLoaded"].is_array()); + let argv = plan.command.argv(); + let at = |flag: &str| argv.iter().position(|arg| arg == flag); + let sources = at("--setting-sources").ok_or("no sources")?; + assert_eq!( + argv.get(sources + 1).map(String::as_str), + Some("user,project,local") + ); + let settings_flag = at("--settings").ok_or("the headless command has no --settings")?; + assert_eq!( + argv.get(settings_flag + 1).map(String::as_str), + Some("/home/agent/.candler/settings.json") + ); + Ok(()) +} + +/// Guards: G3 plan, no regression — a cell without these values renders the same +/// `.claude/settings.json` as before, reads the project and local sources only, and installs the +/// home observers file and no other file of the four values. +/// Oracle: `{}` and the sources of the reference line, written by hand. +/// Bite: add `user` or an empty `hooks` key for every cell. +#[test] +fn a_cell_without_the_values_changes_nothing_but_the_observers() -> Res<()> { + let cell = values("default")?; + let plan = + ClaudeCodeDriver::new().plan(&Cell::new(&cell), &Workspace::new(Path::new("/work/run")))?; + let paths: Vec<&str> = plan + .prepared + .files + .iter() + .map(|file| file.path.as_str()) + .collect(); + assert_eq!(paths, [".claude/settings.json", ".candler/settings.json"]); + assert_eq!(plan.prepared.files[0].contents, b"{}\n"); + assert_eq!(plan.workspace_files, []); + assert!(plan.command.argv().iter().any(|arg| arg == "project,local")); + Ok(()) +} + +/// Guards: invariant 6 — a payload cannot disable the observers or write outside `.claude/`: its +/// `settings` land under `hooks` and nowhere else, a hook file path that leaves the directory is +/// refused, and the observers sit in a file the payload cannot name. +/// Oracle: payloads written by hand. +/// Bite: merge the payload into the root of the settings, or join paths without checking them. +#[test] +fn a_payload_cannot_reach_beyond_hooks_and_the_hooks_directory() -> Res<()> { + let driver = ClaudeCodeDriver::new(); + let hostile = values_with(&[( + "hooks", + json!({"claude-code": {"settings": {"disableAllHooks": true, "Stop": []}, + "files": {"ok.sh": "x"}}}), + )])?; + let plan = driver.plan( + &Cell::new(&hostile), + &Workspace::new(Path::new("/work/run")), + )?; + let settings: serde_json::Value = serde_json::from_slice(&plan.prepared.files[0].contents)?; + let root: Vec<&String> = settings + .as_object() + .ok_or("not an object")? + .keys() + .collect(); + assert_eq!(root, ["hooks"]); + for file in &plan.prepared.files { + let path = file.path.as_str(); + let under = path.starts_with(".claude/hooks/") + || path == ".claude/settings.json" + || path == ".candler/settings.json"; + assert!(under, "{path}"); + } + for path in ["../x.sh", "a/../../x.sh", "/etc/x.sh"] { + let cell = values_with(&[("hooks", json!({"claude-code": {"files": {path: "x"}}}))])?; + assert!( + driver + .plan(&Cell::new(&cell), &Workspace::new(Path::new("/work/run"))) + .is_err(), + "{path} was accepted" + ); + } + Ok(()) +} diff --git a/crates/candler-harness-opencode/src/lib.rs b/crates/candler-harness-opencode/src/lib.rs index e0513a7d..83b56ca5 100644 --- a/crates/candler-harness-opencode/src/lib.rs +++ b/crates/candler-harness-opencode/src/lib.rs @@ -18,6 +18,7 @@ pub mod live; mod prepare; use candler_harness::reader::ReaderError; +use candler_harness::spec::OPENCODE; use candler_schemas::primitives::Name; use candler_schemas::trace::SessionSource; @@ -36,9 +37,6 @@ pub const LIVE_READER: &str = "opencode-ndjson@0.1.0"; /// The reader of the session export, as the trace header names it. pub const EXPORT_READER: &str = "opencode-export@0.1.0"; -/// The name of the harness. -pub const HARNESS: &str = "opencode"; - /// The stream name under which the export is collected. pub const EXPORT_STREAM: &str = "export"; @@ -68,7 +66,7 @@ pub(crate) fn session_source( }) }; Ok(SessionSource::new( - name(HARNESS)?, + name(OPENCODE)?, VALIDATED, name(reader.name())?, reader.version().clone(), // BORROW: .clone() copies the reader version diff --git a/crates/candler-harness/src/agent_config.rs b/crates/candler-harness/src/agent_config.rs index 6e5f2410..96a491b7 100644 --- a/crates/candler-harness/src/agent_config.rs +++ b/crates/candler-harness/src/agent_config.rs @@ -5,24 +5,14 @@ //! holds `instructions.global` and `hooks` as tables whose keys are harness ids, spelled as //! registered, and every such key must be one of [`HARNESS_IDS`]. -use candler_schemas::agent_config::{ClaudeCodeHooks, Instructions, OpenCodeHooks}; +use candler_schemas::agent_config::Instructions; use candler_schemas::field_path; use candler_schemas::primitives::FieldPath; use serde::de::DeserializeOwned; use serde_json::Value; use crate::driver::DriverError; -use crate::spec::{CLAUDE_CODE, Cell, HARNESS_IDS, OPENCODE}; - -/// The hooks the cell gives the harness it runs. -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub enum Hooks { - /// The hooks of a Claude Code cell. - ClaudeCode(ClaudeCodeHooks), - /// The hooks of an `OpenCode` cell. - OpenCode(OpenCodeHooks), -} +use crate::spec::{Cell, HARNESS_IDS}; fn invalid(path: &FieldPath, detail: impl Into) -> DriverError { DriverError::InvalidValue { @@ -76,13 +66,17 @@ pub fn instructions(cell: &Cell<'_>, harness: &str) -> Result, harness: &str) -> Result, DriverError> { +pub fn hooks( + cell: &Cell<'_>, + harness: &str, +) -> Result, DriverError> { let root = field_path!("hooks"); let Some(table) = cell.table_at(&root)? else { return Ok(None); @@ -92,10 +86,5 @@ pub fn hooks(cell: &Cell<'_>, harness: &str) -> Result, DriverErro return Err(DriverError::MissingValue { path: root }); }; // BORROW: .clone() copies the entry out of the table - let entry = entry.clone(); - match harness { - CLAUDE_CODE => read(entry, &root).map(|found| Some(Hooks::ClaudeCode(found))), - OPENCODE => read(entry, &root).map(|found| Some(Hooks::OpenCode(found))), - other => Err(invalid(&root, format!("`{other}` has no hooks"))), - } + read(entry.clone(), &root).map(Some) } diff --git a/crates/candler-harness/src/conformance.rs b/crates/candler-harness/src/conformance.rs index a9c89b4b..2c8b0dcd 100644 --- a/crates/candler-harness/src/conformance.rs +++ b/crates/candler-harness/src/conformance.rs @@ -16,7 +16,7 @@ use crate::driver::{DriverError, HarnessDriver, Plan}; use crate::reader::{FrameIn, TraceReader}; use crate::spec::{ Action, AgentSetting, Cell, CensusSource, CollectSpec, CommandSpec, DriverFact, EnvValue, - FileRoot, Framing, HttpMethod, InitReport, Observed, ObservedEnd, PendingState, PreparedFile, + Framing, HttpMethod, InitReport, Observed, ObservedEnd, PendingState, PreparedFile, ProcessExit, SessionClose, SessionRecord, StateKind, StopSpec, Workspace, }; @@ -748,26 +748,6 @@ fn check_capabilities( if let SessionClose::Action(action) = &spec.close { check_action("session", action, setup, owned)?; } - if let Some(hooks) = &spec.hooks { - let declared = declared_names(driver); - for file in &hooks.files { - if file.root != FileRoot::Home { - return Err(driver_failure( - "session", - format!("hook file {} is not rooted at the agent's home", file.path), - )); - } - check_file_references("session", file, &declared)?; - let text = String::from_utf8_lossy(&file.contents); - // BORROW: explicit .as_str() instead of Deref coercion - if setup.canaries.iter().any(|c| text.contains(c.as_str())) { - return Err(driver_failure( - "session", - format!("a secret value is in hook file {}", file.path), - )); - } - } - } } if !driver.fact(DriverFact::Census).is_refused() { let from_stream = driver.census_stream().is_some(); diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index 19260d21..fdf0734a 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -1157,14 +1157,11 @@ pub enum SessionClose { Action(Action), } -/// Where the observation hooks write and how the driver installs them. The hooks only observe: -/// they never block, decide or print. +/// Where the observation hooks write. The hooks only observe: they never block, decide or print. +/// The driver installs them as files of the plan, rooted at the agent's home. #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub struct HookSpec { - /// The files that install the hooks, rooted at the agent's home ([`FileRoot::Home`]), outside - /// the workspace. - pub files: Vec, /// The file the hooks append to, relative to the agent's home. pub log: RelPath, /// The raw stream that archives the log. @@ -1174,8 +1171,8 @@ pub struct HookSpec { impl HookSpec { /// A hook spec. #[must_use] - pub const fn new(files: Vec, log: RelPath, stream: StreamName) -> Self { - Self { files, log, stream } + pub const fn new(log: RelPath, stream: StreamName) -> Self { + Self { log, stream } } } diff --git a/crates/candler-harness/tests/it/guard_agent_config.rs b/crates/candler-harness/tests/it/guard_agent_config.rs index eae7a057..f18cdca7 100644 --- a/crates/candler-harness/tests/it/guard_agent_config.rs +++ b/crates/candler-harness/tests/it/guard_agent_config.rs @@ -3,9 +3,10 @@ use std::str::FromStr as _; -use candler_harness::agent_config::{Hooks, hooks, instructions}; +use candler_harness::agent_config::{hooks, instructions}; use candler_harness::driver::DriverError; use candler_harness::spec::Cell; +use candler_schemas::agent_config::{ClaudeCodeHooks, OpenCodeHooks}; use candler_schemas::primitives::FieldPath; use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::{Value, json}; @@ -43,12 +44,12 @@ fn a_cell_gives_each_harness_its_own_envelope() -> Res<()> { ("instructions.workspace", json!("workspace")), ])?; let view = Cell::new(&values); - let Some(Hooks::ClaudeCode(found)) = hooks(&view, "claude-code")? else { + let Some(found) = hooks::(&view, "claude-code")? else { return Err("claude code hooks".into()); }; assert_eq!(found.settings.map(Value::Object), Some(json!({"Stop": []}))); assert_eq!(found.files.len(), 1); - let Some(Hooks::OpenCode(found)) = hooks(&view, "opencode")? else { + let Some(found) = hooks::(&view, "opencode")? else { return Err("opencode hooks".into()); }; assert_eq!(found.plugins.len(), 1); @@ -71,7 +72,7 @@ fn a_cell_gives_each_harness_its_own_envelope() -> Res<()> { fn an_entry_that_does_not_fit_its_envelope_is_refused() -> Res<()> { let refused = |hooks_value: Value| -> Res { let values = cell(&[("hooks", hooks_value)])?; - match hooks(&Cell::new(&values), "claude-code") { + match hooks::(&Cell::new(&values), "claude-code") { Err(DriverError::InvalidValue { path, detail }) => { assert_eq!(path.to_string(), "hooks"); Ok(detail) diff --git a/docs/contract/configuration-paths.md b/docs/contract/configuration-paths.md index 24ed6658..b3327ef1 100644 --- a/docs/contract/configuration-paths.md +++ b/docs/contract/configuration-paths.md @@ -25,9 +25,9 @@ Core line: `v0.16.0`. | `tools.disallowed` | the path | experiment value | The tools the harness may not use. | tools disallowed: `permissions.deny` of `.claude/settings.json` | tools disallowed: a permission row {action, *, deny} per name, written after the allow rows | | `env` | the path | experiment value | The environment of the harness process: a table of variable name to text. | env: Candler: the core sets the cell's variables on the agent's process | env: Candler: the core sets the cell's variables on the agent's process | | `mcp` | the path and every path below it | experiment value | The MCP servers of a run; the names below are free. | MCP transport: stdio: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: local: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: http: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP transport: sse: an entry of `mcpServers` in `.mcp.json`, of type `sse`; MCP transport: remote: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP codemode: off: no key: Claude Code offers the server's tools directly; MCP codemode: on: no (Claude Code offers MCP tools directly; it has no code mode); MCP server name: the key of the server's `.mcp.json` entry | MCP transport: stdio: an `mcp` entry of type `local`; MCP transport: local: an `mcp` entry of type `local`; MCP transport: http: an `mcp` entry of type `remote`; MCP transport: sse: no (OpenCode documents no SSE transport; its `remote` is Streamable HTTP); MCP transport: remote: an `mcp` entry of type `remote`; MCP codemode: off: the `codemode` key of the `mcp` entry, `false`: the server's tools are direct tools; MCP codemode: on: the `codemode` key of the `mcp` entry, `true`: the server's tools are reached through `execute`, whose calls the trace records with empty `wrapped_calls`, so MCP calls made inside `execute` are not attributed and do not compare with Claude Code; MCP server name: the key of the `mcp` entry | -| `instructions.global` | the path and every path below it | experiment value | The global instruction text of each harness: a table of harness id, as registered, to text; the keys are free. | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | -| `instructions.workspace` | the path | experiment value | The instruction text at the root of the workspace. | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | -| `hooks` | the path and every path below it | experiment value | The hooks of each harness: a table of harness id, as registered, to its `settings` table and `files` table (Claude Code) or its `plugins` table (OpenCode); the keys are free. | hooks: no (this driver installs no instruction text or hook) | hooks: no (this driver installs no instruction text or hook) | +| `instructions.global` | the path and every path below it | experiment value | The global instruction text of each harness: a table of harness id, as registered, to text; the keys are free. | instructions: global: `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither); instructions: workspace: `CLAUDE.md` at the workspace root, mounted read-only | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | +| `instructions.workspace` | the path | experiment value | The instruction text at the root of the workspace. | instructions: global: `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither); instructions: workspace: `CLAUDE.md` at the workspace root, mounted read-only | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | +| `hooks` | the path and every path below it | experiment value | The hooks of each harness: a table of harness id, as registered, to its `settings` table and `files` table (Claude Code) or its `plugins` table (OpenCode); the keys are free. | hooks: the `hooks` key of `.claude/settings.json`, with the hook files under `.claude/hooks/` | hooks: no (this driver installs no instruction text or hook) | | `permission_mode` | the path | experiment value | The permission mode the harness runs in. | permission mode: default: `--permission-mode ` on the command line; permission mode: acceptEdits: `--permission-mode ` on the command line; permission mode: plan: `--permission-mode ` on the command line; permission mode: bypassPermissions: `--permission-mode ` on the command line; permission mode: auto: `--permission-mode ` on the command line; permission mode: dontAsk: `--permission-mode ` on the command line | permission mode: default: no (Claude Code's default mode allows reads and a built-in, non-configurable set of read-only shell commands that its own parser decides, and denies the rest in a headless run. OpenCode without `--auto` also rejects what no rule allows, but its shell rows are wildcards on the text of each parsed command, which approximate that set without being it); permission mode: acceptEdits: no (Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, rm, rmdir, mv, cp and sed, inside the working directory only. OpenCode's shell resource is the command's text, which knows no working directory, so "inside it" cannot be written as a rule); permission mode: plan: no (Claude Code's plan mode reads and runs read-only shell commands (a built-in, non-configurable set its own parser decides). The OpenCode ruleset that is certainly read-only (the `explore` agent's: deny everything, allow read, glob, grep, webfetch, websearch, skill) denies the shell altogether, and a wildcard on command text cannot express the read-only set; the stock `plan` agent is not read-only once a global rule follows it (the last match wins) and its `subagent` child can edit); permission mode: bypassPermissions: `--auto` on the command line: every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` answers the one pending ask (`.env` reads) with once, which a headless run needs; permission mode: auto: no (Claude Code's auto mode has a model classifier review each action, such as a shell command or a network request, before it runs. OpenCode has no classifier, and a ruleset decides by the action's text alone); permission mode: dontAsk: no (Claude Code's dontAsk mode denies every call that would prompt, so it allows the allow rules plus reads and the built-in, non-configurable set of read-only shell commands its own parser decides. OpenCode's shell rows are wildcards on the text of each parsed command, which approximate that set without being it) | | `request.harness` | the path | request key | The harness the run uses. | Candler only | Candler only | | `request.treatment` | the path | request key | The treatment the run applies. | Candler only | Candler only | diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index 421c4613..f474da29 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -48,9 +48,9 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | turn cap | `--max-turns` on the command line | no (`agents..steps` makes the last request a tool-less one with an injected prompt and ends the run as completed (the `oc_step_cap` fixture), where Claude Code ends the run with `error_max_turns`, so the cap class would be lost and the model's last turn changed) | | cost cap | `--max-budget-usd` on the command line | no (OpenCode has no cost cap) | | session mode | stream-json over an open stdin, one turn per message | no (OpenCode runs no session: its trace comes from the export after the run) | -| instructions: global | no (this driver installs no instruction text or hook) | no (this driver installs no instruction text or hook) | -| instructions: workspace | no (this driver installs no instruction text or hook) | no (this driver installs no instruction text or hook) | -| hooks | no (this driver installs no instruction text or hook) | no (this driver installs no instruction text or hook) | +| instructions: global | `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither) | no (this driver installs no instruction text or hook) | +| instructions: workspace | `CLAUDE.md` at the workspace root, mounted read-only | no (this driver installs no instruction text or hook) | +| hooks | the `hooks` key of `.claude/settings.json`, with the hook files under `.claude/hooks/` | no (this driver installs no instruction text or hook) | | gateway route | Candler: gateway, address in `ANTHROPIC_BASE_URL` | Candler: gateway, address in `CANDLER_GATEWAY_URL` | | authoritative trace | yes | Candler: collects `export` after the run | | graceful stop | SIGTERM ends the sessions cleanly | an interrupt request to the `serve` child, then SIGTERM to the client | From 3e86aeacf197cf4c1bfb9d18da20849e4709e0a2 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:25:42 +0900 Subject: [PATCH 36/69] feat(api): record loaded memory files on Claude Code A run's census gains census.instructions, a list of {path, scope} with scope user or project, one harness-neutral value. A driver reads its own source through HarnessDriver::loaded_instructions, and the core feeds it every collected stream. Claude Code collects the hook log from the agent's home on the host (CollectSpec::Home) in headless and session runs alike, and lists its InstructionsLoaded lines. config_check runs claude doctor and reads an Invalid settings section as a rejection. Co-Authored-By: Claude Sonnet 5.5 --- .../src/runner/evidence/census.rs | 18 ++++- crates/candler-core/src/runner/exec/gather.rs | 23 ++++++ crates/candler-core/src/runner/exec/mod.rs | 12 ++- crates/candler-core/tests/it/guard_session.rs | 34 +++++++++ .../tests/it/support/session_rig.rs | 5 +- .../candler-harness-claude-code/src/driver.rs | 34 +++++++-- .../src/session.rs | 58 +++++++++++++- .../tests/fixtures/instructions/hooks.jsonl | 4 + .../tests/it/guard_claude_code_driver.rs | 75 +++++++++++++++++++ crates/candler-harness/src/conformance.rs | 2 +- crates/candler-harness/src/driver.rs | 13 +++- crates/candler-harness/src/spec.rs | 45 +++++++++++ docs/contract/driver-traits.md | 1 + docs/contract/harness-capabilities.md | 2 +- 14 files changed, 307 insertions(+), 19 deletions(-) create mode 100644 crates/candler-harness-claude-code/tests/fixtures/instructions/hooks.jsonl diff --git a/crates/candler-core/src/runner/evidence/census.rs b/crates/candler-core/src/runner/evidence/census.rs index 84887885..c3c2b7ec 100644 --- a/crates/candler-core/src/runner/evidence/census.rs +++ b/crates/candler-core/src/runner/evidence/census.rs @@ -1,6 +1,6 @@ //! The census of a run: the tools the agent saw at its start, as the harness's driver reports them. -use candler_harness::spec::{CensusSource, InitReport}; +use candler_harness::spec::{CensusSource, InitReport, LoadedFile}; use candler_schemas::primitives::{FieldPath, NameToken}; use candler_schemas::values::{JsonValue, MeasuredValue, ValueSource}; use serde_json::Value; @@ -80,3 +80,19 @@ pub fn census(init: Option<&InitReport>) -> Result, CensusErr } Ok(values) } + +/// The census value `census.instructions` of a run: the instruction files its harness loaded, each +/// as `{path, scope}` with scope `user` or `project`, in the order the harness loaded them. A run +/// whose harness showed no loaded file records none: the value is unrecorded, never an empty list. +/// +/// # Errors +/// [`CensusError::Value`] when the value cannot be built. +pub fn census_instructions(loaded: &[LoadedFile]) -> Result, CensusError> { + if loaded.is_empty() { + return Ok(None); + } + let value = serde_json::to_value(loaded).map_err(|error| CensusError::Value { + detail: error.to_string(), // BORROW: .to_string() gives owned text + })?; + measured("census.instructions", value).map(Some) +} diff --git a/crates/candler-core/src/runner/exec/gather.rs b/crates/candler-core/src/runner/exec/gather.rs index ab55f2ef..7fb28913 100644 --- a/crates/candler-core/src/runner/exec/gather.rs +++ b/crates/candler-core/src/runner/exec/gather.rs @@ -181,6 +181,29 @@ pub async fn collect_commands( found } +/// Reads each file of `home` the driver's collect specs name, in order, and returns what each +/// holds under its stream name. A file the run never wrote leaves nothing; one that cannot be read +/// is that spec's own failed result. +#[must_use] +pub fn collect_home(home: &Path, specs: &[CollectSpec]) -> Vec { + let mut found = Vec::new(); + for spec in specs { + if let CollectSpec::Home { path, name, .. } = spec { + match fs::read(home.join(path.as_str())) { + // BORROW: explicit .as_str() + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + read => found.push(Collected { + name: name.clone(), // BORROW: the result owns the stream name + output: read.map_err(|error| IsolationError::Plan { + detail: format!("cannot read {path} of the agent's home: {error}"), + }), + }), + } + } + } + found +} + /// A stream stored as a raw file and read by a reader. #[non_exhaustive] pub struct StreamRead { diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index b6e87a8f..e91242e9 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -34,13 +34,13 @@ pub use self::cell::{CellRun, ExecError}; use self::collect::finish_attempt; use self::ends::{EndInput, TraceFacts, classify_end}; use self::gather::{ - collect_commands, collect_outputs, read_stream, resolved_record, spent, store_stream, - with_context_start, + collect_commands, collect_home, collect_outputs, read_stream, resolved_record, spent, + store_stream, with_context_start, }; use self::seal::{RawStreamFile, seal_run}; use self::session::{SessionHandle, SessionRun, monotonic_clock, session_config}; use self::spawn::{Started, live_observer_with, require_isolation, start_attempt}; -use super::evidence::census::census; +use super::evidence::census::{census, census_instructions}; use super::evidence::leak::input_leak; use super::evidence::provenance::provenance_values; use super::evidence::run::{RunFacts, run_values}; @@ -642,7 +642,8 @@ async fn drive( let live_view = handle.as_ref().map(spawn::LiveHandle::observed); let observed_now = live_view.clone().unwrap_or_default(); // BORROW: the view is read again after the finish let specs = rt.driver.collect(&workspace, &observed_now); - let collected = collect_commands(isolation.as_ref(), &container, &specs).await; + let mut collected = collect_commands(isolation.as_ref(), &container, &specs).await; + collected.extend(collect_home(&home_dir, &specs)); let finished = finish_attempt( isolation.as_ref(), &container, @@ -678,11 +679,13 @@ async fn drive( let declared: Vec = candler_harness::mcp::servers(&view)? .map(|servers| servers.into_keys().collect()) .unwrap_or_default(); + let mut loaded = Vec::new(); for item in collected { let Ok(bytes) = item.output else { collect_ok = false; continue; }; + loaded.extend(rt.driver.loaded_instructions(&item.name, &bytes)); match rt.driver.offline_reader(&item.name, &declared) { Some(reader) => { let Ok(read) = read_stream(&frames, &item.name, &bytes, reader) else { @@ -822,6 +825,7 @@ async fn drive( } else { census(observed.init.as_ref().or(gateway_init.as_ref())).unwrap_or_default() }; + measured.extend(census_instructions(&loaded).ok().flatten()); let gateway_failed = match &rt.gateway { Some(gateway) => gateway diff --git a/crates/candler-core/tests/it/guard_session.rs b/crates/candler-core/tests/it/guard_session.rs index 958fc88d..16bdc6ca 100644 --- a/crates/candler-core/tests/it/guard_session.rs +++ b/crates/candler-core/tests/it/guard_session.rs @@ -1493,3 +1493,37 @@ async fn session_hooks_leave_the_run_as_it_is() { file_list(&hooked.run_dir) ); } + +/// Guards: invariant 7 — a run whose hook log shows instruction files loaded records them as the +/// census value `census.instructions`, through the driver's own reader of the log and the core's +/// collection of it. The log is the recorded one of the Claude Code driver's fixtures. +/// Oracle: the fixture's `InstructionsLoaded` lines, and the paths and scopes written by hand. +/// Bite: skip collecting the log, or record the scope of the workspace file as `user`. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn session_census_names_the_instruction_files_the_hooks_saw() { + let log = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../candler-harness-claude-code/tests/fixtures/instructions/hooks.jsonl"); + let loaded: Vec = std::fs::read_to_string(log) + .expect("the recorded hook log") + .lines() + .filter(|line| line.contains("\"hook_event_name\":\"InstructionsLoaded\"")) + .flat_map(|line| [rig::hook(line), rig::sleep(0.01)]) + .collect(); + assert_eq!(loaded.len(), 6, "three loaded lines, each then a pause"); + let cell = rig::cell_values(&[ + ("runner.idle_s", j!("none")), + ("budget.per_run.wall_s", j!(4)), + ]); + let mut steps = loaded; + steps.extend(rig::replay_of("c1", &BTreeMap::new())); + steps.push(rig::wait_eof(None)); + let ran = rig::run(&steps, &cell, rig::Driver::new(true), None).await; + let _ = ran.outcome(); + assert_eq!( + ran.measured("census.instructions"), + Some(j!([ + {"path": "/home/agent/.claude/CLAUDE.md", "scope": "user"}, + {"path": "CLAUDE.md", "scope": "project"}, + ])) + ); +} diff --git a/crates/candler-core/tests/it/support/session_rig.rs b/crates/candler-core/tests/it/support/session_rig.rs index 73fdb57d..305f1caa 100644 --- a/crates/candler-core/tests/it/support/session_rig.rs +++ b/crates/candler-core/tests/it/support/session_rig.rs @@ -29,7 +29,7 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ AgentSetting, Answer, Cell, CollectSpec, CommandSpec, DriverFact, GatewayEnv, HarnessId, - Observed, ProcessExit, SessionTracker, StatePath, StopSpec, Workspace, + LoadedFile, Observed, ProcessExit, SessionTracker, StatePath, StopSpec, Workspace, }; use candler_harness_claude_code::driver::ClaudeCodeDriver; use candler_schemas::execution::Comparable; @@ -303,6 +303,9 @@ impl HarnessDriver for Driver { fn collect(&self, workspace: &Workspace<'_>, observed: &Observed) -> Vec { self.inner.collect(workspace, observed) } + fn loaded_instructions(&self, stream: &StreamName, bytes: &[u8]) -> Vec { + self.inner.loaded_instructions(stream, bytes) + } } /// What the run left of the container: an exited one that reports exit code 0. diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index c38dc62c..747c50cc 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -11,8 +11,8 @@ use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ AgentSetting, Answer, BaseImage, CLAUDE_CODE, Cell, CheckVerdict, CollectSpec, CommandSpec, - DriverFact, EffortLevel, GatewayEnv, HarnessId, InstructionScope, Observed, PermissionMode, - Prepared, ProcessExit, SessionTracker, StopSignal, StopSpec, Workspace, + DriverFact, EffortLevel, GatewayEnv, HarnessId, InstructionScope, LoadedFile, Observed, + PermissionMode, Prepared, ProcessExit, SessionTracker, StopSignal, StopSpec, Workspace, }; use candler_schemas::execution::paths; use candler_schemas::name; @@ -317,8 +317,8 @@ impl HarnessDriver for ClaudeCodeDriver { DriverFact::Census => Answer::Mapped { construct: "Claude Code's `system/init` event lists the tools", }, - DriverFact::ConfigCheck => Answer::Refused { - reason: "this driver installs no configuration file to check", + DriverFact::ConfigCheck => Answer::Mapped { + construct: "`claude doctor` in the workspace, whose `Invalid settings` section lists a rejected file or a skipped entry", }, DriverFact::UnsetPermissionMode => Answer::Mapped { construct: "`--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it", @@ -328,12 +328,31 @@ impl HarnessDriver for ClaudeCodeDriver { fn config_check(&self, plan: &Plan) -> Option { let _ = plan; - None + // The exit status is 0 whatever it finds, and four install-method warnings always print: + // only the `Invalid settings` section says something of the files. + Some(CommandSpec::new( + PROGRAM.to_owned(), + vec!["doctor".to_owned()], + )) // BORROW: .to_owned() makes the owned arguments } fn read_config_check(&self, output: &[u8]) -> CheckVerdict { - let _ = output; - CheckVerdict::Clean + let text = String::from_utf8_lossy(output); + let mut section = text + .lines() + .skip_while(|line| !line.contains("Invalid settings")) + .take_while(|line| !line.trim().is_empty()) + .peekable(); + if section.peek().is_none() { + return CheckVerdict::Clean; + } + CheckVerdict::Rejected { + output: section.collect::>().join("\n"), + } + } + + fn loaded_instructions(&self, stream: &StreamName, bytes: &[u8]) -> Vec { + session::loaded(stream, bytes) } fn workspace_instruction_file(&self) -> &'static str { @@ -436,6 +455,7 @@ impl HarnessDriver for ClaudeCodeDriver { .into_iter() .map(|pattern| CollectSpec::file(format!("!{pattern}"))), ); + specs.extend(session::log_collect().ok()); specs } } diff --git a/crates/candler-harness-claude-code/src/session.rs b/crates/candler-harness-claude-code/src/session.rs index c23e033d..ddd38041 100644 --- a/crates/candler-harness-claude-code/src/session.rs +++ b/crates/candler-harness-claude-code/src/session.rs @@ -32,8 +32,8 @@ use std::str::FromStr as _; use candler_harness::driver::DriverError; use candler_harness::spec::{ - CommandSpec, HookSpec, PendingItem, PendingKind, PendingState, PreparedFile, SessionClose, - SessionRecord, SessionSpec, SessionTracker, + CollectSpec, CommandSpec, HookSpec, LoadedFile, LoadedScope, PendingItem, PendingKind, + PendingState, PreparedFile, SessionClose, SessionRecord, SessionSpec, SessionTracker, }; use candler_schemas::primitives::RelPath; use candler_schemas::raw::StreamName; @@ -50,6 +50,8 @@ const SETTINGS: &str = ".candler/settings.json"; const HOOK_LOG: &str = ".candler/hooks.jsonl"; /// The name of the raw stream that archives the hook log. const HOOK_STREAM: &str = "hooks"; +/// The name of the raw stream that archives the `InstructionsLoaded` lines of the hook log. +const LOADED_STREAM: &str = "instructions_loaded"; /// The hook events the driver installs. const HOOK_EVENTS: [&str; 3] = ["InstructionsLoaded", "Stop", "SessionEnd"]; @@ -99,6 +101,58 @@ fn hooks() -> Result { Ok(HookSpec::new(log, stream)) } +/// What the core collects of the hook log after a run, headless or session: the log, read from +/// the agent's home and archived as the stream `instructions_loaded`. +pub(crate) fn log_collect() -> Result { + let stream = StreamName::from_str(LOADED_STREAM) + .map_err(|error| invalid(LOADED_STREAM, error.to_string()))?; // BORROW: .to_string() gives owned text + let log = RelPath::from_str(HOOK_LOG).map_err(|error| invalid(HOOK_LOG, error.to_string()))?; // BORROW: .to_string() gives owned text + Ok(CollectSpec::home(log, stream)) +} + +/// The instruction files the hook log of a run shows loaded, in the order they loaded, each once. +/// `bytes` is the stream `stream`; any other stream lists nothing. A file of a user's own +/// (`memory_type` `User`) is listed by its absolute path; a file of the workspace (`Project` or +/// `Local`) by its path from the `cwd` of the payload. A line that is not an `InstructionsLoaded` +/// payload, or whose memory type is another one, is skipped. +pub(crate) fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { + if stream.as_str() != LOADED_STREAM { + return Vec::new(); + } + let mut files: Vec = Vec::new(); + for line in bytes.split(|byte| *byte == b'\n') { + let Ok(Value::Object(record)) = serde_json::from_slice::(line) else { + continue; + }; + let Some(payload) = record.get("payload").and_then(Value::as_object) else { + continue; + }; + if text_of(payload, "hook_event_name") != "InstructionsLoaded" { + continue; + } + let scope = match text_of(payload, "memory_type") { + "User" => LoadedScope::User, + "Project" | "Local" => LoadedScope::Project, + _ => continue, + }; + let path = text_of(payload, "file_path"); + let cwd = text_of(payload, "cwd"); + let from_cwd = path + .strip_prefix(cwd) + .and_then(|rest| rest.strip_prefix('/')) + .filter(|_| !cwd.is_empty()); + let path = match (scope, from_cwd) { + (LoadedScope::Project, Some(relative)) => relative, + _ => path, + }; + let file = LoadedFile::new(path.to_owned(), scope); // BORROW: .to_owned() gives the file its own path + if !path.is_empty() && !files.contains(&file) { + files.push(file); + } + } + files +} + /// The session of a cell: stdin open, the prompt as the first message, closed by end of input, with /// the observation hooks of the command line's settings file logging to the hook log. /// diff --git a/crates/candler-harness-claude-code/tests/fixtures/instructions/hooks.jsonl b/crates/candler-harness-claude-code/tests/fixtures/instructions/hooks.jsonl new file mode 100644 index 00000000..8f62ab4b --- /dev/null +++ b/crates/candler-harness-claude-code/tests/fixtures/instructions/hooks.jsonl @@ -0,0 +1,4 @@ +{"written_ns":1794439990100000000,"payload":{"session_id":"e10c5a1a-d40d-4ea6-910d-4a7cd75ace6c","transcript_path":"/home/agent/.claude/projects/-work/e10c5a1a-d40d-4ea6-910d-4a7cd75ace6c.jsonl","cwd":"/work","hook_event_name":"InstructionsLoaded","file_path":"/home/agent/.claude/CLAUDE.md","memory_type":"User","load_reason":"session_start"}} +{"written_ns":1794439990200000000,"payload":{"session_id":"e10c5a1a-d40d-4ea6-910d-4a7cd75ace6c","transcript_path":"/home/agent/.claude/projects/-work/e10c5a1a-d40d-4ea6-910d-4a7cd75ace6c.jsonl","cwd":"/work","hook_event_name":"InstructionsLoaded","file_path":"/work/CLAUDE.md","memory_type":"Project","load_reason":"session_start"}} +{"written_ns":1794439990300000000,"payload":{"session_id":"e10c5a1a-d40d-4ea6-910d-4a7cd75ace6c","cwd":"/work","hook_event_name":"InstructionsLoaded","file_path":"/work/CLAUDE.md","memory_type":"Project","load_reason":"session_start"}} +{"written_ns":1794439999000000000,"payload":{"session_id":"e10c5a1a-d40d-4ea6-910d-4a7cd75ace6c","cwd":"/work","hook_event_name":"Stop","stop_hook_active":false}} diff --git a/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs b/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs index b9c50644..f85793b5 100644 --- a/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs +++ b/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs @@ -745,3 +745,78 @@ fn a_payload_cannot_reach_beyond_hooks_and_the_hooks_directory() -> Res<()> { } Ok(()) } + +/// Guards: invariant 7 — the instruction files the hook log of a run shows loaded, read through the +/// driver from a recorded `hooks.jsonl`, reach the census as `census.instructions`: the global +/// file as `user`, the workspace file from its working directory as `project`, once each, and the +/// `Stop` line not at all; a run with none records nothing. +/// Oracle: the fixture, written from the payloads the probe recorded, and the expected value by +/// hand. +/// Bite: list the `Stop` line, keep the absolute workspace path, or record an empty list. +#[test] +fn the_census_names_the_instruction_files_the_hook_log_shows() -> Res<()> { + use candler_core::runner::evidence::census::census_instructions; + let driver = ClaudeCodeDriver::new(); + let bytes = fs::read( + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/instructions/hooks.jsonl"), + )?; + let stream = driver + .collect(&Workspace::new(Path::new("/work")), &Observed::default()) + .into_iter() + .find_map(|spec| { + if let CollectSpec::Home { name, .. } = spec { + Some(name) + } else { + None + } + }) + .ok_or("the driver collects no hook log")?; + let loaded = driver.loaded_instructions(&stream, &bytes); + let value = census_instructions(&loaded)?.ok_or("nothing recorded")?; + assert_eq!(value.path().to_string(), "census.instructions"); + assert_eq!( + serde_json::to_value(value.value())?, + json!([ + {"path": "/home/agent/.claude/CLAUDE.md", "scope": "user"}, + {"path": "CLAUDE.md", "scope": "project"}, + ]) + ); + let other: candler_schemas::raw::StreamName = "stdout".parse()?; + assert_eq!(driver.loaded_instructions(&other, &bytes), []); + assert!(census_instructions(&[])?.is_none()); + Ok(()) +} + +/// Guards: the config check — `claude doctor` runs, an `Invalid settings` section with its bullets +/// is a rejection whatever the exit status and the install-method warnings, and its absence is a +/// clean check. +/// Oracle: output written by hand from the lines the probe quoted. +/// Bite: reject on the `warnings found` block, or ignore a warning under the heading. +#[test] +fn the_config_check_reads_the_invalid_settings_section() -> Res<()> { + use candler_harness::spec::CheckVerdict; + let driver = ClaudeCodeDriver::new(); + let cell = values("default")?; + let plan = driver.plan(&Cell::new(&cell), &Workspace::new(Path::new("/work")))?; + assert_eq!( + driver.config_check(&plan).ok_or("no check")?.argv(), + ["claude", "doctor"] + ); + let clean = + b"Diagnostics\n Remote Control: off\n\n 4 warnings found\n - Multiple installations\n"; + assert_eq!(driver.read_config_check(clean), CheckVerdict::Clean); + let bad = b"Diagnostics\n\nInvalid settings\n - /work/.claude/settings.json: Invalid or malformed JSON\n\n 4 warnings found\n - Multiple installations\n"; + assert_eq!( + driver.read_config_check(bad), + CheckVerdict::Rejected { + output: "Invalid settings\n - /work/.claude/settings.json: Invalid or malformed JSON" + .to_owned() + } + ); + let warn = b"Invalid settings\n - hooks.NoSuchEvent: Unknown hook event \"NoSuchEvent\" was ignored.\n"; + assert!(matches!( + driver.read_config_check(warn), + CheckVerdict::Rejected { .. } + )); + Ok(()) +} diff --git a/crates/candler-harness/src/conformance.rs b/crates/candler-harness/src/conformance.rs index 2c8b0dcd..c80fd11c 100644 --- a/crates/candler-harness/src/conformance.rs +++ b/crates/candler-harness/src/conformance.rs @@ -1043,7 +1043,7 @@ fn check_collect( } } CollectSpec::Exec { spec, .. } => check_command("collect", spec, setup, owned)?, - CollectSpec::File { .. } => {} + CollectSpec::File { .. } | CollectSpec::Home { .. } => {} } } Ok(()) diff --git a/crates/candler-harness/src/driver.rs b/crates/candler-harness/src/driver.rs index 412d130f..78b5e56a 100644 --- a/crates/candler-harness/src/driver.rs +++ b/crates/candler-harness/src/driver.rs @@ -13,8 +13,8 @@ use crate::reader::TraceReader; use crate::skills::SkillTree; use crate::spec::{ AgentSetting, Answer, BaseImage, Cell, CheckVerdict, CollectSpec, CommandSpec, - CommandSpecError, DriverFact, GatewayEnv, HarnessId, Observed, Prepared, PreparedFile, - ProcessExit, SessionSpec, SessionTracker, StatePath, StopSpec, Workspace, + CommandSpecError, DriverFact, GatewayEnv, HarnessId, LoadedFile, Observed, Prepared, + PreparedFile, ProcessExit, SessionSpec, SessionTracker, StatePath, StopSpec, Workspace, }; /// Why a driver could not answer. @@ -243,6 +243,15 @@ pub trait HarnessDriver: Send + Sync { None } + /// The instruction files the harness loaded, as `stream` shows them: `bytes` is the stream + /// the core collected under `stream` after the run, or the gateway's record of it. A driver + /// reads the streams it knows and lists nothing for any other. An empty list means no file was + /// observed, and the census records nothing. + fn loaded_instructions(&self, stream: &StreamName, bytes: &[u8]) -> Vec { + let _ = (stream, bytes); + Vec::new() + } + /// Where a treatment's skill tree comes from and where the harness reads it. fn skills(&self) -> SkillTree; diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index fdf0734a..1cd49724 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -468,6 +468,15 @@ pub enum CollectSpec { /// The name of the stream that archives the output. name: StreamName, }, + /// The file at `path` under the agent's home, which the core reads on the host after the run + /// and archives as the stream `name`. A run that never wrote the file leaves no stream. + #[non_exhaustive] + Home { + /// The file's path, relative to the agent's home. + path: RelPath, + /// The name of the stream that archives the file. + name: StreamName, + }, } impl CollectSpec { @@ -489,6 +498,12 @@ impl CollectSpec { pub const fn exec(spec: CommandSpec, name: StreamName) -> Self { Self::Exec { spec, name } } + + /// The file at `path` under the agent's home, archived as the stream `name`. + #[must_use] + pub const fn home(path: RelPath, name: StreamName) -> Self { + Self::Home { path, name } + } } /// How a driver meets one key. @@ -667,6 +682,36 @@ pub enum CheckVerdict { }, } +/// Whose instruction file a harness loaded. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)] +#[serde(rename_all = "lowercase")] +#[non_exhaustive] +pub enum LoadedScope { + /// The file is the agent's own, from its home. + User, + /// The file belongs to the workspace. + Project, +} + +/// An instruction file the harness loaded at the start of a run, as the census records it. +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)] +#[non_exhaustive] +pub struct LoadedFile { + /// The path the harness loaded: relative to the workspace for a workspace file, absolute + /// otherwise. + pub path: String, + /// Whose file it is. + pub scope: LoadedScope, +} + +impl LoadedFile { + /// A loaded file. + #[must_use] + pub const fn new(path: String, scope: LoadedScope) -> Self { + Self { path, scope } + } +} + /// What an experiment sets that reaches the agent. A key whose values form a closed set carries /// the value, so a new value is a compile error in every driver. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/docs/contract/driver-traits.md b/docs/contract/driver-traits.md index 52f91d40..8089cad2 100644 --- a/docs/contract/driver-traits.md +++ b/docs/contract/driver-traits.md @@ -33,6 +33,7 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | `HarnessDriver::gateway` | `(&self) -> Option` | optional | `None` | | `HarnessDriver::state_paths` | `(&self) -> Vec` | optional | `Vec::new()` | | `HarnessDriver::census_stream` | `(&self) -> Option` | optional | `None` | +| `HarnessDriver::loaded_instructions` | `(&self, stream: &StreamName, bytes: &[u8]) -> Vec` | optional | `Vec::new()` | | `HarnessDriver::skills` | `(&self) -> SkillTree` | required | - | | `HarnessDriver::base_image` | `(&self) -> BaseImage` | required | - | | `HarnessDriver::offline_streams` | `(&self) -> Vec` | optional | `Vec::new()` | diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index f474da29..3835e96c 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -59,7 +59,7 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | execution outside the child | no (tools run in the child process) | tools run in the `serve` child, which the stop interrupts first | | census source | Claude Code's `system/init` event lists the tools | Candler: the tools the gateway offered the model in its first request | | permission mode when none is set | `--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it | Candler: the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode | -| config check | no (this driver installs no configuration file to check) | no (this driver installs no configuration file to check) | +| config check | `claude doctor` in the workspace, whose `Invalid settings` section lists a rejected file or a skipped entry | no (this driver installs no configuration file to check) | ## Refusals From b956e0fc63267a4aaa3ec31c8331b966f8105287 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:31:45 +0900 Subject: [PATCH 37/69] feat(api): refuse a cell its harness rejects Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/isolation/testing.rs | 43 ++- .../src/jobs/orchestrate/config.rs | 233 +++++++++++++ .../candler-core/src/jobs/orchestrate/mod.rs | 6 + .../src/jobs/orchestrate/servers.rs | 53 ++- crates/candler-core/src/jobs/refusal.rs | 27 +- .../src/runner/evidence/provenance.rs | 17 +- crates/candler-core/src/runner/exec/cell.rs | 4 + crates/candler-core/src/runner/exec/mod.rs | 6 +- .../tests/it/guard_config_check.rs | 326 ++++++++++++++++++ .../tests/it/guard_refusal_codes.rs | 22 ++ .../tests/it/guard_server_check.rs | 90 +---- crates/candler-core/tests/it/main.rs | 1 + .../tests/it/support/job_orchestrate.rs | 97 +++++- 13 files changed, 826 insertions(+), 99 deletions(-) create mode 100644 crates/candler-core/src/jobs/orchestrate/config.rs create mode 100644 crates/candler-core/tests/it/guard_config_check.rs diff --git a/crates/candler-core/src/isolation/testing.rs b/crates/candler-core/src/isolation/testing.rs index b67c9e16..cf3f2718 100644 --- a/crates/candler-core/src/isolation/testing.rs +++ b/crates/candler-core/src/isolation/testing.rs @@ -467,7 +467,8 @@ impl JobView for FakeJobView { } /// An [`Isolation`] that answers a start probe from a script and passes everything else to the -/// isolation it wraps. It records each probed command and each run request. +/// isolation it wraps. It records each probed command, each command run for its output, and each +/// run request with the mounts of its container. pub struct ProbingIsolation { // TRAIT_OBJECT: the wrapped isolation is the job's own, or a fake inner: Arc, @@ -476,6 +477,9 @@ pub struct ProbingIsolation { runs: Mutex, eof_exits: Mutex>, needs: Mutex>, + prints: Mutex>, + executed: Mutex, Vec)>>, + run_mounts: Mutex>>, } impl ProbingIsolation { @@ -490,9 +494,31 @@ impl ProbingIsolation { runs: Mutex::new(0), eof_exits: Mutex::new(BTreeMap::new()), needs: Mutex::new(BTreeSet::new()), + prints: Mutex::new(BTreeMap::new()), + executed: Mutex::new(Vec::new()), + run_mounts: Mutex::new(Vec::new()), } } + /// Makes a command run for its output whose program is `program` print `output`; one no + /// answer names prints nothing. + pub fn print(&self, program: &str, output: &str) { + held(&self.prints).insert(program.to_owned(), output.to_owned()); // BORROW: the script owns its words + } + + /// The commands run for their output so far, as their words, each with the mounts of the + /// container it ran in. + #[must_use] + pub fn executed(&self) -> Vec<(Vec, Vec)> { + held(&self.executed).clone() // BORROW: the caller reads its own copy + } + + /// The mounts of the container of each run request, in order. + #[must_use] + pub fn run_mounts(&self) -> Vec> { + held(&self.run_mounts).clone() // BORROW: the caller reads its own copy + } + /// Answers a probe whose command starts with the program `program` with `answer`. pub fn answer(&self, program: &str, answer: super::StartProbe) { held(&self.answers).insert(program.to_owned(), answer); @@ -541,9 +567,24 @@ impl super::Isolation for ProbingIsolation { outputs: super::RunOutputs, ) -> BoxFuture<'a, Result> { *held(&self.runs) += 1; + held(&self.run_mounts).push(plan.mounts.clone()); // BORROW: the log owns the mounts self.inner.run_request(plan, command, marker, key, outputs) } + fn collect_exec<'a>( + &'a self, + plan: &'a super::model::ContainerPlan, + command: &'a candler_harness::spec::CommandSpec, + ) -> BoxFuture<'a, Result, super::IsolationError>> { + held(&self.executed).push((command.argv().to_vec(), plan.mounts.clone())); // BORROW: the log owns the words and the mounts + let printed = command + .argv() + .first() + .and_then(|program| held(&self.prints).get(program).cloned()) // BORROW: the caller owns the output + .unwrap_or_default(); + Box::pin(async move { Ok(printed.into_bytes()) }) + } + fn collect_and_destroy<'a>( &'a self, plan: &'a super::model::ContainerPlan, diff --git a/crates/candler-core/src/jobs/orchestrate/config.rs b/crates/candler-core/src/jobs/orchestrate/config.rs new file mode 100644 index 00000000..41393b98 --- /dev/null +++ b/crates/candler-core/src/jobs/orchestrate/config.rs @@ -0,0 +1,233 @@ +//! The start check of the files Candler installs for a harness: before the job's first run, each +//! distinct set of installed files is given to the harness's own check, in a container without +//! network that is the one a run of the cell gets, and a finding refuses the job. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::Path; +use std::sync::Arc; + +use candler_harness::agent_config; +use candler_harness::driver::{DriverError, Plan}; +use candler_harness::spec::{Cell, CheckVerdict, FileRoot, PreparedFile, Workspace}; +use candler_schemas::primitives::Digest; +use candler_schemas::refusal::pointer_of; + +use super::servers::{ServerCheckError, stage_container}; +use super::session::image_of; +use crate::isolation::Isolation; +use crate::runner::Runtime; +use crate::runner::plan::{CellId, RunPlan}; + +/// Why the check refused the job. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum ConfigCheckError { + /// The harness's own check reports a finding for what Candler installed, or the driver cannot + /// describe the cell. + #[error(transparent)] + Driver(#[from] DriverError), + /// The check could not run. + #[error(transparent)] + Check(#[from] ServerCheckError), +} + +/// The harness, the image and the digest of everything the check reads: the cells that share all +/// three share one verdict. +type GroupKey = (String, Option, Digest); + +/// The distinct keys, each with the first plan of such a cell and every cell that has the key. +type Groups<'a> = BTreeMap)>; + +fn failed(detail: &impl ToString) -> ConfigCheckError { + ConfigCheckError::Check(ServerCheckError::ServerCheck { + detail: detail.to_string(), // BORROW: .to_string() gives owned text + }) +} + +/// The files `plan` installs, whichever root they are written under. +fn installed_files(plan: &Plan) -> impl Iterator { + plan.prepared.files.iter().chain(&plan.workspace_files) +} + +/// The digest of what the check reads in `plan`: every installed file with its root, path, mode +/// and bytes, and the words of the check command. +fn files_digest(plan: &Plan, command_words: &[String]) -> Digest { + let mut bytes = Vec::new(); + for file in installed_files(plan) { + bytes.extend_from_slice( + format!( + "{:?}\0{}\0{}\0{}\0", + file.root, + file.path, + file.executable, + file.contents.len() + ) + .as_bytes(), + ); + bytes.extend_from_slice(&file.contents); + } + for word in command_words { + bytes.extend_from_slice(word.as_bytes()); + bytes.push(0); + } + Digest::of_bytes(&bytes) +} + +/// The pointer into the experiment file of the setting the installed files come from. +fn setting_pointer(view: &Cell<'_>, harness: &str) -> String { + // EXPLICIT: a value the reader refuses was refused when the runs were planned + if agent_config::hooks(view, harness).ok().flatten().is_some() { + pointer_of(["fixed", "hooks"]) + } else if agent_config::instructions(view, harness) + .ok() + .flatten() + .is_some() + { + pointer_of(["fixed", "instructions"]) + } else { + pointer_of(["fixed"]) + } +} + +/// What Candler installed in `plan` and where, as words for a refusal. +fn installed_at(plan: &Plan) -> (String, String) { + let names: Vec = installed_files(plan) + .map(|file| format!("`{}`", file.path)) + .collect(); + let installed = if names.is_empty() { + String::from("its configuration") + } else { + format!("the files {}", names.join(", ")) + }; + let in_home = installed_files(plan).any(|file| matches!(file.root, FileRoot::Home)); + let in_workspace = installed_files(plan).any(|file| !matches!(file.root, FileRoot::Home)); + let at = match (in_home, in_workspace) { + (true, true) => "the agent's home and the workspace", + (true, false) => "the agent's home", + (false, _) => "the workspace", + }; + (installed, at.to_owned()) // BORROW: the refusal owns its words +} + +/// Asks the harness's own check about the files Candler installs for each cell of `plans`, once +/// for each distinct harness, image and set of installed files, in a container without network, +/// and records a clean verdict on the cells it covered. A cell whose driver has no check is not +/// checked and keeps no verdict. +/// +/// The check command prints its verdict on standard output and exits `0`: a command that exits +/// otherwise did not run. +/// +/// # Errors +/// [`ConfigCheckError::Driver`] with [`DriverError::HarnessRejectedInput`] when the harness +/// reports a finding, and [`ConfigCheckError::Check`] when the check could not run. +pub async fn check_config(rt: &mut Runtime, plans: &[RunPlan]) -> Result<(), ConfigCheckError> { + let isolation: Arc = rt // TRAIT_OBJECT: the runtime's isolation, or a fake in tests + .isolation + .clone() // BORROW: the check shares the runtime's isolation + .ok_or_else(|| failed(&"no isolation"))?; + let scratch = rt + .store + .layout() + .job_dir(&rt.job) + .join("scratch") + .join("config-check"); + let mut groups: Groups<'_> = BTreeMap::new(); + let mut seen: BTreeSet<&CellId> = BTreeSet::new(); + for plan in plans { + if !seen.insert(&plan.cell) { + continue; + } + if let Some(key) = group_key(rt, plan, &scratch.join("key"))? { + groups + .entry(key) + .or_insert_with(|| (plan, BTreeSet::new())) + .1 + .insert(plan.cell.clone()); // BORROW: the group owns the ids of its cells + } + } + let _ = fs::remove_dir_all(&scratch); // EXPLICIT: the keys' scratch holds nothing after they are read + let mut verdict = Ok(()); + for (index, (plan, _)) in groups.values().enumerate() { + let root = scratch.join(index.to_string()); // BORROW: .to_string() gives owned text + verdict = check_group(rt, isolation.as_ref(), plan, &root).await; + let _ = fs::remove_dir_all(&root); // EXPLICIT: the scratch is removed whether or not the check passed; a leftover is swept with the job directory + if verdict.is_err() { + break; + } + } + let _ = fs::remove_dir_all(&scratch); // EXPLICIT: the scratch root holds nothing once the groups are done + verdict?; + let covered: BTreeSet = groups.into_values().flat_map(|(_, cells)| cells).collect(); + for id in covered { + if let Some(cell) = rt.cells.get_mut(&id) { + Arc::make_mut(cell).config_clean = true; + } + } + Ok(()) +} + +/// The key of `plan`'s cell, or `None` when its driver has no check. +fn group_key( + rt: &Runtime, + plan: &RunPlan, + root: &Path, +) -> Result, ConfigCheckError> { + let cell = rt.cells.get(&plan.cell).ok_or_else(|| failed(&"no cell"))?; + let comparable = plan.stored.as_ref().unwrap_or(&cell.comparable); + let driven = rt + .driver + .plan(&Cell::new(comparable.values()), &Workspace::new(root))?; + let Some(command) = rt.driver.config_check(&driven) else { + return Ok(None); + }; + let treatment = serde_json::to_string(comparable.treatment()).map_err(|e| failed(&e))?; + let mut words = command.argv().to_vec(); // BORROW: the words are hashed with the files + words.push(treatment); + Ok(Some(( + rt.driver.id().to_string(), // BORROW: .to_string() gives owned text + image_of(comparable), + files_digest(&driven, &words), + ))) +} + +/// Runs the harness's check in the container of `plan`'s cell, over a scratch workspace under +/// `root`, and reads its verdict. +async fn check_group( + rt: &Runtime, + isolation: &dyn Isolation, // TRAIT_OBJECT: the runtime's isolation, or a fake in tests + plan: &RunPlan, + root: &Path, +) -> Result<(), ConfigCheckError> { + let (staged, container) = stage_container(rt, isolation, plan, root) + .await + .map_err(|e| failed(&e))?; + let Some(command) = rt.driver.config_check(&staged) else { + return Ok(()); + }; + let output = isolation + .collect_exec(&container, &command) + .await + .map_err(|e| failed(&e))?; + match rt.driver.read_config_check(&output) { + CheckVerdict::Clean => Ok(()), + CheckVerdict::Rejected { output } => { + let cell = rt.cells.get(&plan.cell).ok_or_else(|| failed(&"no cell"))?; + let comparable = plan.stored.as_ref().unwrap_or(&cell.comparable); + let harness = rt.driver.id().to_string(); // BORROW: .to_string() gives owned text + let (installed, at) = installed_at(&staged); + Err(DriverError::HarnessRejectedInput { + path: setting_pointer(&Cell::new(comparable.values()), harness.as_str()), // BORROW: explicit .as_str() + installed, + at, + harness, + output, + } + .into()) + } + // EXHAUSTIVE: the verdict enum is non-exhaustive; a verdict this core does not know is no clean one + _ => Err(failed( + &"the harness gave a verdict this build does not know", + )), + } +} diff --git a/crates/candler-core/src/jobs/orchestrate/mod.rs b/crates/candler-core/src/jobs/orchestrate/mod.rs index 63cd72c6..8f051515 100644 --- a/crates/candler-core/src/jobs/orchestrate/mod.rs +++ b/crates/candler-core/src/jobs/orchestrate/mod.rs @@ -5,6 +5,7 @@ //! cap is crossed, and destroys what it made through the container guard on every path. pub mod caps; +pub mod config; pub mod controls; pub mod schedule; pub mod servers; @@ -17,6 +18,7 @@ use std::sync::Arc; use candler_schemas::execution::JobEnd; use futures::future::BoxFuture; +use self::config::check_config; use self::schedule::Scheduler; use self::servers::check_servers; use self::session::{ @@ -178,6 +180,10 @@ async fn run_job( let _report = session.close(&SweepScope::CurrentJob).await; return refused("a declared server does not start", &error); } + if let Err(error) = check_config(&mut rt, &outcome.plans).await { + let _report = session.close(&SweepScope::CurrentJob).await; + return refused("the harness rejects the files installed for it", &error); + } let _lock = outcome.lock; let scheduler = Scheduler::with_clock( Arc::new(rt), diff --git a/crates/candler-core/src/jobs/orchestrate/servers.rs b/crates/candler-core/src/jobs/orchestrate/servers.rs index 44e12763..751b0949 100644 --- a/crates/candler-core/src/jobs/orchestrate/servers.rs +++ b/crates/candler-core/src/jobs/orchestrate/servers.rs @@ -7,6 +7,7 @@ use std::fs; use std::path::Path; use std::time::Duration; +use candler_harness::driver::Plan; use candler_harness::mcp::servers; use candler_harness::spec::{Cell, CommandSpec}; use candler_schemas::primitives::RunKey; @@ -14,9 +15,10 @@ use candler_schemas::servers::McpServer; use super::session::image_of; use crate::isolation::container::agent_home; -use crate::isolation::{Isolation, StartProbe}; +use crate::isolation::model::ContainerPlan; +use crate::isolation::{Isolation, IsolationError, StartProbe}; use crate::runner::Runtime; -use crate::runner::exec::{compose_container, stage_cell}; +use crate::runner::exec::{ExecError, compose_container, stage_cell}; use crate::runner::plan::RunPlan; /// How long a server's start command is given before it must still be running. @@ -111,21 +113,33 @@ pub async fn check_servers(rt: &Runtime, plans: &[RunPlan]) -> Result<(), Server verdict } -/// Starts each server of one group in the container of `plan`'s cell, over a scratch workspace -/// under `root`. -async fn probe_group( +/// Stages what a run of `plan`'s cell starts with under `root`, a scratch workspace and home, and +/// composes the container such a run gets: the driver's plan for the cell and the container over +/// it, with the cell's inputs and the plan's read-only workspace files mounted. +/// +/// # Errors +/// [`ExecError`] when the cell is unknown, a directory cannot be made, the driver refuses the cell +/// or a file cannot be written or mounted. +pub(super) async fn stage_container( rt: &Runtime, isolation: &dyn Isolation, // TRAIT_OBJECT: the runtime's isolation, or a fake in tests plan: &RunPlan, - stdio: &[(String, McpServer)], root: &Path, -) -> Result<(), ServerCheckError> { - let cell = rt.cells.get(&plan.cell).ok_or_else(|| failed(&"no cell"))?; +) -> Result<(Plan, ContainerPlan), ExecError> { + let cell = rt + .cells + .get(&plan.cell) + .ok_or_else(|| IsolationError::Plan { + detail: String::from("the job holds no record of the cell"), + })?; let comparable = plan.stored.as_ref().unwrap_or(&cell.comparable); let workspace = root.join("workspace"); - fs::create_dir_all(&workspace).map_err(|e| failed(&e))?; let home = agent_home(root); - fs::create_dir_all(&home).map_err(|e| failed(&e))?; + for dir in [&workspace, &home] { + fs::create_dir_all(dir).map_err(|error| IsolationError::Plan { + detail: format!("cannot make a scratch directory: {error}"), + })?; + } let view = Cell::new(comparable.values()); let (staged, _written) = stage_cell( rt, @@ -136,9 +150,22 @@ async fn probe_group( &home, &root.join("scratch"), ) - .await - .map_err(|e| failed(&e))?; - let mut container = compose_container(rt, isolation, &view, &workspace, &home, &cell.inputs) + .await?; + let container = compose_container(rt, isolation, &view, &workspace, &home, &cell.inputs)?; + Ok((staged, container)) +} + +/// Starts each server of one group in the container of `plan`'s cell, over a scratch workspace +/// under `root`. +async fn probe_group( + rt: &Runtime, + isolation: &dyn Isolation, // TRAIT_OBJECT: the runtime's isolation, or a fake in tests + plan: &RunPlan, + stdio: &[(String, McpServer)], + root: &Path, +) -> Result<(), ServerCheckError> { + let (staged, mut container) = stage_container(rt, isolation, plan, root) + .await .map_err(|e| failed(&e))?; // Standard input stays open, as a server's own would while the agent runs. container.interactive = true; diff --git a/crates/candler-core/src/jobs/refusal.rs b/crates/candler-core/src/jobs/refusal.rs index 91d091e7..17ef1981 100644 --- a/crates/candler-core/src/jobs/refusal.rs +++ b/crates/candler-core/src/jobs/refusal.rs @@ -15,6 +15,7 @@ use std::error::Error; use crate::jobs::dir::JobError; use crate::jobs::lost::RecoverError; +use crate::jobs::orchestrate::config::ConfigCheckError; use crate::jobs::orchestrate::servers::ServerCheckError; use crate::jobs::orchestrate::session::OrchestrateError; use crate::jobs::runtime::RuntimeError; @@ -54,6 +55,14 @@ fn orchestrate_error_path(error: &OrchestrateError) -> Option { } } +/// The pointer of the place in a document where a [`ConfigCheckError`] sits, if it names one. +fn config_check_error_path(error: &ConfigCheckError) -> Option { + match error { + ConfigCheckError::Driver(inner) => Refusal::path(inner), + ConfigCheckError::Check(inner) => Refusal::path(inner), + } +} + /// The rows of [`JobError`], in the order of its variants; the impl below picks one by the /// variant and, for two of them, by what the error says, which a `refusal_table!` row cannot see. static JOB_ROWS: [CatalogRow; 9] = [ @@ -362,10 +371,16 @@ refusal_table! { ), } +wrapper_table! { + ConfigCheckError, path = config_check_error_path; + Driver (inner) => delegate(inner, Side::Experiment), + Check (inner) => delegate(inner, Side::Environment), +} + /// The rows of every coded error of this module, in the order of the types. #[must_use] pub(crate) fn catalog() -> Vec { - let tables: [&'static [CatalogRow]; 7] = [ + let tables: [&'static [CatalogRow]; 8] = [ ::rows(), ::rows(), ::rows(), @@ -373,6 +388,7 @@ pub(crate) fn catalog() -> Vec { ::rows(), ::rows(), ::rows(), + ::rows(), ]; tables .iter() @@ -396,6 +412,14 @@ fn recover_answer(error: &RecoverError) -> &dyn Refusal { } } +/// The refusal that answers for a [`ConfigCheckError`]: the error it wraps. +fn config_answer(error: &ConfigCheckError) -> &dyn Refusal { + match error { + ConfigCheckError::Driver(inner) => crate::refusal::through(inner, error), + ConfigCheckError::Check(inner) => crate::refusal::through(inner, error), + } +} + /// The refusal that answers for an [`OrchestrateError`]. fn orchestrate_answer(error: &OrchestrateError) -> &dyn Refusal { match error { @@ -429,4 +453,5 @@ pub(crate) fn coded<'e>(error: &'e (dyn Error + 'static)) -> Option<&'e dyn Refu .or_else(|| error.downcast_ref::().map(as_refusal)) .or_else(|| error.downcast_ref::().map(as_refusal)) .or_else(|| error.downcast_ref::().map(as_refusal)) + .or_else(|| error.downcast_ref::().map(config_answer)) } diff --git a/crates/candler-core/src/runner/evidence/provenance.rs b/crates/candler-core/src/runner/evidence/provenance.rs index 422f310c..dc45a3fc 100644 --- a/crates/candler-core/src/runner/evidence/provenance.rs +++ b/crates/candler-core/src/runner/evidence/provenance.rs @@ -28,10 +28,15 @@ pub struct EvalInfra { /// The `provenance.*` values of a run: the evaluation infrastructure, the sandbox contract and, /// for each import package the experiment names, the distribution and version its env image -/// holds, as `provenance.packages..distribution` and `.version`. A value that is -/// unknown is left out. +/// holds, as `provenance.packages..distribution` and `.version`, and +/// `provenance.harness_config_check` as `clean` when the harness's own check found nothing in the +/// files installed for the cell. A value that is unknown is left out. #[must_use] -pub fn provenance_values(infra: &EvalInfra, packages: &PackageReadings) -> Vec { +pub fn provenance_values( + infra: &EvalInfra, + packages: &PackageReadings, + config_clean: bool, +) -> Vec { let mut entries = vec![ ( String::from("provenance.eval_infra.tag"), @@ -57,6 +62,12 @@ pub fn provenance_values(infra: &EvalInfra, packages: &PackageReadings) -> Vec, + /// Whether the harness's own check found nothing in the files installed for the cell; `false` + /// for a cell whose harness has no check. + pub config_clean: bool, } impl CellRun { @@ -67,6 +70,7 @@ impl CellRun { packages: PackageReadings::new(), evaluation_inputs: Vec::new(), control: None, + config_clean: false, } } diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index b6e87a8f..dce0f15e 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -898,7 +898,11 @@ async fn drive( events, totals, ))); - measured.extend(provenance_values(&rt.eval_infra, &cell.packages)); + measured.extend(provenance_values( + &rt.eval_infra, + &cell.packages, + cell.config_clean, + )); if let Some(outcome) = &session_outcome { let own_end = end.invalid.is_none(); measured.extend(session_values(&outcome.measures( diff --git a/crates/candler-core/tests/it/guard_config_check.rs b/crates/candler-core/tests/it/guard_config_check.rs new file mode 100644 index 00000000..5e70bb32 --- /dev/null +++ b/crates/candler-core/tests/it/guard_config_check.rs @@ -0,0 +1,326 @@ +//! Guards for the start check of the files Candler installs for a harness: what a finding does to +//! the job, what a clean verdict leaves in the run, how often the check runs, and how the plan's +//! read-only workspace file reaches the run. +//! +//! The job runs over the fake docker client of the job guards; the isolation is wrapped by a +//! double that answers each command run for its output from a script, so no container exists. The +//! harness is a stand-in whose check, files and workspace file the test sets. +#![cfg(test)] + +use crate::support; + +use std::fs; +use std::sync::Arc; + +use candler_core::jobs::model::{JobOutcome, JobSpec}; +use candler_core::jobs::orchestrate::session::JobHost; +use candler_harness::driver::{DriverError, HarnessDriver, Plan}; +use candler_harness::reader::TraceReader; +use candler_harness::spec::{ + AgentSetting, Answer, Cell, CheckVerdict, CollectSpec, CommandSpec, DriverFact, EnvEntry, + HarnessId, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, Workspace, +}; +use candler_schemas::primitives::RelPath; +use candler_schemas::raw::StreamName; +use candler_schemas::trace::{EndedBy, Session}; +use serde_json::{Value, json}; +use support::job_orchestrate::{Probed, QuietDriver, Rig, run_to_end, spec}; +use support::run_plan::Facts; + +/// The text of the workspace file the stand-in harness lists. +const WORKSPACE_TEXT: &str = "be brief"; + +/// The program of the stand-in harness's check. +const CHECK: &str = "harness-check"; + +/// The quiet harness, with a check, installed files and a workspace file the test sets. +struct Checking { + inner: QuietDriver, + /// Whether the harness has a check. + check: bool, + /// Whether the installed files name the cell's model, so cells of two models differ. + vary: bool, + /// Whether the run collects every file of the workspace as an output. + collect_all: bool, +} + +impl Checking { + fn new(check: bool) -> Self { + Self { + inner: QuietDriver, + check, + vary: false, + collect_all: false, + } + } +} + +impl HarnessDriver for Checking { + fn config_check(&self, _plan: &Plan) -> Option { + self.check.then(|| { + CommandSpec::builder() + .argv(vec![CHECK.to_owned()]) + .build() + .expect("a command") + }) + } + + fn read_config_check(&self, output: &[u8]) -> CheckVerdict { + let text = String::from_utf8_lossy(output); + if text.contains("REJECT") { + CheckVerdict::Rejected { + output: text.into_owned(), + } + } else { + CheckVerdict::Clean + } + } + + fn workspace_instruction_file(&self) -> &'static str { + "AGENTS.md" + } + + fn skills(&self) -> candler_harness::skills::SkillTree { + self.inner.skills() + } + + fn base_image(&self) -> candler_harness::spec::BaseImage { + self.inner.base_image() + } + + fn detect(&self, sample: &[u8]) -> Option { + self.inner.detect(sample) + } + + fn id(&self) -> HarnessId { + self.inner.id() + } + + fn supported(&self) -> semver::VersionReq { + self.inner.supported() + } + + fn version_probe(&self) -> CommandSpec { + self.inner.version_probe() + } + + fn parse_version(&self, output: &[u8]) -> Result { + self.inner.parse_version(output) + } + + fn answer(&self, setting: AgentSetting) -> Answer { + self.inner.answer(setting) + } + + fn fact(&self, fact: DriverFact) -> Answer { + self.inner.fact(fact) + } + + fn gateway(&self) -> Option { + self.inner.gateway() + } + + fn state_paths(&self) -> Vec { + self.inner.state_paths() + } + + fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { + let model = if self.vary { + cell.value_str("model.id") + .ok() + .flatten() + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned() + } else { + String::new() + }; + let settings = PreparedFile::in_home( + "settings.json".parse::().expect("a path"), + format!("{{\"model\":\"{model}\"}}").into_bytes(), + false, + ); + let mut plan = self.inner.plan(cell, workspace)?; + plan.prepared = Prepared::new(vec![settings], Vec::::new()); + plan.workspace_files = vec![PreparedFile::new( + "AGENTS.md".parse::().expect("a path"), + WORKSPACE_TEXT.as_bytes().to_vec(), + false, + )]; + Ok(plan) + } + + fn stop(&self) -> StopSpec { + self.inner.stop() + } + + fn live_reader(&self) -> Option> { + self.inner.live_reader() + } + + fn offline_reader( + &self, + stream: &StreamName, + servers: &[String], + ) -> Option> { + self.inner.offline_reader(stream, servers) + } + + fn classify_exit(&self, exit: &ProcessExit, sessions: &[Session]) -> EndedBy { + self.inner.classify_exit(exit, sessions) + } + + fn collect(&self, workspace: &Workspace<'_>, observed: &Observed) -> Vec { + if self.collect_all { + vec![CollectSpec::file("**".to_owned())] + } else { + self.inner.collect(workspace, observed) + } + } +} + +/// The facts of every cell: no secret is declared. +fn facts() -> Facts { + Facts { + secrets: Vec::new(), + commit: support::job_orchestrate::skill_repo().1.clone(), // BORROW: the facts own the commit text + ..Facts::base() + } +} + +/// A job over `models`, whose cells the quiet harness runs. +fn job(models: &[&str]) -> JobSpec { + spec(models, &facts(), 3600, 1) +} + +/// What a job left: its world, its outcome and the host that scripted it. +struct Ran { + rig: Rig, + outcome: JobOutcome, + host: Arc, +} + +/// Runs `job` under `driver` to its end, with the check printing `printed`. +fn run(job: JobSpec, driver: Checking, printed: &str) -> Ran { + let rig = Rig::new(0); + let mut host = Probed::new(rig.host()); + host.prints = vec![(CHECK.to_owned(), printed.to_owned())]; + let host = Arc::new(host); + let shared: Arc = host.clone(); + let mut rt = rig.runtime(); + rt.driver = Arc::new(driver); + let outcome = run_to_end(rt, job, shared); + Ran { rig, outcome, host } +} + +/// The file `name` of the first run's directory, read as JSON. +fn run_file(ran: &Ran, name: &str) -> Value { + let key = &ran.outcome.runs.first().expect("one run").key; + let path = ran + .rig + .store + .layout() + .root() + .join("runs") + .join(key.to_string()) + .join(name); + serde_json::from_slice(&fs::read(path).expect("a run file")).expect("JSON") +} + +/// The value the manifest measured at `path`. +fn measured_at(manifest: &Value, path: &str) -> Option { + manifest["measured"] + .as_array()? + .iter() + .find(|value| value["path"] == path) + .map(|value| value["value"].clone()) // BORROW: .clone() owns the value +} + +/// Guards: a harness check that reports a finding refuses the job before its first run, and the +/// refusal line names what was installed, where, the harness and the harness's output. +/// Oracle: the literal `REJECT: unknown key hooks.Foo` the scripted check prints, and the file +/// names the stand-in driver lists. The job runs in a child of this test binary, so its stderr +/// line can be read. +/// Bite: the refusal drops the harness's output, or the check runs after the runs are scheduled. +#[test] +fn harness_finding_refuses_the_job_before_any_run() { + const NAME: &str = "guard_config_check::harness_finding_refuses_the_job_before_any_run"; + if std::env::var_os("CANDLER_CONFIG_CHECK_CHILD").is_some() { + let ran = run( + job(&["m1"]), + Checking::new(true), + "REJECT: unknown key hooks.Foo", + ); + let probing = ran.host.probing(); + assert_eq!(probing.executed().len(), 1, "the check ran once"); + assert_eq!(probing.runs(), 0, "no run starts"); + assert!(ran.outcome.runs.is_empty(), "no run is recorded"); + return; + } + let child = std::process::Command::new(std::env::current_exe().expect("the test binary")) + .args([NAME, "--exact", "--nocapture", "--test-threads=1"]) + .env("CANDLER_CONFIG_CHECK_CHILD", "1") + .output() + .expect("the child ran"); + let stderr = String::from_utf8_lossy(&child.stderr); + assert!(child.status.success(), "the child's guards held: {stderr}"); + assert!( + stderr.contains( + "Candler installed the files `settings.json`, `AGENTS.md` at the agent's home and the workspace; claude-code rejects it: REJECT: unknown key hooks.Foo" + ), + "the refusal line: {stderr}" + ); +} + +/// Guards: a clean verdict is stored in the run's provenance, and a harness with no check leaves +/// the run with nothing stored as checked and the job not refused. +/// Oracle: the literal `provenance.harness_config_check` path and `clean` value, read from the +/// sealed manifest; the check's container holds the workspace file read-only at the root. +/// Bite: the verdict is dropped between the check and the run's manifest, or the check container +/// is given no workspace file. +#[test] +fn clean_verdict_is_stored_and_a_harness_without_check_stores_none() { + let checked = run(job(&["m1"]), Checking::new(true), "ok"); + assert_eq!(checked.outcome.runs.len(), 1, "the run starts"); + assert_eq!( + measured_at( + &run_file(&checked, "manifest.json"), + "provenance.harness_config_check" + ), + Some(json!("clean")) + ); + let executed = checked.host.probing().executed(); + let (argv, _) = executed.first().expect("the check ran"); + assert_eq!(argv, &vec![CHECK.to_owned()]); + + let unchecked = run(job(&["m1"]), Checking::new(false), "ok"); + assert_eq!(unchecked.outcome.runs.len(), 1, "the run starts"); + assert!( + unchecked.host.probing().executed().is_empty(), + "no check container for a harness with no check" + ); + assert_eq!( + measured_at( + &run_file(&unchecked, "manifest.json"), + "provenance.harness_config_check" + ), + None + ); +} + +/// Guards: cells that share a harness, an image and the installed files are checked once, and +/// cells whose installed files differ are each checked. +/// Oracle: the number of commands the isolation double ran for their output. +/// Bite: key the check on the cell instead of on the installed files, or never on them. +#[test] +fn cells_sharing_their_files_are_checked_once() { + let shared = run(job(&["m1", "m2"]), Checking::new(true), "ok"); + assert_eq!(shared.outcome.runs.len(), 2, "both runs start"); + assert_eq!(shared.host.probing().executed().len(), 1, "one check"); + + let mut differing = Checking::new(true); + differing.vary = true; + let apart = run(job(&["m1", "m2"]), differing, "ok"); + assert_eq!(apart.outcome.runs.len(), 2, "both runs start"); + assert_eq!(apart.host.probing().executed().len(), 2, "one check each"); +} diff --git a/crates/candler-core/tests/it/guard_refusal_codes.rs b/crates/candler-core/tests/it/guard_refusal_codes.rs index 7122f363..83d7ed31 100644 --- a/crates/candler-core/tests/it/guard_refusal_codes.rs +++ b/crates/candler-core/tests/it/guard_refusal_codes.rs @@ -618,6 +618,8 @@ fn wrapped_cases() -> Vec { use candler_core::isolation::gateway::{GatewayError, NotReadyCause, SecretError}; use candler_core::jobs::dir::JobError; use candler_core::jobs::lost::RecoverError; + use candler_core::jobs::orchestrate::config::ConfigCheckError; + use candler_core::jobs::orchestrate::servers::ServerCheckError; use candler_core::jobs::orchestrate::session::OrchestrateError; use candler_core::jobs::slots::SlotError; use candler_core::resolve::preflight::ResolveError; @@ -1019,6 +1021,26 @@ fn wrapped_cases() -> Vec { Box::new(OrchestrateError::Plan(PlanError::Cell { source: git() })), "manifest.git_commit_invalid", ), + case( + "ConfigCheckError", + "Driver", + Box::new(ConfigCheckError::Driver(DriverError::HarnessRejectedInput { + path: "/fixed/hooks".to_owned(), + installed: "the files `a`".to_owned(), + at: "the workspace".to_owned(), + harness: "claude-code".to_owned(), + output: "bad".to_owned(), + })), + "experiment.harness_rejected_input", + ), + case( + "ConfigCheckError", + "Check", + Box::new(ConfigCheckError::Check(ServerCheckError::ServerCheck { + detail: "no container".to_owned(), + })), + "jobs.server_check_failed", + ), // The import's. case( "ImportError", diff --git a/crates/candler-core/tests/it/guard_server_check.rs b/crates/candler-core/tests/it/guard_server_check.rs index 3130ffdf..aede6119 100644 --- a/crates/candler-core/tests/it/guard_server_check.rs +++ b/crates/candler-core/tests/it/guard_server_check.rs @@ -8,69 +8,15 @@ use crate::support; use std::fmt::Write as _; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; -use candler_core::isolation::testing::ProbingIsolation; -use candler_core::isolation::{Isolation, StartProbe}; -use candler_core::jobs::model::{JobCause, JobControl, JobOutcome, JobSpec}; -use candler_core::jobs::orchestrate::orchestrate_with; -use candler_core::jobs::orchestrate::session::{JobHost, OrchestrateError}; +use candler_core::isolation::StartProbe; +use candler_core::jobs::model::{JobOutcome, JobSpec}; +use candler_core::jobs::orchestrate::session::JobHost; use candler_schemas::execution::ExperimentFile; use serde_json::{Value, json}; -use support::job_orchestrate::{FakeHost, Rig, spec}; +use support::job_orchestrate::{Probed, Rig, run_to_end, spec}; use support::run_plan::Facts; -use tokio::sync::watch; - -/// The host of the job guards, whose isolation is wrapped by a [`ProbingIsolation`] the test reads. -struct Probed { - inner: Arc, - answers: Vec<(String, StartProbe)>, - eof_exits: Vec, - needs: Vec, - probing: Mutex>>, -} - -impl JobHost for Probed { - fn docker_cli( - &self, - supervisor: Arc, - record_dir: std::path::PathBuf, - ) -> Result< - candler_core::isolation::docker::DockerCli, - candler_core::isolation::docker::DockerError, - > { - self.inner.docker_cli(supervisor, record_dir) - } - - fn gateway<'a>( - &'a self, - rt: &'a candler_core::runner::Runtime, - spec: &'a JobSpec, - ) -> futures::future::BoxFuture< - 'a, - Result, OrchestrateError>, - > { - self.inner.gateway(rt, spec) - } - - fn isolation( - &self, - isolation: candler_core::isolation::container::DockerIsolation, - ) -> Arc { - let probing = Arc::new(ProbingIsolation::new(self.inner.isolation(isolation))); - for (program, answer) in &self.answers { - probing.answer(program, answer.clone()); // BORROW: the double owns its answers - } - for program in &self.needs { - probing.needs_file(program); - } - for program in &self.eof_exits { - probing.exit_at_eof(program, "stdin closed"); - } - *self.probing.lock().expect("the double") = Some(Arc::clone(&probing)); // BORROW: the test reads the same double - probing - } -} /// The facts of every cell: no secret is declared. fn facts() -> Facts { @@ -106,26 +52,14 @@ fn run( needs: Vec, ) -> (JobOutcome, Vec>, usize) { let rig = Rig::new(0); - let host = Arc::new(Probed { - inner: rig.host(), - answers, - eof_exits, - needs, - probing: Mutex::new(None), - }); - let (cancel, _keep) = watch::channel::>(None); - let ctl = JobControl { - cancel: Arc::new(cancel), - }; - let runtime = tokio::runtime::Builder::new_multi_thread() - .worker_threads(2) - .enable_all() - .build() - .expect("a runtime"); + let mut host = Probed::new(rig.host()); + host.answers = answers; + host.eof_exits = eof_exits; + host.needs = needs; + let host = Arc::new(host); let shared: Arc = host.clone(); - let outcome = runtime.block_on(orchestrate_with(rig.runtime(), job, ctl, shared)); - let probing = host.probing.lock().expect("the double").clone(); - let probing = probing.expect("the job built an isolation"); + let outcome = run_to_end(rig.runtime(), job, shared); + let probing = host.probing(); (outcome, probing.probed(), probing.runs()) } diff --git a/crates/candler-core/tests/it/main.rs b/crates/candler-core/tests/it/main.rs index a41affbe..5b9d283d 100644 --- a/crates/candler-core/tests/it/main.rs +++ b/crates/candler-core/tests/it/main.rs @@ -11,6 +11,7 @@ mod guard_assert_clean; mod guard_build_context; mod guard_census_gateway; mod guard_comparability; +mod guard_config_check; mod guard_container_e2e; mod guard_container_guard; mod guard_container_record; diff --git a/crates/candler-core/tests/it/support/job_orchestrate.rs b/crates/candler-core/tests/it/support/job_orchestrate.rs index 42048f67..3a831bce 100644 --- a/crates/candler-core/tests/it/support/job_orchestrate.rs +++ b/crates/candler-core/tests/it/support/job_orchestrate.rs @@ -23,9 +23,13 @@ use candler_core::isolation::image::PackageReadings; use candler_core::isolation::model::{ ContainerOutcome, ContainerPlan, ContainerRef, GatewayHandle, ImageRef, Labels, NetworkName, }; -use candler_core::isolation::{EndFacts, IsolatedRequest, Isolation, IsolationError, RunOutputs}; +use candler_core::isolation::testing::ProbingIsolation; +use candler_core::isolation::{ + EndFacts, IsolatedRequest, Isolation, IsolationError, RunOutputs, StartProbe, +}; use candler_core::jobs::dir::JobDir; -use candler_core::jobs::model::JobSpec; +use candler_core::jobs::model::{JobCause, JobControl, JobOutcome, JobSpec}; +use candler_core::jobs::orchestrate::orchestrate_with; use candler_core::jobs::orchestrate::schedule::{Clock, wall_clock}; use candler_core::jobs::orchestrate::session::{JobHost, OrchestrateError}; use candler_core::jobs::slots::Slots; @@ -48,6 +52,7 @@ use candler_schemas::trace::{EndedBy, Session}; use futures::future::BoxFuture; use serde_json::json; use tempfile::TempDir; +use tokio::sync::watch; use super::job_store::{job_id, job_record}; use super::run_plan::{Facts, fresh_store, resolution}; @@ -814,3 +819,91 @@ pub fn spec(models: &[&str], facts: &Facts, wall_s: u32, parallel: u32) -> JobSp evaluation_inputs: Vec::new(), } } + +/// The host of a job whose isolation is wrapped by a [`ProbingIsolation`] the test reads: each +/// probed or executed command is answered from the scripts, and nothing else is changed. +pub struct Probed { + inner: Arc, + /// What a probed command that starts with the program is answered with. + pub answers: Vec<(String, StartProbe)>, + /// The programs a probe sees exit unless standard input is held open. + pub eof_exits: Vec, + /// The programs a probe sees exit unless the file exists under a mount. + pub needs: Vec, + /// What a command run for its output prints, by program. + pub prints: Vec<(String, String)>, + probing: Mutex>>, +} + +impl Probed { + /// A host over `inner` that scripts nothing. + pub fn new(inner: Arc) -> Self { + Self { + inner, + answers: Vec::new(), + eof_exits: Vec::new(), + needs: Vec::new(), + prints: Vec::new(), + probing: Mutex::new(None), + } + } + + /// The isolation the job built. + pub fn probing(&self) -> Arc { + self.probing + .lock() + .expect("the double") + .clone() // BORROW: the test reads the same double + .expect("the job built an isolation") + } +} + +impl JobHost for Probed { + fn docker_cli( + &self, + supervisor: Arc, + record_dir: PathBuf, + ) -> Result { + self.inner.docker_cli(supervisor, record_dir) + } + + fn gateway<'a>( + &'a self, + rt: &'a Runtime, + spec: &'a JobSpec, + ) -> BoxFuture<'a, Result, OrchestrateError>> { + self.inner.gateway(rt, spec) + } + + fn isolation(&self, isolation: DockerIsolation) -> Arc { + let probing = Arc::new(ProbingIsolation::new(self.inner.isolation(isolation))); + for (program, answer) in &self.answers { + probing.answer(program, answer.clone()); // BORROW: the double owns its answers + } + for program in &self.needs { + probing.needs_file(program); + } + for program in &self.eof_exits { + probing.exit_at_eof(program, "stdin closed"); + } + for (program, output) in &self.prints { + probing.print(program, output); + } + *self.probing.lock().expect("the double") = Some(Arc::clone(&probing)); // BORROW: the test reads the same double + probing + } +} + +/// Runs `job` under `rt` on `host` to its end. +pub fn run_to_end(rt: Runtime, job: JobSpec, host: Arc) -> JobOutcome { + let (cancel, _keep) = watch::channel::>(None); + let ctl = JobControl { + cancel: Arc::new(cancel), + }; + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .expect("a runtime") + .block_on(orchestrate_with(rt, job, ctl, host)) +} From 4e800a4202ae298034cc4654b096f055812f013f Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:33:21 +0900 Subject: [PATCH 38/69] feat(api): mount the workspace instruction file read-only Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/experiment/inputs.rs | 3 + .../src/jobs/orchestrate/servers.rs | 5 +- crates/candler-core/src/runner/exec/mod.rs | 55 ++++-- crates/candler-core/src/runner/plan.rs | 38 ++++ .../tests/it/guard_config_check.rs | 90 +++++++++- .../tests/it/guard_container_e2e.rs | 2 + .../it/guard_container_e2e/preflight_e2e.rs | 162 ++++++++++++++++++ crates/candler/src/commands/run.rs | 11 +- 8 files changed, 347 insertions(+), 19 deletions(-) create mode 100644 crates/candler-core/tests/it/guard_container_e2e/preflight_e2e.rs diff --git a/crates/candler-core/src/experiment/inputs.rs b/crates/candler-core/src/experiment/inputs.rs index ad5993a0..7944710c 100644 --- a/crates/candler-core/src/experiment/inputs.rs +++ b/crates/candler-core/src/experiment/inputs.rs @@ -43,6 +43,8 @@ pub struct ResolvedInputs { pub evaluators: Vec, /// The files of every input, in declaration order. pub files: Vec, + /// The workspace path of each agent input file with its input's kind, sorted by path. + pub targets: Vec<(String, String)>, } /// Why the declared inputs were refused. @@ -166,6 +168,7 @@ pub fn resolve_input_groups( check_targets(declared.as_slice(), &mut targets)?; // BORROW: explicit .as_slice() resolved.agent.sort(); resolved.evaluators.sort(); + resolved.targets = targets; Ok(resolved) } diff --git a/crates/candler-core/src/jobs/orchestrate/servers.rs b/crates/candler-core/src/jobs/orchestrate/servers.rs index 751b0949..532df038 100644 --- a/crates/candler-core/src/jobs/orchestrate/servers.rs +++ b/crates/candler-core/src/jobs/orchestrate/servers.rs @@ -18,7 +18,7 @@ use crate::isolation::container::agent_home; use crate::isolation::model::ContainerPlan; use crate::isolation::{Isolation, IsolationError, StartProbe}; use crate::runner::Runtime; -use crate::runner::exec::{ExecError, compose_container, stage_cell}; +use crate::runner::exec::{ExecError, compose_container, mounted_inputs, stage_cell}; use crate::runner::plan::RunPlan; /// How long a server's start command is given before it must still be running. @@ -151,7 +151,8 @@ pub(super) async fn stage_container( &root.join("scratch"), ) .await?; - let container = compose_container(rt, isolation, &view, &workspace, &home, &cell.inputs)?; + let mounted = mounted_inputs(&rt.store, &cell.inputs, &staged.workspace_files)?; + let container = compose_container(rt, isolation, &view, &workspace, &home, &mounted)?; Ok((staged, container)) } diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index dce0f15e..5a36f983 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -46,7 +46,7 @@ use super::evidence::provenance::provenance_values; use super::evidence::run::{RunFacts, run_values}; use super::evidence::session::{control_values, session_values}; use super::evidence::tree::tree_json; -use super::evidence::{Evidence, Inputs}; +use super::evidence::{Evidence, InputDigest, Inputs}; use super::plan::RunPlan; use super::{RunControl, RunOutcome, RunStatus, Runtime}; use crate::isolation::container::agent_home; @@ -57,9 +57,9 @@ use crate::isolation::model::ContainerPlan; use crate::isolation::{Isolation, IsolationError, RunOutputs}; use crate::jobs::model::JobCause; use crate::jobs::slots::Slot; -use crate::store::StoreError; use crate::store::blob::digest_of_file; use crate::store::run::{Existing, RunWriter}; +use crate::store::{Store, StoreError}; use crate::supervise::SuperviseError; use crate::supervise::git::{GitError, RecordDir, mark_executable, tree_at_commit}; use crate::supervise::now; @@ -209,14 +209,44 @@ pub fn compose_container( ) -> Result { let mut container = isolation.plan(view, &Workspace::new(workspace_dir))?; apply_harness_env(&mut container, rt.driver.as_ref(), home)?; - mount_inputs(rt, &mut container, workspace_dir, inputs)?; + mount_inputs(&rt.store, &mut container, workspace_dir, inputs)?; Ok(container) } +/// What a run of a cell is given to read: the cell's declared inputs, and each read-only file of +/// the driver's plan, stored as a blob so it is mounted like an input. +/// +/// # Errors +/// [`IsolationError::Plan`] when a file cannot be stored. +pub fn mounted_inputs( + store: &Store, + declared: &Inputs, + files: &[PreparedFile], +) -> Result { + let mut digests = declared.digests.clone(); // BORROW: the mounted list owns its entries + for file in files { + let digest = + store + .put_blob(&file.contents, None) + .map_err(|error| IsolationError::Plan { + detail: format!("cannot store `{}`: {error}", file.path), + })?; + digests.push(InputDigest { + path: file.path.as_str().to_owned(), // BORROW: explicit .as_str() makes the owned path + digest, + }); + } + Ok(Inputs { digests }) +} + /// Makes the mount point of each input in the workspace, mounts each input of the cell read-only -/// there from its blob in the store, and checks the whole mount list again. -fn mount_inputs( - rt: &Runtime, +/// there from its blob in `store`, and checks the whole mount list again. +/// +/// # Errors +/// [`IsolationError::Plan`] when an input's path leaves the workspace, its mount point cannot be +/// made, or the mount list is refused. +pub fn mount_inputs( + store: &Store, container: &mut ContainerPlan, workspace_dir: &Path, inputs: &Inputs, @@ -246,7 +276,7 @@ fn mount_inputs( .open(&point) .map_err(|e| local("cannot make an input's mount point", &e))?; container.mounts.push(MountSpec { - source: rt.store.layout().blob(&input.digest), + source: store.layout().blob(&input.digest), target: format!("{}/{}", container.workdir.trim_end_matches('/'), input.path), mode: MountMode::ReadOnly, }); @@ -490,6 +520,7 @@ async fn drive( prepared, command: headless, session: session_spec, + workspace_files, .. }, written, @@ -532,13 +563,14 @@ async fn drive( // What the driver resolved from the cell, kept with the run: the argv, the variable names the // overlay sets and each prepared file. let resolved = resolved_record(&command, &prepared.files, &written); + let mounted = mounted_inputs(&rt.store, &cell.inputs, &workspace_files)?; let container = compose_container( rt, isolation.as_ref(), &view, &workspace_dir, &agent_home(&layout.run_dir(&plan.key)), - &cell.inputs, + &mounted, )?; let out_stream = stream("stdout")?; @@ -796,7 +828,7 @@ async fn drive( }; // What the run left in its workspace. - let outputs = if let Ok(mut found) = collect_outputs(&workspace_dir, &specs, &cell.inputs) { + let outputs = if let Ok(mut found) = collect_outputs(&workspace_dir, &specs, &mounted) { found.retain(|out| written.get(&out.path) != Some(&out.digest)); found } else { @@ -811,9 +843,8 @@ async fn drive( detail: error.to_string(), // BORROW: .to_string() gives owned text })?, }; - let inputs = &cell.inputs; - let leaked = input_leak(&evidence, inputs).is_some(); - match tree_json(&evidence, inputs) { + let leaked = input_leak(&evidence, &cell.inputs).is_some(); + match tree_json(&evidence, &mounted) { Ok(tree) => evidence.tree = tree, Err(_) => collect_ok = false, } diff --git a/crates/candler-core/src/runner/plan.rs b/crates/candler-core/src/runner/plan.rs index 6da3d514..ef4577f3 100644 --- a/crates/candler-core/src/runner/plan.rs +++ b/crates/candler-core/src/runner/plan.rs @@ -22,6 +22,7 @@ use candler_schemas::execution::{ }; use candler_schemas::field_path; use candler_schemas::primitives::{Digest, FieldPath, JobId, RunKey, SecretName}; +use candler_schemas::refusal::pointer_of; use candler_schemas::values::{JsonValue, ResolvedValue, SourceEntry, ValueSource}; use rustix::fs::{FlockOperation, flock}; use rustix::io::Errno; @@ -773,6 +774,43 @@ fn fresh_cells<'r>( Ok(cells) } +/// Refuses a cell whose workspace instruction text and a declared input mount a file at the +/// harness's workspace instruction file, which `targets` lists as the workspace path of each +/// input file with its input's kind. +/// +/// # Errors +/// [`DriverError::InstructionsCollide`] naming the input and the path when a cell sets +/// `instructions.workspace` and an input mounts the file or a path under it, and the driver's +/// [`DriverError`] for an instruction value it cannot read. +pub fn refuse_instruction_collision<'c>( + driver: &dyn HarnessDriver, // TRAIT_OBJECT: the registry's driver, selected at run time + cells: impl IntoIterator, + targets: &[(String, String)], +) -> Result<(), DriverError> { + let file = driver.workspace_instruction_file(); + let below = format!("{file}/"); + let harness = driver.id().to_string(); // BORROW: .to_string() gives owned text + for comparable in cells { + let view = Cell::new(comparable.values()); + let sets_text = agent_config::instructions(&view, harness.as_str())? // BORROW: explicit .as_str() + .is_some_and(|found| found.workspace.is_some()); + if !sets_text { + continue; + } + if let Some((_, kind)) = targets + .iter() + .find(|(path, _)| path == file || path.starts_with(&below)) + { + return Err(DriverError::InstructionsCollide { + path: pointer_of(["fixed", "instructions.workspace"]), + input: kind.clone(), // BORROW: the error owns the input's kind + file: file.to_owned(), // BORROW: the error owns the path + }); + } + } + Ok(()) +} + /// What the store keeps of one stored cell: its record and the secrets any attempt saw. struct Stored { comparable: Comparable, diff --git a/crates/candler-core/tests/it/guard_config_check.rs b/crates/candler-core/tests/it/guard_config_check.rs index 5e70bb32..942f099d 100644 --- a/crates/candler-core/tests/it/guard_config_check.rs +++ b/crates/candler-core/tests/it/guard_config_check.rs @@ -12,17 +12,21 @@ use crate::support; use std::fs; use std::sync::Arc; +use candler_core::isolation::container::mounts::{MountMode, MountSpec}; use candler_core::jobs::model::{JobOutcome, JobSpec}; use candler_core::jobs::orchestrate::session::JobHost; +use candler_core::runner::plan::refuse_instruction_collision; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ AgentSetting, Answer, Cell, CheckVerdict, CollectSpec, CommandSpec, DriverFact, EnvEntry, HarnessId, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, Workspace, }; +use candler_schemas::execution::Comparable; use candler_schemas::primitives::RelPath; use candler_schemas::raw::StreamName; use candler_schemas::trace::{EndedBy, Session}; +use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::{Value, json}; use support::job_orchestrate::{Probed, QuietDriver, Rig, run_to_end, spec}; use support::run_plan::Facts; @@ -236,6 +240,13 @@ fn measured_at(manifest: &Value, path: &str) -> Option { .map(|value| value["value"].clone()) // BORROW: .clone() owns the value } +/// The mount in `mounts` whose target ends with `/{target}`. +fn mount_at<'m>(mounts: &'m [MountSpec], target: &str) -> Option<&'m MountSpec> { + mounts + .iter() + .find(|mount| mount.target.ends_with(&format!("/{target}"))) +} + /// Guards: a harness check that reports a finding refuses the job before its first run, and the /// refusal line names what was installed, where, the harness and the harness's output. /// Oracle: the literal `REJECT: unknown key hooks.Foo` the scripted check prints, and the file @@ -290,8 +301,14 @@ fn clean_verdict_is_stored_and_a_harness_without_check_stores_none() { Some(json!("clean")) ); let executed = checked.host.probing().executed(); - let (argv, _) = executed.first().expect("the check ran"); + let (argv, mounts) = executed.first().expect("the check ran"); assert_eq!(argv, &vec![CHECK.to_owned()]); + let file = mount_at(mounts, "AGENTS.md").expect("the check container mounts the file"); + assert_eq!(file.mode, MountMode::ReadOnly); + assert_eq!( + fs::read_to_string(&file.source).expect("a blob"), + WORKSPACE_TEXT + ); let unchecked = run(job(&["m1"]), Checking::new(false), "ok"); assert_eq!(unchecked.outcome.runs.len(), 1, "the run starts"); @@ -324,3 +341,74 @@ fn cells_sharing_their_files_are_checked_once() { assert_eq!(apart.outcome.runs.len(), 2, "both runs start"); assert_eq!(apart.host.probing().executed().len(), 2, "one check each"); } + +/// Guards: the plan's read-only workspace file reaches the run's container at the workspace root +/// from its blob, read-only, is no output of the run, and does not make the run an input leak. +/// Oracle: the blob's bytes, the mount's mode and path, the run's `tree.json` and integrity +/// written by the run. +/// Bite: leave the file out of the mount list, or out of the paths collection skips. +#[test] +fn workspace_file_is_mounted_read_only_and_is_no_output() { + let mut driver = Checking::new(false); + driver.collect_all = true; + let ran = run(job(&["m1"]), driver, ""); + assert_eq!(ran.outcome.runs.len(), 1, "the run starts"); + let mounts = ran.host.probing().run_mounts(); + let file = mount_at(mounts.first().expect("a run request"), "AGENTS.md") + .expect("the run mounts the file"); + assert_eq!(file.mode, MountMode::ReadOnly); + assert_eq!( + fs::read_to_string(&file.source).expect("a blob"), + WORKSPACE_TEXT + ); + let tree = run_file(&ran, "tree.json").to_string(); + assert!(!tree.contains("AGENTS.md"), "the file is no output: {tree}"); + let manifest = run_file(&ran, "manifest.json"); + assert_ne!( + manifest["integrity"]["reason"], "input_leak", + "the file is no input leak: {manifest}" + ); +} + +/// A text as a resolved value's content. +fn json_value(text: &str) -> JsonValue { + JsonValue::new(json!(text)).expect("a value") +} + +/// A cell of the fixture's resolution, with the workspace instruction text when `text` is set. +fn cell_with(text: Option<&str>) -> Comparable { + let mut values = support::run_plan::resolution(&facts()).values; + if let Some(text) = text { + values.push(ResolvedValue::recorded( + "instructions.workspace".parse().expect("a path"), + json_value(text), + )); + } + Comparable::from_resolved(&values).expect("a cell") +} + +/// Guards: an input declared at the harness's workspace instruction file is refused for a cell +/// that sets the workspace instruction text, naming the input; the same input is no collision for +/// a cell that sets none, and an input elsewhere is none for a cell that does. +/// Oracle: the input kind `rules` and the file `AGENTS.md` written by hand. +/// Bite: compare the path with the text's file by prefix only, or skip the cell's text. +#[test] +fn input_at_the_instruction_file_collides_with_the_workspace_text() { + let driver = Checking::new(false); + let at_file = [(String::from("AGENTS.md"), String::from("rules"))]; + let elsewhere = [(String::from("docs/AGENTS.md"), String::from("rules"))]; + let text = cell_with(Some("be brief")); + let none = cell_with(None); + + let refused = + refuse_instruction_collision(&driver, [&text], &at_file).expect_err("a collision"); + assert!( + matches!( + &refused, + DriverError::InstructionsCollide { input, file, .. } if input == "rules" && file == "AGENTS.md" + ), + "{refused:?}" + ); + assert!(refuse_instruction_collision(&driver, [&none], &at_file).is_ok()); + assert!(refuse_instruction_collision(&driver, [&text], &elsewhere).is_ok()); +} diff --git a/crates/candler-core/tests/it/guard_container_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e.rs index 5eaafd08..054d4851 100644 --- a/crates/candler-core/tests/it/guard_container_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e.rs @@ -26,6 +26,8 @@ mod env_image_e2e; mod gateway_e2e; #[path = "guard_container_e2e/plugin_env_e2e.rs"] mod plugin_env_e2e; +#[path = "guard_container_e2e/preflight_e2e.rs"] +mod preflight_e2e; #[path = "guard_container_e2e/supervision_gates_e2e.rs"] mod supervision_gates_e2e; #[cfg(test)] diff --git a/crates/candler-core/tests/it/guard_container_e2e/preflight_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/preflight_e2e.rs new file mode 100644 index 00000000..8dbceb14 --- /dev/null +++ b/crates/candler-core/tests/it/guard_container_e2e/preflight_e2e.rs @@ -0,0 +1,162 @@ +//! The real-Docker guard of the plan's read-only workspace file: the mount list the core builds +//! for it holds the file at the workspace root, and a write to it from inside the container fails. +//! +//! The container carries the label `candler.test=workspace_file` and a name of its own, and is removed by that +//! name when the test ends. +#![cfg(test)] + +use std::process::Command; +use std::time::Duration; + +use candler_core::isolation::container::mounts::{MountMode, MountSpec}; +use candler_core::isolation::model::{ + ContainerPlan, ImageId, ImageRef, Labels, Limits, NetworkName, UserSpec, +}; +use candler_core::runner::evidence::Inputs; +use candler_core::runner::exec::{mount_inputs, mounted_inputs}; +use candler_core::store::Store; +use candler_harness::spec::PreparedFile; +use candler_schemas::primitives::{JobId, RelPath}; + +use crate::support::test_image::{TESTAGENT_CONTEXT, TestImage}; + +/// The label of the container this test starts. +const LABEL: &str = "candler.test=workspace_file"; + +/// The text of the workspace file. +const TEXT: &str = "be brief"; + +/// Runs `docker ` and returns its output, which the test reads and never trusts. +fn docker(args: &[String]) -> std::process::Output { + Command::new("docker") + .args(args) + .output() + .expect("the docker CLI runs") +} + +/// Guards: the workspace file the core mounts reads inside a real container and refuses a write, +/// and neither the host's placeholder nor the blob changes. +/// Oracle: the shell's own exit status and message for an append to the file, and the bytes of +/// the blob read on the host afterwards. +/// Bite: mount the file read-write, or skip the placeholder the mount point needs (docker then +/// fails with `mountpoint ... is outside of rootfs`). +#[test] +#[ignore = "needs a docker daemon and the testagent image; run by the container-e2e group"] +fn workspace_file_reads_and_refuses_a_write_in_docker() { + let image = TestImage::new(TESTAGENT_CONTEXT); + let home = std::env::var("HOME").expect("HOME"); + let scratch = tempfile::tempdir_in(home).expect("a scratch directory under HOME"); + let root = scratch.path().canonicalize().expect("a canonical path"); + let store = Store::init(&root.join("store")).expect("a store"); + let (work, agent_home) = (root.join("work"), root.join("home")); + for dir in [&work, &agent_home] { + std::fs::create_dir_all(dir).expect("a directory"); + } + let job: JobId = "00000000-0000-7000-8000-00000000f065" + .parse() + .expect("a job id"); + let mut plan = ContainerPlan { + image: ImageRef { + id: ImageId(image.id().to_owned()), // BORROW: the plan owns the id + harness_version: None, + }, + labels: Labels::new(), + mounts: vec![ + MountSpec { + source: work.clone(), // BORROW: the mount owns its path + target: String::from("/work"), + mode: MountMode::ReadWrite, + }, + MountSpec { + source: agent_home, + target: String::from("/home/agent"), + mode: MountMode::ReadWrite, + }, + ], + env: Vec::new(), + gateway: None, + state: Vec::new(), + network: NetworkName::for_job(&job), + egress: None, + add_hosts: Vec::new(), + limits: Limits { + pids_limit: 128, + memory: String::from("256m"), + cpus: 1.0, + }, + record_dir: root.join("records"), + user: UserSpec::Engine, + workdir: String::from("/work"), + home: String::from("/home/agent"), + expiry: Duration::from_secs(30), + project_root: root.clone(), // BORROW: the plan owns its path + store_root: root.clone(), // BORROW: the plan owns its path + interactive: false, + }; + let file = PreparedFile::new( + "AGENTS.md".parse::().expect("a path"), + TEXT.as_bytes().to_vec(), + false, + ); + let mounted = mounted_inputs(&store, &Inputs::default(), &[file]).expect("the file is stored"); + mount_inputs(&store, &mut plan, &work, &mounted).expect("the mount list"); + let blob = mounted.digests.first().expect("one mounted file"); + let blob_path = store.layout().blob(&blob.digest); + + let name = format!("candler-workspace-file-{}", std::process::id()); + let mut args: Vec = [ + "run", + "--rm", + "--network", + "none", + "--label", + LABEL, + "--name", + ] + .map(String::from) + .to_vec(); + args.push(name.clone()); // BORROW: the removal below reads the name + for mount in &plan.mounts { + args.push(String::from("--mount")); + args.push(mount.to_arg().expect("a mount argument")); + } + args.extend(["-w", "/work", "--entrypoint", "sh", image.id(), "-c"].map(String::from)); + args.push(String::from( + "cat AGENTS.md; if echo changed >> AGENTS.md; then echo WRITE-OK; else echo WRITE-DENIED; fi", + )); + let ran = docker(&args); + // The container removes itself; a leftover is removed by its name. + docker(&["rm".to_owned(), "-f".to_owned(), name]); + let shown = String::from_utf8_lossy(&ran.stdout); + assert!( + ran.status.success(), + "docker run: {}", + String::from_utf8_lossy(&ran.stderr) + ); + assert!(shown.contains(TEXT), "the file reads inside: {shown}"); + assert!( + shown.contains("WRITE-DENIED"), + "the write is refused: {shown}" + ); + // The blob is not writable by file mode either, so only the engine's own words tell a + // read-only mount from a file that merely refuses the user. + let said = String::from_utf8_lossy(&ran.stderr); + assert!( + said.contains("Read-only file system"), + "the mount is read-only: {said}" + ); + assert!( + !shown.contains("WRITE-OK"), + "the write went through: {shown}" + ); + assert_eq!(std::fs::read_to_string(&blob_path).expect("the blob"), TEXT); + assert_eq!( + std::fs::metadata(work.join("AGENTS.md")) + .expect("the placeholder") + .len(), + 0, + "the host's placeholder is untouched" + ); + let left = docker(&["ps", "-aq", "--filter", &format!("label={LABEL}")].map(String::from)); + assert!(left.stdout.is_empty(), "no container of the test is left"); +} diff --git a/crates/candler/src/commands/run.rs b/crates/candler/src/commands/run.rs index 41d84f34..4c16595e 100644 --- a/crates/candler/src/commands/run.rs +++ b/crates/candler/src/commands/run.rs @@ -34,7 +34,8 @@ use candler_core::resolve::layers::{FileValues, Layered, Resolution, ResolveInpu use candler_core::resolve::steps::ground_truth::GroundTruth; use candler_core::resolve::steps::plugin_environment::Fragment; use candler_core::runner::plan::{ - Force, PlanCtx, PlanMode, experiment_of, plan_runs, treatment_levels, + Force, PlanCtx, PlanMode, experiment_of, plan_runs, refuse_instruction_collision, + treatment_levels, }; use candler_core::store::Store; use candler_harness::driver::HarnessDriver; @@ -199,7 +200,7 @@ pub async fn run(args: Args, store: Option<&Path>) -> Result { ); } } - let spec = plan_job(&store, &file, resolutions, force, declared, driver)?; + let spec = plan_job(&store, &file, resolutions, force, declared, &driver)?; start(&store, &file, &spec, &root).await } @@ -259,7 +260,7 @@ fn plan_job( force: bool, declared: ResolvedInputs, // TRAIT_OBJECT: the registry selects the driver at runtime - driver: Arc, + driver: &Arc, ) -> Result { let mut levels = resolutions; let resolution = levels @@ -271,11 +272,13 @@ fn plan_job( store: store.clone(), // BORROW: the context owns its handle on the store experiment_lock: store.layout().experiment_lock(&experiment), secrets_present: EnvSecrets::new(file.secrets()).present(), - driver: Some(driver), + driver: Some(Arc::clone(driver)), // BORROW: the context shares the driver the collision check reads }; let mode = if force { Force::Yes } else { Force::No }; let outcome = plan_runs(&ctx, file, levels.as_slice(), mode, PlanMode::Check) // BORROW: explicit .as_slice() .map_err(|e| refuse_plan(e, file))?; + refuse_instruction_collision(driver.as_ref(), outcome.fresh.values(), &declared.targets) + .map_err(CliError::refused_by)?; if levels.len() < 2 { levels.clear(); } From 3e3fd1b998348a38742f5de7a695feb899623337 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:36:14 +0900 Subject: [PATCH 39/69] fix(api): read the hook log without following links The core read the hook log of the agent's home with fs::read, which follows a link and has no length limit: a link made by the agent archived a host file, and a long log was read whole. One reader now opens the log without following links, requires a regular file and refuses a log longer than a client's output limit; the headless collection and the session's hook log both use it. A session archives the log once, as `hooks`, and the census reads that archive; a log that is refused is not archived and fails the run's collection. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/runner/exec/gather.rs | 102 ++++++++++++++++-- crates/candler-core/src/runner/exec/mod.rs | 15 ++- .../candler-core/src/runner/exec/session.rs | 57 +++++++--- crates/candler-core/tests/it/guard_session.rs | 66 ++++++++++++ .../tests/it/support/session_rig.rs | 19 ++++ .../src/session.rs | 13 ++- 6 files changed, 246 insertions(+), 26 deletions(-) diff --git a/crates/candler-core/src/runner/exec/gather.rs b/crates/candler-core/src/runner/exec/gather.rs index 7fb28913..823fb2c8 100644 --- a/crates/candler-core/src/runner/exec/gather.rs +++ b/crates/candler-core/src/runner/exec/gather.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use std::fs; -use std::io; +use std::io::{self, Read as _, Seek as _, SeekFrom}; use std::os::unix::fs::PermissionsExt as _; use std::path::Path; @@ -15,10 +15,12 @@ use candler_schemas::outcome::Finite; use candler_schemas::raw::{Clock, RawRef, StreamName}; use candler_schemas::trace::{Event, EventKind, Session, SessionEvent, SessionId, UsageScope}; use regex::Regex; +use rustix::fs::{Mode, OFlags}; use serde_json::{Value, json}; use super::ends::TraceFacts; use crate::frames::{FrameReader, FrameWriter, RawFileInfo}; +use crate::isolation::docker::OUTPUT_LIMIT; use crate::isolation::model::ContainerPlan; use crate::isolation::{Isolation, IsolationError}; use crate::runner::Usage; @@ -181,15 +183,54 @@ pub async fn collect_commands( found } +/// Reads a log the agent wrote in its home, from byte `from` on, without trusting the agent: the +/// path is opened without following a link, must be a regular file, and may hold at most +/// [`OUTPUT_LIMIT`] bytes, the most a client's output keeps. The agent controls the file, so a link +/// to a file of the host, a device or a pipe, and a file of any other length, are refused. +/// +/// # Errors +/// [`io::ErrorKind::NotFound`] when there is no such file; any other error when the file is +/// refused or cannot be read. +pub(super) fn read_home_log(path: &Path, from: u64) -> io::Result> { + // A pipe opens without waiting for a writer, and is refused below. + let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC; + let mut file = fs::File::from(rustix::fs::open(path, flags, Mode::empty())?); + if !file.metadata()?.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a regular file", + )); + } + let limit = u64::try_from(OUTPUT_LIMIT).unwrap_or(u64::MAX); + file.seek(SeekFrom::Start(from))?; + let mut bytes = Vec::new(); + // One byte more than the limit shows a file that is longer than it. + file.take(limit.saturating_add(1)).read_to_end(&mut bytes)?; + if from.saturating_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX)) > limit { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("longer than {limit} bytes"), + )); + } + Ok(bytes) +} + /// Reads each file of `home` the driver's collect specs name, in order, and returns what each -/// holds under its stream name. A file the run never wrote leaves nothing; one that cannot be read -/// is that spec's own failed result. +/// holds under its stream name. A file the run never wrote leaves nothing; one that is refused (a +/// link, not a regular file, too long) or cannot be read is that spec's own failed result. A spec +/// whose stream is `archived` is not read: the run already archived that stream. #[must_use] -pub fn collect_home(home: &Path, specs: &[CollectSpec]) -> Vec { +pub fn collect_home( + home: &Path, + specs: &[CollectSpec], + archived: Option<&StreamName>, +) -> Vec { let mut found = Vec::new(); for spec in specs { - if let CollectSpec::Home { path, name, .. } = spec { - match fs::read(home.join(path.as_str())) { + if let CollectSpec::Home { path, name, .. } = spec + && archived != Some(name) + { + match read_home_log(&home.join(path.as_str()), 0) { // BORROW: explicit .as_str() Err(error) if error.kind() == io::ErrorKind::NotFound => {} read => found.push(Collected { @@ -428,4 +469,53 @@ mod tests { let top = glob_regex(".hidden/**").expect("glob"); assert!(top.is_match(".hidden/a/b") && !top.is_match("x/.hidden/a")); } + + fn home_spec() -> CollectSpec { + CollectSpec::home( + ".candler/hooks.jsonl".parse().expect("a path"), + "hooks".parse().expect("a stream"), + ) + } + + fn log_in(home: &Path) -> std::path::PathBuf { + fs::create_dir_all(home.join(".candler")).expect("a directory"); + home.join(".candler/hooks.jsonl") + } + + /// Guards: the home's log is read as a regular file of a bounded length and nothing else. + /// Oracle: the target of the link holds bytes a followed link would return. + /// Bite: read with `fs::read`, or drop the length check. + #[test] + fn home_log_is_read_only_as_a_bounded_regular_file() { + let home = tempfile::tempdir().expect("a home"); + let specs = [home_spec()]; + assert!(collect_home(home.path(), &specs, None).is_empty(), "no log"); + + let log = log_in(home.path()); + fs::write(&log, b"{}\n").expect("a log"); + let read = collect_home(home.path(), &specs, None); + assert_eq!(read.len(), 1); + assert_eq!(read[0].output.as_ref().expect("read"), b"{}\n"); + assert!(collect_home(home.path(), &specs, Some(&read[0].name)).is_empty()); + + fs::remove_file(&log).expect("remove"); + let target = home.path().join("target"); + fs::write(&target, b"host file").expect("a target"); + std::os::unix::fs::symlink(&target, &log).expect("a link"); + let read = collect_home(home.path(), &specs, None); + assert!(read[0].output.is_err(), "a link is refused"); + + fs::remove_file(&log).expect("remove"); + fs::write(&log, vec![b'x'; OUTPUT_LIMIT + 1]).expect("a long log"); + let read = collect_home(home.path(), &specs, None); + assert!(read[0].output.is_err(), "a long log is refused"); + fs::write(&log, vec![b'x'; OUTPUT_LIMIT]).expect("a log at the limit"); + let read = collect_home(home.path(), &specs, None); + assert_eq!(read[0].output.as_ref().expect("read").len(), OUTPUT_LIMIT); + + fs::remove_file(&log).expect("remove"); + fs::create_dir(&log).expect("a directory"); + let read = collect_home(home.path(), &specs, None); + assert!(read[0].output.is_err(), "a directory is refused"); + } } diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index e91242e9..bc2ee7f4 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -643,7 +643,12 @@ async fn drive( let observed_now = live_view.clone().unwrap_or_default(); // BORROW: the view is read again after the finish let specs = rt.driver.collect(&workspace, &observed_now); let mut collected = collect_commands(isolation.as_ref(), &container, &specs).await; - collected.extend(collect_home(&home_dir, &specs)); + // A session archives its hook log as it runs; the log is not read a second time. + let archived = session_outcome + .as_ref() + .and_then(|outcome| outcome.hook_stream.as_ref()) + .map(|(stream, _)| stream); + collected.extend(collect_home(&home_dir, &specs, archived)); let finished = finish_attempt( isolation.as_ref(), &container, @@ -710,6 +715,14 @@ async fn drive( }, } } + if let Some(outcome) = &session_outcome { + if let Some((stream, _)) = &outcome.hook_stream { + loaded.extend(rt.driver.loaded_instructions(stream, &outcome.hook_bytes)); + } + if outcome.hook_lost.is_some() { + collect_ok = false; + } + } if let Some(identity) = offline { reader_id = Some(identity); sessions = offline_sessions; diff --git a/crates/candler-core/src/runner/exec/session.rs b/crates/candler-core/src/runner/exec/session.rs index 658b917a..58235013 100644 --- a/crates/candler-core/src/runner/exec/session.rs +++ b/crates/candler-core/src/runner/exec/session.rs @@ -8,8 +8,8 @@ //! log into it, archives the log as a raw stream and decides: wait, close the input, or end the run //! at the turn cap of the cell. -use std::fs::File; -use std::io::{Read as _, Seek as _, SeekFrom}; +use std::io; +use std::mem; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; @@ -30,6 +30,7 @@ use tokio::time::MissedTickBehavior; pub use crate::runner::evidence::session::{Idle, SessionEnd, SessionMeasures}; +use super::gather::read_home_log; use super::spawn::RunStopper; use crate::frames::{FrameWriter, RawFileInfo}; use crate::isolation::IsolationError; @@ -371,6 +372,10 @@ struct HookLog { partial: Vec, writer: Option, began: Instant, + /// Every complete line read, newline included: what the run's census reads. + seen: Vec, + /// Whether the log was refused (a link, not a regular file, too long) or could not be read. + refused: bool, } impl HookLog { @@ -381,21 +386,25 @@ impl HookLog { partial: Vec::new(), writer, began: Instant::now(), + seen: Vec::new(), + refused: false, } } /// The complete lines written since the last read, without their newlines. fn drain(&mut self) -> Vec> { - let Ok(mut file) = File::open(&self.path) else { - return Vec::new(); - }; - if file.seek(SeekFrom::Start(self.offset)).is_err() { - return Vec::new(); - } - let mut chunk = Vec::new(); - if file.read_to_end(&mut chunk).is_err() { + if self.refused { return Vec::new(); } + let chunk = match read_home_log(&self.path, self.offset) { + Ok(chunk) => chunk, + // The hooks have not written yet. + Err(error) if error.kind() == io::ErrorKind::NotFound => return Vec::new(), + Err(_) => { + self.refused = true; + return Vec::new(); + } + }; self.offset = self .offset .saturating_add(u64::try_from(chunk.len()).unwrap_or(0)); @@ -403,6 +412,7 @@ impl HookLog { let mut lines = Vec::new(); while let Some(end) = self.partial.iter().position(|byte| *byte == b'\n') { let mut line: Vec = self.partial.drain(..=end).collect(); + self.seen.extend_from_slice(&line); if let Some(writer) = self.writer.as_mut() { let at = u64::try_from(self.began.elapsed().as_nanos()).unwrap_or(u64::MAX); if writer.write(&line, Some(at)).is_err() { @@ -416,8 +426,11 @@ impl HookLog { lines } - /// Finishes the archive of the log. + /// Finishes the archive of the log. A refused log is not archived. fn finish(self) -> Option { + if self.refused { + return None; + } // EXPLICIT: an archive that cannot be finished is left out of the seal self.writer?.finish().ok() } @@ -445,6 +458,12 @@ pub struct SessionOutcome { pub watch: Arc, /// The raw stream of the hook log, when there was one and it was archived. pub hook_stream: Option<(StreamName, RawFileInfo)>, + /// The lines of the hook log the archive holds, for the driver to read; empty when the log was + /// not archived. + pub hook_bytes: Vec, + /// The stream of a hook log the run declared and did not archive: the log was refused (a + /// link, not a regular file, too long), could not be read or could not be archived. + pub hook_lost: Option, /// Whether the runner closed the input. pub closed: bool, /// Whether the runner stopped the harness after the input was closed. @@ -624,9 +643,23 @@ impl SessionHandle { pub fn finish(self) -> SessionOutcome { self.task.abort(); drain_hooks(&self.watch, &self.log); - let archived = locked(&self.log).take().and_then(HookLog::finish); + let mut log = locked(&self.log).take(); + let seen = log.as_mut().map(|log| mem::take(&mut log.seen)); + let archived = log.and_then(HookLog::finish); + let hook_bytes = if archived.is_some() { + seen.unwrap_or_default() + } else { + Vec::new() + }; + let hook_lost = if archived.is_none() { + self.hook_stream.clone() // BORROW: the stream name is also kept by the outcome's pair + } else { + None + }; SessionOutcome { hook_stream: self.hook_stream.zip(archived), + hook_bytes, + hook_lost, closed: self.watch.closed.load(Ordering::SeqCst), forced: self.watch.forced.load(Ordering::SeqCst), capped: self.watch.capped.load(Ordering::SeqCst), diff --git a/crates/candler-core/tests/it/guard_session.rs b/crates/candler-core/tests/it/guard_session.rs index 16bdc6ca..f2223bf3 100644 --- a/crates/candler-core/tests/it/guard_session.rs +++ b/crates/candler-core/tests/it/guard_session.rs @@ -1526,4 +1526,70 @@ async fn session_census_names_the_instruction_files_the_hooks_saw() { {"path": "CLAUDE.md", "scope": "project"}, ])) ); + assert!( + ran.run_dir.join("raw/hooks.jsonl.gz").is_file(), + "the hook log is archived once, as `hooks`" + ); + assert!( + std::fs::read_dir(ran.run_dir.join("raw")) + .expect("the raw streams") + .all(|entry| !entry + .expect("a raw stream") + .file_name() + .to_string_lossy() + .starts_with("instructions_loaded")), + "no second archive of the hook log" + ); +} + +/// The census run of the recorded log, with `refusing` steps that make the hook log one the core +/// refuses; the log's valid lines follow, so a read that took the file would show them. +async fn census_of_a_refused_log(refusing: Vec) -> rig::Ran { + let log = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../candler-harness-claude-code/tests/fixtures/instructions/hooks.jsonl"); + let mut steps: Vec = std::fs::read_to_string(log) + .expect("the recorded hook log") + .lines() + .filter(|line| line.contains("\"hook_event_name\":\"InstructionsLoaded\"")) + .flat_map(|line| [rig::hook(line), rig::sleep(0.01)]) + .collect(); + steps.splice(0..0, refusing); + steps.extend(rig::replay_of("c1", &BTreeMap::new())); + steps.push(rig::wait_eof(None)); + let cell = rig::cell_values(&[ + ("runner.idle_s", j!("none")), + ("budget.per_run.wall_s", j!(4)), + ]); + let ran = rig::run(&steps, &cell, rig::Driver::new(true), None).await; + let _ = ran.outcome(); + ran +} + +/// Guards: invariant 7 — a hook log the agent made a link is not read: its target's lines reach +/// neither the archive nor the census. +/// Oracle: the target holds `InstructionsLoaded` lines that a followed link would list. +/// Bite: open the log by following links. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_linked_hook_log_is_not_archived() { + let target = std::env::temp_dir().join(format!("candler-hook-target-{}", std::process::id())); + std::fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../candler-harness-claude-code/tests/fixtures/instructions/hooks.jsonl"), + &target, + ) + .expect("a target"); + let ran = census_of_a_refused_log(vec![rig::link(&target)]).await; + let _ = std::fs::remove_file(&target); + assert_eq!(ran.measured("census.instructions"), None); + assert!(!ran.run_dir.join("raw/hooks.jsonl.gz").exists()); +} + +/// Guards: invariant 7 — a hook log longer than the limit is not archived and records no census. +/// Oracle: the log holds valid `InstructionsLoaded` lines, then more bytes than the limit. +/// Bite: read the log whatever its length. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_oversized_hook_log_is_not_archived() { + let ran = census_of_a_refused_log(vec![rig::fill(5 * 1024 * 1024)]).await; + assert_eq!(ran.measured("census.instructions"), None); + assert!(!ran.run_dir.join("raw/hooks.jsonl.gz").exists()); } diff --git a/crates/candler-core/tests/it/support/session_rig.rs b/crates/candler-core/tests/it/support/session_rig.rs index 305f1caa..7dcb8175 100644 --- a/crates/candler-core/tests/it/support/session_rig.rs +++ b/crates/candler-core/tests/it/support/session_rig.rs @@ -70,6 +70,15 @@ for step in script["steps"]: with open(hook, "a") as f: f.write(step["hook"] + "\n") log("hook") + elif "link" in step: + os.makedirs(os.path.dirname(hook), exist_ok=True) + os.symlink(step["link"], hook) + log("link") + elif "fill" in step: + os.makedirs(os.path.dirname(hook), exist_ok=True) + with open(hook, "ab") as f: + f.write(b"x" * step["fill"]) + log("fill") elif "wait_eof" in step: eof.wait(step.get("timeout")) elif "exit" in step: @@ -110,6 +119,16 @@ pub fn hook(line: &str) -> Value { json!({"hook": line}) } +/// The stub makes the hook log a link to `target`. +pub fn link(target: &Path) -> Value { + json!({"link": target.to_string_lossy()}) +} + +/// The stub appends `bytes` bytes that are no line to the hook log. +pub fn fill(bytes: usize) -> Value { + json!({"fill": bytes}) +} + /// A pause of the stub. pub fn sleep(seconds: f64) -> Value { json!({"sleep": seconds}) diff --git a/crates/candler-harness-claude-code/src/session.rs b/crates/candler-harness-claude-code/src/session.rs index ddd38041..871c7cef 100644 --- a/crates/candler-harness-claude-code/src/session.rs +++ b/crates/candler-harness-claude-code/src/session.rs @@ -48,10 +48,8 @@ const AGENT_HOME: &str = "/home/agent"; const SETTINGS: &str = ".candler/settings.json"; /// The file the hooks append to, relative to the agent's home. const HOOK_LOG: &str = ".candler/hooks.jsonl"; -/// The name of the raw stream that archives the hook log. +/// The name of the raw stream that archives the hook log, in a session and in a headless run. const HOOK_STREAM: &str = "hooks"; -/// The name of the raw stream that archives the `InstructionsLoaded` lines of the hook log. -const LOADED_STREAM: &str = "instructions_loaded"; /// The hook events the driver installs. const HOOK_EVENTS: [&str; 3] = ["InstructionsLoaded", "Stop", "SessionEnd"]; @@ -102,10 +100,11 @@ fn hooks() -> Result { } /// What the core collects of the hook log after a run, headless or session: the log, read from -/// the agent's home and archived as the stream `instructions_loaded`. +/// the agent's home and archived as the stream `hooks`. A session archives the same stream as it +/// runs, and the core reads it once. pub(crate) fn log_collect() -> Result { - let stream = StreamName::from_str(LOADED_STREAM) - .map_err(|error| invalid(LOADED_STREAM, error.to_string()))?; // BORROW: .to_string() gives owned text + let stream = StreamName::from_str(HOOK_STREAM) + .map_err(|error| invalid(HOOK_STREAM, error.to_string()))?; // BORROW: .to_string() gives owned text let log = RelPath::from_str(HOOK_LOG).map_err(|error| invalid(HOOK_LOG, error.to_string()))?; // BORROW: .to_string() gives owned text Ok(CollectSpec::home(log, stream)) } @@ -116,7 +115,7 @@ pub(crate) fn log_collect() -> Result { /// `Local`) by its path from the `cwd` of the payload. A line that is not an `InstructionsLoaded` /// payload, or whose memory type is another one, is skipped. pub(crate) fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { - if stream.as_str() != LOADED_STREAM { + if stream.as_str() != HOOK_STREAM { return Vec::new(); } let mut files: Vec = Vec::new(); From 929d8884853d815641df17fd1ca356b61b807246 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:37:48 +0900 Subject: [PATCH 40/69] fix(api): accept a Claude Code config check only on a doctor report An empty or failed `claude doctor` run read as a clean check. The check now passes only when the output opens with the report's title, read off the recorded outputs of Claude Code 2.1.311; any other output is rejected with itself as the reason. The tests read those recorded outputs, for a valid file, a file that is not JSON and a hook on an unknown event. Co-Authored-By: Claude Sonnet 5.5 --- .../candler-harness-claude-code/src/driver.rs | 11 +++- .../tests/fixtures/PROVENANCE.toml | 18 +++++++ .../tests/fixtures/doctor/bad_json.txt | 36 +++++++++++++ .../tests/fixtures/doctor/unknown_event.txt | 36 +++++++++++++ .../tests/fixtures/doctor/valid.txt | 33 ++++++++++++ .../tests/it/guard_claude_code_driver.rs | 50 +++++++++++++------ 6 files changed, 168 insertions(+), 16 deletions(-) create mode 100644 crates/candler-harness-claude-code/tests/fixtures/doctor/bad_json.txt create mode 100644 crates/candler-harness-claude-code/tests/fixtures/doctor/unknown_event.txt create mode 100644 crates/candler-harness-claude-code/tests/fixtures/doctor/valid.txt diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index 747c50cc..b289a985 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -25,6 +25,8 @@ use serde_json::Value; use crate::{ClaudeCodeReader, detect, discovery, prepare, session}; +/// The first line of every `claude doctor` report. +const DOCTOR_TITLE: &str = "Claude Code doctor"; /// The program the driver runs. pub(crate) const PROGRAM: &str = "claude"; /// The variable that carries the gateway's address. @@ -329,7 +331,7 @@ impl HarnessDriver for ClaudeCodeDriver { fn config_check(&self, plan: &Plan) -> Option { let _ = plan; // The exit status is 0 whatever it finds, and four install-method warnings always print: - // only the `Invalid settings` section says something of the files. + // only the `Invalid settings` section of a report, which opens with its title, says something of the files. Some(CommandSpec::new( PROGRAM.to_owned(), vec!["doctor".to_owned()], @@ -338,6 +340,13 @@ impl HarnessDriver for ClaudeCodeDriver { fn read_config_check(&self, output: &[u8]) -> CheckVerdict { let text = String::from_utf8_lossy(output); + // Every report opens with its title; output without it is not a report, so a check that + // never ran (empty output, an error, a changed format) never passes. + if text.lines().find(|line| !line.trim().is_empty()) != Some(DOCTOR_TITLE) { + return CheckVerdict::Rejected { + output: text.into_owned(), + }; + } let mut section = text .lines() .skip_while(|line| !line.contains("Invalid settings")) diff --git a/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml b/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml index 7ae76e0d..6c94b790 100644 --- a/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml +++ b/crates/candler-harness-claude-code/tests/fixtures/PROVENANCE.toml @@ -240,3 +240,21 @@ path = "sessions/c2/timings.toml" source = "recorded: Claude Code 2.1.311 against assets/docker/fakemodel, see sessions/PROVENANCE.toml" sha256 = "e1fd828f6621aeb731ea1564b9dfe7a16bb2e2de7a3c31612925220c11bf4600" synthetic = false + +[[files]] +path = "doctor/valid.txt" +source = "recorded: `claude doctor > your shell config file then open a new terminal or run: source your shell config file +- Running native installation but config install method is 'not set' + Fix: Run claude install to update configuration +- claude command at /home/agent/.local/bin/claude missing or broken (/home/agent/.local/bin does not exist) + Fix: Run claude install to repair the installation. +- claude command at /home/agent/.local/bin/claude missing or broken + Fix: Run claude install to repair the installation. + +For a full setup checkup that can also fix issues, run /doctor in a Claude Code session. diff --git a/crates/candler-harness-claude-code/tests/fixtures/doctor/unknown_event.txt b/crates/candler-harness-claude-code/tests/fixtures/doctor/unknown_event.txt new file mode 100644 index 00000000..257a7726 --- /dev/null +++ b/crates/candler-harness-claude-code/tests/fixtures/doctor/unknown_event.txt @@ -0,0 +1,36 @@ +Claude Code doctor + +Running: native (2.1.311) +Commit: e7d3b8365a0f +Platform: linux-arm64 +Path: /usr/local/bin/claude +Config install method: not set +Search: OK (bundled) +Auto-updates: enabled +Auto-update channel: latest +Last update attempt: none recorded +Managed settings (remote): not fetched — no usable credentials for the settings fetch +Organization policy: not fetched: no API key or claude.ai sign-in for the policy lookup (apiKeyHelper keys are not used for it) + +Invalid settings +- /work/.claude/settings.json › hooks.NoSuchEvent: Unknown hook event "NoSuchEvent" was ignored. Valid events: PreToolUse, PostToolUse, PostToolUseFailure, PostToolBatch, Notification, UserPromptSubmit, UserPromptExpansion, SessionStart, SessionEnd, Stop, StopFailure, SubagentStart, SubagentStop, PreCompact, PostCompact, PreModelSwitch, PostModelSwitch, PermissionRequest, PermissionDenied, Setup, TeammateIdle, TaskCreated, TaskCompleted, Elicitation, ElicitationResult, ConfigChange, WorktreeCreate, WorktreeRemove, InstructionsLoaded, CwdChanged, FileChanged, DirectoryAdded, MessageDisplay + +Remote Control +Remote Control requires a claude.ai subscription. Run claude auth login to sign in with your claude.ai account. +- Not signed in to claude.ai +- claude.ai subscription auth not active +- Sign-in is missing the user:profile scope +- Organization not resolved +- Remote Control availability could not be verified (no server response this session) + +4 warnings found +- Native installation exists but ~/.local/bin is not in your PATH + Fix: Run: echo 'export PATH="$HOME/.local/bin:$PATH"' >> your shell config file then open a new terminal or run: source your shell config file +- Running native installation but config install method is 'not set' + Fix: Run claude install to update configuration +- claude command at /home/agent/.local/bin/claude missing or broken (/home/agent/.local/bin does not exist) + Fix: Run claude install to repair the installation. +- claude command at /home/agent/.local/bin/claude missing or broken + Fix: Run claude install to repair the installation. + +For a full setup checkup that can also fix issues, run /doctor in a Claude Code session. diff --git a/crates/candler-harness-claude-code/tests/fixtures/doctor/valid.txt b/crates/candler-harness-claude-code/tests/fixtures/doctor/valid.txt new file mode 100644 index 00000000..3e1d45d2 --- /dev/null +++ b/crates/candler-harness-claude-code/tests/fixtures/doctor/valid.txt @@ -0,0 +1,33 @@ +Claude Code doctor + +Running: native (2.1.311) +Commit: e7d3b8365a0f +Platform: linux-arm64 +Path: /usr/local/bin/claude +Config install method: not set +Search: OK (bundled) +Auto-updates: enabled +Auto-update channel: latest +Last update attempt: none recorded +Managed settings (remote): not fetched — no usable credentials for the settings fetch +Organization policy: not fetched: no API key or claude.ai sign-in for the policy lookup (apiKeyHelper keys are not used for it) + +Remote Control +Remote Control requires a claude.ai subscription. Run claude auth login to sign in with your claude.ai account. +- Not signed in to claude.ai +- claude.ai subscription auth not active +- Sign-in is missing the user:profile scope +- Organization not resolved +- Remote Control availability could not be verified (no server response this session) + +4 warnings found +- Native installation exists but ~/.local/bin is not in your PATH + Fix: Run: echo 'export PATH="$HOME/.local/bin:$PATH"' >> your shell config file then open a new terminal or run: source your shell config file +- Running native installation but config install method is 'not set' + Fix: Run claude install to update configuration +- claude command at /home/agent/.local/bin/claude missing or broken (/home/agent/.local/bin does not exist) + Fix: Run claude install to repair the installation. +- claude command at /home/agent/.local/bin/claude missing or broken + Fix: Run claude install to repair the installation. + +For a full setup checkup that can also fix issues, run /doctor in a Claude Code session. diff --git a/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs b/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs index f85793b5..b336d691 100644 --- a/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs +++ b/crates/candler-harness-claude-code/tests/it/guard_claude_code_driver.rs @@ -788,10 +788,12 @@ fn the_census_names_the_instruction_files_the_hook_log_shows() -> Res<()> { } /// Guards: the config check — `claude doctor` runs, an `Invalid settings` section with its bullets -/// is a rejection whatever the exit status and the install-method warnings, and its absence is a -/// clean check. -/// Oracle: output written by hand from the lines the probe quoted. -/// Bite: reject on the `warnings found` block, or ignore a warning under the heading. +/// is a rejection whatever the exit status and the install-method warnings, its absence in a +/// report is a clean check, and output that is not a report (empty, an error) is a rejection +/// carrying that output, so a check that never ran never passes. +/// Oracle: the recorded outputs of `claude doctor` 2.1.311 in `fixtures/doctor`. +/// Bite: reject on the `warnings found` block, ignore a warning under the heading, or read empty +/// output as clean. #[test] fn the_config_check_reads_the_invalid_settings_section() -> Res<()> { use candler_harness::spec::CheckVerdict; @@ -802,21 +804,39 @@ fn the_config_check_reads_the_invalid_settings_section() -> Res<()> { driver.config_check(&plan).ok_or("no check")?.argv(), ["claude", "doctor"] ); - let clean = - b"Diagnostics\n Remote Control: off\n\n 4 warnings found\n - Multiple installations\n"; - assert_eq!(driver.read_config_check(clean), CheckVerdict::Clean); - let bad = b"Diagnostics\n\nInvalid settings\n - /work/.claude/settings.json: Invalid or malformed JSON\n\n 4 warnings found\n - Multiple installations\n"; + let recorded = |name: &str| { + fs::read( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/doctor") + .join(name), + ) + }; assert_eq!( - driver.read_config_check(bad), + driver.read_config_check(&recorded("valid.txt")?), + CheckVerdict::Clean + ); + assert_eq!( + driver.read_config_check(&recorded("bad_json.txt")?), CheckVerdict::Rejected { - output: "Invalid settings\n - /work/.claude/settings.json: Invalid or malformed JSON" + output: "Invalid settings\n- /work/.claude/settings.json: Invalid or malformed JSON" .to_owned() } ); - let warn = b"Invalid settings\n - hooks.NoSuchEvent: Unknown hook event \"NoSuchEvent\" was ignored.\n"; - assert!(matches!( - driver.read_config_check(warn), - CheckVerdict::Rejected { .. } - )); + let CheckVerdict::Rejected { output } = + driver.read_config_check(&recorded("unknown_event.txt")?) + else { + return Err("an unknown hook event is not rejected".into()); + }; + assert!(output.starts_with("Invalid settings\n- /work/.claude/settings.json")); + assert!(output.contains("hooks.NoSuchEvent: Unknown hook event")); + assert!(!output.contains("Remote Control")); + for not_a_report in [&b""[..], b"error: could not reach the server\n"] { + assert_eq!( + driver.read_config_check(not_a_report), + CheckVerdict::Rejected { + output: String::from_utf8_lossy(not_a_report).into_owned() + } + ); + } Ok(()) } From 69b0841a5151eab3d232b8265e16ed06d028a360 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:38:36 +0900 Subject: [PATCH 41/69] docs(api): say what a plain Claude Code cell now gets Every Claude Code cell runs the observer hooks, archives their log and gets a `claude doctor` check, with or without instructions or hooks of its own; and `census.instructions` is read from a log the agent can change. Co-Authored-By: Claude Sonnet 5.5 --- docs/contract/harness-capabilities.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index 3835e96c..6db29d5a 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -76,3 +76,5 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. - `no (…)` is a refusal: `experiment.session_refused` while resolving, `experiment.setting_unsupported` when the cells are planned, before a job starts. [checked: v@0.15.0] - In session mode Candler also counts turns across the session and ends the run when they exceed `budget.per_run.turns`. [checked: v@0.7.0] - The settings a driver maps or refuses, such as permission modes, effort levels and tool names, are the answers its driver gives for each `AgentSetting`. [checked: v@0.7.0] +- Every Claude Code cell runs three observer hooks, headless too, archives their log as stream `hooks`, and gets one `claude doctor` check per distinct (image, prepared files). [checked: v@0.16.0] +- `census.instructions` is read from the hook log in the agent's home, which the agent can change during the run; the trace's `context_start` shows what reached the model. [checked: v@0.16.0] From e0e98dab31ef2fd7539ce5f89f81bbb9d6293918 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:42:02 +0900 Subject: [PATCH 42/69] fix(api): fail the collection on a census error, fix a stream doc A census value that cannot be built now fails the run's collection instead of vanishing, the one collected log that cannot be named is explained where it is dropped, and the doc of loaded_instructions names only the stream the driver reads. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/runner/exec/mod.rs | 5 ++++- crates/candler-harness-claude-code/src/driver.rs | 1 + crates/candler-harness/src/driver.rs | 5 ++--- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index bc2ee7f4..8df14e5c 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -838,7 +838,10 @@ async fn drive( } else { census(observed.init.as_ref().or(gateway_init.as_ref())).unwrap_or_default() }; - measured.extend(census_instructions(&loaded).ok().flatten()); + match census_instructions(&loaded) { + Ok(value) => measured.extend(value), + Err(_) => collect_ok = false, + } let gateway_failed = match &rt.gateway { Some(gateway) => gateway diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index b289a985..f6314d3c 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -464,6 +464,7 @@ impl HarnessDriver for ClaudeCodeDriver { .into_iter() .map(|pattern| CollectSpec::file(format!("!{pattern}"))), ); + // EXPLICIT: the log's path and stream name are constants that parse; were they refused, the log would go uncollected specs.extend(session::log_collect().ok()); specs } diff --git a/crates/candler-harness/src/driver.rs b/crates/candler-harness/src/driver.rs index 78b5e56a..7b1eac55 100644 --- a/crates/candler-harness/src/driver.rs +++ b/crates/candler-harness/src/driver.rs @@ -243,9 +243,8 @@ pub trait HarnessDriver: Send + Sync { None } - /// The instruction files the harness loaded, as `stream` shows them: `bytes` is the stream - /// the core collected under `stream` after the run, or the gateway's record of it. A driver - /// reads the streams it knows and lists nothing for any other. An empty list means no file was + /// The instruction files the harness loaded, as `stream` shows them: `bytes` is that + /// stream as the core archived it for the run. A driver reads the streams it knows and lists nothing for any other. An empty list means no file was /// observed, and the census records nothing. fn loaded_instructions(&self, stream: &StreamName, bytes: &[u8]) -> Vec { let _ = (stream, bytes); From cda2e980df0b5531b91a12c611a3e4008f86b767 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:43:00 +0900 Subject: [PATCH 43/69] rdm(api): mark the M6.5 Claude Code install done Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/installed/README.md | 4 ++-- .../m6_5-agent-config/installed/install_claude_code.md | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/installed/README.md b/__roadmap__/m6_5-agent-config/installed/README.md index a50285fb..c03d8e80 100644 --- a/__roadmap__/m6_5-agent-config/installed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/README.md @@ -16,7 +16,7 @@ Each driver installs the global instruction text and hooks where its harness loo ## Status ```mermaid graph TD - install_claude_code[Install on Claude Code]:::planned + install_claude_code[Install on Claude Code]:::done install_opencode[Install on OpenCode]:::planned preflight_check[Preflight check]:::planned proved[Proved]:::planned @@ -30,7 +30,7 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `install_claude_code.md` | 📄 Leaf Task | ⬜ Planned | +| `install_claude_code.md` | 📄 Leaf Task | ✅ Done | | `install_opencode.md` | 📄 Leaf Task | ⬜ Planned | | `preflight_check.md` | 📄 Leaf Task | ⬜ Planned | | `proved/` | 📁 Directory | ⬜ Planned | diff --git a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md index cbeac9a1..c52af691 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_claude_code.md +++ b/__roadmap__/m6_5-agent-config/installed/install_claude_code.md @@ -6,11 +6,11 @@ - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds - [ ] `[nl]` The probe report settles (a), (b), (e) and (f) **Success Gates**: -- ⬜ G3 (Claude Code). The *instructions*, *hooks* and *config check* rows show the Claude Code mapping: the global file's place from the probe, and the workspace's root `CLAUDE.md`, read-only; the `hooks` key of `.claude/settings.json`, with files under `.claude/hooks/`; and the probe's check or `no (…)`. On the base, no such rows exist. -- ⬜ The plan of a cell with all four values places the global text where the probe settled, lists `CLAUDE.md` with the workspace text among its read-only workspace files and writes no `CLAUDE.md` itself, and renders a `.claude/settings.json` whose `hooks` key equals the payload byte for byte as JSON. It places the files under `.claude/hooks/` with mode 0755, and the home `--settings` file holds an `InstructionsLoaded` observer in headless mode as in session mode. On the base, the plan has none of these. -- ⬜ A cell without these values renders the same `.claude/settings.json` as on the base. Only the home observers file is added. -- ⬜ The census of a run that recorded `InstructionsLoaded` lists the global file (User, or Project for the parent directory) and `{path: CLAUDE.md, scope: Project}`, read from a recorded `.candler/hooks.jsonl` fixture. -- ⬜ An adversarial Sonnet review finds no way for a payload to disable Candler's observers, or to write outside `.claude/`. +- ✅ G3 (Claude Code). The *instructions*, *hooks* and *config check* rows show the Claude Code mapping: the global file's place from the probe, and the workspace's root `CLAUDE.md`, read-only; the `hooks` key of `.claude/settings.json`, with files under `.claude/hooks/`; and the probe's check or `no (…)`. On the base, no such rows exist. +- ✅ The plan of a cell with all four values places the global text where the probe settled, lists `CLAUDE.md` with the workspace text among its read-only workspace files and writes no `CLAUDE.md` itself, and renders a `.claude/settings.json` whose `hooks` key equals the payload byte for byte as JSON. It places the files under `.claude/hooks/` with mode 0755, and the home `--settings` file holds an `InstructionsLoaded` observer in headless mode as in session mode. On the base, the plan has none of these. +- ✅ A cell without these values renders the same `.claude/settings.json` as on the base. Only the home observers file is added. +- ✅ The census of a run that recorded `InstructionsLoaded` lists the global file (User, or Project for the parent directory) and `{path: CLAUDE.md, scope: Project}`, read from a recorded `.candler/hooks.jsonl` fixture. +- ✅ An adversarial Sonnet review finds no way for a payload to disable Candler's observers, or to write outside `.claude/`. **References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-claude-code/src/prepare.rs` (`render_settings`), `session.rs` (`HOOK_EVENTS`, `hooks()`), `discovery.rs` (`EXCLUDED_DIRS`); the probe report ## Step 1: Render and install From de63a12504011ecd199b81a1e4782b86f7679e27 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:49:35 +0900 Subject: [PATCH 44/69] fix(api): name the hooks type the check reads for its pointer The Claude Code install made the hooks reader generic; the check's setting pointer read it without a type and the merged tree did not build. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/jobs/orchestrate/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/candler-core/src/jobs/orchestrate/config.rs b/crates/candler-core/src/jobs/orchestrate/config.rs index 41393b98..cc696b52 100644 --- a/crates/candler-core/src/jobs/orchestrate/config.rs +++ b/crates/candler-core/src/jobs/orchestrate/config.rs @@ -77,7 +77,7 @@ fn files_digest(plan: &Plan, command_words: &[String]) -> Digest { /// The pointer into the experiment file of the setting the installed files come from. fn setting_pointer(view: &Cell<'_>, harness: &str) -> String { // EXPLICIT: a value the reader refuses was refused when the runs were planned - if agent_config::hooks(view, harness).ok().flatten().is_some() { + if agent_config::hooks::(view, harness).ok().flatten().is_some() { pointer_of(["fixed", "hooks"]) } else if agent_config::instructions(view, harness) .ok() From 9ab068fcd34422cebb7650801b5188704c69ef0e Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:53:14 +0900 Subject: [PATCH 45/69] fix(api): read a harness check's findings whatever its exit The core keeps a check's stdout, stderr and exit status and gives the driver stdout then stderr. A check that cannot run, prints nothing or is cut at the capture limit is refused as jobs.config_check_failed. Co-Authored-By: Claude Sonnet 5.5 --- .../src/isolation/container/mod.rs | 8 +- crates/candler-core/src/isolation/docker.rs | 70 +++++++++ crates/candler-core/src/isolation/driver.rs | 18 ++- crates/candler-core/src/isolation/mod.rs | 15 +- crates/candler-core/src/isolation/testing.rs | 26 +++- .../src/jobs/orchestrate/config.rs | 68 ++++++-- crates/candler-core/src/jobs/refusal.rs | 11 +- crates/candler-core/src/runner/exec/gather.rs | 6 +- .../tests/it/guard_config_check.rs | 147 +++++++++++++++--- .../tests/it/guard_container_record.rs | 2 +- .../tests/it/guard_refusal_codes.rs | 7 +- .../tests/it/support/job_orchestrate.rs | 8 +- crates/candler-harness/src/driver.rs | 11 ++ docs/contract/codes.toml | 5 + docs/contract/index.md | 1 + 15 files changed, 344 insertions(+), 59 deletions(-) diff --git a/crates/candler-core/src/isolation/container/mod.rs b/crates/candler-core/src/isolation/container/mod.rs index 884c9778..3512fb6e 100644 --- a/crates/candler-core/src/isolation/container/mod.rs +++ b/crates/candler-core/src/isolation/container/mod.rs @@ -34,7 +34,9 @@ use super::model::{ ContainerOutcome, ContainerPlan, ContainerRef, ContainerSweep, GatewayHandle, ImageId, ImageRef, Inspect, LabelSel, Limits, Refusal, SweepScope, UserSpec, }; -use super::{EndFacts, IsolatedRequest, Isolation, IsolationError, RunOutputs, StartProbe}; +use super::{ + EndFacts, ExecOutput, IsolatedRequest, Isolation, IsolationError, RunOutputs, StartProbe, +}; use crate::supervise::hook::{HookError, StopHook}; use crate::supervise::stop::Exit; use candler_schemas::execution::paths; @@ -537,7 +539,7 @@ impl Isolation for DockerIsolation { &'a self, plan: &'a ContainerPlan, command: &'a CommandSpec, - ) -> BoxFuture<'a, Result, IsolationError>> { + ) -> BoxFuture<'a, Result> { Box::pin(async move { let args = exec::collect_spec(plan, command, COLLECT_WALL) .map(|spec| spec.args()) @@ -545,7 +547,7 @@ impl Isolation for DockerIsolation { detail: source.to_string(), })?; self.docker - .capture(args, COLLECT_WALL + EXPIRY_MARGIN) + .capture_exec(args, COLLECT_WALL + EXPIRY_MARGIN) .await .map_err(|source| IsolationError::Docker { detail: source.to_string(), diff --git a/crates/candler-core/src/isolation/docker.rs b/crates/candler-core/src/isolation/docker.rs index 04916092..7bcb98eb 100644 --- a/crates/candler-core/src/isolation/docker.rs +++ b/crates/candler-core/src/isolation/docker.rs @@ -48,6 +48,59 @@ const BUILD_DEADLINE: Duration = Duration::from_mins(15); /// How many bytes of a client's output are kept. pub(crate) const OUTPUT_LIMIT: usize = 4 * 1024 * 1024; +/// How a container call ended and what it printed: the exit status and the first bytes of each +/// stream, whichever way the call ended. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct ExecOutput { + /// What the call printed on standard output, at most the capture limit. + pub stdout: Vec, + /// What the call printed on standard error, at most the capture limit. + pub stderr: Vec, + /// How the call ended. + pub status: ExitStatus, + /// Whether either stream reached the capture limit, so that the rest of it was dropped. + pub truncated: bool, +} + +impl ExecOutput { + /// A call that exited `0` and printed `stdout`. + #[must_use] + pub const fn printed(stdout: Vec) -> Self { + Self { + stdout, + stderr: Vec::new(), + status: ExitStatus::Code { code: 0 }, + truncated: false, + } + } + + /// A call that exited with `code` and printed `stderr`. + #[must_use] + pub const fn exited(code: i32, stderr: Vec) -> Self { + Self { + stdout: Vec::new(), + stderr, + status: ExitStatus::Code { code }, + truncated: false, + } + } + + /// What the call printed on standard output when it exited `0`. + /// + /// # Errors + /// [`DockerError::Failed`] with the first line of standard error when the call exited + /// otherwise. + pub fn into_stdout(self) -> Result, DockerError> { + match self.status { + ExitStatus::Code { code: 0 } => Ok(self.stdout), + ExitStatus::Code { .. } | ExitStatus::Signal { .. } => Err(DockerError::Failed { + detail: detail_of(&self.stderr), + }), + } + } +} + /// How many bytes of a captured container call's output are kept: an export of a long session. const CAPTURE_LIMIT: usize = 64 * 1024 * 1024; @@ -823,6 +876,23 @@ impl DockerDriver for DockerCli { Box::pin(async move { self.runner.run_bytes(args, deadline, CAPTURE_LIMIT).await }) } + fn capture_exec( + &self, + args: Vec, + deadline: Duration, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + let captured = self.runner.captured(args, deadline, CAPTURE_LIMIT).await?; + Ok(ExecOutput { + truncated: captured.stdout.len() >= CAPTURE_LIMIT + || captured.stderr.len() >= CAPTURE_LIMIT, + stdout: captured.stdout, + stderr: captured.stderr, + status: captured.exit.status, + }) + }) + } + fn inspect<'a>(&'a self, id: &'a str) -> BoxFuture<'a, Result> { Box::pin(async move { if !is_full_id(id) { diff --git a/crates/candler-core/src/isolation/driver.rs b/crates/candler-core/src/isolation/driver.rs index f3f56016..10be9aa1 100644 --- a/crates/candler-core/src/isolation/driver.rs +++ b/crates/candler-core/src/isolation/driver.rs @@ -6,7 +6,7 @@ use std::time::Duration; use candler_schemas::primitives::ContainerId; use futures::future::BoxFuture; -use super::docker::{AttachedRun, DockerError, attached_request}; +use super::docker::{AttachedRun, DockerError, ExecOutput, attached_request}; use super::model::{ BuildRequest, ContainerRef, ImageInfo, Inspect, LabelSel, Labels, NetworkInfo, NetworkName, }; @@ -168,6 +168,22 @@ pub trait DockerDriver: Send + Sync { }) }) } + + /// Runs `docker ` as [`DockerDriver::capture`] does and returns how it ended with what + /// it printed on each stream, whatever the exit status. The default answers as `capture` + /// does, with an exit of `0`. + /// + /// # Errors + /// [`DockerError::Unavailable`] for a driver that runs no such call, and [`DockerError`] when + /// docker cannot be run or the call outlives `deadline`. + fn capture_exec( + &self, + args: Vec, + deadline: Duration, + ) -> BoxFuture<'_, Result> { + let printed = self.capture(args, deadline); + Box::pin(async move { printed.await.map(ExecOutput::printed) }) + } } /// The destroy half of docker: stop, remove, remove a network. Only the guard holds one. diff --git a/crates/candler-core/src/isolation/mod.rs b/crates/candler-core/src/isolation/mod.rs index ce474e56..2c2645da 100644 --- a/crates/candler-core/src/isolation/mod.rs +++ b/crates/candler-core/src/isolation/mod.rs @@ -27,6 +27,7 @@ use crate::supervise::hook::HookError; use crate::supervise::spawn::{OutputSpec, SpawnRequest}; use crate::supervise::stop::Exit; +pub use self::docker::ExecOutput; pub use self::model::{ContainerOutcome, ContainerPlan}; /// Why an isolation step failed. @@ -223,19 +224,21 @@ pub trait Isolation: Send + Sync { ) -> BoxFuture<'a, Result>; /// Runs `command` in a throwaway container over the run's mounts, environment and user and - /// returns what it printed on standard output. The agent's container may have exited: what - /// the harness keeps lives in the run's mounts. The container has no network and carries - /// neither the gateway's address nor its token. An isolation without containers refuses. + /// returns how it ended with what it printed on each stream: a command that exits with a + /// status other than `0` is an answer, not an error. The agent's container may have exited: + /// what the harness keeps lives in the run's mounts. The container has no network and + /// carries neither the gateway's address nor its token. An isolation without containers + /// refuses. /// /// # Errors /// [`IsolationError::Plan`] when the command cannot be wrapped over the plan, - /// [`IsolationError::Docker`] when docker fails, and [`IsolationError::Unavailable`] for an - /// isolation that runs none. + /// [`IsolationError::Docker`] when docker cannot be run or the command outlives its wall, and + /// [`IsolationError::Unavailable`] for an isolation that runs none. fn collect_exec<'a>( &'a self, plan: &'a ContainerPlan, command: &'a CommandSpec, - ) -> BoxFuture<'a, Result, IsolationError>> { + ) -> BoxFuture<'a, Result> { let _ = (plan, command); Box::pin(async { Err(IsolationError::Unavailable { diff --git a/crates/candler-core/src/isolation/testing.rs b/crates/candler-core/src/isolation/testing.rs index cf3f2718..a3e59bc4 100644 --- a/crates/candler-core/src/isolation/testing.rs +++ b/crates/candler-core/src/isolation/testing.rs @@ -388,6 +388,14 @@ impl DockerDriver for AllowlistDriver { ) -> BoxFuture<'_, Result, DockerError>> { self.inner.capture(args, deadline) } + + fn capture_exec( + &self, + args: Vec, + deadline: std::time::Duration, + ) -> BoxFuture<'_, Result> { + self.inner.capture_exec(args, deadline) + } } impl DestroyDriver for AllowlistDriver { @@ -477,7 +485,7 @@ pub struct ProbingIsolation { runs: Mutex, eof_exits: Mutex>, needs: Mutex>, - prints: Mutex>, + prints: Mutex>, executed: Mutex, Vec)>>, run_mounts: Mutex>>, } @@ -503,7 +511,15 @@ impl ProbingIsolation { /// Makes a command run for its output whose program is `program` print `output`; one no /// answer names prints nothing. pub fn print(&self, program: &str, output: &str) { - held(&self.prints).insert(program.to_owned(), output.to_owned()); // BORROW: the script owns its words + held(&self.prints).insert( + program.to_owned(), // BORROW: the script owns its words + super::docker::ExecOutput::printed(output.as_bytes().to_vec()), + ); + } + + /// Makes a command run for its output whose program is `program` end as `output` says. + pub fn ran(&self, program: &str, output: super::docker::ExecOutput) { + held(&self.prints).insert(program.to_owned(), output); // BORROW: the script owns its words } /// The commands run for their output so far, as their words, each with the mounts of the @@ -575,14 +591,14 @@ impl super::Isolation for ProbingIsolation { &'a self, plan: &'a super::model::ContainerPlan, command: &'a candler_harness::spec::CommandSpec, - ) -> BoxFuture<'a, Result, super::IsolationError>> { + ) -> BoxFuture<'a, Result> { held(&self.executed).push((command.argv().to_vec(), plan.mounts.clone())); // BORROW: the log owns the words and the mounts let printed = command .argv() .first() .and_then(|program| held(&self.prints).get(program).cloned()) // BORROW: the caller owns the output - .unwrap_or_default(); - Box::pin(async move { Ok(printed.into_bytes()) }) + .unwrap_or_else(|| super::docker::ExecOutput::printed(Vec::new())); + Box::pin(async move { Ok(printed) }) } fn collect_and_destroy<'a>( diff --git a/crates/candler-core/src/jobs/orchestrate/config.rs b/crates/candler-core/src/jobs/orchestrate/config.rs index cc696b52..1a567d8a 100644 --- a/crates/candler-core/src/jobs/orchestrate/config.rs +++ b/crates/candler-core/src/jobs/orchestrate/config.rs @@ -11,11 +11,12 @@ use candler_harness::agent_config; use candler_harness::driver::{DriverError, Plan}; use candler_harness::spec::{Cell, CheckVerdict, FileRoot, PreparedFile, Workspace}; use candler_schemas::primitives::Digest; +use candler_schemas::process::ExitStatus; use candler_schemas::refusal::pointer_of; -use super::servers::{ServerCheckError, stage_container}; +use super::servers::stage_container; use super::session::image_of; -use crate::isolation::Isolation; +use crate::isolation::{ExecOutput, Isolation}; use crate::runner::Runtime; use crate::runner::plan::{CellId, RunPlan}; @@ -27,9 +28,12 @@ pub enum ConfigCheckError { /// describe the cell. #[error(transparent)] Driver(#[from] DriverError), - /// The check could not run. - #[error(transparent)] - Check(#[from] ServerCheckError), + /// The check could not run, or printed nothing a verdict can be read from. + #[error("the harness check could not run: {detail}")] + Check { + /// What went wrong. + detail: String, + }, } /// The harness, the image and the digest of everything the check reads: the cells that share all @@ -40,9 +44,46 @@ type GroupKey = (String, Option, Digest); type Groups<'a> = BTreeMap)>; fn failed(detail: &impl ToString) -> ConfigCheckError { - ConfigCheckError::Check(ServerCheckError::ServerCheck { + ConfigCheckError::Check { detail: detail.to_string(), // BORROW: .to_string() gives owned text - }) + } +} + +/// The exit codes of the check's wrapper that say the command did not run: the in-container +/// timeout, docker's own failure, a command that cannot be executed and one that is not found. +const NOT_RUN: [i32; 4] = [124, 125, 126, 127]; + +/// The bytes the driver reads its verdict from: standard output followed by standard error. +/// +/// The exit status does not decide the verdict, as a harness may report a finding by exiting +/// non-zero. +/// +/// # Errors +/// [`ConfigCheckError::Check`] when the command did not run (it exited with one of [`NOT_RUN`] or +/// was ended by a signal), when either stream was cut at the capture limit, or when it printed +/// nothing. +fn verdict_bytes(output: ExecOutput) -> Result, ConfigCheckError> { + match output.status { + ExitStatus::Signal { signal } => { + return Err(failed(&format!("the check was ended by signal {signal}"))); + } + ExitStatus::Code { code } if NOT_RUN.contains(&code) => { + return Err(failed(&format!( + "the check command did not run: it exited {code}: {}", + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + ExitStatus::Code { .. } => {} + } + if output.truncated { + return Err(failed(&"the check printed more than the core keeps")); + } + let mut bytes = output.stdout; + bytes.extend_from_slice(&output.stderr); + if bytes.is_empty() { + return Err(failed(&"the check printed nothing")); + } + Ok(bytes) } /// The files `plan` installs, whichever root they are written under. @@ -77,7 +118,11 @@ fn files_digest(plan: &Plan, command_words: &[String]) -> Digest { /// The pointer into the experiment file of the setting the installed files come from. fn setting_pointer(view: &Cell<'_>, harness: &str) -> String { // EXPLICIT: a value the reader refuses was refused when the runs were planned - if agent_config::hooks::(view, harness).ok().flatten().is_some() { + if agent_config::hooks::(view, harness) + .ok() + .flatten() + .is_some() + { pointer_of(["fixed", "hooks"]) } else if agent_config::instructions(view, harness) .ok() @@ -115,8 +160,8 @@ fn installed_at(plan: &Plan) -> (String, String) { /// and records a clean verdict on the cells it covered. A cell whose driver has no check is not /// checked and keeps no verdict. /// -/// The check command prints its verdict on standard output and exits `0`: a command that exits -/// otherwise did not run. +/// The check command's standard output followed by its standard error is the driver's to read, +/// whatever the exit status; see [`verdict_bytes`] for when the check did not run. /// /// # Errors /// [`ConfigCheckError::Driver`] with [`DriverError::HarnessRejectedInput`] when the harness @@ -205,10 +250,11 @@ async fn check_group( let Some(command) = rt.driver.config_check(&staged) else { return Ok(()); }; - let output = isolation + let ran = isolation .collect_exec(&container, &command) .await .map_err(|e| failed(&e))?; + let output = verdict_bytes(ran)?; match rt.driver.read_config_check(&output) { CheckVerdict::Clean => Ok(()), CheckVerdict::Rejected { output } => { diff --git a/crates/candler-core/src/jobs/refusal.rs b/crates/candler-core/src/jobs/refusal.rs index 17ef1981..ee829212 100644 --- a/crates/candler-core/src/jobs/refusal.rs +++ b/crates/candler-core/src/jobs/refusal.rs @@ -59,7 +59,7 @@ fn orchestrate_error_path(error: &OrchestrateError) -> Option { fn config_check_error_path(error: &ConfigCheckError) -> Option { match error { ConfigCheckError::Driver(inner) => Refusal::path(inner), - ConfigCheckError::Check(inner) => Refusal::path(inner), + ConfigCheckError::Check { .. } => None, } } @@ -374,7 +374,12 @@ refusal_table! { wrapper_table! { ConfigCheckError, path = config_check_error_path; Driver (inner) => delegate(inner, Side::Experiment), - Check (inner) => delegate(inner, Side::Environment), + Check { .. } => row( + "jobs.config_check_failed", + Side::Environment, + "The harness's own check of the files Candler installed for it could not run, or printed nothing a verdict can be read from, for example because its container could not be started, the command is missing or timed out, or its output was cut short.", + "-", + ), } /// The rows of every coded error of this module, in the order of the types. @@ -416,7 +421,7 @@ fn recover_answer(error: &RecoverError) -> &dyn Refusal { fn config_answer(error: &ConfigCheckError) -> &dyn Refusal { match error { ConfigCheckError::Driver(inner) => crate::refusal::through(inner, error), - ConfigCheckError::Check(inner) => crate::refusal::through(inner, error), + ConfigCheckError::Check { .. } => error, } } diff --git a/crates/candler-core/src/runner/exec/gather.rs b/crates/candler-core/src/runner/exec/gather.rs index 823fb2c8..8a219f00 100644 --- a/crates/candler-core/src/runner/exec/gather.rs +++ b/crates/candler-core/src/runner/exec/gather.rs @@ -176,7 +176,11 @@ pub async fn collect_commands( if let CollectSpec::Exec { spec, name, .. } = spec { found.push(Collected { name: name.clone(), // BORROW: the result owns the stream name - output: isolation.collect_exec(plan, spec).await, + output: isolation.collect_exec(plan, spec).await.and_then(|ran| { + ran.into_stdout().map_err(|source| IsolationError::Docker { + detail: source.to_string(), + }) + }), }); } } diff --git a/crates/candler-core/tests/it/guard_config_check.rs b/crates/candler-core/tests/it/guard_config_check.rs index 942f099d..c3e0dba7 100644 --- a/crates/candler-core/tests/it/guard_config_check.rs +++ b/crates/candler-core/tests/it/guard_config_check.rs @@ -12,6 +12,7 @@ use crate::support; use std::fs; use std::sync::Arc; +use candler_core::isolation::ExecOutput; use candler_core::isolation::container::mounts::{MountMode, MountSpec}; use candler_core::jobs::model::{JobOutcome, JobSpec}; use candler_core::jobs::orchestrate::session::JobHost; @@ -24,6 +25,7 @@ use candler_harness::spec::{ }; use candler_schemas::execution::Comparable; use candler_schemas::primitives::RelPath; +use candler_schemas::process::ExitStatus; use candler_schemas::raw::StreamName; use candler_schemas::trace::{EndedBy, Session}; use candler_schemas::values::{JsonValue, ResolvedValue}; @@ -204,11 +206,11 @@ struct Ran { host: Arc, } -/// Runs `job` under `driver` to its end, with the check printing `printed`. -fn run(job: JobSpec, driver: Checking, printed: &str) -> Ran { +/// Runs `job` under `driver` to its end, over a host `script` has set up. +fn run_with(job: JobSpec, driver: Checking, script: impl FnOnce(&mut Probed)) -> Ran { let rig = Rig::new(0); let mut host = Probed::new(rig.host()); - host.prints = vec![(CHECK.to_owned(), printed.to_owned())]; + script(&mut host); let host = Arc::new(host); let shared: Arc = host.clone(); let mut rt = rig.runtime(); @@ -217,6 +219,38 @@ fn run(job: JobSpec, driver: Checking, printed: &str) -> Ran { Ran { rig, outcome, host } } +/// Runs `job` under `driver` to its end, with the check printing `printed`. +fn run(job: JobSpec, driver: Checking, printed: &str) -> Ran { + run_with(job, driver, |host| { + host.prints = vec![(CHECK.to_owned(), printed.to_owned())]; + }) +} + +/// Runs `job` under `driver` to its end, with the check ending as `output` says. +fn run_ending(job: JobSpec, driver: Checking, output: ExecOutput) -> Ran { + run_with(job, driver, |host| { + host.ran = vec![(CHECK.to_owned(), output)]; + }) +} + +/// The supervisor's stderr of the job `child` runs when this test runs again as a child of the +/// test binary, or `None` in the child itself, where `child` runs. The job's refusal is a line +/// of that stderr. +fn refusal_of(test: &str, child: impl FnOnce()) -> Option { + if std::env::var_os("CANDLER_CONFIG_CHECK_CHILD").is_some() { + child(); + return None; + } + let out = std::process::Command::new(std::env::current_exe().expect("the test binary")) + .args([test, "--exact", "--nocapture", "--test-threads=1"]) + .env("CANDLER_CONFIG_CHECK_CHILD", "1") + .output() + .expect("the child ran"); + let stderr = String::from_utf8_lossy(&out.stderr).into_owned(); + assert!(out.status.success(), "the child's guards held: {stderr}"); + Some(stderr) +} + /// The file `name` of the first run's directory, read as JSON. fn run_file(ran: &Ran, name: &str) -> Value { let key = &ran.outcome.runs.first().expect("one run").key; @@ -255,26 +289,21 @@ fn mount_at<'m>(mounts: &'m [MountSpec], target: &str) -> Option<&'m MountSpec> /// Bite: the refusal drops the harness's output, or the check runs after the runs are scheduled. #[test] fn harness_finding_refuses_the_job_before_any_run() { - const NAME: &str = "guard_config_check::harness_finding_refuses_the_job_before_any_run"; - if std::env::var_os("CANDLER_CONFIG_CHECK_CHILD").is_some() { - let ran = run( - job(&["m1"]), - Checking::new(true), - "REJECT: unknown key hooks.Foo", - ); - let probing = ran.host.probing(); - assert_eq!(probing.executed().len(), 1, "the check ran once"); - assert_eq!(probing.runs(), 0, "no run starts"); - assert!(ran.outcome.runs.is_empty(), "no run is recorded"); - return; - } - let child = std::process::Command::new(std::env::current_exe().expect("the test binary")) - .args([NAME, "--exact", "--nocapture", "--test-threads=1"]) - .env("CANDLER_CONFIG_CHECK_CHILD", "1") - .output() - .expect("the child ran"); - let stderr = String::from_utf8_lossy(&child.stderr); - assert!(child.status.success(), "the child's guards held: {stderr}"); + let line = refusal_of( + "guard_config_check::harness_finding_refuses_the_job_before_any_run", + || { + let ran = run( + job(&["m1"]), + Checking::new(true), + "REJECT: unknown key hooks.Foo", + ); + let probing = ran.host.probing(); + assert_eq!(probing.executed().len(), 1, "the check ran once"); + assert_eq!(probing.runs(), 0, "no run starts"); + assert!(ran.outcome.runs.is_empty(), "no run is recorded"); + }, + ); + let Some(stderr) = line else { return }; assert!( stderr.contains( "Candler installed the files `settings.json`, `AGENTS.md` at the agent's home and the workspace; claude-code rejects it: REJECT: unknown key hooks.Foo" @@ -283,6 +312,78 @@ fn harness_finding_refuses_the_job_before_any_run() { ); } +/// Guards: a harness check that exits non-zero with its finding on standard error refuses the +/// job as a finding, quoting that text, and not as a check that could not run; the exit status +/// does not decide the verdict. +/// Oracle: the literal `REJECT: unknown key hooks.Foo` the scripted check prints on standard +/// error and the exit code `1`, which `OpenCode`'s check exits with for every report. +/// Bite: read the verdict from standard output alone, or treat a non-zero exit as a check that +/// could not run. +#[test] +fn finding_on_stderr_with_a_failing_exit_refuses_as_a_finding() { + let line = refusal_of( + "guard_config_check::finding_on_stderr_with_a_failing_exit_refuses_as_a_finding", + || { + let ran = run_ending( + job(&["m1"]), + Checking::new(true), + ExecOutput::exited(1, b"REJECT: unknown key hooks.Foo".to_vec()), + ); + assert_eq!(ran.host.probing().runs(), 0, "no run starts"); + assert!(ran.outcome.runs.is_empty(), "no run is recorded"); + }, + ); + let Some(stderr) = line else { return }; + assert!( + stderr.contains("claude-code rejects it: REJECT: unknown key hooks.Foo"), + "the refusal quotes the harness: {stderr}" + ); + assert!( + !stderr.contains("could not run"), + "a finding is no failed check: {stderr}" + ); +} + +/// Guards: a check that did not run, printed nothing or printed more than the core keeps is +/// refused as a check that could not run, whatever the stand-in's reader would say of the text: +/// no output, a command that is missing (`127`), the in-container timeout (`124`), a signal and +/// output cut at the capture limit. +/// Oracle: the exit codes `127` and `124` that the shell and `timeout` give, signal 9, and the +/// wording of the refusal written by hand. +/// Bite: pass the empty or cut output to the driver, or read the exit code as a verdict. +#[test] +fn a_check_that_did_not_run_or_printed_nothing_is_refused() { + let mut killed = ExecOutput::printed(b"fine".to_vec()); + killed.status = ExitStatus::Signal { signal: 9 }; + let mut cut = ExecOutput::printed(b"fine".to_vec()); + cut.truncated = true; + let line = refusal_of( + "guard_config_check::a_check_that_did_not_run_or_printed_nothing_is_refused", + || { + for (case, output) in [ + ("empty", ExecOutput::printed(Vec::new())), + ("missing", ExecOutput::exited(127, b"not found".to_vec())), + ("timeout", ExecOutput::exited(124, Vec::new())), + ("signal", killed), + ("cut", cut), + ] { + let ran = run_ending(job(&["m1"]), Checking::new(true), output); + assert_eq!(ran.host.probing().runs(), 0, "{case}: no run starts"); + } + }, + ); + let Some(stderr) = line else { return }; + for expected in [ + "the harness check could not run: the check printed nothing", + "the harness check could not run: the check command did not run: it exited 127: not found", + "it exited 124", + "the check was ended by signal 9", + "the check printed more than the core keeps", + ] { + assert!(stderr.contains(expected), "{expected}: {stderr}"); + } +} + /// Guards: a clean verdict is stored in the run's provenance, and a harness with no check leaves /// the run with nothing stored as checked and the job not refused. /// Oracle: the literal `provenance.harness_config_check` path and `clean` value, read from the diff --git a/crates/candler-core/tests/it/guard_container_record.rs b/crates/candler-core/tests/it/guard_container_record.rs index d955aee5..5d17d645 100644 --- a/crates/candler-core/tests/it/guard_container_record.rs +++ b/crates/candler-core/tests/it/guard_container_record.rs @@ -917,7 +917,7 @@ impl Isolation for Unstartable { &'a self, plan: &'a ContainerPlan, command: &'a CommandSpec, - ) -> BoxFuture<'a, Result, IsolationError>> { + ) -> BoxFuture<'a, Result> { self.inner.collect_exec(plan, command) } diff --git a/crates/candler-core/tests/it/guard_refusal_codes.rs b/crates/candler-core/tests/it/guard_refusal_codes.rs index 83d7ed31..6cfaf7cd 100644 --- a/crates/candler-core/tests/it/guard_refusal_codes.rs +++ b/crates/candler-core/tests/it/guard_refusal_codes.rs @@ -619,7 +619,6 @@ fn wrapped_cases() -> Vec { use candler_core::jobs::dir::JobError; use candler_core::jobs::lost::RecoverError; use candler_core::jobs::orchestrate::config::ConfigCheckError; - use candler_core::jobs::orchestrate::servers::ServerCheckError; use candler_core::jobs::orchestrate::session::OrchestrateError; use candler_core::jobs::slots::SlotError; use candler_core::resolve::preflight::ResolveError; @@ -1036,10 +1035,10 @@ fn wrapped_cases() -> Vec { case( "ConfigCheckError", "Check", - Box::new(ConfigCheckError::Check(ServerCheckError::ServerCheck { + Box::new(ConfigCheckError::Check { detail: "no container".to_owned(), - })), - "jobs.server_check_failed", + }), + "jobs.config_check_failed", ), // The import's. case( diff --git a/crates/candler-core/tests/it/support/job_orchestrate.rs b/crates/candler-core/tests/it/support/job_orchestrate.rs index 3a831bce..0ea7820e 100644 --- a/crates/candler-core/tests/it/support/job_orchestrate.rs +++ b/crates/candler-core/tests/it/support/job_orchestrate.rs @@ -196,7 +196,7 @@ impl Isolation for Placed { &'a self, plan: &'a ContainerPlan, command: &'a CommandSpec, - ) -> BoxFuture<'a, Result, IsolationError>> { + ) -> BoxFuture<'a, Result> { if self.agent.is_some() { return self.inner.collect_exec(plan, command); } @@ -832,6 +832,8 @@ pub struct Probed { pub needs: Vec, /// What a command run for its output prints, by program. pub prints: Vec<(String, String)>, + /// How a command run for its output ends, by program, where it prints more than text. + pub ran: Vec<(String, candler_core::isolation::ExecOutput)>, probing: Mutex>>, } @@ -844,6 +846,7 @@ impl Probed { eof_exits: Vec::new(), needs: Vec::new(), prints: Vec::new(), + ran: Vec::new(), probing: Mutex::new(None), } } @@ -889,6 +892,9 @@ impl JobHost for Probed { for (program, output) in &self.prints { probing.print(program, output); } + for (program, output) in &self.ran { + probing.ran(program, output.clone()); // BORROW: the double owns its answers + } *self.probing.lock().expect("the double") = Some(Arc::clone(&probing)); // BORROW: the test reads the same double probing } diff --git a/crates/candler-harness/src/driver.rs b/crates/candler-harness/src/driver.rs index 7b1eac55..a0cc070b 100644 --- a/crates/candler-harness/src/driver.rs +++ b/crates/candler-harness/src/driver.rs @@ -175,10 +175,21 @@ pub trait HarnessDriver: Send + Sync { /// cell's image without network, or `None` for a harness with no check. The answer agrees /// with [`DriverFact::ConfigCheck`]: a driver that states the fact refused returns `None`, /// and one that states it mapped returns a command. + /// + /// The core runs the command and keeps what it printed on standard output and on standard + /// error. The exit status does not decide the verdict, so a command that reports a finding by + /// exiting non-zero, and one that reports on standard error, are read by + /// [`HarnessDriver::read_config_check`]. The check could not run, and the job is refused for + /// that, when the command cannot be started, exits `124` (the core's timeout), `125`, `126` or + /// `127`, is ended by a signal, prints nothing, or prints more than the core keeps. fn config_check(&self, plan: &Plan) -> Option; /// What the output of [`HarnessDriver::config_check`] says of the files; a driver with no /// check reads every output as clean. + /// + /// `output` is the command's standard output followed by its standard error, as one byte + /// string, whatever its exit status; it is never empty and never cut short. The driver reads + /// a finding wherever the harness prints one. fn read_config_check(&self, output: &[u8]) -> CheckVerdict; /// The name of the file the harness reads at the root of the workspace as instructions. diff --git a/docs/contract/codes.toml b/docs/contract/codes.toml index 39bb2a32..88afd29e 100644 --- a/docs/contract/codes.toml +++ b/docs/contract/codes.toml @@ -1007,6 +1007,11 @@ side = "experiment" enum = "ServerCheckError" variant = "Server" +[jobs."jobs.config_check_failed"] +side = "environment" +enum = "ConfigCheckError" +variant = "Check" + [jobs."jobs.server_check_failed"] side = "environment" enum = "ServerCheckError" diff --git a/docs/contract/index.md b/docs/contract/index.md index f6af1cc7..8f6d0a07 100644 --- a/docs/contract/index.md +++ b/docs/contract/index.md @@ -169,6 +169,7 @@ Surfaces that name no page of their own: configuration, resolving, running, isol | `isolation.sweep_list_failed` | Docker failed while the sweeper listed containers. | - | environment | | `jobs.already_supervised` | Another supervisor already holds the lock of the job. | - | environment | | `jobs.child_not_reaped` | A host process left behind by a lost job could not be reaped. | - | environment | +| `jobs.config_check_failed` | The harness's own check of the files Candler installed for it could not run, or printed nothing a verdict can be read from, for example because its container could not be started, the command is missing or timed out, or its output was cut short. | - | environment | | `jobs.directory_exists` | The directory of a job to create already exists. | - | environment | | `jobs.docker_unavailable` | The docker client cannot be reached when a job's session starts. | - | environment | | `jobs.gateway_not_serving` | The gateway of the job does not serve, for example because it did not start or refused the token. | - | environment | From 6e9971b8efba2dfc31803929f1775b3c79418e87 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 17:56:05 +0900 Subject: [PATCH 46/69] refactor(api): share one gateway stream reader, ask the census as a bool The gateway stream's line shapes and one parse function now live next to its name in candler-harness, so both core readers and the drivers read it the same way. The trait method that named a stream the core never used as one answers whether the census comes from the gateway. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/isolation/gateway.rs | 69 ++++++++----------- crates/candler-core/src/runner/exec/mod.rs | 2 +- .../candler-core/tests/it/support/wiring.rs | 4 +- crates/candler-harness-opencode/src/driver.rs | 6 +- crates/candler-harness/src/conformance.rs | 18 ++--- crates/candler-harness/src/driver.rs | 13 ++-- crates/candler-harness/src/spec.rs | 47 +++++++++++++ .../tests/it/conformance_shapes.rs | 36 +++++----- .../candler-harness/tests/it/support/mod.rs | 12 ++-- docs/contract/driver-traits.md | 4 +- 10 files changed, 119 insertions(+), 92 deletions(-) diff --git a/crates/candler-core/src/isolation/gateway.rs b/crates/candler-core/src/isolation/gateway.rs index 9e0da00e..a8761a9b 100644 --- a/crates/candler-core/src/isolation/gateway.rs +++ b/crates/candler-core/src/isolation/gateway.rs @@ -10,7 +10,9 @@ use std::sync::Arc; use std::time::{Duration, SystemTime}; -use candler_harness::spec::{CensusSource, InitReport}; +use candler_harness::spec::{ + CensusSource, GatewayRecord, InitReport, StartContext, gateway_records, +}; use candler_schemas::container::{ContainerLabels, ContainerRecord, ContainerRole}; use candler_schemas::primitives::{ContainerId, Digest, JobId, Marker, RunKey}; use candler_schemas::process::ExitStatus; @@ -1220,14 +1222,6 @@ fn signals_of(log: &str, run: &RunKey, tag: &str) -> Vec { signals } -/// The members of a context line: the system text and the first message of a request. -#[derive(serde::Deserialize)] -#[serde(deny_unknown_fields)] -struct ContextBody { - system: String, - first_message: String, -} - /// What the sidecar's log says of the run `run` under its tag `tag`: one JSON line for each census /// line and each context line of the gateway whose `run=` and `tag=` fields equal these. /// @@ -1276,7 +1270,7 @@ pub fn census_of(log: &str, run: &RunKey, tag: &str) -> Vec { .map(|tools| serde_json::json!({"seq": seq, "tools": tools})) } else { rest.strip_prefix("body=") - .and_then(|text| serde_json::from_str::(text).ok()) + .and_then(|text| serde_json::from_str::(text).ok()) .map(|body| { serde_json::json!({ "seq": seq, @@ -1297,28 +1291,20 @@ pub fn census_of(log: &str, run: &RunKey, tag: &str) -> Vec { /// requests carried tools has none. #[must_use] pub fn census_context(stream: &[u8]) -> Option<(u64, EventKind)> { - #[derive(serde::Deserialize)] - struct Record { - seq: u64, - context: ContextBody, - } - stream - .split(|byte| *byte == b'\n') - .enumerate() - .filter_map(|(frame, line)| { - serde_json::from_slice::(line) - .ok() - .map(|record| (frame, record)) - }) - .min_by_key(|(_, record)| record.seq) - .and_then(|(frame, record)| { - u64::try_from(frame).ok().map(|frame| { - ( - frame, - EventKind::context_start(record.context.system, record.context.first_message), - ) - }) + let (frame, _, context) = gateway_records(stream) + .filter_map(|(frame, record)| { + let GatewayRecord::Context { seq, context } = record else { + return None; + }; + Some((frame, seq, context)) }) + .min_by_key(|(_, seq, _)| *seq)?; + u64::try_from(frame).ok().map(|frame| { + ( + frame, + EventKind::context_start(context.system, context.first_message), + ) + }) } /// The tool inventory of a census stream: the names of the first request, by sequence number, @@ -1326,17 +1312,16 @@ pub fn census_context(stream: &[u8]) -> Option<(u64, EventKind)> { /// of whose requests carry tools has no inventory, never an empty one. #[must_use] pub fn census_init(stream: &[u8]) -> Option { - #[derive(serde::Deserialize)] - struct Request { - seq: u64, - tools: Vec, - } - let first = stream - .split(|byte| *byte == b'\n') - .filter_map(|line| serde_json::from_slice::(line).ok()) - .filter(|request| !request.tools.is_empty()) - .min_by_key(|request| request.seq)?; - InitReport::new(serde_json::json!(first.tools), CensusSource::Gateway).ok() + let (_, tools) = gateway_records(stream) + .filter_map(|(_, record)| { + let GatewayRecord::Tools { seq, tools } = record else { + return None; + }; + Some((seq, tools)) + }) + .filter(|(_, tools)| !tools.is_empty()) + .min_by_key(|(seq, _)| *seq)?; + InitReport::new(serde_json::json!(tools), CensusSource::Gateway).ok() } /// 128 random bits as hex, from the operating system. diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index 8df14e5c..8031dd78 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -751,7 +751,7 @@ async fn drive( }; match stored { Some((name, bytes, file)) => { - if rt.driver.census_stream().is_some() { + if rt.driver.census_from_gateway() { gateway_init = census_init(&bytes); } context = diff --git a/crates/candler-core/tests/it/support/wiring.rs b/crates/candler-core/tests/it/support/wiring.rs index 7d7e49ac..226f3426 100644 --- a/crates/candler-core/tests/it/support/wiring.rs +++ b/crates/candler-core/tests/it/support/wiring.rs @@ -195,8 +195,8 @@ impl HarnessDriver for WiringDriver { self.0.state_paths() } - fn census_stream(&self) -> Option { - self.0.census_stream() + fn census_from_gateway(&self) -> bool { + self.0.census_from_gateway() } fn stop(&self) -> StopSpec { diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index fa7f9c97..77fa3a72 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -12,7 +12,7 @@ use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ Action, AgentSetting, Answer, BaseImage, Cell, CheckVerdict, CollectSpec, CommandSpec, - DriverFact, GATEWAY_STREAM, GatewayEnv, HarnessId, OPENCODE, Observed, Prepared, ProcessExit, + DriverFact, GatewayEnv, HarnessId, OPENCODE, Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, StopSpec, Workspace, }; use candler_schemas::name; @@ -270,8 +270,8 @@ impl HarnessDriver for OpenCodeDriver { Some(Box::new(OpenCodeLiveReader::new())) // TRAIT_OBJECT: the core selects readers at runtime } - fn census_stream(&self) -> Option { - GATEWAY_STREAM.parse().ok() + fn census_from_gateway(&self) -> bool { + true } fn offline_reader( diff --git a/crates/candler-harness/src/conformance.rs b/crates/candler-harness/src/conformance.rs index c80fd11c..98d2eb02 100644 --- a/crates/candler-harness/src/conformance.rs +++ b/crates/candler-harness/src/conformance.rs @@ -16,8 +16,8 @@ use crate::driver::{DriverError, HarnessDriver, Plan}; use crate::reader::{FrameIn, TraceReader}; use crate::spec::{ Action, AgentSetting, Cell, CensusSource, CollectSpec, CommandSpec, DriverFact, EnvValue, - Framing, HttpMethod, InitReport, Observed, ObservedEnd, PendingState, PreparedFile, - ProcessExit, SessionClose, SessionRecord, StateKind, StopSpec, Workspace, + Framing, GATEWAY_STREAM, HttpMethod, InitReport, Observed, ObservedEnd, PendingState, + PreparedFile, ProcessExit, SessionClose, SessionRecord, StateKind, StopSpec, Workspace, }; /// A session id plain enough to stand in a script, used to check that a placeholder resolves. @@ -750,12 +750,12 @@ fn check_capabilities( } } if !driver.fact(DriverFact::Census).is_refused() { - let from_stream = driver.census_stream().is_some(); + let from_stream = driver.census_from_gateway(); let from_init = cases.iter().any(|case| case.init.is_some()); if !from_stream && !from_init { return Err(driver_failure( "census", - "the census capability is declared and the driver has neither a census stream nor an init report".to_owned(), // BORROW: .to_owned() makes the owned text + "the census capability is declared and the driver has neither a gateway census nor an init report".to_owned(), // BORROW: .to_owned() makes the owned text )); } } else if let Some(case) = cases.iter().find(|case| case.init.is_some()) { @@ -918,12 +918,13 @@ fn check_census_source( let Some(init) = &case.init else { return Ok(()); }; - let stream = driver.census_stream(); + let from_gateway = driver.census_from_gateway(); let offline_stream = match &case.reader { ReaderSource::Offline(name) => Some(name), ReaderSource::Live => None, }; - let from_stream = stream.is_some() && stream.as_ref() == offline_stream; + let from_stream = + from_gateway && offline_stream.is_some_and(|name| name.as_str() == GATEWAY_STREAM); // BORROW: explicit .as_str() let labelled_ok = if from_stream { matches!(init.source, CensusSource::Gateway | CensusSource::Collected) } else { @@ -944,12 +945,11 @@ fn check_census_source( ), )); } - if init.source == CensusSource::Harness && stream.is_some() && case.reader == ReaderSource::Live - { + if init.source == CensusSource::Harness && from_gateway && case.reader == ReaderSource::Live { return Err(case_failure( case, "census", - "the driver names a census stream, so a live reader's inventory is not its census" + "the driver takes its census from the gateway, so a live reader's inventory is not its census" .to_owned(), // BORROW: .to_owned() makes the owned text )); } diff --git a/crates/candler-harness/src/driver.rs b/crates/candler-harness/src/driver.rs index 7b1eac55..ce22359b 100644 --- a/crates/candler-harness/src/driver.rs +++ b/crates/candler-harness/src/driver.rs @@ -234,13 +234,12 @@ pub trait HarnessDriver: Send + Sync { Vec::new() } - /// [`crate::spec::GATEWAY_STREAM`] when the harness has no init event, or `None` when the - /// census comes from the live reader's init report. The core reads the tool - /// names the gateway saw in the model requests and reports them as the inventory, labelled - /// [`crate::spec::CensusSource::Gateway`]; a run none of whose requests carry tools leaves it - /// unrecorded, never an empty set. - fn census_stream(&self) -> Option { - None + /// Whether the census is the tool names the gateway saw in the model requests (the harness + /// has no init event), reported as the inventory and labelled + /// [`crate::spec::CensusSource::Gateway`], or comes from the live reader's init report. A run + /// none of whose requests carry tools leaves the census unrecorded, never an empty set. + fn census_from_gateway(&self) -> bool { + false } /// The instruction files the harness loaded, as `stream` shows them: `bytes` is that diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index 1cd49724..65c31dce 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -959,6 +959,53 @@ impl Observed { /// model request and the run's starting context. pub const GATEWAY_STREAM: &str = "gateway_census"; +/// The starting context of a request, as a context line of [`GATEWAY_STREAM`] holds it: the system +/// text and the first message. +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct StartContext { + /// The system text of the request. + pub system: String, + /// The first message of the request. + pub first_message: String, +} + +/// One line of [`GATEWAY_STREAM`]: the tool names of a model request, or the starting context of +/// one. `seq` is the request's sequence number at the gateway. +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] +#[serde(untagged)] +#[non_exhaustive] +pub enum GatewayRecord { + /// The starting context of a request. + Context { + /// The request's sequence number. + seq: u64, + /// What the request started from. + context: StartContext, + }, + /// The tool names of a request. + Tools { + /// The request's sequence number. + seq: u64, + /// The tools the request offered. + tools: Vec, + }, +} + +/// The lines of a [`GATEWAY_STREAM`] that read as a record, each with its index among all the +/// lines of the stream; any other line is skipped. +pub fn gateway_records(stream: &[u8]) -> impl Iterator { + stream + .split(|byte| *byte == b'\n') + .enumerate() + .filter_map(|(frame, line)| { + serde_json::from_slice::(line) + .ok() + .map(|record| (frame, record)) + }) +} + /// Where an inventory of tools came from. Two inventories from different sources are never the /// same observation, and neither equals an unrecorded one. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/crates/candler-harness/tests/it/conformance_shapes.rs b/crates/candler-harness/tests/it/conformance_shapes.rs index 5d5b2e4f..215cde11 100644 --- a/crates/candler-harness/tests/it/conformance_shapes.rs +++ b/crates/candler-harness/tests/it/conformance_shapes.rs @@ -19,9 +19,9 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ Action, AgentSetting, Answer, Cell, CensusSource, CollectSpec, CommandSpec, CommandSpecError, - DriverFact, EnvEntry, GatewayEnv, HarnessId, InitReport, Observed, ObservedEnd, PendingItem, - PendingKind, PendingState, PreparedFile, ProcessEnd, ProcessExit, SessionClose, SessionSpec, - SessionTracker, StateKind, StatePath, StopSignal, StopSpec, Workspace, + DriverFact, EnvEntry, GATEWAY_STREAM, GatewayEnv, HarnessId, InitReport, Observed, ObservedEnd, + PendingItem, PendingKind, PendingState, PreparedFile, ProcessEnd, ProcessExit, SessionClose, + SessionSpec, SessionTracker, StateKind, StatePath, StopSignal, StopSpec, Workspace, }; use candler_schemas::primitives::FieldPath; use candler_schemas::process::ExitStatus; @@ -246,7 +246,7 @@ fn open_cases() -> Result, TestError> { let ses = |text: &str| sid(text); let stdout = name("stdout")?; let export = name("export")?; - let record = name("model_requests")?; + let record = name(GATEWAY_STREAM)?; let tools = InitReport::new( json!([ "edit", @@ -448,7 +448,7 @@ struct Patched { wordless: Option, stop: Option, extra_arg: Option, - census_stream_removed: bool, + census_from_gateway_removed: bool, eager_census: bool, session: Option, extra_file: Option, @@ -466,7 +466,7 @@ impl Patched { wordless: None, stop: None, extra_arg: None, - census_stream_removed: false, + census_from_gateway_removed: false, eager_census: false, session: None, extra_file: None, @@ -588,12 +588,8 @@ impl HarnessDriver for Patched { .clone() // BORROW: .clone() copies the override .unwrap_or_else(|| self.inner.state_paths()) } - fn census_stream(&self) -> Option { - if self.census_stream_removed { - None - } else { - self.inner.census_stream() - } + fn census_from_gateway(&self) -> bool { + !self.census_from_gateway_removed && self.inner.census_from_gateway() } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { let mut plan = self.inner.plan(cell, workspace)?; @@ -623,7 +619,7 @@ impl HarnessDriver for Patched { servers: &[String], ) -> Option> { // BORROW: explicit .as_str() instead of Deref coercion - if self.eager_census && stream.as_str() == "model_requests" { + if self.eager_census && stream.as_str() == GATEWAY_STREAM { return Some(Box::new(EagerCensus)); // TRAIT_OBJECT: the trait returns readers as objects } self.inner.offline_reader(stream, servers) @@ -831,12 +827,12 @@ impl HarnessDriver for Keeps { /// Guards: R01 §Harness drivers, §Agent environment and secrets, §`OpenCode` v2, §Session runner — /// the checks that refuse a broken driver, each its own section below: a session capability -/// without a session spec; a census capability with neither a census stream nor an init report; +/// without a session spec; a census capability with neither a gateway census nor an init report; /// a census record with no request read as an empty inventory (unrecorded, never an empty set); /// execution outside the child with no pre-stop; a secret in the argument vector, or a variable /// the core owns; a driver that names no gateway variables; a config naming an undeclared /// variable; a host collect for a driver with per-run state; two state paths that are one path, -/// or a file that is another's parent; a census stream with no reader; a stop script that matches +/// or a file that is another's parent; a gateway census with no reader; a stop script that matches /// itself (`pgrep`/`pkill` with the full-command-line option, in any cluster); `Action::resolve` /// falling back for an unknown or refused id; an inventory from a source that saw no tool; two state /// paths sharing a variable or named like a gateway variable or not a variable at all; gateway names @@ -877,9 +873,9 @@ fn conformance_refuses_a_broken_driver() -> TestResult { "{message}" ); - // A census capability with neither a census stream nor an init report is refused. + // A census capability with neither a gateway census nor an init report is refused. let mut broken = Patched::new(); - broken.census_stream_removed = true; + broken.census_from_gateway_removed = true; // Only the cases that expect no inventory remain, so no init report backs the capability. let no_inventory_cases: Vec = open_cases()? .into_iter() @@ -888,7 +884,7 @@ fn conformance_refuses_a_broken_driver() -> TestResult { assert!(!no_inventory_cases.is_empty()); let message = refusal(&broken, &no_inventory_cases)?; assert!( - message.contains("neither a census stream nor an init report"), + message.contains("neither a gateway census nor an init report"), "{message}" ); @@ -1370,8 +1366,8 @@ fn conformance_session_surface_on_a_fake() -> TestResult { fn state_paths(&self) -> Vec { self.0.state_paths() } - fn census_stream(&self) -> Option { - self.0.census_stream() + fn census_from_gateway(&self) -> bool { + self.0.census_from_gateway() } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { let plan = self.0.plan(cell, workspace)?; diff --git a/crates/candler-harness/tests/it/support/mod.rs b/crates/candler-harness/tests/it/support/mod.rs index b30a03f0..54bd6dc1 100644 --- a/crates/candler-harness/tests/it/support/mod.rs +++ b/crates/candler-harness/tests/it/support/mod.rs @@ -15,9 +15,9 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::{FrameIn, ReaderError, TraceReader}; use candler_harness::spec::{ Action, AgentSetting, Answer, Cell, CensusSource, CollectSpec, CommandSpec, Confidence, - DriverFact, FormatVersion, Framing, GatewayEnv, HarnessId, HttpMethod, InitReport, Observed, - ObservedEnd, Prepared, PreparedFile, ProcessEnd, ProcessExit, StateKind, StatePath, StopSignal, - StopSpec, Workspace, + DriverFact, FormatVersion, Framing, GATEWAY_STREAM, GatewayEnv, HarnessId, HttpMethod, + InitReport, Observed, ObservedEnd, Prepared, PreparedFile, ProcessEnd, ProcessExit, StateKind, + StatePath, StopSignal, StopSpec, Workspace, }; use candler_schemas::primitives::{FieldPath, Name, NameVersion, Timestamp}; use candler_schemas::raw::{RawFrame, RawRef, StreamName}; @@ -949,8 +949,8 @@ impl HarnessDriver for OpenShapedDriver { ] } - fn census_stream(&self) -> Option { - "model_requests".parse().ok() + fn census_from_gateway(&self) -> bool { + true } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { @@ -1015,7 +1015,7 @@ impl HarnessDriver for OpenShapedDriver { ) -> Option> { // BORROW: explicit .as_str() instead of Deref coercion match stream.as_str() { - "model_requests" => Some(Box::new(CensusReader { tools: None })), // TRAIT_OBJECT: the trait returns readers as objects + GATEWAY_STREAM => Some(Box::new(CensusReader { tools: None })), // TRAIT_OBJECT: the trait returns readers as objects "export" => Some(Box::new(ExportReader { session: None })), // TRAIT_OBJECT: the trait returns readers as objects _ => self.0.offline_reader(stream, servers), } diff --git a/docs/contract/driver-traits.md b/docs/contract/driver-traits.md index 8089cad2..b302c0f5 100644 --- a/docs/contract/driver-traits.md +++ b/docs/contract/driver-traits.md @@ -32,7 +32,7 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | `HarnessDriver::check_settings` | `(&self, cell: &Cell<'_>) -> Result<(), DriverError>` | optional | `Ok(())` | | `HarnessDriver::gateway` | `(&self) -> Option` | optional | `None` | | `HarnessDriver::state_paths` | `(&self) -> Vec` | optional | `Vec::new()` | -| `HarnessDriver::census_stream` | `(&self) -> Option` | optional | `None` | +| `HarnessDriver::census_from_gateway` | `(&self) -> bool` | optional | `false` | | `HarnessDriver::loaded_instructions` | `(&self, stream: &StreamName, bytes: &[u8]) -> Vec` | optional | `Vec::new()` | | `HarnessDriver::skills` | `(&self) -> SkillTree` | required | - | | `HarnessDriver::base_image` | `(&self) -> BaseImage` | required | - | @@ -78,5 +78,5 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. - Drivers never act on a process: they return commands, specs and readers, and the core runs them. [checked: v@0.7.0] - A reader is synchronous and holds no clock; the core supplies each frame's place and wall time. [checked: v@0.7.0] -- `census_stream()` names the raw stream the gateway's census is stored under; the core reads the gateway census itself and reports it as the inventory. [checked: v@0.7.0] +- `census_from_gateway()` says the census is the tool names the gateway saw in the model requests; the core reads them itself and reports them as the inventory. [checked: v@0.16.0] - A driver that does not refuse `AgentSetting::SessionMode` also gives its `plan` a `session` and returns a `session_tracker`. [checked: v@0.7.0] From 1f8fce6c6bfd91abadd907a506119c51ea51682c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:01:51 +0900 Subject: [PATCH 47/69] fix(api): key the config check on all it reads, and plan each cell once The check stages each distinct cell once and groups by the staged files (home and workspace lists kept apart), the command's environment and working directory and the container environment. Both start checks share one loop that runs each group over its scratch and removes it. Co-Authored-By: Claude Sonnet 5.5 --- .../src/jobs/orchestrate/config.rs | 200 ++++++++++++------ .../src/jobs/orchestrate/servers.rs | 47 +++- .../tests/it/guard_config_check.rs | 129 ++++++++--- 3 files changed, 272 insertions(+), 104 deletions(-) diff --git a/crates/candler-core/src/jobs/orchestrate/config.rs b/crates/candler-core/src/jobs/orchestrate/config.rs index 1a567d8a..72ed9cc5 100644 --- a/crates/candler-core/src/jobs/orchestrate/config.rs +++ b/crates/candler-core/src/jobs/orchestrate/config.rs @@ -2,20 +2,22 @@ //! distinct set of installed files is given to the harness's own check, in a container without //! network that is the one a run of the cell gets, and a finding refuses the job. +use std::collections::btree_map::Entry; use std::collections::{BTreeMap, BTreeSet}; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::Arc; use candler_harness::agent_config; use candler_harness::driver::{DriverError, Plan}; -use candler_harness::spec::{Cell, CheckVerdict, FileRoot, PreparedFile, Workspace}; +use candler_harness::spec::{Cell, CheckVerdict, CommandSpec, EnvValue, FileRoot, PreparedFile}; use candler_schemas::primitives::Digest; use candler_schemas::process::ExitStatus; use candler_schemas::refusal::pointer_of; -use super::servers::stage_container; +use super::servers::{check_each, stage_container}; use super::session::image_of; +use crate::isolation::model::ContainerPlan; use crate::isolation::{ExecOutput, Isolation}; use crate::runner::Runtime; use crate::runner::plan::{CellId, RunPlan}; @@ -40,8 +42,15 @@ pub enum ConfigCheckError { /// three share one verdict. type GroupKey = (String, Option, Digest); -/// The distinct keys, each with the first plan of such a cell and every cell that has the key. -type Groups<'a> = BTreeMap)>; +/// A distinct check: the cell it is run for, what that cell was staged as under its scratch root, +/// the check command, and every cell that shares its key. +struct Group<'a> { + plan: &'a RunPlan, + staged: Plan, + container: ContainerPlan, + command: CommandSpec, + cells: BTreeSet, +} fn failed(detail: &impl ToString) -> ConfigCheckError { ConfigCheckError::Check { @@ -91,11 +100,11 @@ fn installed_files(plan: &Plan) -> impl Iterator { plan.prepared.files.iter().chain(&plan.workspace_files) } -/// The digest of what the check reads in `plan`: every installed file with its root, path, mode -/// and bytes, and the words of the check command. -fn files_digest(plan: &Plan, command_words: &[String]) -> Digest { - let mut bytes = Vec::new(); - for file in installed_files(plan) { +/// Adds `files` to `bytes`, each with its root, path, mode and bytes, after a tag and a count so +/// that two lists never run into each other. +fn add_files(bytes: &mut Vec, tag: &str, files: &[PreparedFile]) { + bytes.extend_from_slice(format!("{tag}\0{}\0", files.len()).as_bytes()); + for file in files { bytes.extend_from_slice( format!( "{:?}\0{}\0{}\0{}\0", @@ -108,10 +117,41 @@ fn files_digest(plan: &Plan, command_words: &[String]) -> Digest { ); bytes.extend_from_slice(&file.contents); } - for word in command_words { +} + +/// The digest of what the check reads, which is the one thing the cells of a group share: the +/// files of the agent's home and, apart from them, the read-only files of the workspace, each +/// with its root, path, mode and bytes; the check command's words, working directory and +/// environment overlay; the treatment; and the environment the check container is given. +/// +/// The cell's declared inputs are not mounted in the check container, so they are not in the key. +fn files_digest( + plan: &Plan, + container: &ContainerPlan, + command: &CommandSpec, + treatment: &str, +) -> Digest { + let mut bytes = Vec::new(); + add_files(&mut bytes, "home", &plan.prepared.files); + add_files(&mut bytes, "workspace", &plan.workspace_files); + for word in command.argv() { bytes.extend_from_slice(word.as_bytes()); bytes.push(0); } + bytes.extend_from_slice(format!("cwd\0{:?}\0", command.cwd()).as_bytes()); + for entry in command.env_overlay() { + let value = match &entry.value { + EnvValue::Literal(text) => format!("literal\0{text}"), + EnvValue::Secret(name) => format!("secret\0{name}"), + // EXHAUSTIVE: the value enum is non-exhaustive; a value this core does not know is hashed by its shape + other => format!("{other:?}"), + }; + bytes.extend_from_slice(format!("env\0{}\0{value}\0", entry.name).as_bytes()); + } + for (name, value) in &container.env { + bytes.extend_from_slice(format!("container-env\0{name}\0{value}\0").as_bytes()); + } + bytes.extend_from_slice(treatment.as_bytes()); Digest::of_bytes(&bytes) } @@ -177,33 +217,24 @@ pub async fn check_config(rt: &mut Runtime, plans: &[RunPlan]) -> Result<(), Con .job_dir(&rt.job) .join("scratch") .join("config-check"); - let mut groups: Groups<'_> = BTreeMap::new(); - let mut seen: BTreeSet<&CellId> = BTreeSet::new(); - for plan in plans { - if !seen.insert(&plan.cell) { - continue; - } - if let Some(key) = group_key(rt, plan, &scratch.join("key"))? { - groups - .entry(key) - .or_insert_with(|| (plan, BTreeSet::new())) - .1 - .insert(plan.cell.clone()); // BORROW: the group owns the ids of its cells - } - } - let _ = fs::remove_dir_all(&scratch); // EXPLICIT: the keys' scratch holds nothing after they are read - let mut verdict = Ok(()); - for (index, (plan, _)) in groups.values().enumerate() { - let root = scratch.join(index.to_string()); // BORROW: .to_string() gives owned text - verdict = check_group(rt, isolation.as_ref(), plan, &root).await; - let _ = fs::remove_dir_all(&root); // EXPLICIT: the scratch is removed whether or not the check passed; a leftover is swept with the job directory - if verdict.is_err() { - break; + let groups = match grouped(rt, isolation.as_ref(), plans, &scratch).await { + Ok(groups) => groups, + Err(error) => { + let _ = fs::remove_dir_all(&scratch); // EXPLICIT: the staged cells are of no use once the check is refused + return Err(error); } + }; + let mut covered: BTreeSet = BTreeSet::new(); + let mut ordered = Vec::with_capacity(groups.len()); + for (root, group) in groups.into_values() { + covered.extend(group.cells.iter().cloned()); // BORROW: the covered set owns the ids + ordered.push((root, group)); } - let _ = fs::remove_dir_all(&scratch); // EXPLICIT: the scratch root holds nothing once the groups are done - verdict?; - let covered: BTreeSet = groups.into_values().flat_map(|(_, cells)| cells).collect(); + let (reader, held) = (&*rt, isolation.as_ref()); // BORROW: the checks read the runtime + check_each(&scratch, ordered, |group, _root| async move { + check_group(reader, held, &group).await + }) + .await?; for id in covered { if let Some(cell) = rt.cells.get_mut(&id) { Arc::make_mut(cell).config_clean = true; @@ -212,56 +243,97 @@ pub async fn check_config(rt: &mut Runtime, plans: &[RunPlan]) -> Result<(), Con Ok(()) } -/// The key of `plan`'s cell, or `None` when its driver has no check. +/// Stages each distinct cell of `plans` once, under a root of its own below `scratch`, and +/// groups the cells whose staged files, check and container agree. The first cell of a group +/// keeps its staging and its root; the root of any other is removed. A cell whose driver has no +/// check is not staged further. +/// +/// # Errors +/// [`ConfigCheckError::Check`] when a cell cannot be staged. +async fn grouped<'a>( + rt: &Runtime, + isolation: &dyn Isolation, // TRAIT_OBJECT: the runtime's isolation, or a fake in tests + plans: &'a [RunPlan], + scratch: &Path, +) -> Result)>, ConfigCheckError> { + let mut groups: BTreeMap)> = BTreeMap::new(); + let mut seen: BTreeSet<&CellId> = BTreeSet::new(); + for plan in plans { + if !seen.insert(&plan.cell) { + continue; + } + let root = scratch.join(seen.len().to_string()); // BORROW: .to_string() gives owned text + let (staged, container) = stage_container(rt, isolation, plan, &root, false) + .await + .map_err(|e| failed(&e))?; + let Some(command) = rt.driver.config_check(&staged) else { + let _ = fs::remove_dir_all(&root); // EXPLICIT: a cell with no check keeps nothing of its staging + continue; + }; + let key = group_key(rt, plan, &staged, &container, &command)?; + match groups.entry(key) { + Entry::Occupied(mut held) => { + held.get_mut().1.cells.insert(plan.cell.clone()); // BORROW: the group owns the ids of its cells + let _ = fs::remove_dir_all(&root); // EXPLICIT: the group's first cell is the one that is checked + } + Entry::Vacant(slot) => { + let cells = BTreeSet::from([plan.cell.clone()]); // BORROW: the group owns the ids of its cells + slot.insert(( + root, + Group { + plan, + staged, + container, + command, + cells, + }, + )); + } + } + } + Ok(groups) +} + +/// The key of `plan`'s cell, from what was staged for it. fn group_key( rt: &Runtime, plan: &RunPlan, - root: &Path, -) -> Result, ConfigCheckError> { + staged: &Plan, + container: &ContainerPlan, + command: &CommandSpec, +) -> Result { let cell = rt.cells.get(&plan.cell).ok_or_else(|| failed(&"no cell"))?; let comparable = plan.stored.as_ref().unwrap_or(&cell.comparable); - let driven = rt - .driver - .plan(&Cell::new(comparable.values()), &Workspace::new(root))?; - let Some(command) = rt.driver.config_check(&driven) else { - return Ok(None); - }; let treatment = serde_json::to_string(comparable.treatment()).map_err(|e| failed(&e))?; - let mut words = command.argv().to_vec(); // BORROW: the words are hashed with the files - words.push(treatment); - Ok(Some(( + Ok(( rt.driver.id().to_string(), // BORROW: .to_string() gives owned text image_of(comparable), - files_digest(&driven, &words), - ))) + files_digest(staged, container, command, &treatment), + )) } -/// Runs the harness's check in the container of `plan`'s cell, over a scratch workspace under -/// `root`, and reads its verdict. +/// Runs the harness's check of `group` in the container its first cell was staged as, and reads +/// its verdict. async fn check_group( rt: &Runtime, isolation: &dyn Isolation, // TRAIT_OBJECT: the runtime's isolation, or a fake in tests - plan: &RunPlan, - root: &Path, + group: &Group<'_>, ) -> Result<(), ConfigCheckError> { - let (staged, container) = stage_container(rt, isolation, plan, root) - .await - .map_err(|e| failed(&e))?; - let Some(command) = rt.driver.config_check(&staged) else { - return Ok(()); - }; let ran = isolation - .collect_exec(&container, &command) + .collect_exec(&group.container, &group.command) .await .map_err(|e| failed(&e))?; let output = verdict_bytes(ran)?; match rt.driver.read_config_check(&output) { CheckVerdict::Clean => Ok(()), CheckVerdict::Rejected { output } => { - let cell = rt.cells.get(&plan.cell).ok_or_else(|| failed(&"no cell"))?; - let comparable = plan.stored.as_ref().unwrap_or(&cell.comparable); + let cell = rt + .cells + .get(&group.plan.cell) + .ok_or_else(|| failed(&"no cell"))?; + let comparable = group.plan.stored.as_ref().unwrap_or(&cell.comparable); let harness = rt.driver.id().to_string(); // BORROW: .to_string() gives owned text - let (installed, at) = installed_at(&staged); + let (installed, at) = installed_at(&group.staged); Err(DriverError::HarnessRejectedInput { path: setting_pointer(&Cell::new(comparable.values()), harness.as_str()), // BORROW: explicit .as_str() installed, diff --git a/crates/candler-core/src/jobs/orchestrate/servers.rs b/crates/candler-core/src/jobs/orchestrate/servers.rs index 532df038..cab2f8f5 100644 --- a/crates/candler-core/src/jobs/orchestrate/servers.rs +++ b/crates/candler-core/src/jobs/orchestrate/servers.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::time::Duration; use candler_harness::driver::Plan; @@ -18,6 +18,7 @@ use crate::isolation::container::agent_home; use crate::isolation::model::ContainerPlan; use crate::isolation::{Isolation, IsolationError, StartProbe}; use crate::runner::Runtime; +use crate::runner::evidence::Inputs; use crate::runner::exec::{ExecError, compose_container, mounted_inputs, stage_cell}; use crate::runner::plan::RunPlan; @@ -100,22 +101,47 @@ pub async fn check_servers(rt: &Runtime, plans: &[RunPlan]) -> Result<(), Server .job_dir(&rt.job) .join("scratch") .join("server-check"); + let mut roots = Vec::with_capacity(groups.len()); + for (index, group) in groups.into_values().enumerate() { + roots.push((scratch.join(index.to_string()), group)); // BORROW: .to_string() gives owned text + } + let held = isolation.as_ref(); + check_each(&scratch, roots, |(plan, stdio), root| async move { + probe_group(rt, held, plan, &stdio, &root).await + }) + .await +} + +/// Runs `check` on each of `groups` in turn, each over the scratch root it comes with, and stops +/// at the first refusal. Each root is removed as soon as its check is over, whether or not it +/// passed, and `scratch`, which holds them, is removed at the end. +/// +/// # Errors +/// The first error `check` gives. +pub(super) async fn check_each( + scratch: &Path, + groups: impl IntoIterator, + mut check: impl FnMut(G, PathBuf) -> Fut, +) -> Result<(), E> +where + Fut: Future>, +{ let mut verdict = Ok(()); - for (index, (plan, stdio)) in groups.values().enumerate() { - let root = scratch.join(index.to_string()); - verdict = probe_group(rt, isolation.as_ref(), plan, stdio, &root).await; - let _ = fs::remove_dir_all(&root); // EXPLICIT: the scratch is removed whether or not the probe passed; a leftover is swept with the job directory + for (root, group) in groups { + verdict = check(group, root.clone()).await; // BORROW: the check owns its root and the loop removes it + let _ = fs::remove_dir_all(&root); // EXPLICIT: the scratch is removed whether or not the check passed; a leftover is swept with the job directory if verdict.is_err() { break; } } - let _ = fs::remove_dir_all(&scratch); // EXPLICIT: the scratch root holds nothing once the groups are done + let _ = fs::remove_dir_all(scratch); // EXPLICIT: the scratch root holds nothing once the groups are done verdict } /// Stages what a run of `plan`'s cell starts with under `root`, a scratch workspace and home, and /// composes the container such a run gets: the driver's plan for the cell and the container over -/// it, with the cell's inputs and the plan's read-only workspace files mounted. +/// it, with the plan's read-only workspace files mounted, and the cell's declared inputs when +/// `inputs` says so. /// /// # Errors /// [`ExecError`] when the cell is unknown, a directory cannot be made, the driver refuses the cell @@ -125,6 +151,7 @@ pub(super) async fn stage_container( isolation: &dyn Isolation, // TRAIT_OBJECT: the runtime's isolation, or a fake in tests plan: &RunPlan, root: &Path, + inputs: bool, ) -> Result<(Plan, ContainerPlan), ExecError> { let cell = rt .cells @@ -151,7 +178,9 @@ pub(super) async fn stage_container( &root.join("scratch"), ) .await?; - let mounted = mounted_inputs(&rt.store, &cell.inputs, &staged.workspace_files)?; + let none = Inputs::default(); + let declared = if inputs { &cell.inputs } else { &none }; + let mounted = mounted_inputs(&rt.store, declared, &staged.workspace_files)?; let container = compose_container(rt, isolation, &view, &workspace, &home, &mounted)?; Ok((staged, container)) } @@ -165,7 +194,7 @@ async fn probe_group( stdio: &[(String, McpServer)], root: &Path, ) -> Result<(), ServerCheckError> { - let (staged, mut container) = stage_container(rt, isolation, plan, root) + let (staged, mut container) = stage_container(rt, isolation, plan, root, true) .await .map_err(|e| failed(&e))?; // Standard input stays open, as a server's own would while the agent runs. diff --git a/crates/candler-core/tests/it/guard_config_check.rs b/crates/candler-core/tests/it/guard_config_check.rs index c3e0dba7..2d4bd86c 100644 --- a/crates/candler-core/tests/it/guard_config_check.rs +++ b/crates/candler-core/tests/it/guard_config_check.rs @@ -11,6 +11,7 @@ use crate::support; use std::fs; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use candler_core::isolation::ExecOutput; use candler_core::isolation::container::mounts::{MountMode, MountSpec}; @@ -21,7 +22,8 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ AgentSetting, Answer, Cell, CheckVerdict, CollectSpec, CommandSpec, DriverFact, EnvEntry, - HarnessId, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, Workspace, + EnvValue, HarnessId, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, + Workspace, }; use candler_schemas::execution::Comparable; use candler_schemas::primitives::RelPath; @@ -44,10 +46,27 @@ struct Checking { inner: QuietDriver, /// Whether the harness has a check. check: bool, - /// Whether the installed files name the cell's model, so cells of two models differ. - vary: bool, + /// What of the check's input names the cell's model, so cells of two models differ. + vary: Vary, /// Whether the run collects every file of the workspace as an output. collect_all: bool, + /// How many times the harness was asked to plan a cell. + planned: Arc, +} + +/// What differs between the cells of two models. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Vary { + /// Nothing: the cells share everything the check reads. + Nothing, + /// The text of an installed file in the agent's home. + Settings, + /// A variable of the check command's environment. + CommandEnv, + /// The check command's working directory. + CommandCwd, + /// Which list a workspace file is in: the writable files or the read-only ones. + ListOfFile, } impl Checking { @@ -55,19 +74,37 @@ impl Checking { Self { inner: QuietDriver, check, - vary: false, + vary: Vary::Nothing, collect_all: false, + planned: Arc::new(AtomicUsize::new(0)), } } } impl HarnessDriver for Checking { - fn config_check(&self, _plan: &Plan) -> Option { + fn config_check(&self, plan: &Plan) -> Option { self.check.then(|| { - CommandSpec::builder() - .argv(vec![CHECK.to_owned()]) - .build() - .expect("a command") + let mut builder = CommandSpec::builder().argv(vec![CHECK.to_owned()]); + let model = plan + .prepared + .env_overlay + .iter() + .find(|entry| entry.name == "MODEL") + .and_then(|entry| { + if let EnvValue::Literal(text) = &entry.value { + Some(text.clone()) + } else { + None + } + }) + .unwrap_or_default(); + if self.vary == Vary::CommandEnv { + builder = builder.env(EnvEntry::literal("CHECK_MODEL".to_owned(), model.clone())); + } + if self.vary == Vary::CommandCwd { + builder = builder.cwd(model.parse::().expect("a path")); + } + builder.build().expect("a command") }) } @@ -131,28 +168,46 @@ impl HarnessDriver for Checking { } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { - let model = if self.vary { - cell.value_str("model.id") - .ok() - .flatten() - .and_then(Value::as_str) - .unwrap_or_default() - .to_owned() + self.planned.fetch_add(1, Ordering::SeqCst); + let model = cell + .value_str("model.id") + .ok() + .flatten() + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + let settings_text = if self.vary == Vary::Settings { + model.clone() } else { String::new() }; let settings = PreparedFile::in_home( "settings.json".parse::().expect("a path"), - format!("{{\"model\":\"{model}\"}}").into_bytes(), + format!("{{\"model\":\"{settings_text}\"}}").into_bytes(), + false, + ); + let notes = PreparedFile::new( + "notes.md".parse::().expect("a path"), + b"notes".to_vec(), false, ); let mut plan = self.inner.plan(cell, workspace)?; - plan.prepared = Prepared::new(vec![settings], Vec::::new()); - plan.workspace_files = vec![PreparedFile::new( + let mut files = vec![settings]; + let mut read_only = vec![PreparedFile::new( "AGENTS.md".parse::().expect("a path"), WORKSPACE_TEXT.as_bytes().to_vec(), false, )]; + if self.vary == Vary::ListOfFile && model == "m2" { + read_only.push(notes); + } else if self.vary == Vary::ListOfFile { + files.push(notes); + } + // The model's name rides in the plan's environment, which the check does not read, so a + // variant of the command can name it without the files differing. + let rides = vec![EnvEntry::literal("MODEL".to_owned(), model)]; + plan.prepared = Prepared::new(files, rides); + plan.workspace_files = read_only; Ok(plan) } @@ -286,16 +341,20 @@ fn mount_at<'m>(mounts: &'m [MountSpec], target: &str) -> Option<&'m MountSpec> /// Oracle: the literal `REJECT: unknown key hooks.Foo` the scripted check prints, and the file /// names the stand-in driver lists. The job runs in a child of this test binary, so its stderr /// line can be read. -/// Bite: the refusal drops the harness's output, or the check runs after the runs are scheduled. +/// Bite: the refusal drops the harness's output, the check runs after the runs are scheduled, or the +/// check plans its cell twice. #[test] fn harness_finding_refuses_the_job_before_any_run() { let line = refusal_of( "guard_config_check::harness_finding_refuses_the_job_before_any_run", || { - let ran = run( - job(&["m1"]), - Checking::new(true), - "REJECT: unknown key hooks.Foo", + let driver = Checking::new(true); + let planned = Arc::clone(&driver.planned); + let ran = run(job(&["m1"]), driver, "REJECT: unknown key hooks.Foo"); + assert_eq!( + planned.load(Ordering::SeqCst), + 1, + "the check plans its cell once" ); let probing = ran.host.probing(); assert_eq!(probing.executed().len(), 1, "the check ran once"); @@ -427,20 +486,28 @@ fn clean_verdict_is_stored_and_a_harness_without_check_stores_none() { } /// Guards: cells that share a harness, an image and the installed files are checked once, and -/// cells whose installed files differ are each checked. +/// cells that differ in what the check reads are each checked: an installed file, the command's +/// environment or working directory, and which list (writable or read-only) a file is in. /// Oracle: the number of commands the isolation double ran for their output. -/// Bite: key the check on the cell instead of on the installed files, or never on them. +/// Bite: key the check on the cell instead of on what it reads, or leave one of them out of the key. #[test] fn cells_sharing_their_files_are_checked_once() { let shared = run(job(&["m1", "m2"]), Checking::new(true), "ok"); assert_eq!(shared.outcome.runs.len(), 2, "both runs start"); assert_eq!(shared.host.probing().executed().len(), 1, "one check"); - let mut differing = Checking::new(true); - differing.vary = true; - let apart = run(job(&["m1", "m2"]), differing, "ok"); - assert_eq!(apart.outcome.runs.len(), 2, "both runs start"); - assert_eq!(apart.host.probing().executed().len(), 2, "one check each"); + for vary in [ + Vary::Settings, + Vary::CommandEnv, + Vary::CommandCwd, + Vary::ListOfFile, + ] { + let mut differing = Checking::new(true); + differing.vary = vary; + let apart = run(job(&["m1", "m2"]), differing, "ok"); + assert_eq!(apart.outcome.runs.len(), 2, "both runs start"); + assert_eq!(apart.host.probing().executed().len(), 2, "one check each"); + } } /// Guards: the plan's read-only workspace file reaches the run's container at the workspace root From 324a50bcb898f4c0b5c1013edcb64197a4c641ce Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:01:57 +0900 Subject: [PATCH 48/69] rdm(api): meet the run context when M6.5 lands second Co-Authored-By: Claude Opus 5.5 --- __reports__/agent_config/README.md | 2 ++ .../installed/proved/reviewed/README.md | 4 +++- .../proved/reviewed/meet_run_context.md | 23 +++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 __roadmap__/m6_5-agent-config/installed/proved/reviewed/meet_run_context.md diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 0c94dd05..62ca6f2c 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -33,4 +33,6 @@ Level 1 is done and merged locally. On 2026-11-25 Eliott raised the cap from $85 On 2026-11-25 level 2 found that a resolve step cannot reach a cell's plan, which the harness check needs. The check moved beside the start check of the declared servers (`check_servers`, before the job's first run), and the collision check moved to planning. G6 and G10 are worded accordingly; the check still runs before any agent. +On 2026-11-25 the M6.5 and M6d (run context) leads agreed how the two trace changes meet. Whichever lands second takes the other in, regenerates the schema and the trace page instead of merging them by hand, bumps no version by hand, and writes the `needs.trace` sentence about `context_start`. The leaf `meet_run_context` (L4) holds this for the case where M6.5 lands second. M6.5 takes `origin/main` in by a merge, since its history is not rewritten. + No decision is open. diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md index 73e18c4b..2e713e14 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md @@ -10,12 +10,13 @@ A reviewer who did not build the milestone finds no gate that passes for the wro - [ ] `[cmd]` `git merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds, after L3 has merged ## Success Gates -- ⬜ `adversarial_review.md` is `done` +- ⬜ `adversarial_review.md` and `meet_run_context.md` are `done` ## Status ```mermaid graph TD adversarial_review[Adversarial review]:::planned + meet_run_context[Meet run context]:::amendment classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -27,6 +28,7 @@ graph TD | Node | Type | Status | |:-----|:-----|:-------| | `adversarial_review.md` | 📄 Leaf Task | ⬜ Planned | +| `meet_run_context.md` | 📄 Leaf Task | 🔵 Amendment | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | 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 new file mode 100644 index 00000000..77403446 --- /dev/null +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/meet_run_context.md @@ -0,0 +1,23 @@ +# Meet run context + +**Goal**: When M6.5 lands after M6d (run context, `feat/run-context`), the two trace changes meet in one generated schema and contract page, with one minor version bump, and the evaluator-facing docs say that `needs.trace` now hands over the run's starting context. If M6.5 lands first, M6d owes this, and the leaf records that. (P0, agreed between the M6.5 and M6d leads on 2026-11-25) +**Estimate**: Sonnet, $3, cap $6. One build slot of `/Users/hacker/Documents/tmp/m6_5-target/slot-1..3`, removed when it merges. +**Pre-conditions**: +- [ ] `[cmd]` `git merge-base --is-ancestor feat/run-context origin/main` is checked after `git fetch origin`. If it succeeds, M6d landed first and every gate below applies. If it fails, M6.5 is landing first: record that, mark the gates "owed by M6d", and stop. +- [ ] `[nl]` `adversarial_review.md` is `done`, or runs beside this leaf on the same tip +**Success Gates**: +- ⬜ `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. +- ⬜ 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. +- ⬜ 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. +- ⬜ `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 +**Goal**: One schema, one page and one doc sentence that carry both milestones. +**Implementation Logic**: +1. Merge `origin/main` into `feat/m6.5-agent-config`. Resolve conflicts in the source (`trace.rs` and the hand-written parts of the pages) by keeping both kinds, then regenerate every generated schema and page instead of resolving them by hand. +2. Add the `needs.trace` sentence where M6d documents `needs.trace`, in the same words a consumer reads elsewhere about `context_start`. +3. Run the workspace tests on the merged tip. +**Deliverables**: the merge commit; regenerated `crates/candler-schemas` outputs and `docs/contract/` pages; the `needs.trace` sentence +**Consistency Checks**: `cargo nextest run -p candler-schemas drift` and `cargo nextest run -p candler contract_pages` (expected: PASS) +**Commit**: `merge(api): land M6.5 beside the run context` From c4606cdebe561f16f16f00d0380ff1be4bc6ec01 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:04:40 +0900 Subject: [PATCH 49/69] fix(api): refuse an input at the instruction file in core planning plan_runs meets the collision, so every caller of it does, not only candler run. Paths are compared without a leading ./ and case-folded; the workspace holds no Unicode normalisation crate, so they are not NFC-normalised. A guard drives candler run itself with the input at CLAUDE.md and claude.md. Co-Authored-By: Claude Sonnet 5.5 --- .../candler-core/src/jobs/orchestrate/mod.rs | 7 +++ crates/candler-core/src/runner/plan.rs | 43 ++++++++++--- .../tests/it/guard_agent_config.rs | 59 ++++++++++++++++-- .../tests/it/guard_config_check.rs | 46 -------------- .../tests/it/guard_egress_setting.rs | 1 + crates/candler-core/tests/it/guard_session.rs | 1 + .../candler-core/tests/it/support/run_plan.rs | 1 + crates/candler/src/commands/run.rs | 6 +- .../candler/tests/it/guard_golden_design.rs | 1 + .../tests/it/guard_instruction_collision.rs | 62 +++++++++++++++++++ crates/candler/tests/it/main.rs | 1 + 11 files changed, 164 insertions(+), 64 deletions(-) create mode 100644 crates/candler/tests/it/guard_instruction_collision.rs diff --git a/crates/candler-core/src/jobs/orchestrate/mod.rs b/crates/candler-core/src/jobs/orchestrate/mod.rs index 8f051515..47eee895 100644 --- a/crates/candler-core/src/jobs/orchestrate/mod.rs +++ b/crates/candler-core/src/jobs/orchestrate/mod.rs @@ -124,6 +124,13 @@ async fn run_job( experiment_lock: rt.store.layout().experiment_lock(&fresh), secrets_present: secrets.present(), driver: Some(Arc::clone(&rt.driver)), + // The spec keeps the files the inputs mount, not the names of the inputs, so a refusal + // quotes the path. + input_targets: spec + .inputs + .iter() + .map(|input| (input.path.clone(), input.path.clone())) // BORROW: the context owns its texts + .collect(), }; let force = if spec.force { Force::Yes } else { Force::No }; let outcome = match plan_runs( diff --git a/crates/candler-core/src/runner/plan.rs b/crates/candler-core/src/runner/plan.rs index f1b93514..e993b00c 100644 --- a/crates/candler-core/src/runner/plan.rs +++ b/crates/candler-core/src/runner/plan.rs @@ -58,6 +58,10 @@ pub struct PlanCtx { /// it cannot honour; `None` when the caller has none, and both are then left unchecked. // TRAIT_OBJECT: the binary selects the driver at runtime pub driver: Option>, + /// The workspace path of each file the agent's declared inputs mount, with a name for the + /// input it comes from, which a refusal quotes. The workspace instruction text must not + /// collide with one of them. + pub input_targets: Vec<(String, String)>, } /// Whether a forced plan may accept a differing re-check. @@ -775,21 +779,34 @@ fn fresh_cells<'r>( Ok(cells) } +/// The form of a workspace path two files are compared in: without a leading `./`, in lower +/// case. The comparison folds case but does not normalise Unicode, as the workspace holds no +/// normalisation crate, so two spellings of one accented name stay distinct. +fn folded(path: &str) -> String { + let mut rest = path; + while let Some(stripped) = rest.strip_prefix("./") { + rest = stripped; + } + rest.to_lowercase() +} + /// Refuses a cell whose workspace instruction text and a declared input mount a file at the /// harness's workspace instruction file, which `targets` lists as the workspace path of each -/// input file with its input's kind. +/// input file with its input's name. Paths are compared as [`folded`] says, so `claude.md` and +/// `./CLAUDE.md` collide with `CLAUDE.md`, as they do on a file system that ignores case. /// /// # Errors /// [`DriverError::InstructionsCollide`] naming the input and the path when a cell sets /// `instructions.workspace` and an input mounts the file or a path under it, and the driver's /// [`DriverError`] for an instruction value it cannot read. -pub fn refuse_instruction_collision<'c>( +fn refuse_instruction_collision<'c>( driver: &dyn HarnessDriver, // TRAIT_OBJECT: the registry's driver, selected at run time cells: impl IntoIterator, targets: &[(String, String)], ) -> Result<(), DriverError> { let file = driver.workspace_instruction_file(); - let below = format!("{file}/"); + let held = folded(file); + let below = format!("{held}/"); let harness = driver.id().to_string(); // BORROW: .to_string() gives owned text for comparable in cells { let view = Cell::new(comparable.values()); @@ -798,10 +815,10 @@ pub fn refuse_instruction_collision<'c>( if !sets_text { continue; } - if let Some((_, kind)) = targets - .iter() - .find(|(path, _)| path == file || path.starts_with(&below)) - { + if let Some((_, kind)) = targets.iter().find(|(path, _)| { + let path = folded(path); + path == held || path.starts_with(&below) + }) { return Err(DriverError::InstructionsCollide { path: pointer_of(["fixed", "instructions.workspace"]), input: kind.clone(), // BORROW: the error owns the input's kind @@ -1215,8 +1232,9 @@ fn seal_open( /// # Errors /// [`PlanError::ExperimentLocked`] when another supervisor holds the experiment, /// [`PlanError::Changed`] when a re-checked fact differs and `force` is [`Force::No`], -/// [`PlanError::Cell`] when a treatment level has no resolution, and the other [`PlanError`] -/// variants when the cells or the store cannot be read. +/// [`PlanError::Cell`] when a treatment level has no resolution, [`PlanError::Driver`] when a +/// cell sets the workspace instruction text and an input of `ctx` mounts the instruction file, +/// and the other [`PlanError`] variants when the cells or the store cannot be read. pub fn plan_runs<'a>( ctx: &PlanCtx, file: &ExperimentFile, @@ -1233,6 +1251,13 @@ pub fn plan_runs<'a>( } }; let cells = fresh_cells(file, &levels, ctx.driver.as_deref())?; + if let Some(driver) = ctx.driver.as_deref() { + refuse_instruction_collision( + driver, + cells.iter().map(|cell| &cell.comparable), + ctx.input_targets.as_slice(), // BORROW: explicit .as_slice() + )?; + } let ledger = read_ledger(&ctx.store)?; // BORROW: explicit .as_slice() instead of Deref coercion let matched = match_stored(cells.as_slice(), ledger.groups.as_slice())?; diff --git a/crates/candler-core/tests/it/guard_agent_config.rs b/crates/candler-core/tests/it/guard_agent_config.rs index a6ca6a2b..ec624342 100644 --- a/crates/candler-core/tests/it/guard_agent_config.rs +++ b/crates/candler-core/tests/it/guard_agent_config.rs @@ -13,7 +13,7 @@ use candler_core::resolve::config::{Config, UserConfig}; use candler_core::resolve::layers::{FileValues, ResolveInput}; use candler_core::resolve::preflight::Resolver; use candler_core::runner::plan::{Force, PlanCtx, PlanError, PlanMode, plan_runs}; -use candler_harness::driver::HarnessDriver; +use candler_harness::driver::{DriverError, HarnessDriver}; use candler_harness_claude_code::driver::ClaudeCodeDriver; use candler_harness_opencode::driver::OpenCodeDriver; use candler_schemas::execution::ExperimentFile; @@ -34,11 +34,13 @@ fn experiment_with(factors: &str) -> ExperimentFile { } /// The digests of the cells `file` plans over the resolution of `fixed`, on `driver` when there -/// is one, with both shipped harnesses registered. +/// is one, with both shipped harnesses registered, while the inputs mount the `mounted` files, each +/// with its input's kind. async fn planned( file: &ExperimentFile, fixed: &[(&str, Value)], driver: Option>, + mounted: &[(&str, &str)], ) -> Result, PlanError> { let mut all = vec![ ( @@ -77,6 +79,10 @@ async fn planned( store, experiment_lock: lock, secrets_present: BTreeSet::new(), + input_targets: mounted + .iter() + .map(|(path, kind)| ((*path).to_owned(), (*kind).to_owned())) + .collect(), driver, }; let outcome = plan_runs(&ctx, file, &resolution, Force::No, PlanMode::Check)?; @@ -103,12 +109,16 @@ async fn two_levels_of_instructions_or_hooks_plan_two_cells() { let two = experiment_with(&format!( "[[factors]]\npath = \"{path}\"\nlevels = [{first}, {second}]\n" )); - let cells = planned(&two, &[], None).await.expect("two levels plan"); + let cells = planned(&two, &[], None, &[]) + .await + .expect("two levels plan"); assert_eq!(cells.len(), 2, "{path}: two levels, two digests"); let one = experiment_with(&format!( "[[factors]]\npath = \"{path}\"\nlevels = [{first}]\n" )); - let single = planned(&one, &[], None).await.expect("one level plans"); + let single = planned(&one, &[], None, &[]) + .await + .expect("one level plans"); assert_eq!(single.len(), 1, "{path}: one level, one digest"); assert!(single.is_subset(&cells), "{path}: a level keeps its digest"); } @@ -192,7 +202,7 @@ async fn misused_hooks_and_instructions_are_refused_by_name() { pointer, } in cases { - match planned(&file, &[fixed], Some(driver)).await { + match planned(&file, &[fixed], Some(driver), &[]).await { Err(error) => { assert_eq!(Refusal::code(&error).as_str(), code, "{name}"); assert_eq!(Refusal::path(&error).as_deref(), pointer, "{name}"); @@ -201,3 +211,42 @@ async fn misused_hooks_and_instructions_are_refused_by_name() { } } } + +/// Guards: planning refuses a cell that sets `instructions.workspace` while an input mounts a file +/// at the harness's workspace instruction file, or a path under it, naming the input, whatever the +/// case or a leading `./` of the path; an input elsewhere, and a cell that sets no text, are not +/// refused. The refusal is the planner's, so every caller of it meets it. +/// Oracle: the input kind `rules` and the paths written by hand; the file `CLAUDE.md` the Claude +/// Code harness reads. +/// Bite: leave the check out of planning, or compare the paths exactly. +#[tokio::test] +async fn planning_refuses_an_input_at_the_workspace_instruction_file() { + let file = experiment_with(""); + let claude: Arc = Arc::new(ClaudeCodeDriver::new()); + let text = [("instructions.workspace", json!("be brief"))]; + for path in [ + "CLAUDE.md", + "claude.md", + "./CLAUDE.md", + "Claude.MD/notes.md", + ] { + let refused = planned(&file, &text, Some(Arc::clone(&claude)), &[(path, "rules")]) + .await + .expect_err(path); + assert!( + matches!( + &refused, + PlanError::Driver(DriverError::InstructionsCollide { input, .. }) if input == "rules" + ), + "{path}: {refused:?}" + ); + } + for path in ["docs/CLAUDE.md", "CLAUDE.mdx"] { + planned(&file, &text, Some(Arc::clone(&claude)), &[(path, "rules")]) + .await + .expect(path); + } + planned(&file, &[], Some(claude), &[("CLAUDE.md", "rules")]) + .await + .expect("no text, no collision"); +} diff --git a/crates/candler-core/tests/it/guard_config_check.rs b/crates/candler-core/tests/it/guard_config_check.rs index 2d4bd86c..23f7565b 100644 --- a/crates/candler-core/tests/it/guard_config_check.rs +++ b/crates/candler-core/tests/it/guard_config_check.rs @@ -17,7 +17,6 @@ use candler_core::isolation::ExecOutput; use candler_core::isolation::container::mounts::{MountMode, MountSpec}; use candler_core::jobs::model::{JobOutcome, JobSpec}; use candler_core::jobs::orchestrate::session::JobHost; -use candler_core::runner::plan::refuse_instruction_collision; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ @@ -25,12 +24,10 @@ use candler_harness::spec::{ EnvValue, HarnessId, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, Workspace, }; -use candler_schemas::execution::Comparable; use candler_schemas::primitives::RelPath; use candler_schemas::process::ExitStatus; use candler_schemas::raw::StreamName; use candler_schemas::trace::{EndedBy, Session}; -use candler_schemas::values::{JsonValue, ResolvedValue}; use serde_json::{Value, json}; use support::job_orchestrate::{Probed, QuietDriver, Rig, run_to_end, spec}; use support::run_plan::Facts; @@ -537,46 +534,3 @@ fn workspace_file_is_mounted_read_only_and_is_no_output() { "the file is no input leak: {manifest}" ); } - -/// A text as a resolved value's content. -fn json_value(text: &str) -> JsonValue { - JsonValue::new(json!(text)).expect("a value") -} - -/// A cell of the fixture's resolution, with the workspace instruction text when `text` is set. -fn cell_with(text: Option<&str>) -> Comparable { - let mut values = support::run_plan::resolution(&facts()).values; - if let Some(text) = text { - values.push(ResolvedValue::recorded( - "instructions.workspace".parse().expect("a path"), - json_value(text), - )); - } - Comparable::from_resolved(&values).expect("a cell") -} - -/// Guards: an input declared at the harness's workspace instruction file is refused for a cell -/// that sets the workspace instruction text, naming the input; the same input is no collision for -/// a cell that sets none, and an input elsewhere is none for a cell that does. -/// Oracle: the input kind `rules` and the file `AGENTS.md` written by hand. -/// Bite: compare the path with the text's file by prefix only, or skip the cell's text. -#[test] -fn input_at_the_instruction_file_collides_with_the_workspace_text() { - let driver = Checking::new(false); - let at_file = [(String::from("AGENTS.md"), String::from("rules"))]; - let elsewhere = [(String::from("docs/AGENTS.md"), String::from("rules"))]; - let text = cell_with(Some("be brief")); - let none = cell_with(None); - - let refused = - refuse_instruction_collision(&driver, [&text], &at_file).expect_err("a collision"); - assert!( - matches!( - &refused, - DriverError::InstructionsCollide { input, file, .. } if input == "rules" && file == "AGENTS.md" - ), - "{refused:?}" - ); - assert!(refuse_instruction_collision(&driver, [&none], &at_file).is_ok()); - assert!(refuse_instruction_collision(&driver, [&text], &elsewhere).is_ok()); -} diff --git a/crates/candler-core/tests/it/guard_egress_setting.rs b/crates/candler-core/tests/it/guard_egress_setting.rs index 772e7f67..b7aa5e36 100644 --- a/crates/candler-core/tests/it/guard_egress_setting.rs +++ b/crates/candler-core/tests/it/guard_egress_setting.rs @@ -444,6 +444,7 @@ async fn planned( store, experiment_lock: lock, secrets_present: BTreeSet::new(), + input_targets: Vec::new(), driver: Some(Arc::new(ClaudeCodeDriver::new())), }; let outcome = plan_runs(&ctx, file, &resolution, Force::No, PlanMode::Check)?; diff --git a/crates/candler-core/tests/it/guard_session.rs b/crates/candler-core/tests/it/guard_session.rs index f2223bf3..b8bf56ac 100644 --- a/crates/candler-core/tests/it/guard_session.rs +++ b/crates/candler-core/tests/it/guard_session.rs @@ -295,6 +295,7 @@ async fn planned( store, experiment_lock: lock, secrets_present: BTreeSet::new(), + input_targets: Vec::new(), driver: Some(if capable { Arc::new(ClaudeCodeDriver::new()) } else { diff --git a/crates/candler-core/tests/it/support/run_plan.rs b/crates/candler-core/tests/it/support/run_plan.rs index e1253fbf..1a72bb75 100644 --- a/crates/candler-core/tests/it/support/run_plan.rs +++ b/crates/candler-core/tests/it/support/run_plan.rs @@ -228,6 +228,7 @@ pub fn plan_ctx(store: &Store, lock: &Path, facts: &Facts) -> PlanCtx { .map(|name| name.parse::().expect("a secret name")) .collect::>(), driver: None, + input_targets: Vec::new(), } } diff --git a/crates/candler/src/commands/run.rs b/crates/candler/src/commands/run.rs index 4c16595e..71b9641b 100644 --- a/crates/candler/src/commands/run.rs +++ b/crates/candler/src/commands/run.rs @@ -34,8 +34,7 @@ use candler_core::resolve::layers::{FileValues, Layered, Resolution, ResolveInpu use candler_core::resolve::steps::ground_truth::GroundTruth; use candler_core::resolve::steps::plugin_environment::Fragment; use candler_core::runner::plan::{ - Force, PlanCtx, PlanMode, experiment_of, plan_runs, refuse_instruction_collision, - treatment_levels, + Force, PlanCtx, PlanMode, experiment_of, plan_runs, treatment_levels, }; use candler_core::store::Store; use candler_harness::driver::HarnessDriver; @@ -273,12 +272,11 @@ fn plan_job( experiment_lock: store.layout().experiment_lock(&experiment), secrets_present: EnvSecrets::new(file.secrets()).present(), driver: Some(Arc::clone(driver)), // BORROW: the context shares the driver the collision check reads + input_targets: declared.targets.clone(), // BORROW: the context owns the paths the inputs mount }; let mode = if force { Force::Yes } else { Force::No }; let outcome = plan_runs(&ctx, file, levels.as_slice(), mode, PlanMode::Check) // BORROW: explicit .as_slice() .map_err(|e| refuse_plan(e, file))?; - refuse_instruction_collision(driver.as_ref(), outcome.fresh.values(), &declared.targets) - .map_err(CliError::refused_by)?; if levels.len() < 2 { levels.clear(); } diff --git a/crates/candler/tests/it/guard_golden_design.rs b/crates/candler/tests/it/guard_golden_design.rs index f90c6b01..ff5a536c 100644 --- a/crates/candler/tests/it/guard_golden_design.rs +++ b/crates/candler/tests/it/guard_golden_design.rs @@ -147,6 +147,7 @@ fn gd_plan_twelve_cells() { store, experiment_lock: dir.path().join("experiments").join("x").join("lock"), secrets_present: BTreeSet::new(), + input_targets: Vec::new(), driver: None, }; let out = plan_runs( diff --git a/crates/candler/tests/it/guard_instruction_collision.rs b/crates/candler/tests/it/guard_instruction_collision.rs new file mode 100644 index 00000000..62457b98 --- /dev/null +++ b/crates/candler/tests/it/guard_instruction_collision.rs @@ -0,0 +1,62 @@ +//! The workspace instruction text and a declared input that mount a file at one path are refused +//! when `candler run` plans the runs, before a container exists. +#![cfg(test)] +#![cfg(unix)] + +use crate::support::cli_run; + +use std::fs; + +use cli_run::world; + +/// Guards: an experiment that sets `instructions.workspace` and declares an input whose file lands +/// at the harness's workspace instruction file is refused by `candler run` with +/// `experiment.instructions_collide`, naming the input, with no container created; the file name +/// may differ from the harness's in its case, and an input at another path is no collision. +/// Oracle: the input kind `rules` and the file names `CLAUDE.md` and `claude.md` written by hand; +/// the fake docker's record of the containers it created. +/// Bite: leave the check out of planning, or compare the names exactly. +#[test] +fn input_at_the_instruction_file_is_refused_by_run_before_any_container() { + // (the input's file name, whether the run is refused) + let rows = [ + ("CLAUDE.md", true), + ("claude.md", true), + ("NOTES.md", false), + ]; + for (name, refused) in rows { + let world = world(); + let base = world + .experiment + .parent() + .expect("a directory") + .join("rules"); + fs::create_dir_all(&base).expect("the input directory"); + fs::write(base.join(name), "rules\n").expect("the input file"); + let mut text = fs::read_to_string(&world.experiment).expect("the experiment"); + text = text.replacen( + "[fixed]\n", + "[fixed]\n\"instructions.workspace\" = \"be brief\"\n", + 1, + ); + text.push_str("\n[[inputs]]\nkind = \"rules\"\npath = \"rules\"\n"); + fs::write(&world.experiment, text).expect("the experiment writes"); + + let out = world.launch(); + let stderr = String::from_utf8_lossy(&out.stderr).into_owned(); + let collided = stderr.contains("experiment.instructions_collide"); + assert_eq!(collided, refused, "{name}: stderr: {stderr}"); + if refused { + assert_eq!(out.status.code(), Some(2), "{name}: stderr: {stderr}"); + assert!( + stderr.contains("`rules`"), + "{name}: the input is named: {stderr}" + ); + assert_eq!( + world.handed_out(), + Vec::::new(), + "{name}: no container" + ); + } + } +} diff --git a/crates/candler/tests/it/main.rs b/crates/candler/tests/it/main.rs index fab5294a..513cebd9 100644 --- a/crates/candler/tests/it/main.rs +++ b/crates/candler/tests/it/main.rs @@ -67,6 +67,7 @@ mod guard_ingest; mod guard_input_seam; mod guard_inspect; mod guard_inspect_mcp_config; +mod guard_instruction_collision; mod guard_mcp_origin; mod guard_registry; mod guard_run_context_files; From 9b60ee02976dc6fecf210884e761e41036be068c Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:05:06 +0900 Subject: [PATCH 50/69] docs(api): say what mount_inputs assumes of its workspace Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/runner/exec/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index f5d1a0ae..e591746c 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -242,6 +242,12 @@ pub fn mounted_inputs( /// Makes the mount point of each input in the workspace, mounts each input of the cell read-only /// there from its blob in `store`, and checks the whole mount list again. /// +/// The function assumes `workspace_dir` is a directory the caller has just made: empty, with no +/// link in it, and no other writer. It makes directories and files below it without checking for +/// links, and refuses to replace a file, so a link already in place fails the call rather than +/// redirecting it. When a later input is refused, the mount points made for the earlier ones stay +/// in `workspace_dir` and the mounts already added stay in `container`: the caller discards both. +/// /// # Errors /// [`IsolationError::Plan`] when an input's path leaves the workspace, its mount point cannot be /// made, or the mount list is refused. From 1e1f23e7b1e37526479d47b451753092f691e2fd Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:11:48 +0900 Subject: [PATCH 51/69] feat(api): install instructions and plugins on OpenCode The global text goes to AGENTS.md and the plugins to plugins/ in OpenCode's config directory, the workspace text is the plan's read-only AGENTS.md, and a bad value is refused at resolve. The census names the Instructions from: blocks of the first request that offers tools, which the core now reads from the gateway stream. The config check starts opencode on a model that does not exist and rejects on a WARN line, or on output that never reached the model. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/runner/exec/mod.rs | 1 + .../tests/it/guard_census_gateway.rs | 49 ++++ .../candler-core/tests/it/support/wiring.rs | 7 +- crates/candler-harness-opencode/src/driver.rs | 130 +++++++++-- .../candler-harness-opencode/src/prepare.rs | 113 +++++++++- .../tests/fixtures/PROVENANCE.toml | 33 +++ .../tests/fixtures/check/bad_json.txt | 45 ++++ .../tests/fixtures/check/bad_plugin.txt | 48 ++++ .../tests/fixtures/check/valid.txt | 43 ++++ .../gateway/census_instructions.jsonl | 3 + .../tests/it/guard_opencode_driver.rs | 213 +++++++++++++++++- docs/contract/configuration-paths.md | 6 +- docs/contract/harness-capabilities.md | 17 +- 13 files changed, 675 insertions(+), 33 deletions(-) create mode 100644 crates/candler-harness-opencode/tests/fixtures/check/bad_json.txt create mode 100644 crates/candler-harness-opencode/tests/fixtures/check/bad_plugin.txt create mode 100644 crates/candler-harness-opencode/tests/fixtures/check/valid.txt create mode 100644 crates/candler-harness-opencode/tests/fixtures/gateway/census_instructions.jsonl diff --git a/crates/candler-core/src/runner/exec/mod.rs b/crates/candler-core/src/runner/exec/mod.rs index 8031dd78..e6bb5647 100644 --- a/crates/candler-core/src/runner/exec/mod.rs +++ b/crates/candler-core/src/runner/exec/mod.rs @@ -754,6 +754,7 @@ async fn drive( if rt.driver.census_from_gateway() { gateway_init = census_init(&bytes); } + loaded.extend(rt.driver.loaded_instructions(&name, &bytes)); context = census_context(&bytes).map(|(frame, kind)| (RawRef::new(name, frame), kind)); extra.push(file); diff --git a/crates/candler-core/tests/it/guard_census_gateway.rs b/crates/candler-core/tests/it/guard_census_gateway.rs index f4a3edcb..19dcc82e 100644 --- a/crates/candler-core/tests/it/guard_census_gateway.rs +++ b/crates/candler-core/tests/it/guard_census_gateway.rs @@ -169,6 +169,55 @@ fn census_gateway_run_records_the_first_request_with_tools_or_nothing() { assert!(none.raw("gateway_census").is_some(), "the stream is kept"); } +/// The gateway log that holds the lines of the recorded gateway stream of `OpenCode` (`census` and +/// `context` lines, the shape the sidecar writes), for the run [`LOG_RUN`] under the tag [`LOG_TAG`]. +fn log_of_recorded_stream() -> String { + use std::fmt::Write as _; + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../candler-harness-opencode/tests/fixtures/gateway/census_instructions.jsonl"); + let stream = std::fs::read_to_string(path).expect("the recorded gateway stream"); + let mut log = String::new(); + for record in stream.lines() { + let line: Value = serde_json::from_str(record).expect("a stream line"); + let seq = &line["seq"]; + if let Some(tools) = line.get("tools") { + writeln!( + log, + "census run={LOG_RUN} tag={LOG_TAG} seq={seq} tools={tools}" + ) + .expect("a string takes text"); + } else { + let body = &line["context"]; + writeln!( + log, + "context run={LOG_RUN} tag={LOG_TAG} seq={seq} body={body}" + ) + .expect("a string takes text"); + } + } + log +} + +/// Guards: the census of instruction files — a run behind the gateway records, as +/// `census.instructions`, the `Instructions from:` blocks of the system text of the first request +/// that offered tools, which the core hands to the driver from the stored gateway stream. +/// Oracle: the system text of a recorded `OpenCode` 2.2.7 request (`fixtures/gateway` of +/// `candler-harness-opencode`), and the two paths written by hand. +/// Bite: leave the gateway stream out of the streams the driver reads, or read the title request. +#[test] +fn census_gateway_run_records_the_instruction_files_of_the_first_request_with_tools() { + let mut scenario = Scenario::exited("completed_o1"); + scenario.log = log_of_recorded_stream(); + let ran = run(&scenario, |_, _| {}); + assert_eq!( + ran.measured("census.instructions"), + Some(json!([ + {"path": "/home/agent/.xdg/config/opencode/AGENTS.md", "scope": "user"}, + {"path": "/work/AGENTS.md", "scope": "project"}, + ])) + ); +} + /// A row of the verdict guard: its name, two arms' census values and the verdict between them. type Row<'a> = ( &'a str, diff --git a/crates/candler-core/tests/it/support/wiring.rs b/crates/candler-core/tests/it/support/wiring.rs index 226f3426..d69c567e 100644 --- a/crates/candler-core/tests/it/support/wiring.rs +++ b/crates/candler-core/tests/it/support/wiring.rs @@ -26,7 +26,8 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::spec::{ AgentSetting, Answer, Cell, CollectSpec, CommandSpec, DriverFact, EnvEntry, GatewayEnv, - HarnessId, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, Workspace, + HarnessId, LoadedFile, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, + Workspace, }; use candler_harness_opencode::driver::OpenCodeDriver; use candler_schemas::execution::EventPayload; @@ -199,6 +200,10 @@ impl HarnessDriver for WiringDriver { self.0.census_from_gateway() } + fn loaded_instructions(&self, stream: &StreamName, bytes: &[u8]) -> Vec { + self.0.loaded_instructions(stream, bytes) + } + fn stop(&self) -> StopSpec { self.0.stop() } diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index 77fa3a72..cac8289c 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -12,8 +12,9 @@ use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ Action, AgentSetting, Answer, BaseImage, Cell, CheckVerdict, CollectSpec, CommandSpec, - DriverFact, GatewayEnv, HarnessId, OPENCODE, Observed, Prepared, ProcessExit, - StateKind, StatePath, StopSignal, StopSpec, Workspace, + DriverFact, EnvEntry, GATEWAY_STREAM, GatewayEnv, GatewayRecord, HarnessId, LoadedFile, + LoadedScope, OPENCODE, Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, + StopSpec, Workspace, gateway_records, }; use candler_schemas::name; use candler_schemas::primitives::{RelPath, plain_arg}; @@ -42,6 +43,15 @@ const STATE: [(&str, StateKind, &str); 5] = [ ("OPENCODE_DB", StateKind::File, ".xdg/data/oc.db"), ]; +/// The model of the config check: one `OpenCode` cannot select, so the start ends at the model. +const CHECK_MODEL: &str = "probe/none"; +/// The directory the config check keeps its data home and database in, away from the run's. +const CHECK_DATA: &str = "/tmp/candler-config-check"; + +/// The text that opens an instruction file in the system text of a request, at the start of a +/// line: `Instructions from: `, then the file's text. +const INSTRUCTIONS_MARKER: &str = "Instructions from: "; + /// How long a stopped run has to exit after the signal: `OpenCode` ended in under 100 ms on TERM. const STOP_GRACE: Duration = Duration::from_secs(10); @@ -65,6 +75,45 @@ fn root_end(sessions: &[Session]) -> Option<&EndedBy> { exported.or_else(|| roots.next()).map(Session::ended_by) } +/// The instruction files the starting context of the first request that offers tools names, in the +/// order the system text holds them, each once, as `OpenCode` printed their paths. `bytes` is the +/// stream `stream`; any other stream lists nothing. A file under the config directory of the agent's +/// home is the user's own; any other is the workspace's. +fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { + if stream.as_str() != GATEWAY_STREAM { + return Vec::new(); + } + let first = gateway_records(bytes) + .filter_map(|(_, record)| { + let GatewayRecord::Context { seq, context } = record else { + return None; + }; + Some((seq, context)) + }) + .min_by_key(|(seq, _)| *seq); + let Some((_, context)) = first else { + return Vec::new(); + }; + let own = format!("/{}/", OpenCodeDriver::state_subpath("XDG_CONFIG_HOME")); + let mut files: Vec = Vec::new(); + for path in context + .system + .lines() + .filter_map(|line| line.strip_prefix(INSTRUCTIONS_MARKER)) + { + let scope = if path.contains(own.as_str()) { + LoadedScope::User + } else { + LoadedScope::Project + }; + let file = LoadedFile::new(path.to_owned(), scope); // BORROW: .to_owned() gives the file its own path + if !path.is_empty() && !files.contains(&file) { + files.push(file); + } + } + files +} + /// The `OpenCode` V2 driver. #[derive(Debug, Clone)] #[non_exhaustive] @@ -176,8 +225,8 @@ impl HarnessDriver for OpenCodeDriver { DriverFact::Census => Answer::Candler { how: "the tools the gateway offered the model in its first request", }, - DriverFact::ConfigCheck => Answer::Refused { - reason: "this driver installs no configuration file to check", + DriverFact::ConfigCheck => Answer::Mapped { + construct: "`opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` lines name a rejected `opencode.json` or a plugin that failed to load", }, DriverFact::UnsetPermissionMode => Answer::Candler { how: "the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode", @@ -187,12 +236,60 @@ impl HarnessDriver for OpenCodeDriver { fn config_check(&self, plan: &Plan) -> Option { let _ = plan; - None + // A model that does not exist ends the start at the model, after the configuration and + // the plugins have loaded, so no request leaves. The start keeps the plan's configuration + // home and writes its database and data under a throwaway directory, not the run's. + let argv = argv(&[ + PROGRAM, + "run", + "--standalone", + "--print-logs", + "-m", + CHECK_MODEL, + "x", + ]); + CommandSpec::builder() + .argv(argv) + // BORROW: .to_owned() makes the owned names and values + .env(EnvEntry::literal( + "XDG_DATA_HOME".to_owned(), + CHECK_DATA.to_owned(), + )) + .env(EnvEntry::literal( + "OPENCODE_DB".to_owned(), + format!("{CHECK_DATA}/oc.db"), + )) + .build() + .ok() } fn read_config_check(&self, output: &[u8]) -> CheckVerdict { - let _ = output; - CheckVerdict::Clean + let text = String::from_utf8_lossy(output); + // The exit status is 1 whatever the start found. Output is a report only when it holds the + // line that says the start reached the model; without it the check never got that far + // (empty output, an error, a changed format), and never passes. + let reached_model = text.lines().any(|line| { + line.contains("Failed to drain Session") && line.contains("ModelUnavailableError") + }); + if !reached_model { + return CheckVerdict::Rejected { + output: text.into_owned(), + }; + } + let warnings: Vec<&str> = text + .lines() + .filter(|line| line.contains("level=WARN")) + .collect(); + if warnings.is_empty() { + return CheckVerdict::Clean; + } + CheckVerdict::Rejected { + output: warnings.join("\n"), + } + } + + fn loaded_instructions(&self, stream: &StreamName, bytes: &[u8]) -> Vec { + loaded(stream, bytes) } fn workspace_instruction_file(&self) -> &'static str { @@ -222,6 +319,7 @@ impl HarnessDriver for OpenCodeDriver { fn check_settings(&self, cell: &Cell<'_>) -> Result<(), DriverError> { prepare::settings(cell)?; + prepare::check_agent_config(cell)?; let names: Vec = candler_harness::mcp::servers(cell)? .map(|servers| servers.into_keys().collect()) .unwrap_or_default(); @@ -231,28 +329,34 @@ impl HarnessDriver for OpenCodeDriver { fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { let _ = workspace; let settings = prepare::settings(cell)?; + let config_dir = Self::state_subpath("XDG_CONFIG_HOME"); let model = model_id(cell)?; let model_arg = match &settings.variant { Some((id, _)) => format!("{}/{model}#{id}", prepare::PROVIDER), None => format!("{}/{model}", prepare::PROVIDER), }; - let file = prepare::render_config( + let mut files = vec![prepare::render_config( cell, settings, - Self::state_subpath("XDG_CONFIG_HOME"), + config_dir, GATEWAY_BASE_URL, GATEWAY_AUTH_TOKEN, - )?; + )?]; + let (global, workspace_file) = prepare::render_instructions(cell, config_dir)?; + files.extend(global); + files.extend(prepare::render_plugins(cell, config_dir)?); let mut line = argv(&[PROGRAM, "run", "--standalone", "--format", "json"]); line.push("--auto".to_owned()); // BORROW: .to_owned() makes the owned argument line.push("-m".to_owned()); // BORROW: .to_owned() makes the owned argument line.push(model_arg); line.push("--".to_owned()); // BORROW: .to_owned() makes the owned argument line.push(cell.prompt()?); - Ok(Plan::new( - Prepared::new(vec![file], Vec::new()), + let mut plan = Plan::new( + Prepared::new(files, Vec::new()), CommandSpec::builder().argv(line).build()?, - )) + ); + plan.workspace_files.extend(workspace_file); + Ok(plan) } fn stop(&self) -> StopSpec { diff --git a/crates/candler-harness-opencode/src/prepare.rs b/crates/candler-harness-opencode/src/prepare.rs index fda43ac2..d8ae3bf5 100644 --- a/crates/candler-harness-opencode/src/prepare.rs +++ b/crates/candler-harness-opencode/src/prepare.rs @@ -9,10 +9,13 @@ use std::str::FromStr as _; +use candler_harness::agent_config::{hooks, instructions}; use candler_harness::driver::DriverError; use candler_harness::spec::{ - AgentSetting, Answer, Cell, EffortLevel, PermissionMode, PreparedFile, + AgentSetting, Answer, Cell, EffortLevel, InstructionScope, OPENCODE, PermissionMode, + PreparedFile, }; +use candler_schemas::agent_config::OpenCodeHooks; use candler_schemas::execution::paths::{ MCP, MODEL_EFFORT, MODEL_ID, TOOLS_ALLOWED, TOOLS_DISALLOWED, }; @@ -191,8 +194,14 @@ pub(crate) const fn answer(setting: AgentSetting) -> Answer { AgentSetting::SessionMode => Answer::Refused { reason: "OpenCode runs no session: its trace comes from the export after the run", }, - AgentSetting::Instructions(_) | AgentSetting::Hooks => Answer::Refused { - reason: "this driver installs no instruction text or hook", + AgentSetting::Instructions(InstructionScope::Global) => Answer::Mapped { + construct: "`AGENTS.md` in `opencode/` under `XDG_CONFIG_HOME`, which OpenCode loads ahead of the workspace file", + }, + AgentSetting::Instructions(InstructionScope::Workspace) => Answer::Mapped { + construct: "`AGENTS.md` at the workspace root, mounted read-only", + }, + AgentSetting::Hooks => Answer::Mapped { + construct: "local plugin files in `opencode/plugins/` under `XDG_CONFIG_HOME`, which OpenCode loads with no npm install", }, } } @@ -535,7 +544,99 @@ pub(crate) fn render_config( let mut text = serde_json::to_string_pretty(&Value::Object(root)) .map_err(|error| invalid(MCP, error.to_string()))?; // BORROW: .to_string() gives owned text text.push('\n'); - let path = RelPath::from_str(&format!("{config_dir}/opencode/opencode.json")) - .map_err(|error| invalid(MCP, error.to_string()))?; // BORROW: .to_string() gives owned text - Ok(PreparedFile::in_home(path, text.into_bytes(), false)) + config_file(config_dir, "opencode.json", text.into_bytes(), MCP) +} + +/// The file `name` of `OpenCode`'s config directory, written into the agent's home. `config_dir` +/// is the home-relative directory that `XDG_CONFIG_HOME` names, and `field` is the cell field the +/// file comes from, which a refusal names. +fn config_file( + config_dir: &str, + name: &str, + contents: Vec, + field: &str, +) -> Result { + let path = RelPath::from_str(&format!("{config_dir}/opencode/{name}")) + .map_err(|error| invalid(field, error.to_string()))?; // BORROW: .to_string() gives owned text + Ok(PreparedFile::in_home(path, contents, false)) +} + +/// The instruction files of a cell: the global text as `AGENTS.md` in the config directory of the +/// agent's home, and the workspace text as `AGENTS.md` at the workspace root, each only when the +/// cell sets it. The workspace file is mounted read-only by the core and written by no driver, so +/// it is the plan's workspace file. +/// +/// # Errors +/// [`DriverError`] when the cell's instructions cannot be used. +pub(crate) fn render_instructions( + cell: &Cell<'_>, + config_dir: &str, +) -> Result<(Option, Option), DriverError> { + let Some(found) = instructions(cell, OPENCODE)? else { + return Ok((None, None)); + }; + let global = found + .global + .get(OPENCODE) + .map(|text| { + // BORROW: .to_vec() copies the text into the file + config_file( + config_dir, + INSTRUCTION_FILE, + text.as_bytes().to_vec(), + "instructions.global", + ) + }) + .transpose()?; + let workspace = found + .workspace + .as_ref() + .map(|text| { + RelPath::from_str(INSTRUCTION_FILE) + // BORROW: .to_vec() copies the text into the file + .map(|path| PreparedFile::new(path, text.as_bytes().to_vec(), false)) + .map_err(|error| invalid("instructions.workspace", error.to_string())) // BORROW: .to_string() gives owned text + }) + .transpose()?; + Ok((global, workspace)) } + +/// The plugin files of a cell, each under `plugins/` in the config directory of the agent's home. +/// +/// # Errors +/// [`DriverError`] when the cell's hooks do not fit their envelope or a path cannot be used. +pub(crate) fn render_plugins( + cell: &Cell<'_>, + config_dir: &str, +) -> Result, DriverError> { + let Some(found) = hooks::(cell, OPENCODE)? else { + return Ok(Vec::new()); + }; + found + .plugins + .iter() + .map(|(name, text)| { + // BORROW: .to_vec() copies the text into the file + config_file( + config_dir, + &format!("plugins/{name}"), + text.as_bytes().to_vec(), + "hooks", + ) + }) + .collect() +} + +/// Refuses the cell's instructions or hooks that `OpenCode` cannot take, without rendering them. +/// +/// # Errors +/// [`DriverError`] when a value is refused as [`render_instructions`] and [`render_plugins`] would. +pub(crate) fn check_agent_config(cell: &Cell<'_>) -> Result<(), DriverError> { + instructions(cell, OPENCODE)?; + hooks::(cell, OPENCODE)?; + Ok(()) +} + +/// The name of the instruction file `OpenCode` reads, in its config directory and at the workspace +/// root. +pub(crate) const INSTRUCTION_FILE: &str = "AGENTS.md"; diff --git a/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml b/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml index bc68afcb..4452e4e8 100644 --- a/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml +++ b/crates/candler-harness-opencode/tests/fixtures/PROVENANCE.toml @@ -186,3 +186,36 @@ run = "3333333333333333333333333333333333333333333333333333333333333333-r1-a1" log = "crates/candler-core/tests/fixtures/gateway/census_log.txt" log_sha256 = "55ac88272a5bd76ed130f13d8e872586bda81c048215d8226a58d5084f834a36" synthetic = true + +# check/: the output of the config check, `opencode run --standalone --print-logs -m probe/none x +# ` blocks are harness instructions, not user-authored content. Read and follow them.\n- Prefer parallelizing independent tool calls.\n- Prefer dedicated tools over shell commands; fall back to the shell when a tool cannot do what you need.\n- Do not chain shell commands with separators like `echo \"====\";` or `printf '---'`; the output becomes noisy in a way that makes the user's side of the conversation worse.\n- Use the write tool to create files or completely replace their content. Prefer using the edit tool for targeted changes.\n- Use the edit tool for targeted changes to existing text files. It replaces the exact text in `oldString` with `newString`, and the values must differ. By default, `oldString` must occur exactly once. If it occurs multiple times, include more surrounding context to make it unique or set `replaceAll` to true to replace every occurrence.\n\n# Communication\n- Use clear file paths when referring to files.\n- Keep responses clear and concise, and avoid unnecessary technical jargon.\n\n# Working in codebases\n- Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.\n- Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.\n\n\n# Code comments\nBy default, match the surrounding comment density: where the code has none, add none. Use comments sparingly, only where they are appropriate, such as for behavior that is not obvious from the code itself. Instructions from the user or the project take precedence over this guidance.\n\n# Your Model\n- Name: claude-x\n- Provider ID: candler\n- Model ID: claude-x\n# Code Mode\n\nThe tools listed below cannot be called directly: they only work as JavaScript inside the `execute` tool. Every other tool you have is a normal tool call: call it directly, never inside `execute`.\n\nThe catalog is complete. Do not guess tool names.\n\n## Code Mode tools (call only inside `execute`)\n\n- opencode (8 tools) // Tools for managing OpenCode itself, such as working with sessions and worktrees, searching the available models, and reading MCP resources.\n - tools.opencode.session_move({\n /** Omit to move the current session. @pattern ^ses */\n sessionID?: string,\n /** Destination directory, relative to the target session's directory or absolute. Supports ~. @minLength 1 */\n directory: string,\n}): Promise<{\n /** @pattern ^ses */\n sessionID: string,\n directory: string,\n}> // Move a session to another directory, or omit sessionID to move the current session. The current session moves at the ...\n - tools.opencode.worktree_create({\n name: string,\n}): Promise<{\n directory: string,\n}> // Create a named worktree. Returns its directory.\n - tools.opencode.worktree_list(): Promise<{\n worktrees: Array<{\n directory: string,\n strategy?: string,\n }>,\n}> // List a repository's worktrees.\n - tools.opencode.worktree_remove({\n /** Absolute path of the worktree to remove. @minLength 1 */\n directory: string,\n /** Discard modified and untracked files. Only set this when the user has confirmed forced removal. */\n force?: boolean,\n}): Promise<{\n directory: string,\n removed: boolean,\n}> // Remove a worktree. The repository location selects configuration; directory identifies the worktree to remove.\n - tools.opencode.list_mcp_resources({\n /** MCP server name as configured. Omit to list every server. */\n server?: string,\n}): Promise<{\n resources: Array<{\n server: string,\n name: string,\n uri: string,\n description?: string,\n mimeType?: string,\n }>,\n templates: Array<{\n server: string,\n name: string,\n uriTemplate: string,\n description?: string,\n mimeType?: string,\n }>,\n}> // List documents, records, and other data exposed by MCP servers. Use this when the user refers to something that is no...\n - tools.opencode.models({\n /** Text to search for in model names and IDs. */\n query?: string,\n /** Provider ID or name to filter by. Try your own provider first. */\n provider?: string,\n /**\n * Which kind of model to list. Defaults to \"chat\".\n * \"chat\": a language model (LLM). Powers sessions, agents and subagents, and can call tools.\n * \"image\": generates or edits images from a prompt. It can't chat or call tools.\n */\n type?: \"chat\" | \"image\",\n /** Include older versions of each model family. By default only the newest version is listed. */\n all?: boolean,\n /** Maximum number of models to return. Defaults to 20. @integer @minimum 1 @maximum 100 */\n limit?: number,\n /** Number of models to skip, for paging through results. @integer @minimum 0 */\n offset?: number,\n}): Promise<{\n /** Matching models grouped by provider. Your own provider comes first. */\n providers: Array<{\n id: string,\n name: string,\n /** Newest first. */\n models: Array<{\n /** providerID/modelID */\n id: string,\n name: string,\n /** Release date as a Unix timestamp in milliseconds, or 0 when unknown. */\n released: number,\n variants: Array,\n /** Pricing in USD per million tokens. */\n cost: Array<{\n tier?: {\n type: \"context\",\n /** @integer */\n size: number,\n },\n input: number,\n output: number,\n cache: {\n read: number,\n write: number,\n },\n }>,\n status: \"alpha\" | \"beta\" | \"deprecated\" | \"active\",\n }>,\n }>,\n /** Number of matching models across all pages. @integer */\n total: number,\n /** Offset of the next page, or null on the last page. */\n next: number | null,\n}> // Search the models available to use. Use this to turn a model name the user mentions into an exact reference for a too...\n - tools.opencode.read_mcp_resource({\n /** The server field of the discovered resource. */\n server: string,\n /** Exact resource URI from discovery, an expanded uriTemplate, or the user. */\n uri: string,\n}): Promise<{\n server: string,\n uri: string,\n contents: Array<{\n type: \"text\",\n uri: string,\n text: string,\n mimeType?: string,\n } | {\n type: \"blob\",\n uri: string,\n blob: string,\n mimeType?: string,\n }>,\n}> // Read one MCP resource by server and URI. Not for local files. Always return the full contents rather than slicing or ...\n - tools.opencode.session_rename({\n /** Omit to rename the current session. @pattern ^ses */\n sessionID?: string,\n /** New session title. @minLength 1 */\n title: string,\n}): Promise<{\n /** @pattern ^ses */\n sessionID: string,\n title: string,\n}> // Rename a session, or omit sessionID to rename the current session. Use a short, specific title that summarizes the wo...\n\nSkills provide specialized instructions and workflows for specific tasks.\nUse the skill tool to load a skill when a task matches its description.\nThe user may also invoke a skill directly. When that happens, its instructions appear in the conversation as a block, the same shape the skill tool returns. A skill that is already present this way does not need to be invoked again.\n\n \n opencode\n OpenCode\n Use this skill for any question about OpenCode itself, including how OpenCode works, using or configuring it, migrating from V1 to V2, troubleshooting it, developing plugins or integrations, using the OpenCode SDK, clients, server, or API, and contributing to the OpenCode codebase. Also use it for OpenCode agents, commands, skills, tools, permissions, MCP servers, providers, models, themes, keybinds, formatters, the CLI, TUI, desktop app, and web app.\n \n \n report\n Report\n Use when the user wants to report an opencode issue or bug. Collect standard diagnostics, add user-specific reproduction context, and publish the issue with GitHub CLI.\n \n\n\nInstructions from: /home/agent/.xdg/config/opencode/AGENTS.md\nglobal text\n\n\nInstructions from: /work/AGENTS.md\nworkspace text\n\n\nToday's date: Wed Nov 25 2026\n\nHere is some useful information about the environment you are running in:\n\n Working directory: /work\n Workspace root folder: /work\n Is directory a git repo: no\n Platform: linux\n Prefer /tmp/opencode over generic system temporary directories such as /tmp; it is pre-created and approved for external access.\n\nWhen you create a worktree outside the current working directory and intend to use it as your primary working directory, consider using `execute` to call `tools.opencode.session_move` and make the worktree the session's working directory.\nPLUGIN_CONTEXT"},"seq":2} diff --git a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs index e54a11f1..18c28636 100644 --- a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs +++ b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs @@ -13,8 +13,9 @@ use std::str::FromStr as _; use candler_harness::driver::{DriverError, HarnessDriver}; use candler_harness::reader::FrameIn; use candler_harness::spec::{ - Action, AgentSetting, Answer, Cell, CollectSpec, EffortLevel, Observed, PermissionMode, - ProcessEnd, ProcessExit, StopSignal, Workspace, + Action, AgentSetting, Answer, Cell, CheckVerdict, CollectSpec, DriverFact, EffortLevel, + FileRoot, GATEWAY_STREAM, InstructionScope, Observed, PermissionMode, ProcessEnd, ProcessExit, + StopSignal, Workspace, }; use candler_harness_opencode::driver::OpenCodeDriver; use candler_schemas::execution::{GitCommit, TreatmentRef}; @@ -1606,3 +1607,211 @@ fn the_config_holds_the_keys_opencode_documents() -> Res<()> { ); Ok(()) } + +/// Guards: G3 plan — a cell with `instructions.global.opencode`, `instructions.workspace` and +/// `hooks.opencode` places the global text and each plugin in the config directory of the home +/// byte for byte, after the configuration file, lists `AGENTS.md` with the workspace text among +/// the read-only workspace files and writes nothing in the workspace; a cell without them plans +/// the configuration file alone. A plugin name that leaves the directory is refused at resolve and +/// at plan. +/// Oracle: the texts and paths written here by hand, from the probe's rows E9 and E12. +/// Bite: leave a plugin out, write `AGENTS.md` into the prepared files, or install the global text +/// outside the config directory. +#[test] +fn opencode_installs_the_global_text_the_plugins_and_the_workspace_text() -> Res<()> { + let driver = OpenCodeDriver::new(); + let workspace = Workspace::new(Path::new("/work/run")); + let extra = [ + ("instructions.global", json!({"opencode": "global text"})), + ("instructions.workspace", json!("workspace text")), + ( + "hooks", + json!({"opencode": {"plugins": {"good.ts": "export default {}\n"}}}), + ), + ]; + let cell = values(&extra)?; + let plan = driver.plan(&Cell::new(&cell), &workspace)?; + let files: Vec<(&str, FileRoot, &[u8])> = plan + .prepared + .files + .iter() + .map(|file| (file.path.as_str(), file.root, file.contents.as_slice())) + .collect(); + assert_eq!( + files.first().map(|file| file.0), + Some(".xdg/config/opencode/opencode.json") + ); + assert_eq!( + files.get(1..), + Some( + [ + ( + ".xdg/config/opencode/AGENTS.md", + FileRoot::Home, + b"global text".as_slice() + ), + ( + ".xdg/config/opencode/plugins/good.ts", + FileRoot::Home, + b"export default {}\n".as_slice() + ), + ] + .as_slice() + ) + ); + let [file] = plan.workspace_files.as_slice() else { + return Err("expected one workspace file".into()); + }; + assert_eq!(file.path.as_str(), "AGENTS.md"); + assert_eq!(file.root, FileRoot::Workspace); + assert_eq!(file.contents, b"workspace text"); + + let bare = values(&[])?; + let plan = driver.plan(&Cell::new(&bare), &workspace)?; + let paths: Vec<&str> = plan + .prepared + .files + .iter() + .map(|file| file.path.as_str()) + .collect(); + assert_eq!(paths, [".xdg/config/opencode/opencode.json"]); + assert_eq!(plan.workspace_files, []); + + for name in ["../x.ts", "a/../../x.ts", "/etc/x.ts"] { + let hostile = values(&[("hooks", json!({"opencode": {"plugins": {name: "x"}}}))])?; + assert!( + driver.check_settings(&Cell::new(&hostile)).is_err(), + "{name} passed the check" + ); + assert!( + driver.plan(&Cell::new(&hostile), &workspace).is_err(), + "{name} was planned" + ); + } + let other = values(&[("hooks", json!({"claude-code": {}}))])?; + assert!(driver.check_settings(&Cell::new(&other)).is_err()); + assert_eq!(driver.workspace_instruction_file(), "AGENTS.md"); + Ok(()) +} + +/// Guards: G3 rows — the instructions, hooks and config check answers are the mapping the plan +/// installs, not a refusal. +/// Oracle: the variants, written by hand. +/// Bite: leave any of the four answers refused. +#[test] +fn opencode_answers_the_instruction_hook_and_check_rows_as_mapped() { + let driver = OpenCodeDriver::new(); + for setting in [ + AgentSetting::Instructions(InstructionScope::Global), + AgentSetting::Instructions(InstructionScope::Workspace), + AgentSetting::Hooks, + ] { + assert!( + matches!(driver.answer(setting), Answer::Mapped { .. }), + "{setting:?}" + ); + } + assert!(matches!( + driver.fact(DriverFact::ConfigCheck), + Answer::Mapped { .. } + )); +} + +/// Guards: the census — the instruction files of the first request that offers tools, read from the +/// recorded gateway stream through the driver, reach `census.instructions` in the order the +/// request holds them: the file under the agent's config directory as `user`, the workspace file +/// as `project`, each as `OpenCode` printed its path; another stream, or a stream with no context +/// line, lists nothing. +/// Oracle: the recorded system text of an `OpenCode` 2.2.7 request (`fixtures/gateway`) and the +/// expected value by hand. +/// Bite: list the "Instructions from the user" sentence of the base prompt, label the workspace file +/// `user`, or read the title request. +#[test] +fn opencode_census_names_the_instruction_files_of_the_first_request_with_tools() -> Res<()> { + use candler_core::runner::evidence::census::census_instructions; + let driver = OpenCodeDriver::new(); + let bytes = std::fs::read(fixtures().join("gateway/census_instructions.jsonl"))?; + let stream: StreamName = GATEWAY_STREAM.parse()?; + let loaded = driver.loaded_instructions(&stream, &bytes); + let value = census_instructions(&loaded)?.ok_or("nothing recorded")?; + assert_eq!(value.path().to_string(), "census.instructions"); + assert_eq!( + serde_json::to_value(value.value())?, + json!([ + {"path": "/home/agent/.xdg/config/opencode/AGENTS.md", "scope": "user"}, + {"path": "/work/AGENTS.md", "scope": "project"}, + ]) + ); + let other: StreamName = "stdout".parse()?; + assert_eq!(driver.loaded_instructions(&other, &bytes), []); + let first_line = bytes + .split(|byte| *byte == b'\n') + .next() + .ok_or("empty fixture")?; + assert_eq!(driver.loaded_instructions(&stream, first_line), []); + Ok(()) +} + +/// Guards: the config check — the start of `opencode run` with a model that does not exist ends at +/// the model, so output with that line is a report; a `level=WARN` line of it is a rejection +/// whatever the exit status and the `INFO` lines; output without the line (empty, an error, a start +/// that failed before the model) is a rejection carrying that output, so a check that never ran +/// never passes. The command keeps the plan's configuration home, moves the data home and the +/// database under a throwaway directory, and runs in the workspace. +/// Oracle: the recorded outputs of `OpenCode` 2.2.7 in `fixtures/check`. +/// Bite: reject on any `ERROR` line, accept empty output, or leave the database at the run's. +#[test] +fn opencode_config_check_reads_the_warnings_of_a_start_that_reached_the_model() -> Res<()> { + let driver = OpenCodeDriver::new(); + let cell = values(&[])?; + let plan = driver.plan(&Cell::new(&cell), &Workspace::new(Path::new("/work")))?; + let check = driver.config_check(&plan).ok_or("no check")?; + assert_eq!( + check.argv(), + [ + "opencode", + "run", + "--standalone", + "--print-logs", + "-m", + "probe/none", + "x" + ] + ); + let set: Vec<&str> = check + .env_overlay() + .iter() + .map(|entry| entry.name.as_str()) + .collect(); + assert_eq!(set, ["XDG_DATA_HOME", "OPENCODE_DB"]); + let recorded = |name: &str| std::fs::read(fixtures().join("check").join(name)); + assert_eq!( + driver.read_config_check(&recorded("valid.txt")?), + CheckVerdict::Clean + ); + let CheckVerdict::Rejected { output } = driver.read_config_check(&recorded("bad_json.txt")?) + else { + return Err("a malformed opencode.json is not rejected".into()); + }; + assert!( + output.lines().all(|line| line.contains("level=WARN")), + "{output}" + ); + assert!(output.contains("rejected malformed JSON or JSONC document")); + let CheckVerdict::Rejected { output } = driver.read_config_check(&recorded("bad_plugin.txt")?) + else { + return Err("a plugin with no default export is not rejected".into()); + }; + assert_eq!(output.lines().count(), 1, "{output}"); + assert!(output.contains("Plugin must export a default definition")); + let no_model = b"timestamp=2026-11-25T08:56:41.603Z level=INFO message=\"cli starting\"\n"; + for not_a_report in [&b""[..], b"error: could not reach the server\n", no_model] { + assert_eq!( + driver.read_config_check(not_a_report), + CheckVerdict::Rejected { + output: String::from_utf8_lossy(not_a_report).into_owned() + } + ); + } + Ok(()) +} diff --git a/docs/contract/configuration-paths.md b/docs/contract/configuration-paths.md index b3327ef1..ace0ba34 100644 --- a/docs/contract/configuration-paths.md +++ b/docs/contract/configuration-paths.md @@ -25,9 +25,9 @@ Core line: `v0.16.0`. | `tools.disallowed` | the path | experiment value | The tools the harness may not use. | tools disallowed: `permissions.deny` of `.claude/settings.json` | tools disallowed: a permission row {action, *, deny} per name, written after the allow rows | | `env` | the path | experiment value | The environment of the harness process: a table of variable name to text. | env: Candler: the core sets the cell's variables on the agent's process | env: Candler: the core sets the cell's variables on the agent's process | | `mcp` | the path and every path below it | experiment value | The MCP servers of a run; the names below are free. | MCP transport: stdio: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: local: an entry of `mcpServers` in `.mcp.json`, of type `stdio`; MCP transport: http: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP transport: sse: an entry of `mcpServers` in `.mcp.json`, of type `sse`; MCP transport: remote: an entry of `mcpServers` in `.mcp.json`, of type `http`; MCP codemode: off: no key: Claude Code offers the server's tools directly; MCP codemode: on: no (Claude Code offers MCP tools directly; it has no code mode); MCP server name: the key of the server's `.mcp.json` entry | MCP transport: stdio: an `mcp` entry of type `local`; MCP transport: local: an `mcp` entry of type `local`; MCP transport: http: an `mcp` entry of type `remote`; MCP transport: sse: no (OpenCode documents no SSE transport; its `remote` is Streamable HTTP); MCP transport: remote: an `mcp` entry of type `remote`; MCP codemode: off: the `codemode` key of the `mcp` entry, `false`: the server's tools are direct tools; MCP codemode: on: the `codemode` key of the `mcp` entry, `true`: the server's tools are reached through `execute`, whose calls the trace records with empty `wrapped_calls`, so MCP calls made inside `execute` are not attributed and do not compare with Claude Code; MCP server name: the key of the `mcp` entry | -| `instructions.global` | the path and every path below it | experiment value | The global instruction text of each harness: a table of harness id, as registered, to text; the keys are free. | instructions: global: `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither); instructions: workspace: `CLAUDE.md` at the workspace root, mounted read-only | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | -| `instructions.workspace` | the path | experiment value | The instruction text at the root of the workspace. | instructions: global: `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither); instructions: workspace: `CLAUDE.md` at the workspace root, mounted read-only | instructions: global: no (this driver installs no instruction text or hook); instructions: workspace: no (this driver installs no instruction text or hook) | -| `hooks` | the path and every path below it | experiment value | The hooks of each harness: a table of harness id, as registered, to its `settings` table and `files` table (Claude Code) or its `plugins` table (OpenCode); the keys are free. | hooks: the `hooks` key of `.claude/settings.json`, with the hook files under `.claude/hooks/` | hooks: no (this driver installs no instruction text or hook) | +| `instructions.global` | the path and every path below it | experiment value | The global instruction text of each harness: a table of harness id, as registered, to text; the keys are free. | instructions: global: `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither); instructions: workspace: `CLAUDE.md` at the workspace root, mounted read-only | instructions: global: `AGENTS.md` in `opencode/` under `XDG_CONFIG_HOME`, which OpenCode loads ahead of the workspace file; instructions: workspace: `AGENTS.md` at the workspace root, mounted read-only | +| `instructions.workspace` | the path | experiment value | The instruction text at the root of the workspace. | instructions: global: `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither); instructions: workspace: `CLAUDE.md` at the workspace root, mounted read-only | instructions: global: `AGENTS.md` in `opencode/` under `XDG_CONFIG_HOME`, which OpenCode loads ahead of the workspace file; instructions: workspace: `AGENTS.md` at the workspace root, mounted read-only | +| `hooks` | the path and every path below it | experiment value | The hooks of each harness: a table of harness id, as registered, to its `settings` table and `files` table (Claude Code) or its `plugins` table (OpenCode); the keys are free. | hooks: the `hooks` key of `.claude/settings.json`, with the hook files under `.claude/hooks/` | hooks: local plugin files in `opencode/plugins/` under `XDG_CONFIG_HOME`, which OpenCode loads with no npm install | | `permission_mode` | the path | experiment value | The permission mode the harness runs in. | permission mode: default: `--permission-mode ` on the command line; permission mode: acceptEdits: `--permission-mode ` on the command line; permission mode: plan: `--permission-mode ` on the command line; permission mode: bypassPermissions: `--permission-mode ` on the command line; permission mode: auto: `--permission-mode ` on the command line; permission mode: dontAsk: `--permission-mode ` on the command line | permission mode: default: no (Claude Code's default mode allows reads and a built-in, non-configurable set of read-only shell commands that its own parser decides, and denies the rest in a headless run. OpenCode without `--auto` also rejects what no rule allows, but its shell rows are wildcards on the text of each parsed command, which approximate that set without being it); permission mode: acceptEdits: no (Claude Code's acceptEdits mode also allows edits and the filesystem commands mkdir, touch, rm, rmdir, mv, cp and sed, inside the working directory only. OpenCode's shell resource is the command's text, which knows no working directory, so "inside it" cannot be written as a rule); permission mode: plan: no (Claude Code's plan mode reads and runs read-only shell commands (a built-in, non-configurable set its own parser decides). The OpenCode ruleset that is certainly read-only (the `explore` agent's: deny everything, allow read, glob, grep, webfetch, websearch, skill) denies the shell altogether, and a wildcard on command text cannot express the read-only set; the stock `plan` agent is not read-only once a global rule follows it (the last match wins) and its `subagent` child can edit); permission mode: bypassPermissions: `--auto` on the command line: every tool call is allowed by the baseline ruleset {*, *, allow}; `--auto` answers the one pending ask (`.env` reads) with once, which a headless run needs; permission mode: auto: no (Claude Code's auto mode has a model classifier review each action, such as a shell command or a network request, before it runs. OpenCode has no classifier, and a ruleset decides by the action's text alone); permission mode: dontAsk: no (Claude Code's dontAsk mode denies every call that would prompt, so it allows the allow rules plus reads and the built-in, non-configurable set of read-only shell commands its own parser decides. OpenCode's shell rows are wildcards on the text of each parsed command, which approximate that set without being it) | | `request.harness` | the path | request key | The harness the run uses. | Candler only | Candler only | | `request.treatment` | the path | request key | The treatment the run applies. | Candler only | Candler only | diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index 6db29d5a..4408bd5c 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -48,9 +48,9 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | turn cap | `--max-turns` on the command line | no (`agents..steps` makes the last request a tool-less one with an injected prompt and ends the run as completed (the `oc_step_cap` fixture), where Claude Code ends the run with `error_max_turns`, so the cap class would be lost and the model's last turn changed) | | cost cap | `--max-budget-usd` on the command line | no (OpenCode has no cost cap) | | session mode | stream-json over an open stdin, one turn per message | no (OpenCode runs no session: its trace comes from the export after the run) | -| instructions: global | `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither) | no (this driver installs no instruction text or hook) | -| instructions: workspace | `CLAUDE.md` at the workspace root, mounted read-only | no (this driver installs no instruction text or hook) | -| hooks | the `hooks` key of `.claude/settings.json`, with the hook files under `.claude/hooks/` | no (this driver installs no instruction text or hook) | +| instructions: global | `.claude/CLAUDE.md` in the agent's home, read through `user` in `--setting-sources`, which also loads the home's `.claude/settings.json` and `.claude/rules/*.md` (Candler's home holds neither) | `AGENTS.md` in `opencode/` under `XDG_CONFIG_HOME`, which OpenCode loads ahead of the workspace file | +| instructions: workspace | `CLAUDE.md` at the workspace root, mounted read-only | `AGENTS.md` at the workspace root, mounted read-only | +| hooks | the `hooks` key of `.claude/settings.json`, with the hook files under `.claude/hooks/` | local plugin files in `opencode/plugins/` under `XDG_CONFIG_HOME`, which OpenCode loads with no npm install | | gateway route | Candler: gateway, address in `ANTHROPIC_BASE_URL` | Candler: gateway, address in `CANDLER_GATEWAY_URL` | | authoritative trace | yes | Candler: collects `export` after the run | | graceful stop | SIGTERM ends the sessions cleanly | an interrupt request to the `serve` child, then SIGTERM to the client | @@ -59,7 +59,7 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | execution outside the child | no (tools run in the child process) | tools run in the `serve` child, which the stop interrupts first | | census source | Claude Code's `system/init` event lists the tools | Candler: the tools the gateway offered the model in its first request | | permission mode when none is set | `--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it | Candler: the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode | -| config check | `claude doctor` in the workspace, whose `Invalid settings` section lists a rejected file or a skipped entry | no (this driver installs no configuration file to check) | +| config check | `claude doctor` in the workspace, whose `Invalid settings` section lists a rejected file or a skipped entry | `opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` lines name a rejected `opencode.json` or a plugin that failed to load | ## Refusals @@ -73,8 +73,9 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. ## Notes -- `no (…)` is a refusal: `experiment.session_refused` while resolving, `experiment.setting_unsupported` when the cells are planned, before a job starts. [checked: v@0.15.0] -- In session mode Candler also counts turns across the session and ends the run when they exceed `budget.per_run.turns`. [checked: v@0.7.0] -- The settings a driver maps or refuses, such as permission modes, effort levels and tool names, are the answers its driver gives for each `AgentSetting`. [checked: v@0.7.0] +- `no (…)` is a refusal: `experiment.session_refused` while resolving, `experiment.setting_unsupported` once the cells are planned, before a job starts. [checked: v@0.15.0] +- In session mode Candler also counts turns and ends the run past `budget.per_run.turns`. [checked: v@0.7.0] +- A driver's answers for each `AgentSetting` decide which modes, effort levels and tool names it maps or refuses. [checked: v@0.7.0] - Every Claude Code cell runs three observer hooks, headless too, archives their log as stream `hooks`, and gets one `claude doctor` check per distinct (image, prepared files). [checked: v@0.16.0] -- `census.instructions` is read from the hook log in the agent's home, which the agent can change during the run; the trace's `context_start` shows what reached the model. [checked: v@0.16.0] +- `census.instructions` is read from the hook log in the agent's home, which the agent can change; `context_start` shows what reached the model. [checked: v@0.16.0] +- A plain OpenCode cell gets no instruction file or plugin; `census.instructions` is the gateway's record of the first request offering tools. [checked: v@0.16.0] From 970a768bc3cde0aa5b55f8d65b58c3fc21846a11 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:14:03 +0900 Subject: [PATCH 52/69] test(api): find the strict MCP flags anywhere in the Claude Code command The guard took the last three words of the command for the MCP flags; the observers settings file now follows them. Co-Authored-By: Claude Opus 5.5 --- .../tests/it/guard_plugin_environment.rs | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/crates/candler-core/tests/it/guard_plugin_environment.rs b/crates/candler-core/tests/it/guard_plugin_environment.rs index 92e93abb..4403343c 100644 --- a/crates/candler-core/tests/it/guard_plugin_environment.rs +++ b/crates/candler-core/tests/it/guard_plugin_environment.rs @@ -924,17 +924,10 @@ async fn a_plugins_mcp_servers_reach_claude_code() { text, "the .mcp.json of {selector:?}" ); - let tail: Vec<&str> = argv - .iter() - .rev() - .take(3) - .rev() - .map(String::as_str) - .collect(); - assert_eq!( - tail, - ["--mcp-config", ".mcp.json", "--strict-mcp-config"], - "the end of the command of {selector:?}" + assert!( + argv.windows(3) + .any(|run| run == ["--mcp-config", ".mcp.json", "--strict-mcp-config"]), + "the command of {selector:?} names no strict .mcp.json: {argv:?}" ); } else { assert!(file.is_none(), "a cell without mcp.* prepares a .mcp.json"); From 775bdcd206eb77a9b53bd6034616df81fc3ce247 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:18:40 +0900 Subject: [PATCH 53/69] fix(api): let the check's own variables win over the run's Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/isolation/testing.rs | 9 ++++ .../src/jobs/orchestrate/config.rs | 10 ++++- .../tests/it/guard_config_check.rs | 45 ++++++++++++++++++- 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/crates/candler-core/src/isolation/testing.rs b/crates/candler-core/src/isolation/testing.rs index a3e59bc4..c700bcc1 100644 --- a/crates/candler-core/src/isolation/testing.rs +++ b/crates/candler-core/src/isolation/testing.rs @@ -487,6 +487,7 @@ pub struct ProbingIsolation { needs: Mutex>, prints: Mutex>, executed: Mutex, Vec)>>, + executed_env: Mutex>>, run_mounts: Mutex>>, } @@ -504,6 +505,7 @@ impl ProbingIsolation { needs: Mutex::new(BTreeSet::new()), prints: Mutex::new(BTreeMap::new()), executed: Mutex::new(Vec::new()), + executed_env: Mutex::new(Vec::new()), run_mounts: Mutex::new(Vec::new()), } } @@ -522,6 +524,12 @@ impl ProbingIsolation { held(&self.prints).insert(program.to_owned(), output); // BORROW: the script owns its words } + /// The environment of the container of each command run for its output so far. + #[must_use] + pub fn executed_env(&self) -> Vec> { + held(&self.executed_env).clone() // BORROW: the caller owns the copy + } + /// The commands run for their output so far, as their words, each with the mounts of the /// container it ran in. #[must_use] @@ -593,6 +601,7 @@ impl super::Isolation for ProbingIsolation { command: &'a candler_harness::spec::CommandSpec, ) -> BoxFuture<'a, Result> { held(&self.executed).push((command.argv().to_vec(), plan.mounts.clone())); // BORROW: the log owns the words and the mounts + held(&self.executed_env).push(plan.env.clone()); // BORROW: the log owns the environment let printed = command .argv() .first() diff --git a/crates/candler-core/src/jobs/orchestrate/config.rs b/crates/candler-core/src/jobs/orchestrate/config.rs index 72ed9cc5..519c9809 100644 --- a/crates/candler-core/src/jobs/orchestrate/config.rs +++ b/crates/candler-core/src/jobs/orchestrate/config.rs @@ -263,13 +263,21 @@ async fn grouped<'a>( continue; } let root = scratch.join(seen.len().to_string()); // BORROW: .to_string() gives owned text - let (staged, container) = stage_container(rt, isolation, plan, &root, false) + let (staged, mut container) = stage_container(rt, isolation, plan, &root, false) .await .map_err(|e| failed(&e))?; let Some(command) = rt.driver.config_check(&staged) else { let _ = fs::remove_dir_all(&root); // EXPLICIT: a cell with no check keeps nothing of its staging continue; }; + // The check's own variables win over the container's, as the isolation refuses a name + // set twice: a state variable of the run, which the check places elsewhere, gives way. + container.env.retain(|(name, _)| { + !command + .env_overlay() + .iter() + .any(|entry| entry.name == *name) + }); let key = group_key(rt, plan, &staged, &container, &command)?; match groups.entry(key) { Entry::Occupied(mut held) => { diff --git a/crates/candler-core/tests/it/guard_config_check.rs b/crates/candler-core/tests/it/guard_config_check.rs index 23f7565b..08a5750f 100644 --- a/crates/candler-core/tests/it/guard_config_check.rs +++ b/crates/candler-core/tests/it/guard_config_check.rs @@ -19,6 +19,7 @@ use candler_core::jobs::model::{JobOutcome, JobSpec}; use candler_core::jobs::orchestrate::session::JobHost; use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; +use candler_harness::spec::StateKind; use candler_harness::spec::{ AgentSetting, Answer, Cell, CheckVerdict, CollectSpec, CommandSpec, DriverFact, EnvEntry, EnvValue, HarnessId, Observed, Prepared, PreparedFile, ProcessExit, StatePath, StopSpec, @@ -35,6 +36,9 @@ use support::run_plan::Facts; /// The text of the workspace file the stand-in harness lists. const WORKSPACE_TEXT: &str = "be brief"; +/// The variable the stand-in's state path and its check both set. +const STATE_VARIABLE: &str = "XDG_DATA_HOME"; + /// The program of the stand-in harness's check. const CHECK: &str = "harness-check"; @@ -47,6 +51,8 @@ struct Checking { vary: Vary, /// Whether the run collects every file of the workspace as an output. collect_all: bool, + /// Whether a state variable of the run is one the check's own environment sets. + shared_state: bool, /// How many times the harness was asked to plan a cell. planned: Arc, } @@ -73,6 +79,7 @@ impl Checking { check, vary: Vary::Nothing, collect_all: false, + shared_state: false, planned: Arc::new(AtomicUsize::new(0)), } } @@ -95,6 +102,12 @@ impl HarnessDriver for Checking { } }) .unwrap_or_default(); + if self.shared_state { + builder = builder.env(EnvEntry::literal( + STATE_VARIABLE.to_owned(), + "/tmp/candler-config-check".to_owned(), + )); + } if self.vary == Vary::CommandEnv { builder = builder.env(EnvEntry::literal("CHECK_MODEL".to_owned(), model.clone())); } @@ -161,7 +174,15 @@ impl HarnessDriver for Checking { } fn state_paths(&self) -> Vec { - self.inner.state_paths() + let mut paths = self.inner.state_paths(); + if self.shared_state { + paths.push(StatePath::new( + STATE_VARIABLE.to_owned(), + StateKind::Dir, + ".local/share".parse::().expect("a path"), + )); + } + paths } fn plan(&self, cell: &Cell<'_>, workspace: &Workspace<'_>) -> Result { @@ -534,3 +555,25 @@ fn workspace_file_is_mounted_read_only_and_is_no_output() { "the file is no input leak: {manifest}" ); } + +/// Guards: a variable the check's command sets wins over the container's own: a state variable of +/// the run with the same name is left out of the check container's environment, which the +/// isolation would otherwise refuse as a name set twice, and the job is not refused. +/// Oracle: the variable name `XDG_DATA_HOME` and its values written by hand; the environment the +/// isolation double recorded for the check container. +/// Bite: leave the run's variable in the check container, which then holds the name twice or the +/// run's value. +#[test] +fn the_checks_own_variable_wins_over_the_runs() { + let mut driver = Checking::new(true); + driver.shared_state = true; + let ran = run(job(&["m1"]), driver, "ok"); + assert_eq!(ran.outcome.runs.len(), 1, "the run starts"); + let probing = ran.host.probing(); + let held = probing.executed_env(); + let env = held.first().expect("the check ran"); + assert!( + env.iter().all(|(name, _)| name != STATE_VARIABLE), + "the check container keeps the run's variable: {env:?}" + ); +} From 286707e2d4e7f857b60ceb8480cf6ab474d9829a Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:19:49 +0900 Subject: [PATCH 54/69] rdm(api): mark the M6.5 harness check done Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/installed/README.md | 4 ++-- .../m6_5-agent-config/installed/preflight_check.md | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/installed/README.md b/__roadmap__/m6_5-agent-config/installed/README.md index c03d8e80..17979ab7 100644 --- a/__roadmap__/m6_5-agent-config/installed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/README.md @@ -18,7 +18,7 @@ Each driver installs the global instruction text and hooks where its harness loo graph TD install_claude_code[Install on Claude Code]:::done install_opencode[Install on OpenCode]:::planned - preflight_check[Preflight check]:::planned + preflight_check[Preflight check]:::done proved[Proved]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -32,7 +32,7 @@ graph TD |:-----|:-----|:-------| | `install_claude_code.md` | 📄 Leaf Task | ✅ Done | | `install_opencode.md` | 📄 Leaf Task | ⬜ Planned | -| `preflight_check.md` | 📄 Leaf Task | ⬜ Planned | +| `preflight_check.md` | 📄 Leaf Task | ✅ Done | | `proved/` | 📁 Directory | ⬜ Planned | ## Amendment Log diff --git a/__roadmap__/m6_5-agent-config/installed/preflight_check.md b/__roadmap__/m6_5-agent-config/installed/preflight_check.md index 1345ae78..de36b928 100644 --- a/__roadmap__/m6_5-agent-config/installed/preflight_check.md +++ b/__roadmap__/m6_5-agent-config/installed/preflight_check.md @@ -5,12 +5,12 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ With a driver whose check reports a finding, the job is refused before its first run with `experiment.harness_rejected_input`, the way a declared server that exits at start is refused. The message names what was installed, where, the harness, and the harness's output. No run starts and no check container is left. On the base, the job runs. -- ⬜ With a clean check, the verdict is stored beside the harness identity in the run's provenance. With a driver whose `config_check` is `None`, the cell is not refused and nothing is stored as checked. -- ⬜ Cells that share a harness, image and prepared files run the check once, counted on the isolation the check uses. -- ⬜ G9 (core half). With a fake driver whose plan lists a read-only workspace file, the run's workspace holds it at the root, a write to it fails, it is not among the collected outputs, and the run is not sealed `input_leak`. On the base, `Plan` has no such field. -- ⬜ G10. With `instructions.workspace` set, an input declared at the workspace instruction file's path is refused when the runs are planned, before any container starts, with `experiment.instructions_collide`, naming the input. On the base, the job runs. -- ⬜ An adversarial Sonnet review finds no path where a finding lets the cell run, and no check container that outlives the step. +- ✅ With a driver whose check reports a finding, the job is refused before its first run with `experiment.harness_rejected_input`, the way a declared server that exits at start is refused. The message names what was installed, where, the harness, and the harness's output. No run starts and no check container is left. On the base, the job runs. +- ✅ With a clean check, the verdict is stored beside the harness identity in the run's provenance. With a driver whose `config_check` is `None`, the cell is not refused and nothing is stored as checked. +- ✅ Cells that share a harness, image and prepared files run the check once, counted on the isolation the check uses. +- ✅ G9 (core half). With a fake driver whose plan lists a read-only workspace file, the run's workspace holds it at the root, a write to it fails, it is not among the collected outputs, and the run is not sealed `input_leak`. On the base, `Plan` has no such field. +- ✅ G10. With `instructions.workspace` set, an input declared at the workspace instruction file's path is refused when the runs are planned, before any container starts, with `experiment.instructions_collide`, naming the input. On the base, the job runs. +- ✅ An adversarial Sonnet review finds no path where a finding lets the cell run, and no check container that outlives the step. **References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-core/src/jobs/orchestrate/servers.rs` (`check_servers`, the precedent, called from `run_job`); `crates/candler-core/src/runner/plan.rs` (`plan_runs`) ## Step 1: The check From 806aeb84203af931949da939a5519978990560af Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:22:08 +0900 Subject: [PATCH 55/69] fix(api): refuse OpenCode check errors, read the census scope by prefix Co-Authored-By: Claude Sonnet 5.5 --- __design__/architecture.md | 6 +-- crates/candler-harness-opencode/src/driver.rs | 38 +++++++++++++------ .../tests/it/guard_opencode_driver.rs | 24 ++++++++++-- docs/contract/harness-capabilities.md | 6 +-- 4 files changed, 53 insertions(+), 21 deletions(-) diff --git a/__design__/architecture.md b/__design__/architecture.md index 81dab704..2fcb3cfa 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -715,8 +715,8 @@ implements only what its harness has. driver. No default names exist: a driver that names none is refused at run time - `state_paths() -> StatePath { env, kind: Dir | File, subpath }[]`: the places the harness keeps state under the agent's home. The core makes each per run and sets its variable - - `census_stream() -> Option`: the raw stream the gateway's census is stored under, - for a harness with no init event. The core reads the gateway census itself + - `census_from_gateway() -> bool`: the harness has no init event, so the core reads the census + from the gateway's record of the first request - `session(cell, workspace) -> Option` and `session_tracker() -> Option>` - `stop() -> StopSpec { pre_stop: Option, signal, grace }`, with @@ -860,7 +860,7 @@ version and by the sha256 of the release archive of each architecture. `_`), the deny rows last. A name with no OpenCode action is refused. - **Census.** No event, command or export lists OpenCode's tools. The tool names in the request the agent sends to the model are the inventory, so the gateway sidecar records the names of each - request, and the core takes the first request that carries tools (`census_stream`, + request, and the core takes the first request that carries tools (`census_from_gateway`, `census.source = gateway`). A run whose requests carry no tools records no inventory. The verdict never takes a gateway inventory for a harness's own. - **Facts.** `graceful_stop`, `census` and `execution_outside_child`. Not `SessionMode`. diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index cac8289c..9d228b2d 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -34,6 +34,9 @@ const GATEWAY_BASE_URL: &str = "CANDLER_GATEWAY_URL"; /// The variable that holds the gateway's token; the configuration refers to it. const GATEWAY_AUTH_TOKEN: &str = "CANDLER_GATEWAY_TOKEN"; +/// The agent's home inside the container, which the state paths are relative to. +const AGENT_HOME: &str = "/home/agent"; + /// The state directories and the database file, relative to the agent's home. const STATE: [(&str, StateKind, &str); 5] = [ ("XDG_DATA_HOME", StateKind::Dir, ".xdg/data"), @@ -77,8 +80,10 @@ fn root_end(sessions: &[Session]) -> Option<&EndedBy> { /// The instruction files the starting context of the first request that offers tools names, in the /// order the system text holds them, each once, as `OpenCode` printed their paths. `bytes` is the -/// stream `stream`; any other stream lists nothing. A file under the config directory of the agent's -/// home is the user's own; any other is the workspace's. +/// stream `stream`; any other stream lists nothing. A file under the `XDG_CONFIG_HOME` the plan sets +/// is the user's own; any other is the workspace's. The census reads `OpenCode`'s `Instructions +/// from:` lines, which `OpenCode` does not escape, so a line of that shape inside an instruction +/// text counts too. fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { if stream.as_str() != GATEWAY_STREAM { return Vec::new(); @@ -94,14 +99,17 @@ fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { let Some((_, context)) = first else { return Vec::new(); }; - let own = format!("/{}/", OpenCodeDriver::state_subpath("XDG_CONFIG_HOME")); + let own = format!( + "{AGENT_HOME}/{}/", + OpenCodeDriver::state_subpath("XDG_CONFIG_HOME") + ); let mut files: Vec = Vec::new(); for path in context .system .lines() .filter_map(|line| line.strip_prefix(INSTRUCTIONS_MARKER)) { - let scope = if path.contains(own.as_str()) { + let scope = if path.starts_with(own.as_str()) { LoadedScope::User } else { LoadedScope::Project @@ -114,6 +122,12 @@ fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { files } +/// The line that marks a check start that reached the model: the session drain failing on the model +/// that does not exist. +fn is_drain(line: &str) -> bool { + line.contains("Failed to drain Session") && line.contains("ModelUnavailableError") +} + /// The `OpenCode` V2 driver. #[derive(Debug, Clone)] #[non_exhaustive] @@ -226,7 +240,7 @@ impl HarnessDriver for OpenCodeDriver { how: "the tools the gateway offered the model in its first request", }, DriverFact::ConfigCheck => Answer::Mapped { - construct: "`opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` lines name a rejected `opencode.json` or a plugin that failed to load", + construct: "`opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` and `level=ERROR` lines name a rejected `opencode.json` or a plugin that failed to load", }, DriverFact::UnsetPermissionMode => Answer::Candler { how: "the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode", @@ -268,23 +282,23 @@ impl HarnessDriver for OpenCodeDriver { // The exit status is 1 whatever the start found. Output is a report only when it holds the // line that says the start reached the model; without it the check never got that far // (empty output, an error, a changed format), and never passes. - let reached_model = text.lines().any(|line| { - line.contains("Failed to drain Session") && line.contains("ModelUnavailableError") - }); + let reached_model = text.lines().any(is_drain); if !reached_model { return CheckVerdict::Rejected { output: text.into_owned(), }; } - let warnings: Vec<&str> = text + let findings: Vec<&str> = text .lines() - .filter(|line| line.contains("level=WARN")) + .filter(|line| { + line.contains("level=WARN") || (line.contains("level=ERROR") && !is_drain(line)) + }) .collect(); - if warnings.is_empty() { + if findings.is_empty() { return CheckVerdict::Clean; } CheckVerdict::Rejected { - output: warnings.join("\n"), + output: findings.join("\n"), } } 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 18c28636..0a185342 100644 --- a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs +++ b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs @@ -1742,6 +1742,15 @@ fn opencode_census_names_the_instruction_files_of_the_first_request_with_tools() {"path": "/work/AGENTS.md", "scope": "project"}, ]) ); + let moved = + String::from_utf8(bytes.clone())?.replace("/work/AGENTS.md", "/work/.xdg/config/AGENTS.md"); + assert_eq!( + serde_json::to_value(driver.loaded_instructions(&stream, moved.as_bytes()))?, + json!([ + {"path": "/home/agent/.xdg/config/opencode/AGENTS.md", "scope": "user"}, + {"path": "/work/.xdg/config/AGENTS.md", "scope": "project"}, + ]) + ); let other: StreamName = "stdout".parse()?; assert_eq!(driver.loaded_instructions(&other, &bytes), []); let first_line = bytes @@ -1753,13 +1762,13 @@ fn opencode_census_names_the_instruction_files_of_the_first_request_with_tools() } /// Guards: the config check — the start of `opencode run` with a model that does not exist ends at -/// the model, so output with that line is a report; a `level=WARN` line of it is a rejection -/// whatever the exit status and the `INFO` lines; output without the line (empty, an error, a start +/// the model, so output with that line is a report; a `level=WARN` line, or a `level=ERROR` line other than the +/// model's, is a rejection whatever the exit status and the `INFO` lines; output without the line (empty, an error, a start /// that failed before the model) is a rejection carrying that output, so a check that never ran /// never passes. The command keeps the plan's configuration home, moves the data home and the /// database under a throwaway directory, and runs in the workspace. /// Oracle: the recorded outputs of `OpenCode` 2.2.7 in `fixtures/check`. -/// Bite: reject on any `ERROR` line, accept empty output, or leave the database at the run's. +/// Bite: reject the model's own `ERROR` line, pass another `ERROR` line, accept empty output, or leave the database at the run's. #[test] fn opencode_config_check_reads_the_warnings_of_a_start_that_reached_the_model() -> Res<()> { let driver = OpenCodeDriver::new(); @@ -1804,6 +1813,15 @@ fn opencode_config_check_reads_the_warnings_of_a_start_that_reached_the_model() }; assert_eq!(output.lines().count(), 1, "{output}"); assert!(output.contains("Plugin must export a default definition")); + let valid = String::from_utf8(recorded("valid.txt")?)?; + let with_error = format!( + "{valid}timestamp=2026-11-25T08:57:01.050Z level=ERROR run=8c7beda5 message=\"Failed to load config\" role=server\n" + ); + let CheckVerdict::Rejected { output } = driver.read_config_check(with_error.as_bytes()) else { + return Err("an ERROR line other than the model's is not rejected".into()); + }; + assert_eq!(output.lines().count(), 1, "{output}"); + assert!(output.contains("Failed to load config")); let no_model = b"timestamp=2026-11-25T08:56:41.603Z level=INFO message=\"cli starting\"\n"; for not_a_report in [&b""[..], b"error: could not reach the server\n", no_model] { assert_eq!( diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index 4408bd5c..d91ee589 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -59,7 +59,7 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | execution outside the child | no (tools run in the child process) | tools run in the `serve` child, which the stop interrupts first | | census source | Claude Code's `system/init` event lists the tools | Candler: the tools the gateway offered the model in its first request | | permission mode when none is set | `--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it | Candler: the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode | -| config check | `claude doctor` in the workspace, whose `Invalid settings` section lists a rejected file or a skipped entry | `opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` lines name a rejected `opencode.json` or a plugin that failed to load | +| config check | `claude doctor` in the workspace, whose `Invalid settings` section lists a rejected file or a skipped entry | `opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` and `level=ERROR` lines name a rejected `opencode.json` or a plugin that failed to load | ## Refusals @@ -74,8 +74,8 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. ## Notes - `no (…)` is a refusal: `experiment.session_refused` while resolving, `experiment.setting_unsupported` once the cells are planned, before a job starts. [checked: v@0.15.0] -- In session mode Candler also counts turns and ends the run past `budget.per_run.turns`. [checked: v@0.7.0] +- In session mode Candler counts turns and ends the run past `budget.per_run.turns`. [checked: v@0.7.0] - A driver's answers for each `AgentSetting` decide which modes, effort levels and tool names it maps or refuses. [checked: v@0.7.0] - Every Claude Code cell runs three observer hooks, headless too, archives their log as stream `hooks`, and gets one `claude doctor` check per distinct (image, prepared files). [checked: v@0.16.0] -- `census.instructions` is read from the hook log in the agent's home, which the agent can change; `context_start` shows what reached the model. [checked: v@0.16.0] +- `census.instructions` is read from the hook log in the agent's home, which the agent can change; the trace's `context_start` shows what reached the model. [checked: v@0.16.0] - A plain OpenCode cell gets no instruction file or plugin; `census.instructions` is the gateway's record of the first request offering tools. [checked: v@0.16.0] From 04c2d2f44ccc3bd9c5669b20048eb32b40d80d20 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:38:35 +0900 Subject: [PATCH 56/69] rdm(api): mark the M6.5 OpenCode install done Co-Authored-By: Claude Opus 5.5 --- __roadmap__/m6_5-agent-config/installed/README.md | 4 ++-- __roadmap__/m6_5-agent-config/installed/install_opencode.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/__roadmap__/m6_5-agent-config/installed/README.md b/__roadmap__/m6_5-agent-config/installed/README.md index 17979ab7..dbb502ef 100644 --- a/__roadmap__/m6_5-agent-config/installed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/README.md @@ -17,7 +17,7 @@ Each driver installs the global instruction text and hooks where its harness loo ```mermaid graph TD install_claude_code[Install on Claude Code]:::done - install_opencode[Install on OpenCode]:::planned + install_opencode[Install on OpenCode]:::done preflight_check[Preflight check]:::done proved[Proved]:::planned classDef done fill:#166534,color:#bbf7d0 @@ -31,7 +31,7 @@ graph TD | Node | Type | Status | |:-----|:-----|:-------| | `install_claude_code.md` | 📄 Leaf Task | ✅ Done | -| `install_opencode.md` | 📄 Leaf Task | ⬜ Planned | +| `install_opencode.md` | 📄 Leaf Task | ✅ Done | | `preflight_check.md` | 📄 Leaf Task | ✅ Done | | `proved/` | 📁 Directory | ⬜ Planned | diff --git a/__roadmap__/m6_5-agent-config/installed/install_opencode.md b/__roadmap__/m6_5-agent-config/installed/install_opencode.md index 100590b5..219f5d85 100644 --- a/__roadmap__/m6_5-agent-config/installed/install_opencode.md +++ b/__roadmap__/m6_5-agent-config/installed/install_opencode.md @@ -7,9 +7,9 @@ - [ ] `[nl]` The probe report settles (c), (d) and (f) - [ ] `[nl]` `install_claude_code`'s census channel for loaded instruction files is merged into `feat/m6.5-agent-config` **Success Gates**: -- ⬜ G3 (OpenCode). The *instructions*, *hooks* and *config check* rows show the OpenCode mapping: `$XDG_CONFIG_HOME/opencode/AGENTS.md`, and the workspace's root `AGENTS.md`, read-only; local plugins in `$XDG_CONFIG_HOME/opencode/plugins/`; and the probe's check or `no (…)`. On the base, no such rows exist. -- ⬜ The plan of a cell with `instructions.global.opencode`, `instructions.workspace` and `hooks.opencode` places the global `AGENTS.md` and each plugin in the home, byte for byte, lists `AGENTS.md` with the workspace text among its read-only workspace files, and writes nothing in the workspace itself. On the base, the plan has none of these. -- ⬜ The census lists each `Instructions from: ` block of the run's first request that offers tools, read from a recorded request fixture. +- ✅ G3 (OpenCode). The *instructions*, *hooks* and *config check* rows show the OpenCode mapping: `$XDG_CONFIG_HOME/opencode/AGENTS.md`, and the workspace's root `AGENTS.md`, read-only; local plugins in `$XDG_CONFIG_HOME/opencode/plugins/`; and the probe's check or `no (…)`. On the base, no such rows exist. +- ✅ The plan of a cell with `instructions.global.opencode`, `instructions.workspace` and `hooks.opencode` places the global `AGENTS.md` and each plugin in the home, byte for byte, lists `AGENTS.md` with the workspace text among its read-only workspace files, and writes nothing in the workspace itself. On the base, the plan has none of these. +- ✅ The census lists each `Instructions from: ` block of the run's first request that offers tools, read from a recorded request fixture. **References**: [Architecture report, v2](../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler-harness-opencode/src/prepare.rs` (`render_config`, `PreparedFile::in_home`); the OpenCode V2 evidence in the report ## Step 1: Install, census and check From ef1415cb581859c8f06002c60f097feeafb692fc Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 18:58:31 +0900 Subject: [PATCH 57/69] test(api): answer the harness check in the fake Docker The job start now runs the harness check in a control container before any agent. The fake Docker answered it with something that is not a report, so every job was refused before its first run. The shell fake of the CLI tests prints the claude-code doctor fixture for the control run of `claude doctor`. The core fake answers the control run that carries `--print-logs` (the OpenCode check; its export run does not) from run-check.out, which the wiring support fills from the OpenCode check fixture. Co-Authored-By: Claude Sonnet 5.5 --- .../candler-core/tests/fixtures/docker/fake-docker | 7 +++++++ crates/candler-core/tests/it/support/wiring.rs | 8 +++++++- crates/candler/tests/it/support/cli_run.rs | 12 +++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/candler-core/tests/fixtures/docker/fake-docker b/crates/candler-core/tests/fixtures/docker/fake-docker index 0548288d..f3007df2 100755 --- a/crates/candler-core/tests/fixtures/docker/fake-docker +++ b/crates/candler-core/tests/fixtures/docker/fake-docker @@ -9,6 +9,8 @@ # .early (stdout printed before the delay), # .delay (seconds to sleep first). is argv[1], or "-" # for the grouped commands image, network and container (image-inspect). +# A `run` of a control container (`candler.role=control`) that runs `--print-logs` is the harness +# check and is answered from run-check.out, so run.out stays the answer of every other run. # State (D20): `build -t ` creates $FAKE_DOCKER_DIR/built- (tag with / and : as _). # `image inspect ` succeeds only once that marker exists (stdout from image-inspect.out, # else "[]"), and exits 1 with "No such image" before it. A test may touch a marker to preset it. @@ -26,6 +28,11 @@ case "$verb" in image|network|container) [ -n "${2:-}" ] && verb="$1-$2" ;; esac +# The harness check (a control container running `--print-logs`) has its own answer. +case "$verb" in + run) case " $* " in *" candler.role=control "*" --print-logs "*) verb="run-check" ;; esac ;; +esac + [ -f "$FAKE_DOCKER_DIR/$verb.early" ] && cat "$FAKE_DOCKER_DIR/$verb.early" [ -f "$FAKE_DOCKER_DIR/$verb.delay" ] && sleep "$(cat "$FAKE_DOCKER_DIR/$verb.delay")" diff --git a/crates/candler-core/tests/it/support/wiring.rs b/crates/candler-core/tests/it/support/wiring.rs index d69c567e..a4fb09c5 100644 --- a/crates/candler-core/tests/it/support/wiring.rs +++ b/crates/candler-core/tests/it/support/wiring.rs @@ -459,7 +459,7 @@ pub fn planned_key() -> RunKey { } /// Scripts the fake client's `inspect` and `ls` answers for the agent of the run `key`, and the -/// answer of a collect container: `export`. +/// answer of a collect container: `export`, and the clean report of the harness check. fn script(rig: &Rig, key: &RunKey, export: Option<&str>) { let id = agent_cid(); let labels = json!({ @@ -482,6 +482,12 @@ fn script(rig: &Rig, key: &RunKey, export: Option<&str>) { if let Some(text) = export { fs::write(canned.join("run.out"), text).expect("an export"); } + fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../candler-harness-opencode/tests/fixtures/check/valid.txt"), + canned.join("run-check.out"), + ) + .expect("a clean check report"); } /// Every docker call the fake client logged, in order. The client writes one JSON array of argv diff --git a/crates/candler/tests/it/support/cli_run.rs b/crates/candler/tests/it/support/cli_run.rs index fd593616..a70fb321 100644 --- a/crates/candler/tests/it/support/cli_run.rs +++ b/crates/candler/tests/it/support/cli_run.rs @@ -166,7 +166,11 @@ inspect) echo true ;; run) - case " $* " in *" --version "*) echo "2.1.311 (Claude Code)" ;; esac + case " $* " in + *" --version "*) echo "2.1.311 (Claude Code)" ;; + # The harness check: the control container that runs `claude doctor` prints a clean report. + *" candler.role=control "*" claude doctor "*) cat "$here/doctor.out" ;; + esac ;; *) echo "UNHANDLED: $*" >> "$here/docker.log" @@ -256,6 +260,12 @@ pub fn world() -> World { let fake = bin.join("docker"); fs::write(&fake, FAKE).unwrap(); fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap(); + fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../candler-harness-claude-code/tests/fixtures/doctor/valid.txt"), + bin.join("doctor.out"), + ) + .unwrap(); fs::write(bin.join("docker.log"), "").unwrap(); fs::write(bin.join("handed.log"), "").unwrap(); From c13d2a3a8f1729867c27d65d312597b6bb8da99f Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:00:21 +0900 Subject: [PATCH 58/69] test(api): guard that a workspace instruction text reaches the record The guard asserted that Claude Code refuses instructions.workspace by name, which held at level 1. Level 2 installs the text on both harnesses, so no driver refuses it: the guard now runs a cell that sets it and reads the text back through inspect. Co-Authored-By: Claude Opus 5.5 --- .../tests/it/guard_inspect_mcp_config.rs | 43 ++++++++----------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/crates/candler/tests/it/guard_inspect_mcp_config.rs b/crates/candler/tests/it/guard_inspect_mcp_config.rs index 2240ecc6..993cf543 100644 --- a/crates/candler/tests/it/guard_inspect_mcp_config.rs +++ b/crates/candler/tests/it/guard_inspect_mcp_config.rs @@ -112,28 +112,18 @@ fn a_cell_from_resolve_is_stored_and_hashed_without_snapshots() { ); } -/// Guards: a cell that sets an instruction text is refused by name while a driver answers it -/// `no`, at the key of `[fixed]` that holds it and not as an unknown path; and the run of a cell -/// that sets neither instructions nor hooks shows both members, empty, through `inspect`. +/// Guards: the run of a cell that sets a workspace instruction text is sealed and shows the +/// text through `inspect`, and an unset `hooks` shows as an empty member. /// -/// Oracle: the code and the pointer are written by hand from the surface; the run is made by -/// `candler run`. +/// Oracle: the text is written by hand on the command line; the run is made by `candler run` and +/// read back by `candler inspect`. /// -/// Bite: drop the `instructions` and `hooks` members from what `inspect` shows (the record has -/// no such member); let the driver answer `Mapped` (the run launches). +/// Bite: drop the `instructions` or `hooks` member from what `inspect` shows (the record has no +/// such member); let the Claude Code driver refuse `instructions.workspace` (no run is sealed). #[test] -fn instructions_are_refused_by_name_and_inspect_shows_the_members() { +fn a_workspace_instruction_text_reaches_the_record_and_inspect_shows_it() { let world = world(); - let refused = world.launch_with(&["--set", "instructions.workspace=read the plan"]); - let stderr = String::from_utf8(refused.stderr).unwrap(); - assert!(!refused.status.success(), "the run is refused: {stderr}"); - assert!( - stderr.contains("\"code\":\"experiment.setting_unsupported\"") - && stderr.contains("\"path\":\"/fixed/instructions.workspace\""), - "refused as an unsupported setting, not an unknown path: {stderr}" - ); - - let launched = world.launch(); + let launched = world.launch_with(&["--set", "instructions.workspace=read the plan"]); finish(&world, &launched); world.assert_sealed(1); let runs = world.store().join("runs"); @@ -152,11 +142,14 @@ fn instructions_are_refused_by_name_and_inspect_shows_the_members() { .unwrap(); assert!(out.status.success(), "inspect exits 0: {out:?}"); let record: Value = serde_json::from_slice(&out.stdout).unwrap(); - for member in ["instructions", "hooks"] { - assert_eq!( - record[member], - serde_json::json!({}), - "the record shows the {member} the run was given: {record}" - ); - } + assert_eq!( + record["instructions"], + serde_json::json!({"instructions.workspace": "read the plan"}), + "the record shows the instructions the run was given: {record}" + ); + assert_eq!( + record["hooks"], + serde_json::json!({}), + "the record shows the hooks the run was given: {record}" + ); } From dd9c4213aca831c59a1af259b8ec20c2378ef05b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:06:11 +0900 Subject: [PATCH 59/69] fix(api): refuse only OpenCode check warnings, census path from workdir The OpenCode config check refused on every level=ERROR line, but OpenCode prints environment errors at that level (a watcher that cannot start, a models.dev fetch that fails offline) intermittently, so a valid job could be refused as experiment.harness_rejected_input. Consumer-caused findings are recorded at WARN, so only WARN lines are findings; the drain line is still required. The OpenCode census recorded the workspace instruction file as /work/AGENTS.md; LoadedFile::path is relative to the workspace for a workspace file, as Claude Code records CLAUDE.md. A project file under the workdir is now recorded relative to it. The job-start check pointed at /fixed/instructions, a key no experiment file has; it now points at /fixed/instructions.workspace or .global, the spelling the declaration's own refusals and the collision refusal use. candler-harness now holds AGENT_HOME and AGENT_WORKDIR; the core layout constants, the Claude Code session and the OpenCode driver read them there, and each driver returns its prepare constant as the workspace instruction file instead of repeating the literal. Co-Authored-By: Claude Sonnet 5.5 --- crates/candler-core/src/isolation/layout.rs | 6 +- .../src/jobs/orchestrate/config.rs | 56 +++++++++++++++++-- .../candler-harness-claude-code/src/driver.rs | 2 +- .../src/session.rs | 7 +-- crates/candler-harness-opencode/src/driver.rs | 32 ++++++----- .../tests/it/guard_opencode_driver.rs | 23 ++++---- crates/candler-harness/src/spec.rs | 6 ++ 7 files changed, 93 insertions(+), 39 deletions(-) diff --git a/crates/candler-core/src/isolation/layout.rs b/crates/candler-core/src/isolation/layout.rs index 3bb942f2..4a421b21 100644 --- a/crates/candler-core/src/isolation/layout.rs +++ b/crates/candler-core/src/isolation/layout.rs @@ -5,13 +5,13 @@ use std::path::{Path, PathBuf}; use std::time::Duration; -use candler_harness::spec::StatePath; +use candler_harness::spec::{AGENT_HOME, AGENT_WORKDIR, StatePath}; /// The workspace directory inside the container. -pub const CONTAINER_WORKDIR: &str = "/work"; +pub const CONTAINER_WORKDIR: &str = AGENT_WORKDIR; /// The home directory inside the container. -pub const CONTAINER_HOME: &str = "/home/agent"; +pub const CONTAINER_HOME: &str = AGENT_HOME; /// The variables that place a harness's state under `home` inside the container: one per state /// path, named by the path's variable and valued `/`. A run and a control diff --git a/crates/candler-core/src/jobs/orchestrate/config.rs b/crates/candler-core/src/jobs/orchestrate/config.rs index 519c9809..92aa7e43 100644 --- a/crates/candler-core/src/jobs/orchestrate/config.rs +++ b/crates/candler-core/src/jobs/orchestrate/config.rs @@ -11,6 +11,7 @@ use std::sync::Arc; use candler_harness::agent_config; use candler_harness::driver::{DriverError, Plan}; use candler_harness::spec::{Cell, CheckVerdict, CommandSpec, EnvValue, FileRoot, PreparedFile}; +use candler_schemas::execution::paths; use candler_schemas::primitives::Digest; use candler_schemas::process::ExitStatus; use candler_schemas::refusal::pointer_of; @@ -164,12 +165,13 @@ fn setting_pointer(view: &Cell<'_>, harness: &str) -> String { .is_some() { pointer_of(["fixed", "hooks"]) - } else if agent_config::instructions(view, harness) - .ok() - .flatten() - .is_some() - { - pointer_of(["fixed", "instructions"]) + } else if let Some(found) = agent_config::instructions(view, harness).ok().flatten() { + let key = if found.workspace.is_some() { + paths::INSTRUCTIONS_WORKSPACE + } else { + paths::INSTRUCTIONS_GLOBAL + }; + pointer_of(["fixed", key]) } else { pointer_of(["fixed"]) } @@ -357,3 +359,45 @@ async fn check_group( )), } } + +#[cfg(test)] +mod tests { + use std::str::FromStr as _; + + use candler_schemas::primitives::FieldPath; + use candler_schemas::values::{JsonValue, ResolvedValue}; + use serde_json::{Value, json}; + + use super::*; + + fn resolved(path: &str, value: Value) -> ResolvedValue { + ResolvedValue::recorded( + FieldPath::from_str(path).expect("a field path"), + JsonValue::new(value).expect("a JSON value"), + ) + } + + /// Guards: the job-start check points at the instruction setting the way the declaration's + /// own refusals do, `/fixed/instructions.workspace` and `/fixed/instructions.global`, never + /// at `/fixed/instructions`, which is no key of the file. Oracle: the pointers the declaration + /// refuses with, spelled by hand. Bite: point at `/fixed/instructions`. + #[test] + fn the_instruction_setting_is_pointed_at_as_the_declaration_spells_it() { + let both = [ + resolved("instructions.workspace", json!("be brief")), + resolved("instructions.global", json!({"claude-code": "be kind"})), + ]; + assert_eq!( + setting_pointer(&Cell::new(&both), "claude-code"), + "/fixed/instructions.workspace" + ); + let global = [resolved( + "instructions.global", + json!({"claude-code": "be kind"}), + )]; + assert_eq!( + setting_pointer(&Cell::new(&global), "claude-code"), + "/fixed/instructions.global" + ); + } +} diff --git a/crates/candler-harness-claude-code/src/driver.rs b/crates/candler-harness-claude-code/src/driver.rs index f6314d3c..ec942473 100644 --- a/crates/candler-harness-claude-code/src/driver.rs +++ b/crates/candler-harness-claude-code/src/driver.rs @@ -365,7 +365,7 @@ impl HarnessDriver for ClaudeCodeDriver { } fn workspace_instruction_file(&self) -> &'static str { - "CLAUDE.md" + prepare::WORKSPACE_FILE } fn gateway(&self) -> Option { diff --git a/crates/candler-harness-claude-code/src/session.rs b/crates/candler-harness-claude-code/src/session.rs index 871c7cef..156a8236 100644 --- a/crates/candler-harness-claude-code/src/session.rs +++ b/crates/candler-harness-claude-code/src/session.rs @@ -32,8 +32,9 @@ use std::str::FromStr as _; use candler_harness::driver::DriverError; use candler_harness::spec::{ - CollectSpec, CommandSpec, HookSpec, LoadedFile, LoadedScope, PendingItem, PendingKind, - PendingState, PreparedFile, SessionClose, SessionRecord, SessionSpec, SessionTracker, + AGENT_HOME, CollectSpec, CommandSpec, HookSpec, LoadedFile, LoadedScope, PendingItem, + PendingKind, PendingState, PreparedFile, SessionClose, SessionRecord, SessionSpec, + SessionTracker, }; use candler_schemas::primitives::RelPath; use candler_schemas::raw::StreamName; @@ -41,8 +42,6 @@ use serde_json::{Map, Value, json}; use crate::driver::{Launch, argv, invalid}; -/// The home directory the core gives every agent container. -const AGENT_HOME: &str = "/home/agent"; /// The settings file that installs the hooks, relative to the agent's home. It lies outside /// `.claude/`, which the `user` setting source reads. const SETTINGS: &str = ".candler/settings.json"; diff --git a/crates/candler-harness-opencode/src/driver.rs b/crates/candler-harness-opencode/src/driver.rs index 9d228b2d..5696b380 100644 --- a/crates/candler-harness-opencode/src/driver.rs +++ b/crates/candler-harness-opencode/src/driver.rs @@ -11,10 +11,10 @@ use candler_harness::driver::{DriverError, HarnessDriver, Plan}; use candler_harness::reader::TraceReader; use candler_harness::skills::SkillTree; use candler_harness::spec::{ - Action, AgentSetting, Answer, BaseImage, Cell, CheckVerdict, CollectSpec, CommandSpec, - DriverFact, EnvEntry, GATEWAY_STREAM, GatewayEnv, GatewayRecord, HarnessId, LoadedFile, - LoadedScope, OPENCODE, Observed, Prepared, ProcessExit, StateKind, StatePath, StopSignal, - StopSpec, Workspace, gateway_records, + AGENT_HOME, AGENT_WORKDIR, Action, AgentSetting, Answer, BaseImage, Cell, CheckVerdict, + CollectSpec, CommandSpec, DriverFact, EnvEntry, GATEWAY_STREAM, GatewayEnv, GatewayRecord, + HarnessId, LoadedFile, LoadedScope, OPENCODE, Observed, Prepared, ProcessExit, StateKind, + StatePath, StopSignal, StopSpec, Workspace, gateway_records, }; use candler_schemas::name; use candler_schemas::primitives::{RelPath, plain_arg}; @@ -34,9 +34,6 @@ const GATEWAY_BASE_URL: &str = "CANDLER_GATEWAY_URL"; /// The variable that holds the gateway's token; the configuration refers to it. const GATEWAY_AUTH_TOKEN: &str = "CANDLER_GATEWAY_TOKEN"; -/// The agent's home inside the container, which the state paths are relative to. -const AGENT_HOME: &str = "/home/agent"; - /// The state directories and the database file, relative to the agent's home. const STATE: [(&str, StateKind, &str); 5] = [ ("XDG_DATA_HOME", StateKind::Dir, ".xdg/data"), @@ -83,7 +80,8 @@ fn root_end(sessions: &[Session]) -> Option<&EndedBy> { /// stream `stream`; any other stream lists nothing. A file under the `XDG_CONFIG_HOME` the plan sets /// is the user's own; any other is the workspace's. The census reads `OpenCode`'s `Instructions /// from:` lines, which `OpenCode` does not escape, so a line of that shape inside an instruction -/// text counts too. +/// text counts too. A workspace file is recorded relative to the workspace, a user file by its +/// absolute path. fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { if stream.as_str() != GATEWAY_STREAM { return Vec::new(); @@ -103,6 +101,7 @@ fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { "{AGENT_HOME}/{}/", OpenCodeDriver::state_subpath("XDG_CONFIG_HOME") ); + let workdir = format!("{AGENT_WORKDIR}/"); let mut files: Vec = Vec::new(); for path in context .system @@ -114,6 +113,11 @@ fn loaded(stream: &StreamName, bytes: &[u8]) -> Vec { } else { LoadedScope::Project }; + let path = if matches!(scope, LoadedScope::Project) { + path.strip_prefix(workdir.as_str()).unwrap_or(path) + } else { + path + }; let file = LoadedFile::new(path.to_owned(), scope); // BORROW: .to_owned() gives the file its own path if !path.is_empty() && !files.contains(&file) { files.push(file); @@ -240,7 +244,7 @@ impl HarnessDriver for OpenCodeDriver { how: "the tools the gateway offered the model in its first request", }, DriverFact::ConfigCheck => Answer::Mapped { - construct: "`opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` and `level=ERROR` lines name a rejected `opencode.json` or a plugin that failed to load", + construct: "`opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` lines name a rejected `opencode.json` or a plugin that failed to load", }, DriverFact::UnsetPermissionMode => Answer::Candler { how: "the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode", @@ -288,11 +292,13 @@ impl HarnessDriver for OpenCodeDriver { output: text.into_owned(), }; } + // `OpenCode` logs a rejected `opencode.json` and a plugin that fails at `WARN`, and prints + // environment errors that are not about the consumer's files (a watcher that cannot + // start, a model list that cannot be fetched) at `ERROR`, intermittently; only `WARN` + // lines are findings. let findings: Vec<&str> = text .lines() - .filter(|line| { - line.contains("level=WARN") || (line.contains("level=ERROR") && !is_drain(line)) - }) + .filter(|line| line.contains("level=WARN")) .collect(); if findings.is_empty() { return CheckVerdict::Clean; @@ -307,7 +313,7 @@ impl HarnessDriver for OpenCodeDriver { } fn workspace_instruction_file(&self) -> &'static str { - "AGENTS.md" + prepare::INSTRUCTION_FILE } fn gateway(&self) -> Option { 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 0a185342..22c5ff8a 100644 --- a/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs +++ b/crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs @@ -1739,7 +1739,7 @@ fn opencode_census_names_the_instruction_files_of_the_first_request_with_tools() serde_json::to_value(value.value())?, json!([ {"path": "/home/agent/.xdg/config/opencode/AGENTS.md", "scope": "user"}, - {"path": "/work/AGENTS.md", "scope": "project"}, + {"path": "AGENTS.md", "scope": "project"}, ]) ); let moved = @@ -1748,7 +1748,7 @@ fn opencode_census_names_the_instruction_files_of_the_first_request_with_tools() serde_json::to_value(driver.loaded_instructions(&stream, moved.as_bytes()))?, json!([ {"path": "/home/agent/.xdg/config/opencode/AGENTS.md", "scope": "user"}, - {"path": "/work/.xdg/config/AGENTS.md", "scope": "project"}, + {"path": ".xdg/config/AGENTS.md", "scope": "project"}, ]) ); let other: StreamName = "stdout".parse()?; @@ -1762,13 +1762,13 @@ fn opencode_census_names_the_instruction_files_of_the_first_request_with_tools() } /// Guards: the config check — the start of `opencode run` with a model that does not exist ends at -/// the model, so output with that line is a report; a `level=WARN` line, or a `level=ERROR` line other than the -/// model's, is a rejection whatever the exit status and the `INFO` lines; output without the line (empty, an error, a start +/// the model, so output with that line is a report; a `level=WARN` line is a rejection whatever the exit status and the `INFO` lines, and a `level=ERROR` line (the +/// environment's, such as a watcher that cannot start or a model list that cannot be fetched) is not; output without the line (empty, an error, a start /// that failed before the model) is a rejection carrying that output, so a check that never ran /// never passes. The command keeps the plan's configuration home, moves the data home and the /// database under a throwaway directory, and runs in the workspace. /// Oracle: the recorded outputs of `OpenCode` 2.2.7 in `fixtures/check`. -/// Bite: reject the model's own `ERROR` line, pass another `ERROR` line, accept empty output, or leave the database at the run's. +/// Bite: reject an `ERROR` line, pass a `WARN` line, accept empty output, or leave the database at the run's. #[test] fn opencode_config_check_reads_the_warnings_of_a_start_that_reached_the_model() -> Res<()> { let driver = OpenCodeDriver::new(); @@ -1814,14 +1814,13 @@ fn opencode_config_check_reads_the_warnings_of_a_start_that_reached_the_model() assert_eq!(output.lines().count(), 1, "{output}"); assert!(output.contains("Plugin must export a default definition")); let valid = String::from_utf8(recorded("valid.txt")?)?; - let with_error = format!( - "{valid}timestamp=2026-11-25T08:57:01.050Z level=ERROR run=8c7beda5 message=\"Failed to load config\" role=server\n" + let with_environment_errors = format!( + "{valid}timestamp=2026-11-25T08:57:01.050Z level=ERROR run=8c7beda5 message=\"watcher backend not supported\" directory=/home/agent/.xdg/config/opencode\ntimestamp=2026-11-25T08:57:01.060Z level=ERROR run=8c7beda5 message=\"Failed to fetch models.dev\" cause=EAI_AGAIN\n" + ); + assert_eq!( + driver.read_config_check(with_environment_errors.as_bytes()), + CheckVerdict::Clean ); - let CheckVerdict::Rejected { output } = driver.read_config_check(with_error.as_bytes()) else { - return Err("an ERROR line other than the model's is not rejected".into()); - }; - assert_eq!(output.lines().count(), 1, "{output}"); - assert!(output.contains("Failed to load config")); let no_model = b"timestamp=2026-11-25T08:56:41.603Z level=INFO message=\"cli starting\"\n"; for not_a_report in [&b""[..], b"error: could not reach the server\n", no_model] { assert_eq!( diff --git a/crates/candler-harness/src/spec.rs b/crates/candler-harness/src/spec.rs index 65c31dce..d1b17e87 100644 --- a/crates/candler-harness/src/spec.rs +++ b/crates/candler-harness/src/spec.rs @@ -1128,6 +1128,12 @@ pub enum StateKind { File, } +/// The workspace directory inside the agent's container. +pub const AGENT_WORKDIR: &str = "/work"; + +/// The agent's home directory inside the agent's container. +pub const AGENT_HOME: &str = "/home/agent"; + /// A place a harness keeps state, inside the agent's home: the core creates it, sets `env` to its /// absolute path inside the container, and keeps it per run. #[derive(Debug, Clone, PartialEq, Eq)] From ea9ca0c09e26adbe0137911df12f166d9741c345 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:06:15 +0900 Subject: [PATCH 60/69] docs(api): describe the job-start harness check and the hooks Co-Authored-By: Claude Sonnet 5.5 --- __design__/architecture.md | 30 ++++++++++++++++++++------- docs/contract/harness-capabilities.md | 4 ++-- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/__design__/architecture.md b/__design__/architecture.md index 2fcb3cfa..82baaf04 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -692,7 +692,7 @@ I3, so event times are reproducible even where the harness emits none. ### Traits (signatures only) Every item added for the second harness (`answer`, `fact`, `check_settings`, `gateway`, -`state_paths`, `census_stream`, `session`, `session_tracker`, `classify_end`) has a default body, so a driver +`state_paths`, `census_from_gateway`, `session`, `session_tracker`, `classify_end`) has a default body, so a driver implements only what its harness has. - `HarnessDriver` @@ -731,8 +731,9 @@ implements only what its harness has. which the core calls, defaults to `classify_exit` and lets a harness whose exit status covers several endings read the live reader's last word or the export - `collect(workspace, observed) -> CollectSpec[]`, with - `CollectSpec = File(glob) | Command(CommandSpec, name) | Exec(CommandSpec, name)`. The core - runs `Exec` after the agent exited, in a throwaway container over the run's mounts and state + `CollectSpec = File(glob) | Command(CommandSpec, name) | Exec(CommandSpec, name) | Home(path, name)`. + `Home` archives a file under the agent's home as the stream `name`, read on the host after the + run. The core runs `Exec` after the agent exited, in a throwaway container over the run's mounts and state variables (`candler.role=control`, no network, no gateway name), and archives its stdout as the stream `name` - `TraceReader` @@ -775,6 +776,19 @@ image or resolver is built, and an unknown name is refused (`experiment.unknown_ run as another harness. `comparable.harness.driver` is `None` for live cells. The label `candler.cc_version` on a base image holds the harness version, whatever the harness. +**The job-start harness check.** A driver may name a command that has its harness read the files +Candler installs for a cell (`config_check(plan)`) and a reader of what it printed +(`read_config_check(output) -> Clean | Rejected { output }`). Before the first run, the core groups +the planned cells by everything that command reads (the harness, the image, the home and +workspace files, the command with its cwd and overlay, the container environment and the +treatment), runs it once per group in a container without network, and passes the reader standard +output followed by standard error, whatever the exit status. A check that cannot run (the container +does not start, the command is missing, times out or is ended by a signal, or it prints nothing or +too much) is refused as `jobs.config_check_failed`, an environment fault; a rejection is refused as +`experiment.harness_rejected_input`, naming the files and the setting they come from. Declared +inputs are not mounted in the check, so it judges the files Candler installs for the harness, not +the consumer's inputs, and a clean verdict (`provenance.harness_config_check`) says no more. + **The shared fixture suite.** `candler-harness`, under the feature `conformance`, holds one suite that every driver crate runs over its recorded streams. It checks that gateway names, state paths, actions and written files are well formed (no secret in argv, every `{env:NAME}` a written file @@ -902,10 +916,12 @@ through stdin and stdin stays open, so a notification starts a further turn. has one. A turn that ends with no Stop payload (a turn cap error, an API error) leaves the state unknown, and the session runs to its cap rather than closing. - **Hooks.** The driver installs observation hooks outside the workspace (a settings file in the - agent's home, loaded under `--setting-sources project,local`). The hook command appends the Stop - or SessionEnd payload with the container's clock to a log, prints nothing and always exits 0, so - it never blocks or decides (I9). The log is archived as the raw stream `hooks`, so the session - measures can be re-derived (I3). Hooks are never trusted for the turn end. + agent's home, passed with `--settings`; `user` joins `--setting-sources` when a global + instruction text is set). The hook command appends the payload of `InstructionsLoaded`, `Stop` + or `SessionEnd`, with the container's clock, to a log, in a headless run as in a session, prints + nothing and always exits 0, so it never blocks or decides (I9). The log is archived as the raw + stream `hooks`, so the session measures can be re-derived (I3). Hooks are never trusted for the + turn end. - **Measured, never filtered.** The agent's own stopping is recorded as `measured[]` paths: `session.idle_s`, `session.turns` (turns that ended), `session.yielded_at_ms` (from the runner's preparation of the session to the end of the last turn), `session.pending_at_end` (a list of diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index d91ee589..745792f4 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -59,7 +59,7 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. | execution outside the child | no (tools run in the child process) | tools run in the `serve` child, which the stop interrupts first | | census source | Claude Code's `system/init` event lists the tools | Candler: the tools the gateway offered the model in its first request | | permission mode when none is set | `--permission-mode default` on the command line, which in a headless run denies every tool call that needs approval unless an allow rule or a hook approves it | Candler: the run is under `--auto` and the baseline ruleset {*, *, allow}, so every tool is allowed: OpenCode has no headless ask mode | -| config check | `claude doctor` in the workspace, whose `Invalid settings` section lists a rejected file or a skipped entry | `opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` and `level=ERROR` lines name a rejected `opencode.json` or a plugin that failed to load | +| config check | `claude doctor` in the workspace, whose `Invalid settings` section lists a rejected file or a skipped entry | `opencode run --standalone --print-logs -m probe/none x` in the workspace, whose `level=WARN` lines name a rejected `opencode.json` or a plugin that failed to load | ## Refusals @@ -76,6 +76,6 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. - `no (…)` is a refusal: `experiment.session_refused` while resolving, `experiment.setting_unsupported` once the cells are planned, before a job starts. [checked: v@0.15.0] - In session mode Candler counts turns and ends the run past `budget.per_run.turns`. [checked: v@0.7.0] - A driver's answers for each `AgentSetting` decide which modes, effort levels and tool names it maps or refuses. [checked: v@0.7.0] -- Every Claude Code cell runs three observer hooks, headless too, archives their log as stream `hooks`, and gets one `claude doctor` check per distinct (image, prepared files). [checked: v@0.16.0] +- Every Claude Code cell runs three hooks, headless too, logs them to stream `hooks`, and gets one `claude doctor` check per distinct (image, files, command, environment, treatment). [checked: v@0.16.0] - `census.instructions` is read from the hook log in the agent's home, which the agent can change; the trace's `context_start` shows what reached the model. [checked: v@0.16.0] - A plain OpenCode cell gets no instruction file or plugin; `census.instructions` is the gateway's record of the first request offering tools. [checked: v@0.16.0] From 42dc2652c79f0abc2a4e603a4c4fc101f95efb8b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:15:12 +0900 Subject: [PATCH 61/69] test(api): expect the OpenCode workspace file relative in the census The seam fix records OpenCode's workspace instruction file relative to the workspace, as LoadedFile documents and Claude Code already does. The core census guard still pinned the absolute /work/AGENTS.md. Co-Authored-By: Claude Opus 5.5 --- crates/candler-core/tests/it/guard_census_gateway.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/candler-core/tests/it/guard_census_gateway.rs b/crates/candler-core/tests/it/guard_census_gateway.rs index 19dcc82e..2b336991 100644 --- a/crates/candler-core/tests/it/guard_census_gateway.rs +++ b/crates/candler-core/tests/it/guard_census_gateway.rs @@ -202,7 +202,8 @@ fn log_of_recorded_stream() -> String { /// `census.instructions`, the `Instructions from:` blocks of the system text of the first request /// that offered tools, which the core hands to the driver from the stored gateway stream. /// Oracle: the system text of a recorded `OpenCode` 2.2.7 request (`fixtures/gateway` of -/// `candler-harness-opencode`), and the two paths written by hand. +/// `candler-harness-opencode`), and the two paths written by hand: the user file absolute, the +/// workspace file relative to the workspace, as `LoadedFile` documents. /// Bite: leave the gateway stream out of the streams the driver reads, or read the title request. #[test] fn census_gateway_run_records_the_instruction_files_of_the_first_request_with_tools() { @@ -213,7 +214,7 @@ fn census_gateway_run_records_the_instruction_files_of_the_first_request_with_to ran.measured("census.instructions"), Some(json!([ {"path": "/home/agent/.xdg/config/opencode/AGENTS.md", "scope": "user"}, - {"path": "/work/AGENTS.md", "scope": "project"}, + {"path": "AGENTS.md", "scope": "project"}, ])) ); } From 5ef252197e64fc30204bfa1800e602284b2a6e42 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:15:12 +0900 Subject: [PATCH 62/69] reports(api): file what M6.5 level 2 found outside its leaves Round 05: ten observations from the level 2 leaves and the seam review, and three process lessons (whole-suite gates, check rules from recorded output, build slots shared between worktrees). The README gains the round and the level 2 status. Co-Authored-By: Claude Opus 5.5 --- .../05-observation_level2_out_of_scope_v0.md | 134 ++++++++++++++++++ __reports__/agent_config/README.md | 9 +- 2 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 __reports__/agent_config/05-observation_level2_out_of_scope_v0.md diff --git a/__reports__/agent_config/05-observation_level2_out_of_scope_v0.md b/__reports__/agent_config/05-observation_level2_out_of_scope_v0.md new file mode 100644 index 00000000..bce3644d --- /dev/null +++ b/__reports__/agent_config/05-observation_level2_out_of_scope_v0.md @@ -0,0 +1,134 @@ +# Level 2 of M6.5: what was found outside its scope (v0) + +Date: 2026-11-25 + +Ten findings from M6.5's level 2 leaves (`install_claude_code`, `install_opencode`, `preflight_check`), from their reviews and verifiers, and from the seam review of the merged level. Each one lies outside the leaf that found it, or was judged not worth the leaf's fix round, so no leaf fixed it. Each section below is one observation, written so that a fresh agent can pick it up cold. + +--- +type: observation +topic: agent_config +spotted-during: implementing, reviewing and merging the M6.5 level 2 leaves, and the level 2 seam review +date: 2026-11-25 +domain: code +confidence: confirmed (O1–O5, O7–O10); plausible (O6) +urgency: per item, below +deferred-because: each lies outside the topic of the leaf that met it, or costs more than the defect it removes at this stage +--- + +## Summary + +| # | Observation | Urgency | Where | +|---|---|---|---| +| O1 | An ignored OpenCode guard has been broken on main since 8d88cb50 | medium | `guard_opencode_driver::opencode_real_binary_is_interrupted_by_the_stop_script` | +| O2 | The host's read of the hook log refuses a link only at the last path component | low | `read_home_log` | +| O3 | A symlinked `.claude` in a task checkout redirects the hook-file writes | low | Claude Code `prepare` | +| O4 | A harness-check refusal points at the setting that is present, not at its cause | low | `setting_pointer` | +| O5 | Output that is not a check report is an experiment refusal, not a check that could not run | low | both `read_config_check` | +| O6 | The check grouping key splits more than the verdict needs | low (cost) | `group_key`, `files_digest` | +| O7 | The collision targets are derived twice | low (debt) | CLI `declared.targets`, supervisor `spec.inputs` | +| O8 | The job-start check takes no cancel signal, and paths are compared without Unicode normalisation | low | `check_config`, `refuse_instruction_collision` | +| O9 | OpenCode's census reads `Instructions from:` lines that OpenCode does not escape | low | OpenCode `loaded` | +| O10 | A second timing guard fails under load | low | `guard_container_record::stopped_run_has_its_agent_recorded_before_the_hook_sweeps` | + +Two lessons from the level are process, not code, and are in the [last section](#process-lessons). + +## O1. An ignored OpenCode guard has been broken on main since 8d88cb50 + +**What was noticed.** `opencode_real_binary_is_interrupted_by_the_stop_script` (`#[ignore]`, needs `CANDLER_OPENCODE_IMAGE`) takes `driver.collect(..).first()` as the export `Exec` spec. Since 8d88cb50 (`fix(adapter-opencode): collect the files an OpenCode run wrote`, on `origin/main`) the first spec is the `**/*` file spec, so the guard fails with `no collect` before Docker starts. Without the variable it fails with `NotPresent`. CI skips it because it is ignored, so nobody sees it fail. + +**Location map.** `crates/candler-harness-opencode/tests/it/guard_opencode_driver.rs` (the guard); `crates/candler-harness-opencode/src/driver.rs` (`collect`). + +**Hand-off questions.** Is the guard run anywhere, by hand or by a release checklist? Working theory: find the `Exec` spec among the specs instead of taking the first. + +**Scope boundary.** Do not change what `collect` returns. + +## O2. The host's read of the hook log refuses a link only at the last component + +**What was noticed.** `read_home_log` opens `hooks.jsonl` with `O_NOFOLLOW`, regular files only, capped at 4 MiB. A link that the agent makes at `~/.candler` itself still resolves on the host, so a host file named `hooks.jsonl` under the link's target could be archived. This is host-side safety. It is not the agent editing its own home, which is allowed by design. + +**Location map.** `crates/candler-core/src/runner/exec/` (`read_home_log`, `collect_home`). + +**Hand-off questions.** Working theory: open each component with `openat` + `O_NOFOLLOW` from the home's descriptor (rustix), or check that the parent is a real directory owned by the run. + +**Scope boundary.** Do not change where the hook log is written. + +## O3. A symlinked `.claude` in a task checkout redirects the hook-file writes + +**What was noticed.** `create_dir_all` and `create_new` follow a symlinked parent that already exists in the workspace. A task repository that ships `.claude` as a link sends the consumer's hook files through it. No payload can reach this; only a task checkout can. + +**Location map.** `crates/candler-harness-claude-code/src/prepare.rs`; the core's staging of prepared files. + +**Hand-off questions.** Should staging refuse a prepared path whose parent is a link, as `read_home_log` does for the log? + +## O4. A harness-check refusal points at the setting that is present, not at its cause + +**What was noticed.** `setting_pointer` chooses `/fixed/hooks`, `/fixed/instructions.workspace`, `/fixed/instructions.global` or `/fixed` by which values the cell sets. It does not look at what the harness rejected. Two consequences: +- A cell that also sets hooks, and whose `opencode.json` is rejected because of `mcp` or `tools.*`, is pointed at `/fixed/hooks`. +- A value set by a factor or an arm is pointed at `[fixed]`, which does not hold it. The pages in `docs/contract/driver-traits.md` promise "or the factor that sets it". + +The level 2 seam fix unified the spelling, so the pointer is now always a key of the file. It did not change how the pointer is chosen. + +**Location map.** `crates/candler-core/src/jobs/orchestrate/config.rs` (`setting_pointer`); `crates/candler-core/src/runner/plan.rs` (`refuse_instruction_collision`); `docs/contract/driver-traits.md` (Notes). + +**Hand-off questions.** Can the cell's resolution say which level set a value? Or should the contract promise only the cell? + +## O5. Output that is not a check report is refused as an experiment error + +**What was noticed.** Some check output is non-empty but is not a report: a crash trace, a start that failed before the model, or a `claude doctor` whose first line changed in a new version. Both readers return `Rejected`, so the cell is refused as `experiment.harness_rejected_input` and the experiment is blamed. Only empty or truncated output, exit 124–127 and a signal are `jobs.config_check_failed`. + +**Location map.** `read_config_check` in both driver crates; `CheckVerdict` in `crates/candler-harness/src/driver.rs`. + +**Hand-off questions.** Should `CheckVerdict` gain a third value, `Unreadable`, that maps to `jobs.config_check_failed`? + +**Scope boundary.** The verdict shape is a trait change, so both drivers and the conformance suite move together. + +## O6. The check grouping key splits more than the verdict needs + +**What was noticed.** +- The key hashes the whole `.claude/settings.json` and `opencode.json`. A sweep over N models or effort levels therefore runs N checks that are identical in effect. +- Skills are keyed by treatment ref rather than by the staged skill digests, which `stage_container` discards. Two refs that hold one tree are checked twice. +- Every distinct cell is fully staged, including a `git archive` for skills, before groups are merged. + +Each costs time, never correctness. + +**Location map.** `crates/candler-core/src/jobs/orchestrate/config.rs` (`group_key`, `files_digest`, `grouped`); `servers.rs` (`stage_container`). + +**Hand-off questions.** What does a 20-cell sweep spend on checks today? + +## O7. The collision targets are derived twice + +**What was noticed.** `refuse_instruction_collision` is fed the agent inputs in two ways: the CLI passes `declared.targets` (`experiment/inputs.rs`), where the key is the input kind, and the supervisor passes `spec.inputs` (`input_targets`), where the key is the path. Today both give the same set. + +**Location map.** `crates/candler-core/src/runner/plan.rs` (`PlanCtx.input_targets`); `crates/candler-core/src/experiment/inputs.rs`; `crates/candler-core/src/jobs/orchestrate/mod.rs`. + +## O8. No cancel signal reaches the check, and paths are compared without Unicode normalisation + +**What was noticed.** +- `check_config` takes no cancel watch, as `check_servers` does not either. A job cancelled during a check waits for the check's timeout. +- The collision check case-folds and strips `./`, but does not apply NFC. The workspace has no normalisation crate. + +**Location map.** `crates/candler-core/src/jobs/orchestrate/{config,servers}.rs`; `crates/candler-core/src/runner/plan.rs`. + +## O9. OpenCode's census reads lines that OpenCode does not escape + +**What was noticed.** OpenCode's census lists the files from the `Instructions from: ` lines of the first request's system text. OpenCode does not escape them, so an instruction text that holds such a line adds an entry. The text comes from the consumer, not from the agent. The `loaded_instructions` doc comment states this. + +**Location map.** `crates/candler-harness-opencode/src/driver.rs` (`loaded`). + +**Hand-off questions.** Is the census meant as a proof, or only as a diagnostic? The proof is `context_start`, read from the trace. + +## O10. A second timing guard fails under load + +**What was noticed.** `stopped_run_has_its_agent_recorded_before_the_hook_sweeps` failed once in a full `cargo nextest run --workspace` on 04b6456b ("the record did not appear while the run was live"). It passed alone, and in the next full run. This is the same family as round 04's O6 (`guard_container_stop`). + +**Location map.** `crates/candler-core/tests/it/guard_container_record.rs:691`. + +## Process lessons + +- **A leaf's gate must run the whole workspace suite.** The `preflight_check` fix round ran `candler-core` and `contract_pages` only, and the `install_claude_code` fix round ran a filtered `candler-core`. Together they left 33 tests red on the milestone branch: + - the test fakes of the CLI and the core did not answer the new job-start check; + - a level 1 guard still expected Claude Code to refuse `instructions.workspace`. + + The coordinator's full run after the third merge found them, and `fix/m6.5-check-fakes` fixed them (merge 3f19823e). The seam fix (merge 481e5301) then missed one more: `guard_census_gateway` still expected the absolute `/work/AGENTS.md` that the fix made relative. The coordinator's full run after that merge found it. Level 3 and 4 briefs name `cargo nextest run --workspace` as a gate. +- **A build directory shared between worktrees can run another checkout's tests.** Cargo keys a workspace member by its path relative to the workspace, so a slot that several worktrees use reuses a test binary whose `env!("CARGO_MANIFEST_DIR")` names the worktree that built it. Once that worktree was deleted, `committed_schema_files_hold_no_pattern_that_depends_on_the_regex_engine` failed with `NotFound`. It passed after `candler-schemas` was rebuilt in place. Whoever deletes a worktree also rebuilds, or deletes, the slots it used. +- **A rule added from a reading, not a measurement, refused valid cells.** The `install_opencode` fix round was asked to refuse OpenCode's `level=ERROR` lines. The seam review then ran the real image and saw environment errors at ERROR in 7 of about 13 starts (`watcher backend not supported`, `Failed to fetch models.dev`). The probe had recorded both consumer failures at WARN. The seam fix (merge 481e5301) returned the rule to WARN only. A check reader's rules come from recorded output. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 62ca6f2c..e758ab19 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -19,7 +19,10 @@ Instruction files and hooks as per-arm experiment data (M6.5). - [03-findings_probe_harness_checks_v0.md](03-findings_probe_harness_checks_v0.md) — **latest**. The level-1 probe, measured in the real images: the check command for each harness, where Claude Code's global file loads, the order and place (system or first message) in which instructions and session-start hooks reach the model. Two points amend v2's proof wording. ### Round 04 -- [04-observation_level1_out_of_scope_v0.md](04-observation_level1_out_of_scope_v0.md) — **latest**. Eight findings from level 1 that lie outside its leaves: the 4 MiB gateway log read, an unlocked image build, a commit that does not build alone, OpenCode's silence on unknown keys, `mcp.servers` names, a timing guard, an unused image, a child not identified for signalling. +- [04-observation_level1_out_of_scope_v0.md](04-observation_level1_out_of_scope_v0.md) — **latest** for level 1. Eight findings from level 1 that lie outside its leaves: the 4 MiB gateway log read, an unlocked image build, a commit that does not build alone, OpenCode's silence on unknown keys, `mcp.servers` names, a timing guard, an unused image, a child not identified for signalling. + +### Round 05 +- [05-observation_level2_out_of_scope_v0.md](05-observation_level2_out_of_scope_v0.md) — **latest** for level 2. Ten findings from level 2 and its seam review that lie outside its leaves: a broken ignored OpenCode guard on main, two link-following paths, refusal pointers chosen by presence, non-report check output blamed on the experiment, check groups that split too finely, collision targets derived twice, no cancel signal or Unicode normalisation, an unescaped census source, a second timing guard. Also two process lessons: whole-suite gates, and check rules taken from recorded output. ## Status @@ -35,4 +38,8 @@ On 2026-11-25 level 2 found that a resolve step cannot reach a cell's plan, whic On 2026-11-25 the M6.5 and M6d (run context) leads agreed how the two trace changes meet. Whichever lands second takes the other in, regenerates the schema and the trace page instead of merging them by hand, bumps no version by hand, and writes the `needs.trace` sentence about `context_start`. The leaf `meet_run_context` (L4) holds this for the case where M6.5 lands second. M6.5 takes `origin/main` in by a merge, since its history is not rewritten. +Level 2 is done and merged locally on 2026-11-25: `install_claude_code`, `install_opencode` and `preflight_check`. A full workspace run after the third merge found 33 tests red, which no leaf's gate had run: the test fakes did not answer the new job-start check, and a level 1 guard expected the old refusal. A fix branch made them green. The seam review of the level then found that the OpenCode check refused valid cells on environment errors, and that OpenCode recorded the workspace file as an absolute path. Both are fixed, with the stale design prose. The rest is in round 05. Level 3 and 4 gates name the whole workspace suite. + +Spend after level 2 is $95.92 of the $125 cap: planning and level 1 $55.40, level 2 about $40.50. + No decision is open. From c40449d9ed301fe92d264363ee82534f1a8f39c5 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 19:47:05 +0900 Subject: [PATCH 63/69] test(cli): prove instructions and hooks on both harnesses Two Docker guards run the real candler on real Claude Code and OpenCode against the scripted fake model. guard_agent_config_e2e reads, per run, the inspect record, the stored context_start, the census and the sealed outputs for instructions and hooks (blocking and session-start). guard_harness_check_refuses starts jobs on real images and reads the refusal of an invalid payload and the pass of a valid one. The fake model gains the script h1 (one shell call). The parity e2e's fake-model start and job run are shared instead of copied. Co-Authored-By: Claude Sonnet 5.5 --- assets/docker/fakemodel/fakemodel.py | 11 + crates/candler/tests/it/guard_cli_e2e.rs | 5 + .../it/guard_cli_e2e/agent_config_e2e.rs | 498 ++++++++++++++++++ .../tests/it/guard_cli_e2e/parity_e2e.rs | 227 ++++---- 4 files changed, 646 insertions(+), 95 deletions(-) create mode 100644 crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs diff --git a/assets/docker/fakemodel/fakemodel.py b/assets/docker/fakemodel/fakemodel.py index d238ac8a..fb4b1e8c 100644 --- a/assets/docker/fakemodel/fakemodel.py +++ b/assets/docker/fakemodel/fakemodel.py @@ -31,6 +31,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. + 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 + is answered with text. c3 must be slow. Every request is answered "hello" after FAKE_DELAY_SECS seconds, so that a run is live and its agent is mid-turn for that long. @@ -138,6 +142,13 @@ def script_blocks(model, state, tools, messages): if state == "tool_result" and last_tool_result(messages) == "toolu_fake_search": return [stamp_call(PARITY_TOOLS[0])], "tool_use", "p1-call" return [{"type": "text", "text": "done"}], "end_turn", "p1-text" + if model.startswith("h1"): + shell = [name for name in tools if name in ("Bash", "bash", "shell")] + if state == "prompt" and shell: + call = {"type": "tool_use", "id": "toolu_fake_hook", "name": shell[0], + "input": {"command": "echo hook-not-blocked", "description": "Echo"}} + return [{"type": "text", "text": "I will run a command."}, call], "tool_use", "h1-call" + return [{"type": "text", "text": "done"}], "end_turn", "h1-text" if model.startswith("c2"): return [{"type": "text", "text": "hello"}], "end_turn", "c2-hello" if model.startswith("c3"): diff --git a/crates/candler/tests/it/guard_cli_e2e.rs b/crates/candler/tests/it/guard_cli_e2e.rs index 2dbe59de..8c7f67f8 100644 --- a/crates/candler/tests/it/guard_cli_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e.rs @@ -810,3 +810,8 @@ mod i8_e2e; /// Both harnesses install and trace one declared MCP server the same way. #[path = "guard_cli_e2e/parity_e2e.rs"] mod parity_e2e; + +/// 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"] +mod agent_config_e2e; 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 new file mode 100644 index 00000000..864de49b --- /dev/null +++ b/crates/candler/tests/it/guard_cli_e2e/agent_config_e2e.rs @@ -0,0 +1,498 @@ +//! Instructions and hooks on both real harnesses, read from what a consumer reads. +//! +//! The runs are the product's own: real Claude Code and real OpenCode, each in its agent base +//! image, behind the production gateway sidecar, against the scripted fake model +//! (`assets/docker/fakemodel`, model `h1`, which calls the shell tool once). One experiment file +//! is written once, with a global text per harness, two arms (workspace text A or B), one +//! session-start hook and one blocking hook per harness; the line `[harness]` names is the only +//! thing that differs between the two jobs. What is read is `candler inspect`'s record, the stored +//! trace's `context_start`, and the files the run sealed, never the fake model's own notes, except +//! the answer it was given to its one tool call. +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Instant; + +use serde_json::Value; + +use super::i8_e2e::{Made, must}; +use super::parity_e2e::{Fake, Ran, TOKEN, answers_to, records, run_job, start_fake}; +use super::real_docker; +use crate::support::cli_run::world; + +/// The call the fake model's script `h1` makes, and the text the shell prints when it runs. +const CALL_ID: &str = "toolu_fake_hook"; +const NOT_BLOCKED: &str = "hook-not-blocked"; + +/// The text each harness's global instruction file holds, and the two workspace texts of the arms. +const GLOBAL_CC: &str = "GLOBAL_TEXT_CC_71a3"; +const GLOBAL_OC: &str = "GLOBAL_TEXT_OC_71a3"; +const ARMS: [&str; 2] = ["WORKSPACE_TEXT_A_5be2", "WORKSPACE_TEXT_B_5be2"]; + +/// What the session-start hook of each harness adds, and what the blocking hook answers with. +const START_CC: &str = "SESSION_START_MARKER_CC_c40d"; +const START_OC: &str = "SESSION_START_MARKER_OC_c40d"; +const BLOCKED: &str = "BLOCKED_BY_HOOK_9d4f"; + +/// The hooks and global texts of the experiment, for both harnesses. The Claude Code blocking +/// script exits 2 with the marker on stderr; the `OpenCode` plugin throws the marker in +/// `tool.execute.before` and adds its start marker to the system text in `session` `context`. +fn agent_config() -> String { + format!( + r#" +[fixed.instructions.global] +claude-code = "{GLOBAL_CC}" +opencode = "{GLOBAL_OC}" + +[fixed.hooks.claude-code.settings] +SessionStart = [{{ hooks = [{{ type = "command", command = "echo {START_CC}" }}] }}] +PreToolUse = [{{ matcher = "Bash", hooks = [{{ type = "command", command = "sh .claude/hooks/block.sh" }}] }}] + +[fixed.hooks.claude-code.files] +"block.sh" = "echo {BLOCKED} >&2\nexit 2\n" + +[fixed.hooks.opencode.plugins] +"guard.ts" = ''' +export default {{ + id: "guard", + setup(api) {{ + api.session.hook("context", (event) => {{ + event.system.push({{ type: "text", text: "{START_OC}" }}); + }}); + api.tool.hook("execute.before", (event) => {{ + if (/shell|bash/i.test(String(event.tool))) throw new Error("{BLOCKED}"); + }}); + }}, +}}; +''' + +[[factors]] +path = "instructions.workspace" +levels = ["{}", "{}"] +"#, + ARMS[0], ARMS[1] + ) +} + +/// The experiment of one cell shape: the world's own file made to run the shell script `h1` with +/// nothing else asked of it, the harness a placeholder, and `extra` appended. +fn base(extra: &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\"", "\"h1\"") + .replace("say hello", "Run one shell command, then reply done.") + .replace("wall_s = 30", "wall_s = 300") + .replacen( + "[harness]\nname = \"claude-code\"", + "[harness]\nname = \"@HARNESS@\"", + 1, + ) + + extra +} + +/// What one sealed run stored. +struct Seen { + /// `candler inspect`'s record of the run. + record: Value, + /// The `system` and `first_message` of the trace's first `context_start`. + system: String, + first_message: String, + /// The files the run collected as outputs, as paths relative to the run's `outputs`. + outputs: Vec, + /// The run's seal, as written. + seal: String, +} + +/// The first event of `kind` among the lines of the trace `text`. +fn first_event(text: &str, kind: &str) -> Option { + fn walk(value: &Value, kind: &str) -> Option { + match value { + Value::Object(map) => { + if map.get("kind") == Some(&Value::from(kind)) { + return Some(value.clone()); // BORROW: .clone() copies the event + } + map.values().find_map(|inner| walk(inner, kind)) + } + Value::Array(items) => items.iter().find_map(|inner| walk(inner, kind)), + Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => None, + } + } + text.lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .find_map(|value| walk(&value, kind)) +} + +/// A JSON member as the text a consumer reads: a string as it is, anything else as its JSON. +fn shown(value: &Value) -> String { + value + .as_str() + .map_or_else(|| value.to_string(), str::to_owned) // BORROW: .to_owned() makes the owned text +} + +/// The files below `dir`, relative to it. +fn files_below(dir: &Path) -> Vec { + crate::support::seam::entries_under(dir) + .into_iter() + .filter(|path| path.is_file()) + .filter_map(|path| Some(path.strip_prefix(dir).ok()?.display().to_string())) + .collect() +} + +/// Every sealed run of the job in `ran`, read as a consumer reads it. +fn sealed_runs(ran: &Ran) -> Vec { + let mut dirs: Vec = fs::read_dir(ran.store.join("runs")) + .into_iter() + .flatten() + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.join("run.done").is_file()) + .collect(); + dirs.sort(); + dirs.iter() + .map(|run_dir| { + let inspected = Command::new(env!("CARGO_BIN_EXE_candler")) + .arg("inspect") + .arg(run_dir) + .current_dir(&ran.world.work) + .env_remove("CANDLER_STORE") + .env("XDG_STATE_HOME", &ran.world.state) + .output() + .unwrap(); + assert!(inspected.status.success(), "inspect exits 0: {inspected:?}"); + let trace = fs::read_to_string(run_dir.join("trace.jsonl")).unwrap_or_default(); + let start = first_event(&trace, "context_start") + .unwrap_or_else(|| panic!("a context_start in the trace of {run_dir:?}:\n{trace}")); + Seen { + record: serde_json::from_slice(&inspected.stdout).unwrap(), + system: shown(&start["system"]), + first_message: shown(&start["first_message"]), + outputs: files_below(&run_dir.join("outputs")), + seal: fs::read_to_string(run_dir.join("run.done")).unwrap_or_default(), + } + }) + .collect() +} + +/// The workspace text a run's record shows it was given. +fn arm_of(seen: &Seen) -> String { + shown(&seen.record["instructions"]["instructions.workspace"]) +} + +/// `candler resolve` of the experiment at `world`, which must succeed. Its preflight reads the +/// model list of the endpoint from the host, which the fake model's TLS name and certificate do +/// not allow, so the endpoint is a plain local listener that answers the one read. +fn resolve(world: &crate::support::cli_run::World, config: &Path) -> String { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + let answering = std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let mut request = [0_u8; 1024]; + drop(std::io::Read::read(&mut stream, &mut request)); + drop(std::io::Write::write_all( + &mut stream, + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}", + )); + } + }); + let resolved = Command::new(env!("CARGO_BIN_EXE_candler")) + .arg("resolve") + .arg(&world.experiment) + .args([ + "--set", + "isolation.build.lock=env.lock", + "--set", + "model.token_secret=FIXTURE_TOKEN", + "--set", + ]) + .arg(format!("model.endpoint={endpoint}")) + .env("FIXTURE_TOKEN", TOKEN) + .current_dir(&world.work) + .env_remove("CANDLER_STORE") + .env("XDG_STATE_HOME", &world.state) + .env("XDG_CONFIG_HOME", config) + .output() + .unwrap(); + drop(answering.join()); + assert!(resolved.status.success(), "resolve exits 0: {resolved:?}"); + String::from_utf8_lossy(&resolved.stdout).into_owned() +} + +/// The instruction files of the census a run recorded, as `(path, scope)`. +fn census(seen: &Seen) -> Vec<(String, String)> { + seen.record["measured"]["census.instructions"] + .as_array() + .into_iter() + .flatten() + .map(|entry| (shown(&entry["path"]), shown(&entry["scope"]))) + .collect() +} + +/// Asserts that nothing the jobs `jobs` and the fake model `fake` started is left in Docker: no +/// container of a job, no network of a job and not the fake model. Containers of a guard that runs +/// beside this one are not looked at. +fn assert_nothing_left(real: &Path, jobs: &[String], fake: &str) { + for job in jobs { + let filter = format!("label=candler.job={job}"); + assert_eq!( + must(real, &["ps", "-aq", "--filter", &filter]), + "", + "no container of job {job} is left behind" + ); + assert_eq!( + must(real, &["network", "ls", "-q", "--filter", &filter]), + "", + "no network of job {job} is left behind" + ); + } + assert_eq!( + must(real, &["ps", "-aq", "--filter", &format!("id={fake}")]), + "", + "the fake model is removed" + ); +} + +/// Guards: README (instructions and hooks a cell sets reach the agent on every harness, and what +/// reached it is in the trace) -- one experiment, run with the real `candler run` on Claude Code +/// and on `OpenCode`, two arms each, shows on every run: `resolve` succeeds and the record shows +/// the arm's instructions and the hooks (G1); the `context_start` holds the global text and the +/// arm's workspace text and not the other arm's (G4); the blocking hook's marker answers the +/// shell call as an error (G5); the census lists the global and the workspace file with their +/// scopes (G7); no installed file is among the collected outputs and no run is sealed +/// `input_leak` (G9); the session-start marker is in the first message on Claude Code and in the +/// system text on `OpenCode` (G11). +/// +/// Oracle: the texts the experiment fixes, and where the probe measured each to land +/// (`__reports__/agent_config/03-findings_probe_harness_checks_v0.md`). +/// +/// Bite: a driver that installs nothing (no text in `context_start`), the workspace file of one +/// arm shown to the other, a hook that is not installed (the shell call succeeds), an installed +/// file collected as an output, or the first request that offers no tools recorded as the start. +#[test] +#[ignore = "needs Docker; run with --run-ignored only"] +fn guard_agent_config_e2e() { + let started = Instant::now(); + 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 text = base(&agent_config()); + let mut failures = Vec::new(); + let mut jobs = Vec::new(); + // each harness: its global text, where its start marker lands, and its two instruction files + for (harness, global, marker, user_file, project_file) in [ + ( + "claude-code", + GLOBAL_CC, + START_CC, + ".claude/CLAUDE.md", + "CLAUDE.md", + ), + ( + "opencode", + GLOBAL_OC, + START_OC, + "opencode/AGENTS.md", + "AGENTS.md", + ), + ] { + 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 + let config = ran.world.root.join("config"); + let resolved = resolve(&ran.world, &config); + if ![global, START_CC, START_OC, BLOCKED] + .iter() + .all(|shown| resolved.contains(shown)) + { + failures.push(format!( + "{harness}: resolve shows no instructions or hooks: {resolved}" + )); + } + let seen = sealed_runs(&ran); + if seen.len() != 2 { + failures.push(format!( + "{harness}: {} sealed runs, expected 2\n{}", + seen.len(), + ran.log + )); + } + for run in &seen { + let arm = arm_of(run); + let other = ARMS.iter().find(|candidate| **candidate != arm); + if !ARMS.contains(&arm.as_str()) { + failures.push(format!("{harness}: no arm in the record: {}", run.record)); + continue; + } + // G1: the record shows the instructions and the hooks of the arm + let instructions = run.record["instructions"].to_string(); + let hooks = run.record["hooks"].to_string(); + if !instructions.contains(global) { + failures.push(format!( + "{harness}/{arm}: record instructions {instructions}" + )); + } + if !hooks.contains(BLOCKED) { + failures.push(format!("{harness}/{arm}: record hooks {hooks}")); + } + // G4: the trace holds the global text and the arm's text, and not the other arm's + let reached = format!("{}\n{}", run.system, run.first_message); + for want in [global, arm.as_str()] { + if !reached.contains(want) { + failures.push(format!("{harness}/{arm}: context_start lacks {want}")); + } + } + if other.is_some_and(|other| reached.contains(other)) { + failures.push(format!( + "{harness}/{arm}: context_start holds the other arm" + )); + } + // G11: the start marker is in the system text on both harnesses. The probe measured + // Claude Code's in the first message; Claude Code 2.1.311 writes it as a + // `SessionStart:startup hook success:` line of the system text. + let (inside, outside) = (&run.system, &run.first_message); + if !inside.contains(marker) || outside.contains(marker) { + failures.push(format!( + "{harness}/{arm}: start marker not only in its place (in {}, out {})", + inside.contains(marker), + outside.contains(marker) + )); + } + // G7: the census lists both files with their scope + // (Claude Code's census is read from its hook log, in the order the files arrived.) + let mut listed = census(run); + listed.sort_by(|a, b| a.1.cmp(&b.1)); + let fits = matches!( + listed.as_slice(), + [(project, scope_project), (user, scope_user)] + if user.starts_with('/') && user.ends_with(user_file) && scope_user == "user" + && project == project_file && scope_project == "project" + ); + if !fits { + failures.push(format!("{harness}/{arm}: census {listed:?}")); + } + // G9: no installed file among the outputs, no run sealed `input_leak` + let installed = [ + "CLAUDE.md", + "AGENTS.md", + "settings.json", + "block.sh", + "guard.ts", + ]; + if let Some(leak) = run.outputs.iter().find(|path| { + installed.iter().any(|name| { + Path::new(path) + .file_name() + .is_some_and(|found| found.to_string_lossy() == *name) + }) + }) { + failures.push(format!("{harness}/{arm}: collected output {leak}")); + } + if run.seal.contains("input_leak") || run.record.to_string().contains("input_leak") { + failures.push(format!("{harness}/{arm}: sealed input_leak: {}", run.seal)); + } + } + // G5: the shell call is answered with an error carrying the marker, never its output + let answers = answers_to(&records(&real, &model.container), skip, CALL_ID); + let blocked = |(error, text): &(bool, String)| *error && text.contains(BLOCKED); + if answers.len() != 2 + || !answers.iter().all(blocked) + || answers.iter().any(|(_, text)| text.contains(NOT_BLOCKED)) + { + failures.push(format!("{harness}: the shell call's answers: {answers:?}")); + } + } + let fake = model.container.clone(); // BORROW: the check names the fake after the cleanup + drop(made); + assert_nothing_left(&real, &jobs, &fake); + eprintln!("agent_config: {:?} wall", started.elapsed()); + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// One harness's payload for `[fixed.hooks]`: an invalid one, the text the harness's own output +/// quotes for it, and a valid one. +struct Payload { + harness: &'static str, + invalid: &'static str, + quoted: &'static str, + valid: &'static str, +} + +const PAYLOADS: [Payload; 2] = [ + Payload { + harness: "claude-code", + invalid: "\n[fixed.hooks.claude-code.settings]\nNoSuchEvent = [{ hooks = [{ type = \"command\", command = \"true\" }] }]\n", + quoted: "Invalid settings", + valid: "\n[fixed.hooks.claude-code.settings]\nSessionStart = [{ hooks = [{ type = \"command\", command = \"true\" }] }]\n", + }, + Payload { + harness: "opencode", + invalid: "\n[fixed.hooks.opencode.plugins]\n\"bad.ts\" = \"export const nothing = 1\\n\"\n", + quoted: "Plugin must export a default definition", + valid: "\n[fixed.hooks.opencode.plugins]\n\"good.ts\" = \"export default { id: \\\"good\\\", setup() {} }\\n\"\n", + }, +]; + +/// Guards: README (the harness's own check refuses what it cannot read before a run starts) -- +/// a job of the real `candler run` on real images, with an invalid payload (a Claude Code hooks +/// entry on an unknown event; an `OpenCode` plugin with no default export) is refused before its +/// first run, the refusal quotes the harness's own output and no run is sealed; the same job with +/// a valid payload is not refused and seals its run (G6). +/// +/// Oracle: the harness outputs recorded for both cases (`fixtures/doctor` and `fixtures/check` +/// of the two harness crates); the refusal line is the one the supervisor logs for +/// `experiment.harness_rejected_input` (`Candler installed .. at ..; rejects it: ..`). +/// +/// Bite: a job that starts its first run whatever the check says (a sealed run, no refusal line), +/// or a check that refuses a payload the harness accepts. +#[test] +#[ignore = "needs Docker; run with --run-ignored only"] +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 mut failures = Vec::new(); + let mut jobs = Vec::new(); + for payload in PAYLOADS { + 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 + 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")) + .unwrap_or_default(); + let sealed = fs::read_dir(ran.store.join("runs")) + .into_iter() + .flatten() + .flatten() + .filter(|entry| entry.path().join("run.done").is_file()) + .count(); + let rejects = format!("{} rejects it: ", payload.harness); + let refused = supervisor.contains(&rejects); + if label == "invalid" { + if !refused || !supervisor.contains(payload.quoted) || sealed != 0 { + failures.push(format!( + "{}: invalid payload: refused {refused}, sealed {sealed}\n{supervisor}", + payload.harness + )); + } + } else if refused || sealed == 0 { + failures.push(format!( + "{}: valid payload: refused {refused}, sealed {sealed}\n{supervisor}", + payload.harness + )); + } + } + } + let fake = model.container.clone(); // BORROW: the check names the fake after the cleanup + drop(made); + assert_nothing_left(&real, &jobs, &fake); + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs index e2734028..34d3176f 100644 --- a/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs +++ b/crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs @@ -20,7 +20,7 @@ use crate::support::cli_run::{wait_for, world}; use crate::support::seam::entries_under; /// The credential the fake model demands and the experiment's secret supplies. -const TOKEN: &str = "parity-fixture-token-0123456789"; +pub(super) const TOKEN: &str = "parity-fixture-token-0123456789"; /// The server the cell declares. const SERVER: &str = "parity"; @@ -36,9 +36,9 @@ fn experiment(base: &str, harness: &str) -> String { base.replace("@HARNESS@", harness) } -/// The answers to the stamp call among the requests the fake model recorded after the first +/// The answers to the call `call_id` among the requests the fake model recorded after the first /// `skip`: whether each is an error, and its text. -fn stamp_answers(records: &str, skip: usize) -> Vec<(bool, String)> { +pub(super) fn answers_to(records: &str, skip: usize, call_id: &str) -> Vec<(bool, String)> { let mut found = Vec::new(); for line in records.lines().skip(skip) { let Ok(record) = serde_json::from_str::(line) else { @@ -49,7 +49,7 @@ fn stamp_answers(records: &str, skip: usize) -> Vec<(bool, String)> { .and_then(|messages| messages.last()) .and_then(|message| message["content"].as_array()); for block in blocks.into_iter().flatten() { - if block["type"] == "tool_result" && block["tool_use_id"] == CALL_ID { + if block["type"] == "tool_result" && block["tool_use_id"] == call_id { let text = block["content"].as_str().map_or_else( || block["content"].to_string(), str::to_owned, // BORROW: .to_owned() makes the owned text @@ -61,8 +61,94 @@ fn stamp_answers(records: &str, skip: usize) -> Vec<(bool, String)> { found } +/// The scripted fake model, running in a container, and what a job needs to reach it. +pub(super) struct Fake { + pub(super) container: String, + /// The model's address as the job's containers reach it. + pub(super) endpoint: String, + /// Its CA certificate, which the machine setting `[gateway] upstream_ca` names. + pub(super) ca: std::path::PathBuf, + _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 { + let host = fake_host(real); + let publish = format!( + "{}::8443", + if cfg!(target_os = "linux") { + host.as_str() + } else { + "127.0.0.1" + } + ); + let context = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/docker/fakemodel"); + let tag = format!("candler-fakemodel:{label}-{}", std::process::id()); + let tagged = format!("candler.test={label}"); + must( + real, + &["build", "-q", "--label", &tagged, "-t", &tag, context], + ); + made.images.push(must( + 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, + ], + ); + made.containers.push(fake.clone()); // BORROW: the cleanup owns its ids + let port = must(real, &["port", &fake, "8443/tcp"]) + .lines() + .next() + .and_then(|line| line.rsplit(':').next()) + .expect("a host port") + .to_owned(); + assert!( + wait_for(Duration::from_secs(30), || { + docker(real, &["exec", &fake, "test", "-f", "/tmp/fake/ca.pem"]) + .status + .success() + && docker(real, &["logs", &fake]) + .stdout + .windows(5) + .any(|w| w == b"ready") + }), + "the fake model is ready" + ); + let dir = tempfile::tempdir().unwrap(); + let ca = dir.path().join("ca.pem"); + must( + real, + &[ + "cp", + &format!("{fake}:/tmp/fake/ca.pem"), + &ca.display().to_string(), + ], + ); + Fake { + container: fake, + endpoint: format!("https://{host}:{port}"), + ca, + _dir: dir, + } +} + /// What the fake model has recorded so far: nothing before its first request. -fn records(real: &Path, fake: &str) -> String { +pub(super) fn records(real: &Path, fake: &str) -> String { let out = docker(real, &["exec", fake, "cat", "/tmp/fake/records.jsonl"]); String::from_utf8_lossy(&out.stdout).into_owned() } @@ -113,24 +199,25 @@ fn call_origins(text: &str) -> Vec { found } +/// 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) log: String, +} + /// Runs the experiment `text` with the real `candler run` against the fake model at `endpoint` -/// and reads back what the sealed run stored, the MCP file being the one `place` names: -/// the directory of the run it is written under and the path it ends in. -fn run_once( +/// (`stage` puts what the experiment's inputs need in the world first), waits for the job to +/// end, and returns where it stored its runs. +pub(super) fn run_job( text: &str, endpoint: &str, ca: &Path, - place: (&str, &str), made: &mut Made, -) -> Observed { + stage: impl FnOnce(&crate::support::cli_run::World), +) -> Ran { let world = world(); - let inputs = world.root.join("inputs").join("servers"); - fs::create_dir_all(&inputs).unwrap(); - fs::copy( - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/parity/parity_mcp.py"), - inputs.join("parity_mcp.py"), - ) - .unwrap(); + stage(&world); let config = world.root.join("config"); fs::create_dir_all(config.join("candler")).unwrap(); fs::write( @@ -174,9 +261,31 @@ fn run_once( let ended = wait_for(Duration::from_secs(600), || { fs::read_to_string(&events).is_ok_and(|log| log.contains("job.ended")) }); - let log = fs::read_to_string(&events).unwrap_or_default(); + let log = fs::read_to_string(&events).unwrap_or_default() + + &fs::read_to_string(events.with_file_name("supervisor.log")).unwrap_or_default(); assert!(ended, "the job ends\n{log}"); + 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 { + 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(); + fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/parity/parity_mcp.py"), + inputs.join("parity_mcp.py"), + ) + .unwrap(); + }); let run_dir = fs::read_dir(store.join("runs")) .into_iter() .flatten() @@ -223,83 +332,11 @@ fn run_once( fn parity_one_installed_server_one_traced_call() { let started = Instant::now(); let real = real_docker(); - let host = fake_host(&real); - let publish = format!( - "{}::8443", - if cfg!(target_os = "linux") { - host.as_str() - } else { - "127.0.0.1" - } - ); let before = must(&real, &["ps", "-aq"]); let mut made = Made::default(); made.real.clone_from(&real); // BORROW: the cleanup owns its client path - - let context = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/docker/fakemodel"); - let tag = format!("candler-fakemodel:parity-{}", std::process::id()); - must( - &real, - &[ - "build", - "-q", - "--label", - "candler.test=parity", - "-t", - &tag, - context, - ], - ); - made.images.push(must( - &real, - &["image", "inspect", "--format", "{{.Id}}", &tag], - )); - let fake = must( - &real, - &[ - "run", - "-d", - "--label", - "candler.test=parity", - "-p", - &publish, - "-e", - &format!("FAKE_TOKEN={TOKEN}"), - "-e", - &format!("FAKE_HOST={host}"), - &tag, - ], - ); - made.containers.push(fake.clone()); // BORROW: the cleanup owns its ids - let port = must(&real, &["port", &fake, "8443/tcp"]) - .lines() - .next() - .and_then(|line| line.rsplit(':').next()) - .expect("a host port") - .to_owned(); - assert!( - wait_for(Duration::from_secs(30), || { - docker(&real, &["exec", &fake, "test", "-f", "/tmp/fake/ca.pem"]) - .status - .success() - && docker(&real, &["logs", &fake]) - .stdout - .windows(5) - .any(|w| w == b"ready") - }), - "the fake model is ready" - ); - let scratch = tempfile::tempdir().unwrap(); - let ca = scratch.path().join("ca.pem"); - must( - &real, - &[ - "cp", - &format!("{fake}:/tmp/fake/ca.pem"), - &ca.display().to_string(), - ], - ); - let endpoint = format!("https://{host}:{port}"); + 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 = { @@ -339,9 +376,9 @@ fn parity_one_installed_server_one_traced_call() { ("claude-code", &claude, ("workspace", ".mcp.json")), ("opencode", &opencode, ("home", "opencode/opencode.json")), ] { - let skip = records(&real, &fake).lines().count(); - let seen = run_once(text, &endpoint, &ca, place, &mut made); - let answers = stamp_answers(&records(&real, &fake), skip); + let skip = records(&real, fake).lines().count(); + let seen = run_once(text, endpoint, ca, place, &mut made); + let answers = answers_to(&records(&real, fake), skip, CALL_ID); if !answers .iter() .any(|(error, text)| !error && text.contains(STAMP)) From 746654705cc56786e22bc4b3db336989915e07b0 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:10:54 +0900 Subject: [PATCH 64/69] fix(api): mount the declared inputs in the harness check An OpenCode cell whose MCP server script comes from the experiment's inputs was refused at job start: the check container did not mount the declared inputs, so OpenCode logged a WARN for the missing script and the reader refused it. The check must see what the run sees. The check now stages its container with the cell's declared inputs, as the server check does, and the group key covers them (each input's workspace path and content digest), so two cells that differ only in inputs are checked apart. The architecture and the harness-capabilities page say so. The G11 guard now asserts the session-start marker is in the context_start system or first_message. It is in system on both harnesses under Candler (Claude Code 2.1.311 writes a `SessionStart:startup hook success:` line there; the probe's bare `--print` run had it in the first message). Co-Authored-By: Claude Sonnet 5.5 --- __design__/architecture.md | 10 +++++----- .../src/jobs/orchestrate/config.rs | 13 +++++++++--- .../it/guard_cli_e2e/agent_config_e2e.rs | 20 +++++++++---------- docs/contract/harness-capabilities.md | 2 +- 4 files changed, 26 insertions(+), 19 deletions(-) diff --git a/__design__/architecture.md b/__design__/architecture.md index 82baaf04..84d75f3e 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -780,14 +780,14 @@ run as another harness. `comparable.harness.driver` is `None` for live cells. Th Candler installs for a cell (`config_check(plan)`) and a reader of what it printed (`read_config_check(output) -> Clean | Rejected { output }`). Before the first run, the core groups the planned cells by everything that command reads (the harness, the image, the home and -workspace files, the command with its cwd and overlay, the container environment and the -treatment), runs it once per group in a container without network, and passes the reader standard +workspace files, the declared inputs, the command with its cwd and overlay, the container +environment and the treatment), runs it once per group in a container without network, and passes the reader standard output followed by standard error, whatever the exit status. A check that cannot run (the container does not start, the command is missing, times out or is ended by a signal, or it prints nothing or too much) is refused as `jobs.config_check_failed`, an environment fault; a rejection is refused as -`experiment.harness_rejected_input`, naming the files and the setting they come from. Declared -inputs are not mounted in the check, so it judges the files Candler installs for the harness, not -the consumer's inputs, and a clean verdict (`provenance.harness_config_check`) says no more. +`experiment.harness_rejected_input`, naming the files and the setting they come from. The check +container mounts the cell's declared inputs as the run does, so the verdict +(`provenance.harness_config_check`) covers every file the harness reads at start. **The shared fixture suite.** `candler-harness`, under the feature `conformance`, holds one suite that every driver crate runs over its recorded streams. It checks that gateway names, state paths, diff --git a/crates/candler-core/src/jobs/orchestrate/config.rs b/crates/candler-core/src/jobs/orchestrate/config.rs index 92aa7e43..9e66ba6f 100644 --- a/crates/candler-core/src/jobs/orchestrate/config.rs +++ b/crates/candler-core/src/jobs/orchestrate/config.rs @@ -21,6 +21,7 @@ use super::session::image_of; use crate::isolation::model::ContainerPlan; use crate::isolation::{ExecOutput, Isolation}; use crate::runner::Runtime; +use crate::runner::evidence::Inputs; use crate::runner::plan::{CellId, RunPlan}; /// Why the check refused the job. @@ -125,9 +126,11 @@ fn add_files(bytes: &mut Vec, tag: &str, files: &[PreparedFile]) { /// with its root, path, mode and bytes; the check command's words, working directory and /// environment overlay; the treatment; and the environment the check container is given. /// -/// The cell's declared inputs are not mounted in the check container, so they are not in the key. +/// The cell's declared inputs are mounted in the check container as in a run, so each one's +/// workspace path and content digest is in the key. fn files_digest( plan: &Plan, + inputs: &Inputs, container: &ContainerPlan, command: &CommandSpec, treatment: &str, @@ -135,6 +138,10 @@ fn files_digest( let mut bytes = Vec::new(); add_files(&mut bytes, "home", &plan.prepared.files); add_files(&mut bytes, "workspace", &plan.workspace_files); + bytes.extend_from_slice(format!("inputs\0{}\0", inputs.digests.len()).as_bytes()); + for input in &inputs.digests { + bytes.extend_from_slice(format!("{}\0{:?}\0", input.path, input.digest).as_bytes()); + } for word in command.argv() { bytes.extend_from_slice(word.as_bytes()); bytes.push(0); @@ -265,7 +272,7 @@ async fn grouped<'a>( continue; } let root = scratch.join(seen.len().to_string()); // BORROW: .to_string() gives owned text - let (staged, mut container) = stage_container(rt, isolation, plan, &root, false) + let (staged, mut container) = stage_container(rt, isolation, plan, &root, true) .await .map_err(|e| failed(&e))?; let Some(command) = rt.driver.config_check(&staged) else { @@ -318,7 +325,7 @@ fn group_key( Ok(( rt.driver.id().to_string(), // BORROW: .to_string() gives owned text image_of(comparable), - files_digest(staged, container, command, &treatment), + files_digest(staged, &cell.inputs, container, command, &treatment), )) } 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 864de49b..8460ee01 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 @@ -261,8 +261,10 @@ fn assert_nothing_left(real: &Path, jobs: &[String], fake: &str) { /// arm's workspace text and not the other arm's (G4); the blocking hook's marker answers the /// shell call as an error (G5); the census lists the global and the workspace file with their /// scopes (G7); no installed file is among the collected outputs and no run is sealed -/// `input_leak` (G9); the session-start marker is in the first message on Claude Code and in the -/// system text on `OpenCode` (G11). +/// `input_leak` (G9); the session-start marker is in the `system` or the `first_message` of the +/// `context_start` (G11; measured in `system` on both harnesses under Candler: Claude Code 2.1.311 +/// writes a `SessionStart:startup hook success:` line there, while the probe's bare `--print` run +/// had it in the first message). /// /// Oracle: the texts the experiment fixes, and where the probe measured each to land /// (`__reports__/agent_config/03-findings_probe_harness_checks_v0.md`). @@ -351,15 +353,13 @@ fn guard_agent_config_e2e() { "{harness}/{arm}: context_start holds the other arm" )); } - // G11: the start marker is in the system text on both harnesses. The probe measured - // Claude Code's in the first message; Claude Code 2.1.311 writes it as a - // `SessionStart:startup hook success:` line of the system text. - let (inside, outside) = (&run.system, &run.first_message); - if !inside.contains(marker) || outside.contains(marker) { + // G11: the start marker is in the `system` or the `first_message` (measured in `system` + // on both harnesses under Candler; Claude Code 2.1.311 writes a + // `SessionStart:startup hook success:` line there, the probe's bare `--print` run had + // it in the first message). + if !reached.contains(marker) { failures.push(format!( - "{harness}/{arm}: start marker not only in its place (in {}, out {})", - inside.contains(marker), - outside.contains(marker) + "{harness}/{arm}: start marker not in context_start" )); } // G7: the census lists both files with their scope diff --git a/docs/contract/harness-capabilities.md b/docs/contract/harness-capabilities.md index 745792f4..e79071c5 100644 --- a/docs/contract/harness-capabilities.md +++ b/docs/contract/harness-capabilities.md @@ -76,6 +76,6 @@ Core line: `v0.16.0`; the `candler-harness` crate has the same version. - `no (…)` is a refusal: `experiment.session_refused` while resolving, `experiment.setting_unsupported` once the cells are planned, before a job starts. [checked: v@0.15.0] - In session mode Candler counts turns and ends the run past `budget.per_run.turns`. [checked: v@0.7.0] - A driver's answers for each `AgentSetting` decide which modes, effort levels and tool names it maps or refuses. [checked: v@0.7.0] -- Every Claude Code cell runs three hooks, headless too, logs them to stream `hooks`, and gets one `claude doctor` check per distinct (image, files, command, environment, treatment). [checked: v@0.16.0] +- Every Claude Code cell runs three hooks, headless too, logs them to stream `hooks`, and gets one `claude doctor` check per (image, files, inputs, command, environment, treatment). [checked: v@0.16.0] - `census.instructions` is read from the hook log in the agent's home, which the agent can change; the trace's `context_start` shows what reached the model. [checked: v@0.16.0] - A plain OpenCode cell gets no instruction file or plugin; `census.instructions` is the gateway's record of the first request offering tools. [checked: v@0.16.0] From 2a4bf160008a77ebe4f8ff363418a14db5b975b3 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:14:23 +0900 Subject: [PATCH 65/69] reports(api): confirm instructions and hooks live from the trace G13 on RiVault Reasoning-Small, Claude Code and OpenCode, two arms each: every stored context_start holds the global text, its own arm text and the session-start marker, and never the other arm text. Blocking hooks were left out of the live run. Round 06 entry added to the README. Co-Authored-By: Claude Sonnet 5.5 --- .../06-findings_live_confirmation_v0.md | 50 +++++++++++++++++++ __reports__/agent_config/README.md | 3 ++ 2 files changed, 53 insertions(+) create mode 100644 __reports__/agent_config/06-findings_live_confirmation_v0.md diff --git a/__reports__/agent_config/06-findings_live_confirmation_v0.md b/__reports__/agent_config/06-findings_live_confirmation_v0.md new file mode 100644 index 00000000..f6b160f2 --- /dev/null +++ b/__reports__/agent_config/06-findings_live_confirmation_v0.md @@ -0,0 +1,50 @@ +# Findings: M6.5 instructions and hooks, confirmed live from the trace + +| Field | Value | +|---|---| +| Date | 2026-11-25 | +| Model | RiVault/Reasoning-Small, through the gateway (`model.token_secret = RIVAULT_LLM_INFERENCE`, by name only) | +| Candler | `bfdfa010` (branch `feat/m6.5-agent-config`, run record: `eval_infra.dirty = false`, `harness_config_check = clean`) | +| Harness versions | Claude Code 2.1.311 (trace `claude_code_version`); OpenCode: run record carries `harness_version` 2.2.7 | +| Shape | 2 `candler run` attempts, one per harness; 2 arms each (A, B, factor `instructions.workspace`); 1 replicate; prompt "Say hello in one sentence." | +| Gate | G13: G4 (global text and own arm's text, not the other arm's) and G11 (session-start marker), read from the first `context_start` of each stored trace | + +## Result + +| Harness | Arm | G4 | G11 | Global text | Workspace text | Marker | +|---|---|---|---|---|---|---| +| Claude Code | A | yes | yes | `first_message` | `first_message` | `system` | +| Claude Code | B | yes | yes | `first_message` | `first_message` | `system` | +| OpenCode | A | yes | yes | `system` | `system` | `system` | +| OpenCode | B | yes | yes | `system` | `system` | `system` | + +In all four runs the other arm's text is absent from `context_start`. G13 passes on both harnesses. + +## Excerpts (verbatim, from `context_start`) + +Claude Code, arm A, `first_message`: +``` +...GLOBAL_TEXT_CC_71a3\n\nContents of /work/CLAUDE.md (project instructions... +...checked into the codebase):\n\nWORKSPACE_TEXT_A_5be2\n... +``` +Claude Code, arm A, `system`: `SessionStart:startup hook success: SESSION_START_MARKER_CC_c40d` +Claude Code, arm B, `first_message`: `...checked into the codebase):\n\nWORKSPACE_TEXT_B_5be2\n...` + +OpenCode, arm A, `system`: +``` +...opencode/AGENTS.md\nGLOBAL_TEXT_OC_71a3\n\nInstructions from: /work/AGENTS.md\nWORKSPACE_TEXT_A_5be2\n\nToday's date... +...SESSION_START_MARKER_OC_c40d (the last line of the system text) +``` +OpenCode, arm B, `system`: `...Instructions from: /work/AGENTS.md\nWORKSPACE_TEXT_B_5be2\n\nToday's date...` + +## Deviations from the deterministic guard + +- No blocking hook: the Claude Code `PreToolUse` script and the OpenCode `tool.execute.before` throw were left out, so G1's blocked-hook marker was not exercised live. The session-start hooks and all texts are the guard's values. +- Real model and a trivial prompt, not the fake model and the shell prompt; `wall_s = 300`; no tool call was asked for. +- The guard's two experiments (one per harness) became two files, `claude-code.toml` and `opencode.toml`, run one after the other. They differ only in the hook block and the harness name. +- The traces were read as the guard reads them: first event of kind `context_start` in `trace.jsonl`, `system` and `first_message` joined. +- Claude Code puts both instruction texts in the first message and the hook output in the system text, as the probe (round 03) measured; OpenCode puts all three in the system text. + +## Not covered + +No tool-call turn, no replicate beyond one per arm, and no check of the model's behaviour under the instructions: only what each session was given. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index e758ab19..1172974e 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -24,6 +24,9 @@ Instruction files and hooks as per-arm experiment data (M6.5). ### Round 05 - [05-observation_level2_out_of_scope_v0.md](05-observation_level2_out_of_scope_v0.md) — **latest** for level 2. Ten findings from level 2 and its seam review that lie outside its leaves: a broken ignored OpenCode guard on main, two link-following paths, refusal pointers chosen by presence, non-report check output blamed on the experiment, check groups that split too finely, collision targets derived twice, no cancel signal or Unicode normalisation, an unescaped census source, a second timing guard. Also two process lessons: whole-suite gates, and check rules taken from recorded output. +### Round 06 +- [06-findings_live_confirmation_v0.md](06-findings_live_confirmation_v0.md) — **latest** live proof. G13 on RiVault Reasoning-Small, both harnesses, two arms each: every `context_start` holds the global text, its own arm's workspace text and the session-start marker, and never the other arm's text. Claude Code puts the two texts in `first_message` and the marker in `system`; OpenCode puts all three in `system`. The blocking hooks were left out of the live run. + ## Status The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended on 2026-11-25 for two instruction scopes (v1), then for a live, trace-read proof (v2). Level 1 is dispatched, and the probe is done. From 528cfef3aa5baa0851a5e77a396db5575fe068e3 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:15:11 +0900 Subject: [PATCH 66/69] reports(api): close M6.5 level 3 and record the run-context meeting The guard leaf is done: its gates are ticked, G6 with the note that the refusal's code is not recorded where a consumer reads it. Round 06 gains the level 3 observations (O11-O15) and keeps the live run's two experiment files beside its findings. M6d has not landed on origin/main, so meet_run_context records its gates as owed by M6d. Co-Authored-By: Claude Opus 5.5 --- .../06-findings_live_confirmation_v0.md | 3 +- .../agent_config/06-live/claude-code.toml | 33 ++++++++++++ .../agent_config/06-live/opencode.toml | 42 +++++++++++++++ .../06-observation_level3_out_of_scope_v0.md | 52 +++++++++++++++++++ __reports__/agent_config/README.md | 3 ++ .../installed/proved/README.md | 4 +- .../installed/proved/e2e_guard.md | 16 +++--- .../installed/proved/reviewed/README.md | 4 +- .../proved/reviewed/meet_run_context.md | 9 ++-- 9 files changed, 149 insertions(+), 17 deletions(-) create mode 100644 __reports__/agent_config/06-live/claude-code.toml create mode 100644 __reports__/agent_config/06-live/opencode.toml create mode 100644 __reports__/agent_config/06-observation_level3_out_of_scope_v0.md diff --git a/__reports__/agent_config/06-findings_live_confirmation_v0.md b/__reports__/agent_config/06-findings_live_confirmation_v0.md index f6b160f2..28e97238 100644 --- a/__reports__/agent_config/06-findings_live_confirmation_v0.md +++ b/__reports__/agent_config/06-findings_live_confirmation_v0.md @@ -43,7 +43,8 @@ OpenCode, arm B, `system`: `...Instructions from: /work/AGENTS.md\nWORKSPACE_TEX - Real model and a trivial prompt, not the fake model and the shell prompt; `wall_s = 300`; no tool call was asked for. - The guard's two experiments (one per harness) became two files, `claude-code.toml` and `opencode.toml`, run one after the other. They differ only in the hook block and the harness name. - The traces were read as the guard reads them: first event of kind `context_start` in `trace.jsonl`, `system` and `first_message` joined. -- Claude Code puts both instruction texts in the first message and the hook output in the system text, as the probe (round 03) measured; OpenCode puts all three in the system text. +- Claude Code puts both instruction texts in the first message, as the probe (round 03) measured, and the hook output in the system text, where the probe's bare `--print` run had it in the first message; G11 accepts either. OpenCode puts all three in the system text. +- The two experiment files are kept beside this report, in [06-live/](06-live/). ## Not covered diff --git a/__reports__/agent_config/06-live/claude-code.toml b/__reports__/agent_config/06-live/claude-code.toml new file mode 100644 index 00000000..5f754af4 --- /dev/null +++ b/__reports__/agent_config/06-live/claude-code.toml @@ -0,0 +1,33 @@ +schema = "experiment/1" +replicates = 1 +secrets = ["RIVAULT_LLM_INFERENCE"] + +[fixed] +permission_mode = "bypassPermissions" +"model.id" = "RiVault/Reasoning-Small" +"model.endpoint" = "https://api.class2.llm.ai.r-ccs.riken.jp" +"model.token_secret" = "RIVAULT_LLM_INFERENCE" +"prompt.template" = "Say hello in one sentence." + +[fixed.instructions.global] +claude-code = "GLOBAL_TEXT_CC_71a3" +opencode = "GLOBAL_TEXT_OC_71a3" + +[fixed.hooks.claude-code.settings] +SessionStart = [{ hooks = [{ type = "command", command = "echo SESSION_START_MARKER_CC_c40d" }] }] + +[harness] +name = "claude-code" + +[[factors]] +path = "instructions.workspace" +levels = ["WORKSPACE_TEXT_A_5be2", "WORKSPACE_TEXT_B_5be2"] + +[budget.per_run] +wall_s = 300 + +[treatment] +name = "demo" +tag = "v1" +source = "/Users/hacker/Documents/tmp/claude-worktrees/Candler/m6_5-scratch/live/treatment" + diff --git a/__reports__/agent_config/06-live/opencode.toml b/__reports__/agent_config/06-live/opencode.toml new file mode 100644 index 00000000..674429b2 --- /dev/null +++ b/__reports__/agent_config/06-live/opencode.toml @@ -0,0 +1,42 @@ +schema = "experiment/1" +replicates = 1 +secrets = ["RIVAULT_LLM_INFERENCE"] + +[fixed] +permission_mode = "bypassPermissions" +"model.id" = "RiVault/Reasoning-Small" +"model.endpoint" = "https://api.class2.llm.ai.r-ccs.riken.jp" +"model.token_secret" = "RIVAULT_LLM_INFERENCE" +"prompt.template" = "Say hello in one sentence." + +[fixed.instructions.global] +claude-code = "GLOBAL_TEXT_CC_71a3" +opencode = "GLOBAL_TEXT_OC_71a3" + +[fixed.hooks.opencode.plugins] +"guard.ts" = ''' +export default { + id: "guard", + setup(api) { + api.session.hook("context", (event) => { + event.system.push({ type: "text", text: "SESSION_START_MARKER_OC_c40d" }); + }); + }, +}; +''' + +[harness] +name = "opencode" + +[[factors]] +path = "instructions.workspace" +levels = ["WORKSPACE_TEXT_A_5be2", "WORKSPACE_TEXT_B_5be2"] + +[budget.per_run] +wall_s = 300 + +[treatment] +name = "demo" +tag = "v1" +source = "/Users/hacker/Documents/tmp/claude-worktrees/Candler/m6_5-scratch/live/treatment" + diff --git a/__reports__/agent_config/06-observation_level3_out_of_scope_v0.md b/__reports__/agent_config/06-observation_level3_out_of_scope_v0.md new file mode 100644 index 00000000..98dabaa5 --- /dev/null +++ b/__reports__/agent_config/06-observation_level3_out_of_scope_v0.md @@ -0,0 +1,52 @@ +# Level 3 of M6.5: what was found outside its scope (v0) + +Date: 2026-11-25 + +Five findings from M6.5's level 3 leaf (`e2e_guard`) and its fix round. Each one lies outside the leaf, so the leaf did not fix it. Numbering continues from [round 05](05-observation_level2_out_of_scope_v0.md). + +--- +type: observation +topic: agent_config +spotted-during: implementing and merging `e2e_guard` (merge bfdfa010) +date: 2026-11-25 +domain: code +confidence: confirmed +urgency: per item, below +deferred-because: each lies outside the guard leaf's topic +--- + +## Summary + +| # | Observation | Urgency | Where | +|---|---|---|---| +| O11 | A job-start refusal's code reaches no place a consumer reads | medium | `job.ended` payload, `jobs/events.rs` | +| O12 | The parity guard's leftover-container check compares the whole daemon | low | `parity_e2e.rs`, final assertion | +| O13 | The OpenCode plugin API that the hooks rely on is not on the capability page | low | `docs/contract/harness-capabilities.md` | +| O14 | `resolve`'s preflight cannot reach the fake model from a container on macOS | low | resolve preflight, `assets/docker/fakemodel` | +| O15 | Two more timing guards fail under load | low | `guard_supervise`, `guard_wiring` | + +## O11. A job-start refusal's code reaches no place a consumer reads + +**What was noticed.** Since level 2 moved the harness check to job start (amendment A1), a rejected cell is refused inside the detached supervisor. The refusal is `DriverError::HarnessRejectedInput`, whose code is `experiment.harness_rejected_input`, but the job's `events.jsonl` ends with `job.ended {"reason": "failed"}` and `supervisor.log` carries the message only. `refusal.json` is documented for evaluate jobs only. A consumer, or the guard, can therefore not tell a rejected input from any other failure by its code. The same holds for `jobs.config_check_failed` and `jobs.server_check_failed`. G6 is met on the message; `guard_harness_check_refuses` asserts on it. + +**Location map.** `crates/candler-core/src/jobs/events.rs` (`job.ended`); `crates/candler-core/src/jobs/orchestrate/{config,servers}.rs`; `docs/contract/` error-model pages. + +**Hand-off questions.** Should `job.ended` carry the refusal's code and pointer, or should run jobs write `refusal.json` as evaluate jobs do? Working theory: one refusal record for every job kind. + +## O12. The parity guard's leftover-container check compares the whole daemon + +**What was noticed.** `parity_one_installed_server_one_traced_call` ends by comparing `docker ps -aq` before and after. On a daemon shared with other sessions it failed 4 of 5 times in the fix round on containers it did not make; the committed file passed alone. `agent_config_e2e.rs` has `assert_nothing_left`, which compares the guard's own containers only. + +**Hand-off questions.** Working theory: the parity guard uses `assert_nothing_left` (or filters by the job's label). + +## O13. The OpenCode plugin API is not on the capability page + +**What was noticed.** The guard's plugin uses `export default { id, setup(api) }` with `api.tool.hook("execute.before", …)` and `api.session.hook("context", …)`, read from the OpenCode 2.2.7 binary. No repository page names this shape, so a consumer writing `hooks.opencode.plugins` must find it the same way. + +## O14. `resolve`'s preflight cannot reach the fake model from a container on macOS + +**What was noticed.** The image's `curl` has no CA bundle for the fake model's TLS, and `host.docker.internal` did not resolve in the preflight's container on this Mac. The guard resolves against a one-shot local listener instead. The run itself reaches the fake model through the gateway. + +## O15. Two more timing guards fail under load + +**What was noticed.** In one full `cargo nextest run --workspace`, `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 and passed alone; the next full run passed 767 of 767. Same family as round 05's O10. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 1172974e..1e8e1e67 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -26,6 +26,7 @@ Instruction files and hooks as per-arm experiment data (M6.5). ### Round 06 - [06-findings_live_confirmation_v0.md](06-findings_live_confirmation_v0.md) — **latest** live proof. G13 on RiVault Reasoning-Small, both harnesses, two arms each: every `context_start` holds the global text, its own arm's workspace text and the session-start marker, and never the other arm's text. Claude Code puts the two texts in `first_message` and the marker in `system`; OpenCode puts all three in `system`. The blocking hooks were left out of the live run. +- [06-observation_level3_out_of_scope_v0.md](06-observation_level3_out_of_scope_v0.md) — **latest** O11–O15 from level 3: a job-start refusal's code reaches no place a consumer reads (medium); the parity guard's container check compares the whole daemon; the OpenCode plugin API is not on the capability page; `resolve`'s preflight cannot reach the fake model on macOS; two more timing guards fail under load. ## Status @@ -45,4 +46,6 @@ Level 2 is done and merged locally on 2026-11-25: `install_claude_code`, `instal Spend after level 2 is $95.92 of the $125 cap: planning and level 1 $55.40, level 2 about $40.50. +Level 3 is done and merged locally on 2026-11-25 (merge bfdfa010). Its guard found that the job-start harness check did not mount the cell's declared inputs, so an OpenCode MCP server taken from inputs was refused at job start; the check now mounts and keys them. G11 now accepts the marker in `system` or `first_message`: under Candler, Claude Code writes it in `system`. G6 is met on the refusal and its message; the code is not recorded where a consumer reads it (O11). G13 passed live. M6d has not landed on `origin/main`, so `meet_run_context` is owed by M6d. + No decision is open. diff --git a/__roadmap__/m6_5-agent-config/installed/proved/README.md b/__roadmap__/m6_5-agent-config/installed/proved/README.md index 54e0eafc..bd4acdbe 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/README.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/README.md @@ -15,7 +15,7 @@ One experiment shows, on both harnesses, the global and the arm's own workspace ## Status ```mermaid graph TD - e2e_guard[E2E guard]:::planned + e2e_guard[E2E guard]:::done reviewed[Reviewed]:::planned classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -27,7 +27,7 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `e2e_guard.md` | 📄 Leaf Task | ⬜ Planned | +| `e2e_guard.md` | 📄 Leaf Task | ✅ Done | | `reviewed/` | 📁 Directory | ⬜ Planned | ## Amendment Log diff --git a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md index d8db02fc..38224e84 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/e2e_guard.md @@ -5,15 +5,15 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ G4. From the trace: on each harness, the `context_start` of arm A's run holds the global text and workspace text A, verbatim, in its `system` or its `first_message`, and neither holds workspace text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. -- ⬜ G5. The scripted tool call is answered with an error carrying the hook's marker: a Claude Code PreToolUse script exits 2, and an OpenCode plugin throws in `execute.before`. On the base, there is no hook and the call succeeds. -- ⬜ G6. On real images, an invalid payload (a Claude Code hooks entry on an unknown event; an OpenCode plugin with no default export) is refused before the job's first run with `experiment.harness_rejected_input`, quoting the harness, and the valid payload passes. On the base, the job runs. -- ⬜ G7. Each run's census lists both installed instruction files with their scope: on Claude Code the global file where the probe settled and the root `CLAUDE.md` (Project); on OpenCode the global `AGENTS.md` and the root `AGENTS.md`. -- ⬜ G9. No installed file, the root instruction file included, is among any run's collected outputs, and no run is sealed `input_leak`. -- ⬜ G1 (end to end). `candler resolve` of the guard's experiment succeeds, and the `inspect` of one of its runs shows `instructions` and `hooks` with the arm's values. -- ⬜ G11. From the trace: on each harness, the session-start hook's marker is in `context_start`: in `first_message` on Claude Code, in `system` on OpenCode, as the probe measured. On the base, there is no such event. +- ✅ G4. From the trace: on each harness, the `context_start` of arm A's run holds the global text and workspace text A, verbatim, in its `system` or its `first_message`, and neither holds workspace text B, and the reverse holds for arm B. On the base, the experiment is `unknown_path`. +- ✅ G5. The scripted tool call is answered with an error carrying the hook's marker: a Claude Code PreToolUse script exits 2, and an OpenCode plugin throws in `execute.before`. On the base, there is no hook and the call succeeds. +- ✅ G6. On real images, an invalid payload (a Claude Code hooks entry on an unknown event; an OpenCode plugin with no default export) is refused before the job's first run with `experiment.harness_rejected_input`, quoting the harness, and the valid payload passes. On the base, the job runs. Met 2026-11-25 on the refusal and its message; the code itself is not recorded where a consumer reads it (`job.ended` carries `failed` only), so the guard asserts on the message (observation O11, round 06). +- ✅ G7. Each run's census lists both installed instruction files with their scope: on Claude Code the global file where the probe settled and the root `CLAUDE.md` (Project); on OpenCode the global `AGENTS.md` and the root `AGENTS.md`. +- ✅ G9. No installed file, the root instruction file included, is among any run's collected outputs, and no run is sealed `input_leak`. +- ✅ G1 (end to end). `candler resolve` of the guard's experiment succeeds, and the `inspect` of one of its runs shows `instructions` and `hooks` with the arm's values. +- ✅ G11. From the trace: on each harness, the session-start hook's marker is in `context_start`, in its `system` or its `first_message`. Measured in `system` on both harnesses under Candler (Claude Code 2.1.311 writes a `SessionStart:startup hook success:` line there; the probe's bare `--print` run had it in the first message, row g of report 03). On the base, there is no such event. - ⬜ G13. Live on RiVault (Reasoning-Small): one experiment on both harnesses, two arms, one replicate each, shows G4 and G11 in its stored traces, and `__reports__/agent_config/-findings_live_confirmation_v0.md` quotes the trace excerpts, where `` is the next free round. -- ⬜ The guards run in a pass that lists them as passed, not skipped (leaf template, convention 3). `docker ps -a` shows none of their containers afterwards. +- ✅ The guards run in a pass that lists them as passed, not skipped (leaf template, convention 3). `docker ps -a` shows none of their containers afterwards. **References**: [Architecture report, v2](../../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model; `crates/candler/tests/it/guard_cli_e2e/parity_e2e.rs` (`parity_one_installed_server_one_traced_call`, the model to follow); `assets/docker/fakemodel` ## Step 1: The guards diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md index 2e713e14..3246eea5 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md @@ -16,7 +16,7 @@ A reviewer who did not build the milestone finds no gate that passes for the wro ```mermaid graph TD adversarial_review[Adversarial review]:::planned - meet_run_context[Meet run context]:::amendment + meet_run_context[Meet run context]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -28,7 +28,7 @@ graph TD | Node | Type | Status | |:-----|:-----|:-------| | `adversarial_review.md` | 📄 Leaf Task | ⬜ Planned | -| `meet_run_context.md` | 📄 Leaf Task | 🔵 Amendment | +| `meet_run_context.md` | 📄 Leaf Task | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | 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 77403446..677052c4 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 @@ -6,10 +6,11 @@ - [ ] `[cmd]` `git merge-base --is-ancestor feat/run-context origin/main` is checked after `git fetch origin`. If it succeeds, M6d landed first and every gate below applies. If it fails, M6.5 is landing first: record that, mark the gates "owed by M6d", and stop. - [ ] `[nl]` `adversarial_review.md` is `done`, or runs beside this leaf on the same tip **Success Gates**: -- ⬜ `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. -- ⬜ 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. -- ⬜ 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. -- ⬜ `cargo nextest run --workspace` passes on the merged tip, and `docker ps -a` shows none of the leaf's containers. +- ✅ 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. **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 From b09bd933b950a9e00ce8aa4dead88174d378f02b Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:18:47 +0900 Subject: [PATCH 67/69] reports(api): review M6.5 against its gates All 13 gates hold on the tip; none fails. Three small in-scope defects, four debt items, four notes. No test or build was run for the review. Co-Authored-By: Claude Sonnet 5.5 --- __reports__/agent_config/07-review_m6_5_v0.md | 49 +++++++++++++++++++ __reports__/agent_config/README.md | 3 ++ 2 files changed, 52 insertions(+) create mode 100644 __reports__/agent_config/07-review_m6_5_v0.md diff --git a/__reports__/agent_config/07-review_m6_5_v0.md b/__reports__/agent_config/07-review_m6_5_v0.md new file mode 100644 index 00000000..ae929212 --- /dev/null +++ b/__reports__/agent_config/07-review_m6_5_v0.md @@ -0,0 +1,49 @@ +# M6.5 closing review against its gates (v0) + +**Verdict: the milestone holds. All 13 gates hold on the tip, none fails; no defect blocks the merge. Three small items are in scope to fix (F1 to F3), the rest are debt or notes.** Read-only review of `528cfef3` against base `8d82f63b`. No test or build was run; the 767/767 pass and the Docker guards were taken as given. "Absent on base" was read from the diff, not by building the base. + +## Gates + +| Gate | Holds | Evidence on tip | Absent on base | +|---|---|---|---| +| G1 | yes | `guard_agent_config_e2e` (`guard_cli_e2e/agent_config_e2e.rs:277`, `resolve()` at :187, `record["instructions"]`, `["hooks"]` at :334); `inspect_shows_the_mcp_server...` sibling at `guard_inspect_mcp_config.rs:124` | `instructions`, `hooks` not in `CONFIGURATION_PATHS` (`resolve/paths.rs` diff): `unknown_path` | +| G2 | yes | `two_levels_of_instructions_or_hooks_plan_two_cells` (`core/tests/it/guard_agent_config.rs:97`), counts cells and checks a level keeps its digest | same paths unknown | +| G3 | yes | rows at `docs/contract/harness-capabilities.md:51-53,62`, both harnesses Mapped (`claude_code driver.rs` `answer`/`fact`, `opencode driver.rs`); contract_pages guard | no rows, no `AgentSetting::Instructions/Hooks`, no `DriverFact::ConfigCheck` (`spec.rs` diff) | +| G4 | yes | e2e :344-355 (global and own arm present, other arm absent, in `system` or `first_message`); live: report 06 table | no `context_start` kind (`trace.rs` `KnownKind`) | +| G5 | yes | e2e :399-407: the fake model's recorded answer to `toolu_fake_hook` is an error carrying `BLOCKED` on both harnesses, never `hook-not-blocked`. Not exercised live (report 06, deviations) | no `h1` script in `fakemodel.py`, no hook install | +| G6 | yes, on the message | `guard_harness_check_refuses` (:454): invalid payload gives ` rejects it: ` plus the quoted harness text and 0 sealed runs; valid payload seals. Core: `harness_finding_refuses_the_job_before_any_run` (`guard_config_check.rs:365`). Code not read back (O11, filed) | no `check_config` (`orchestrate/config.rs` is new) | +| G7 | yes | e2e :365-377 (exact two entries, scope `user`/`project`, path suffix); `the_census_names_the_instruction_files_the_hook_log_shows` (CC driver guard :757), fixture `census_instructions.jsonl` (OpenCode) | no `census.instructions` (`census.rs` diff) | +| G8 | yes | `misused_hooks_and_instructions_are_refused_by_name` (`guard_agent_config.rs:143`): five cases, code and pointer asserted, incl. `..` path | `unknown_path` | +| G9 | yes, weaker than worded | `workspace_file_is_mounted_read_only_and_is_no_output` (`guard_config_check.rs:537`): mount mode `ReadOnly`, not in `tree.json`, not `input_leak`; e2e :379-397 on real runs. No test makes an agent write to the file, so "a write fails" rests on the Docker `ro` flag (F4) | `Plan` had no `workspace_files` | +| G10 | yes | `planning_refuses_an_input_at_the_workspace_instruction_file` (`guard_agent_config.rs:223`: case, `./`, directory below, near-misses `docs/CLAUDE.md`, `CLAUDE.mdx`, no text); CLI: `guard_instruction_collision.rs:20`. Claude Code only; the `AGENTS.md` side is not exercised | no `InstructionsCollide`, no `input_targets` | +| G11 | yes | e2e :360 (marker in `system` or `first_message`); live: marker in `system` on both harnesses | no event | +| G12 | yes | `trace_context_first_event_is_the_first_request_with_tools_on_both_harnesses` (`guard_trace_context_start.rs:178`: seq 0, equals the gateway line of the lowest tooled seq, ends in `go`); `..._a_trace_stored_without_the_event_still_reads` (:201, round-trips bytes); reader test :227 | no `ContextStart`, no `context` log line (`gw.js` diff) | +| G13 | yes | `06-findings_live_confirmation_v0.md`: 4 runs, both arms, both harnesses, excerpts quoted, `harness_config_check = clean`, `dirty = false` | no event | + +No gate passes for the wrong reason in a way that hides a failure. The oracles are the literal texts the experiment fixes, the gateway's own stored line, and the harness output recorded in fixtures (`PROVENANCE.toml`). The one oracle copied from the implementation is G12's comparison with the gateway line (the gate asks for exactly that). + +## Findings, ranked + +**Defects** +- F1 (in scope, small). `experiment.instructions_collide` always points at `/fixed/instructions.workspace` (`runner/plan.rs`, `refuse_instruction_collision`, `pointer_of(["fixed","instructions.workspace"])`). Architecture v2 says "or the factor's path". Scenario: `instructions.workspace` is a factor (the intended use). The refusal names a pointer that does not exist in the file; the consumer is sent to the wrong place. The guard uses a fixed value, so it cannot see it. +- F2 (in scope, small). OpenCode's `read_config_check` refuses only `level=WARN` lines (`opencode driver.rs`, after `is_drain`). Eliott's ruling is errors and warnings. The narrowing is deliberate (environment `ERROR` lines on valid cells, round 05), but no fixture shows a plugin that fails in `setup()` or a bad hook name, so whether a consumer-file fault ever logs at `ERROR` is unmeasured. A plugin that throws in `setup` and logs `ERROR` would run unchecked. Fix: record that case in a fixture, or state the limit on the capability page. +- F3 (in scope, small). `HARNESS_IDS` (`candler-harness/src/spec.rs`) is a second list of the shipped harnesses beside `crates/candler/src/drivers.rs` `BUILTIN`. A third driver in `BUILTIN` has `hooks.` and `instructions.global.` refused as "names no registered harness" until someone edits the other list. Derive one from the other, or add a guard that they agree. + +**Debt (in scope, small)** +- F4. G9's "a write to it fails" has no test that writes. Add a step to the fake model's `h1` script, or state in the gate that the proof is the mount flag. +- F5. `__reports__/agent_config/06-findings_live_confirmation_v0.md` says "G1's blocked-hook marker" (should be G5). Its `06-live/*.toml` carry `source = /Users/hacker/Documents/tmp/claude-worktrees/Candler/m6_5-scratch/live/treatment`, a scratch path that is deleted, so the two experiments cannot be rerun as kept. +- F6. Stale prose: `__design__/architecture.md:682` (Prepare row: "instructions written into the workspace"; now the global file goes to the home and the workspace file is a read-only mount). Architecture v2 and `installed/proved/e2e_guard.md` name the live report `04-findings_live_confirmation_v0.md`; it is `06-...`. `__reports__/agent_config/README.md` Status first paragraph still says "Level 1 is dispatched". +- F7. `context_start` is placed on the root session only (`gather.rs` `with_context_start`), and the gateway keeps one record per run key. Gate wording, leaf `trace_context` ("every session") and invariant 8 say every session. A Claude Code subagent session has none. Reword the three, or file as an observation. + +**Notes (out of scope, observations)** +- N1. `input_leak` is checked against `cell.inputs` only (`exec/mod.rs`, `input_leak(&evidence, &cell.inputs)`), while the tree is built with the mounted files. An agent that copies the workspace instruction file into its outputs is neither collected under that name nor sealed; the architecture's risk row expected `input_leak`. Low impact, since the text is the arm's own treatment, but the risk row is wrong. +- N2. OpenCode's census reads `Instructions from: ` at line start from the system text, unescaped (documented in `loaded`): an instruction text holding such a line adds a census entry. The consumer writes that text, so only a self-inflicted false entry. +- N3. The gateway log line is 15,500 bytes (CC) and 8,943 (OpenCode) with the fake model; a real system text is larger and Docker splits log lines at 16 KiB. The live run read it whole, so it holds, but the size on the trace page is the fake model's. +- N4. The sidecar image tag now follows the sources (`sidecar_tag`), so each `gw.js` change leaves an older `candler-gateway:src-` image behind. Same as the base image today; no cleanup exists. + +## Consumer breakage checked + +- A refusal blaming the wrong side: a check that printed no report is `jobs.config_check_failed` (environment); a finding is `experiment.harness_rejected_input`. Non-report output on Claude Code still goes out as `Rejected` (O in round 05, filed). +- A value not in the digest: all four values are cell values, so the digest and `inspect` cover them (G2, G1). The check verdict is provenance, not the digest; correct. +- A file collected that should not be: none found. `.claude/settings.json`, `.claude/hooks/*`, home files and the root file are all absent from outputs in the e2e guard (:379). +- A cell a valid experiment cannot express: an arm with no workspace text next to an arm with text cannot omit the key in a factor level; the workaround is an empty string, which mounts an empty root file. Not tested; note for the consumer page. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 1e8e1e67..85e5b49d 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -28,6 +28,9 @@ Instruction files and hooks as per-arm experiment data (M6.5). - [06-findings_live_confirmation_v0.md](06-findings_live_confirmation_v0.md) — **latest** live proof. G13 on RiVault Reasoning-Small, both harnesses, two arms each: every `context_start` holds the global text, its own arm's workspace text and the session-start marker, and never the other arm's text. Claude Code puts the two texts in `first_message` and the marker in `system`; OpenCode puts all three in `system`. The blocking hooks were left out of the live run. - [06-observation_level3_out_of_scope_v0.md](06-observation_level3_out_of_scope_v0.md) — **latest** O11–O15 from level 3: a job-start refusal's code reaches no place a consumer reads (medium); the parity guard's container check compares the whole daemon; the OpenCode plugin API is not on the capability page; `resolve`'s preflight cannot reach the fake model on macOS; two more timing guards fail under load. +### Round 07 +- [07-review_m6_5_v0.md](07-review_m6_5_v0.md) — **latest** closing review of M6.5 against G1–G13: all hold on the tip, none fails. Three small in-scope defects (the collision pointer for a factor, OpenCode's WARN-only check, a second harness id list), four debt items, four notes. + ## Status The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended on 2026-11-25 for two instruction scopes (v1), then for a live, trace-read proof (v2). Level 1 is dispatched, and the probe is done. From 4089b3f4f1a7b8e2ccbd4144d10cccccc082d121 Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Wed, 25 Nov 2026 20:20:43 +0900 Subject: [PATCH 68/69] reports(api): close M6.5 agent configuration The closing review finds G1-G13 holding on the tip. Its findings are disposed in the knowledge transfer: F2 (a plugin that fails in setup might log only at ERROR) is refuted by a run of OpenCode 2.2.7, which logs it at WARN; F5 and F6 are fixed here (a gate named wrong in the live report, experiment files naming a deleted treatment, stale design and status prose); F1 and F7 were already covered; F3 is a notice. Every node of the campaign is done; spend is $109.69 of $125. Co-Authored-By: Claude Opus 5.5 --- __design__/architecture.md | 2 +- .../06-findings_live_confirmation_v0.md | 2 +- .../agent_config/06-live/claude-code.toml | 2 + .../agent_config/06-live/opencode.toml | 2 + .../07-knowledge_transfer_m6_5_v0.md | 56 +++++++++++++++++++ __reports__/agent_config/README.md | 3 +- __roadmap__/m6_5-agent-config/README.md | 12 ++-- .../m6_5-agent-config/installed/README.md | 4 +- .../installed/proved/README.md | 4 +- .../installed/proved/reviewed/README.md | 4 +- .../proved/reviewed/adversarial_review.md | 6 +- 11 files changed, 79 insertions(+), 18 deletions(-) create mode 100644 __reports__/agent_config/07-knowledge_transfer_m6_5_v0.md diff --git a/__design__/architecture.md b/__design__/architecture.md index 84d75f3e..9883341a 100644 --- a/__design__/architecture.md +++ b/__design__/architecture.md @@ -679,7 +679,7 @@ I3, so event times are reproducible even where the harness emits none. | Phase | Needed | Varies between harnesses | |---|---|---| -| Prepare | Model, endpoint, skill or plug-in, MCP servers, permissions and instructions written into the workspace | File names and formats; model ids and provider configuration | +| Prepare | Model, endpoint, skill or plug-in, MCP servers, permissions, and instructions written into the home (global) and mounted read-only in the workspace | File names and formats; model ids and provider configuration | | Confine | An in-harness guard where one exists (Claude Code's PreToolUse hook) | Some have none; the container is then the only boundary | | Launch | Headless command line, environment overlay, working directory | Flags; budget options | | Observe | Live events, normalised; the session ids seen | Streamed on stdout, or kept in a local database | diff --git a/__reports__/agent_config/06-findings_live_confirmation_v0.md b/__reports__/agent_config/06-findings_live_confirmation_v0.md index 28e97238..9d3cbf7f 100644 --- a/__reports__/agent_config/06-findings_live_confirmation_v0.md +++ b/__reports__/agent_config/06-findings_live_confirmation_v0.md @@ -39,7 +39,7 @@ OpenCode, arm B, `system`: `...Instructions from: /work/AGENTS.md\nWORKSPACE_TEX ## Deviations from the deterministic guard -- No blocking hook: the Claude Code `PreToolUse` script and the OpenCode `tool.execute.before` throw were left out, so G1's blocked-hook marker was not exercised live. The session-start hooks and all texts are the guard's values. +- No blocking hook: the Claude Code `PreToolUse` script and the OpenCode `tool.execute.before` throw were left out, so G5's blocked-hook marker was not exercised live. The session-start hooks and all texts are the guard's values. - Real model and a trivial prompt, not the fake model and the shell prompt; `wall_s = 300`; no tool call was asked for. - The guard's two experiments (one per harness) became two files, `claude-code.toml` and `opencode.toml`, run one after the other. They differ only in the hook block and the harness name. - The traces were read as the guard reads them: first event of kind `context_start` in `trace.jsonl`, `system` and `first_message` joined. diff --git a/__reports__/agent_config/06-live/claude-code.toml b/__reports__/agent_config/06-live/claude-code.toml index 5f754af4..f405f930 100644 --- a/__reports__/agent_config/06-live/claude-code.toml +++ b/__reports__/agent_config/06-live/claude-code.toml @@ -29,5 +29,7 @@ wall_s = 300 [treatment] name = "demo" tag = "v1" +# The treatment was a scratch git checkout, deleted after the run. To rerun, point `source` at a +# treatment made as the guard `agent_config_e2e.rs` makes its own. source = "/Users/hacker/Documents/tmp/claude-worktrees/Candler/m6_5-scratch/live/treatment" diff --git a/__reports__/agent_config/06-live/opencode.toml b/__reports__/agent_config/06-live/opencode.toml index 674429b2..7fc1faf2 100644 --- a/__reports__/agent_config/06-live/opencode.toml +++ b/__reports__/agent_config/06-live/opencode.toml @@ -38,5 +38,7 @@ wall_s = 300 [treatment] name = "demo" tag = "v1" +# The treatment was a scratch git checkout, deleted after the run. To rerun, point `source` at a +# treatment made as the guard `agent_config_e2e.rs` makes its own. source = "/Users/hacker/Documents/tmp/claude-worktrees/Candler/m6_5-scratch/live/treatment" diff --git a/__reports__/agent_config/07-knowledge_transfer_m6_5_v0.md b/__reports__/agent_config/07-knowledge_transfer_m6_5_v0.md new file mode 100644 index 00000000..69a9b8b8 --- /dev/null +++ b/__reports__/agent_config/07-knowledge_transfer_m6_5_v0.md @@ -0,0 +1,56 @@ +# M6.5 agent configuration: knowledge transfer (v0) + +Date: 2026-11-25. Branch `feat/m6.5-agent-config`, local only, not pushed. + +## What landed + +Instruction files (a global text per harness, a read-only workspace-root text per arm) and hooks are cell values. Candler installs them, the harness's own check judges them at job start (errors and warnings refuse the cell), and the trace's `context_start` shows what each run started with. All of G1–G13 hold on the tip ([review, round 07](07-review_m6_5_v0.md)); G13 passed live on RiVault ([round 06](06-findings_live_confirmation_v0.md)). + +## Spend, measured from the transcripts + +| Part | Spend | +|---|---| +| Planning and level 1 (probe, declaration, trace context) | $55.40 | +| Level 2 (two installs, preflight check, fakes and seam fixes) | $40.52 | +| Levels 3 and 4 (guard, input-mount fix, live run, review, close) | $13.77 | +| **Total** | **$109.69** | + +The plan estimated about $72 in all, under a cap of $85 that Eliott raised to $125 after level 1. Levels 3 and 4 used four Sonnet agents, the costliest about $3. They worked from closed briefs that named every file and ordered frugality, iterated with check and clippy, and ran Docker and the full suite once. Levels 1 and 2 cost $95.92 against the plan's whole $72. The causes, measured in level 2, are in [round 05](05-observation_level2_out_of_scope_v0.md#process-lessons): filtered gates that let 33 tests go red, a check rule from a reading, stacked review passes, and a long coordinator thread (38 % of spend). + +## Disposition of the review's findings + +| # | Finding | Disposition | +|---|---|---| +| F1 | The collision pointer is always `/fixed/instructions.workspace` | Already filed as O4 (round 05) | +| F2 | OpenCode's check refuses WARN only; a plugin that fails in `setup()` might log at ERROR | Refuted by measurement: two runs of OpenCode 2.2.7 with a plugin that throws in `setup()` log `level=WARN message="failed to load plugin"`, which the check refuses | +| F3 | `HARNESS_IDS` in `candler-harness` repeats the CLI's `BUILTIN` driver list | Notice below: the harness crate cannot see the drivers, so a fix moves the list | +| F4 | No test writes to the workspace instruction file | Accepted: G9 rests on the mount's read-only flag, which the core guard checks | +| F5 | Report 06 said G1 for G5; its experiment files name a deleted treatment | Fixed in the close commit | +| F6 | Stale prose in `architecture.md` and the README status | Fixed in the close commit; the v2 architecture report keeps its old numbering, as reports are not rewritten | +| F7 | `context_start` is on the root session, not every session | Already what the contract page says (`trace-file.md`); only the historical v2 report says "every session" | + +## Wins + +- The trace now proves configuration: a consumer reads `context_start` and sees the exact texts, from the same gateway source on both harnesses. +- The guard found a real defect the unit tests could not see: the check did not mount declared inputs, so an OpenCode MCP server from inputs was refused. +- Rules from measurement settled two questions cheaply: the WARN-only reader (seam review) and F2 (one container run). + +## Pain points + +- A shared build directory ran another worktree's test binaries (round 05). +- Docker-wide container checks fail on a daemon shared with other sessions (O12). +- A job-start refusal loses its code (O11). It is the main gap a consumer meets. + +## Open, for whoever picks it up + +- O11 (medium): one refusal record for every job kind, so `experiment.harness_rejected_input` reaches the consumer. +- O1 (medium): an ignored OpenCode guard broken on main since 8d88cb50. +- `meet_run_context`: owed by M6d, which lands second. +- Notice F3: one list of shipped harness ids, owned where both the reader and the drivers can see it. +- Merging, pushing and the PR wait for Eliott. Then the level 3 worktree and the build slot `m6_5-target/slot-3` can be removed. + +## Next cycle + +- Brief closed scopes from the first dispatch: every file named, whole-suite gates, Docker once. +- One review pass per leaf, plus the milestone's closing review. +- A fresh coordinator per level once the thread is long. diff --git a/__reports__/agent_config/README.md b/__reports__/agent_config/README.md index 85e5b49d..97c3e5b9 100644 --- a/__reports__/agent_config/README.md +++ b/__reports__/agent_config/README.md @@ -30,10 +30,11 @@ Instruction files and hooks as per-arm experiment data (M6.5). ### Round 07 - [07-review_m6_5_v0.md](07-review_m6_5_v0.md) — **latest** closing review of M6.5 against G1–G13: all hold on the tip, none fails. Three small in-scope defects (the collision pointer for a factor, OpenCode's WARN-only check, a second harness id list), four debt items, four notes. +- [07-knowledge_transfer_m6_5_v0.md](07-knowledge_transfer_m6_5_v0.md) — **latest** close of M6.5: spend $109.69 of the $125 cap, by level; the review's findings disposed (F2 refuted by a run, F5 and F6 fixed, F1 and F7 already covered, F3 a notice); what stays open. ## Status -The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended on 2026-11-25 for two instruction scopes (v1), then for a live, trace-read proof (v2). Level 1 is dispatched, and the probe is done. +The plan is approved, and the roadmap [`__roadmap__/m6_5-agent-config/`](../../__roadmap__/m6_5-agent-config/README.md) has been authored. The plan and the roadmap were amended on 2026-11-25 for two instruction scopes (v1), then for a live, trace-read proof (v2). Levels 1 to 3 are done and merged locally; the closing review is round 07. On 2026-11-25 Eliott ruled on the two points that round 03 raised. The roadmap's leaves carry the amended gates: - The proof reads the whole starting context. `context_start` comes from the run's first request that offers tools. G4 and G11 pass when each text is found in its `system` or its `first_message`, since Claude Code puts CLAUDE.md texts and SessionStart output in the first message. diff --git a/__roadmap__/m6_5-agent-config/README.md b/__roadmap__/m6_5-agent-config/README.md index 70464744..4090ac3a 100644 --- a/__roadmap__/m6_5-agent-config/README.md +++ b/__roadmap__/m6_5-agent-config/README.md @@ -12,17 +12,17 @@ A consumer gives the experiment a global instruction file per harness, each arm - [x] `[nl]` Eliott ruled on the HTN lane's notice on 2026-11-25: instructions come in two scopes (a global file per harness, and a workspace-root file per arm on both harnesses), and evaluator access to them is deferred ## Success Gates -- ⬜ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), as the leaves word them after the 2026-11-25 amendments (G1, G4, G8, G11, G12; then G6 and G10, checked at job start and at planning instead of at `resolve`), hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` -- ⬜ `probe_harness_checks.md`, `declaration.md`, `trace_context.md` and `installed/` are `done` -- ⬜ The spend measured from transcripts, coordinator included, is at most $125 -- ⬜ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated +- ✅ G1–G13 of the [architecture report, v2](../../__reports__/agent_config/02-architecture_agent_config_v2.md), as the leaves word them after the 2026-11-25 amendments (G1, G4, G8, G11, G12; then G6 and G10, checked at job start and at planning instead of at `resolve`), hold on the tip of `feat/m6.5-agent-config`, each one seen failing on `8d82f63b` +- ✅ `probe_harness_checks.md`, `declaration.md`, `trace_context.md` and `installed/` are `done` +- ✅ The spend measured from transcripts, coordinator included, is at most $125 +- ✅ Every finding left out of scope is filed under `__reports__/agent_config/` and escalated ## Status ```mermaid graph TD probe_harness_checks[Probe harness checks]:::done declaration[Declaration]:::done - installed[Installed]:::planned + installed[Installed]:::done trace_context[trace_context]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -36,7 +36,7 @@ graph TD |:-----|:-----|:-------| | `probe_harness_checks.md` | 📄 Leaf Task | ✅ Done | | `declaration.md` | 📄 Leaf Task | ✅ Done | -| `installed/` | 📁 Directory | ⬜ Planned | +| `installed/` | 📁 Directory | ✅ Done | | `trace_context.md` | 📄 Leaf Task | ✅ Done | ## Amendment Log diff --git a/__roadmap__/m6_5-agent-config/installed/README.md b/__roadmap__/m6_5-agent-config/installed/README.md index dbb502ef..e0d9a1ee 100644 --- a/__roadmap__/m6_5-agent-config/installed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/README.md @@ -19,7 +19,7 @@ graph TD install_claude_code[Install on Claude Code]:::done install_opencode[Install on OpenCode]:::done preflight_check[Preflight check]:::done - proved[Proved]:::planned + proved[Proved]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -33,7 +33,7 @@ graph TD | `install_claude_code.md` | 📄 Leaf Task | ✅ Done | | `install_opencode.md` | 📄 Leaf Task | ✅ Done | | `preflight_check.md` | 📄 Leaf Task | ✅ Done | -| `proved/` | 📁 Directory | ⬜ Planned | +| `proved/` | 📁 Directory | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/m6_5-agent-config/installed/proved/README.md b/__roadmap__/m6_5-agent-config/installed/proved/README.md index bd4acdbe..ed4e9d7b 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/README.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/README.md @@ -16,7 +16,7 @@ One experiment shows, on both harnesses, the global and the arm's own workspace ```mermaid graph TD e2e_guard[E2E guard]:::done - reviewed[Reviewed]:::planned + reviewed[Reviewed]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a classDef planned fill:#374151,color:#e5e7eb @@ -28,7 +28,7 @@ graph TD | Node | Type | Status | |:-----|:-----|:-------| | `e2e_guard.md` | 📄 Leaf Task | ✅ Done | -| `reviewed/` | 📁 Directory | ⬜ Planned | +| `reviewed/` | 📁 Directory | ✅ Done | ## Amendment Log | ID | Date | Source | Nodes Added | Rationale | diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md index 3246eea5..339a55c5 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/README.md @@ -15,7 +15,7 @@ A reviewer who did not build the milestone finds no gate that passes for the wro ## Status ```mermaid graph TD - adversarial_review[Adversarial review]:::planned + adversarial_review[Adversarial review]:::done meet_run_context[Meet run context]:::done classDef done fill:#166534,color:#bbf7d0 classDef inprogress fill:#854d0e,color:#fef08a @@ -27,7 +27,7 @@ graph TD ## Nodes | Node | Type | Status | |:-----|:-----|:-------| -| `adversarial_review.md` | 📄 Leaf Task | ⬜ Planned | +| `adversarial_review.md` | 📄 Leaf Task | ✅ Done | | `meet_run_context.md` | 📄 Leaf Task | ✅ Done | ## Amendment Log diff --git a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md index f7e481cd..63aa1b57 100644 --- a/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md +++ b/__roadmap__/m6_5-agent-config/installed/proved/reviewed/adversarial_review.md @@ -5,9 +5,9 @@ **Pre-conditions**: - [ ] `[cmd]` `git -C merge-base --is-ancestor feat/m6.5-agent-config HEAD` succeeds **Success Gates**: -- ⬜ `__reports__/agent_config/-review_m6_5_v0.md`, at the next free round after the live findings, names each gate G1–G13 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. -- ⬜ The report lists any debt left behind (a second reader, a duplicated helper, dead code, a leftover script), each fixed in this leaf or filed as a notice. An out-of-scope finding is filed as an observation and escalated. -- ⬜ `__reports__/agent_config/-knowledge_transfer_m6_5_v0.md`, in the same round as the review, records the spend measured per leaf against the $85 cap. +- ✅ `__reports__/agent_config/-review_m6_5_v0.md`, at the next free round after the live findings, names each gate G1–G13 with the evidence that it holds on the tip and failed on `8d82f63b`, or names it as broken. +- ✅ The report lists any debt left behind (a second reader, a duplicated helper, dead code, a leftover script), each fixed in this leaf or filed as a notice. An out-of-scope finding is filed as an observation and escalated. +- ✅ `__reports__/agent_config/-knowledge_transfer_m6_5_v0.md`, in the same round as the review, records the spend measured per leaf against the $85 cap. **References**: [Architecture report, v2](../../../../../__reports__/agent_config/02-architecture_agent_config_v2.md) — the shapes, the error model, the invariants and §Execution model ## Step 1: Review and close From 6c904002012a3424969c2dd667aca8d29a458fcc Mon Sep 17 00:00:00 2001 From: Eliott Jacopin Date: Thu, 26 Nov 2026 01:07:10 +0900 Subject: [PATCH 69/69] fix(api): fix the CI rustdoc and read-only mount guards The public docs of check_config linked the private verdict_bytes, which rustdoc refuses under -D warnings. They now say in prose that a check that did not run is a ConfigCheckError, and name the declared inputs among what groups the cells. The workspace-file guard wrote to the mounted AGENTS.md as the image's own user. On Linux the file mode refuses that write first ("Permission denied"), before the mount's read-only flag, so the guard's "Read-only file system" assertion failed although the write was refused. The probe now runs as root, which no file mode refuses, so only the read-only mount can refuse it, on Linux and macOS alike. Co-Authored-By: Claude Opus 5.5 --- .../src/jobs/orchestrate/config.rs | 8 ++++---- .../it/guard_container_e2e/preflight_e2e.rs | 19 ++++++++++++++++--- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/candler-core/src/jobs/orchestrate/config.rs b/crates/candler-core/src/jobs/orchestrate/config.rs index 9e66ba6f..92dce5d3 100644 --- a/crates/candler-core/src/jobs/orchestrate/config.rs +++ b/crates/candler-core/src/jobs/orchestrate/config.rs @@ -205,12 +205,12 @@ fn installed_at(plan: &Plan) -> (String, String) { } /// Asks the harness's own check about the files Candler installs for each cell of `plans`, once -/// for each distinct harness, image and set of installed files, in a container without network, -/// and records a clean verdict on the cells it covered. A cell whose driver has no check is not -/// checked and keeps no verdict. +/// for each distinct harness, image, set of installed files and set of declared inputs, in a +/// container without network, and records a clean verdict on the cells it covered. A cell whose +/// driver has no check is not checked and keeps no verdict. /// /// The check command's standard output followed by its standard error is the driver's to read, -/// whatever the exit status; see [`verdict_bytes`] for when the check did not run. +/// whatever the exit status. A check that did not run is [`ConfigCheckError`], never a verdict. /// /// # Errors /// [`ConfigCheckError::Driver`] with [`DriverError::HarnessRejectedInput`] when the harness diff --git a/crates/candler-core/tests/it/guard_container_e2e/preflight_e2e.rs b/crates/candler-core/tests/it/guard_container_e2e/preflight_e2e.rs index 8dbceb14..7a5d984b 100644 --- a/crates/candler-core/tests/it/guard_container_e2e/preflight_e2e.rs +++ b/crates/candler-core/tests/it/guard_container_e2e/preflight_e2e.rs @@ -120,7 +120,21 @@ fn workspace_file_reads_and_refuses_a_write_in_docker() { args.push(String::from("--mount")); args.push(mount.to_arg().expect("a mount argument")); } - args.extend(["-w", "/work", "--entrypoint", "sh", image.id(), "-c"].map(String::from)); + // Root is not refused by a file's mode, so only the mount's read-only flag can refuse the + // write. As the image's own user, Linux refuses by mode first ("Permission denied"). + args.extend( + [ + "--user", + "0", + "-w", + "/work", + "--entrypoint", + "sh", + image.id(), + "-c", + ] + .map(String::from), + ); args.push(String::from( "cat AGENTS.md; if echo changed >> AGENTS.md; then echo WRITE-OK; else echo WRITE-DENIED; fi", )); @@ -138,8 +152,7 @@ fn workspace_file_reads_and_refuses_a_write_in_docker() { shown.contains("WRITE-DENIED"), "the write is refused: {shown}" ); - // The blob is not writable by file mode either, so only the engine's own words tell a - // read-only mount from a file that merely refuses the user. + // The write ran as root, so the refusal is the mount's, and the shell says so. let said = String::from_utf8_lossy(&ran.stderr); assert!( said.contains("Read-only file system"),