# Benchmark runners

Scope: the CooperBench runners, their fixtures, teardown and recovery. Read before editing `scripts/benchmarks/` or `test/benchmarks/`, or before running a benchmark.

- Never auto-register Orca benchmark fixtures, including ad-hoc or copied runners; require an explicit pre-existing repo and exact worktree registration, and preserve fixture directories, Git state and benchmark evidence during cleanup.
- The manifest-v3 Pi/Qwen CooperBench driver (`scripts/benchmarks/native-pi-qwen.ts`, #140) is headless and never touches Orca. Its pinned build is the effective one: each native's `--version` runs under the final isolation environment (Qwen inside its seatbelt profile with `QWEN_HOME` set; the PATH bootstrap lies about the managed build under isolation). Its protected-file probe counts only with structured denial evidence (a guard denial or a failed read tool call with EPERM/EACCES), never a model-written marker alone, and each peer's serialized `sandboxProbe` readiness reports only that peer's observed probe outcome (`denied` with its evidence, else explicit `failed`/`unknown`; #150), never a synthesized denial. Served-model evidence is each request's own journaled `RelayRequestRecord` (#139): a heartbeat-only or cancelled-before-identification record certifies nothing, and every identified record is evidence whatever its outcome; a confirmed mismatch on a request cancelled after identification fails the model gate. A backend's last-served label is never a request's evidence. Qwen's peer tool approval is the exact canonical `mcp__pilot-peer-bus__hub_send` through the adapter's #138 binding, never a title-prefix workaround.
- The benchmark run's restoration state: `restoration.json` says `restored: false` from before the runner locks anything until it writes its outcome, and the recovery trusts `restored: true` only when `restoration-ledger.json` agrees (`unrestored` in `scripts/benchmarks/teardown.ts`). A run directory that is not restored is never reused: its locked modes would become the originals. A ledger from before 0.12.5 (no runner identity) owes its locks but, when `restoration.json` says `restored: true` or names a runner, keeps its trust entry as it was then (`owed`; with no `restoration.json`, its runner did not finish and the entry is owed too): the reuse check and the recovery read both through these two functions, never on their own (#120).
- A latched active-window terminal failure carries the #175 bounded diagnosis: the terminal class comes only from the pinned Qwen build's exact loop-protection message contract (anything else stays `unknown`), the active-window tool trace is count-only and phase/generation-fenced like the latch (setup probes and teardown never count), tool categories come from the protocol kinds and the #138 canonical binding (`canonicalMcpToolName` in `src/adapters/acp.ts`), and the native guard's threshold, predicate and no-op signals are declared unavailable, never derived from event totals. The diagnosis explains the latched failure and never changes it: no retry, no continuation, no guard relaxation.
- Classify Pi's ceiling only from the adapter's validated producer signal bound to the latched peer/active generation. Keep shared budgets and Qwen's guard distinct; diagnostics never change the frozen end cause.
- Pi's managed step ceiling changed from 30 to 100 (#1502, `src/pi/extension.ts`, `src/pi/launch.ts`), so a collection using that default has a changed study condition. Declare it before collecting. Host continuation (#1500) requires a settled ceiling with no active or pending tools and an accepting live owner, and is bounded by `pi.max_continuations` for the same accepted task and owner. Aborted turns do not continue; a successful turn resets the continuation count. Do not count an unsettled ceiling or an abort as a continuation.
- A collection that exercises Pi task worktrees with install inputs must account for dependency preparation (#1509, `src/pi/task-dependencies.ts`, `src/pi/dependency-publish.ts`): install inputs come from the reviewed base, the task worktree is rechecked before publication, and preparation failure is advisory rather than task-acceptance evidence.
- Read terminal coverage only through bounded `terminal_coverage` metadata reads, rebinding the audit, ledger and manifest to the seal index. Require complete sealed state, all audit checks, plan/cell/count reconciliation and zero recorded live owners. Report recorded verification separately from fresh audit; missing or inconsistent evidence is unavailable.
- Publish Pi benchmark descriptors from `benchPiToolProblem`; keep production schemas unchanged and omit solo peer messaging. Attest every bootstrap tool publication against declared native/schema/source pins before scored generation. Fail/defer missing, mixed, malformed, truncated or changed publications; retain only bounded names/counts/hashes. Declare a new study condition before any changed collection; never rewrite historical artifacts or select retries by score. The driver's Qwen profile and Pi tool sandbox are `profile()` from `src/local/sandbox.ts`: a change to that profile (#270's refusal of the `.git` name is one) is such a changed condition. So is a change to when its Qwen `AcpPeer` cancels a turn: it passes no `toolCeilingMs`, so a silent open tool call runs to the default ACP tool ceiling (#542), not `watchdogMs`.
- The benchmark runner's Claude trust entry: a write still `pending` in the runner's own process never landed, so it is `not_written` on every path (contained or not, its temp file removed or left), and neither the runner nor the recovery touches an entry then. Only a dead runner's `pending` leaves that question to the recovery, which takes back only an entry exactly as the runner would have written it, and none while the runner's temp file is still there (the rename never happened). `changed_concurrently` is the user's entry and is never taken back. The runner's settlement is `settleTrust` in `scripts/benchmarks/teardown.ts`, tested as a table: change it there, never inline.

- Treat an earlier journal-less ACP attempt as possibly affected by cancellation overlap (#304) when its recorded peer `state` goes idle without an answer near `watchdogMs` after the last recorded activity, followed by rapid `failure` entries and `qwen_log` prompt-failed lines, then `active_end` as `peer-failure` with that reason. The driver's tap does not record `undeliverable`, main logged no watchdog cancel, and Qwen's busy-refusal wording is still unmeasured: these are candidate signs, not proof, and absence does not clear an attempt. Keep historical results unchanged and the native measurement owed in `docs/smoke.md`.
- After #304, an unreported cancelled prompt leaves a cancellation-deadline line in `qwen_log`, a recorded offline state about 30 s after the watchdog, and `active_end` as `native-failure` on the next driver tick. The driver starts each peer once and cannot restart it within the attempt; its in-memory queue ends with the process. The end cause of affected attempts is not comparable across this fix (formerly `peer-failure` or the wall limit); keep that distinction in later collections, per issue #304's Decision, without changing historical scores or results.
- The benchmark local-worker tool surface is `src/local/tools.ts`: its `bash` permit now carries a host shell recheck (#816, see local-worker.md). A benchmark driver that stubs `ctx.permit` needs no change, since an absent `shellExecutionCheck` means `valid`.

## Routing promotion rule (#637 part 1)

A default that decides who takes a task is changed with a receipt, not by hand. Scope: `templates/routing.toml` (task routing: class peer lists, `local_allowed`, `[signals]`, `[constraints]`, `[pi]` windows) and what `assign()` reads of it. Model routing (`hub_routes`, `local.route`, `fixed_model`, the gateway aliases) is part 2 of #637 and has its own corpus, receipt and check below; this rule's receipt still says `served_models: not applicable`.

- **The frozen corpus** is `scripts/benchmarks/routing-corpus.json`: board-shaped cases (class, signals, peer states, reservations, exclusions, dependencies), each with the owner it must get (a peer or nobody), optionally the reviewer and the refusals that must appear. Every case has a `train` or `test` split, and the file carries a content hash over everything but the hash itself, the split included. The cases freeze the roles they route with (`defaults.roles`), so a change to the shipped roles cannot move them. Each split must hold at least one PII case and one refusal case, and a PII case that must reach `local` as well as one that must reach nobody.
- **Expectations are written from the policy's documented rules** (the `note` of each case names the rule), never copied from a run. A case a plausible default change would flip is the point; a corpus every edit passes measures nothing. `test/benchmarks/routing-gate.test.ts` edits the template eleven ways and requires each to be blocked.
- **The gate** is `bun scripts/benchmarks/routing-gate.ts`: no flag prints the current default's numbers (it must be 100% on both splits); `--receipt [--base <ref>]` compares the work tree's `templates/routing.toml` with the default at the base (the merge base with `origin/main` by default) on the test split and writes `docs/verification/<date>-routing-<sha8>.md`; `--freeze` rewrites the hash after an intended corpus change. It runs the pure `assign()`: no clock, no network, no model, so CI can run it and `ahub route explain` cannot drift from it.
- **The rule.** A PR that changes `templates/routing.toml` links a receipt whose candidate is not worse on the primary metric (owner top-1 accuracy on the test split) and regresses no PII or refusal case. Any regression on a PII case blocks, even when the primary metric rises. A case counts as a regression when the base passed it (owner, the stated reviewer and the stated refusals) and the candidate fails it.
- **CI** is `.github/workflows/routing-receipt.yml` running `scripts/check-routing-receipt.ts`. It fails a PR that changes the template unless a receipt under `docs/verification/` names that exact file (sha256), was made for the current corpus hash and for the default at the merge base, is on the test split, and is, field for field, what the gate would write for the corpus and the two files: the check REBUILDS the whole receipt (both policy summaries, the changed keys, every metric, every per-case outcome, the served-model note) and compares it canonically with the machine block, then compares the text outside the block (the summary and the case table) with what the gate renders from that data. The receipt chooses only its date (`YYYY-MM-DD`, also in the file name) and a short label for the base ref; a receipt edited by hand in any field, or a block with an extra field, cannot pass, and a receipt whose verdict is `blocked` does not pass either. The corpus never changes in the same PR as the default (land the corpus change and its refreeze first). A PR that does not touch the template needs nothing.
- **A corpus change voids every earlier receipt** (their corpus hash no longer matches). That is intended: the receipt of an old default is evidence about an old measuring stick.
- **Do not**: edit a case's `expect` to make a candidate pass, relax a guard, move a case between splits to flatter a candidate, or regenerate a receipt from a different base than the merge base. A candidate that fails a case the policy documents wrong is a spec question for the person, not a corpus edit in the same PR.
- A check that certifies a generated file recomputes ALL of it and compares it whole, never a chosen subset of fields (#321 review: the first version compared the verdict and counts only, so a receipt could carry any configuration, changed keys and per-case table and still be certified). Add a tampering test for every field the file carries, and one for the text around a machine block.
- **The routing gate is the repository's eval check (#481 S5, person's scope of 2026-10-28).** `scripts/check-routing-receipt.ts --publish` also creates, through the Checks API, one completed check run named `routing-eval` at the PR head, whose title carries `eval_pass_rate=<0..1> eval_suite=<corpus hash, first 12 digits>`: the owner top-1 accuracy of the head's `templates/routing.toml` on the test split, and the corpus version. Those are the two markers `readEvalResult` (`src/hub/eval-gate.ts`) parses. The person names it with `eval_check = "routing-eval"` in `.agenthub/sdlc.toml`. It is a SECOND run because an Actions job's own check run (`routing-receipt`) has a null title and summary, so the hub could read no marker from it; the job needs `checks: write`. A rerun UPDATES the run (the hub reads exactly one completed run of that name at a head). A publish that cannot be made is a `::warning` and never changes the job's exit status, which is the receipt verdict; the hub then shows the eval gate's "pass rate or suite version not reported" gap. With no readable corpus or template the report has no markers and a failed conclusion, never a made-up number. The rate is a score of the shipped default on the test split (100% while every documented rule holds), not a score of the change: the change is judged by the receipt.
- A reader of many generated files tests the SHAPE of each before it dereferences any field (`receiptShape` in `scripts/benchmarks/routing-corpus.ts`): a block that is only a receipt by `kind` and `version` is skipped, never an exception, so one malformed old file cannot stop the check before a valid receipt beside it is considered (#321 review nit). Test malformed and valid files together, in both orders.

## Model-routing promotion rule (#637 part 2)

A default that decides which MODEL answers is changed with a receipt too. Scope: the model-routing keys of `templates/routing.toml`, read as one summary (`modelRoutingSummary` in `scripts/benchmarks/model-routing-corpus.ts`): `[local]`, `[hub_routes.*]`, top-level `stay_switch` and `max_switch_prefill_tokens`, each class's `route`, `fixed_model` and `pi_backend`, and the `[pi]` windows. Peers, `local_allowed`, `[signals]` and `[constraints]` are part 1's. Part 1's receipt hashes and rebuilds the WHOLE template (its `policySummary` is every parsed key), so ANY change to `templates/routing.toml` still needs part 1's receipt, and a change to a model-routing key needs this one as well: two receipts, one per gate. A change that touches no model-routing key (peer order, signals, constraints) needs only part 1's, and this check says so and passes. Narrowing part 1 to task-routing keys would end the double receipt; it is left unchanged here (out of this task's paths) and is the upgrade path.

- **The frozen corpus** is `scripts/benchmarks/model-routing-corpus.json`, built from `build-model-routing-corpus.ts` (readable fixtures) and frozen with `model-routing-gate.ts --freeze`. Three case kinds. `selection` cases give the route and alias a class gets on the local worker. `route` cases drive the REAL `HubRouteRuntime` (stage, plan_execute, advisor, escalation) with a scripted host: the "model" is a fake that records which alias was asked and replays the case's judge replies, so what is scored is the routing code and the routing keys, never a model. `judge` cases are conversations whose verdict class (approve or redo, escalate or not) a sound judge returns, written from the judge prompts' own rules; they are scored ONLY by the hand-run live receipt, never in CI.
- **Expectations are written from the documented rules** (each `note` names one), never copied from a run. Both splits carry a deterministic PII guard and a deterministic hard-override guard, the test split carries a prompt-injection judge guard, and validation refuses a corpus without them. A PII case has an ordinary twin (the PII trace carries no prefill size, the ordinary one does), so it cannot pass on an empty trace.
- **The gate** is `bun scripts/benchmarks/model-routing-gate.ts`: no flag prints the shipped default's numbers (100% on both splits); `--receipt [--base <ref>] [--out <file>] [--live]` writes `docs/verification/<date>-modelrouting-<sha8>.md` (the name differs from part 1's `-routing-` so neither check reads the other's files). The sha8 is the digest of the model-routing keys, not of the whole template.
- **The rule.** The candidate is not worse on the primary metric (deterministic case pass rate on the test split) and regresses no PII or hard-override case; when the live half is present, the judge cases follow the same rule (fewer passes or a regressed guard judge case blocks). The receipt's `overall` verdict (its heading, and the gate's exit code) combines both; `evidence.verdict` is the deterministic part only, and the document prints both. A change that needs the live half but was written without it says `Incomplete` in its heading.
- **The live half is by hand.** A change to an alias, a judge or any key outside the deterministic set (`liveRequired`) moves what a model answers, so the receipt must carry a `live` block made with `--live`: it asks each policy's judge alias the judge cases through the gateway with the request THAT POLICY builds (`judgeRequestFor`: the same prompts and the advisor's route `transcript_max_chars` as `HubRouteRuntime.review` passes them; a test compares it with what the real runtime sends) and writes the model id the gateway REPORTED for each alias (OmniRoute `servedModel`). Each outcome records the sha256 of the request it was asked, and CI recomputes it, so a receipt for a changed cap that measured the default's request is refused. It needs `AGENTHUB_OMNIROUTE_URL` and `OMNIROUTE_API_KEY`, exits 2 without them before any request, and writes nothing when a call failed, the gateway named no served model, or it named the alias. A deterministic-only change may carry `served_models: live-not-run`.
- **CI** is the second step of `.github/workflows/routing-receipt.yml`, `scripts/check-model-routing-receipt.ts`. It runs no model and has no gateway or key. It REBUILDS everything the files determine (configurations, changed keys, every metric and per-case outcome, the rendered document) and compares it whole, as part 1 does. The live block is the one thing no file determines, so CI checks its shape and consistency only: exactly the test-split judge cases, the alias each policy asks, no failed call, a served id for every alias that is a real model id and not the alias, and scores recomputed from the recorded verdicts. It cannot check that a model said it: a person who reads the receipt owns that.
- **A corpus change voids every earlier receipt** and never lands in the same PR as the keys it measures. Do not edit a case's `expect` to make a candidate pass, relax a guard, or move a case between splits to flatter a candidate.
