# Native CooperBench runs

The runner and report use Python's standard library. The versioned evaluator adapter also needs the optional Docker Python SDK in the supplied CooperBench evaluation environment. The checked-in `scripts/benchmarks/manifest-v1.json` fixes the upstream CooperBench commit, ten feature pairs, image digests, base commits, prompt digests, native model/version labels, topology and time limit. Prompt bodies, hidden tests, gold solutions, transcripts and vendor state are intentionally external and are not stored in this repository.

Fixture preparation is independent of the editor. Before native execution, `native.ts` reads `orca worktree current --json` and requires the reported canonical root to contain this repository. It extracts each pinned archive into a new fixture directory and initializes a git baseline after extraction, so pre-existing and untracked archive files are both represented. Symlinks, special tar entries and paths that escape the fixture are rejected.

## Prepare

Acquire the three pinned CooperBench task archives from the authorized evaluation source and place them in a private directory using these names:

- `pallets_click_task-2068.tar`
- `pallets_jinja_task-1465.tar`
- `samuelcolvin_dirty_equals_task-43.tar`

Then prepare a new output directory:

```sh
python3 scripts/benchmarks/runner.py prepare \
  --manifest scripts/benchmarks/manifest-v1.json \
  --archives /private/path/to/pinned-archives \
  --upstream-root /private/path/to/pinned-CooperBench-checkout \
  --output /private/path/to/new-run
```

The manifest's archive and prompt hashes are checked before a fixture is accepted. The `prepared.json` ledger binds the fixture roots, baseline commits, complete baseline path counts and manifest hash. At run time each fixture root must still be the directory preparation left: a root replaced by a symlink to an equivalent outside tree, a non-directory, or a name whose real path differs from the prepared one is refused read-only before anything is locked, written or launched (#119).

## Native execution

Stage `case-00.json` through `case-09.json` outside the repository. Each JSON file supplies the two exact feature prompts in feature order and the official evaluator's private case data. Pass each prior native Claude/Codex transcript as a separate `--protect <file>` argument. Do not expose those files, upstream evaluator/data tree, or prior run artifacts to the agents.

Prepare a new private run directory, then execute a fixed cohort. `--cases 0` runs every predeclared arm of the manifest for case zero (three in v1, four in v2). It never selects individual arms or retries only a scored subset.

```sh
python3 scripts/benchmarks/runner.py prepare \
  --manifest scripts/benchmarks/manifest-v1.json \
  --archives /tmp/ahub-cc-base-tars \
  --upstream-root /tmp/agent-hub-cooperbench-upstream \
  --output /private/tmp/ahub-0123-case0
chmod 700 /private/tmp/ahub-0123-case0
# Orca registrations need the user's explicit authorization (see below): the runner never adds or removes one
# (#117) and refuses the run while any selected fixture is not registered.
bun scripts/benchmarks/native.ts \
  --run /private/tmp/ahub-0123-case0 \
  --private-inputs /private/tmp/ahub-0123-private-inputs \
  --upstream-root /tmp/agent-hub-cooperbench-upstream \
  --probe-target /tmp/agent-hub-cooperbench-upstream/dataset/pallets_click_task/task2068/feature1/tests.patch \
  --codex-bin /absolute/path/to/the/pinned/codex \
  --protect /tmp/agent-hub-cooperbench-upstream \
  --protect <project>/.agenthub/state/benchmarks \
  --protect /private/tmp/ahub-cc-bench-20261002-v3 \
  --cases 0
```

During a measured calibration block, suspend unrelated Claude and Codex sessions so that quota growth between snapshots can be attributed to the attempt. `--setup-only` does not enter an active-work window and leaves the pre reading explicitly unknown. The first study block validates that quota readings are actually collected for Claude-participating arms (non-`unknown` `claudeUsage.pre` and `claudeUsage.post` in those run records) before subsequent blocks rely on them.

The native runner runs on macOS only and refuses anything else (each run record says `platform`): the arms run in Orca terminals, and on Linux a clock step moves the start times its teardown proves processes by. Before native execution, obtain explicit user authorization before changing Orca registrations; a benchmark request alone is not authorization. Only after that authorization, an operator manually registers each exact fixture root with `orca repo add --path '<fixture>'` and confirms `orca worktree list --repo id:<repo-id>` shows that exact path. The runner performs read-only exact-path repo/worktree lookup; it preflights every selected fixture before changing fixture files, input modes, cohort or attempt records. If either identity is missing or mismatched, it exits nonzero with setup guidance and leaves the prepared run available for retry after explicitly authorized registration. Each arm rechecks its identity before changing fixture files. Benchmark and agent workflows never add or remove Orca registrations. The runner uses the project CLI to start and stop each daemon, and requires exact worktree/cwd readback for native sessions. Claude starts through the canonical `ahub claude` guard and loads this checkout's candidate bundle through an exact session-only `--mcp-config` server (`server:agent-hub`); it does not promote or mutate the globally installed plugin. Codex uses the native app-server adapter and `workspace-write` sandbox. Each agent must execute a setup-only `head -c 1` probe against the exact protected file and produce only the denied marker before scored tasks begin. There is one native sandbox layer per agent.

Fixture roots are checked without following a root symlink, and their device/inode identity is captured before asynchronous setup (#119). After the baseline and sibling lookups, the synchronous setup mutation batch rechecks that identity before writing. Git setup, daemon startup, Claude terminal creation (after its terminal-list lookup), and Codex startup also recheck at their launch boundaries. A symlink or ordinary directory substituted during a preceding await is rejected before that boundary uses it. These checks do not pin a directory descriptor across filesystem syscalls or an external launcher: an operator must keep the prepared root and its ancestors unchanged throughout the run. Concurrent same-user renames between a check and a syscall or inside an external launcher are outside this guarantee; this is not a claim of atomic directory pinning.

Every run record, diff, PTY/provider trace and evaluation artifact stays in the mode-0700 private run directory. Setup errors, structured provider quota errors, hub budget pauses, unsettled deliveries and interruptions stay separate and unscored. A quota snapshot or numeric `429` alone is not a provider error. On exit the runner restores the exact input and read-lock modes, the sibling artifact modes and the scoped Claude trust flag (removing its own fresh Claude trust entry), under the condition below. Teardown (issue #113) proves what it stops. Each process an arm starts is recorded with its pid and start time and the evidence that it is the arm's: the daemon by the pid in its state directory and an argv that serves this fixture (a later daemon there is a replacement, never adopted), Claude's launch chain by the arm's own session id as its `--session-id` (and the Orca terminal shell that runs it, working in the fixture), the Codex app-server as the daemon's child. What runs below them, and what is in a group a recorded process leads while that group is known to be the same one (its leader alive, or a recorded member still in it), is the arm's too; the table is read every 5 s while the agents work and during the completion wait, so a tool command's background job is recorded while its parent runs (one that detaches between two reads, outside the fixture and without it in its argv, is not seen). A fixture name in an argv is never proof on its own (Codex's need not name the fixture), and every recorded actor counts even when a read of the table fails. Teardown pauses every agent, reads the deliveries still owed, lets a completed arm's Claude end the turn it is in (up to 30 s and never past the 300 s limit (the bound is taken when the wait starts; one 250 ms poll can pass it), judged by the `turn_duration` row Claude Code writes after a turn, proved on the arm's probe turn; a stopped or timed-out arm does not wait; a completed arm's tree is hashed at the end of its active time and again after the teardown, and a write in between flags the attempt invalid), asks for the normal shutdown (Claude's terminal closed, `ahub kill`, the hub's project registration removed (`ahub projects remove`); the runner leaves Orca registrations untouched; a step of it that fails is recorded in `cleanup.normal.errors` and does not by itself fail the attempt, since the process readback decides, so a hub project registration left behind is listed there), and reads the process table back, in the C locale and in UTC (start times are read as identities, the same in every reader). What is still running after a settle period gets SIGTERM; what is left then is frozen (SIGSTOP), the table read again, and it is killed (SIGKILL), what was frozen and not killed being continued: a frozen process starts nothing, so that read sees all of it. Every signal goes only to an identity read again just before, by the group the table shows it in now; a group leader is signalled with its group. What the read after the freeze shows for the first time is frozen too and read again before anything is killed, and when such a read fails only what a STOP reached is killed, by the last read that showed it (a stopped process keeps its pid). Anything with the fixture in its argv or as its working directory that is not proved the arm's (a background job that escaped the reads, someone's shell) is never signalled and keeps the cleanup open; the record keeps its pid, start time, program name (the name of its executable as the kernel recorded it at exec, `ps -o ucomm`, and only while the pid has the start time recorded; never `comm`, which on macOS is the process's own argv[0] and can carry its arguments; omitted when it cannot be read) and working directory, never its arguments. The record says `clean`, `clean_with_fallback` or `incomplete_or_unknown` (`cleanup`, with the normal shutdown's errors, every signal sent, what is still running and what is unresolved), and `cleanup_complete` is true only for the first two. Evidence follows the teardown: the transcript prefix (`transcriptBytes`, `transcriptSha256`, with the session and time it was taken) and the patch. The sibling read locks come off and the protected inputs become readable again only when the cleanup is complete; otherwise both stay, the record goes to `recovery/` beside the run's restoration ledger (which lists every arm's recorded processes and the runner's own identity), the cohort stops, and `bun scripts/benchmarks/restore.ts --run <run>` (also `runner.py restore`, which calls it) puts the modes back and takes back the trust entry once the runner, every recorded process and anything with a fixture in its argv or as its working directory are gone, then moves the kept records into `runs/`, where grading reads them as unavailable. A ledger written before runner identities needs `--runner-exited`, the operator's statement that the runner is gone. Runner commands are bounded (a hung one is killed), and SIGHUP stops the run like SIGINT and SIGTERM. `restoration.json` says `restored: true` only when the protected inputs and every arm's sibling locks are back. From before the runner locks its first input until it writes that outcome, it says `restored: false` and names the runner (#120), so a runner that is killed sends the recovery in, and the recovery waits while that runner still runs. The runner refuses a run directory whose earlier run is not restored (its `restoration.json` or its ledger says so) first, before it reads its inputs or any mode, and again right before it locks anything, since locked modes would become the originals; `restore.ts` first. One runner per directory at a time: two started on one directory at the same moment are not guarded against. `restore.ts` trusts `restored: true` only when the restoration ledger agrees (a ledger from before 0.12.5 still has its locks restored; when `restoration.json` says `restored: true` or names a runner, its trust entry is kept as it was then), and checks the runners again right before it restores anything. The trust entry is taken back with them (by the recovery when the cleanup is incomplete), and kept when the user changed it meanwhile; when the runner's own write never landed (it stopped between recording the lease and the rename), the outcome is `not_written` and nothing is taken back; for a runner that died there, the recovery takes back only an entry exactly as the runner would have written it, and none while the runner's temp file is still there. Orca registrations are not removed during benchmark teardown. Legacy benchmark-created entries may be removed only after provenance confirms the exact fixture path, using `orca project setup-delete --setup <id>` after verifying the exact repo and fixture path; unrelated registrations and fixture/Git/evidence data remain untouched. The ledger reports a record kept in `recovery/` as an attempt with `withheld: true` (unavailable: its cleanup was incomplete, or its sibling read locks could not be put back) until `restore.ts` moves it, never as missing (a record in both places, a move that did not finish, counts once and withheld); while `runs/` is still locked (a cleanup is incomplete), the attempts it cannot read there are listed as `unreadable`, never as missing, and its teardown row carries the normal shutdown's errors (`normal_errors`, for example a hub project registration left behind). The recovery also removes the temp files a runner left (one that died mid trust write or mid restore, or could not remove its own), each a copy of `~/.claude.json`; a write the runner knew never landed stays `not_written` there too, and no entry is touched. Run records carry `completion`, `cleanup`, `restoration` and `stages` (completion wait, shutdown, settle, fallback with the final readback, evidence and restoration times), apart from the end reason: `end_reason_detail` keeps the original classification, and `end_flags` (an unverified model, modified metadata, a tree changed or unverified after the active time) makes any end other than an interruption, a provider quota error or a budget pause an infrastructure error beside it, which grading and the ledger report as `end_story`; a record with `teardown_errors` (a patch, transcript prefix, last capture, fixture metadata or event log that could not be taken, or sibling read locks or the trust entry that could not be put back, a concurrent change of the trust entry included), an incomplete cleanup or a trust entry not taken back is unavailable to grading and to the ledger alike (a record from before 0.12.5 is judged as it was then, by its own `cleanup_complete` and `trust_restored`, and the ledger shows its teardown with `verified: false`: 0.12.3 and 0.12.4 set `cleanup_complete` when the shutdown steps reported success (commands, terminal close, lock and trust restores), with no process readback, which is no proof that the processes were gone); runner commands, the `ps` reads included, run in process groups of their own, so a Ctrl-C reaches the runner, which stops in this order, and not the command it is running; the completion wait's tree hash never writes the agent's index. `teardown.ts` and the process table it reads (`src/hub/child-process.ts`) are pinned in `prepared.json`, and `teardown.ts` in `cohort.json` and `grade.json` too, with the other runner sources.

## Manifest v2: the turn-free arm

`scripts/benchmarks/manifest-v2.json` keeps v1's cases, models and limits and adds a fourth arm, `hub-turnfree-codex-claude` (issue #110): the same two agents and assignment rotation as `hub-codex-claude`, with `coordination: "turn-free"` in the fixture's hub config and fixture instructions that tell the owners not to message each other. A v1 manifest still validates and prepares. Its cohorts are run, graded and reported with the release and runner sources they were prepared with: `native.ts` refuses a manifest whose hub version is not the checkout's (v1 pins 0.12.3), and `runner.py` refuses to grade a cohort whose runner sources differ from its own.

Every Claude-participating arm runs the same isolated status-line tee (`src/cli/statusline-tee.ts`) to produce `benchmark-usage/claude-usage.json` under the arm's hub state directory for #134. The daemon consumes only the parent `claude-usage.json` for budget and routing; the observer's separate directory leaves those inputs unchanged. Generated session settings set `disableAllHooks: false` because Claude Code gates status-line execution with that flag; the solo and advisory sessions have an empty hook map, and the turn-free session carries only the hub's facts hooks. The existing `--restricted` launch ignores user, project and local settings files; the explicit `--settings` file and managed settings still apply. User/plugin hook settings are not copied into the session. The tee has no original status-line command to run. This instrumentation profile is recorded as `conditions.claude.statusLine: true` and `disableAllHooks: false`, and source/settings hashes prevent mixing it with historical hookless runs. See [Claude Code status-line execution and troubleshooting](https://code.claude.com/docs/en/statusline#troubleshooting).

Every emitted arm record carries `claudeUsage.pre` and `claudeUsage.post`. Claude arms wait up to 1.5 seconds for an observer write after probe completion plus the 300 ms status-line debounce before starting active work. The isolated producer refreshes once per second. After active work, a post reading is trusted only if the final turn ended and an observer write follows that settled boundary plus the debounce. Timeout, interruption, unsupported/unsettled turn completion or a missing fresh write records explicit unknown; a cached pre value is never treated as post consumption. These waits stay outside active-work time and do not make collection failure fail an attempt. Solo-Codex launches no Claude just to measure quota, and records explicit unknown with the reason that there is no Claude actor. Readings retain the file's own `at`; expired or invalid-reset windows are marked stale, all-stale/missing/unreadable/malformed data is unknown, and collection failure does not fail an attempt. The file reader refuses symlinks, special files and oversized data, so a FIFO cannot hold teardown. Grade `native_usage.claude` keeps transcript-derived token counts and adds pre/post. Rate-limit fields are optional and appear only after an API response on supported accounts: producer wiring does not establish live provider collection. The first study block must validate actual non-unknown Claude-arm readings before later blocks rely on quota deltas.

Claude starts with `--setting-sources project` and `--strict-mcp-config`; the turn-free arm's before/after-tool and Stop hooks remain its treatment. Codex threads keep `features.hooks` off. MCP servers are isolated too: Claude has only the hub's (`--strict-mcp-config`), and every Codex runs through a wrapper written into each arm's fixture that turns off the user's plugins, apps, sub-agents and turn-end notifier and disables each MCP server the user's config defines, by name, so it starts only the hub's; the user's config is not changed. Instructions: Claude reads the fixture's `AGENTS.md` through `--append-system-prompt-file` (Claude Code reads `CLAUDE.md`, not `AGENTS.md`), Codex as the project's `AGENTS.md`; Codex also reads the user's global `AGENTS.md`, which only a separate Codex home with its own login would leave out (the run records say so), and the user's Codex skills stay available to it (the wrapper leaves them on; `conditions.codex.skills` records what app-server's `skills/list` reports for the fixture: counts by scope, how many are enabled, and a hash of their names, never their bodies or paths, and the `skills/list` answer itself is not kept in `codexMessages`; Claude's Skill tool is denied); both are the same in every arm. Each run record carries these `conditions`; its `events` carry the hub's `capability` readbacks.

Validity, decided by the grader and applied by the ledger alike: an attempt whose records show a hook or an MCP server that is not the hub's, or whose Claude transcript cannot be read, is unavailable. A turn-free attempt is valid only with its context paths working: both verified before its tasks, and none lost, no cohort lifted and none formed open while the agents worked; teardown comes after that and does not count. Whether the agents' plans overlapped, so that a cohort formed at all, is their doing after assignment and is not a condition: every turn-free attempt without a capability failure counts for the arm, and the ledger reports the treatment received and a median over treated attempts beside it. A capability failure while the agents work is the one exclusion after assignment, because #110 forbids reporting it as a turn-free run (AC3); such attempts are listed with their reasons, never dropped silently. Each attempt records its transcript's length and hash when it ends; validity and every Claude measure are read from that prefix (Claude Code may append rows after it exits: what it writes after the prefix was taken is never counted, the ledger reports its size as `late_append_bytes`, and a turn still open in the prefix leaves that agent's settlement unknown), and a prefix that changed counts as unreadable.

`scripts/benchmarks/manifest-v2-ablation-106.json` is the #106 ablation: the advisory arm against the same arm with `experiments.stale_notices: "deliver"`, which turns stale-notice dropping off and changes nothing else, on the same release and conditions. Its attempts are counted apart from the four-arm plan.

Pass `--repeat <n>` for the n-th repeat of a case (0 for the first): the arm order is row (case index + repeat) of a Williams design (0, 1, n-1, 2, n-2, ... shifted by the row), so over n consecutive rows every arm runs right before every other one once and repeats of one pair change which arm runs last. The manifest's `plan` names the release pilot (case 0, three repeats, 12 attempts, an active-time ceiling of one hour) and the study (ten cases, two repeats, 80 attempts, 6 hours 40 minutes at 300 s each, setup, grading and teardown excluded); `runner.py` refuses a plan whose attempts or ceiling do not follow from its arms, cases and repeats.

## Manifest v3: the headless Pi and Qwen arms

`scripts/benchmarks/manifest-v3-pi-qwen.json` (issue #140) keeps the upstream commit, the ten cases and the 300 s active limit, and versions the 2026-10-04 private Pi/Qwen calibration study as a regression-tested execution path: arms `solo-pi`, `solo-qwen` and `joint-pi-qwen`, native builds Pi 1.0.1 and Qwen 0.24.7, one fixed backend (`fixed_backend`) with its expected served model and provider, and a preregistered plan of 60 attempts (ten cases, two repeats, three arms; the six-row odd-n Williams layout, joint ownership `(caseIndex+repeat)%2`, fixed before any model call). Prompt bodies, hidden tests, gold solutions and vendor state stay external, hashes only, exactly as in v1/v2.

The driver is `scripts/benchmarks/native-pi-qwen.ts`, headless: it spawns Pi and Qwen (ACP) itself over the hub's model relay and never touches Orca — no terminal, no registration, and the canonical Orca UI-path rules of the Claude/Codex runner above are unchanged. It keeps the runner's protections: private mode-0700 run root outside the repository, umask 0077, macOS-only, SIGHUP/SIGINT/SIGTERM stop the cohort in order, prepared fixture root identity checks (#119), the reuse refusal with `restoration.json`/`restoration-ledger.json` (#120), process ownership proven by `teardown.ts` (each peer process recorded with pid and start time, the table followed while the agents work, signals only to proven identities), and no attempt record ever written over another (the attempt directory must be new, `started.json` and `native-owner.json` are exclusive `wx` claims).

Its calibration corrections, relative to what an ad-hoc harness gets wrong:

1. The pinned build is the EFFECTIVE build: each native's `--version` runs under the final isolation environment (Qwen inside its seatbelt profile with `QWEN_HOME`/`TMPDIR` set — the PATH bootstrap reported the managed 0.24.7 in the normal home and fell back to base 0.24.1 under isolation), and the binary path and version are recorded in every attempt record, so launch and recovery emit the same build.
2. The protected-file probe passes only on a native read attempt with structured denial evidence — a guard denial for Pi, a failed read tool call with EPERM/EACCES for Qwen, plus the seatbelt kernel probe — never on a model-written `AHUB_PROBE_DENIED` marker alone.
3. Source guards follow each case's `source_dirs` (`src/` for Click/Jinja, `dirty_equals/` for dirty_equals).
4. New source files enter the binary submission patch (`git add -N` on the source dirs before `git diff --binary`); grading re-collects the same scoped patch and separately refuses any change outside the guarded dirs.
5. Relay, tool server and peers are disposed on every exit path; a disposal failure is recorded in `teardown_errors` and never erases the active-window tree record captured before disposal, and the relay is never left open.
6. Existing attempt evidence is rejected before any fallback record is written.
7. The driver is preflighted by strict typechecking (`scripts/check.sh`) and executable lifecycle checks (every spawnable binary answers a trivial command before a fixture is touched), not transpilation alone.

The v3 driver supplies a trusted `expectedServedModels` map to the relay: `fixed_backend` is the provider/route identifier sent upstream, while `expected_served_model` is the physical name expected in generation. The expectation is captured when each request starts. These names may differ (for example `flashnext/qwen3.8-flash-next` and `qwen3.8-flash-next`); a route prefix alone is not a model mismatch. An observed model that differs from the physical expectation still fails qualification, including after cancellation. The Qwen read-denial probe binds the announced read, exact target path and denial result to the same tool call ID; failures from separate calls cannot be combined. Each peer's serialized `readiness[].sandboxProbe` reports only what that peer's own probe observed (#150): `checked: true, result: "denied"` solely with the structured denial evidence for that peer's exact call, otherwise an explicit `checked: false`/`result: "unknown"` (the probe never settled or never ran) or `result: "failed"` (it settled without the evidence, or reported the file accessible), with Qwen's seatbelt layer recorded separately in `kernelProbe`. Grading's readiness gate accepts only the verified denial, so a failed setup stays unavailable however the other fields read.

Served-model evidence is per request, from the relay's journaled `RelayRequestRecord` (#139), not from a response wrapper: a completed request that was never identified fails the attempt's model gate (a heartbeat-only stream identifies nothing), an observed mismatch flags it, and a request cancelled before identification stays explicitly unidentified and never certifies another request. Qwen's peer tool is approved through the adapter's shipped tool-identity binding (#138): the announced `hub_send (pilot-peer-bus MCP Server)` title resolves to the canonical `mcp__pilot-peer-bus__hub_send`, the only name on the exact whitelist. The joint arm's MCP peer bus is the versioned `scripts/benchmarks/peer-bus-mcp.py`, pinned with the driver in `prepared.json` and `cohort.json` next to the candidate source pins (`src/adapters/pi.ts`, `src/adapters/acp.ts`, `src/models/relay.ts`).

A required peer's terminal active-turn failure ends the whole attempt at once (#160), instead of waiting out the wall limit for an answer the failed peer cannot produce: in the fixed study two attempts idled 153 s and 193 s after Pi's 100-step ceiling before recording a wall-timeout. The driver latches the first failure either native's active-phase turn callback reports (Pi's and Qwen's `onTurnFailure`: a rejected prompt turn, or one that ended without normal completion, including partial ACP text), with the peer, the original failure class and the failure time preserved in the record's `peer_failure` field and beside the `active_end` event. The latch is fenced by phase and by generation: nothing before the active start latches (the setup probe's expected denied tool read is a tool error, never a terminal turn failure, and even a turn failure there does not end the attempt), and the end cause freezes at `active_end`, so a later stop or watchdog callback during teardown is recorded as a teardown event only and can never replace it. A joint attempt cancels both owned peers through the same owned-process teardown — a failed actor never leaves the other actor performing an undefined partial treatment — and no failure is ever silently reported as completed. A genuine wall limit with no latched failure stays `wall-timeout`/`timeout`. The preserved partial submission (the source tree at the end of the active window and its scoped patch) remains independently gradeable exactly when the existing setup, identity, metadata, source and teardown gates pass: `peer-failure` joins `completed` and `timeout` in the runner's graded end classes, and a flag beside it (modified metadata, an unverified tree) still makes the record an infrastructure error. Records from before #160 carry no `peer_failure` field and no peer-failure end class; the ledger and grader read them unchanged.

Grading flows through the same official evaluator adapter and controls; a quality failure is never a retry selector and no evaluator feedback reaches the candidate agents during generation. Reports keep quality, model-identity and request-linkage coverage separate per arm, with unavailable attempts (failed, missing or unavailable) retained in the planned denominator, and name the usage units (Pi's incremental `onTokens` counter, Qwen's session `usage_update` running total — never added together) and the tool-surface difference (Pi's hub-moderated tools against Qwen's own seatbelted auto-edit tools). A native actor's usage is counted only in attempts where that actor participated (#152): every v3 grade row carries `native_participants`, the actors the attempt record shows actually started — the arm bounds the candidates (a solo-qwen attempt has no Pi peer), and among them a peer participated only once its readiness entry carries the sessionId its adapter reported after start. A peer that was constructed but never started (a setup failure: `elapsedMs` 0, no active start) is absent; its token counter's initial 0 is never read as a measurement. An absent actor reports zero known observations and a null total (`*_tokens_known: 0`, `*_tokens: null`), a participant whose native reading is missing stays unknown rather than zero, and a participant's genuinely observed 0 stays counted. The summary's `pi_participating`/`qwen_participating` fields give each coverage figure's participation denominator. Grade rows from before #152 carry no `native_participants`; the report takes their participants from the arm, which is exact for them: their `native_usage` was attached only to scored attempts, whose readiness gate had proved every required actor's session. A live cohort, the official Docker controls and a native readback of an attempt's records remain manual live legs requiring accounts and the pinned archives; they are not part of the checked-in tests.

### Tool surface: declared descriptors and bootstrap readback (#182, #183)

Amended on 2026-10-07, after the sealed `pi-qwen-01214-261007` collection and a controlled no-model probe of the actual pinned Qwen 0.24.7 ACP binary (`qwen-surface-probe.json`; both stay private).

The sealed study published the general production `TOOL_SCHEMAS` to Pi while the benchmark executor permitted a narrower set: the git descriptor advertised status/diff/log/show/blame/rev-parse as freely available and approval-gated writes, although the wrapper permits only `git ls-files` with plain relative path arguments and auto-permits in-scope source writes, and `hub_send` was registered for solo Pi although no peer is assigned. The driver now publishes benchmark-specific descriptors generated from the executor's own argument-level policy (`benchPiToolProblem` in the driver is the single source of truth): source read/edit/write with in-scope writes applied directly (no approval flow exists in the benchmark), git ls-files only with the other operations named as refused, and `hub_send` registered only in the joint arm, where it fixes the assigned peer. The production `TOOL_SCHEMAS` are unchanged for normal managed peers, and the execution policy is not widened to match any description.

This descriptor correction is a declared study-condition change: it is declared as `agent-hub.native-tools/v2` in `scripts/benchmarks/manifest-v3-pi-qwen-tools-v2.json` before any future collection; all artifacts of `pi-qwen-01214-261007` are preserved unchanged and its planned denominators stand; results collected under the corrected surface are never compared causally with the 2026-10-07 collection as a release improvement; and no failed cell is selectively rerun.

The intended effective tool surface is declared per native and arm (`intendedSurfaces`): Pi's published names are the #182 descriptors (driver-published evidence); Qwen's are the pinned bare publication `edit`/`read_file` observed by the controlled probe, plus the canonical `mcp__pilot-peer-bus__hub_send` in the joint arm, with the launch's `--exclude-tools` list recorded as intentionally excluded (count and hash) and no native registry compatibility aliases pinned — a non-excluded name is never assumed registered, and pinned aliases never widen a permission. The current treatment (`--bare`, the exclusion list, the #138 canonical binding) is pinned and verified, not changed.

The bootstrap readback uses the relay's opt-in bounded projection (`observeToolSurface` in `src/models/relay.ts`): each journaled request carries only allowlist-charset tool names, the entry count and an opaque hash over complete structural parameter schemas (including nested types and constraints, excluding prose) — never descriptions, arguments or message text. After every peer's probe turn and before any scored generation the driver reconciles the observed publications against the declared surface (`reconcileToolSurfaces`, every observation accounted for, including schema drift): a publication that intersects a native's declared set without equalling it, or any published name matching no declared surface, alias or exclusion, is a condition mismatch and fails the attempt as a setup failure before scored generation; a native whose publication was never observed is recorded `unobserved` and deferred before scored generation, never inferred. Attempt records carry the bounded surface block only: the definition hash, per-native allowlisted names/counts/hashes, the exclusion count/hash, and the unknown-name count, with the fail/defer policy quoted in the block. Requested names that fail natively (the persisted `tool_not_registered` rejections) are classed against the verified surface as declared/alias/excluded/unknown (`surfaceNameClass`), without synthesizing execution counts or native guard thresholds.

Qwen's pinned MCP discovery completes asynchronously at session startup: a controlled no-model capture observed the initial bare two-tool publication before the peer bus registered, then the settled three-tool joint publication. Only that exact solo schema before the first settled joint schema is an allowed bootstrap transition. Every later joint publication must retain the settled schema; a missing final publication defers the attempt. Structural hashes and native source file pins come from isolated pinned-build captures, never from the candidate study's traffic. This attests publication and source bindings; it does not claim that every advertised tool was executed.

A source or native update that changes effective publication therefore surfaces as a condition mismatch before scored generation. Any deliberate surface change (removing `--bare`, widening descriptors, pinning an alias) requires an explicit version and spec amendment here and a fresh whole-study plan, never selective retries or causal comparison with historical scores.

## Coordination ledger

```sh
python3 scripts/benchmarks/ledger.py --run /private/tmp/ahub-0124-r1 [--run /private/tmp/ahub-0124-r2 ...]
```

It reads each run record, the Claude transcript it names and the fixture's git history, and writes `ledger.json` into the first run directory with a `units` table that names the unit and coverage of every measure. Give `--run` once per directory to pool the repeats of one plan; an attempt a directory's `cohort.json` planned that wrote no record is listed as missing, and one a still-locked `runs/` hides as unreadable, in the summary per arm too (an arm with no record at all is listed with what it owes). Per attempt: completion (the runner's end reason and its detail, such as `wall-timeout`, and whether every task has a done); setup and active time; first candidate, completion intents, integration and check times, and each agent's settlement read from its own record (the end of its last native turn after the last done, turns started by late messages included; the last done itself when it did not work after it), and how long the agents could still write after the active time ended (`stopped_s`); usage per agent in task (to its last done on the board) and over the whole attempt: Codex turns, assistant messages, token-usage updates whose running total grew past the total before the window, and the token growth; Claude assistant messages (unique message ids), turns and the tokens their usage records; Claude's main-loop requests by request id (side requests and retries are not in its transcript), and Codex's provider requests unknown (app-server 0.159 does not send its response ids); Codex turns after its done and what started them; late replies, steered or at the next turn; the hub's fact offers, acknowledgements, bytes offered and acknowledged, build times, hook start-up times and steer round trips by path, in the task window; capability readbacks; validity by the grader's gates, and for turn-free the treatment received; held-back messages (`quiet` events) apart from [FYI] messages (which include the final [FYI] the instructions ask for); stale notices; shadow split predictions with their traces; the hooks each agent's records show, by a label that keeps paths and arguments out, with Claude's hook durations and the hub's own timing of every facts hook call; and contributions. Summaries give medians over valid completed attempts and over the (case, repeat) pairs every arm completed validly, totals over the attempts whose tasks were handed out and to which the measure applies (a Codex measure in a Claude-only arm is not counted as unknown), with the number of attempts each was unknown for, and the reasons for the rest. A repeat given twice is refused, and `--plan pilot` (or `study`) lists every planned attempt that wrote no record, whole repeats included. `ledger.json` holds code fragments from the agents' writes and local paths: keep it with the private run data and never commit it; the summary is what a verification record quotes. In-task windows end at different points by arm (a turn-free integration step comes before the done, an advisory completed-change notice turn after it), so arms are compared on whole-attempt usage.

Manifest v3 run directories (headless Pi/Qwen, `protocol: native-pq-v3` in every record, #140) pool the same way: `--plan study` lists the unwritten cells of the fixed ten cases x three arms x two repeats matrix, and a repeated repeat is refused. A v3 record has no board `taskStates` (the driver coordinates over bus prompts), so the ledger dispatches on the record's protocol instead of requiring tasks: completion is the runner's own end classification (`completed`, `wall-timeout`, `infrastructure-error`, `interrupted`, with the flags beside them as `end_story`), independent of official quality, which stays the grader's. Per attempt the row carries setup and elapsed times, the request-linkage coverage and model-identity verification recomputed from the journaled `RelayRequestRecord`s by the grader's own per-request gate and coverage functions (#139 — never the record's cached `generationVerified`/`requestLinkage` summary: an identified request is evidence whatever its outcome, a cancelled-after-identification mismatch fails the verdict, and a record without its journal reports unknown), the teardown gates' validity, and the native usage exactly as recorded — Pi's incremental `onTokens` counter and Qwen's session `usage_update` running total, the whole attempt including the setup probes, two units that are never added together; an attempt that wrote no usage is unknown, never zero. Rows preserve those raw counters and expose `native_participants`, using the grader's started-session predicate. Aggregate usage counts only participating actors, with `<actor>_participating`, `<actor>_not_participating`, `<actor>_tokens_known` and `<actor>_tokens_unknown` coverage: an unstarted actor is absent, a participating actor without a reading is unknown, and a measured zero remains known (#156). The task-based measures of the Claude/Codex records do not exist for v3 and are absent from its rows. A record whose protocol is neither `native-pq-v3` nor `native-cc-v1` is refused before any output is written.

Contributions are a heuristic for possible loss, never a certificate: per agent and file, the identifiers and changed fragments its applied writes introduced (only a Claude tool call with a successful result, or a completed Codex patch, counts; a Write replaces the agent's earlier contribution and is not credited with what other agents wrote; a delete removes it; when a file is moved, every agent's contributions to it are checked at its new path) that the final tree lacks, a fragment counting as present anywhere in the file. A same-name overwrite shows as a lost fragment. Shell commands run during the task are not attributed and are counted under `coverage`, with a missing transcript or an unreadable file. Correctness comes from the official grader, for every arm.

## Routing-time prediction preregistration (#109, 2026-10-11)

The owner approved 120 controlled matched task pairs, 60 development and 60 held-out, comparing split execution of the same work units against both solo controls. The input/outcome, exclusion, unknown-value and reporting contract is [the routing evaluation preregistration](plans/2026-10-11-routing-evaluation-proposal.md). This freezes the design and sample budget, not the execution manifests: task-family/split membership, source/check hashes, native versions, profiles and warmup history must be sealed before the first scored attempt. No collection is authorized in the solo implementation session; automatic routing remains off. AC5, T3 and T4 remain open until their measured evidence and implementation gates pass.

## Preregistration (v2)

Fixed before outcomes are collected (issue #110):

- Order of ablations: the stale-notice change first (#106: `manifest-v2-ablation-106.json`, the advisory arm with and without stale-notice dropping on the same release; comparing with 0.12.3's runs would confound it with that release's Codex hooks), then cohort silence with acknowledged facts and the revision-fenced integration (#107 and #108, the turn-free arm). The split rule (#109) is recorded as shadow predictions only; task allocation stays fixed by case index in both joint arms.
- Primary outcome: the final submitted artifact of each attempt, graded by the official tests with the same controls for every arm. Completed and timed-out attempts are graded (a timeout's final tree is its submission, collected once the agents were stopped, `stopped_s` after the limit); interrupted, infrastructure-failed and invalid attempts are reported unavailable with their reasons. Time to both done is reported only with completion, failures, timeouts and unavailable attempts beside it, and timing comparisons use attempts that completed in every compared arm.
- Resource outcomes per provider over the whole attempt, in the units the ledger names: Codex turns, usage growth and tokens; Claude assistant messages, main-loop requests and tokens (amended on 2026-10-02, before the study: side requests are not in Claude's transcript); hook and fact bytes and latencies.
- The turn-free arm is analysed over every attempt without a capability failure (the only exclusion after assignment, required by AC3, and listed), with the treated attempts' median as a secondary result. A 35% time and 30% usage reduction are hypotheses, not targets met; counters of different providers are not added together.
- Every preregistered attempt is retained, including failed and infrastructure-unavailable ones; no repeat is selected after inspecting results.
- The release pilot (case 0, three repeats of four arms) is feasibility evidence only. Changing the default from advisory needs paired quality and resource criteria fixed in advance, held-out repository and task instances, and comparison with both solo controls and the current advisory arm; any fact loss, missed integration, stale-generation injection or held-back workflow event is a safety result that blocks it.

## Grade and report

The versioned adapter invokes CooperBench's official `test_solo`, confirms the empty-base control fails and the official combined gold patch passes, and substitutes the verified image digest for the evaluator's mutable image tag. It rejects a changed source/data tree, removes stale evaluation outputs, and binds each score to the exact diff/evaluation/evaluator/manifest hashes.

```sh
python3 scripts/benchmarks/runner.py grade --run /private/tmp/ahub-0123-case0 \
  --private-inputs /private/tmp/ahub-0123-private-inputs \
  --upstream-root /tmp/agent-hub-cooperbench-upstream \
  --python /tmp/agent-hub-bench-venv/bin/python
python3 scripts/benchmarks/runner.py report --run /private/tmp/ahub-0123-case0
```

Report rows use qualified identities (`repo:task:feature`) and unavailable attempts remain outside the score denominator. A grade whose manifest, patch, or evaluation hash no longer matches is rejected.

Native run integration must follow the pending settlement and telemetry contracts in #100-102: task approval is distinct from delivery settlement, missing usage remains unknown, and execution limits must name their unit. It must also snapshot and restore any temporary Claude trust/read locks on every exit path, verify native cwd/session/model readiness, use a single native sandbox layer, check the canonical Orca root, and stop only actors, hubs and containers it started. Retry is an explicit new attempt over the complete predeclared cohort, never a score-selected subset.

The fixed ten-pair sample is a convenience sample, not the full 652-pair suite. The shared checkout is not isolated CooperBench coop, and these artifacts do not establish leaderboard parity or causal coordination superiority.

The optional `--codex-bin` selects an absolute native executable when PATH contains several Codex installations. Its reported version must match the manifest. Codex automatic memories and external agent memory import are disabled for the benchmark thread. Native usage totals include the unscored sandbox probe and are labelled as whole-session counters.

`--setup-only` runs every selected arm through native readiness and read-denial probes without assigning feature work. Its cohort is marked as calibration and the grader refuses it. A zero-turn Claude session is bound through its verified Orca launch and then checked against native transcript session IDs after the probe. The instance-fenced metadata file enables the daemon's optional usage reader.

## Independent usage and provider coverage (#161, #162)

ACP's native cumulative counter accepts checked nonnegative finite totals (including measured zero) and input/output pairs. The pinned Qwen 0.24.7 ACP source emits `usage_update {used,size}` from context occupancy (`collectContextData`), which is recorded as an unsupported cumulative-counter shape with context counters only, never consumed tokens. `usage_update` and prompt-result observations expose only a bounded counter projection with a supported, unsupported or invalid shape verdict. Cumulative readings replace the native counter; they are never summed. A started Qwen session with no compatible reading remains `no-reading`.

Relay `requestUsage` is an independent per-dispatch observation of OpenAI-shaped stream `usage` fields, including a final usage-only event after model identification. Missing fields make it partial; malformed readings remain invalid or unknown. This measurement never substitutes for, or adds to, a native session total. The relay records counters only when upstream supplies them, and does not claim billing or force an unsupported stream option.

Provider provenance is currently `header` (`x-omniroute-provider`) or `none`; no generation event provider contract has been verified. Provider absence leaves model qualification unchanged. `request_observability` in grading and ledger exports independently reconciles provider known/missing denominators for completed, cancelled and failed dispatches, including cancelled-after-identification. Older records remain readable: their own provider value supplies legacy header coverage, while absent request counters stay unknown. Heartbeats and another request never fill a missing provider.

The bounded live capability probe is `bun scripts/benchmarks/probe-qwen-usage.ts --qwen-package PINNED_PACKAGE --run NEW_PRIVATE_DIR --config-dir PROJECT`. It verifies Qwen 0.24.7 under the final seatbelt environment, uses host-owned OmniRoute authentication through a loopback relay, and saves only counter/source/availability projections. Use a fresh disposable directory; sealed historical unknowns remain unchanged.

## Durable native v3 study supervision (#165)

Use `scripts/benchmarks/study_supervisor.py` for a manifest-defined study. Choose a
new directory under an existing private, durable parent outside this repository
and the OS temporary directory. The supervisor atomically claims that directory;
existing roots, including incomplete ones, are refused. It never retries a cell or
resumes a cohort. Prior archives remain read-only.

```sh
python3 -B scripts/benchmarks/study_supervisor.py \
  --manifest scripts/benchmarks/manifest-v3-pi-qwen-tools-v2.json \
  --output "$STUDY_ROOT" --archives "$ARCHIVE_ROOT" \
  --private-inputs "$PRIVATE_CASE_ROOT" --upstream-root "$UPSTREAM_ROOT" \
  --probe-target "$PROTECTED_PROBE" --qwen-package "$QWEN_PACKAGE" \
  --protect "$PRIOR_ARTIFACT_ROOT" --preflight-only
```

Repeat the command without `--preflight-only` to execute. Every required archive,
upstream commit, prompt pin, native build, protected root, probe and cached
Docker image must be available before fixture preparation. Use `--python` to
select the evaluator Python environment with the upstream dependencies installed. Explicitly optional
prior roots use `--optional-protect`; their presence or absence is recorded.
For a bounded native lifecycle check, use a separate manifest with a declared
small plan and `--plan` to select it; preserve all case/model/order/budget pins.
`--generation-only` stops at restored generation, records outcome generation-only,
and never grades or seals that root. The fixed study plan remains unchanged.
Version mismatch fails unless `--bind-current-hub` explicitly changes only
`hub_version` and `versions.hub`. Both original and runtime hashes, source
identity, invocation, and preparation's archive-path additions are sealed in the
private provenance file. Native versions are checked in isolation at preflight
and rechecked by the existing driver in each arm's final environment.

The phase order is claimed, prepared, generated, restored, graded, sealed. All
repeat roots are freshly prepared, each generation runs sequentially, and all
planned generations finish before any official controls or grading. Restoration
markers, their ledgers, and live PID/start-time identities must agree before
grading. Every retained cell also passes a grade-independent readback of its
actual fixture metadata, guarded source diff, sealed baseline and native patch
bytes/hash. This same gate runs before reporting restored generation with
`--generation-only`; stored `metadata_clean` flags alone never qualify it.
Scored cells add the grade/evaluation bindings to that native evidence chain. A failure preserves an incomplete private root and logs for inspection.
The procedure uses the existing native driver, official grade/report commands,
and pooled ledger, without Orca registration or toolchain tree copying.

This entrypoint requires the evaluator service and images to be available. It
never starts or stops a shared VM or service. An operator who explicitly starts a
service must retain original-state and ownership evidence separately and restore
only that owned service after proving no unrelated usage; otherwise restoration
is deferred. Service ownership in this supervisor is recorded as require-existing.

Audit historical repeat roots without changing them:

```sh
python3 -B scripts/benchmarks/study_audit.py \
  --run "$STUDY_ROOT/r0" --run "$STUDY_ROOT/r1" \
  --export "$NEW_SAFE_EXPORT"
```

The auditor reconstructs the exact matrix and checks restoration, request-based
model gates, official controls, evaluation/patch bindings and owned live processes.
It constructs its output from fixed scalar fields and hashes. Nested official
test output, answers, native events, errors, provider identifiers and machine paths
are never copied to stdout or the safe aggregate. Unknown usage remains null.
Export creation is exclusive, so it cannot overwrite a historical artifact. The
complete private logs, evidence hash index, and safe aggregate stay in the durable
study root. A failed audit exits nonzero with a fixed error code and no raw error.
