Skip to content

Experience-Driven Black-Box Cost Control for Coding Agents

docs cleanup

Aaron29e037edfad0
diff --git a/.gitignore b/.gitignore
index 4d65330..f7745d8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,7 +9,7 @@ dist/
.mypy_cache/
.ruff_cache/
-# Local virtualenvs. experiments/docs/ENVIRONMENT.md tells you to create `.venv` right here,
+# Local virtualenvs. experiments/README.md tells you to create `.venv` right here,
# and CPython's venv only started writing a self-excluding .gitignore in 3.13 — so ignore it
# explicitly rather than relying on the tool that happened to create it.
.venv/
diff --git a/CLAUDE.md b/CLAUDE.md
index 56db567..218ea3f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2,8 +2,8 @@
A plugin for Claude Code, Codex, the Copilot CLI and Pi that reads finished sessions and changes
what later sessions in the same repository pay for: micro-skills, tool pruning, and a loop guard.
-See `README.md` for the overview, `docs/PLUGIN.md` for the design and the verified agent
-behavior, and `docs/METHOD.md` for the method.
+See `README.md` for the overview and the method, `docs/PLUGIN.md` for the design and the verified
+agent behavior, and `docs/ARCHITECTURE.md` for how the package fits together.
## Layout
- `tokeneconomizer/` — the one Python package, standard library only
@@ -19,7 +19,8 @@ behavior, and `docs/METHOD.md` for the method.
skills (`codex-skills/`, Codex having no plugin slash commands), the Pi extension; `lib/` links
the package
- `experiments/` — benchmark-only: `te_bench/` (adapters, arms, facade, benchmark-only
- controllers), `te_harness/` (Docker runners), `scripts/`, `docs/`, its own `tests/`
+ controllers), `te_harness/` (Docker runners), `scripts/`, `workloads/`, its own `tests/`;
+ its `README.md` is the run book
- `package.json` — the repository as a Pi package (`pi install git:github.com/…`); it names
the same extension as `plugin/package.json`, which a test pins
- `scripts/build_plugin.py` — a self-contained plugin bundle for marketplace installs
diff --git a/README.md b/README.md
index be0ed64..1b822ec 100644
--- a/README.md
+++ b/README.md
@@ -45,6 +45,31 @@ Each mechanism can be switched off or tuned on its own. The plugin's actions are
one line, every hook fails open, and by default it makes no model calls of its own. What it learns
stays on your machine, under `~/.tokeneconomizer`.
+## How it works
+
+Coding agents are built for task success, not for what a task costs, and every turn re-bills
+the agent's instructions, every loaded tool, and the conversation so far. Developers use the same
+agent on the same codebase over many tasks, so much of that cost recurs: the same environment
+facts rediscovered, the same unused tools re-sent, the same kind of failing loop. TokenEconomizer
+holds the agent fixed -- no change to its model, weights or code -- and treats a repository's
+stream of sessions as the unit to optimize: what finished sessions show about the repository
+shapes what later sessions are given, and anything the plugin spends is amortized over the stream.
+Four principles shape the mechanisms:
+
+- **Act through what the agent already reads.** Facts go into the context at session start and
+ tools leave through the agent's own settings, so nothing depends on the agent adopting a new
+ tool.
+- **Count cost as it is billed.** Most tokens in a session are cached re-reads, so cost is
+ measured on a cache-aware basis, including any model calls the plugin makes.
+- **Keep task success.** Facts form only from recurring evidence, tools are pruned only after
+ going unused, and the loop guard spares a turn that is still making progress.
+- **Recover from mistakes.** A fact a later session contradicts is retired, an applied deny list
+ can be restored, and the guard redirects before it ever stops a turn.
+
+The paper evaluates these mechanisms with Claude Code, Codex and the Copilot CLI on SWE-Bench,
+Web-Bench and two security benchmarks; [`experiments/`](experiments/README.md) reruns the
+SWE-Bench and Web-Bench experiments.
+
## Supported agents
| Agent | Install |
@@ -98,19 +123,12 @@ terminal inside the repository, as `~/.tokeneconomizer/bin/te <command>`.
```text
/tokeneconomizer:config set loopguard=off # one mechanism off, in this repository
/tokeneconomizer:config set toolprune=off --global # ... or in every repository
-/tokeneconomizer:config set microskills_max_facts=2 # inject at most two facts
-/tokeneconomizer:config set toolprune_evidence=10 # wait ten unused sessions before proposing
-/tokeneconomizer:config set loopguard_nudges=2 # allow two redirects per turn
-/tokeneconomizer:config set loopguard.min_turns=30 # 30 tool calls before a turn can count as stuck
-/tokeneconomizer:config unset loopguard.min_turns # back to the default
+/tokeneconomizer:config set microskills_max_facts=2 # tune one: inject at most two facts
```
-The paid extras are off unless you set `paid=true`: an LLM proposer that authors repository
-facts beyond the free ones (`microskills=envfacts+distiller`) and a stuck judge for the loop
-guard, both run through your own agent's CLI, on the same plan or login as your sessions, and
-recorded in the session's ledger. Every
-setting, its default and its environment variable: [Settings](plugin/README.md#settings).
-Settings written under the earlier names (`inject`, `untool`, `spiral`, ...) are still read.
+The paid helpers -- an LLM fact proposer and a judge for the loop guard -- are off unless you set
+`paid=true`; they run through your own agent's CLI, on the same plan or login as your sessions.
+Every setting, its default and its environment variable: [Settings](plugin/README.md#settings).
## What it does on each agent
@@ -123,7 +141,8 @@ Settings written under the earlier names (`inject`, `untool`, `spiral`, ...) are
Nothing is written to your settings until you approve it, and `toolprune restore` removes only
what the plugin added. How each agent's hooks and settings were verified to behave is in
-**[`docs/PLUGIN.md`](docs/PLUGIN.md)**; the method itself is in **[`docs/METHOD.md`](docs/METHOD.md)**.
+**[`docs/PLUGIN.md`](docs/PLUGIN.md)**, and how the package fits together in
+**[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)**.
## Repository
@@ -135,8 +154,8 @@ what the plugin added. How each agent's hooks and settings were verified to beha
| [`tokeneconomizer/trace`](tokeneconomizer/trace/) | Each agent's session log, read into one shape |
| [`tokeneconomizer/plugin`](tokeneconomizer/plugin/) | The runtime the hooks and the `te` command run |
| [`plugin`](plugin/) | The installable plugin: manifests, hook files, launchers, slash commands, the Pi extension |
-| [`experiments`](experiments/) | The benchmark harness, arms, workloads and run book behind the paper |
-| [`docs`](docs/) | `PLUGIN.md` (design, verified agent behavior) and `METHOD.md` (the method) |
+| [`experiments`](experiments/) | The harness, launchers and task sets behind the paper's results |
+| [`docs`](docs/) | `PLUGIN.md` (design, verified agent behavior) and `ARCHITECTURE.md` (how the package fits together) |
| [`tests`](tests/) | Offline tests for the package and the plugin |
The package is standard-library only. Run the tests with `python -m pytest tests` (add
@@ -145,10 +164,10 @@ The package is standard-library only. Run the tests with `python -m pytest tests
## Reproducing the experiments
-The benchmark experiments -- the Docker harness that runs sealed agents on SWE-bench and
-Web-Bench, the arms, the sweep and aggregation pipeline, and the evaluated task sets -- live in
-**[`experiments/`](experiments/README.md)**. They are not packaged with the plugin and share
-only `tokeneconomizer/`.
+The code behind the paper's results -- a harness that runs Claude Code, Codex and the Copilot CLI
+on SWE-Bench and Web-Bench, the launchers, and the evaluated task sets -- is in
+**[`experiments/`](experiments/README.md)**, whose README gives the setup and one command per
+result. It is not packaged with the plugin and shares only `tokeneconomizer/`.
## Citation
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
new file mode 100644
index 0000000..4341626
--- /dev/null
+++ b/docs/ARCHITECTURE.md
@@ -0,0 +1,37 @@
+# Architecture
+
+The three mechanisms (see the [main README](../README.md)) know neither the agent, the harness
+nor the task domain. Everything specific to those enters through a few small interfaces in the
+standard-library-only package `tokeneconomizer`:
+
+- `tokeneconomizer.trace` is the one place a saved session log is read (`load_trajectory`,
+ `call_cwds`, `tool_usage`, `parse_catalog`), with one module per agent's format. A new agent
+ needs a reader here and nothing else.
+- `tokeneconomizer.ledger` and `tokeneconomizer.pricing` are the one definition of cost.
+ Mechanisms record their per-task overhead; the plugin's session ledger and the experiments'
+ aggregation read it back through the same modules, so recorded and reported cost cannot
+ drift.
+- `tokeneconomizer.domain.DomainAdapter` is the interface to the task domain: reading a session,
+ the tools pruning protects or excludes, a trajectory's loop signals, the task text for the
+ optional judge, and the micro-skill vocabulary. A new domain is a new adapter, with no change
+ to a mechanism. The plugin's adapter is `tokeneconomizer.plugin.adapter.LiveAdapter`; the
+ benchmark adapters (SWE-Bench, Web-Bench, CredData, ReposVul) are in
+ `experiments/te_bench/adapters/`.
+- `tokeneconomizer.stage.Stage` is the set of hooks a mechanism offers whoever runs it:
+ `before_task`, `build_tools`, `run_kwargs` and `after_task`.
+
+Two callers run the stages, and the mechanisms import neither:
+
+- **The plugin** (`tokeneconomizer.plugin`) runs them inside a person's sessions through each
+ agent's hooks: `PrefixStage` and `ToolingStage` over each finished session, and the loop guard
+ (`loopguard.TurnGuard`) one tool call at a time. What happens at each hook, and what was
+ verified on each agent, is in [`PLUGIN.md`](PLUGIN.md).
+- **The experiments** (`experiments/te_bench`) run them over benchmark task streams: the
+ `Economizer` facade wires the three stages around one adapter, and
+ `te_bench.runner.AgentRunner` is the interface to a task-execution harness (Docker, an agent
+ CLI, a grader), with `experiments/te_harness` as the implementation the paper used. The
+ benchmark-only controllers -- `SpiralStage`, the streamed `NudgeGuard` and the Codex finalize
+ policy -- live there too. See [`experiments/README.md`](../experiments/README.md).
+
+`tests/test_plugin_package.py` pins both boundaries: the mechanisms never import
+`tokeneconomizer.plugin`, and nothing under `tokeneconomizer/` imports `experiments/`.
diff --git a/docs/METHOD.md b/docs/METHOD.md
deleted file mode 100644
index 20acac6..0000000
--- a/docs/METHOD.md
+++ /dev/null
@@ -1,82 +0,0 @@
-# Method — thesis, amortized setting, and the seams
-
-## Thesis
-
-Hold the **agent fixed** (Claude Code, Codex, Copilot CLI, Pi) and make the **environment
-learn a cheaper interface to itself**, without losing task success. The optimization is
-delivered **externally** -- no change to the agent -- and has to **transfer across agents**.
-
-The cost is amortized over a **stream** of tasks (sessions) on one repository, not any single
-task. Some mechanism cost is paid once (a between-session proposer call) and reused by every
-later session, so the quantity of interest is the **amortized accuracy–cost curve** over the
-stream, not per-task overhead in isolation.
-
-## Design constraints
-
-- **Optimize turns, not bytes.** Cost is driven by round-trips × re-read context, not
- per-command output size, so compressing command output alone is not enough.
-- **Prefer levers the agent already uses.** Agents under-adopt tools they are nudged toward;
- environment-side levers they already read (the context at session start, the tool list) do
- not depend on adoption.
-- **Cache-aware cost or nothing.** Most raw tokens in an agent session are cached re-reads, so
- comparing on raw token totals flatters methods that prune cheap re-reads. Everything is
- measured on `pricing.effective_tokens` plus `ledger.overhead`.
-- **Task success is a guardrail.** A mechanism that is cheaper but loses task success is not
- shipped. The loop guard's stop and the Codex finalize rule are gated to spare a trajectory
- that is still making progress.
-
-## The three mechanisms
-
-Each acts at a different point of a session and is switched on or off on its own:
-
-| Mechanism | Package | When | What it does |
-|---|---|---|---|
-| **Micro-skill synthesis and injection** | `tokeneconomizer.microskills` | before a session | State short, learned repository facts up front. An LLM-free layer (`envfacts`) forms facts from recurring failure→repair shapes of a command (naming the repair with the best record as typed, one piece of evidence per session) and of its test-label arguments, an environment variable the code asks for and the value that worked, refused hosts and empty probes; its vocabulary comes from the domain adapter. An optional paid proposer (`distiller`) authors open-vocabulary facts and extractors over a compact digest, told which facts the free layer already states. Every fact goes through one lifecycle (`lifecycle`): formation on repeated sessions (for a proposed fact about the code, sessions that edited different files), retirement on contradiction, and a firing gate so only facts whose failure keeps occurring stay injected. |
-| **Tool pruning** | `tokeneconomizer.toolprune` | at session construction | Drop tool definitions a repository's work does not use. Evidence pruning drops a tool loaded but unused for N sessions, never a protected work-surface tool or one ever used, with an optional per-task instruction-aware judge. On Codex the unit is a capability package removed from the request contract, evidence-gated. |
-| **Failure-loop intervention** | `tokeneconomizer.loopguard` | during a turn | Notice a trajectory stuck repeating the same failure, against a learned per-repository envelope of how long turns that end well run: a free gate, then either a sampled LLM judge or a strict heuristic, then a redirect, then a stop. On Codex, a same-thread finalize redirect once a trustworthy green check passes and every failed scope is cleared. |
-
-## The seams that keep the mechanisms self-contained
-
-The mechanisms know neither the harness nor the domain. Everything specific enters through a
-few small, named surfaces, all in the standard-library-only package:
-
-- `tokeneconomizer.trace` -- the ONE place a saved session log is read (`load_trajectory`,
- `call_cwds`, `tool_usage`, `parse_catalog`), with one module per agent's format.
-- `tokeneconomizer.ledger` and `tokeneconomizer.pricing` -- the ONE definition of amortized
- cost. Mechanisms record per-task overhead fields; the plugin's session ledger and the
- experiments' aggregation read them back through the same module, so the recorded and the
- reported cost cannot drift.
-- `tokeneconomizer.domain.DomainAdapter` -- the seam to the task domain: reading a session,
- the tool sets pruning protects or excludes, a trajectory's loop signals, task text for the
- optional judge, and the micro-skill vocabulary. A new domain is a new adapter, with no
- mechanism edit. The plugin's adapter is `tokeneconomizer.plugin.adapter.LiveAdapter`; the
- benchmark adapters (SWE-bench, Web-Bench, CredData, ReposVul, CyberGym, a WebArena stub) are
- in `experiments/te_bench/adapters/`.
-- `tokeneconomizer.stage.Stage` -- the lifecycle hooks a mechanism offers a caller
- (`before_task`, `build_tools`, `run_kwargs`, `after_task`).
-
-Who runs the stages is outside the package:
-
-- **The plugin** (`tokeneconomizer.plugin`) runs them inside a person's sessions through each
- agent's hooks: `PrefixStage` and `ToolingStage` over each finished session, and the loop guard
- one tool call at a time (`loopguard.TurnGuard`). The mechanisms never import it.
-- **The experiments** (`experiments/te_bench`) run them over benchmark streams: the
- `Economizer` facade wires the three stages around one adapter, and `te_bench.runner.AgentRunner`
- is the seam to a task-execution harness (Docker, an agent CLI, a grader), with
- `experiments/te_harness` as the reference implementation. The benchmark-only controllers --
- `SpiralStage`, the streamed `NudgeGuard`, the Codex finalize policy -- live there too.
-
-## Entry point (the experiments)
-
-```python
-from te_bench.facade import Economizer
-
-econ = Economizer.from_args(args, repo=repo, results_root=root, fresh=True,
- runner=my_runner) # an AgentRunner, or an optimizer callable
-# per task:
-injected = econ.injection_prefix(task)
-exclude_tools = econ.build_tools(task, i)
-run_kwargs = econ.run_kwargs(task)
-# ... execute the task through the runner with those decisions ...
-opt_tokens, reason = econ.after_task(task, row, run_dir_path, srow)
-```
diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md
index f40b29f..87379e2 100644
--- a/docs/PLUGIN.md
+++ b/docs/PLUGIN.md
@@ -1,19 +1,11 @@
-# The plugin — the three mechanisms in your own agent sessions
+# The plugin: design and verified agent behaviour
-The experiments in this repository hold a sealed agent fixed and run it, headless, over streams
-of benchmark tasks. This document is about the other way to use the same controller: as a
-**plugin** that runs inside the sessions you already have — Claude Code, Codex, the GitHub
-Copilot CLI and Pi — through the hooks (or, on Pi, the extension events) the agent exposes.
-
-It covers what the plugin does at each hook, what changes relative to the experimental setting
-and why, the agent behaviour each design choice rests on, how to install and configure it, and
-what is not done yet. The code is `tokeneconomizer/plugin/` (the runtime the hooks run) on top of
-the three mechanism packages (`microskills`, `toolprune`, `loopguard`), and `plugin/` (the host
-packaging).
-
-> **The plugin ships the mechanisms, not results.** The experiments ran on sealed, headless,
-> graded SWE-bench / Web-Bench streams; a real session is interactive, has no grader, and
-> differs in the ways listed in §2. Each mechanism can be switched off on its own (§5).
+How the plugin runs the three mechanisms inside your own Claude Code, Codex, Copilot CLI and Pi
+sessions, through the hooks (on Pi, the extension events) each agent exposes: what it does at
+each hook, what differs from the experiments and why, the agent behaviour each choice rests on,
+where its state lives, and its known limitations. The code is `tokeneconomizer/plugin/` (what
+the hooks run) and `plugin/` (the packaging for each agent). To install and use it, see
+[`plugin/README.md`](../plugin/README.md).
---
@@ -70,7 +62,7 @@ Every hook fails open: any error becomes an empty output (no change) and a trace
## 3. Verified agent behaviour
What the code relies on about each agent, and how it was checked. Each block names the version
-and date it was verified on; §7 says what has not been exercised.
+and date it was verified on; §5 says what has not been exercised.
**Claude Code 2.1.286 — verified with a local plugin (`--plugin-dir`) on Haiku, 2026-09-30:**
@@ -128,6 +120,10 @@ isolated `CODEX_HOME`, `--dangerously-bypass-hook-trust`; 2026-09-30):
variables, which is why the host is detected from the payload (`turn_id`), never the env.
* `CODEX_HOME` under `/tmp` makes Codex refuse to install its helper binaries, and its sandbox then
fails every command (`codex-linux-sandbox: No such file`); keep it out of temporary dirs.
+* Codex also turns a plugin's `commands/` folder into skills of its own (`source-command-status`,
+ …), which listed every command twice in its skill picker beside `codex-skills/`. The slash
+ commands therefore live in `slash-commands/`, which the Claude Code and Copilot manifests name
+ and Codex does not read (verified 2026-10-17).
Hooks are **trust-gated**: skipped until approved in `/hooks` (stored as
`[hooks.state.<key>].trusted_hash`), unless the run passes `--dangerously-bypass-hook-trust`.
@@ -184,7 +180,9 @@ feature flags):
`paid_model`, else a concrete `COPILOT_MODEL`, else `claude-haiku-4-5` on an Anthropic
provider. It answered, and was priced from its own session log. The local capture behind
`refresh-catalog` and `measure` mimics the person's model family, so it records the same
- built-in tools (`edit`/`create` for Claude models, not `apply_patch`).
+ built-in tools (`edit`/`create` for Claude models, not `apply_patch`). Copilot 1.0.83 does not
+ pass its `COPILOT_PROVIDER_*` variables to the hooks, so with BYOK set through them the side
+ calls run signed out; they answer nothing and say so in `errors.log`.
**GitHub Copilot CLI 1.0.83 — verified live, 2026-10-07**, against a scripted OpenAI-compatible
endpoint on localhost (Copilot's BYOK mode, `COPILOT_PROVIDER_BASE_URL`). Every request the CLI
@@ -308,125 +306,7 @@ needed sessions that edited different files and, once injected, decayed (the fol
what the session was given); a Codex install copy had no package; side calls failed silently
and left sessions in Claude Code's history; `te` without `--host` showed Claude Code's state.
-## 4. Install
-
-The plugin directory is `plugin/`; the repository root is also a Claude Code marketplace
-(`.claude-plugin/marketplace.json`). Requires Python ≥ 3.10 on `PATH` (or `TE_PYTHON`).
-
-**Claude Code, from a checkout**
-(`git clone https://github.com/microsoft/TokenEconomizer.git`). This loads in place,
-so edits apply at the next session. Then run `/tokeneconomizer:toolprune refresh-catalog` once on
-the machine (the catalog is per machine); without it, evidence pruning sees only deferred tools:
-
-```bash
-claude --plugin-dir /path/to/TokenEconomizer/plugin # one session
-# or, persistently:
-/plugin marketplace add /path/to/TokenEconomizer
-/plugin install tokeneconomizer@tokeneconomizer
-```
-
-**From a bundle** — a marketplace install that copies the plugin directory finds the package in
-the checkout it came from, so that checkout must stay. For a copy that carries the package itself,
-`python3 scripts/build_plugin.py` writes a self-contained marketplace to
-`dist/marketplace/` (add it with `/plugin marketplace add`, publish it as a branch or repository,
-or `--zip` it for `claude --plugin-url`).
-
-**Codex** — the plugin carries `.codex-plugin/plugin.json`, `hooks/codex-hooks.json` and, as
-Codex has no plugin slash commands, its commands as Codex skills (`codex-skills/`:
-`tokeneconomizer-status`, `-microskills`, `-toolprune`, `-config`, each running the matching
-`te --host codex` command). Codex 0.153.1 also turns a plugin's `commands/` folder into skills
-(`source-command-status`, …), which listed every command twice in its skill picker; the slash
-commands therefore live in `slash-commands/`, which the Claude Code and Copilot manifests name and
-Codex does not read. Codex copies an installed plugin; the copy finds the package in the
-checkout it was added from (or carries it, from the bundle):
-
-```bash
-codex plugin marketplace add /path/to/TokenEconomizer
-codex plugin add tokeneconomizer@tokeneconomizer
-# self-contained instead: python3 scripts/build_plugin.py --out ~/te-marketplace, and add that
-```
-
-Then approve its hooks once in the TUI (headless runs: `codex exec
---dangerously-bypass-hook-trust`, for automation that vets its hook sources). Verified end to
-end on 0.153.1 (2026-10-08, in an isolated `CODEX_HOME`): the bundle installs as a copy with the
-package in `lib/`. Until trusted, the hooks do not run, and a session leaves no plugin
-state. At start the TUI says "Hooks need review: 5 hooks are new or changed". Its hooks screen
-lists the plugin's five hooks; `t` trusts all, recorded as
-`[hooks.state."tokeneconomizer@tokeneconomizer:hooks/codex-hooks.json:…"] trusted_hash`.
-After that, a plain `codex exec` ran them, folded and priced the session, and wrote
-`~/.tokeneconomizer/bin/te` pointing into the plugin cache. Through that launcher, `toolprune
-apply` removed sub-agents, goals and the image viewer from the next live session, by the
-model's own report, and `restore` gave them back. The deny list
-(`te --host codex toolprune …`) writes the project's `.codex/config.toml`, which Codex reads only
-once you trust the project.
-
-**Copilot CLI** — the plugin carries `.github/plugin/plugin.json` and `hooks/copilot-hooks.json`.
-Copilot loads a local marketplace in place, so the checkout itself is the install:
-
-```bash
-copilot plugin marketplace add /path/to/TokenEconomizer
-copilot plugin install tokeneconomizer@tokeneconomizer
-/tokeneconomizer:toolprune refresh-catalog # in Copilot, once: the tools a session loads
-```
-
-Copilot runs the plugin's slash commands in its interactive mode, not under `copilot -p` (its
-notices show in both). From a terminal, use `~/.tokeneconomizer/bin/te --host copilot <command>`
-(or `plugin/scripts/te`; in Copilot's own shell, `te` detects Copilot without `--host`).
-Copilot does not pass its environment's `COPILOT_PROVIDER_*` variables to the hooks (1.0.83), so
-under BYOK set through them the paid side calls run signed out; they answer nothing and say so in
-errors.log.
-
-**Pi** — the repository root is a Pi package (`package.json` → `pi.extensions` →
-`plugin/pi/tokeneconomizer.ts`), and so is `plugin/` on its own, for the bundle. A git source
-clones the repository and loads it from its root, as a local path does:
-
-```bash
-pi install git:github.com/microsoft/TokenEconomizer # what a Pi user runs
-pi install /path/to/TokenEconomizer # a checkout, loaded in place
-pi -e /path/to/TokenEconomizer/plugin/pi/tokeneconomizer.ts # one run only
-```
-
-Inside Pi, `/te status` (and `microskills`, `config`) runs the command line: its answer is a
-notice in the terminal UI (and over RPC), and goes to stderr in print and JSON modes.
-
-## 5. Configure
-
-Each mechanism has its own switch, and each takes a plain `on` / `off` (`on` = the default
-below). The defaults are the conservative end of each:
-
-| Key | Default | Values |
-|---|---|---|
-| `microskills` | `envfacts` | `off`, `envfacts`, `envfacts+distiller`, `distiller` (the last two make paid calls) |
-| `toolprune` | `propose` | `off`, `propose`, `auto` (apply proposals as they form) |
-| `loopguard` | `nudge` | `off`, `nudge`, `stop` (nudge, then stop — headless only) |
-| `mode` | `auto` | `auto`, `interactive`, `headless` |
-| `paid` | `false` | gate for every LLM call a mechanism would make |
-| `paid_model` | `""` | model for paid calls (`haiku` on Claude Code when empty; Pi's own default model on Pi) |
-| `shadow` | `false` | compute and log every decision, act on none |
-
-Hyperparameters, set by hand:
-
-| Key | Default | Sets |
-|---|---|---|
-| `microskills_max_facts`, `microskills_max_tokens` | `4`, `150` | caps on the injected fact block (`InjectionConfig.max_facts` / `max_tokens`, passed to `EnvFactsDistiller`) |
-| `microskills_propose_every` | `5` | sessions between paid proposer runs |
-| `toolprune_evidence` | `5` | sessions a tool must go unused (×3 for NotebookEdit and Codex's `image_media`; WebFetch / WebSearch are never proposed) |
-| `loopguard_aggr` | `default` | `conservative`, `default`, `aggressive` (`loopguard.SPIRAL_LEVELS`) |
-| `loopguard_nudges` | `1` | the guard's nudge budget per prompt-turn |
-| `loopguard.<name>` | the preset | one key of `DEFAULT_THRESHOLDS`, pinned: `loopguard.thresholds` applies it over the preset and over what the repository's envelope learned; the `envelope_*` keys go to the `EnvelopeTracker` itself |
-| `repomap`, `repomap_tokens`, `repomap_python`, `repomap_timeout` | `off`, `2048`, auto, `8` | the opt-in repository map (`plugin/repomap.py`): aider's ranked map, made by the Python that has aider (`plugin/repomap_gen.py --git --cache`), cached per commit in the state directory, injected once per session -- ranked toward the first prompt where the prompt hook carries context (Claude Code, Copilot, Pi), at session start otherwise (Codex, or `repomap=start`) |
-
-Set them with `te config set KEY=VALUE` (this repository) or `--global`, `te config unset KEY`
-to fall back, or per session with `TE_<KEY>` (`TE_LOOPGUARD_THRESHOLDS` takes JSON);
-`TE_DISABLE=1` turns the plugin off. The names before the rename (`inject`, `untool`, `spiral`,
-their settings and `TE_*` variables, `spiral=guard`) are still read, and a new name wins over
-its old one. `te config show` prints each mechanism's state and the guard's thresholds in
-effect. Commands: `/tokeneconomizer:status`, `:microskills`, `:toolprune` (`:facts` and
-`:untool` still work),
-`:config` in Claude Code and Copilot; `plugin/scripts/te <command>` anywhere. The
-user-facing reference is the Settings section of [`plugin/README.md`](../plugin/README.md#settings).
-
-## 6. State and privacy
+## 4. State and privacy
All state is local, under `$TOKENECONOMIZER_HOME` (default `~/.tokeneconomizer`), one directory
per repository and host: the mechanisms' own state, `ledger.jsonl` (one priced record per
@@ -453,7 +333,7 @@ command forms and hosts, and lints out completion advice; the paid proposer's fa
open-vocabulary. Read them with `te microskills` before enabling the proposer on a repository you do
not trust.
-## 7. Not done yet
+## 5. Known limitations
* **Copilot CLI** — the real-model checks used one model (Claude Haiku 4.5, over BYOK). A
per-tool deny list waits on Copilot gaining a persistent per-tool filter.
diff --git a/experiments/.env.example b/experiments/.env.example
index 6f3a0c1..716d65e 100644
--- a/experiments/.env.example
+++ b/experiments/.env.example
@@ -1,135 +1,26 @@
-# TokenEconomizer — local credentials + run environment (TEMPLATE, tracked in git).
-#
-# cp .env.example .env # then fill in the real values; .env is git-ignored
-#
-# Format: plain `KEY=value`, one per line. A `#` starts a comment ONLY at the start of a
-# line -- a trailing `# ...` after a value is part of the VALUE, not a comment. Quote values containing
-# spaces. No `$VAR` interpolation and no command substitution — both the Python loader
-# (scripts/_env.py) and the shell loader (scripts/launch/_env.sh) treat values literally.
-# Loaders NEVER overwrite a variable already exported in your shell, so a one-off
-# `ANTHROPIC_API_KEY=... bash scripts/launch/...` still wins.
+# Copy to experiments/.env (git-ignored) and fill in. One KEY=value per line: no quotes, no
+# $VAR expansion, and a `#` starts a comment only at the start of a line. A variable already
+# exported in your shell wins over this file.
-# --- Agent credentials ---------------------------------------------------------------------
-# Each agent bills its own vendor's API directly:
-# Claude Code -> the Anthropic API on ANTHROPIC_API_KEY
-# Codex -> the OpenAI API on OPENAI_API_KEY
-# Copilot CLI -> the GitHub Copilot subscription (or Copilot's own BYOK, further down)
-# ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN are not read: the launchers say so and unset
-# them if they are set, because Claude Code would otherwise honour them.
+# --- API keys -------------------------------------------------------------------------------
+# Claude Code bills the Anthropic API, Codex the OpenAI API.
ANTHROPIC_API_KEY=
OPENAI_API_KEY=
-# Regional OpenAI endpoint, ONLY for a key issued against one: a key scoped to a region
-# 401s on the global endpoint. Leave it unset for a global key. The launchers refuse any
-# host that is not OpenAI's own API.
+# Only for an OpenAI key issued against a regional endpoint:
# OPENAI_BASE_URL=https://us.api.openai.com/v1
-# --- Models billed by the sealed agents ---------------------------------------------------
-# These label the cost basis and are what the harness passes to the CLIs. Keep an A/B's two
-# arms on the SAME model — the comparison is meaningless otherwise.
-#
-# The main sweep runs claude-opus-4-8 and claude-sonnet-5 on both agents, plus 4 required
-# arms on claude-opus-5 (docs/RUNNING.md). main_sweep.sh passes --model per lane
-# and that WINS over this variable, so for the sweep leave it commented out.
-# ANTHROPIC_MODEL=claude-opus-5
-# ANTHROPIC_MODEL=claude-sonnet-5
-# ANTHROPIC_MODEL=claude-opus-4-8
-#
-# SPELLING. The older Opus has two spellings and the catalogs disagree: the Anthropic API
-# serves the DASHED `claude-opus-4-8` and 404s the dotted form; the Copilot CLI's own
-# catalog on a subscription lists the DOTTED `claude-opus-4.8`. Write the dashed form
-# everywhere: the launchers spell it for the backend (te_model_for_agent in
-# scripts/launch/_env.sh, logged as `[env] model id: ... -> ...`), the Copilot probe
-# verifies it against the CLI and switches spelling if a vendor rotates it, and
-# te_model_tag folds both to one tree tag (opus48) so the two spellings can never fork a
-# tree. `claude-opus-5` and `claude-sonnet-5` have one spelling and are untouched.
-# Reasoning effort the sealed agent runs at: low|medium|high|xhigh|max. Part of the cost
-# basis, so keep BOTH arms of an A/B on the same level.
-# COMMENT THIS OUT for the main sweep: its baseline-low/-medium arms set the level from the
-# arm name, and an inherited value makes the driver log an override for every cell.
-TE_EFFORT_LEVEL=high
-# Small/fast model for Claude Code's own background calls. An unserved id is a per-call
-# FAILURE, not a fallback, and te_harness forwards this var into the task container, so a
-# wrong value reaches the CLI. Leave it unset to keep Claude Code's own default.
-# ANTHROPIC_SMALL_FAST_MODEL=claude-haiku-4-5
-# Codex model. `gpt-5.6-sol` is served on /v1/responses by the OpenAI API (probed
-# 2026-09-09). THE TRAP is the `-codex` ALIASES (gpt-5.1-codex, gpt-5.2-codex, ...):
-# /v1/models lists them and /v1/responses 404s them, so pinning one fails once per task.
-# Pin a base id.
-# Both gpt-5.6-terra and gpt-5.6-sol are evaluated, each in its OWN results tree (the model
-# is part of the cost basis). This picks the default for a command that does not pass MODEL=;
-# docs/RUNNING.md section 5 loops the arm catalog over both.
-CODEX_MODEL=gpt-5.6-sol
+# The Copilot CLI bills the Anthropic API too, through its own provider settings. It does not
+# read ANTHROPIC_API_KEY, so give it the same key again here.
+COPILOT_PROVIDER_TYPE=anthropic
+COPILOT_PROVIDER_BASE_URL=https://api.anthropic.com
+COPILOT_PROVIDER_API_KEY=
-# --- GitHub Copilot CLI (AGENT=copilot) -----------------------------------------------------
-# The Copilot CLI is its own sealed agent and needs no API key: it authenticates against
-# GitHub from ~/.copilot (or a token in COPILOT_GITHUB_TOKEN / GH_TOKEN / GITHUB_TOKEN).
-# Full guide: docs/COPILOT.md.
-#
-# Copilot serves its own model catalog, so an Anthropic id is NOT valid here. 'auto' lets
-# the CLI route; a pinned id fixes the cost basis but must be one your subscription serves
-# (`copilot -p ok --model <id>` tells you). Caveat: 'auto' REJECTS a reasoning-effort flag,
-# so TE_EFFORT_LEVEL above is recorded as null and not applied unless you pin a model.
-COPILOT_MODEL=auto
-# headless/unattended alternative to `copilot /login`
-# COPILOT_GITHUB_TOKEN=
-#
-# BYOK -- Copilot's own built-in "bring your own key": bill your OWN provider instead of the
-# Copilot subscription. THE SUBSCRIPTION IS THE DEFAULT; this is the fallback for a host with no subscription, or one whose monthly quota
-# is spent (which surfaces as HTTP 402 `quota_exceeded` and a tree of turns=1/eff_tok=0
-# rows). COPILOT_PROVIDER_BASE_URL is the ONE switch: set it and the CLI bills that provider
-# and does not use GitHub auth at all. Full variable list: `copilot help providers`.
-#
-# A BYOK row and a subscription row are DIFFERENT COST BASES. The tree name says
-# `copilot_*` either way, so run_config.json -> routing.base_url is what tells them apart:
-# the provider URL under BYOK, the literal `github-copilot` on a subscription. Do not pool
-# the two (docs/COPILOT.md).
-# COPILOT_PROVIDER_TYPE=anthropic # openai (default) | azure | anthropic
-# COPILOT_PROVIDER_BASE_URL=https://api.anthropic.com
-# COPILOT_PROVIDER_API_KEY= # same key as ANTHROPIC_API_KEY above
-# NOTE: a trailing `# comment` on the same line becomes part of the value -- both loaders
-# treat only a WHOLE-LINE `#` as a comment. Uncomment the bare assignment, not these lines.
-
-# --- Data + results roots (see docs/BENCHMARKS.md, te_data/env.sh) ------------------------
-# These are site-specific paths with NO built-in default: the SWE-bench harness raises
-# at construction when one is missing, instead of resolving to a path that only exists on
-# whichever machine wrote the code. DATA is the root holding swebench/swebench_grading.json
-# and is the shorthand TE_SWEBENCH_GRADING falls back to.
+# --- Data (absolute paths; see README.md, Setup) ---------------------------------------------
+# DATA holds the benchmark data, the staged rtk binary ($DATA/scaffolds) and, unless
+# TE_SWEBENCH_GRADING is set, the grading file ($DATA/swebench/swebench_grading.json).
DATA=
-TE_SWEBENCH_REPO=
-TE_SWEBENCH_GRADING=
-# External tool baselines (tokeneconomizer/baselines/): where the pinned rtk release binary is
-# staged host-side, because the sealed task container cannot reach GitHub. Defaults to
-# $DATA/scaffolds when DATA is set. Only the rtk-bearing arms read it: rtk, trimech-rtk,
-# trimech-rtk-web and codex-trimech-rtk.
-TE_SCAFFOLD_CACHE=
+TOKENECONOMIZER_RESULTS=
TOKENECONOMIZER_SWEBENCH_TASKS=
-TOKENECONOMIZER_WEBBENCH_TASKS=
+TE_SWEBENCH_REPO=
TOKENECONOMIZER_WEBBENCH_PROJECTS=
-TOKENECONOMIZER_RESULTS=
-
-# Every other harness knob -- turn caps, timeouts, the probes, the container CPU limit, the
-# answer-key override -- is in the config table in docs/HARNESS.md. Nothing there is
-# required: each has a default the harness states.
-
-# --- Host resource budget ------------------------------------------------------------------
-# TE_SWEBENCH_MAX_CPUS caps ONE task container (default 16) plus the OMP/MKL/OPENBLAS/NUMEXPR/
-# LOKY thread caps that must agree with it -- `--cpus` alone does not change what `nproc`
-# reports inside, so a parallel test suite would still size its pool to the whole host and
-# thrash. 0 = unlimited. Recorded per row in run_config.json -> cpu_limit.
-#
-# TE_FLEET_CPUS is the one that bounds the HOST: N concurrent lanes are an N x cap ceiling, so
-# the per-container value cannot do it. scripts/launch/fleet_budget.sh writes this onto the
-# cgroup every rootless-docker container scope shares, which binds lanes that are ALREADY
-# running and needs no restart. 0/none = do not enforce. The Codex launcher asserts it.
-# TE_SWEBENCH_MAX_CPUS=4
-# TE_FLEET_CPUS=16
-
-# --- Harness seam -------------------------------------------------------------------------
-# `stub` (offline StubRunner, no Docker/LLM) or `module:factory` returning an AgentRunner.
-# stub runs NO agent and grades nothing -- its rows are synthetic, for wiring checks only,
-# and the launchers now say so loudly at startup. For a real run point this at a harness --
-# the repo's own needs no PYTHONPATH, since the driver puts experiments/ and the core on
-# sys.path:
-# RUNNER=te_harness.swebench:make_runner # SWE-bench
-# RUNNER=te_harness.webbench:make_runner # Web-Bench (all three agents)
-RUNNER=stub
+TOKENECONOMIZER_WEBBENCH_TASKS=
diff --git a/experiments/README.md b/experiments/README.md
index 6a25e1e..3e0fa39 100644
--- a/experiments/README.md
+++ b/experiments/README.md
@@ -1,258 +1,182 @@
-# TokenEconomizer — reproducing the paper's experiments
+# Reproducing the experiments
-This directory holds the code behind the paper: the Docker benchmark harness, the sweep and
-aggregation scripts, the evaluated task sets, and the run book. It is **not part of the
-plugin** and is not packaged with it. The plugin, and the shared core both use, live at the
-repository root; see [`../README.md`](../README.md).
+This directory is the code behind the paper's results: a harness that runs Claude Code, Codex
+and the Copilot CLI on SWE-Bench and Web-Bench, the launchers, and the aggregation scripts. It
+is not part of the plugin; the method is described in the [main README](../README.md).
-Everything here keeps the layout the experiments were run with: `te_harness/`, `scripts/`,
-`workloads/` and `docs/` sit side by side. The shared core, `tokeneconomizer`, stays at the
-repository root, one level up, and the scripts put both directories on `sys.path`
-themselves (an editable install, `pip install -e ..`, works too). Run commands from this
-directory (`cd experiments`), or by path from anywhere; the scripts locate their own root. The `.env` the scripts read is
-`experiments/.env`, else the repository root's.
-
-### Experience-driven black-box cost control for coding agents
-
-**Externally-delivered, agent-agnostic middleware that aims to cut a sealed coding agent's
-amortized token cost without hurting task success.**
-
----
-
-## The problem
-
-A sealed coding agent — Claude Code, the Copilot CLI, Codex — is optimized for **task
-success, not the token bill**. You cannot retrain it, patch it, or see inside it. What you
-get is a fixed interface: a launch command, an instruction channel, a tool contract, and a
-stream of events. Meanwhile its transcript grows monotonically and is replayed into every
-model call.
-
-That shape produces three costs that recur on *every task in a stream*, not once:
-
-| | Cost region | What it looks like |
-|---|---|---|
-| 1 | **Repeated environment discovery** | Re-probing the test command, the build, the repo layout — things the agent already worked out on the previous task, and the task before that. |
-| 2 | **The fixed tool contract** | Every tool schema re-sent on every turn, including the ones this repository will never need. |
-| 3 | **The unproductive tail** | Tokens burned after a rollout has stopped making progress but before it gives up. |
-
-An experienced engineer working in a familiar repository avoids all three. They already know
-the test command, they don't reach for tools the project doesn't use, and they abandon a dead
-approach early.
-
-## The question this repository asks
-
-**Can an external controller supply that familiarity while leaving the agent completely
-fixed** — no weight updates, no fine-tuning, no changes to agent code?
-
-A static plugin is not enough, and that is the substantive claim. How much there is to save,
-and where, depends on the repository, the harness, the agent's tool surface, and the
-trajectory currently unfolding. So the controller has to be **stateful and observational**:
-it reads completed and live traces, maintains per-repository state across a task stream, and
-acts only through interfaces the harness already exposes — the launch call, the instruction
-channel, and the event stream.
-
-Three independently-switchable mechanisms each target one cost region, at a different point
-in a task's lifecycle:
-
-```
-task lifecycle: ── inject ──▶ construct tools ──▶ ═══ rollout ═══▶ finalize ──
- │ │ │
- injection tooling spiral
- learned per-repo drop inapplicable kill/nudge a stuck
- operating manual tool schemas / rollout vs a learned
- before the task capabilities resolved-turn envelope
- (between tasks) (before each task) (during rollout)
+| Path | Contents |
+|---|---|
+| `te_harness/` | runs an agent CLI in each SWE-Bench task's Docker image (on the host for Web-Bench) and grades it with the benchmark's own grader |
+| `te_bench/` | the experiment arms, the benchmark adapters, and the evaluated task sets (`workloads.py`) |
+| `scripts/` | `launch/` (the launchers), `run_experiment.py` (one arm on one task stream), `aggregate.py` and `compare_arms.py` |
+| `workloads/` | the evaluated task ids: `swebench.json` (277 tasks), `webbench.json` (102), and the security sets |
+| `tests/` | offline tests: no Docker, data or API keys |
+
+## Requirements
+
+- Linux x86_64 with Docker usable without `sudo`, and about 200 GB of disk for the SWE-Bench
+ images.
+- Python 3.10 or newer, git, and Node.js with npm (for Web-Bench).
+- An Anthropic API key and an OpenAI API key. Claude Code and the Copilot CLI bill the first,
+ Codex the second.
+- The agent CLIs on the host, at the versions the paper used. The harness mounts them into
+ each task container.
+
+```bash
+curl -fsSL https://claude.ai/install.sh | bash -s 2.1.170 # Claude Code
+npm install -g @openai/[email protected] # Codex
+curl -fsSL https://gh.io/copilot-install | VERSION=1.0.84-7 bash # Copilot CLI
```
-Because they are independently switchable, each can be measured alone as an ablation of the
-combined stack rather than as a separate system.
-
-| Mechanism | Module | What it does |
-|---|---|---|
-| **injection** (micro-skills) | `tokeneconomizer/microskills/` | A paid proposer learns a firing-gated per-repo operating manual (the canonical test command, "a repro script is redundant here", a required env var) over the task stream, and injects it before each task. A formation / decay / firing-gate lifecycle keeps only facts that actually fire. |
-| **tooling** (tool pruning) | `tokeneconomizer/toolprune/` | Drops inapplicable tool schemas: evidence untooling (loaded-but-unused for *N* consecutive tasks) plus an optional instruction-aware judge. Never drops a protected tool — without an edit path and a shell there is no task. |
-| **spiral** (loop guard) | `tokeneconomizer/loopguard/`; the benchmark controllers `te_bench/spiral_stage.py`, `te_bench/nudge_guard.py`, `te_bench/codex_spiral.py` | Kills or nudges a stuck rollout against a learned per-repo resolved-turn envelope: cheap gate → sampled LLM judge → nudge, then abort. |
+## Setup
-## What is actually measured
+**1. Install and check the code.** Every command after `cd experiments` runs from this directory.
-The objective is to **minimize cache-aware effective cost while holding resolve rate** (or
-F1, on the classification domains).
-
-Two properties make that honest rather than rhetorical:
-
-- **Cache-aware cost.** Most raw transcript tokens are cached re-reads. Counting them at full
- weight would let a method look good merely by pruning cheap repetition, so cost is
- measured in fresh-input-token equivalents.
-- **The controller pays for itself.** Every token the controller spends — proposer, tool
- judge, spiral judge, nudge writer — is charged back to TokenEconomizer in the same ledger
- as the task. Reported savings are **net of the mechanisms' own overhead**, so a mechanism
- that buys savings with paid calls has to win on the balance.
-
-One consequence worth stating up front: a mechanism's overhead line is *not* a saving
-available by deleting it, because the mechanisms shape the trajectory that produces every
-other number in the row. Use the ledger to price a mechanism, not to predict its removal.
-
-Results are not part of this repository; the code here produces them.
-
----
-
-## How the repository is organised
+```bash
+git clone https://github.com/microsoft/TokenEconomizer.git && cd TokenEconomizer
+python3 -m venv .venv && . .venv/bin/activate
+pip install -e '.[test,baselines]' # baselines: aider, for the RepoMap arms
+cd experiments
+python -m pytest tests -q
+bash scripts/launch/smoke_test.sh # every arm wired end to end, with a stub agent
+```
-The layout follows one rule: **the controller must not be able to reach the things it is
-supposed to be independent of.** That is enforced structurally, by what sits underneath
-what, rather than by convention.
+**2. SWE-Bench.** Pick a data directory outside the repository, and use its canonical path:
+Web-Bench fails every test when reached through a symlink.
-### Three layers
+```bash
+export DATA="$(readlink -f ~/te_data)"
+git clone https://github.com/SWE-bench/SWE-bench.git "$DATA/SWE-bench"
+pip install -e "$DATA/SWE-bench" # the official grader, into this venv
+python scripts/export_swebench_tasks.py --out-dir "$DATA/swebench"
+docker login # anonymous pulls are rate-limited
+xargs -a "$DATA/swebench/image_tags.txt" -P 4 -n 1 docker pull -q
+```
-**Layer 1 — `tokeneconomizer/`, the controller.** The mechanisms, the cost definition, and
-the trace reader. It is **stdlib-only with zero runtime dependencies**: `import
-tokeneconomizer` cannot touch Docker, an agent CLI, or an LLM SDK, because none of that code
-lives beneath it. This is what makes the agent-agnostic claim checkable instead of
-aspirational.
+The export writes the task list, the grading file and the list of the 277 task images.
-**Layer 2 — `te_harness/`, the reference harness.** The heavy machinery: launching a sealed
-agent inside a benchmark's Docker image, applying the controller's per-task decisions,
-streaming events back, and grading with the benchmark's *official* grader. It is a
-**sibling** package of `tokeneconomizer`, not a submodule, and is excluded from the
-distributed wheel — which is precisely what keeps Layer 1's guarantee structural. Swapping in
-your own harness is a supported path, not a fallback: nothing above the seam changes, because
-the controller never learns which harness it is talking to.
+**3. Web-Bench.** The five evaluated projects, built, with the Playwright browser they pin:
-`tokeneconomizer/plugin/` is the second harness, and the proof of that claim: the plugin
-runtime runs the same mechanism classes inside a user's own Claude Code, Codex, Copilot CLI or
-Pi sessions, through the hooks the agent exposes, and `plugin/` (at the repository root)
-packages it for installation. The mechanisms never import it (a test pins that); it ships in
-the wheel, because it is what `te` runs. See [`../docs/PLUGIN.md`](../docs/PLUGIN.md).
+```bash
+git clone https://github.com/bytedance/web-bench.git "$DATA/web-bench"
+( cd "$DATA/web-bench" && npm install -g @microsoft/rush && rush install \
+ && rush build --to @web-bench/eval --to @web-bench/calculator --to @web-bench/expressjs \
+ --to @web-bench/react --to @web-bench/zustand --to @web-bench/table \
+ && cd projects/calculator && npx playwright install chromium chromium-headless-shell )
+export TOKENECONOMIZER_WEBBENCH_PROJECTS="$DATA/web-bench/projects"
+export TOKENECONOMIZER_WEBBENCH_TASKS="$DATA/webbench_tasks.json"
+python scripts/webbench_tasks_from_yaml.py --all # zustand ships only tasks.yml
+python scripts/export_webbench_tasks.py
+```
-**Layer 3 — `scripts/`, the reproduction pipeline.** Planning a sweep, driving one arm,
-aggregating row trees into CSVs, and comparing arms. Nothing here is imported by Layers 1
-or 2.
+**4. Keys and paths.** `cp .env.example .env`, then fill it in with absolute paths (the file
+does not expand variables):
-### The four seams
+| Variable | Value |
+|---|---|
+| `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` | your keys |
+| `COPILOT_PROVIDER_API_KEY` | your Anthropic key again: the Copilot CLI bills Anthropic through its own provider settings, already set in the file |
+| `DATA` | the data directory |
+| `TOKENECONOMIZER_RESULTS` | where results go, e.g. `$DATA/results` |
+| `TOKENECONOMIZER_SWEBENCH_TASKS` | `$DATA/swebench/swebench_tasks.json` |
+| `TE_SWEBENCH_REPO` | `$DATA/SWE-bench` |
+| `TOKENECONOMIZER_WEBBENCH_PROJECTS`, `TOKENECONOMIZER_WEBBENCH_TASKS` | as exported in step 3 |
+
+**5. One paid task.** Before a full run, check that one task produces a graded row:
+
+```bash
+AGENT=claude MODEL=claude-sonnet-5 DOMAIN=swebench ARMS=baseline REPOS=sympy/sympy SEEDS=0 \
+ LIMIT=1 DETACH=0 RUNNER=te_harness.swebench:make_runner bash scripts/launch/main_sweep.sh
+```
-Every crossing between layers goes through exactly one interface, which is why a new agent,
-harness, or benchmark is an addition rather than an edit:
+Its `row.json`, under `$TOKENECONOMIZER_RESULTS/claude_swebench_sonnet5/baseline/sympy_s0/`,
+should show `num_turns` above zero, token counts, and a `resolved` value.
-| Seam | Module | Separates |
-|---|---|---|
-| `AgentRunner` | `runner.py` | the controller from task execution and paid LLM calls |
-| `DomainAdapter` | `domain.py` | the controller from what a "task" is |
-| trace | `trace/` | every mechanism from the shape of a rollout's event stream |
-| ledger | `ledger.py` | every mechanism from the definition of cost |
+## Running the paper's experiments
-The mechanisms read rollouts through the one trace seam and charge cost through the one
-ledger, so a change to either is a change in one place, and no mechanism can quietly adopt
-its own accounting.
+`main_sweep.sh` runs Claude Code and the Copilot CLI, `codex_ab.sh` runs Codex. Each command
+below is one lane, one agent and model on one benchmark: every arm it names, on every
+repository or project, with seeds 0, 1 and 2. A lane runs in the background and prints where
+its log is and how to stop it, so the commands in a loop run in parallel. Run a command again
+to resume a lane: cells already finished are skipped. `DRYRUN=1` prints a lane's plan without
+running it, and `DETACH=0` keeps it in the foreground.
-### The tree
+The arms, by the names the paper uses:
+| Arm | In the paper |
+|---|---|
+| `baseline`, `baseline-medium`, `baseline-low` | default execution at high, medium and low effort |
+| `rtk`, `repomap` | the fixed strategies RTK and RepoMap |
+| `trimech` (`codex-trimech` on Codex) | TokenEconomizer |
+| `trimech-rtk`, `trimech-repomap` (`codex-trimech-…`) | TokenEconomizer+RTK, TokenEconomizer+RepoMap |
+| `inject-only`, `untool-only`, `spiral-only` | micro-skills, tool pruning and the failure-loop guard alone |
+| `trimech-web` | TokenEconomizer on Web-Bench, whose streams are short |
+
+**SWE-Bench: Table 1, Figures 1(b) and 5, and the ablation in Table 2(a).**
+
+```bash
+SWE="baseline baseline-medium baseline-low rtk repomap trimech trimech-rtk trimech-repomap"
+for MODEL in claude-sonnet-5 claude-opus-4-8; do
+ AGENT=claude MODEL=$MODEL DOMAIN=swebench ARMS="$SWE inject-only untool-only spiral-only" \
+ RUNNER=te_harness.swebench:make_runner bash scripts/launch/main_sweep.sh
+done
+AGENT=copilot MODEL=claude-sonnet-5 DOMAIN=swebench ARMS="$SWE" \
+ RUNNER=te_harness.swebench:make_runner bash scripts/launch/main_sweep.sh
+for MODEL in gpt-5.6-terra gpt-5.6-sol; do
+ MODEL=$MODEL DOMAIN=swebench \
+ ARMS="baseline baseline-medium baseline-low rtk repomap codex-trimech codex-trimech-rtk codex-trimech-repomap" \
+ RUNNER=te_harness.swebench:make_runner bash scripts/launch/codex_ab.sh
+done
```
-experiments/ the paper's reproduction code (this directory)
- te_bench/ Layer 1b — the benchmark side of the controller; the plugin never
- ships or imports it
- facade.py Economizer, the orchestration entry point
- spiral_stage.py nudge_guard.py codex_spiral.py
- the loop guard as the benchmark runs it: the stage, the streamed
- kill-and-resume guard, the Codex finalize policy
- arms.py mechanism_arms.py _armspec.py
- named arm → exact configuration (the experiment's vocabulary)
- runner.py AgentRunner interface — the harness seam
- workloads.py the evaluated task set, as data (which instances, per domain)
- adapters/ swebench · webbench · creddata · reposvul · cybergym · webarena
- baselines/ third-party tool scaffolds (rtk · serena · aider repo-map) —
- comparison points, not mechanisms
- te_harness/ Layer 2 — reference AgentRunner: Docker + agent CLIs + official graders
- swebench.py agent in the instance's pinned image, graded by get_eval_report
- webbench.py agent at the Node evaluator's HTTP seam, graded by its own suites
- copilot.py Copilot CLI overrides (GitHub auth, own catalog, own accounting)
- codex.py Codex CLI seam — the OpenAI API, the capability→config
- mapping, own accounting
- guards/ measurement-integrity guards — refusing fetches of a benchmark's
- own answer key, enforced twice: a PreToolUse hook in each CLI's
- own hook file, and an /etc/hosts block in the task container
- capture_catalog.py mines the real tool catalog off a live run's wire
- scripts/ Layer 3 — reproduction pipeline (planning, driving, aggregating, comparing)
- workloads/ the evaluated task sets as committed JSON (ids only, ~28 KB)
- docs/ setup, provisioning, the harness, the run book (see below)
- tests/ offline suite for the harness and pipeline — no Docker, no datasets
-
-../tokeneconomizer/ Layer 1 — the controller (stdlib-only, zero deps): what the plugin ships
- microskills/ toolprune/ loopguard/
- the three mechanisms (injection · tooling · spiral in the arms)
- trace/ the one trace seam: each agent's session-log format
- config.py ledger.py pricing.py
- the mechanisms' switches, the one cost definition, the price table
- domain.py stage.py the DomainAdapter interface (benchmark adapters are in te_bench/)
- and the Stage hooks
- plugin/ the plugin runtime; repomap_gen.py there is aider's repo-map
- generator, run as a subprocess by the plugin's opt-in map and by
- the repomap baseline
-../plugin/ the installable plugin directory (see ../README.md)
-
-── and deliberately NOT in the repository ───────────────────────────────────────
-te_data/ the data root, beside the repository: benchmark checkouts, task
- specs, grading tables, Docker-image manifests, every results tree.
- Reached only through TOKENECONOMIZER_* / DATA env vars.
-```
-
-### The data root lives *outside* the repository
-Nothing large that the project reads or writes belongs in the checkout. Benchmark
-checkouts, task specifications, grading tables, and every results tree live under **one data
-root of your choosing, outside the repo** — conventionally `te_data/` beside it — and the
-code reaches it only through `TOKENECONOMIZER_*` / `DATA` environment variables.
+**Web-Bench: Table 2(b).** The same agent–model settings as on SWE-Bench.
+
+```bash
+for MODEL in claude-sonnet-5 claude-opus-4-8; do
+ AGENT=claude MODEL=$MODEL DOMAIN=webbench ARMS="baseline trimech-web" \
+ RUNNER=te_harness.webbench:make_runner bash scripts/launch/main_sweep.sh
+done
+AGENT=copilot MODEL=claude-sonnet-5 DOMAIN=webbench ARMS="baseline trimech-web" \
+ RUNNER=te_harness.webbench:make_runner bash scripts/launch/main_sweep.sh
+for MODEL in gpt-5.6-terra gpt-5.6-sol; do
+ MODEL=$MODEL DOMAIN=webbench ARMS="baseline codex-trimech" \
+ RUNNER=te_harness.webbench:make_runner bash scripts/launch/codex_ab.sh
+done
+```
-The reason is scale, and then three practical ones. A working root for this project runs to
-tens of gigabytes (the Web-Bench monorepo alone is ~24 GB, results trees a few GB more),
-on top of ~165 GB of pinned per-instance Docker images that live in the daemon's own store.
-None of that is versionable, and none of it should be one `git add -A` away from a commit.
-Beyond size:
+**Security benchmarks.** The CredData and ReposVul task sets (`workloads/creddata.json`,
+`workloads/reposvul.json`) and their adapters are included, but this harness does not run or
+grade them.
-- **A clone becomes disposable.** Delete or re-clone the repo and your results are untouched
- — which is what makes it safe to test a change in a throwaway clone against the corpus you
- already have.
-- **Several checkouts can share one root.** Two clones, or a git worktree, can run against
- the same provisioned data and the same results tree without re-provisioning any of it.
-- **No machine-specific path is baked into the code.** These variables have no built-in
- defaults on purpose: the harness raises at construction when one is missing rather than
- silently resolving to a path that only exists on whichever machine wrote the code.
+Every arm, the baseline included, runs behind an answer-key guard that blocks the benchmarks'
+public answers on GitHub. The rtk binary is downloaded into `$DATA/scaffolds`.
-`.gitignore` is the belt-and-braces half of the same decision — `results/`, `*.csv`,
-`*.jsonl`, rendered images and `.env` are all excluded — but the primary defence is that
-the data was never inside the tree to begin with. [`docs/ENVIRONMENT.md`](docs/ENVIRONMENT.md)
-and [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) cover the layout and what to put where.
+## Results
-### Provenance, kept as data
+Each lane writes one results tree, `$TOKENECONOMIZER_RESULTS/<agent>_<benchmark>_<model>/`
+(for example `claude_swebench_sonnet5`), with one directory per arm and cell
+(`<arm>/<repository>_s<seed>/`) and a run directory per task holding `row.json`,
+`transcript.jsonl` and `run_config.json`. At the end of a lane, `aggregate.py` writes
+`index/all_rows.csv`, one row per task run, and `index/summary_by_cell.csv`, one row per arm,
+repository and seed; run `python scripts/aggregate.py <tree>` to refresh it. A task run again
+keeps both runs, and the index takes the newest.
-The identities of the evaluated tasks live in the core package (and are mirrored as committed
-JSON under `workloads/`), not in a results tree. So the exact set a published number was
-computed over can be re-provisioned and re-run without inheriting anyone's output directory.
-The published corpus ran a fixed subset per domain rather than a whole benchmark; two
-SWE-bench streams have since been extended because every arm had saturated them, so a *new*
-run's task set is deliberately not identical to the recorded one — [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md)
-spells out both.
+```bash
+python scripts/compare_arms.py --baseline <tree>/baseline/<cell> --arm <tree>/<arm>/<cell>
+```
----
+`compare_arms.py` pairs one cell's tasks by instance and reports cost and resolved tasks
+against the baseline. Cost is in cache-aware effective tokens and includes the arm's own model
+calls. Web-Bench rows carry `resolved_p2`, the Pass@2 the paper reports. Never pool two trees:
+the agent and the model are both part of the cost basis.
-## Where things are documented
+## Troubleshooting
-| Document | What it covers |
+| Symptom | Cause |
|---|---|
-| [`../docs/METHOD.md`](../docs/METHOD.md) | why the mechanisms are shaped this way |
-| [`docs/SETUP.md`](docs/SETUP.md) | fresh clone → running, gated step by step |
-| [`docs/ENVIRONMENT.md`](docs/ENVIRONMENT.md) | machine requirements and Docker setup |
-| [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) | per-benchmark provisioning and on-disk layout |
-| [`docs/HARNESS.md`](docs/HARNESS.md) | the `AgentRunner` seam, and writing your own harness |
-| [`docs/COPILOT.md`](docs/COPILOT.md) | running the Copilot CLI as the sealed agent |
-| [`docs/RUNNING.md`](docs/RUNNING.md) | the run book: authentication per agent, the arm catalog, one command per lane |
-
-**The plugin** — the mechanisms in your own sessions — is documented at the repository root:
-[`../README.md`](../README.md) and [`../plugin/README.md`](../plugin/README.md).
-
-**Start here:** [`../docs/METHOD.md`](../docs/METHOD.md) for the ideas,
-[`docs/SETUP.md`](docs/SETUP.md) to get it running, and
-[`docs/RUNNING.md`](docs/RUNNING.md) to reproduce the experiments.
-
-Requires Python ≥ 3.10. The core has no runtime dependencies; `requirements.txt` here covers
-the test suite (`python -m pytest tests`, from this directory, or
-`python -m pytest` at the repository root for both suites).
+| a launch prints `RUNNER=stub -- SYNTHETIC run` | `RUNNER` was not set; the stub runs no agent |
+| `ModuleNotFoundError` at grading | the SWE-Bench grader is not installed in the venv the launcher uses (step 2) |
+| every Web-Bench test fails and the app never renders | a non-canonical data path; `readlink -f` it (step 2) |
+| `Executable doesn't exist at …/chromium_headless_shell-…` | Playwright was installed outside a project, so its browser build differs from the one the projects pin (step 3) |
+| Codex gets 401 with a valid key | a key issued for a regional endpoint; set `OPENAI_BASE_URL` in `.env` |
+| a lane needs stopping | `kill -TERM -$(cat <log>.pid)`, as printed at launch; the leading `-` stops the whole process group |
diff --git a/experiments/docs/BENCHMARKS.md b/experiments/docs/BENCHMARKS.md
deleted file mode 100644
index 673691b..0000000
--- a/experiments/docs/BENCHMARKS.md
+++ /dev/null
@@ -1,494 +0,0 @@
-# Benchmark provisioning — images, datasets, and env vars
-
-> Per-benchmark reference detail. If you are setting up from a fresh
-> clone, start with [`SETUP.md`](SETUP.md) and come here at its data step.
-
-This is the operational companion to [`../scripts/launch/README.md`](../scripts/launch/README.md).
-It documents, per benchmark, **exactly what you must pull/fetch/build and where it must land**
-before an economized A/B can run.
-
-> **Set up your environment first.** [`ENVIRONMENT.md`](ENVIRONMENT.md) covers the two layers
-> (the core package vs. the harness and what it drives), the `requirements.txt`, and Docker
-> install/update for beginners. The per-benchmark provisioning below is the harness layer.
-
-## What lives where (and why this doc exists)
-
-TokenEconomizer is middleware: it observes traces, maintains per-repo state, and decides
-per-task interventions. It **never pulls an image or downloads a dataset itself** — that is
-the job of the task-execution harness below the `AgentRunner` seam
-(`RUNNER=te_harness.swebench:make_runner`, or your own; see [`HARNESS.md`](HARNESS.md)).
-Nothing provisioned below is committed: the harness is code, and these are payloads.
-
-### The two kinds of path you configure (do not confuse them)
-
-Every domain has **two** independent inputs, read by **two** different components:
-
-| # | What | Read by | Value | Env var pattern |
-|---|---|---|---|---|
-| A | **Task list** | `run_experiment.py` (the driver) — `json.load()`s it | a **JSON file** (a list of `{instance_id, problem_statement, repo}`) | `TOKENECONOMIZER_<DOMAIN>_TASKS` |
-| B | **Dataset root** | the domain **adapter** + your harness | a **directory / suite file** with the raw data | `TOKENECONOMIZER_<DOMAIN>_ROOT` (or `_PROJECTS` / `_SUITE`) |
-
-- **A (task list)** is what the driver iterates and what the per-task tool judge reads. It is
- **always a JSON file path** — pointing it at a directory will crash with `IsADirectoryError`.
-- **B (dataset root)** is where the actual source/labels live, used by the adapter to enumerate
- instances and by your harness to materialize each task's workspace.
-
-For **SWE-bench only**, A and B are the *same file*: `TOKENECONOMIZER_SWEBENCH_TASKS` is both
-the driver's task list and the adapter's instance source. For every other domain they are
-**different** — you export a small task-list JSON (A) *and* set the dataset root (B).
-
-The commands below are the reference provisioning recipe; adapt paths to your infra.
-**All fetched data is git-ignored** — none of it is committed to this repo.
-
-### Which tasks to actually run — `te_bench.workloads`
-
-The experiments do **not** run a whole benchmark. Each domain uses a fixed subset, and that subset is data in the core package — importable on a bare clone, with
-no results tree, no datasets, and no Docker:
-
-```python
-from te_bench import workloads
-
-workloads.task_counts("swebench") # {'django/django': 40, ..., 'pydata/xarray': 39}
-workloads.total_tasks("swebench") # 229 tasks per seed
-workloads.instances("swebench", "pydata/xarray") # the exact 39 instance ids
-workloads.swebench_image_tag("django__django-11532") # the image to pull for one task
-```
-
-| Domain | Workload | Seeds |
-|---|---|---|
-| SWE-bench | **229** recorded over 6 repos (django 40, sphinx 44, sympy 40, xarray 39, matplotlib 34, sklearn 32); a NEW run executes **277** — `workloads.SWEBENCH_EXCLUDED` drops one sklearn instance and `workloads.SWEBENCH_ADDED` extends the two saturated streams, so `runnable_instances()` reports **sklearn 60** and **sympy 60** | `0 1 2` |
-| Web-Bench | **102** tasks over 5 projects (calculator 21, table 21, expressjs/react/zustand 20 each) | `A B C` |
-| CredData | **100** of the 333 repo ids | `0 1 2` |
-| ReposVul | **100** instances, all from the **Python** split (`py-*`) | `0 1 2` |
-
-Provision only what the workload names — it is a small fraction of each full benchmark, and
-for SWE-bench it is the difference between ~277 and 2,294 multi-GB images.
-
-The same lists ship as committed JSON manifests under [`../workloads/`](../workloads/) —
-ids only, ~16 KB for all four, readable without importing the package. The launchers default
-`WORKLOAD` to `workloads/$DOMAIN.json` and pass it to the driver, so a launch is pinned to the
-evaluated set even when your `TASKS_FILE` holds a superset (`WORKLOAD=none` opts out):
-
-```bash
-# uses workloads/swebench.json automatically:
-AGENT=claude DOMAIN=swebench ARM=trimech REPOS="pydata/xarray" SEEDS="0 1 2" \
- RUNNER=te_harness.swebench:make_runner bash scripts/launch/trimech_ab.sh
-
-# or explicitly, straight to the driver:
-python scripts/run_experiment.py --workload workloads/swebench.json --repo pydata/xarray ...
-```
-
-To pin a run to exactly the evaluated set from Python instead, filter the task list yourself:
-
-```python
-tasks = json.load(open(os.environ["TOKENECONOMIZER_SWEBENCH_TASKS"]))
-tasks = workloads.filter_tasks(tasks, "swebench", "pydata/xarray") # exactly 39
-```
-
-> Prefer `filter_tasks` over the driver's `--repo` flag. That flag prefix-matches the repo's
-> short name against `instance_id` and **falls back to the entire task list when nothing
-> matches** (`run_experiment.py:188`) — which is what happens for any repo whose org differs
-> from its name, `pydata/xarray` included.
-
-### Set a base directory first
-
-Every command below writes under `$DATA`. Pick any writable path and export it once
-(`$TOKENECONOMIZER_RESULTS` is where runs land — also your choice):
-
-```bash
-export DATA="$HOME/te_data" # anywhere you like; holds datasets + task lists
-export TOKENECONOMIZER_RESULTS="$DATA/results" # git-ignored results tree
-mkdir -p "$DATA" "$TOKENECONOMIZER_RESULTS"
-```
-
-### Quick map of every placeholder
-
-| Env var | Kind | Consumed by | Points at |
-|---|---|---|---|
-| `TOKENECONOMIZER_SWEBENCH_TASKS` | A + B | driver + swebench adapter | SWE-bench instances JSON (`{instance_id, problem_statement, repo}`) |
-| `TOKENECONOMIZER_WEBBENCH_TASKS` | A | driver | Web-Bench task-list JSON you export (below) |
-| `TOKENECONOMIZER_WEBBENCH_PROJECTS` | B | webbench adapter | Web-Bench `projects/` tree (each has `tasks.jsonl`) |
-| `TOKENECONOMIZER_CREDDATA_TASKS` | A | driver | CredData task-list JSON you export (below) |
-| `TOKENECONOMIZER_CREDDATA_ROOT` | B | creddata adapter | CredData checkout (`data/`, `meta/`) |
-| `TOKENECONOMIZER_REPOSVUL_TASKS` | A | driver | ReposVul task-list JSON you export (below) |
-| `TOKENECONOMIZER_REPOSVUL_ROOT` | B | reposvul adapter | prepared ReposVul (`instances/*.json`) |
-| `TOKENECONOMIZER_CYBERGYM_SUITE` | B | cybergym adapter | CyberGym suite JSON |
-| `TOKENECONOMIZER_RESULTS` | — | aggregate + harness | results trees the harness writes and the aggregator reads |
-| `<DOCKER_IMAGE>` | — | your harness (not this repo) | the era-pinned benchmark image |
-
----
-
-## 1. SWE-bench (primary — Claude / Copilot `trimech`, Codex arms)
-
-**Dataset.** SWE-bench Verified (500 instances) from Hugging Face. The economizer only needs
-the issue text; the grading gold patch stays inside your harness. Here the task list (A) and
-the adapter's instance source (B) are the **same file**.
-
-> **Verified alone is not enough.** A new run executes 277 instances and **79 of them are
-> not in Verified**: the recent `pydata/xarray` tail (30, `workloads.SWEBENCH_FULL_SPLIT_ONLY`)
-> plus all 49 de-saturation additions (`workloads.SWEBENCH_ADDED_FULL_SPLIT_ONLY` — both
-> repos' Verified rows were already spent). Build the task file from both splits and take
-> the union named by `workloads.runnable_instances("swebench")`; those two frozensets list
-> exactly which instances force the second fetch.
-
-```bash
-mkdir -p "$DATA/swebench"
-python - <<'PY'
-import json, os
-from datasets import load_dataset # pip install datasets (provisioning only)
-from te_bench import workloads
-
-wanted = {i for ids in workloads.runnable_instances("swebench").values() for i in ids} # 277
-rows, seen = [], set()
-for name in ("princeton-nlp/SWE-bench_Verified", "princeton-nlp/SWE-bench"):
- for r in load_dataset(name, split="test"): # Verified first, then the
- iid = r["instance_id"] # full split for the 30 extras
- if iid in wanted and iid not in seen:
- seen.add(iid)
- rows.append({"instance_id": iid, "repo": r["repo"],
- "problem_statement": r["problem_statement"]})
- if seen >= wanted:
- break
-missing = wanted - seen
-out = os.path.join(os.environ["DATA"], "swebench", "swebench_tasks.json")
-json.dump(rows, open(out, "w"))
-print(len(rows), "->", out, "| missing:", sorted(missing) or "none")
-PY
-export TOKENECONOMIZER_SWEBENCH_TASKS="$DATA/swebench/swebench_tasks.json"
-```
-
-**Per-instance execution images.** The official SWE-bench harness runs each instance in a
-pinned Docker image (repo + deps + test bed frozen at the issue's era). Your harness pulls
-these; they are large, so pre-pull the repos you'll run:
-
-Note the tag convention: the `__` in an instance id becomes `_1776_` in the image name, so
-`django__django-11532` lives at `swebench/sweb.eval.x86_64.django_1776_django-11532:latest`.
-`workloads.swebench_image_tag()` does that conversion, so the whole set is one loop:
-
-```bash
-python - > "$DATA/swebench/image_tags.txt" <<'PY'
-from te_bench import workloads
-for ids in workloads.runnable_instances("swebench").values():
- for iid in ids:
- print(workloads.swebench_image_tag(iid))
-PY
-wc -l "$DATA/swebench/image_tags.txt" # 277
-xargs -a "$DATA/swebench/image_tags.txt" -P 4 -n 1 docker pull -q
-# ...or let the SWE-bench harness build/pull them: python -m swebench.harness.run_evaluation ...
-```
-
-Budget roughly **150–200 GB** for the 277 images: they share a ~1.4 GB base plus a
-~1–3 GB environment layer per repo/era, with each instance adding only ~0.1–0.5 GB on top.
-Unauthenticated Docker Hub pulls are rate-limited to 100 per 6 h, so `docker login` first
-or expect the pull to span several windows.
-
-**Task-spec schema** (what both the driver and the adapter read):
-```json
-[{"instance_id": "pydata__xarray-1234", "repo": "pydata/xarray",
- "problem_statement": "…issue text…"}]
-```
-The adapter redacts gold-solution URLs (PR/commit/blob links) from `problem_statement`
-automatically.
-
-**Run** (`$TOKENECONOMIZER_RESULTS` was set in the preamble):
-```bash
-AGENT=claude DOMAIN=swebench ARM=trimech \
- REPOS="pydata/xarray django/django sympy/sympy scikit-learn/scikit-learn sphinx-doc/sphinx" \
- SEEDS="0 1 2" RUNNER=te_harness.swebench:make_runner \
- bash scripts/launch/trimech_ab.sh
-# Codex arms use the same task-spec, a different launcher, and one arm per command,
-# billed to OPENAI_API_KEY. Both models are evaluated, each in its own tree:
-# gpt-5.6-terra and gpt-5.6-sol.
-MODEL=gpt-5.6-terra \
- ARM=codex-untool RUNNER=te_harness.swebench:make_runner bash scripts/launch/codex_ab.sh
-# Twelve arms, one per mechanism plus the naive spine, the all-three arm (and its rtk and
-# repomap variants) and all three scaffolds: baseline, baseline-medium, baseline-low,
-# repomap, rtk, serena, codex-inject, codex-untool, codex-spiral, codex-trimech,
-# codex-trimech-rtk, codex-trimech-repomap.
-# rtk on Codex is INSTRUCTION-based (read rtk_compliance); serena is wired through
-# config.toml (read serena_tool_calls). A configured scaffold is not a used one.
-# Full catalog, one command per lane: docs/RUNNING.md section 5.
-```
-
----
-
-## 2. Web-Bench (primary — Copilot / Claude `trimech-web`)
-
-> **All three agents run here** (Codex through `CodexWebBenchRunner`). Because Web-Bench runs
-> the agent on the host with no per-task container, the Codex lane cannot use the PreToolUse
-> hook the other two are guarded by — it ignores hooks — so it carries the SWE-bench
-> `/etc/hosts` block inside an unprivileged user+mount namespace instead. Its rows report
-> `net_guard_installed: false` and `answer_key_hosts_blocked: true`; filter on the second.
->
-> ```bash
-> DOMAIN=webbench MODEL=gpt-5.6-terra \
-> ARM=codex-untool RUNNER=te_harness.webbench:make_runner bash scripts/launch/codex_ab.sh
-> ```
-
-**Dataset + evaluator.** Web-Bench (ByteDance, `bytedance/web-bench`) is 50 Node/TypeScript
-projects, each a stream of 20 sequentially dependent tasks. Its **Node/Playwright evaluator
-owns the task loop and grading** and lives in your harness; the adapter only reads each
-project's `tasks.jsonl`.
-
-```bash
-git clone https://github.com/bytedance/web-bench.git "$DATA/web-bench"
-cd "$DATA/web-bench"
-# It is a RUSH monorepo, not an npm project: `npm install` at the root does nothing useful.
-npm i -g @microsoft/rush # or use ./common/scripts/install-run-rush.js
-rush install # installs every workspace
-rush build --to @web-bench/eval # the Node evaluator YOUR harness drives
-rush build --to @web-bench/calculator --to @web-bench/expressjs --to @web-bench/react \
- --to @web-bench/zustand --to @web-bench/table
-# Playwright browsers must match the version the projects PIN (@playwright/test 1.57.0
-# wants browser build 1200); install from inside a project so the pinned version resolves:
-cd projects/calculator && npx playwright install chromium chromium-headless-shell && cd -
-# (B) dataset root the adapter reads:
-export TOKENECONOMIZER_WEBBENCH_PROJECTS="$DATA/web-bench/projects" # <project>/tasks.jsonl
-```
-
-> Use a **canonical** path here. The evaluator hands this root to each project's dev server
-> while node reports `process.cwd()` already symlink-resolved; reached through a symlinked
-> home (`/home/x` → `/srv/home/x`) the two spellings disagree and Vite cannot resolve the
-> `react` project's entry module — every test fails with an app that never rendered, which
-> looks exactly like an agent that wrote nothing. `readlink -f` the path before exporting it.
-
-**Check the checkout before spending anything.** Run a project's own reference solution
-through its own suite; a project that cannot pass its tests with the answer key cannot grade
-an agent:
-
-```bash
-R="$TOKENECONOMIZER_WEBBENCH_PROJECTS"
-cd "$R/calculator" && MAX_TEST_WORKERS=4 EVAL_PROJECT_ROOT="$R/calculator/src" \
- IS_EVAL_PRODUCTION=true EVAL=true \
- EVAL_PROJECT_PORT=3931 npm run test -- -a # expect: 68 passed
-```
-`MAX_TEST_WORKERS=4` matches the runner's own `TE_WEBBENCH_MAX_WORKERS` (default 4). Leave
-it off and Playwright uses half the CPU count of workers against one dev server; on a
-many-core host the reference solutions then fail their own suites (observed: expressjs
-88/92, react 51/59, prisma 90/91 — prisma has since been retired from the sweep) with
-nothing actually wrong.
-
-Expected totals: calculator 68 · react 59 · expressjs 92 · zustand ? · table ? (the two new
-projects are unmeasured; run the gate command above once to record them)
-(calculator measured 2026-09-07; react and expressjs carried over from the 2026-08
-provisioning). No project in the current five needs a pre-build — `react`/`zustand` are a plain `vite build`
-and `table` and `calculator`/`expressjs` build nothing. `expressjs` still fails one test if a stale `src/test.sqlite` is left behind.
-
-**Expected dataset layout (B)** — `TOKENECONOMIZER_WEBBENCH_PROJECTS/<project>/tasks.jsonl`,
-one object per line:
-```json
-{"id": "init", "date": "…", "level": "easy", "description": "…"}
-{"id": "task-1", "date": "…", "level": "easy", "description": "…"}
-```
-
-**Export the driver task list (A).** The driver needs its own JSON list of the tasks to
-stream (one entry per Web-Bench task, `repo` = the project name). It is a projection of
-`workloads.WEBBENCH_TASKS`, so a script builds it rather than a copy-pasted snippet:
-
-```bash
-export TOKENECONOMIZER_WEBBENCH_TASKS="$DATA/webbench_tasks.json" # (A) driver task list
-python scripts/export_webbench_tasks.py # write it
-python scripts/export_webbench_tasks.py --check # verify only; exit 1 if stale
-```
-
-> **Three registries have to agree, and only one of them is the authority.**
-> `experiments/te_bench/workloads.py` decides which projects and tasks are in the sweep; (A) the
-> driver task list and (C) `workloads/webbench.json` are both projections of it, and (B) the
-> projects tree has to contain a `tasks.jsonl` for every project named. Changing the project
-> list is therefore three commands, in this order:
->
-> ```bash
-> python scripts/webbench_tasks_from_yaml.py --all # B: projects that ship only tasks.yml
-> python scripts/export_workloads.py # C
-> python scripts/export_webbench_tasks.py # A
-> ```
->
-> A stale (A) does not fail loudly at launch — the driver streams the *old* project's tasks
-> into the *new* project's evaluator session and the harness raises
-> `session is running 'X' but the task belongs to 'Y'` partway into the run.
->
-> Some Web-Bench projects (`zustand` among the evaluated five) ship only `tasks.yml`, while
-> `te_harness.webbench` and `WebBenchAdapter` both read `tasks.jsonl` and nothing else.
-> `webbench_tasks_from_yaml.py` derives the jsonl and **leaves the yml in place on purpose**:
-> Web-Bench's own evaluator prefers the yml when both exist, so deleting or editing one
-> without the other silently desyncs the graded task order from the driver's.
-
-
-**Run** (short streams → `trimech-web`, which adds the LLM nudge + frozen envelope). Each
-value in `REPOS` names a Web-Bench **project**; the driver selects that project's adapter and
-filters the task list to it:
-```bash
-AGENT=claude DOMAIN=webbench ARM=trimech-web SEEDS="0" \
- REPOS="calculator expressjs react zustand table" \
- RUNNER=te_harness.webbench:make_runner bash scripts/launch/trimech_ab.sh
-```
-
-Two things a Web-Bench harness has to get right, both because the streams are sequentially
-dependent:
-
-* **The evaluator owns the loop.** It walks a project's whole stream itself, so it must be
- started once per stream rather than per task. The driver exposes the optional
- `begin_stream(tasks, ...)` / `end_stream()` hooks on `AgentRunner` for exactly this; a
- harness that does not define them is called the usual way.
-* **A failed task ends the stream.** In the evaluator's `sequential` mode the project stops
- at the first task that fails every attempt. The driver still asks for the tasks after it,
- and a harness should mark those rows unreached (`stream_broken` / `unreached`) with zero
- tokens rather than letting them read as cheap failures in the cost aggregation.
-
-**Two resolve metrics, and they differ.** Each task gets up to `TE_WEBBENCH_RETRY`
-attempts (default 2), so a row carries `resolved_p1` (first attempt — Web-Bench's own
-headline metric) and `resolved_p2` (any attempt), alongside the per-attempt verdict list
-`webbench_attempt_results`. `resolved` stays pass@N because that is what the evaluator
-acts on when it decides to end a stream — and because a row's cost is the sum of every
-attempt, pass@N is the metric the cost columns actually match. The retry can rescue several tasks
-per arm, so never quote one metric as the other. Unreached tasks carry `None` for both —
-never attempted is not a miss.
-
----
-
-## 3. CredData (secondary — security / secret detection)
-
-**Dataset.** Samsung CredData: 333 repos of obfuscated source, each `data/<repoid>/` with a
-per-repo label CSV `meta/<repoid>.csv`.
-
-```bash
-git clone https://github.com/Samsung/CredData.git "$DATA/CredData"
-cd "$DATA/CredData" && python download_data.py --data_dir data && cd - # per upstream README
-export TOKENECONOMIZER_CREDDATA_ROOT="$DATA/CredData" # (B) dir with data/ + meta/
-```
-
-**Expected dataset layout (B):**
-```
-$TOKENECONOMIZER_CREDDATA_ROOT/
- data/<repoid>/… # obfuscated source to audit (harness copies a disposable clone)
- meta/<repoid>.csv # line-level secret labels → graded to F1 (the quality guardrail)
-```
-Every repo gets the **same** read-only audit prompt; grading is line-level detection **F1**
-(the CredData analog of `resolved`). No Docker image — the harness runs the agent over a
-disposable copy of each repo directory.
-
-**Export the driver task list (A).** The audit prompt is fixed, so build one entry per repoid
-with that prompt as `problem_statement` (the exact prompt lives in
-`experiments/te_bench/adapters/creddata.py:CREDDATA_TASK_PROMPT`):
-```bash
-python - <<'PY'
-import glob, json, os
-from te_bench.adapters.creddata import CREDDATA_TASK_PROMPT
-from te_bench import workloads
-root = os.environ["TOKENECONOMIZER_CREDDATA_ROOT"]
-have = {os.path.basename(p)[:-4] for p in glob.glob(os.path.join(root, "meta", "*.csv"))}
-ids = [rid for rid in workloads.CREDDATA_INSTANCES if rid in have] # 100 of the 333 repos
-print("missing from checkout:", sorted(set(workloads.CREDDATA_INSTANCES) - have) or "none")
-rows = [{"instance_id": rid, "problem_statement": CREDDATA_TASK_PROMPT, "repo": rid}
- for rid in ids]
-out = os.path.join(os.environ["DATA"], "creddata_tasks.json")
-json.dump(rows, open(out, "w"))
-print(len(rows), "->", out)
-PY
-export TOKENECONOMIZER_CREDDATA_TASKS="$DATA/creddata_tasks.json" # (A) JSON list, NOT a dir
-```
-
-**Run:**
-```bash
-AGENT=claude DOMAIN=creddata ARM=trimech SEEDS="0 1 2" \
- RUNNER=your_pkg.harness:make_runner bash scripts/launch/trimech_ab.sh
-```
-
----
-
-## 4. ReposVul (secondary — vulnerability detection)
-
-**Dataset.** ReposVul (ICSE'24, `Eshe0922/ReposVul`): each instance is a CVE with a fixing
-commit; you reconstruct the **pre-fix (vulnerable)** files at their real repo paths and
-grade line-level F1 against the fix-removed lines.
-
-```bash
-git clone https://github.com/Eshe0922/ReposVul.git "$DATA/ReposVul-src"
-# Prepare per-instance vulnerable-file snapshots into instances/*.json with YOUR prep step
-# (checkout parent commit of each fixing commit, capture the removed lines as labels):
-python your_prep/reposvul_prepare.py --src "$DATA/ReposVul-src" --out "$DATA/ReposVul/instances"
-export TOKENECONOMIZER_REPOSVUL_ROOT="$DATA/ReposVul" # (B) dir containing instances/
-```
-
-**Expected dataset layout (B):** `$TOKENECONOMIZER_REPOSVUL_ROOT/instances/<iid>.json` (one
-prepared instance each). Every instance gets the **same** vulnerability-audit prompt; grading
-is line-level **F1**. No Docker image.
-
-**Export the driver task list (A)** (prompt from
-`experiments/te_bench/adapters/reposvul.py:REPOSVUL_TASK_PROMPT`):
-```bash
-python - <<'PY'
-import glob, json, os
-from te_bench.adapters.reposvul import REPOSVUL_TASK_PROMPT
-from te_bench import workloads
-root = os.environ["TOKENECONOMIZER_REPOSVUL_ROOT"]
-have = {os.path.basename(p)[:-5] for p in glob.glob(os.path.join(root, "instances", "*.json"))}
-ids = [iid for iid in workloads.REPOSVUL_INSTANCES if iid in have] # 100 Python-split CVEs
-print("missing from prep:", sorted(set(workloads.REPOSVUL_INSTANCES) - have) or "none")
-rows = [{"instance_id": iid, "problem_statement": REPOSVUL_TASK_PROMPT, "repo": iid}
- for iid in ids]
-out = os.path.join(os.environ["DATA"], "reposvul_tasks.json")
-json.dump(rows, open(out, "w"))
-print(len(rows), "->", out)
-PY
-export TOKENECONOMIZER_REPOSVUL_TASKS="$DATA/reposvul_tasks.json" # (A) JSON list, NOT a dir
-```
-
-**Run:**
-```bash
-AGENT=claude DOMAIN=reposvul ARM=trimech SEEDS="0 1 2" \
- RUNNER=your_pkg.harness:make_runner bash scripts/launch/trimech_ab.sh
-```
-
----
-
-## 5. CyberGym (exploratory — PoC authoring)
-
-**Dataset.** CyberGym tasks give a vulnerable workspace and ask the agent to author a
-proof-of-concept input that triggers the vulnerability. Provisioning is via a single **suite
-JSON** listing tasks; per-task workspaces are materialized by your harness.
-
-```bash
-# Fetch/prepare the suite per your CyberGym source, then:
-export TOKENECONOMIZER_CYBERGYM_SUITE="$DATA/cybergym/suite.json" # (B) adapter reads this
-```
-
-CyberGym has **no `trimech_ab.sh` domain case** — the launchers cover swebench / webbench /
-creddata / reposvul only. Run it by calling the driver directly, supplying the driver task
-list (A) yourself and `--adapter cybergym`:
-
-```bash
-# (A) a JSON list of {instance_id, problem_statement, repo}; problem_statement can be the
-# fixed CYBERGYM_TASK_PROMPT (see experiments/te_bench/adapters/cybergym.py).
-python scripts/run_experiment.py \
- --arm trimech --agent claude --adapter cybergym \
- --tasks-file "$DATA/cybergym_tasks.json" --repo "$PROJECT" --seed 0 \
- --results-root "$TOKENECONOMIZER_RESULTS/claude_cybergym" \
- --runner your_pkg.harness:make_runner
-python scripts/aggregate.py "$TOKENECONOMIZER_RESULTS/claude_cybergym" --arms baseline trimech
-```
-The adapter reads the suite JSON to key the per-task judge; PoC building + triggering live in
-the harness.
-
----
-
-## 6. WebArena — not implemented
-
-`WebArenaAdapter` is a **stub**: every method raises `NotImplementedError` naming the exact
-surface a WebArena integration must supply (episode→trajectory parser, per-action usage
-counter, action-space catalog, waste detector, protected/inapplicable sets). It documents the
-contract; there is nothing to provision until it is implemented.
-
----
-
-## Offline check (no images, no datasets)
-
-Before wiring any real harness, confirm the whole pipeline runs end-to-end with the built-in
-`StubRunner` — it launches no agent, needs no image or dataset, and cleans up after itself:
-
-```bash
-bash scripts/launch/smoke_test.sh # exercises every arm; asserts CSVs; deletes its temp dir
-```
-
-Its numbers are synthetic (a wiring check, not a benchmark). Real results require your
-`AgentRunner`.
diff --git a/experiments/docs/COPILOT.md b/experiments/docs/COPILOT.md
deleted file mode 100644
index c7bbebc..0000000
--- a/experiments/docs/COPILOT.md
+++ /dev/null
@@ -1,312 +0,0 @@
-# Running the GitHub Copilot CLI as the sealed agent
-
-TokenEconomizer's mechanisms are agent-agnostic, but each sealed agent needs its own runner
-below the [`AgentRunner`](../te_bench/runner.py) seam. This page is the Copilot path,
-end to end, for **both** SWE-bench and Web-Bench. It assumes you have already done
-[`SETUP.md`](SETUP.md) steps 1–3 (venv, the two outside-the-repo directories, datasets);
-everything Copilot-specific is here.
-
-Read [`SETUP.md`](SETUP.md) first if you have not. The gates below are cumulative — do not
-skip one because the next looks more interesting.
-
----
-
-## What is different about Copilot
-
-Four things, and each one has bitten this harness at least once:
-
-| | Claude Code | Copilot CLI |
-|---|---|---|
-| **Auth** | `ANTHROPIC_API_KEY` | GitHub, from on-disk `~/.copilot` or `COPILOT_GITHUB_TOKEN`; or Copilot's own BYOK |
-| **Token accounting** | in the stream's terminal `result` event | **only** in the CLI's debug log |
-| **Turn cap** | `--max-turns N` | none — wall clock and the spiral guard are the only bounds |
-| **Tool exclusion** | one comma-joined `--disallowed-tools` | `--excluded-tools` repeated per tool |
-
-The accounting difference is the dangerous one. Copilot's `result` event carries
-`premiumRequests` and durations but **no token fields at all**, so a runner that reads usage
-the Claude way records a row of zeros — every cost number downstream is then wrong rather
-than missing. That is why every Copilot invocation here runs with `--log-level all
---log-dir …` and mines the log
-([`te_harness/copilot.py`](../te_harness/copilot.py)).
-
----
-
-## Step 1 — install and sign in
-
-```bash
-curl -fsSL https://gh.io/copilot-install | bash # -> ~/.local/bin/copilot
-copilot # then: /login
-```
-
-`/login` runs an OAuth device flow and stores the token in your system credential store, or
-in plain text under `~/.copilot/` if there is no credential store. For a headless box,
-export a token instead — the CLI checks `COPILOT_GITHUB_TOKEN`, then `GH_TOKEN`, then
-`GITHUB_TOKEN`. Fine-grained (v2) PATs need the **Copilot Requests** permission; classic
-`ghp_` tokens are not supported.
-
-**Gate:**
-
-```bash
-copilot -p "say ok" --allow-all-tools --no-color --log-level none
-```
-
-Expect `ok`. If you get `No authentication information found` on a box that has been idle,
-**run it a second time** — see the token-staleness note in Step 5; the first call refreshes
-the token as a side effect.
-
-### BYOK — Copilot's own provider keys
-
-Without a subscription, or with its quota spent, the CLI can bill **your own provider**
-instead (`copilot help providers`). `COPILOT_PROVIDER_BASE_URL` is the one switch — set it
-and GitHub auth is not used at all:
-
-```bash
-COPILOT_PROVIDER_TYPE=anthropic
-COPILOT_PROVIDER_BASE_URL=https://api.anthropic.com
-COPILOT_PROVIDER_API_KEY=<your Anthropic key> # the CLI never reads ANTHROPIC_API_KEY
-```
-
-The launcher then prints `routing: Copilot CLI BYOK -> anthropic at …` and skips the GitHub
-auth probe. With the base URL set and neither `COPILOT_PROVIDER_API_KEY` nor
-`COPILOT_PROVIDER_BEARER_TOKEN`, it warns, and every task would fail — read the banner.
-
-* **It is still the Copilot CLI.** BYOK keeps the agent `copilot`, its own trajectory shape,
- tool names and `copilot_<domain>_<tag>` trees; it is not Claude Code on the same key.
-* **`--effort` is accepted under BYOK**, so the effort arms run.
-* **`--model` keeps the first-party id** on the Anthropic wire (`claude-opus-4-8`, dashed).
- `COPILOT_PROVIDER_MODEL_ID` / `COPILOT_PROVIDER_WIRE_MODEL` are for a provider whose served
- id differs from the one you want recorded (a router that prefixes `anthropic/`, for
- example); leave them unset otherwise.
-* **A BYOK row and a subscription row are different cost bases, and the tree name does not
- separate them.** The discriminator is `run_config.json` → `routing.base_url`: the provider
- URL under BYOK, the literal `github-copilot` on a subscription. Never pool the two; if you
- switch mid-sweep, move the finished cells to their own tree first.
-
-The harness forwards the provider variables into the SWE-bench task container and passes
-the credential by name only, so it never reaches argv; Web-Bench's agent runs on the host and
-inherits them directly.
-
-## Step 2 — pick a model, and know what that costs you
-
-Copilot serves its own catalog, which depends on your subscription. An Anthropic model id is
-not a valid value here. Check what yours serves before a sweep — a bad id fails **per task**,
-not at launch:
-
-```bash
-copilot -p "say ok" --model <the-id-you-want> --effort high --no-color --log-level none
-```
-
-This is the same probe the launcher runs, so its verdict is the one you will get:
-
-* `ok` — the model is served **and** takes your effort level. Pin it.
-* `Model "<id>" … is not available.` — pick another id.
-* `Model "<id>" does not support reasoning effort configuration` — the model is served but
- has no effort knob. Usable, but effort will not be applied (see below).
-
-If nothing is available, use `--model auto` and let the CLI route.
-
-### Reasoning effort
-
-**If you want `TE_EFFORT_LEVEL=high` to actually take effect, you must pin a model.** The
-`auto` router rejects the flag outright — `--model auto --effort high` exits with *"Model
-auto does not support reasoning effort configuration"* and the task never runs. Some pinned
-models refuse it too.
-
-The launcher settles this for you with one probe before the sweep starts
-(`te_check_copilot_model`), so neither mistake can cost you a run:
-
-| Probe result | What happens |
-|---|---|
-| model served, effort accepted | `[env] copilot model '<id>' serves; effort=high accepted` — runs with effort, row records it |
-| model served, effort refused | **warns**, exports `TE_EFFORT_APPLIES=0`, runs without the flag, row records `effort: null` |
-| model not served | **hard fail, exit 2** — nothing could have run |
-
-**A pinned model must also be priced.** `pricing.MODEL_WEIGHTS` refuses to guess ratios for
-an id it does not know — deliberately, so a new model can never be silently mispriced. The
-runner now checks this at construction, so an unpriced id fails at startup:
-
-```
-ValueError: pricing: no weight entry for billed model 'my-model' (agent='copilot').
- Add it to pricing.MODEL_WEIGHTS
-```
-
-Add the id to `tokeneconomizer/pricing.py` before pinning it. Ids containing
-`claude` fall back to the Claude curve automatically and need no entry. `auto` needs none
-either — it is a routing directive, not a billed id, so it is recorded as `null` and priced
-on the Claude curve, which is the historical behaviour for Copilot rows.
-
-Set both in the repo's `.env`:
-
-```bash
-COPILOT_MODEL=gpt-5.6-sol # a model id YOUR subscription serves; 'auto' = router, no effort
-TE_EFFORT_LEVEL=high # takes effect only when COPILOT_MODEL is a pinned id
-```
-
-> Where effort is not applied, the row's `effort` is `null` rather than `high`, and the
-> reasoning effort is whatever the model or router defaulted to. Those rows stay internally
-> comparable, but must **not** be compared against effort-pinned Claude numbers as though
-> effort were held equal. Check `effort` in `run_config.json` before you compare.
-
-If you bypass the launcher and call `scripts/run_experiment.py` directly, there is no probe —
-but the runner still fails fast: a refused model or effort raises on the first segment rather
-than writing a tree of 0-turn rows that look like genuine task failures.
-
-## Step 3 — point the driver at the Copilot runner
-
-The runner factories are agent-aware: the driver passes `--agent` to them, and an unknown
-label raises rather than falling back to Claude. Nothing to configure beyond
-`AGENT=copilot`.
-
-```bash
-# in .env
-RUNNER=te_harness.swebench:make_runner # or te_harness.webbench:make_runner
-```
-
-**Gate** — the label really does select the Copilot runner:
-
-```bash
-python3 - <<'EOF'
-import sys; sys.path.insert(0, "scripts")
-from run_experiment import load_runner
-r = load_runner("te_harness.swebench:make_runner", "copilot")
-print(type(r).__name__, r.agent_bin)
-EOF
-```
-
-Expect `CopilotSwebenchRunner /…/bin/copilot`. If you see `ClaudeSwebenchRunner`, the label
-is not reaching the factory and **every row would be Claude's work filed under Copilot's
-name** — stop and fix that before spending anything.
-
-## Step 4 — launch
-
-Same launcher as Claude; only `AGENT` changes.
-
-```bash
-# SWE-bench
-AGENT=copilot DOMAIN=swebench ARM=trimech REPOS="pydata/xarray" SEEDS="0" \
-RUNNER=te_harness.swebench:make_runner \
- bash scripts/launch/trimech_ab.sh
-
-# Web-Bench (short streams -> the tuned arm)
-AGENT=copilot DOMAIN=webbench ARM=trimech-web REPOS="calculator" SEEDS="0" \
-RUNNER=te_harness.webbench:make_runner \
- bash scripts/launch/trimech_ab.sh
-```
-
-The preflight prints which auth path it resolved and warms the token:
-
-```
-[env] routing: native Copilot (on-disk GitHub auth, token warm)
-[trimech_ab] agent=copilot routing=direct domain=swebench arms=(baseline trimech) ...
-```
-
-Results land in `copilot_swebench/` and `copilot_webbench/`, separate from the Claude trees —
-a different agent is a different cost basis and the two must never average into one cell.
-
-## Step 5 — keep the token warm for a long sweep
-
-Copilot's token is short-lived and is refreshed into `~/.copilot/config.json` **only when a
-copilot process runs on the host**. SWE-bench containers authenticate from a read-only mount
-of that file, so during a long unattended sweep the token goes stale (~75 min was the
-observed lifetime) and every later container copies the dead token and fast-fails —
-*"No model backend available"*, a 0-byte patch, ~30s wall. Hundreds of paid-looking failures
-that are really one expired credential.
-
-Run the keepalive for the duration of any sweep longer than about an hour:
-
-```bash
-/path/to/AgentEO/swebench/copilot_auth_keepalive.sh 600 & # refresh every 10 min
-# ... run the sweep ...
-kill %1
-```
-
-Setting `COPILOT_GITHUB_TOKEN` sidesteps this entirely — the token is passed into the
-container by environment and never goes stale mid-run. Prefer that for unattended work.
-
----
-
-## Verifying a finished run
-
-Three checks, in order of how quietly they fail:
-
-```bash
-RUN=$(ls -d <results>/copilot_swebench/baseline/*/2*__copilot__* | head -1)
-
-# 1. the debug log exists -> token accounting and the untooling catalog both work
-ls -la "$RUN/copilot_debug.log"
-
-# 2. the row's tokens came from the log, not the stream fallback
-python3 -c "import json;r=json.load(open('$RUN/row.json'));print(r['tokens_source'], r['input_tokens'], r['cache_read_input_tokens'])"
-
-# 3. the tool catalog is non-empty (an empty one makes untooling a paid no-op)
-python3 -c "
-from tokeneconomizer import trace
-c = trace.parse_catalog('$RUN', 'copilot')
-print(len(c), 'tools;', sum(1 for v in c.values() if v), 'with descriptions')"
-```
-
-`tokens_source` must be `debug_log`. `stream_output_only` means the log was not recovered:
-the row then has output tokens and nothing else, so its cost is a large underestimate rather
-than a gap you would notice in a summary. `mixed` means one spiral segment was accounted and
-another was not.
-
-Check 3 should report ~17 tools. **`0 with descriptions` is expected on a current CLI** and
-is not a failure — see the next section for what it costs you.
-
-### Tool descriptions and which untooling flag to use
-
-Older Copilot builds dumped the full tool **schemas** into the debug log, and
-`reflect.parse_tool_catalog` read `{name: description}` straight out of it. Current builds
-(verified on 1.0.82) log only the tool *calls*; the loaded tool **names** moved to the
-stream's `session.usage_checkpoint` event. `trace.parse_catalog` tries the log first and
-falls back to those names with empty descriptions, so you get names on every version.
-
-That distinction decides which mechanism to run:
-
-| Flag | Needs | On a current CLI |
-|---|---|---|
-| `--untool-evidence N` | names only (drop what was loaded but unused for N tasks) | **works** |
-| `--untool-judge` | descriptions (reason about what each tool is *for*) | **degrades to a paid no-op** — it drops nothing and still bills for the call |
-
-So on a current CLI prefer `--untool-evidence` alone, and treat a `trimech` run that
-includes `--untool-judge` as paying for a judge that cannot contribute. Restoring the judge
-means capturing a description snapshot the way `tokeneconomizer/trace/claude_tool_catalog.json` does for
-Claude (see `te_harness/capture_catalog.py` for the pattern).
-
-## Troubleshooting
-
-| Symptom | Cause |
-|---|---|
-| `no copilot binary found` | Not installed, or installed somewhere else — set `COPILOT_HOST_BIN`. |
-| `copilot host install incomplete: …/.cache/copilot` | The package cache is missing. Run `copilot` once interactively to populate it; docker would otherwise invent an empty dir and every task would fail. |
-| Every task: 0 turns, empty patch, ~30s | Stale or missing auth in the container. See Step 5. |
-| `Model "auto" does not support reasoning effort` | You pinned effort against the router. The launcher probe and the runner both guard this; if you see it raw, you built the argv yourself. |
-| `copilot refused this configuration: …` (run aborts) | `COPILOT_MODEL` is not served, or refuses `--effort`. Fix it per Step 2 — the run stopped deliberately rather than logging hundreds of 0-turn failures. |
-| `tokens_source: stream_output_only` on every row | `--log-level all --log-dir` was dropped, or the log dir was unreadable. |
-| Untooling drops nothing but still bills | Expected for `--untool-judge` on a current CLI (no descriptions). If `--untool-evidence` also drops nothing, check the catalog is non-empty (check 3). |
-| Rows say `copilot` but look like Claude | The runner factory ignored `--agent`. Re-run the Step-3 gate. |
-
-## Known limitations
-
-* **No turn cap.** `max_turns` is recorded in `run_config.json` and the spiral envelope is
- counted in turns, but nothing enforces a cap on the agent. `TE_TASK_TIMEOUT` and the
- spiral guard are the real bounds. A Copilot baseline is therefore not turn-capped the way
- a Claude baseline is.
-* **No vendor USD.** Copilot reports a premium-request count, not a dollar figure, so
- `cost_usd_vendor` stays null. Cost comparisons run on effective tokens, which is the
- basis the study uses anyway. `aggregate.py` knows this: its `vendor_cost_missing` flag
- skips any agent in `AGENTS_WITHOUT_VENDOR_USD` (`copilot`, `codex`), so a Copilot tree
- reports zero of them rather than flagging every row.
-* **Effort on `auto`** — see Step 2.
-* **No tool descriptions** on current CLI builds, so the instruction-aware tool judge has
- nothing to reason over. Evidence untooling is unaffected.
-
-## Verified
-
-A `baseline` task on each domain has been run end to end on the subscription: each resolved
-by that benchmark's own official grader (the SWE-bench harness and Web-Bench's Node
-evaluator), with `tokens_source=debug_log` and the full cache-aware token breakdown
-recovered from the debug log — a real cost basis rather than a row of zeros.
-
-Check the same three things on your first row (see "Verifying a finished run" above) before
-launching a lane.
diff --git a/experiments/docs/ENVIRONMENT.md b/experiments/docs/ENVIRONMENT.md
deleted file mode 100644
index 541482d..0000000
--- a/experiments/docs/ENVIRONMENT.md
+++ /dev/null
@@ -1,165 +0,0 @@
-# Environment & requirements
-
-Everything you need on a **fresh clone**, split into two independent layers. The layers do
-**not** overlap: the repo layer is tiny and pure-Python; the harness layer (Docker, agent
-CLIs, datasets) is external infrastructure you provision only when you want to reproduce the
-real cost numbers.
-
-```
-┌─ Layer 1: THIS REPO ────────────────────────────────────────────────┐
-│ Python >= 3.10. Core = stdlib-only (zero deps). │
-│ + pytest (tests). requirements.txt. │
-│ Lets you: import the package, run the test suite, run the offline │
-│ smoke test. NO Docker, NO datasets. │
-└─────────────────────────────────────────────────────────────────────┘
-┌─ Layer 2: THE HARNESS (te_harness/, + what it drives) ──────────────┐
-│ Docker + the sealed agent CLIs + dataset checkouts. The runner │
-│ itself is in the repo; none of what it drives can be. Lets you: │
-│ run each benchmark for real and measure cost and resolve. │
-│ See docs/HARNESS.md and docs/BENCHMARKS.md. │
-└─────────────────────────────────────────────────────────────────────┘
-```
-
-## Layer 1 — the repo (always required)
-
-| Requirement | Version | Why |
-|---|---|---|
-| Python | ≥ 3.10 | the package + scripts |
-| pip / venv | any recent | install the package |
-| pytest | ≥ 7.0 | test suite — optional |
-
-Core `import tokeneconomizer` needs **nothing beyond the standard library**. `pytest` is
-only for the tests.
-
-**Install (recommended — editable, with the test extra):**
-```bash
-python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
-pip install -e '..[test]' # the repository root's pyproject.toml
-```
-
-**Or with the convenience requirements file** (same pins, no build step):
-```bash
-python3 -m venv .venv && source .venv/bin/activate
-pip install -r requirements.txt
-pip install -e .. # still install the package itself (editable)
-```
-
-**Verify Layer 1 with zero external infra:**
-```bash
-python -c "import tokeneconomizer as te; print(te.Economizer)" # self-contained import
-pytest # offline suite, no Docker/datasets
-bash scripts/launch/smoke_test.sh # every arm wired end-to-end, auto-cleans
-```
-If those three pass, the repo layer is healthy. **A fresh user can do all of this with no
-Docker, no datasets, and no API keys.**
-
-## Layer 2 — the harness (only for real runs)
-
-> This section is the **what**. For the **how**, in order, with a gate after every step, see
-> [`SETUP.md`](SETUP.md) — venv, the data directory, credentials, the runner, then
-> per-benchmark data.
-
-A real run launches a **sealed agent inside a benchmark Docker image** and grades it against
-a gold patch. The code that does this is in the repo
-([`HARNESS.md`](HARNESS.md)); everything it *drives* is not, and cannot be. To reproduce for
-real you supply:
-
-1. **Docker** — to run the per-benchmark execution images (see install guide below).
-2. **A sealed agent CLI** — Claude Code, GitHub Copilot CLI, or Codex, on its own native
- authentication: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or a Copilot subscription or
- Copilot BYOK. Keys go in `.env` (see [`../.env.example`](../.env.example)); the per-agent
- table is in [`RUNNING.md`](RUNNING.md).
-3. **Dataset checkouts** — per [`docs/BENCHMARKS.md`](BENCHMARKS.md) (SWE-bench, Web-Bench,
- CredData, ReposVul, CyberGym).
-4. **Nothing else.** The `AgentRunner` implementation — the glue that launches the agent in
- the image, applies the economizer's per-task decisions, grades, and writes `row.json` +
- `transcript.jsonl` — ships in the repo as `te_harness`, so this is a flag rather than a
- deliverable: `RUNNER=te_harness.swebench:make_runner`. Pass
- `RUNNER=your_pkg.harness:make_runner` to substitute your own.
-
-Some dataset **provisioning** steps need extra tools that are **not** repo dependencies
-(don't put them in `requirements.txt`):
-
-| Tool | Needed for | Install |
-|---|---|---|
-| `git` | cloning Web-Bench / CredData / ReposVul | your OS package manager |
-| `datasets` (HF) | fetching SWE-bench Verified instances | `pip install datasets` (provisioning only) |
-| Node.js + npm | Web-Bench evaluator + Playwright | nodejs.org / `nvm` |
-
----
-
-## Installing & updating Docker (for beginners)
-
-You only need this for **Layer 2**. Skip it entirely if you're just running the repo layer
-(import / tests / smoke test).
-
-### Check what you already have
-```bash
-docker --version # e.g. "Docker version 27.x"
-docker run --rm hello-world # prints a success message if the daemon is working
-```
-If `docker` is missing or `hello-world` fails, install/fix it below.
-
-### Linux (Ubuntu/Debian) — Docker Engine
-```bash
-# 1. Remove any old distro packages
-sudo apt-get remove -y docker docker-engine docker.io containerd runc 2>/dev/null || true
-
-# 2. Add Docker's official apt repository
-sudo apt-get update
-sudo apt-get install -y ca-certificates curl gnupg
-sudo install -m 0755 -d /etc/apt/keyrings
-curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
- sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
-sudo chmod a+r /etc/apt/keyrings/docker.gpg
-echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
- https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo $VERSION_CODENAME) stable" | \
- sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
-
-# 3. Install
-sudo apt-get update
-sudo apt-get install -y docker-ce docker-ce-cli containerd.io \
- docker-buildx-plugin docker-compose-plugin
-
-# 4. Run docker without sudo (log out/in afterward)
-sudo usermod -aG docker "$USER"
-```
-
-### macOS / Windows — Docker Desktop
-- **macOS:** install [Docker Desktop](https://docs.docker.com/desktop/install/mac-install/)
- (Apple-Silicon or Intel build), or `brew install --cask docker`, then launch Docker.app.
-- **Windows:** install [Docker Desktop](https://docs.docker.com/desktop/install/windows-install/)
- with the **WSL 2** backend, and run the launchers from inside a WSL 2 Ubuntu shell.
-
-### Updating Docker
-```bash
-# Linux (Docker Engine): just re-pull the packages
-sudo apt-get update && sudo apt-get install -y \
- docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
-
-# macOS / Windows (Docker Desktop): Docker menu → "Check for Updates…", or reinstall the cask
-brew upgrade --cask docker
-```
-
-### Common first-run fixes
-- **`permission denied … /var/run/docker.sock`** — you're not in the `docker` group yet: run
- the `usermod -aG docker` line above, then log out and back in (or `newgrp docker`).
-- **`Cannot connect to the Docker daemon`** — the daemon isn't running:
- `sudo systemctl start docker` (Linux) or launch Docker Desktop (macOS/Windows).
-- **Benchmark images are large** — pre-pull the instances you'll run and give Docker enough
- disk (SWE-bench per-instance images are multi-GB each).
-
----
-
-## What a fresh user can and cannot reproduce
-
-| Goal | Needs | Doable on a bare clone? |
-|---|---|---|
-| Import the package | Layer 1 | ✅ yes |
-| Run the test suite | Layer 1 | ✅ yes |
-| Run the offline smoke test (all arms wired) | Layer 1 | ✅ yes — synthetic numbers |
-| Measure cost and resolve per arm | Layer 2 (Docker + agent CLI + credentials + datasets) | ⚠️ yes, once Layer 2 is provisioned |
-
-The boundary: **the repo exercises the *method and wiring* out of the box; real numbers need
-Docker, an agent CLI with its credentials, and the datasets**, which are machine- and
-account-specific and therefore not shipped here.
diff --git a/experiments/docs/HARNESS.md b/experiments/docs/HARNESS.md
deleted file mode 100644
index ba351af..0000000
--- a/experiments/docs/HARNESS.md
+++ /dev/null
@@ -1,546 +0,0 @@
-# te_harness — Layer-2 task-execution harness for TokenEconomizer
-
-Everything that touches Docker, an agent CLI, or a credential lives **below**
-`te_bench.runner.AgentRunner`. [`te_harness/`](../te_harness) is this repo's
-implementation of that seam. Supplying your own instead is a supported path, not a
-fallback: pass `--runner your_pkg.harness:make_runner` and nothing above the seam changes.
-
-**It is a sibling package of `tokeneconomizer`, not a submodule of it**, and `pyproject.toml`
-excludes it from the distributed wheel. That boundary is the point: `import tokeneconomizer`
-cannot reach Docker or an agent CLI because the code that shells out to them is not
-underneath it, so the core's stdlib-only guarantee is structural rather than a convention.
-It costs nothing at install time either — this package is stdlib-only at import time too
-(the official SWE-bench grader is imported lazily inside `swebench._import_swebench`, from
-the checkout `TE_SWEBENCH_REPO` names), which is why the `harness` extra installs no
-packages. What it needs cannot come from pip: Docker, an agent CLI on `PATH`, an API key,
-the benchmark images, and for Web-Bench a built Rush monorepo.
-
-Because the harness is versioned alongside the mechanisms, a result is attributable to a
-harness commit and not merely to "whatever was on disk that day". Anything that changes
-recorded cost, `resolved`, or turn counts is a reviewable diff — which matters more than it
-sounds, since the accounting these rows are built from lives here, not above the seam.
-
-It holds one runner per domain, each executing tasks with a **real sealed coding agent** and
-grading with **that benchmark's own official grader**, returning the row + transcript the
-economizer's mechanisms consume:
-
-| Runner | Domain | Agent runs | Graded by |
-|---|---|---|---|
-| `te_harness.swebench:make_runner` | SWE-bench | inside the instance's official Docker image | the official SWE-bench harness (`get_eval_report`) |
-| `te_harness.webbench:make_runner` | Web-Bench | on the host, over the task's file set | Web-Bench's own Node evaluator + Playwright suites |
-| `te_harness.webbench_smoke:make_runner` | Web-Bench | **not at all** — the reference solution stands in | same as above (offline wiring check) |
-
-## Agents
-
-Both real factories take the driver's `--agent` label and return that agent's runner. Each
-agent runs on its own native authentication: Claude Code on `ANTHROPIC_API_KEY`, Codex on
-`OPENAI_API_KEY`, the Copilot CLI on its GitHub subscription or its own BYOK.
-
-| `--agent` | SWE-bench | Web-Bench |
-|---|---|---|
-| `claude` (default) | `ClaudeSwebenchRunner` | `WebBenchRunner` |
-| `copilot` | `CopilotSwebenchRunner` | `CopilotWebBenchRunner` |
-| `codex` | `CodexSwebenchRunner` | `CodexWebBenchRunner` |
-
-An unknown label **raises**. It must never fall back: a factory that quietly returned the
-Claude runner for `--agent copilot` would produce a full tree of Claude rows filed under
-Copilot's name — plausible numbers for an agent that never ran, which is worse than a crash.
-
-Everything Copilot-specific — GitHub auth instead of an API key, its own model catalog,
-token recovery from the debug log, and the absence of a turn cap — lives in
-[`te_harness/copilot.py`](../te_harness/copilot.py); setup is in [`COPILOT.md`](COPILOT.md).
-The Codex seam — the capability→config mapping and its own accounting — is
-[`te_harness/codex.py`](../te_harness/codex.py). The two Copilot runners
-subclass the Claude ones and override only construction, launch, and accounting; the task
-lifecycle (container, spiral segments, grading, evaluator round-trip) is shared.
-
-## Use
-
-```bash
-cd /path/to/TokenEconomizer
-set -a; . ./.env; set +a # ANTHROPIC_API_KEY etc.
-
-python3 scripts/run_experiment.py \
- --arm baseline --agent claude --repo pydata/xarray --seed 0 --limit 1 \
- --adapter swebench --tasks-file "$TOKENECONOMIZER_SWEBENCH_TASKS" \
- --workload workloads/swebench.json \
- --results-root "$TOKENECONOMIZER_RESULTS/claude_swebench" \
- --runner te_harness.swebench:make_runner --fresh
-```
-
-The launchers take the same seam: `RUNNER=te_harness.swebench:make_runner bash
-scripts/launch/trimech_ab.sh`.
-
-No `PYTHONPATH` is needed for either form. `scripts/run_experiment.py` puts `experiments/`
-and the repository root (the shared core) on `sys.path` itself, so `--runner te_harness.…` resolves from any working directory. (While the
-harness lived outside the repo this required exporting `PYTHONPATH`, and forgetting it failed
-a launch at import time — or, worse, appeared to work by namespace-package accident whenever
-the shell happened to be sitting in the harness's parent directory.)
-
-## What one task does
-
-1. **Start** `swebench/sweb.eval.x86_64.<instance>:latest` detached, with the host's
- Claude Code binary bind-mounted in. It is a static ELF, so it runs in the image
- unmodified — no image rebuild, no Node, no network install.
-2. **Run the agent** at `/testbed` via `claude -p --output-format stream-json`, applying the
- economizer's per-task decisions: the injected manual prefix goes in the prompt, the
- untooling mask becomes `--disallowed-tools`, and the spiral guard folds the live stream
- through `NudgeGuard.monitor`. Every raw stream line is written to `transcript.jsonl` —
- the exact schema `tokeneconomizer.trace` re-reads afterwards.
-3. **Spiral rung 1**: on a guard nudge, the agent is re-invoked in the *same* container on
- top of its own on-disk edits, with the leakage-safe redirect appended. On an abort, the
- agent is killed inside the container (killing the `docker exec` client alone would leave
- it running and billing).
-4. **Grade** with `swebench.harness.test_spec` + `.grading` — the same `get_eval_report`
- the official `run_evaluation` calls — running the instance's real eval script in the
- same container. The eval script resets test files and applies the instance's own
- `test_patch`, so agent edits to tests are discarded exactly as upstream discards them.
-5. **Return** `(row, run_dir)` with the cache-aware token breakdown from the CLI's final
- `result` event, `resolved`, `num_turns`, and the spiral/untool telemetry the mechanisms
- read. When the agent was killed before that event, the breakdown is recovered from the
- transcript and the row is flagged — see **Accounting** below.
-
-### Accounting: rows that are a lower bound
-
-Claude Code reports its token breakdown **only** in the stream's terminal
-`{"type":"result"}` event, and both of `_segment`'s break paths — a spiral guard stop and
-`TE_TASK_TIMEOUT` — kill the CLI before it arrives. The segment used to return `{}`, so the
-row recorded **zero** for every token field and for `num_turns`, describing a rollout that
-had really run for tens of turns and hundreds of thousands of tokens as free.
-
-Only economized arms install a guard, so the understatement was **one-directional**: it
-flattered exactly the arms under test and could never touch a baseline. Grading was
-unaffected (it reads the patch), but cost and turn-based claims were not.
-
-`_UsageRecovery` now folds usage in as the stream arrives and rebuilds a `result`-shaped
-event when none comes. What that can and cannot recover:
-
-| Field | Recoverable? | How |
-|---|---|---|
-| `input_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens` | **exactly** | per-message `usage` snapshots deduplicated on `message.id` (they are cumulative and repeat per content block, so summing every event double-counts). Validated against 60 healthy rows that *do* have a `result` event: 60/60 exact on all three |
-| `num_turns` | approximately | deduplicated assistant-message count — exact on 107 of 120 healthy rows, within 1 on 12 more |
-| `output_tokens` | **no** | the per-message figure is the `message_start` placeholder, understating the truth 7.5×–134.7× (median 28×). Reported as 0 and flagged, never estimated |
-
-So a recovered row is honest but incomplete and says so: `usage_incomplete` with
-`output_tokens_missing`, `num_turns_recovered`, and `usage_incomplete_reason`. The flags are
-present-and-`False` on a healthy row, so an absent flag means "written before this check
-existed", not "verified complete". They OR across spiral segments, because degradation is a
-property of the sum — the usual shape is a first segment that completes and a second the
-guard kills.
-
-**A flagged row's cost is a floor, not a measurement.** `pricing.effective_tokens` is
-deliberately left alone: this reports the defect rather than papering over it.
-`scripts/aggregate.py` surfaces `usage_incomplete` in `all_rows.csv`, counts it per cell as
-`n_usage_incomplete` in `summary_by_cell.csv`, and prints a warning naming the affected arms
-— so a distorted mean cannot be read without the distortion beside it. It also recognises
-rows stored *before* the fix by their signature (no tokens, yet the task resolved or left a
-patch) and flags them `legacy_zero_usage`.
-
-Copilot was never affected: it mines its debug log after the kill (`cat {logdir}/*.log`),
-which is why the audit found zero affected rows in 2,571. Its own degraded case is a log it
-could not parse, which `copilot.row_usage` already reports as
-`tokens_source="stream_output_only"` with `None` — not 0 — in the unaccounted fields. Both
-Copilot runners map that onto the same `usage_incomplete` flag, so one filter covers every
-row this harness writes.
-
-Each run dir therefore holds:
-
-| File | What it is |
-|---|---|
-| `transcript.jsonl` | raw `stream-json` events, the schema `tokeneconomizer.trace` re-reads |
-| `run_config.json` | **everything that shaped the run** — effort, model, turn cap, CLI build, routing mode, the tool mask actually applied, spiral params, injected-manual hash |
-| `model_patch.diff` | the agent's working-tree diff, i.e. what was graded |
-| `eval.log` | the official eval script's output, i.e. why it graded that way |
-| `row.json` | the normalized row (written by the driver, not the harness) |
-
-`run_config.json` exists because the CLI records **neither** the effort level nor the tool
-mask in its own transcript — without it, a finished run cannot answer "what settings
-produced this?", and an effort default that silently changed would be undetectable after
-the fact.
-
-Root note: SWE-bench images run as root, where the CLI refuses
-`--dangerously-skip-permissions` unless `IS_SANDBOX=1` says it is containerized. These
-disposable per-task containers are exactly that, so the harness sets it.
-
-## Web-Bench
-
-```bash
-cd /path/to/TokenEconomizer
-set -a; . ./.env; set +a
-
-python3 scripts/run_experiment.py \
- --arm baseline --agent claude --repo calculator --seed 0 \
- --adapter webbench --tasks-file "$TOKENECONOMIZER_WEBBENCH_TASKS" \
- --workload workloads/webbench.json \
- --results-root "$TOKENECONOMIZER_RESULTS/claude_webbench" \
- --runner te_harness.webbench:make_runner --fresh
-```
-
-Or a full A/B over the five evaluated projects (`trimech-web` is the arm tuned for
-Web-Bench's short streams):
-
-```bash
-AGENT=claude DOMAIN=webbench ARM=trimech-web \
- REPOS="calculator expressjs react zustand table" SEEDS="0" \
- RUNNER=te_harness.webbench:make_runner \
- bash scripts/launch/trimech_ab.sh
-```
-
-`--repo` names the Web-Bench **project**, which is one stream of 20–21 sequentially
-dependent tasks (`init`, `task-1` … `task-20`). One driver invocation runs one project.
-
-### Why this one is different
-
-Web-Bench inverts the control flow. Its Node evaluator owns the task loop — copy the
-previous task's workspace forward, collect the file set, ask the agent for files, write them
-back, run the project's build, screenshot, then grade with the project's Playwright suite
-**cumulatively** (`init` + `task-1..task-N`, so a task passes only if every earlier task
-still passes). The economizer's driver owns *its* loop and expects one `run_task` per task.
-
-The runner joins the two at the evaluator's own HTTP agent seam, so neither side is
-reimplemented. Per project it starts a serialized HTTP server speaking the evaluator's
-agent contract and `@web-bench/eval` restricted to that project, pointed at that server.
-`run_task` then blocks on a rendezvous: take the evaluator's request for this task, run
-Claude Code over the request's files in a scratch workspace, answer with the files that
-changed, and wait for the evaluator's verdict line for this task before returning the row.
-`resolved` is Web-Bench's own graded verdict.
-
-The driver reaches this through two optional `AgentRunner` hooks — `begin_stream(tasks)` /
-`end_stream()` — because the evaluator has to be started once for the whole stream, not
-per task. Harnesses that do not define them are unaffected.
-
-Two consequences of Web-Bench's contract shape what the mechanisms can observe, and neither
-is a harness limitation:
-
-* **The agent gets files, not an installed project.** Web-Bench's own reference agent is a
- single files-in/files-out LLM call; the request carries no `node_modules` and no test
- suite (the tests *are* the grader). Claude Code here is strictly more capable — it reads,
- greps and writes across the whole file set — but it cannot build or run the project, so
- trajectories are far shorter than SWE-bench's edit–test–fail loops. That is why the
- `trimech-web` arm exists.
-* **A failed task ends the stream.** In the evaluator's `sequential` mode the project stops
- at the first task that fails every attempt. The driver still asks for the tasks after it;
- those rows come back `resolved: false` with `stream_broken: true`, `unreached: true` and
- zero tokens — unreached, not cheap. Aggregations must not read them as low-cost failures.
-
-**Two resolve metrics, and they differ.** Each task gets up to `TE_WEBBENCH_RETRY`
-attempts (default 2), so a row carries `resolved_p1` (first attempt — Web-Bench's own
-headline metric) and `resolved_p2` (any attempt), alongside the per-attempt verdict list
-`webbench_attempt_results`. `resolved` stays pass@N because that is what the evaluator
-acts on when it decides to end a stream — and because a row's cost is the sum of every
-attempt, pass@N is the metric the cost columns actually match. The retry can rescue several tasks
-per arm, so never quote one metric as the other. Unreached tasks carry `None` for both —
-never attempted is not a miss.
-
-Each run dir holds the same artifacts as a SWE-bench run (`transcript.jsonl`,
-`run_config.json`, `row.json`) plus `agent_request_<n>.json` — what the evaluator actually
-asked for on each attempt. The evaluator's own stdout is teed to
-`<results>/<arm>/<cell>/_webbench_<project>/evaluator.log`, and its report tree lands beside
-it.
-
-### Wiring check (no agent, no spend)
-
-```bash
-python3 scripts/run_experiment.py --arm baseline --agent claude --repo calculator --seed 0 \
- --adapter webbench --tasks-file "$TOKENECONOMIZER_WEBBENCH_TASKS" \
- --workload workloads/webbench.json --results-root /tmp/wb_smoke \
- --runner te_harness.webbench_smoke:make_runner --fresh
-```
-
-This is the production runner with `_segment` replaced by "copy the project's own reference
-solution into the workspace". It exercises the real evaluator, the real HTTP contract and
-the real Playwright grading, so **every task should come back resolved** — anything else is
-a harness fault, not a model result. Run it after touching this file or upgrading the
-Web-Bench checkout.
-
-### Provisioning the checkout
-
-The evaluator is a Rush monorepo and must be installed *and built*; the projects' Playwright
-browsers must match the version they pin (`@playwright/test` 1.57.0 → browser build 1200).
-
-```bash
-cd "$(dirname "$TOKENECONOMIZER_WEBBENCH_PROJECTS")"
-rush install # once
-rush build --to @web-bench/eval # the evaluator + its deps
-rush build --to @web-bench/calculator --to @web-bench/expressjs --to @web-bench/react \
- --to @web-bench/zustand --to @web-bench/table
-cd projects/calculator && npx playwright install chromium chromium-headless-shell
-```
-
-Verify the checkout independently of any agent by running a project's reference solution
-through its own suite — this is what the wiring check automates, and what to reach for when
-a real run's grades look impossible:
-
-```bash
-R="$TOKENECONOMIZER_WEBBENCH_PROJECTS"
-cd "$R/calculator" && MAX_TEST_WORKERS=4 EVAL_PROJECT_ROOT="$R/calculator/src" \
- IS_EVAL_PRODUCTION=true EVAL=true \
- EVAL_PROJECT_PORT=3931 npm run test -- -a # expect: 68 passed
-```
-
-`MAX_TEST_WORKERS=4` matches what the runner passes per grade
-(`TE_WEBBENCH_MAX_WORKERS`, default 4, recorded in the row as `playwright_workers`).
-Without it Playwright picks its own default — half the CPU count — and on a many-core host
-the **reference solution** fails its own suite on the larger projects, which reads like a
-broken checkout and is not one.
-
-No project in the current five needs a special pre-build — `react` and `zustand`
-are plain `vite build`, and `calculator`/`expressjs` build nothing. (The retired `prisma`
-did: its `npm run build` generated the client and seeded `test.sqlite`, and skipping it
-failed ~55 tests.) `expressjs` still fails one test if a stale `src/test.sqlite` is left
-lying around.
-
-> **Paths must be canonical.** Every path the evaluator derives comes from its entry
-> script's `__dirname`, and it passes the project root to each project's dev server through
-> `EVAL_PROJECT_ROOT` — while node reports `process.cwd()` already symlink-resolved.
-> Reached through a symlinked home (`/home/x` → `/srv/home/x`), the two spellings disagree
-> and Vite fails to resolve the `react` project's entry module against a root that is not
-> the root it thinks it is: **every** test fails with an app that never rendered, which
-> reads exactly like an agent that wrote nothing. `webbench_repo()` therefore
-> `realpath`-resolves the checkout, and anything invoking these commands by hand should too.
-
-## Config
-
-Everything comes from the repo's `.env` (see its `.env.example`) plus:
-
-| Var | Default | Meaning |
-|---|---|---|
-| `ANTHROPIC_API_KEY` | — | Claude Code's key, and the mechanisms' calls on a Claude lane. `ANTHROPIC_BASE_URL` / `ANTHROPIC_AUTH_TOKEN` are reported once and ignored: the agent and the mechanisms bill `api.anthropic.com` directly |
-| `OPENAI_API_KEY` | — | Codex's key. `OPENAI_BASE_URL` only for a region-scoped key on an OpenAI host |
-| `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `COPILOT_PROVIDER_*` | — | Copilot's GitHub auth, or its own BYOK; see [`COPILOT.md`](COPILOT.md) |
-| `TE_ENV_ACTIVATION` | `1` | `0` disables [project-environment activation](#project-environment-activation) and reproduces the pre-2026-09-11 (inactive `testbed` env) behaviour. Recorded per row |
-| `ANTHROPIC_MODEL` | `claude-opus-5` | agent model (was `claude-opus-4-8`; still accepted) |
-| `TE_EFFORT_LEVEL` | `high` | reasoning effort (`low`/`medium`/`high`/`xhigh`/`max`), passed as `--effort`. Validated at construction — a typo raises instead of silently using the CLI default |
-| ~~`TE_OPTIMIZER_MODEL`~~ | **refused** | the between-task proposer / judge / nudge-writer runs on the **agent's own model**, on the agent's own authentication, in every harness (`routing.optimizer_transport` records the wire). Not a knob: charging mechanism overhead to a cheaper model would understate what the arm spends, against a baseline that made no such calls. Setting this variable now raises at construction rather than being half-honoured |
-| `TE_CLAUDE_BIN` | from `which claude` | host Claude Code binary to mount |
-| `TE_SWEBENCH_GRADING` | — (`$DATA/swebench/swebench_grading.json` if `DATA` is set) | `instance_id` → grading fields. **Required**: no default — unset raises at construction |
-| `TE_SWEBENCH_REPO` | — | checkout supplying the official grader. **Required**: no default — unset raises at construction, rather than failing as an `ImportError` deep in grading after a task has been paid for |
-| `TE_MAX_TURNS` | `80` | agent turn cap |
-| `TE_TASK_TIMEOUT` / `TE_EVAL_TIMEOUT` | `1800` | wall-clock caps, seconds |
-| `TE_KEEP_CONTAINERS` | unset | `1` leaves containers up for post-mortem |
-| `TE_ALLOW_NETWORK_TOOLS` | unset | `1` lifts EVERY answer-key layer at once — the PreToolUse guard, the `/etc/hosts` block, and Codex's `web_search = "disabled"`. For a run that genuinely wants a browsing agent; a graded benchmark run must leave it unset (the answers are a fetch away) |
-| `TE_CODEX_VENDOR` | resolved from the Node shim's install tree | **Codex lanes only.** The vendor directory bind-mounted read-only into the task container (the static-PIE ELF plus its siblings). Resolved and checked at runner construction, because Docker invents an *empty* directory for a missing bind-mount source rather than erroring — every task would fail `codex: not found` behind a green launch banner |
-| `TE_SWEBENCH_MAX_CPUS` | `16` | CPU cap for ONE task container, plus the matching `OMP`/`MKL`/`OPENBLAS`/`NUMEXPR`/`LOKY` thread caps — which are the half that actually bounds a joblib pool, since `--cpus` does not change what `nproc` reports inside the container. `0` = unlimited. Recorded per row in `run_config.json → cpu_limit`. The launchers set it to `4` |
-| `TE_FLEET_CPUS` | `16` | CPU budget for **every lane's containers together**, written by `scripts/launch/fleet_budget.sh` onto the cgroup all rootless-docker container scopes share. The variable above is per container, so *N* lanes are an *N*×cap ceiling; this is the one that bounds the host. It binds lanes that are already running, needs no restart, and is work-conserving inside the budget. `0`/`none` = do not enforce. An un-delegated or read-only cgroup warns and never fails a launch |
-| `TE_OPTIMIZER_MAX_TOKENS` | `16384` | output cap for optimizer calls, the same on every runner (both agents, both domains). Too low truncates a judge's per-tool JSON into an unparseable answer, which reads downstream as "no verdict" while still billing — truncation is now logged, not silent. Applies on the API transport only: `copilot -p` has no output-cap flag, so on the CLI transport the value is read by nothing |
-| `TE_OPTIMIZER_PREFLIGHT` | set by the driver | `0` skips the mechanism-endpoint probe at runner construction. `run_experiment.py` sets it from `config.needs_optimizer`, so arms that make no paid between-task call neither bill the probe nor depend on the endpoint. Unset means "assume it might", so a direct caller of `make_runner` keeps the check |
-| `TE_OPTIMIZER_LOG` | `$TOKENECONOMIZER_RESULTS/logs/optimizer_calls.jsonl` | where between-task optimizer calls (prompt + response + usage) are recorded; not recorded at all if unset and no results root |
-
-### Project-environment activation
-
-The official SWE-bench images install the instance's dependencies into the `testbed` conda
-env and activate it only from `/root/.bashrc`. No lane runs with `HOME=/root` and no CLI's
-shell sources that file, so until 2026-09-11 a bare `python` / `pytest` in the agent's shell
-hit the **base** interpreter (Python 3.11, no project deps) while `TASK_TEMPLATE` told the
-agent the env was active. A bare `python` then failed to import the project's own
-package, and each failure cost a multi-step detour before the agent found
-`/opt/miniconda3/envs/testbed/bin/python` — or gave up running tests. Copilot's
-`--bash-env=on` was inert because no `BASH_ENV` was set.
-
-Every SWE-bench runner (Claude, Copilot, Codex) now activates the env for the agent
-**process**: at container start it lists `/opt/miniconda3/envs/*/bin`, picks `testbed`
-(or the only env), reads the image's `PATH`, and hands the agent `PATH=<env>/bin:<image
-PATH>`, `CONDA_PREFIX` and `CONDA_DEFAULT_ENV` via `docker exec -e`. That reaches every
-shell shape the CLIs spawn (`bash -lc`, `bash -c`, any `HOME` — measured), which a
-`BASH_ENV` hook does not for Claude Code. `python` is resolved once under the new `PATH`
-and the result is recorded in `run_config.json → env_activation`
-(`mode`, `env_bin`, `python`, `verified`) and on the row as `env_activation`.
-
-`TE_ENV_ACTIVATION=0` restores the old behaviour. **Rows taken with and without activation
-are not comparable on cost** and must not be pooled; the field exists so an aggregator can tell them apart.
-
-### The tool catalog
-
-`reflect.parse_tool_catalog_claude` needs `{tool_name: description}` for the tools a run
-loaded. The Copilot CLI dumps tool schemas into its debug log; Claude Code does not — its
-transcript carries only the tool *names* — so the descriptions are captured off the wire:
-
-```bash
-python -m te_harness.capture_catalog # -> tokeneconomizer/trace/claude_tool_catalog.json
-```
-
-It runs the agent exactly as a task run does (same image, container, flags, and turn cap —
-the CLI's offered tool set depends on the cap) with a stdlib recorder inside the container
-recording the `tools` array off the request and forwarding to the real API. Captures merge
-into any existing snapshot rather than replacing it, since the loaded set drifts slightly
-between runs. Re-run it after a Claude Code upgrade.
-
-### The grading file
-
-`swebench_grading.json` maps each workload instance to `base_commit`,
-`version`, `test_patch`, `FAIL_TO_PASS`, `PASS_TO_PASS`. The repo's `swebench_tasks.json`
-carries only `instance_id` / `problem_statement` / `repo`, which cannot be graded. Rebuild
-it from the HF parquet exports (all but 30 are in SWE-bench_Verified; those 30 xarray
-instances come from the full SWE-bench test split). A new run executes the 277 of
-`workloads.runnable_instances()`, which drops the one instance `SWEBENCH_EXCLUDED` names
-and adds the 49 `SWEBENCH_ADDED` uses to de-saturate the sklearn and sympy streams:
-
-```bash
-cd "$DATA/swebench"
-curl -sL -o verified.parquet "https://huggingface.co/api/datasets/princeton-nlp/SWE-bench_Verified/parquet/default/test/0.parquet"
-curl -sL -o full_test.parquet "https://huggingface.co/api/datasets/princeton-nlp/SWE-bench/parquet/default/test/0.parquet"
-python3 -c "
-import pyarrow.parquet as pq, json
-K=('repo','base_commit','environment_setup_commit','version','test_patch','patch','FAIL_TO_PASS','PASS_TO_PASS')
-out={}
-for f in ('full_test.parquet','verified.parquet'):
- for r in pq.read_table(f).to_pylist():
- out.setdefault(r['instance_id'], {k: r[k] for k in K})
-ids=[t['instance_id'] for t in json.load(open('swebench_tasks.json'))]
-json.dump({i: out[i] for i in ids if i in out}, open('swebench_grading.json','w'))"
-```
-
-## External tool scaffolds (the baseline arms)
-
-The baselines themselves live in the CORE package, at `experiments/te_bench/baselines/`, and
-are stdlib-only: they reach a container only through the callables this harness hands them
-(`exec_`, `copy_in`, `read_bytes`, `host_run` on `ScaffoldContext`). What follows is what
-*this* harness has to get right to drive them. Any other harness that can implement those
-four callables can run the same baselines unchanged.
-
-They install somebody else's off-the-shelf tool for the sealed agent so its cost and
-resolve land on the same honest basis as a mechanism. "Into the container" is the
-SWE-bench case, not the contract: Web-Bench runs the agent on the HOST, and the same
-baseline installs into a per-task `$HOME` and a per-task `bin/` instead. What differs is
-carried by `AgentProfile.home` / `AgentProfile.bin_dir`, so a scaffold never branches on
-the harness -- and one that hardcodes `/usr/local/bin` silently no-ops off-container
-(`chmod` fails, `&&` short-circuits, the row reads `rtk_installed: false`). They are **baselines, not
-mechanisms**: nothing in `tokeneconomizer/` imports the package on its own — not
-`__init__.py`, not any mechanism package — so `import tokeneconomizer` stays
-dependency-free and no mechanism can see a baseline.
-
-| Scaffold | Arms | What it installs | Host requirement |
-|---|---|---|---|
-| `rtk` | `rtk`, `trimech-rtk`, `trimech-rtk-web`, `codex-trimech-rtk` | pinned rtk **0.45.0** musl binary, plus the integration that agent has: a PreToolUse hook on Claude (`settings.json`) and Copilot (`$COPILOT_HOME/hooks/`), instruction files on Codex | staged binary cache (`TE_SCAFFOLD_CACHE`, else `$DATA/scaffolds`) |
-| `serena` | `serena` | `uv tool install serena-agent` in-container, an MCP server, and a nav-tool nudge | none (needs network *from* the container) |
-| `repomap` | `repomap`, `trimech-repomap`, `codex-trimech-repomap` | aider's token-budgeted repo map, written as project instructions | `aider` on the host — `pip install -e '.[baselines]'` |
-
-There is deliberately **no `trimech-serena`**: Serena's contract is that the agent navigates
-through its MCP tools, which is exactly what evidence untooling prunes when a tool goes
-unused, so the combined arm would measure that contention rather than either baseline. RTK
-hooks `Bash` (always in `PROTECTED_TOOLS`, so untooling can never drop it) and the repo map
-writes a file and touches no tool — neither contends, which is why those two combinations
-are well-defined.
-
-### Which baselines each domain can host
-
-`rtk` is the only one Web-Bench can run (`te_harness/webbench.py` `WEBBENCH_SCAFFOLDS`);
-`scripts/sweep_plan.py` `SWEEP_ARMS_WEBBENCH_UNAVAILABLE` is the planner-side twin, and
-`tests/test_sweep_arms.py` asserts the two agree.
-
-| Scaffold | SWE-bench | Web-Bench | Why not |
-|---|---|---|---|
-| `rtk` | yes | **yes** | — it needs no container and no language |
-| `repomap` | yes | no | its generator walks `*.py`; Web-Bench projects are TS/JS |
-| `serena` | yes | no | an MCP navigator for a codebase; Web-Bench ships a file set |
-
-Two Web-Bench-specific differences, both handled by the runner rather than the baseline:
-
-* **Artifacts are excluded from the ANSWER, not from a diff.** There is no `git diff` to
- subtract from — the evaluator applies whatever files the runner returns — so `_collect`
- refuses to ship the scaffold's own names, recording them in `run_config.json` →
- `scaffold.answer_excludes`.
-* **`COPILOT_HOME` is isolated per task-run when a scaffold is active.** The Copilot
- Web-Bench runner deliberately keeps the real `$HOME` (a fresh one would orphan the
- ~170 MB package cache), but both hook writers land in the CLI's config dir — rtk's
- `hooks/rtk-rewrite.json` and the net guard's `settings.json` — which would be the
- operator's own `~/.copilot`. Only that variable is redirected, seeded with the real auth,
- so a sweep cannot leave a hook behind on the machine. The scaffold resolves the directory
- as `${COPILOT_HOME:-$HOME/.copilot}` in the shell, which is right on both lanes.
-
-### Three things that make a scaffold arm silently fake
-
-* **The graded diff.** A scaffold writes project instructions *into* `/testbed`, so
- `git diff` picks them up and the official grader would apply the scaffold's own prompt
- text as part of the agent's fix. Each scaffold declares `patch_excludes`; the runner
- subtracts them (`git diff -- . ':(exclude,top)CLAUDE.md' …`) and records what it
- subtracted in `run_config.json`. With no scaffold the diff command is left byte-identical
- to the pre-scaffold form, so stored baseline rows stay reproducible.
-* **RTK's hook.** `rtk init -g` **declines** to patch the agent's settings
- non-interactively — it prints a "MANUAL STEP" notice and exits 0. Trusting it yields an
- arm where `rtk --version` works, every provenance field looks healthy, and the hook never
- fires. The scaffold registers the hook itself and `rtk_hook_registered` records whether
- that took; a `true` install with a `false` hook logs a warning naming the failure.
-* **Serena is a nudge, not an exclusion.** The original study asked the agent to stop using
- the native navigation tools via an instruction and did not pass `--disallowed-tools`.
- That is kept: `Read` is in `PROTECTED_TOOLS`, so an exclusion would be filtered out and
- the arm would run native with an unused MCP server attached. If the agent keeps grepping,
- that **is** the measurement.
-
-A scaffold that fails is recorded, not raised: the row carries `scaffold_error` (or
-`rtk_installed: false`, `serena_installed: false`, `map_ok: false`) and the task runs
-native. A lane of flagged rows is diagnosable; a lane of missing rows is not. **Filter those
-rows out before quoting a scaffold arm's mean** — they are native rows wearing a scaffold's
-name.
-
-### Adding one
-
-Subclass `Scaffold` (`experiments/te_bench/baselines/base.py`), implement `setup(ctx)` returning a
-notes dict, declare `patch_excludes`, register it in `SCAFFOLDS`, and map its arm(s) in
-`ARM_SCAFFOLDS`. Per-agent differences (instructions path, native tool names, `$HOME`, how
-an MCP config is wired) come from `ctx.profile`, never from a hardcoded assumption — writing
-`CLAUDE.md` on a Copilot run produces an arm that is native with a stray file in it. Add
-the arm to `ARMS` in `scripts/run_experiment.py` with `scaffold="<name>"`;
-`tests/test_sweep_arms.py` asserts the two maps agree.
-
-## The answer-key guard
-
-A SWE-bench instance's fix commit is public on GitHub, so an agent that can fetch it is not
-solving the task — it is reading the answer key, and the resolve verdict it produces is
-worthless. So this applies to **every arm, `baseline` included**: it is a property of the
-measurement, not of an arm. Leaving it to untooling would be worse than useless, since
-untooling drops a tool only after observing disuse — precisely the agents that browse would
-keep the ability.
-
-**One policy.** A single case-insensitive substring, `github`. Re-derived 2026-09-09 over
-3,538 stored run dirs and 558 network-shell calls: it matches 352, every one of them reading
-a repository's source, history, PR diffs or `.patch` files, with **0 false positives** (no
-`pip`/`npm`/`npx`/`yarn` install blocked; pip alone accounts for 180 of the legitimate
-calls) and **0 misses** (nothing naming a `.patch`, a `/commit/`, a `/pull/`, a mirror, or a
-benchmark repo escaped it). That is the argument for keeping it this narrow rather than
-cutting the container's network: the wider rule also deletes the tool surface the untooling
-mechanism is measured on, and charges the baseline for a restriction the cheat route never
-needed.
-
-**Two enforcement points**, because a hook is only as good as the CLI's cooperation:
-
-| layer | how | Claude | Copilot | Codex |
-|---|---|---|---|---|
-| `PreToolUse` hook | exit 2 + reason on stderr | ✅ | ✅ | ✅ since 2026-09-30 — `$CODEX_HOME/hooks.json` + `--dangerously-bypass-hook-trust` |
-| `/etc/hosts` block | answer-key hosts → `127.0.0.1` in the task container | ✅ | ✅ | ✅ |
-
-The hook is the layer that tells the **model why**, which a DNS failure cannot. The hosts
-block needs no cooperation from any CLI, so it is identical on all three lanes, and it was
-the only layer Codex had until 2026-09-30. Verified in a real SWE-bench container: afterwards `curl`, `wget`,
-`git clone` and `python -c "import urllib.request"` all fail with `Connection refused` for
-the answer-key hosts, while `pypi.org`, `files.pythonhosted.org` and a real `pip download`
-keep working. `127.0.0.1` rather than `0.0.0.0` so the connection is refused at once instead
-of hanging to a timeout. The stanza is appended idempotently behind a marker comment and
-then **verified** (`getent hosts github.com` must answer `127.0.0.1`) — a write can succeed
-into a container whose resolver ignores `/etc/hosts`, and that failure is otherwise
-invisible.
-
-`TE_ALLOW_NETWORK_TOOLS=1` lifts every layer, or none.
-
-**Neither layer is bullet-proof**, and the row telemetry is what makes that manageable:
-
-| field | means |
-|---|---|
-| `net_guard_installed` | the hook is armed *and* proved it refuses a probe |
-| `net_guard_blocks` | hook refusals this task |
-| `answer_key_hosts_blocked` | the DNS stanza is installed *and* `github.com` resolves to loopback |
-| `answer_key_attempts` | answer-key-shaped commands found in the transcript afterwards — **agent-independent**, so it is the number to watch on any row whose `net_guard_installed` is false (every Codex row before 2026-09-30); `None` when there is no transcript, never `0` |
-
-An IP literal, a redirect, a mirror or a base64'd URL walks past both layers. A model
-routing around them shows up as `answer_key_attempts` climbing while `net_guard_blocks`
-stays flat — which is why attempts are counted from the trace and not inferred from
-refusals.
-
-## Not covered yet
-
-* **Two tool descriptions are unobtainable.** The catalog is captured (below), but `Task`
- and `ToolSearch` stay name-only: they exist *only* in first-party mode, and pointing the
- CLI at any base URL — including the capture shim — removes them from the offered set.
- Their schemas reach the model's context but never the transcript (a `ToolSearch`
- tool_result is empty by design), so there is nowhere to read them from short of
- intercepting first-party TLS. The judge tolerates a name with no description.
diff --git a/experiments/docs/RUNNING.md b/experiments/docs/RUNNING.md
deleted file mode 100644
index 194238c..0000000
--- a/experiments/docs/RUNNING.md
+++ /dev/null
@@ -1,209 +0,0 @@
-# Running the experiments
-
-The sweep runs three agents — Claude Code, the GitHub Copilot CLI and Codex — each on its own
-native authentication, against SWE-bench and Web-Bench, once per arm. This page is the run
-book: how each agent is billed, how to check the wiring before paying for anything, the arm
-catalog with one command per lane, and what to do with the rows afterwards.
-
-Before this page: [`SETUP.md`](SETUP.md) (venv, data root, Docker, `.env`) and
-[`BENCHMARKS.md`](BENCHMARKS.md) (task images and datasets). Commands below run from
-`experiments/`.
-
-## 1. Authentication — each agent's own
-
-| Agent | Billed through | What to set (in `.env` or the shell) |
-|---|---|---|
-| Claude Code | the Anthropic API | `ANTHROPIC_API_KEY` |
-| Codex | the OpenAI API | `OPENAI_API_KEY`; `OPENAI_BASE_URL` only for a key issued against a regional OpenAI endpoint (`https://<region>.api.openai.com/v1`) |
-| Copilot CLI | your GitHub Copilot subscription | `/login` in `copilot` on the host, or `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` |
-| Copilot CLI | Copilot's own BYOK | `COPILOT_PROVIDER_BASE_URL`, `COPILOT_PROVIDER_TYPE`, `COPILOT_PROVIDER_API_KEY` or `_BEARER_TOKEN`, and a pinned model (see [`COPILOT.md`](COPILOT.md)) |
-
-Each agent bills its own vendor directly. The launchers ignore `ANTHROPIC_BASE_URL` and
-`ANTHROPIC_AUTH_TOKEN` (they say so once and unset them), and refuse an `OPENAI_BASE_URL`
-that is not an OpenAI host. Copilot-specific steps — signing in, keeping a token warm through
-a long sweep, and checking a finished row — are in [`COPILOT.md`](COPILOT.md).
-
-The model is part of the cost basis, so every lane pins one: the results tree is named
-`<agent>_<domain>_<model-tag>` (for example `claude_swebench_opus48`), and two models never
-share a tree.
-
-## 2. Check the wiring for free
-
-```bash
-bash scripts/launch/smoke_test.sh # offline: StubRunner, temp dirs, no Docker, no model
-AGENT=claude MODEL=claude-sonnet-5 DOMAIN=swebench DRYRUN=1 \
- bash scripts/launch/main_sweep.sh # the plan and its size, nothing run
-```
-
-`DRYRUN=1` works on a fresh clone with nothing configured; the billed probes skip themselves.
-
-## 3. One paid cell first
-
-One task, one arm, in the foreground, before any lane:
-
-```bash
-AGENT=claude MODEL=claude-sonnet-5 DOMAIN=swebench ARMS=baseline \
- REPOS=sympy/sympy SEEDS=0 LIMIT=1 DETACH=0 \
- RUNNER=te_harness.swebench:make_runner \
- bash scripts/launch/main_sweep.sh
-```
-
-Then read the row (`$TOKENECONOMIZER_RESULTS/<tree>/baseline/sympy_s0/*/row.json`):
-`num_turns` must be above zero and the token fields populated. A mechanism-bearing arm needs
-more than one task to fire anything — injection proposes on a 5-task cadence, untooling
-needs 3 consecutive unused tasks, and the spiral guard waits for its minimum turn count — so
-pilot `trimech` with `LIMIT=6` before trusting it.
-
-## 4. Claude Code and Copilot — `main_sweep.sh`
-
-One invocation fills one tree: one agent, one model, one domain, every arm × group × seed.
-The main sweep is both agents × `claude-opus-4-8` and `claude-sonnet-5` × both domains, eight
-lanes; `scripts/launch/full_sweep.sh` launches all eight. Each lane is detached by default
-and resumes where it stopped (`SKIP_DONE=1`).
-
-### swebench — 12 arms
-
-| Arm | What runs |
-|---|---|
-| `baseline` | no mechanisms, harness-default effort (`high`) — the cost basis every arm pairs against |
-| `baseline-medium` | `baseline` at `TE_EFFORT_LEVEL=medium` (the arm sets it) |
-| `baseline-low` | `baseline` at `TE_EFFORT_LEVEL=low` |
-| `inject-only` | micro-skill synthesis and injection only |
-| `untool-only` | evidence untooling and the tool judge only |
-| `spiral-only` | spiral guard, judge and nudge only |
-| `trimech` | all three mechanisms together |
-| `rtk` | `baseline` + rtk 0.45.0 |
-| `serena` | `baseline` + Serena |
-| `repomap` | `baseline` + aider's repo map |
-| `trimech-rtk` | `trimech` + rtk |
-| `trimech-repomap` | `trimech` + the repo map |
-
-```bash
-for AGENT in claude copilot; do for MODEL in claude-opus-4-8 claude-sonnet-5; do
- AGENT=$AGENT MODEL=$MODEL DOMAIN=swebench \
- RUNNER=te_harness.swebench:make_runner \
- bash scripts/launch/main_sweep.sh
-done; done
-```
-
-### webbench — 5 arms
-
-| Arm | What runs |
-|---|---|
-| `baseline` | no mechanisms, harness-default effort |
-| `baseline-medium` | `baseline` at `TE_EFFORT_LEVEL=medium` |
-| `baseline-low` | `baseline` at `TE_EFFORT_LEVEL=low` |
-| `trimech-web` | `trimech` with the spiral stage tuned for short streams |
-| `rtk` | `baseline` + rtk 0.45.0 |
-
-```bash
-for AGENT in claude copilot; do for MODEL in claude-opus-4-8 claude-sonnet-5; do
- AGENT=$AGENT MODEL=$MODEL DOMAIN=webbench \
- RUNNER=te_harness.webbench:make_runner \
- bash scripts/launch/main_sweep.sh
-done; done
-```
-
-Web-Bench reaches the agent through the evaluator's HTTP seam with no per-task repository
-container, so `serena`, `repomap` and `trimech-repomap` cannot run there, and the planner
-refuses them. The single-mechanism arms are answered on SWE-bench and are not planned for
-Web-Bench; they still run if named in `ARMS`.
-
-### The frontier lane
-
-`claude-opus-5` runs four arms per domain on both agents, in trees of its own (never pooled
-with the main sweep's):
-
-```bash
-for AGENT in claude copilot; do
- AGENT=$AGENT MODEL=claude-opus-5 DOMAIN=swebench \
- ARMS="baseline baseline-medium baseline-low trimech" \
- RUNNER=te_harness.swebench:make_runner bash scripts/launch/main_sweep.sh
- AGENT=$AGENT MODEL=claude-opus-5 DOMAIN=webbench \
- ARMS="baseline baseline-medium baseline-low trimech-web" \
- RUNNER=te_harness.webbench:make_runner bash scripts/launch/main_sweep.sh
-done
-```
-
-`full_sweep.sh` does not launch these two.
-
-## 5. Codex — `codex_ab.sh`
-
-Codex runs one arm per invocation, through its own launcher, on `gpt-5.6-terra` and
-`gpt-5.6-sol`. `BASELINE=0` runs only the named arm, so the loop below fills one tree per
-model and domain with every arm. The Codex mechanisms are native to it: untooling works on
-capability packages rather than single tool schemas, and the spiral guard nudges in the same
-thread rather than stopping a turn.
-
-### swebench — 12 arms
-
-| Arm | What runs |
-|---|---|
-| `baseline` | no mechanisms, harness-default effort (`high`) |
-| `baseline-medium` | `baseline` at `TE_EFFORT_LEVEL=medium` |
-| `baseline-low` | `baseline` at `TE_EFFORT_LEVEL=low` |
-| `codex-inject` | environment facts plus the distiller, injected at session start (the proposer bills) |
-| `codex-untool` | evidence-gated capability untooling |
-| `codex-spiral` | the defensive spiral profile: same-thread nudges, no abort, no effort change |
-| `codex-trimech` | all three Codex mechanisms |
-| `rtk` | `baseline` + rtk 0.45.0 in its Codex instruction mode |
-| `serena` | `baseline` + Serena |
-| `repomap` | `baseline` + aider's repo map |
-| `codex-trimech-rtk` | `codex-trimech` + rtk |
-| `codex-trimech-repomap` | `codex-trimech` + the repo map |
-
-```bash
-REPOS="django/django matplotlib/matplotlib scikit-learn/scikit-learn sphinx-doc/sphinx sympy/sympy pydata/xarray"
-for MODEL in gpt-5.6-terra gpt-5.6-sol; do
- for ARM in baseline baseline-medium baseline-low codex-inject codex-untool codex-spiral \
- codex-trimech rtk serena repomap codex-trimech-rtk codex-trimech-repomap; do
- MODEL=$MODEL ARM=$ARM BASELINE=0 DOMAIN=swebench REPOS="$REPOS" SEEDS="0 1 2 3 4" \
- RUNNER=te_harness.swebench:make_runner DETACH=0 \
- bash scripts/launch/codex_ab.sh
- done
-done
-```
-
-### webbench — 5 arms
-
-| Arm | What runs |
-|---|---|
-| `baseline` | no mechanisms, harness-default effort |
-| `baseline-medium` | `baseline` at `TE_EFFORT_LEVEL=medium` |
-| `baseline-low` | `baseline` at `TE_EFFORT_LEVEL=low` |
-| `codex-trimech` | all three Codex mechanisms |
-| `rtk` | `baseline` + rtk 0.45.0 in its Codex instruction mode |
-
-```bash
-PROJECTS="calculator expressjs react zustand table"
-for MODEL in gpt-5.6-terra gpt-5.6-sol; do
- for ARM in baseline baseline-medium baseline-low codex-trimech rtk; do
- MODEL=$MODEL ARM=$ARM BASELINE=0 DOMAIN=webbench REPOS="$PROJECTS" SEEDS="0 1 2 3 4" \
- RUNNER=te_harness.webbench:make_runner DETACH=0 \
- bash scripts/launch/codex_ab.sh
- done
-done
-```
-
-On Web-Bench the Codex agent runs on the host; the runner blocks the answer-key hosts in an
-unprivileged user and mount namespace and refuses to start if it cannot.
-
-## 6. Narrowing a lane
-
-Every launcher takes the same knobs: `ARMS` (or `ARM`), `REPOS`, `SEEDS`, `LIMIT` (tasks per
-cell), `DRYRUN=1`, `DETACH=0`, `ON_FAIL=abort`. The variables and their defaults are listed at
-the top of each script and in [`../scripts/launch/README.md`](../scripts/launch/README.md).
-
-## 7. Aggregating and comparing
-
-```bash
-python scripts/aggregate.py $TOKENECONOMIZER_RESULTS/<tree> # -> <tree>/index/*.csv
-python scripts/compare_arms.py \
- --baseline $TOKENECONOMIZER_RESULTS/<tree>/baseline/<cell> \
- --arm $TOKENECONOMIZER_RESULTS/<tree>/<arm>/<cell>
-```
-
-`aggregate.py` rewrites the whole index on every call and refuses an `--arms` subset that
-would drop arms from it. `compare_arms.py` pairs tasks by instance id and prices them on the
-cache-aware effective-token basis, with each arm's own mechanism calls charged to it. Never
-average two trees into one cell: the model and the agent are both part of the cost basis.
diff --git a/experiments/docs/SETUP.md b/experiments/docs/SETUP.md
deleted file mode 100644
index a5b22e5..0000000
--- a/experiments/docs/SETUP.md
+++ /dev/null
@@ -1,339 +0,0 @@
-# Setup — from `git clone` to a real run
-
-A sequential walkthrough of the four things a fresh clone needs: a **venv**, a
-**data directory**, **credentials**, and a **runner**. Every step ends with a
-gate that tells you immediately whether it worked, so a failure lands on the step that
-caused it instead of surfacing hours later as an impossible benchmark result.
-
-Reference detail lives elsewhere and is linked rather than repeated:
-[`ENVIRONMENT.md`](ENVIRONMENT.md) for requirements and Docker install,
-[`BENCHMARKS.md`](BENCHMARKS.md) for per-benchmark dataset provisioning,
-[`../scripts/launch/README.md`](../scripts/launch/README.md) for launcher flags.
-
-```
-Step 1 venv → pytest + smoke test pass (no Docker, no keys)
-Step 2 data directory → $DATA exists, canonical
-Step 3 credentials → each agent's key answers, free
-Step 4 runner → one real task produces a graded row
-Step 5 per-benchmark data → the benchmark can grade its own answer key
-Step 6 first A/B → index CSVs compare_arms.py reads
-```
-
----
-
-## Step 1 — the venv (Layer 1)
-
-```bash
-git clone <repo-url> TokenEconomizer && cd TokenEconomizer
-python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
-pip install -e '.[test]'
-cd experiments # every command below runs from here
-```
-
-The core is stdlib-only; the `test` extra adds `pytest`. Other install shapes
-(`requirements.txt`) are in [`ENVIRONMENT.md`](ENVIRONMENT.md).
-
-**Running the full arm catalog needs two more extras.** The run book lists 12 SWE-bench arms
-per agent, and three of them carry an external tool baseline with a host dependency:
-
-```bash
-pip install -e '..[test,harness,baselines]'
-```
-
-| extra | what it adds | arms that need it |
-|---|---|---|
-| `harness` | nothing on PyPI — it names the intent to run `te_harness/` (Docker, an agent CLI, a key, benchmark images) | every arm |
-| `baselines` | `aider-chat`, for the repo map generated on the HOST | `repomap`, `trimech-repomap`, `codex-trimech-repomap` |
-
-`rtk` and `serena` need no host package — rtk ships a static binary (staged into
-`TE_SCAFFOLD_CACHE`, else `$DATA/scaffolds`, from Step 2) and Serena installs itself inside
-the task container. Skip `baselines` only if you will never run a repo-map arm: without it
-those arms raise `ScaffoldError` at runner construction, naming this command, so a lane fails
-at launch rather than 200 tasks in.
-
-**Gate:**
-
-```bash
-python -c "import tokeneconomizer as te; print(te.Economizer)" # self-contained import
-pytest # offline suite
-bash scripts/launch/smoke_test.sh # every arm wired
-```
-
-Expect `pytest` all-pass and `SMOKE PASS: all arms wired; no artifacts left.` This works with
-no Docker, no datasets and no API keys — if it passes, the repo layer is healthy and
-everything after this point is external infrastructure.
-
-> Use **this** venv for the driver later, and install the SWE-bench grader into it (Step 4).
-> A venv that can run `pytest` but cannot import the grader will fail only once a real run
-> reaches grading.
-
----
-
-## Step 2 — the one directory outside the repo
-
-The `AgentRunner` implementation is **in** the repo — [`te_harness/`](../te_harness) — so
-there is no harness directory to create and no
-`PYTHONPATH` to export: `scripts/run_experiment.py` puts `experiments/` and the repository
-root (the shared core) on `sys.path` itself,
-so `--runner te_harness.swebench:make_runner` resolves from any working directory. (Writing
-your own remains supported; put it anywhere importable and pass
-`--runner your_pkg:make_runner`.)
-
-What does **not** belong in the repo is data — what a benchmark ships and what runs produce.
-One directory, created wherever you like:
-
-| Variable | Holds | Contents |
-|---|---|---|
-| `$DATA` | **what a benchmark ships + what runs produce** | task lists, grading keys, benchmark checkouts, results |
-
-Two things deliberately live in neither: **Docker images** (they belong to Docker's own
-store — `docker images` is the inventory, never copy them into `$DATA`) and the **SWE-bench
-grader checkout**, which is a pip-installable library and can sit anywhere you point
-`TE_SWEBENCH_REPO`.
-
-```bash
-export DATA="$(readlink -f ~/te_data)"
-mkdir -p "$DATA/results"
-```
-
-`readlink -f` is not cosmetic. If your home is a symlink (`/home/you` → `/srv/home/you`),
-Web-Bench's Vite-based project resolves its entry module against a root that disagrees with
-node's already-resolved `process.cwd()`, and **every** test fails with an app that never
-rendered — indistinguishable from an agent that wrote nothing. Canonicalize once, here.
-
-Keep the exports in one sourceable file so every shell, launcher and hand-run command agrees:
-
-```bash
-cat > "$DATA/env.sh" <<'EOF'
-# TokenEconomizer data root — source me
-export DATA="$(readlink -f ~/te_data)"
-export TOKENECONOMIZER_RESULTS="$DATA/results"
-export PLAYWRIGHT_BROWSERS_PATH="$HOME/.cache/ms-playwright"
-EOF
-. "$DATA/env.sh"
-```
-
-### Why a benchmark checkout goes in `$DATA`, not the repo
-
-Some benchmarks ship their grader *with* their data, inseparably. Web-Bench is one monorepo
-holding both its Node/Playwright evaluator **and** its task data
-(`projects/<project>/tasks.jsonl`, `src-init/`, `test/`), and its evaluator resolves
-`projects/` relative to its own location — so the tree cannot be split. Of its ~1.9 GB,
-~1.7 GB is regenerable `node_modules`/pnpm store and ~158 MB is the actual dataset. Moving
-it into the repo would commit a real dataset in order to evict build artifacts from the data
-directory, and would leave the dataset variable pointing inside a git tree. So: **a benchmark
-checkout is a benchmark payload — it lives in `$DATA`**, and the repo stays code only.
-
-Results are also `$DATA` (they are what runs produce) and are git-ignored by the repo.
-Old run archives are worth parking under `$DATA/archive/` rather than at the top level.
-
----
-
-## Step 3 — credentials
-
-```bash
-cp .env.example .env # .env is git-ignored
-```
-
-`.env` is plain `KEY=value`, no interpolation, and **a variable already exported in your
-shell always wins** — so a one-off `ANTHROPIC_API_KEY=... bash scripts/launch/...` overrides
-the file. Each agent runs on its own native authentication; fill in the ones you will run:
-
-| Key | For | Notes |
-|---|---|---|
-| `ANTHROPIC_API_KEY` | Claude Code | `ANTHROPIC_BASE_URL` / `ANTHROPIC_AUTH_TOKEN` are ignored and unset by the launchers |
-| `OPENAI_API_KEY` | Codex | |
-| `OPENAI_BASE_URL` | Codex | **only** for a region-scoped key (`https://<region>.api.openai.com/v1`) — such a key 401s on the global endpoint; any non-OpenAI host is refused |
-| `COPILOT_GITHUB_TOKEN` / `GH_TOKEN`, or `COPILOT_PROVIDER_*` | Copilot CLI | the GitHub subscription, or Copilot's own BYOK — see [`COPILOT.md`](COPILOT.md) |
-| `ANTHROPIC_MODEL`, `CODEX_MODEL` | cost basis | must exist in `pricing.MODEL_WEIGHTS`, which hard-fails rather than mispricing an unknown id |
-| `TE_EFFORT_LEVEL` | cost basis | `low\|medium\|high\|xhigh\|max`. Keep **both arms of an A/B identical**: results at different levels are not directly comparable |
-
-**Gate — prove the keys without spending a token.** The model-list endpoints are free:
-
-```bash
-set -a; . ./.env; set +a
-curl -s -o /dev/null -w 'anthropic %{http_code}\n' https://api.anthropic.com/v1/models \
- -H "x-api-key: $ANTHROPIC_API_KEY" -H "anthropic-version: 2023-06-01"
-curl -s -o /dev/null -w 'openai %{http_code}\n' "${OPENAI_BASE_URL:-https://api.openai.com/v1}/models" \
- -H "Authorization: Bearer $OPENAI_API_KEY"
-```
-
-Each key you set should give `200`. Fetch the listings in full once and check that your
-configured `ANTHROPIC_MODEL` / `CODEX_MODEL` ids actually appear — a typo here fails much
-later, inside a container, after you have paid for the containers that came before it. The
-Copilot gate is in [`COPILOT.md`](COPILOT.md) Step 1.
-
----
-
-## Step 4 — the runner
-
-The heavy machinery — launching a sealed agent, applying the economizer's per-task
-decisions, grading against gold — sits **below `AgentRunner`**
-([`te_bench/runner.py`](../te_bench/runner.py), which is the authoritative
-contract). The repo ships a reference implementation, [`te_harness/`](../te_harness) — see
-[`HARNESS.md`](HARNESS.md) — so this step is a check
-rather than something to write. Every launch selects a runner with `RUNNER=module:factory`
-(a zero-arg callable returning the runner), which is also how you'd point it at your own.
-
-What a runner owes the economizer:
-
-| Member | Contract |
-|---|---|
-| `optimizer_call(prompt, model)` | one small paid LLM request → `(text, effective_tokens)`; used by the between-task proposer / judge / nudge-writer. Must never raise — return `("", 0.0)` on a transport failure so the mechanisms fall back to their LLM-free path |
-| `run_task(task, *, arm, injected, exclude_tools, run_dir_path, **kw)` | run one task with those decisions applied → `(row, run_dir)` |
-| `begin_stream(tasks, **info)` / `end_stream()` | **optional.** For a harness that owns a whole stream rather than one task (Web-Bench's evaluator drives its project's 20 sequentially dependent tasks itself). The driver calls them `hasattr`-guarded, so runners without them are unaffected |
-
-`run_task` must write `transcript.jsonl` under `run_dir_path` (the schema
-`tokeneconomizer.trace` re-reads) and return a row carrying the four-field token breakdown
-`pricing.effective_tokens` reads, plus `resolved` and `num_turns`. Recording a
-`run_config.json` beside it is strongly advised: agent CLIs record neither the reasoning
-effort nor the tool mask in their own transcripts, so without it a finished run cannot answer
-"what settings produced this?".
-
-Pick it per launch. No `PYTHONPATH` is needed for the in-repo harness — the driver puts
-`experiments/` and the repository root on `sys.path` itself, so `te_harness.*` resolves from any working directory; a
-harness of your own just has to be importable by the same interpreter.
-
-`.env` ships `RUNNER=stub`, the built-in offline `StubRunner`. It runs **no agent and grades
-nothing** — its `resolved` is a fixed deterministic pattern — so set `RUNNER` explicitly on
-every real launch. With more than one domain you will have more than one runner, which is
-why this is a per-launch flag rather than a value you set once:
-
-```bash
-RUNNER=te_harness.swebench:make_runner # SWE-bench
-RUNNER=te_harness.webbench:make_runner # Web-Bench
-```
-
-> The factory is handed the driver's `--agent` label (`factory(agent=...)`, falling back to
-> a zero-arg call for older harnesses, with the label also exported as `TE_AGENT`). A factory
-> that ignores it will run whatever agent it hardcodes while the driver files the rows under
-> `--agent`'s name — plausible numbers attributed to an agent that never ran. If your harness
-> supports one agent only, raise on an unexpected label rather than ignoring it. Running the
-> **Copilot CLI** instead of Claude Code: [`COPILOT.md`](COPILOT.md).
-
-**Gate:** launch with `RUNNER=stub` and confirm the banner
-`[env] RUNNER=stub -- SYNTHETIC run: no agent, no grading, numbers are NOT a benchmark`.
-That line is your standing check that you are pointed at a real harness; if you ever see it
-on a run you meant to be real, stop.
-
-### Installing the SWE-bench grader
-
-The official grader is a library the runner imports, so it must be importable from the **same
-interpreter that runs the driver**:
-
-```bash
-git clone https://github.com/princeton-nlp/SWE-bench.git "$DATA/SWE-bench"
-pip install -e "$DATA/SWE-bench" # into the Step-1 venv
-echo 'export TE_SWEBENCH_REPO="$DATA/SWE-bench"' >> "$DATA/env.sh"
-```
-
-**Gate:** `python -c "from swebench.harness.grading import get_eval_report; print('ok')"`.
-Its import chain pulls `bs4`/`datasets`, so a venv that skipped `pip install -e` on the
-checkout raises `ModuleNotFoundError` — and only at grading time, after the agent has run and
-billed.
-
----
-
-## Step 5 — per-benchmark data
-
-Full fetch-and-layout instructions per benchmark are in
-[`BENCHMARKS.md`](BENCHMARKS.md); provision only what the workload names
-(`workloads/*.json`), which is a small fraction of each full benchmark. What belongs here is
-the discipline that saves money:
-
-> **Verify a benchmark can grade its own answer key before you spend anything on an agent.**
-> A benchmark that cannot pass its own reference solution cannot grade a model, and the
-> failure looks identical to a model that produced nothing.
-
-For **SWE-bench** that means, in order: the grading file covers every workload id you intend
-to run; every one of those ids has a local image (`docker images`); then one task at
-`--arm baseline --limit 1` whose `row.json` carries a `resolved` from the official report and
-a full token breakdown.
-
-For **Web-Bench** that means installing *and building* the monorepo (an installed-but-unbuilt
-checkout has no `dist/` to run — they are separate Rush commands), installing the Playwright
-browser build the projects **pin** (a mismatch surfaces as `Executable doesn't exist`, not as
-a version warning), and then running each project's own `src` through its own suite and
-recording the expected pass counts. Some projects need their build step first to generate a
-client or seed a database — exactly what the evaluator does per task — so a bare test run
-under-reports.
-
-Whatever your harness offers as an offline wiring check, run it before the first paid task:
-it should exercise the real grader with the agent call replaced, so **every task comes back
-resolved** and anything else is a harness fault rather than a model result.
-
----
-
-## Step 6 — the first A/B
-
-```bash
-. "$DATA/env.sh"
-AGENT=claude DOMAIN=swebench ARM=trimech SEEDS="0" \
- REPOS="pydata/xarray django/django sympy/sympy" \
- RUNNER=te_harness.swebench:make_runner bash scripts/launch/trimech_ab.sh
-```
-
-Each launcher runs `baseline` then the economized arm over your repos and seeds, then
-aggregates into `index/all_rows.csv` + `index/summary_by_cell.csv`; compare the two arms
-cell by cell with `scripts/compare_arms.py`. Launches **detach by
-default** and print the log path plus the `kill -TERM -<pid>` line that stops the whole
-process group (`DETACH=0` to stay in the foreground).
-
-Read [`RUNNING.md`](RUNNING.md) for the arm catalog and one command per lane,
-[`../scripts/launch/README.md`](../scripts/launch/README.md) for every env var, and
-[`../scripts/README.md`](../scripts/README.md) for the chain from rows to comparisons.
-
-### Where the traces land
-
-```
-$TOKENECONOMIZER_RESULTS/<agent>_<domain>_<model>/ e.g. claude_swebench_opus48
-├── <arm>/<repo-or-project>_s<seed>/ the CELL: one arm x one stream x one seed
-│ ├── 20260826T204556Z__000__claude__<instance>__<arm>__s<seed>__<mode>/
-│ │ ├── transcript.jsonl the raw agent stream — the primary artifact
-│ │ ├── row.json the normalized row (tokens, resolved, telemetry)
-│ │ ├── run_config.json everything that shaped the run (effort, tool mask, …)
-│ │ └── … domain extras: model_patch.diff + eval.log (SWE-bench),
-│ │ agent_request_<n>.json (Web-Bench)
-│ ├── _streams/<stream>__<mode>__stream.jsonl the per-cell amortized cost curve
-│ └── _webbench_<project>/ Web-Bench only: the evaluator's log, config and report
-└── index/ aggregate.py output: all_rows.csv, summary_by_cell.csv
-```
-
-The run-dir name is `<UTC>__<index>__<agent>__<instance>__<arm>__s<seed>__<mode>`:
-
-* **the UTC stamp comes first**, so every run dir is unique and the tree sorts
- chronologically. This is the part that matters operationally — **re-running a cell
- archives the previous attempt beside the new one instead of overwriting its transcript.**
- A trace cannot be reproduced after the fact, so losing one to a re-run loses it for good.
-* **the stream index** (`000`, `001`, …) keeps stream order explicit — which is essential
- for a sequentially dependent Web-Bench stream — and breaks ties when two tasks land in
- the same second (an unreached Web-Bench task costs no wall-clock at all).
-* **`<mode>`** stays in the name because `aggregate.py` recovers it from there.
-
-Because re-runs accumulate, `aggregate.py` reports **one row per (arm, cell, instance),
-taken from the newest attempt**, and prints `superseded runs skipped: N` when it passed over
-older ones. So the CSVs always describe the latest run of each task while the earlier traces
-stay on disk. To retire a bad run rather than supersede it, move its dir under
-`<tree>/provenance/` — the aggregator only walks the arm dirs.
-
-**One interpretation rule before you read any Web-Bench numbers.** Its streams are
-sequentially dependent, so the evaluator stops a project at the first task that fails every
-attempt; the driver still asks for the tasks after it, and a correct harness returns those as
-unreached with zero tokens. They are **not** cheap failures — exclude them from any per-task
-cost mean.
-
----
-
-## Troubleshooting — symptom → cause
-
-| Symptom | Cause |
-|---|---|
-| `ModuleNotFoundError: No module named 'bs4'` at grading | SWE-bench grader not installed into the driver's interpreter (Step 4) |
-| Rows look plausible but resolve follows a fixed pattern | `RUNNER=stub`; check the launch banner (Step 4) |
-| Every Web-Bench test fails, app never rendered | non-canonical path — `readlink -f` your roots (Step 2) |
-| `Executable doesn't exist at .../chromium_headless_shell-<n>` | Playwright browser does not match the version the projects pin (Step 5) |
-| "the evaluator is not built" / no `dist/` | `rush install` ran but `rush build` did not (Step 5) |
-| A whole project's tests fail that passed before | a build/seed step was skipped, or a stale database file was left behind (Step 5) |
-| Codex 401s despite a valid key | a regional OpenAI key is hitting the global endpoint; set `OPENAI_BASE_URL` (Step 3) |
-| `pricing: no weight entry for billed model …` | the billed model id is not in `pricing.MODEL_WEIGHTS`; add it rather than letting it be mispriced |
-| Two runs differ in cost at equal resolve | `TE_EFFORT_LEVEL` differs between them (Step 3) |
diff --git a/experiments/requirements.txt b/experiments/requirements.txt
index 830576c..e10a87c 100644
--- a/experiments/requirements.txt
+++ b/experiments/requirements.txt
@@ -8,7 +8,7 @@
# pip install -e . # then install the package itself (editable)
#
# NOT included on purpose (these belong to the EXTERNAL harness, Layer 2 — see
-# docs/ENVIRONMENT.md and docs/BENCHMARKS.md): Docker, the sealed agent CLIs, and the
+# README.md): Docker, the sealed agent CLIs, and the
# provisioning-only tools (git, Node/npm, the HuggingFace `datasets` package).
pytest>=7.0 # offline test suite (no Docker, no datasets)
diff --git a/experiments/scripts/README.md b/experiments/scripts/README.md
deleted file mode 100644
index 1f56851..0000000
--- a/experiments/scripts/README.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# scripts/ — reproduction pipeline
-
-The scripts here plan, drive, aggregate and compare the experiment arms. The results trees
-they write are **outside the repository and regenerated per run**. Dataset, Docker-image,
-and results paths below are **placeholders**: set the environment variables to point at
-your own runs. The run book is [`../docs/RUNNING.md`](../docs/RUNNING.md).
-
-## The end-to-end chain
-
-```
- build a task stream run each arm aggregate compare
- ───────────────────── ─────────────────────── ───────────────── ──────────────
- <your stream builder> ──▶ run_experiment.py ──▶ aggregate.py ──▶ compare_arms.py
- (chronological task list) (facade + AgentRunner; row.json ─▶ paired per-instance
- Docker/CLI harness: te_harness/) all_rows.csv + cost and resolve
- │ summary_by_cell.csv
- ▼
- _streams/*.jsonl ──▶ summarize_stream.py (amortized cost curve)
-```
-
-### 0. Launchers — `launch/` (reproduce the main experiments)
-
-`run_experiment.py` is the one-arm driver that maps each **proven arm** to an exact
-`EconomizerConfig` and drives the facade per task (see [`launch/README.md`](launch/README.md)
-for the full arm→flags table). The `launch/*.sh` scripts wrap it into lanes and A/Bs:
-
-```bash
-# Claude/Copilot tri-mechanism A/B on a domain (baseline vs trimech), then aggregate:
-AGENT=claude DOMAIN=swebench ARM=trimech REPOS="pydata/xarray" SEEDS="0 1 2" \
- RUNNER=te_harness.swebench:make_runner bash scripts/launch/trimech_ab.sh
-# Codex-native A/B (codex-untool | codex-spiral | codex-inject | codex-trimech | ...):
-ARM=codex-untool RUNNER=te_harness.swebench:make_runner bash scripts/launch/codex_ab.sh
-# Offline wiring check (StubRunner; writes only to a temp dir, cleans up):
-bash scripts/launch/smoke_test.sh
-```
-
-The task-execution harness is selected with `RUNNER=module:factory`: this repo's own is
-[`te_harness/`](../te_harness), and `RUNNER=stub` runs a no-agent stand-in for wiring checks
-only.
-
-### 1. Run each arm
-
-Task execution — launching a sealed agent (Claude Code / Copilot CLI / Codex) inside its
-Docker image, applying the economizer's per-task decisions, and grading against the gold
-patch — lives **below the `te_bench.runner.AgentRunner` interface**, in
-[`te_harness/`](../te_harness) (details: [`../docs/HARNESS.md`](../docs/HARNESS.md)). It is a
-sibling package, never imported from the core and not shipped in the wheel, so the core stays
-free of Docker and CLI dependencies.
-
-Bringing your own is a supported path, not a fallback: pass `--runner module:factory` for a
-zero-arg factory returning an `AgentRunner` that:
-
-- builds an `Economizer` per repo stream (`te_bench.facade.Economizer`);
-- per task calls `injection_prefix` → `build_tools` → `run_kwargs`, runs the agent with
- those decisions, then `after_task`;
-- writes one `row.json` per task-run under `<RESULTS>/<arm>/<repo>_s<seed>/<run>/` and a
- per-task `transcript.jsonl` the mechanisms read;
-- optionally appends each task's row to `<RESULTS>/<arm>/_streams/<repo>__<mode>__<ts>.jsonl`.
-
-Placeholders to set for your harness (see [`../docs/BENCHMARKS.md`](../docs/BENCHMARKS.md)
-for the full recipe and the driver-task-list vs. dataset-root distinction):
-
-| Placeholder | What it is |
-|---|---|
-| `TOKENECONOMIZER_SWEBENCH_TASKS` | JSON list of `{instance_id, problem_statement, repo}` (SWE-bench; driver task list **and** adapter source) |
-| `TOKENECONOMIZER_WEBBENCH_TASKS` / `_CREDDATA_TASKS` / `_REPOSVUL_TASKS` | driver task-list JSON **file** for those domains (not a dir) |
-| `TOKENECONOMIZER_WEBBENCH_PROJECTS` | Web-Bench `projects/` tree (adapter dataset root) |
-| `TOKENECONOMIZER_CREDDATA_ROOT` / `_REPOSVUL_ROOT` / `_CYBERGYM_SUITE` | dataset roots for those adapters |
-| `<DOCKER_IMAGE>` | era-pinned benchmark image (`te_harness.swebench.image_for`, or your runner) |
-| `TOKENECONOMIZER_RESULTS` | root of the results trees the aggregator reads |
-
-The arm catalog, per agent and domain, is in [`../docs/RUNNING.md`](../docs/RUNNING.md).
-
-### 2. Aggregate — `aggregate.py`
-
-Run dirs are timestamped (`<UTC>__<index>__…`), so re-running a cell adds a run dir rather
-than overwriting one. The aggregator therefore keeps **one row per (arm, cell, instance),
-from the newest attempt**, and prints `superseded runs skipped: N` when older attempts were
-passed over — they stay on disk. Move a run under `provenance/` to retire it entirely; only
-the arm dirs are walked.
-
-```
-python scripts/aggregate.py "$TOKENECONOMIZER_RESULTS" [--arms baseline trimech ...]
-```
-
-Walks `<root>/<arm>/<repo>_s<seed>/**/row.json` → writes `<root>/index/all_rows.csv`
-(one row per task-run) and `summary_by_cell.csv` (one row per arm×repo×seed). Cost is the
-honest cache-aware basis `pricing.effective_tokens(row) + ledger.overhead(row)` (vendored).
-
-### 3. Amortized curve — `summarize_stream.py`
-
-```
-python scripts/summarize_stream.py "$TOKENECONOMIZER_RESULTS"/<arm>/_streams/*.jsonl
-python scripts/summarize_stream.py --curve run.jsonl # per-position amortized curve
-```
-
-Folds each task's execution cost + mechanism overhead into one amortized-per-task number,
-cache-aware by default (`--raw` for legacy full-weight `tokens_total`).
-
-### 4. Compare arms — `compare_arms.py`
-
-```
-python scripts/compare_arms.py --baseline "$TOKENECONOMIZER_RESULTS"/<tree>/baseline/<cell> \
- --arm "$TOKENECONOMIZER_RESULTS"/<tree>/<arm>/<cell>
-```
-
-Pairs the two cells on instance id (a task missing from either side is reported and
-excluded) and reports the pooled mean, the median, the paired per-task delta and resolve
-counts, on the same cache-aware basis with each arm's mechanism spend charged to it.
diff --git a/experiments/scripts/aggregate.py b/experiments/scripts/aggregate.py
index aee2ae7..5a6471a 100644
--- a/experiments/scripts/aggregate.py
+++ b/experiments/scripts/aggregate.py
@@ -182,7 +182,7 @@ def vendor_usd(d):
# Agents that never report a per-task dollar figure at all: Copilot meters premium
# requests and Codex bills a subscription, so a null `cost_usd_vendor` on those lanes is
-# the documented normal case (docs/COPILOT.md), not a defect. Matched on the agent prefix,
+# the normal case, not a defect. Matched on the agent prefix,
# so a suffixed label is covered without a new entry.
AGENTS_WITHOUT_VENDOR_USD = ("copilot", "codex")
diff --git a/experiments/scripts/export_swebench_tasks.py b/experiments/scripts/export_swebench_tasks.py
new file mode 100644
index 0000000..f937f7b
--- /dev/null
+++ b/experiments/scripts/export_swebench_tasks.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python3
+"""Write the SWE-bench files the harness reads, for the 277 evaluated tasks.
+
+ swebench_tasks.json {instance_id, repo, problem_statement} per task: the driver's task
+ list ($TOKENECONOMIZER_SWEBENCH_TASKS)
+ swebench_grading.json instance_id -> the fields the official grader needs
+ ($TE_SWEBENCH_GRADING)
+ image_tags.txt the Docker image of each task, one per line, to `docker pull`
+
+The ids come from `te_bench.workloads.runnable_instances("swebench")`. Most are in
+SWE-bench_Verified; the rest exist only in the full SWE-bench test split, so both are read.
+Needs the `datasets` package, which the SWE-bench grader installs.
+
+ python scripts/export_swebench_tasks.py --out-dir "$DATA/swebench"
+"""
+import argparse
+import json
+import os
+import sys
+
+_EXPERIMENTS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path[:0] = [_EXPERIMENTS, os.path.dirname(_EXPERIMENTS)] # te_bench; the core at the root
+
+from te_bench import workloads # noqa: E402
+
+SPLITS = ("princeton-nlp/SWE-bench_Verified", "princeton-nlp/SWE-bench")
+GRADING_FIELDS = ("repo", "base_commit", "environment_setup_commit", "version", "test_patch",
+ "patch", "FAIL_TO_PASS", "PASS_TO_PASS")
+
+
+def build(rows_by_split, wanted):
+ """(tasks, grading) for the `wanted` ids, in stream order; Verified rows win."""
+ found = {}
+ for rows in rows_by_split:
+ for r in rows:
+ if r["instance_id"] in wanted:
+ found.setdefault(r["instance_id"], r)
+ order = [i for ids in workloads.runnable_instances("swebench").values() for i in ids]
+ tasks = [{"instance_id": i, "repo": found[i]["repo"],
+ "problem_statement": found[i]["problem_statement"]} for i in order if i in found]
+ grading = {i: {k: found[i][k] for k in GRADING_FIELDS} for i in order if i in found}
+ return tasks, grading
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--out-dir", required=True, help="where to write the three files")
+ args = ap.parse_args()
+
+ from datasets import load_dataset
+ wanted = {i for ids in workloads.runnable_instances("swebench").values() for i in ids}
+ tasks, grading = build((load_dataset(s, split="test") for s in SPLITS), wanted)
+ missing = sorted(wanted - set(grading))
+ if missing:
+ sys.exit(f"{len(missing)} evaluated ids are in neither split: {missing[:5]} ...")
+
+ os.makedirs(args.out_dir, exist_ok=True)
+ with open(os.path.join(args.out_dir, "swebench_tasks.json"), "w", encoding="utf-8") as fh:
+ json.dump(tasks, fh)
+ with open(os.path.join(args.out_dir, "swebench_grading.json"), "w", encoding="utf-8") as fh:
+ json.dump(grading, fh)
+ with open(os.path.join(args.out_dir, "image_tags.txt"), "w", encoding="utf-8") as fh:
+ fh.writelines(workloads.swebench_image_tag(t["instance_id"]) + "\n" for t in tasks)
+ print(f"wrote {len(tasks)} tasks, their grading fields and image tags to {args.out_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/experiments/scripts/launch/README.md b/experiments/scripts/launch/README.md
deleted file mode 100644
index 20e2220..0000000
--- a/experiments/scripts/launch/README.md
+++ /dev/null
@@ -1,177 +0,0 @@
-# scripts/launch/ — reproducible experiment launchers
-
-These scripts run the **main experiments**: a whole lane (`main_sweep.sh`, `full_sweep.sh`)
-or an A/B (baseline vs. an economized arm, `trimech_ab.sh`, `codex_ab.sh`) over a set of repos
-and seeds via [`../run_experiment.py`](../run_experiment.py), then aggregate the results into
-the index CSVs `compare_arms.py` reads. `run_experiment.py` is the single source of truth
-mapping each arm to an exact `EconomizerConfig`. The run book, with the arm catalog and one
-command per lane, is [`../../docs/RUNNING.md`](../../docs/RUNNING.md).
-
-## The harness seam (why you must supply a runner)
-
-Task execution — launching a sealed agent (Claude Code / Copilot CLI / Codex) inside its
-Docker image, applying the economizer's per-task decisions, and grading against the gold
-patch — lives **below `te_bench.runner.AgentRunner`**, in
-[`../../te_harness`](../../te_harness) (details: [`../../docs/HARNESS.md`](../../docs/HARNESS.md)).
-Select it per launch; no `PYTHONPATH` is needed, since the driver puts `experiments/` and
-the repository root (the shared core) on `sys.path` itself:
-
-```
-RUNNER=te_harness.swebench:make_runner # SWE-bench
-RUNNER=te_harness.webbench:make_runner # Web-Bench
-RUNNER=your_package.harness:make_runner # or your own: any zero-arg callable -> AgentRunner
-```
-
-`RUNNER=stub` (the default) selects the built-in offline `StubRunner`: it runs **no agent**,
-writes a synthetic transcript, and returns a fixed cache-heavy row. It exists only to
-exercise the wiring end-to-end (facade → aggregate) with no Docker, no datasets,
-and no LLM — its numbers are **not** a benchmark. `smoke_test.sh` uses it.
-
-## Arm → exact configuration
-
-| Arm | Original flags | Applies to |
-|---|---|---|
-| `baseline` | *(none)* | all — native cost basis |
-| `trimech` | `--mode manual4 --untool-evidence 3 --untool-judge --spiral-guard --spiral-judge --spiral-nudge` | Claude / Copilot |
-| `trimech-web` | `trimech` + `--spiral-nudge-llm --spiral-frozen-envelope 30` | Claude / Copilot on short Web-Bench streams |
-| `codex-untool` | `--codex-recent-adaptive-untool-v7` | Codex |
-| `codex-spiral` | `--codex-spiral-resume`, the **defensive** profile | Codex |
-| `codex-inject` | `--mode manual4` on the composed `envfacts+distiller` profile (**paid**) | Codex |
-| `codex-trimech` | `codex-inject` + `codex-untool` + `codex-spiral` — all three (**paid**) | Codex |
-| `codex-trimech-rtk` | `codex-trimech` + rtk (instruction mode; row carries `rtk_compliance`) | Codex |
-| `codex-trimech-repomap` | `codex-trimech` + aider's repo map as the project `AGENTS.md` (SWE-bench only; row carries `map_ok`) | Codex |
-
-`rtk`, `repomap` and `serena` all run on the Codex lane: rtk in its instruction mode, serena
-as a `[mcp_servers.serena]` block in the per-task `config.toml` (rows carry `serena_tool_calls`).
-
-The Codex arms run on **both** domains: `codex_ab.sh` takes `DOMAIN=swebench` (default) or
-`DOMAIN=webbench`, and refuses a `RUNNER` that does not match it.
-
-## Detached by default
-
-Both launchers **run in the background by default**. A real sweep is hours of Docker and
-paid agent time; a closed laptop or a dropped ssh session should not cost you the run. The
-launcher validates its config and credentials first, then re-execs itself under `setsid`
-and returns your terminal:
-
-```
-[detach] trimech_ab__claude_swebench_trimech started in the background (DETACH=0 to run in the foreground)
-[detach] log: /data/te_results/logs/trimech_ab__claude_swebench_trimech__20260814-144811.log
-[detach] follow: tail -f /data/te_results/logs/trimech_ab__claude_swebench_trimech__20260814-144811.log
-[detach] stop: kill -TERM -$(cat /data/te_results/logs/trimech_ab__claude_swebench_trimech__20260814-144811.pid)
-```
-
-Because the run gets its own session, it has no controlling terminal and survives SIGHUP.
-Everything it spawns — driver, `docker exec`, the agent — shares one process group, so the
-`kill -TERM -<pid>` above (note the leading `-`: that is the *group*) stops the whole tree.
-The harness also traps TERM/INT/HUP and removes the task container it is holding, since
-containers live outside that process group and would otherwise keep running — and keep
-billing. Logs and pidfiles land under `$TOKENECONOMIZER_RESULTS/logs/`; override with
-`TE_LOG=/path/run.log`.
-
-`DETACH=0` runs in the foreground (streaming to your terminal) — the right choice for a
-quick `LIMIT=1` check or when driving the launcher from another script. `smoke_test.sh` is
-always foreground; it takes seconds and asserts its own result.
-
-## Credentials (`.env`)
-
-Real (non-stub) runs drive each agent CLI on its own native authentication. Copy the
-tracked template and fill it in — `.env` is git-ignored:
-
-```bash
-cp .env.example .env # then set the key for the agent you run
-```
-
-Both launchers source [`_env.sh`](_env.sh) and `run_experiment.py` calls
-[`../_env.py`](../_env.py)`.load_env()`, so the file is picked up automatically. Format is
-plain `KEY=value` (`#` comments, optional `export`, no `$VAR` interpolation); **variables
-already exported in your shell win over the file**, and `KEY=` counts as unset. Point at a
-different file with `TOKENECONOMIZER_ENV_FILE=/path/to/other.env`.
-
-| Agent | Credential |
-|---|---|
-| Claude Code | `ANTHROPIC_API_KEY`. `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` are ignored: the launcher says so once and unsets them. |
-| Codex | `OPENAI_API_KEY`. `OPENAI_BASE_URL` only for a region-scoped key (e.g. `https://us.api.openai.com/v1`); any non-OpenAI host is refused. |
-| Copilot CLI | the GitHub subscription (`COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, or `copilot` then `/login`), or Copilot's own BYOK (`COPILOT_PROVIDER_*`, see [`../../docs/COPILOT.md`](../../docs/COPILOT.md)). |
-
-Before each real run the launcher checks the credential for its agent and fails fast when it
-is missing.
-
-## Placeholders (env vars)
-
-> **Provisioning each benchmark** — what image to pull, dataset to fetch, and the exact
-> commands — is in [`../../docs/BENCHMARKS.md`](../../docs/BENCHMARKS.md). It explains the two
-> path families every non-SWE-bench domain needs: a **`_TASKS` JSON file** (the driver's task
-> list) *and* a **`_ROOT`/`_PROJECTS`/`_SUITE` dataset root** (the adapter's data). For
-> SWE-bench those are the same file.
-
-The launchers themselves read only these:
-
-| Env var | What it is |
-|---|---|
-| `TOKENECONOMIZER_SWEBENCH_TASKS` | JSON list of `{instance_id, problem_statement, repo}` (SWE-bench; also the adapter source) |
-| `TOKENECONOMIZER_WEBBENCH_TASKS` / `_CREDDATA_TASKS` / `_REPOSVUL_TASKS` | driver task-list JSON for those domains (a **file**, not a dir) |
-| `TOKENECONOMIZER_RESULTS` | root of the results trees (outside the repository) the aggregator reads |
-| `RUNNER` | `stub`, `te_harness.swebench:make_runner` / `.webbench:make_runner`, or any `module:factory` |
-| `WORKLOAD` | workload manifest (default `workloads/$DOMAIN.json`); `none` disables filtering |
-| `PYTHON` | interpreter to use (default `python3`) |
-
-**Workload pinning.** Both launchers default `WORKLOAD` to the committed manifest in
-[`../../workloads/`](../../workloads/) and pass it through as `run_experiment.py --workload`,
-which filters `TASKS_FILE` to exactly the evaluated instances for the `--repo` group. Your
-task file may therefore hold a superset (e.g. all of SWE-bench_Verified). This also avoids the
-legacy `--repo` prefix match, which silently falls back to the *entire* task list whenever the
-repo's org differs from its name — `pydata/xarray` included. Set `WORKLOAD=none` to opt out.
-
-The **dataset roots** (`_WEBBENCH_PROJECTS`, `_CREDDATA_ROOT`, `_REPOSVUL_ROOT`,
-`_CYBERGYM_SUITE`) are read by the adapters + your harness, not by these scripts — export them
-per [`../../docs/BENCHMARKS.md`](../../docs/BENCHMARKS.md) before launching.
-
-## Examples
-
-**Claude tri-mechanism on SWE-bench, three seeds:**
-```bash
-export TOKENECONOMIZER_SWEBENCH_TASKS=/data/swebench_verified.json
-export TOKENECONOMIZER_RESULTS=/data/te_results
-AGENT=claude DOMAIN=swebench ARM=trimech \
- REPOS="pydata/xarray django/django sympy/sympy scikit-learn/scikit-learn" \
- SEEDS="0 1 2" RUNNER=te_harness.swebench:make_runner \
- bash scripts/launch/trimech_ab.sh
-```
-
-**Tri-mechanism on Web-Bench (short streams → `trimech-web`):**
-```bash
-AGENT=claude DOMAIN=webbench ARM=trimech-web SEEDS="0" \
- REPOS="calculator expressjs react zustand table" \
- RUNNER=te_harness.webbench:make_runner bash scripts/launch/trimech_ab.sh
-```
-
-Each `REPOS` value is a Web-Bench **project** — one stream of 20–21 sequentially dependent
-tasks (`init`, `task-1` … `task-20`). Two Web-Bench-specific notes:
-
-* Web-Bench's evaluator owns the task loop, so a Web-Bench runner is started once per stream
- through the optional `begin_stream(tasks, ...)` / `end_stream()` hooks on `AgentRunner`
- (see `experiments/te_bench/runner.py`). Runners that do not define them are called as usual.
-* Because the tasks are sequentially dependent and graded cumulatively, the evaluator stops
- the project at the first task that fails every attempt. The driver still asks for the rest;
- a runner should return those as unreached (`stream_broken` / `unreached`, zero tokens) so
- the cost aggregation does not read them as cheap failures.
-
-**Codex untooling A/B:**
-```bash
-ARM=codex-untool REPOS="pydata/xarray sympy/sympy" SEEDS="0" \
- RUNNER=te_harness.swebench:make_runner bash scripts/launch/codex_ab.sh
-```
-
-**Codex spiral A/B:**
-```bash
-ARM=codex-spiral REPOS="pydata/xarray" SEEDS="0" \
- RUNNER=te_harness.swebench:make_runner bash scripts/launch/codex_ab.sh
-```
-
-## Offline smoke test
-
-`bash scripts/launch/smoke_test.sh` runs **every** arm with the StubRunner on a tiny
-synthetic task set, aggregates, asserts the CSVs are produced, and **deletes everything it
-created** (it writes only under a temp dir). Use it to confirm the driver + facade +
-aggregator wiring after any change. See `../README.md` for the full reproduction chain.
diff --git a/experiments/scripts/launch/_env.sh b/experiments/scripts/launch/_env.sh
index 5301e9a..477b9b3 100644
--- a/experiments/scripts/launch/_env.sh
+++ b/experiments/scripts/launch/_env.sh
@@ -34,8 +34,8 @@ te_load_env() {
# te_dryrun_skips_billed <what> — true when this is a DRYRUN, so a BILLED probe must not run.
#
-# A dry run is the gesture the run book teaches for costing a lane before spending anything
-# (docs/RUNNING.md section 2), so a probe that BILLS during one contradicts the whole
+# A dry run is how a lane is costed before spending anything, so a probe that BILLS during
+# one contradicts the whole
# point: DRYRUN=1 on a Copilot lane used to spend up to three premium requests and ~240 s
# before printing "nothing was run".
te_dryrun_skips_billed() {
@@ -125,7 +125,7 @@ te_model_tag() {
# nothing when the id has only one spelling.
#
# claude-opus-4-8 -> claude-opus-4.8 claude-haiku-4.5 -> claude-haiku-4-5
-# claude-opus-5 -> (empty) claude-sonnet-5 -> (empty)
+# claude-sonnet-5 -> (empty)
#
# Two catalogs serve the same model under two spellings: the Copilot CLI's own list uses
# a DOT (`claude-opus-4.8`, measured healthy on 63 stored subscription rows), while the
@@ -149,8 +149,8 @@ te_model_alt_spelling() {
# native catalog on a subscription (`claude-opus-4.8`), so a copilot lane gets the dotted
# form there -- and only there: under Copilot BYOK the CLI speaks the Anthropic wire API,
# which takes the dash. Any other agent is normalised TO the dash, so a dotted id typed from
-# an older doc cannot 404 once per task. Ids with a single spelling (`claude-opus-5`,
-# `claude-sonnet-5`) pass through untouched, as does anything that is not a versioned
+# an older doc cannot 404 once per task. Ids with a single spelling (`claude-sonnet-5`)
+# pass through untouched, as does anything that is not a versioned
# Claude id. te_check_copilot_model still VERIFIES the result against the CLI and switches
# back if a vendor rotates a catalog, so this is a default, not a bet.
te_model_for_agent() {
@@ -274,7 +274,7 @@ te_copilot_refused_die() {
echo " turns=1 / eff_tok=0 rows." >&2
echo " Wait for the quota to reset, or run the Copilot CLI on your own provider:" >&2
echo " COPILOT_PROVIDER_TYPE=anthropic COPILOT_PROVIDER_BASE_URL=https://api.anthropic.com \\" >&2
- echo " COPILOT_PROVIDER_API_KEY=... (docs/COPILOT.md, BYOK)" >&2
+ echo " COPILOT_PROVIDER_API_KEY=... (see README.md)" >&2
exit 2
}
@@ -289,7 +289,7 @@ te_copilot_refused_die() {
# ~/.copilot/config.json only when a copilot process RUNS on the host, so on a box that has
# been idle a while the FIRST invocation can report "No authentication information found"
# and warm the token as a side effect. The probe therefore doubles as the warm-up -- and
-# for a long unattended sweep you still want the keepalive loop (docs/COPILOT.md).
+# for a long unattended sweep on the subscription, keep the token warm (or use BYOK).
te_check_copilot_auth() {
local bin="${COPILOT_HOST_BIN:-$HOME/.local/bin/copilot}" out ok=0
command -v "$bin" >/dev/null 2>&1 || [[ -x "$bin" ]] || bin="$(command -v copilot || true)"
@@ -409,11 +409,11 @@ te_check_copilot_model() {
echo "!! copilot model '$model' is not served by the BYOK provider at $COPILOT_PROVIDER_BASE_URL." >&2
echo " $(printf '%s' "$out" | grep -i 'not found on provider' | head -1)" >&2
echo " Under COPILOT_PROVIDER_TYPE=anthropic the provider takes Anthropic's own ids" >&2
- echo " (claude-opus-4-8, claude-sonnet-5, claude-opus-5); pin one it serves." >&2
+ echo " (claude-sonnet-5, claude-opus-4-8); pin one it serves." >&2
else
echo "!! copilot model '$model' is not available on this subscription." >&2
echo " pick one it serves, or set COPILOT_MODEL=auto (which cannot apply an" >&2
- echo " effort level -- see docs/COPILOT.md step 2)." >&2
+ echo " effort level)." >&2
fi
exit 2
fi
diff --git a/experiments/scripts/launch/codex_ab.sh b/experiments/scripts/launch/codex_ab.sh
index fa3aa8e..3598bb0 100755
--- a/experiments/scripts/launch/codex_ab.sh
+++ b/experiments/scripts/launch/codex_ab.sh
@@ -2,7 +2,7 @@
# Reproduce a Codex-native A/B: a BASELINE arm and one of the two independently-effective
# Codex mechanisms (or their combo), then aggregate into the index CSVs compare_arms.py reads.
#
-# Exact arm configurations (the full catalog is in docs/RUNNING.md section 5):
+# Exact arm configurations (README.md lists the arms the paper ran):
# baseline : native Codex cost basis, no economizer
# codex-untool : --codex-recent-adaptive-untool-v7 (evidence-gated capability untooling;
# deferred_wait is CORE and never demoted)
@@ -48,11 +48,12 @@
# an unprivileged user+mount namespace rather than by a hook the CLI ignores; the
# runner probes that at construction and refuses to pretend otherwise. Selects the
# tasks file, the workload manifest and the RUNNER default.
+# ARMS space-separated arm list: run exactly these, in one lane (ARM/BASELINE ignored)
# BASELINE 1 = run baseline too (paired A/B, default); 0 = run only $ARM against a
# baseline already stored elsewhere; only = run ONLY the baseline arm (a fresh
# baseline lane to pair with an arm running concurrently in another lane)
-# REPOS space-separated repo slugs (default "pydata/xarray")
-# SEEDS space-separated seeds (default "0")
+# REPOS space-separated repo slugs / projects (default: every group in WORKLOAD)
+# SEEDS space-separated seeds (default "0 1 2")
# LIMIT cap tasks per (repo,seed), 0 = all (default 0)
# RUNNER 'stub' or 'module:factory' (default stub)
# TASKS_FILE task-spec JSON (default TOKENECONOMIZER_SWEBENCH_TASKS)
@@ -97,22 +98,35 @@ te_load_env
# fleet cgroup cap below hold the aggregate.
export TE_SWEBENCH_MAX_CPUS="${TE_SWEBENCH_MAX_CPUS:-4}"
-ARM="${ARM:-codex-untool}"
-case "$ARM" in baseline|baseline-medium|baseline-low|repomap|rtk|serena|codex-untool|codex-spiral|codex-spiral-postgreen|codex-spiral-defensive|codex-combo|codex-trimech|codex-trimech-rtk|codex-trimech-repomap|codex-inject|codex-inject-untool|codex-inject-envfacts|codex-inject-distiller) ;; *)
- echo "ARM must be baseline | baseline-medium | baseline-low | repomap | rtk | serena | codex-untool | codex-spiral | codex-spiral-postgreen | codex-spiral-defensive | codex-combo | codex-trimech | codex-trimech-rtk | codex-trimech-repomap | codex-inject | codex-inject-untool | codex-inject-envfacts | codex-inject-distiller (got $ARM)"; exit 2 ;; esac
-# BASELINE=0 runs ONLY $ARM, for a lane whose baseline already exists in a stored tree
-# (compare with scripts/compare_arms.py). BASELINE=only runs ONLY the baseline arm, so a
-# fresh baseline and an arm can run as two concurrent lanes into the same tree. Default 1 =
-# the paired A/B this script is named for.
-BASELINE="${BASELINE:-1}"
-case "$BASELINE" in
- 0) ARMS_TO_RUN=("$ARM") ;;
- only) ARMS_TO_RUN=(baseline) ;;
- *) ARMS_TO_RUN=(baseline "$ARM") ;;
-esac
-LANE_TAG="$([[ "$BASELINE" == "only" ]] && echo baseline || echo "$ARM")"
-REPOS="${REPOS:-pydata/xarray}"
-SEEDS="${SEEDS:-0}"
+CODEX_ARMS="baseline baseline-medium baseline-low repomap rtk serena codex-untool codex-spiral \
+codex-spiral-postgreen codex-spiral-defensive codex-combo codex-trimech codex-trimech-rtk \
+codex-trimech-repomap codex-inject codex-inject-untool codex-inject-envfacts codex-inject-distiller"
+te_codex_arm() {
+ case " $CODEX_ARMS " in *" $1 "*) return 0 ;; esac
+ echo "!! unknown Codex arm '$1'; one of: $CODEX_ARMS" >&2; exit 2
+}
+if [[ -n "${ARMS:-}" ]]; then
+ # ARMS runs exactly the listed arms, one lane, like main_sweep.sh (BASELINE is ignored).
+ read -r -a ARMS_TO_RUN <<<"$ARMS"
+ for a in "${ARMS_TO_RUN[@]}"; do te_codex_arm "$a"; done
+ LANE_TAG="arms"
+else
+ ARM="${ARM:-codex-untool}"
+ te_codex_arm "$ARM"
+ # BASELINE=0 runs ONLY $ARM, for a lane whose baseline already exists in a stored tree
+ # (compare with scripts/compare_arms.py). BASELINE=only runs ONLY the baseline arm, so a
+ # fresh baseline and an arm can run as two concurrent lanes into the same tree. Default 1 =
+ # the paired A/B this script is named for.
+ BASELINE="${BASELINE:-1}"
+ case "$BASELINE" in
+ 0) ARMS_TO_RUN=("$ARM") ;;
+ only) ARMS_TO_RUN=(baseline) ;;
+ *) ARMS_TO_RUN=(baseline "$ARM") ;;
+ esac
+ LANE_TAG="$([[ "$BASELINE" == "only" ]] && echo baseline || echo "$ARM")"
+fi
+REPOS="${REPOS:-}"
+SEEDS="${SEEDS:-0 1 2}"
LIMIT="${LIMIT:-0}"
RUNNER="${RUNNER:-stub}"
SKIP_DONE="${SKIP_DONE:-1}"
@@ -155,13 +169,16 @@ if [[ "$WORKLOAD" != "none" ]]; then
fi
WORKLOAD_ARGS=(--workload "$WORKLOAD")
fi
+if [[ -z "$REPOS" ]]; then
+ [[ "$WORKLOAD" != "none" ]] || { echo "!! WORKLOAD=none needs an explicit REPOS" >&2; exit 2; }
+ REPOS="$("$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" --workload "$WORKLOAD" --format counts | cut -f1 | tr '\n' ' ')"
+fi
RESULTS_ROOT="${TOKENECONOMIZER_RESULTS:-$REPO_ROOT/results}"
# codex_<domain>_<model-tag>. The MODEL is part of the cost basis, so it belongs in the
# tree name -- otherwise two models' lanes share a tree and aggregate.py averages two bases.
MODEL_TAG="$(te_model_tag "$MODEL")"
DEST="$RESULTS_ROOT/$(te_tree_name "$AGENT" "$DOMAIN" "$MODEL_TAG")"
-mkdir -p "$DEST"
# DRYRUN=1 prints the cells and exits WITHOUT detaching -- before te_detach, so a dry run
# cannot hand back the terminal and then bill a full A/B in the background.
@@ -176,9 +193,11 @@ if [[ "${DRYRUN:-0}" == "1" ]]; then
exit 0
fi
+mkdir -p "$DEST"
+
# Detach by default: config is resolved and credentials are checked, so anything that
# fails from here on is a run-time failure that belongs in the log, not the terminal.
-te_detach "codex_ab__${LANE_TAG}" "$0" "$@"
+te_detach "codex_ab__${MODEL_TAG}_${DOMAIN}_${LANE_TAG}" "$0" "$@"
# One budget for every lane on the host, re-asserted here so a launch cannot inherit an
# uncapped cgroup from an earlier session. Idempotent; never fatal.
@@ -190,12 +209,10 @@ echo "[codex_ab] cpus: per-container ${TE_SWEBENCH_MAX_CPUS}, fleet ${TE_FLEET_C
echo "[codex_ab] tasks=$TASKS_FILE workload=$WORKLOAD"
echo "[codex_ab] skip_done=$SKIP_DONE on_fail=$ON_FAIL"
-# expected_rows <repo> -- the task count of that group, from the committed workload record.
-# Same source main_sweep.sh uses: the counts are per GROUP and carry no arm or agent, so
-# the Codex lane reads them unchanged.
+# expected_rows <repo> -- the task count of that group, from the workload manifest.
declare -A GROUP_N
while IFS=$'\t' read -r g n; do GROUP_N["$g"]="$n"; done < <(
- "$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" --format counts)
+ "$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" "${WORKLOAD_ARGS[@]}" --format counts)
# cell_rows <arm> <repo> <seed> -- how many row.json files that cell already holds.
cell_rows() {
@@ -237,9 +254,8 @@ for seed in $SEEDS; do
done
# Aggregate every arm PRESENT in the tree, not just this lane's: --arms limits the rewrite,
-# so passing it would drop the other arms' rows from the index the comparisons read. This
-# lane runs ONE arm per invocation (docs/RUNNING.md section 5), so passing it would
-# leave the index holding whichever arm was launched last.
+# so passing it would drop the other arms' rows from the index the comparisons read, and a
+# lane that ran one arm would leave the index holding only that arm.
echo "[codex_ab] aggregating -> $DEST/index/"
"$PY" "$HERE/../aggregate.py" "$DEST"
echo "[codex_ab] DONE in $(( (SECONDS - START) / 60 )) min: ran=$RAN skipped=$SKIPPED failed=${#FAILED[@]}"
diff --git a/experiments/scripts/launch/full_sweep.sh b/experiments/scripts/launch/full_sweep.sh
deleted file mode 100755
index dd2c779..0000000
--- a/experiments/scripts/launch/full_sweep.sh
+++ /dev/null
@@ -1,154 +0,0 @@
-#!/usr/bin/env bash
-# THE WHOLE SWEEP: every lane of the main experiment, end to end, for real.
-#
-# main_sweep.sh runs ONE lane -- one (agent, model, domain) -- and with ARMS unset it
-# already runs every arm of that lane. This driver is the layer above it: it crosses the
-# agents, the models and the domains and runs the lanes in a defined order, so the whole
-# matrix is one command instead of eight.
-#
-# default matrix = 2 agents x 2 models x 2 domains = 8 lanes
-# agents : claude (Claude Code) + copilot (Copilot CLI)
-# models : claude-opus-4-8 + claude-sonnet-5
-# domains: swebench + webbench
-# BOTH models run on BOTH harnesses -- that is the main sweep, not a choice between
-# them. Each (agent, model, domain) gets its own results tree, because the model is part
-# of the cost basis and two of them must never be averaged into one cell.
-#
-# THESE ARE 8 OF THE 12 REQUIRED LANES. claude-opus-5 runs 4 arms per domain on both
-# agents (baseline / baseline-medium / baseline-low / trimech, or trimech-web) and is
-# NOT optional -- see MODELS below and docs/RUNNING.md (the frontier lane). This script does not launch
-# them, so a green run here is not a finished experiment.
-# `sweep_plan.py --format matrix` prints the exact cell and task-run counts.
-#
-# RUN IT WITH DRYRUN=1 FIRST. A total dollar figure and a total wall-clock are deliberately
-# not quoted, because both would be one repo-dominated per-task mean multiplied by the whole
-# matrix. Budget from the PER-ARM runtime instead: time one arm on your host and multiply --
-# it is nearly the same for every arm in a domain.
-#
-# Usage:
-# DRYRUN=1 bash scripts/launch/full_sweep.sh # the plan and the cost, run nothing
-# bash scripts/launch/full_sweep.sh # the whole matrix, for real
-#
-# # one agent, one model, one domain -- still every arm and every seed of that lane
-# AGENTS=copilot MODELS=claude-opus-4-8 DOMAINS=swebench \
-# bash scripts/launch/full_sweep.sh
-#
-# # seed 0 only: a complete, publishable slice at 1/5 the bill
-# SEEDS=0 bash scripts/launch/full_sweep.sh
-#
-# Env:
-# AGENTS space-separated (default "claude copilot")
-# MODELS space-separated (default "claude-opus-4-8 claude-sonnet-5")
-# One spelling here for both agents; main_sweep.sh spells each lane's id the
-# way its backend serves it (the Copilot CLI's catalog says claude-opus-4.8,
-# the Anthropic API claude-opus-4-8) and both land in the same `_opus48` tree.
-# DOMAINS space-separated (default "swebench webbench")
-# SEEDS space-separated (default "0 1 2 3 4")
-# ARMS restrict the arms (default: every arm the domain defines)
-# REPOS restrict the repo groups (default: every group the domain defines)
-# NOTE: repo groups are domain-specific -- SWE-bench takes slugs
-# ("sympy/sympy"), Web-Bench takes project names ("zustand"). Set REPOS only
-# alongside a single DOMAIN, or one of the two lanes will plan zero cells.
-# LANES serial | parallel (default serial -- see the warning below)
-# DRYRUN 1 = print each lane's plan and cost, run nothing (default 0)
-# Everything else (SKIP_DONE, LIMIT, ON_FAIL, TE_*) is passed through to main_sweep.sh.
-#
-# LANES=serial is the default ON PURPOSE. Every SWE-bench task starts a container, every
-# Web-Bench stream starts dev servers and a Playwright browser, the Copilot lanes share ONE
-# subscription quota and the Claude lanes ONE API key's rate limit -- so lanes contend for
-# Docker, ports and rate limits long before they contend for CPU, and a throttled task
-# shows up as a bad ROW (usage_incomplete), not as a launcher error.
-# Raise it deliberately, one lane at a time, watching n_usage_incomplete.
-#
-# Resuming is free: SKIP_DONE=1 is main_sweep.sh's default, so re-running this command
-# after an interruption fills only the cells that are missing.
-set -uo pipefail
-
-HERE="$(cd "$(dirname "$0")" && pwd)"
-. "$HERE/_env.sh"
-REPO_ROOT="$(cd "$HERE/../.." && pwd)" te_load_env
-
-AGENTS="${AGENTS:-claude copilot}"
-# The main sweep's two models -- sweep_plan.SWEEP_MODELS is the same pair, and
-# tests/test_sweep_arms.py holds them together.
-#
-# claude-opus-5 is deliberately absent, which does NOT mean optional: its 4 lanes are
-# required (baseline / baseline-medium / baseline-low / trimech, both domains, both
-# agents -- docs/RUNNING.md) and are launched by their own main_sweep.sh calls. So this
-# script covers 8 of the 12 required lanes; a green run here is not a finished
-# experiment. Adding the id here would plan a third FULL 21-arm lane instead.
-MODELS="${MODELS:-claude-opus-4-8 claude-sonnet-5}"
-DOMAINS="${DOMAINS:-swebench webbench}"
-SEEDS="${SEEDS:-0 1 2 3 4}"
-LANES="${LANES:-serial}"
-DRYRUN="${DRYRUN:-0}"
-
-runner_for() {
- case "$1" in
- swebench) echo "te_harness.swebench:make_runner" ;;
- webbench) echo "te_harness.webbench:make_runner" ;;
- *) echo "!! unknown domain '$1'" >&2; exit 2 ;;
- esac
-}
-
-# The whole bill, once, before anything runs -- and before any credential is needed.
-echo "[full_sweep] agents='$AGENTS' models='$MODELS' domains='$DOMAINS' seeds='$SEEDS'"
-echo "[full_sweep] lanes=$LANES dryrun=$DRYRUN"
-
-# `sweep_plan --format matrix` always costs the FULL cross of its model list, so printing it
-# under a narrowed scope would quote tens of thousands of dollars for a twelve-cell run.
-# Show it only when nothing is narrowed; otherwise let each lane print its own estimate,
-# which main_sweep.sh already does WITH --limit applied.
-NARROWED=""
-[[ "$DOMAINS" == "swebench webbench" ]] || NARROWED="domains"
-[[ "$SEEDS" == "0 1 2 3 4" ]] || NARROWED="$NARROWED seeds"
-[[ "$AGENTS" == "claude copilot" ]] || NARROWED="$NARROWED agents"
-[[ -z "${ARMS:-}" ]] || NARROWED="$NARROWED arms"
-[[ -z "${REPOS:-}" ]] || NARROWED="$NARROWED repos"
-[[ -z "${LIMIT:-}" || "${LIMIT:-0}" == "0" ]] || NARROWED="$NARROWED limit"
-if [[ -z "$NARROWED" ]]; then
- TE_SWEEP_MODELS="$MODELS" "${PYTHON:-python3}" "$HERE/../sweep_plan.py" --format matrix \
- 2>/dev/null | sed 's/^/[full_sweep] /' || true
-else
- echo "[full_sweep] scope narrowed ($NARROWED) -- the full-matrix estimate does not apply;"
- echo "[full_sweep] each lane prints its own costed plan below."
-fi
-echo
-
-LANE_N=0 FAILED=()
-for domain in $DOMAINS; do
- for model in $MODELS; do
- for agent in $AGENTS; do
- LANE_N=$((LANE_N + 1))
- tag="$agent/$model/$domain"
- echo "===== [full_sweep] lane $LANE_N: $tag ====="
- # DETACH=0: this driver owns the ordering, so each lane must run to completion in the
- # foreground. Detaching every lane would launch all eight at once and silently turn
- # LANES=serial into LANES=parallel.
- if AGENT="$agent" MODEL="$model" DOMAIN="$domain" SEEDS="$SEEDS" \
- RUNNER="$(runner_for "$domain")" DETACH=0 DRYRUN="$DRYRUN" \
- bash "$HERE/main_sweep.sh"; then
- echo "[full_sweep] lane $LANE_N OK: $tag"
- else
- rc=$?
- echo "[full_sweep] !! lane $LANE_N FAILED (rc=$rc): $tag" >&2
- FAILED+=("$tag")
- # A launch-time refusal (exit 2: dead quota, unserved model, missing key) applies to
- # every remaining lane on that credential, so stop rather than repeat it eight times.
- if [[ $rc -eq 2 ]]; then
- echo "[full_sweep] !! exit 2 is a launch refusal, not a task failure -- stopping." >&2
- echo "[full_sweep] !! fix the cause and re-run; SKIP_DONE=1 resumes what finished." >&2
- break 3
- fi
- fi
- done
- done
-done
-
-echo
-if ((${#FAILED[@]})); then
- echo "[full_sweep] DONE with ${#FAILED[@]} failed lane(s):"
- printf ' %s\n' "${FAILED[@]}"
- exit 1
-fi
-echo "[full_sweep] DONE: $LANE_N lane(s), no failures."
diff --git a/experiments/scripts/launch/main_sweep.sh b/experiments/scripts/launch/main_sweep.sh
index 747513b..0ceec82 100755
--- a/experiments/scripts/launch/main_sweep.sh
+++ b/experiments/scripts/launch/main_sweep.sh
@@ -29,20 +29,20 @@
# Billing: Claude Code on the Anthropic API (ANTHROPIC_API_KEY), the Copilot CLI on its
# GitHub subscription or Copilot's own BYOK (COPILOT_PROVIDER_*).
#
-# Usage (one lane; see docs/RUNNING.md for every lane):
-# AGENT=claude MODEL=claude-opus-5 DOMAIN=swebench \
+# Usage (one lane; README.md lists every lane of the paper):
+# AGENT=claude MODEL=claude-sonnet-5 DOMAIN=swebench \
# RUNNER=te_harness.swebench:make_runner \
# bash scripts/launch/main_sweep.sh
#
# Env:
# AGENT claude | copilot (default claude)
-# MODEL model id passed to the CLI and recorded (default claude-opus-5)
+# MODEL model id passed to the CLI and recorded (default claude-sonnet-5)
# It also picks the tree suffix via te_model_tag, so it is REQUIRED to be a
# pinned id: `auto`/`agent` gives no tag and no controlled cost basis.
# DOMAIN swebench | webbench (default swebench)
# ARMS space-separated arm list (default: the domain's SWEEP_ARMS)
# REPOS space-separated groups (default: every group in the workload record)
-# SEEDS space-separated seeds (default "0 1 2 3 4")
+# SEEDS space-separated seeds (default "0 1 2")
# LIMIT cap tasks per cell, 0 = all (default 0)
# RUNNER 'stub' or 'module:factory' (default stub -- SYNTHETIC, not a benchmark)
# SKIP_DONE 1 = skip a cell that already holds its full row count (default 1)
@@ -51,7 +51,9 @@
# ON_FAIL continue | abort (default continue: one bad cell must not
# take a 200-cell lane with it; the lane still exits nonzero and lists them)
# DETACH 1 = background (default), 0 = foreground
-# TASKS_FILE / WORKLOAD / TOKENECONOMIZER_RESULTS as in trimech_ab.sh
+# TASKS_FILE task-spec JSON (default: the domain's TOKENECONOMIZER_*_TASKS)
+# WORKLOAD workload manifest, or 'none' (default workloads/$DOMAIN.json)
+# TOKENECONOMIZER_RESULTS results root (default ./results)
set -uo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
@@ -63,14 +65,14 @@ PY="${PYTHON:-python3}"
te_load_env
AGENT="${AGENT:-claude}"
-MODEL="${MODEL:-claude-opus-5}"
+MODEL="${MODEL:-claude-sonnet-5}"
# One spelling in the docs, the backend's spelling on the wire: the Copilot CLI's own
# catalog lists the older Opus as `claude-opus-4.8` while the Anthropic API takes
# `claude-opus-4-8`. te_model_for_agent picks the served form (and says so); the Copilot
# probe below still verifies it. The tree tag folds both, so nothing forks.
MODEL="$(te_model_for_agent "$AGENT" "$MODEL")"
DOMAIN="${DOMAIN:-swebench}"
-SEEDS="${SEEDS:-0 1 2 3 4}"
+SEEDS="${SEEDS:-0 1 2}"
LIMIT="${LIMIT:-0}"
RUNNER="${RUNNER:-stub}"
SKIP_DONE="${SKIP_DONE:-1}"
@@ -94,7 +96,7 @@ MODEL_TAG="$(te_model_tag "$MODEL")"
if [[ -z "$MODEL_TAG" ]]; then
echo "!! MODEL='$MODEL' is a router directive, not a pinned model: the tree would carry" >&2
echo "!! no model tag and the effort arms could not pin effort. Pin an id (e.g." >&2
- echo "!! MODEL=claude-opus-5 or MODEL=claude-sonnet-5)." >&2
+ echo "!! MODEL=claude-sonnet-5 or MODEL=claude-opus-4-8)." >&2
exit 2
fi
@@ -127,7 +129,7 @@ DEST="$RESULTS_ROOT/$(te_tree_name "$AGENT" "$DOMAIN" "$MODEL_TAG")"
# Captured into a variable first, NOT piped into `mapfile < <(...)`: a process substitution
# discards the producer's exit status, so an unknown arm or an unreadable workload would
# come back as an empty plan and this lane would report a clean zero-cell success.
-if ! PLAN_RAW="$("$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" \
+if ! PLAN_RAW="$("$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" "${WORKLOAD_ARGS[@]}" \
"${ARM_ARGS[@]}" "${REPO_ARGS[@]}" --seeds $SEEDS --format cells)"; then
echo "!! could not plan the sweep (see the error above)" >&2
exit 2
@@ -145,8 +147,8 @@ echo "[main_sweep] dest=$DEST"
echo "[main_sweep] cells=${#PLAN[@]} seeds='$SEEDS' runner=$RUNNER skip_done=$SKIP_DONE"
# --limit must be forwarded or the estimate describes the FULL stream while the run is
# capped: a LIMIT=1 pilot printed "task-runs= 40 ... ~$14" for one task.
-"$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" "${ARM_ARGS[@]}" "${REPO_ARGS[@]}" \
- --seeds $SEEDS --limit "$LIMIT" --format estimate | sed 's/^/[main_sweep] /'
+"$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" "${WORKLOAD_ARGS[@]}" "${ARM_ARGS[@]}" \
+ "${REPO_ARGS[@]}" --seeds $SEEDS --limit "$LIMIT" --format estimate | sed 's/^/[main_sweep] /'
# Credentials preflight (and the loud synthetic-run warning when RUNNER=stub).
te_check_routing "$AGENT"
@@ -167,7 +169,7 @@ fi
# AFTER the preflights, so a dry run still refuses a missing credential. The BILLED probes
# skip themselves on a dry run (te_dryrun_skips_billed), and te_check_routing returns early
# on RUNNER=stub, so DRYRUN=1 on a fresh clone with nothing configured still costs nothing
-# and still works (docs/RUNNING.md section 2).
+# and still works.
if [[ "$DRYRUN" == "1" ]]; then
echo "[main_sweep] DRYRUN -- the cells this lane would run, in order:"
printf ' %s\n' "${PLAN[@]}"
@@ -181,10 +183,10 @@ mkdir -p "$DEST"
# here belongs in a log rather than a terminal a laptop lid will close on.
te_detach "main_sweep__${AGENT}_${MODEL_TAG}_${DOMAIN}" "$0" "$@"
-# expected_rows <repo> — the task count of that group, from the committed workload record.
+# expected_rows <repo> -- the task count of that group, from the workload manifest.
declare -A GROUP_N
while IFS=$'\t' read -r g n; do GROUP_N["$g"]="$n"; done < <(
- "$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" --format counts)
+ "$PY" "$HERE/../sweep_plan.py" --domain "$DOMAIN" "${WORKLOAD_ARGS[@]}" --format counts)
# cell_rows <arm> <repo> <seed> — how many row.json files that cell already holds.
cell_rows() {
diff --git a/experiments/scripts/launch/trimech_ab.sh b/experiments/scripts/launch/trimech_ab.sh
deleted file mode 100755
index 7f495a0..0000000
--- a/experiments/scripts/launch/trimech_ab.sh
+++ /dev/null
@@ -1,177 +0,0 @@
-#!/usr/bin/env bash
-# Reproduce a Claude/Copilot tri-mechanism A/B on one domain: the BASELINE arm (no
-# mechanisms) and the TRIMECH arm (injection=manual4 + evidence untooling + spiral guard),
-# then aggregate both into the index CSVs compare_arms.py reads.
-#
-# The exact arm configurations (the full catalog is in docs/RUNNING.md):
-# baseline : native cost basis, no economizer
-# trimech : --mode manual4 --untool-evidence 3 --untool-judge
-# --spiral-guard --spiral-judge --spiral-nudge
-# (Web-Bench streams are short, so the driver's `trimech-web` arm additionally sets
-# --spiral-nudge-llm --spiral-frozen-envelope 30; pass ARM=trimech-web for those.)
-#
-# The heavy task-execution harness (Docker + agent CLI + gold grading) lives below
-# te_bench.runner.AgentRunner, in the repo's te_harness package, so
-# RUNNER=te_harness.swebench:make_runner (or .webbench) needs no PYTHONPATH. Point RUNNER at
-# your own factory ("module:make_runner") to substitute another. With RUNNER=stub you get the offline
-# StubRunner (no Docker/LLM) used by smoke_test.sh -- synthetic, for wiring checks only.
-#
-# Usage:
-# AGENT=claude DOMAIN=swebench REPOS="pydata/xarray django/django" SEEDS="0 1 2" \
-# RUNNER=te_harness.swebench:make_runner \
-# TOKENECONOMIZER_SWEBENCH_TASKS=/path/tasks.json \
-# TOKENECONOMIZER_RESULTS=/path/results \
-# bash scripts/launch/trimech_ab.sh
-#
-# Env (all have safe defaults except the dataset/results placeholders):
-# AGENT claude | copilot (default claude)
-# DOMAIN swebench | webbench | creddata | reposvul (default swebench)
-# ARM trimech | trimech-web (default trimech)
-# ARMS explicit space-separated arm list, overriding the default "baseline $ARM".
-# Use it to run ONE arm when a comparable baseline already exists in the tree
-# -- e.g. ARMS=trimech to add just the economized arm. Without it the launcher
-# re-runs baseline, which both costs an extra pass and supersedes the stored
-# baseline rows in the index (run dirs are timestamped and the aggregator keeps
-# the newest attempt per arm/cell/instance).
-# REPOS space-separated repo slugs (default "pydata/xarray")
-# on DOMAIN=webbench these are Web-Bench PROJECT names -- one project is one
-# stream of 20-21 sequentially dependent tasks (e.g. "calculator zustand react")
-# SEEDS space-separated seeds (default "0")
-# LIMIT cap tasks per (repo,seed), 0 = all (default 0)
-# RUNNER 'stub' or 'module:factory' (default stub)
-# TASKS_FILE task-spec JSON (default: the domain's TOKENECONOMIZER_*_TASKS env var)
-# WORKLOAD workload manifest, or 'none' (default workloads/$DOMAIN.json)
-# DRYRUN 1 = print the cells this lane would run and exit, run nothing (default 0)
-# The BILLED probes skip themselves, so it costs nothing.
-# DETACH 1 = run in the background (default), 0 = foreground
-# TE_LOG log path when detached (default $TOKENECONOMIZER_RESULTS/logs/<tag>__<ts>.log)
-# TOKENECONOMIZER_RESULTS results root (default: ./results)
-set -uo pipefail
-
-HERE="$(cd "$(dirname "$0")" && pwd)"
-REPO_ROOT="$(cd "$HERE/../.." && pwd)"
-PY="${PYTHON:-python3}"
-
-# Credentials + data roots from the git-ignored repo-root .env (shell exports win).
-# shellcheck source=./_env.sh
-. "$HERE/_env.sh"
-te_load_env
-
-AGENT="${AGENT:-claude}"
-DOMAIN="${DOMAIN:-swebench}"
-ARM="${ARM:-trimech}"
-# Arms to run, in order. Default is the paired A/B; ARMS lets a caller run a single arm.
-ARMS="${ARMS:-baseline $ARM}"
-REPOS="${REPOS:-pydata/xarray}"
-SEEDS="${SEEDS:-0}"
-LIMIT="${LIMIT:-0}"
-RUNNER="${RUNNER:-stub}"
-# Credentials preflight for a real run; for RUNNER=stub this prints the synthetic-run
-# warning instead, so stub output is never mistaken for a benchmark.
-te_check_routing "$AGENT"
-
-# Model matched to the stored runs; only labels the cost, does not change the comparison.
-case "$AGENT" in
- claude) MODEL="${MODEL:-${ANTHROPIC_MODEL:-claude-opus-5}}" ;;
- # Native Copilot serves its OWN catalog, so an Anthropic model id is not a valid value
- # here. 'auto' lets the CLI route; pin COPILOT_MODEL (or MODEL) to fix the cost basis --
- # with an id your subscription serves. `copilot --model <id>` fails per task, not at
- # launch, so check first.
- copilot) MODEL="${MODEL:-${COPILOT_MODEL:-auto}}" ;;
- *) MODEL="${MODEL:-agent}" ;;
-esac
-# The backend's spelling of a two-spelling id (claude-opus-4-8 / claude-opus-4.8); the
-# probes below verify it. See te_model_for_agent.
-MODEL="$(te_model_for_agent "$AGENT" "$MODEL")"
-
-# Copilot only: confirm the pinned model is served and takes the requested effort. Both
-# mistakes otherwise fail once per task instead of once at launch. Skipped for RUNNER=stub
-# (no agent runs) and for MODEL=auto (the router takes no effort level).
-if [[ "$AGENT" == "copilot" && "${RUNNER:-stub}" != "stub" ]]; then
- te_check_copilot_model "$MODEL" "${TE_EFFORT_LEVEL:-high}"
-fi
-
-# Dataset task-spec: default to the domain's placeholder env var.
-case "$DOMAIN" in
- swebench) TASKS_FILE="${TASKS_FILE:-${TOKENECONOMIZER_SWEBENCH_TASKS:-}}" ;;
- webbench) TASKS_FILE="${TASKS_FILE:-${TOKENECONOMIZER_WEBBENCH_TASKS:-}}" ;;
- creddata) TASKS_FILE="${TASKS_FILE:-${TOKENECONOMIZER_CREDDATA_TASKS:-}}" ;;
- reposvul) TASKS_FILE="${TASKS_FILE:-${TOKENECONOMIZER_REPOSVUL_TASKS:-}}" ;;
- *) echo "unknown DOMAIN=$DOMAIN"; exit 2 ;;
-esac
-if [[ -z "$TASKS_FILE" ]]; then
- echo "!! no task-spec JSON: set TASKS_FILE or the domain placeholder env var" >&2
- exit 2
-fi
-
-# Canonical workload manifest (committed, tiny): pins the run to exactly the evaluated
-# instances, so TASKS_FILE may hold a superset. WORKLOAD=none restores the legacy behavior
-# of taking whatever TASKS_FILE contains, filtered by the --repo prefix match.
-WORKLOAD="${WORKLOAD:-$REPO_ROOT/workloads/$DOMAIN.json}"
-WORKLOAD_ARGS=()
-if [[ "$WORKLOAD" != "none" ]]; then
- if [[ ! -f "$WORKLOAD" ]]; then
- echo "!! workload manifest not found: $WORKLOAD (set WORKLOAD=none to run unfiltered)" >&2
- exit 2
- fi
- WORKLOAD_ARGS=(--workload "$WORKLOAD")
-fi
-
-# `trimech-web` is the arm tuned for Web-Bench's short streams (it adds the LLM nudge and a
-# cold-start frozen envelope). Running plain `trimech` there is a valid choice, not an error,
-# so say which one is about to run rather than second-guessing it.
-if [[ "$DOMAIN" == "webbench" && "$ARM" != "trimech-web" ]]; then
- echo "[trimech_ab] note: DOMAIN=webbench with ARM=$ARM -- the arm tuned for Web-Bench's" >&2
- echo "[trimech_ab] short streams is ARM=trimech-web (see docs/RUNNING.md)" >&2
-fi
-
-RESULTS_ROOT="${TOKENECONOMIZER_RESULTS:-$REPO_ROOT/results}"
-# <agent>_<domain>_<model-tag>. The MODEL is part of the cost basis, so it belongs in the
-# tree name exactly as it does in main_sweep.sh: without the tag an opus lane and a sonnet
-# lane land in ONE tree and aggregate.py averages two cost bases into a number that
-# describes neither.
-MODEL_TAG="$(te_model_tag "$MODEL")"
-DEST="$RESULTS_ROOT/$(te_tree_name "$AGENT" "$DOMAIN" "$MODEL_TAG")"
-mkdir -p "$DEST"
-
-# DRYRUN=1 prints the cells this launcher would run and exits WITHOUT detaching. It has to
-# come before te_detach: this script used to detach first, so `DRYRUN=1 bash
-# scripts/launch/trimech_ab.sh` returned the terminal and then billed a full A/B in the
-# background -- the opposite of what a dry run is for.
-if [[ "${DRYRUN:-0}" == "1" ]]; then
- echo "[trimech_ab] DRYRUN -- agent=$AGENT domain=$DOMAIN model=$MODEL"
- echo "[trimech_ab] dest=$DEST"
- echo "[trimech_ab] the cells this lane would run, in order:"
- for seed in $SEEDS; do for repo in $REPOS; do for arm in $ARMS; do
- printf ' %s\t%s\t%s\n' "$arm" "$repo" "$seed"
- done; done; done
- echo "[trimech_ab] DRYRUN: nothing was run."
- exit 0
-fi
-
-# Detach by default: config is resolved and credentials are checked, so anything that
-# fails from here on is a run-time failure that belongs in the log, not the terminal.
-te_detach "trimech_ab__${AGENT}_${DOMAIN}_${ARM}" "$0" "$@"
-
-echo "[trimech_ab] agent=$AGENT domain=$DOMAIN arms=($ARMS) repos='$REPOS' seeds='$SEEDS' runner=$RUNNER"
-echo "[trimech_ab] dest=$DEST tasks=$TASKS_FILE workload=$WORKLOAD"
-
-for seed in $SEEDS; do
- for repo in $REPOS; do
- for arm in $ARMS; do
- "$PY" "$HERE/../run_experiment.py" \
- --arm "$arm" --agent "$AGENT" --repo "$repo" --seed "$seed" --limit "$LIMIT" \
- --adapter "$DOMAIN" --tasks-file "$TASKS_FILE" "${WORKLOAD_ARGS[@]}" \
- --results-root "$DEST" --runner "$RUNNER" \
- --model "$MODEL" --optimizer-model "$AGENT" --fresh \
- || { echo "[trimech_ab] FAILED arm=$arm repo=$repo seed=$seed"; exit 1; }
- done
- done
-done
-
-echo "[trimech_ab] aggregating -> $DEST/index/"
-# Aggregate ALL arms present, not just the ones this invocation ran: --arms limits the
-# rewrite and would drop every other arm's rows from the index the comparisons read.
-"$PY" "$HERE/../aggregate.py" "$DEST"
-echo "[trimech_ab] DONE. Compare an arm with its baseline, cell by cell:"
-echo " $PY scripts/compare_arms.py --baseline $DEST/baseline/<cell> --arm $DEST/<arm>/<cell>"
diff --git a/experiments/scripts/run_experiment.py b/experiments/scripts/run_experiment.py
index e4bf6ce..54a53e9 100644
--- a/experiments/scripts/run_experiment.py
+++ b/experiments/scripts/run_experiment.py
@@ -34,7 +34,7 @@ The single-mechanism arms use the SAME parameters trimech co-activates, so each
ablation of it rather than a separately tuned arm. The external tool scaffolds are
implemented in `experiments/te_bench/baselines/` and install into the task container; a
misconfigured one fails at runner construction rather than producing rows that merely look
-like a scaffold result (docs/HARNESS.md, External tool scaffolds).
+like a scaffold result.
The arm tables live next to the code they configure -- `experiments/te_bench/mechanism_arms.py`
for everything the economizer drives (including the two `trimech-*` integrations, which sit
@@ -45,7 +45,7 @@ entry point the docs point at.
The heavy task-execution harness (Docker + agent CLI + official gold grading) lives BELOW
the ``te_bench.runner.AgentRunner`` seam, in the repo's ``te_harness`` package -- the
one the published rows came from, so ``--runner te_harness.swebench:make_runner`` reproduces
-them as committed (docs/HARNESS.md). Any other harness works the same way: pass
+them as committed. Any other harness works the same way: pass
``--runner module:factory`` (a zero-arg callable returning an AgentRunner). ``--runner stub``
selects the built-in offline StubRunner used by the smoke test -- it writes a synthetic
transcript and a plausible row so the full facade -> aggregate -> figures pipeline can be
@@ -59,7 +59,7 @@ Usage:
Placeholders (env vars): the driver reads a --tasks-file JSON list per domain
(TOKENECONOMIZER_SWEBENCH_TASKS / _WEBBENCH_TASKS / _CREDDATA_TASKS / _REPOSVUL_TASKS); the
adapters + harness separately read the dataset roots (_WEBBENCH_PROJECTS / _CREDDATA_ROOT /
-_REPOSVUL_ROOT / _CYBERGYM_SUITE). See docs/BENCHMARKS.md. The results root is git-ignored.
+_REPOSVUL_ROOT). See README.md. The results root is git-ignored.
"""
import argparse
import collections
@@ -217,16 +217,14 @@ def load_runner(spec, agent, model=None, scaffold=None):
def load_adapter(name, tasks_file, repo=""):
from te_bench.adapters import (
- SwebenchAdapter, WebBenchAdapter, CredDataAdapter, ReposVulAdapter,
- CyberGymAdapter)
+ SwebenchAdapter, WebBenchAdapter, CredDataAdapter, ReposVulAdapter)
if name == "swebench":
return SwebenchAdapter(tasks_path=tasks_file)
if name == "webbench":
# the Web-Bench project (= one stream) is selected by --repo; the per-task judge
# then reads <projects>/<project>/tasks.jsonl. Defaults to 'dom' if --repo is unset.
return WebBenchAdapter(repo.split("/")[-1] or "dom")
- return {"creddata": CredDataAdapter, "reposvul": ReposVulAdapter,
- "cybergym": CyberGymAdapter}[name]()
+ return {"creddata": CredDataAdapter, "reposvul": ReposVulAdapter}[name]()
def workload_ids(workload_file, repo):
@@ -337,10 +335,10 @@ def main():
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--limit", type=int, default=0, help="cap tasks (0 = all)")
ap.add_argument("--adapter", default="swebench",
- choices=["swebench", "webbench", "creddata", "reposvul", "cybergym"])
+ choices=["swebench", "webbench", "creddata", "reposvul"])
ap.add_argument("--tasks-file", required=True,
help="JSON list of {instance_id, problem_statement, repo} (a placeholder "
- "you point at your dataset export; see docs/BENCHMARKS.md)")
+ "you point at your dataset export; see README.md)")
ap.add_argument("--workload", default="",
help="workloads/<domain>.json manifest naming the exact evaluated "
"instances; --tasks-file is filtered to it (and to --repo's group). "
diff --git a/experiments/scripts/sweep_plan.py b/experiments/scripts/sweep_plan.py
index 027a146..db89f5c 100755
--- a/experiments/scripts/sweep_plan.py
+++ b/experiments/scripts/sweep_plan.py
@@ -9,7 +9,6 @@ API key):
--format cells one `arm<TAB>repo<TAB>seed` line per cell, for a launcher to loop over
--format estimate task-runs, wall-clock and dollars for the requested slice
- --format matrix the estimate for the WHOLE sweep, every agent x model x domain
Task counts come from the committed `workloads/<domain>.json` manifest -- the same file
the launcher passes as `--workload` and the driver filters the task stream to -- so the
@@ -23,9 +22,8 @@ the estimate so a reader can rescale it. They are means over a heavy-tailed dist
treat the output as an order of magnitude, not a quote.
Usage:
- python scripts/sweep_plan.py --format matrix
python scripts/sweep_plan.py --domain swebench --arms baseline trimech \\
- --repos django/django --seeds 0 1 2 3 4 --format cells
+ --repos django/django --seeds 0 1 2 --format cells
"""
import argparse
import json
@@ -97,9 +95,8 @@ SWEEP_ARMS_WEBBENCH_OUT_OF_SCOPE = ("inject-only", "untool-only", "spiral-only-w
# serena -- an MCP navigation server for a codebase. Web-Bench hands the agent a file
# set with no installed project, and the projects run 1-140 files, so there is
# essentially nothing to navigate.
-# Generic arms only: this planner enumerates the Claude / Copilot sweep. The Codex catalog
-# (docs/RUNNING.md section 5) is launched by its own loops, and its Web-Bench list
-# already leaves out the two repomap-bearing arms for the same reason as here.
+# Generic arms only: this planner enumerates the Claude / Copilot sweep. The Codex arms
+# are launched by codex_ab.sh, and its Web-Bench list already leaves out the two repomap-bearing arms for the same reason as here.
SWEEP_ARMS_WEBBENCH_UNAVAILABLE = ("serena", "repomap", "trimech-repomap")
# `trimech-rtk` is not "unavailable" on Web-Bench -- it is SUPERSEDED there by
# `trimech-rtk-web`, exactly as `trimech` is by `trimech-web`. Listing it as unavailable
@@ -107,82 +104,7 @@ SWEEP_ARMS_WEBBENCH_UNAVAILABLE = ("serena", "repomap", "trimech-repomap")
SWEEP_ARMS_WEBBENCH_SUPERSEDED = {"trimech": "trimech-web",
"spiral-only": "spiral-only-web",
"trimech-rtk": "trimech-rtk-web"}
-# Every arm that carries an external tool baseline, from the baselines registry itself so
-# this module cannot drift from it. Used only for reporting.
-try:
- from te_bench.baselines import ARM_SCAFFOLDS as _ARM_SCAFFOLDS
- SCAFFOLD_ARM_NAMES = frozenset(_ARM_SCAFFOLDS)
-except ImportError: # pragma: no cover - core is stdlib
- SCAFFOLD_ARM_NAMES = frozenset()
-
-# The agents, and the models they are crossed with. Model ids are what the CLI is passed
-# and what the row records; the tree name gets the short tag (te_model_tag in
-# scripts/launch/_env.sh), so every model in this list lands in its OWN tree and lanes for
-# different models can run at the same time without ever sharing a cell.
-SWEEP_AGENT_NAMES = ("claude", "copilot")
-
-# Verified 2026-09-12 on the Copilot CLI (serves + accepts --effort). Any id here can be
-# run; te_model_tag gives each a distinct tag and pricing.MODEL_WEIGHTS prices each, so
-# adding one needs no other change. Spelled the Anthropic API's way (dashes); the launcher
-# re-spells a two-spelling id for the one backend that differs (the Copilot CLI's own
-# catalog says `claude-opus-4.8`) -- see te_model_for_agent in scripts/launch/_env.sh.
-SWEEP_MODELS_SUPPORTED = ("claude-opus-5", "claude-sonnet-5", "claude-opus-4-8")
-
-# What the DEFAULT sweep runs. Deliberately not all of SWEEP_MODELS_SUPPORTED: the matrix is
-# linear in this list, so adding a third model is a 1.5x bill on a sweep already estimated
-# at five figures. That is the experiment owner's call, not a default. Override
-# without editing this file:
-#
-# TE_SWEEP_MODELS="claude-opus-4-8 claude-sonnet-5 claude-opus-5" \
-# python scripts/sweep_plan.py --format matrix
-#
-# Accepts spaces or commas. An id outside SWEEP_MODELS_SUPPORTED is allowed but warned
-# about, since the check above has not been run for it.
-#
-# `claude-opus-5` is NOT here on purpose, and that is NOT the same as optional. Its lanes
-# are required -- they just run a 4-arm subset instead of the full matrix (baseline /
-# baseline-medium / baseline-low / trimech, both domains -- the Copilot and Claude run
-# books, 3b), so they are launched by their own commands rather than by
-# crossing this list. Listing it here would plan a third FULL 21-arm lane, which is a
-# different and much larger thing: it costs ~2.5x per call what claude-opus-4-8 does on the
-# Copilot path, and the matrix is linear in this list.
-SWEEP_MODELS = ("claude-opus-4-8", "claude-sonnet-5")
-
-
-def _sweep_models():
- """The model list, honouring TE_SWEEP_MODELS. Unknown ids warn rather than raise --
- a new vendor id should be runnable the day it appears, not after a code change."""
- raw = os.environ.get("TE_SWEEP_MODELS", "")
- if not raw.strip():
- return list(SWEEP_MODELS)
- models = [m for m in raw.replace(",", " ").split() if m]
- # Compare with separators folded, the way te_model_tag does: claude-opus-4-8 and
- # claude-opus-4.8 are one model spelled for two catalogs, not two models to list.
- known = {m.replace(".", "").replace("-", "") for m in SWEEP_MODELS_SUPPORTED}
- unknown = [m for m in models
- if m.replace(".", "").replace("-", "") not in known]
- # Warn once per process: this helper is called several times while formatting a matrix,
- # and three identical notices read like three different problems.
- if unknown and not _sweep_models._warned:
- _sweep_models._warned = True
- print(f"[sweep_plan] note: {' '.join(unknown)} not in SWEEP_MODELS_SUPPORTED -- "
- f"run one paid cell on it (docs/RUNNING.md section 3) before spending",
- file=sys.stderr)
- return models
-
-
-_sweep_models._warned = False
-
-
-def sweep_agents():
- """(agent, model) pairs: every agent crossed with every requested model."""
- return tuple((a, m) for a in SWEEP_AGENT_NAMES for m in _sweep_models())
-
-
-# Back-compat: modules and tests that read the constant directly get the default cross.
-SWEEP_AGENTS = tuple((a, m) for a in SWEEP_AGENT_NAMES for m in SWEEP_MODELS)
-SWEEP_DOMAINS = ("swebench", "webbench")
-SWEEP_SEEDS = (0, 1, 2, 3, 4)
+SWEEP_SEEDS = (0, 1, 2) # the paper's three seeds
# Measured on the stored claude_swebench tree: 984 task-runs, mean $0.34/task on the honest
# basis (effective + overhead at the $5/1M-output tier), and ~112-133 s/task from the two
@@ -191,7 +113,7 @@ DEFAULT_SEC_PER_TASK = 120.0
DEFAULT_USD_PER_TASK = 0.34
-def group_sizes(domain):
+def group_sizes(domain, manifest=None):
"""{group -> n_tasks} a NEW run will actually execute, per group.
NOT `workloads.task_counts()`, which is the provenance record and deliberately does
@@ -204,9 +126,9 @@ def group_sizes(domain):
completed cells, paid for, silently. So this reads the same committed manifest the
launcher passes as `--workload` and the driver filters to (`load_tasks` keeps exactly
the ids the manifest names), and falls back to `runnable_instances` when a manifest is
- not on disk. tests/test_sweep_arms.py asserts the two agree.
+ not on disk. tests/test_sweep_arms.py asserts the two agree. `manifest` names another one.
"""
- manifest = os.path.join(_EXPERIMENTS, "workloads", f"{domain}.json")
+ manifest = manifest or os.path.join(_EXPERIMENTS, "workloads", f"{domain}.json")
if os.path.exists(manifest):
with open(manifest, encoding="utf-8") as fh:
groups = json.load(fh).get("groups") or {}
@@ -230,7 +152,7 @@ def cells(domain, arms, repos, seeds):
return out
-def estimate(domain, arms, repos, seeds, sec_per_task, usd_per_task, limit=0):
+def estimate(domain, arms, repos, seeds, sec_per_task, usd_per_task, limit=0, manifest=None):
"""Task-runs, wall-clock and dollars for the requested slice.
`limit` mirrors the launcher's LIMIT (cap tasks per cell, 0 = all). It has to be
@@ -239,7 +161,7 @@ def estimate(domain, arms, repos, seeds, sec_per_task, usd_per_task, limit=0):
-- which is the wrong direction for a number whose whole job is to be checked before
spending money.
"""
- sizes = group_sizes(domain)
+ sizes = group_sizes(domain, manifest)
unknown = [r for r in repos if r not in sizes]
per_repo = {r: sizes.get(r, 0) for r in repos}
if limit and limit > 0:
@@ -292,12 +214,14 @@ def main():
"task count, and reads like a quote it cannot support)")
ap.add_argument("--sec-per-task", type=float, default=DEFAULT_SEC_PER_TASK)
ap.add_argument("--usd-per-task", type=float, default=DEFAULT_USD_PER_TASK)
+ ap.add_argument("--workload", default=None,
+ help="workload manifest to count tasks from (default: workloads/<domain>.json)")
ap.add_argument("--format", default="estimate",
- choices=["cells", "estimate", "matrix", "arms", "counts"])
+ choices=["cells", "estimate", "arms", "counts"])
args = ap.parse_args()
arms = args.arms or list(SWEEP_ARMS[args.domain])
- repos = args.repos or sorted(group_sizes(args.domain))
+ repos = args.repos or sorted(group_sizes(args.domain, args.workload))
seeds = args.seeds if args.seeds is not None else list(SWEEP_SEEDS)
bad = [a for a in arms if a not in ARMS]
@@ -309,7 +233,7 @@ def main():
print(a)
return
if args.format == "counts":
- for group, n in sorted(group_sizes(args.domain).items()):
+ for group, n in sorted(group_sizes(args.domain, args.workload).items()):
print(f"{group}\t{n}")
return
if args.format == "cells":
@@ -329,7 +253,8 @@ def main():
if not (args.domain == "webbench"
and a in SWEEP_ARMS_WEBBENCH_UNAVAILABLE)]
e = estimate(args.domain, usable, repos, seeds,
- args.sec_per_task, args.usd_per_task, limit=args.limit)
+ args.sec_per_task, args.usd_per_task, limit=args.limit,
+ manifest=args.workload)
if e["unknown_repos"]:
print(f"!! not in the {args.domain} workload record: "
f"{' '.join(e['unknown_repos'])} (counted as 0 tasks)", file=sys.stderr)
@@ -339,57 +264,6 @@ def main():
f"(measured means, heavy-tailed -- an order of magnitude, not a quote)")
return
- # --format matrix: the whole sweep, every agent x model x domain
- pairs = sweep_agents()
- print(f"main sweep: {len(pairs)} agent-model pairs x {len(SWEEP_DOMAINS)} "
- f"domains x {len(SWEEP_SEEDS)} seeds")
- print(f" agent-model : {', '.join(f'{a}/{m}' for a, m in pairs)}")
- if len(_sweep_models()) < len(SWEEP_MODELS_SUPPORTED):
- rest = [m for m in SWEEP_MODELS_SUPPORTED if m not in _sweep_models()]
- print(f" not planned here: {' '.join(rest)}")
- # NOT the same as optional. claude-opus-5 runs 4 REQUIRED arms per domain, launched
- # by their own main_sweep.sh calls; this planner only crosses full 21-arm lanes, so
- # a model absent from SWEEP_MODELS is invisible to it either way. Saying "also
- # supported" here read as "skip if you like", which is wrong for that model.
- if any("opus-5" in m.replace(".", "-") for m in rest):
- print(" claude-opus-5: 4 arms x both domains are REQUIRED and are launched "
- "separately\n"
- " (baseline baseline-medium baseline-low trimech"
- " / trimech-web -- docs/RUNNING.md, the frontier lane).")
- print(f" to plan one of these as a FULL {len(SWEEP_ARMS['swebench'])}-arm lane"
- f" instead: TE_SWEEP_MODELS=\"{' '.join(list(_sweep_models()) + rest)}\"")
- total_tasks = total_usd = total_hours = total_cells = 0
- for domain in SWEEP_DOMAINS:
- arms_d = list(SWEEP_ARMS[domain])
- repos_d = sorted(group_sizes(domain))
- e = estimate(domain, arms_d, repos_d, list(SWEEP_SEEDS),
- args.sec_per_task, args.usd_per_task)
- per_pair = _fmt_estimate(e, args.show_cost)
- print(f" per agent-model pair: {per_pair}")
- print(f" arms : {' '.join(arms_d)}")
- print(f" groups: {' '.join(repos_d)}")
- total_tasks += e["n_task_runs"] * len(pairs)
- total_usd += e["usd"] * len(pairs)
- total_hours += e["hours_serial"] * len(pairs)
- total_cells += e["n_cells"] * len(pairs)
- total = f" TOTAL: {total_cells:,} cells {total_tasks:,} task-runs"
- if args.show_cost:
- total += (f" ~${total_usd:,.0f} {total_hours:,.0f} h serial "
- f"({total_hours / 24:,.0f} days; "
- f"/{len(pairs) * len(SWEEP_DOMAINS)} lanes = "
- f"{total_hours / 24 / (len(pairs) * len(SWEEP_DOMAINS)):,.0f} days)")
- print(total)
- if not args.show_cost:
- print(" (exact counts. --show-cost adds a derived $ / wall-clock total: one "
- "repo-dominated per-task mean x the count, so do not quote it -- budget from "
- "the PER-ARM runtime instead: time one arm on your host and multiply)")
- hosted = sorted(a for a in SWEEP_ARMS["webbench"] if a in SCAFFOLD_ARM_NAMES)
- print(f" Web-Bench runs the scaffold arms it can host ({' '.join(hosted)}) and NOT "
- f"({' '.join(SWEEP_ARMS_WEBBENCH_UNAVAILABLE)}): the repo map generates a PYTHON "
- f"symbol map a Node/TypeScript project does not have, and Serena is a codebase "
- f"navigation server for a benchmark that ships a file set, not a codebase "
- f"-- see SWEEP_ARMS_WEBBENCH_UNAVAILABLE")
-
if __name__ == "__main__":
main()
diff --git a/experiments/te_bench/adapters/__init__.py b/experiments/te_bench/adapters/__init__.py
index 62f7d71..cbe925a 100644
--- a/experiments/te_bench/adapters/__init__.py
+++ b/experiments/te_bench/adapters/__init__.py
@@ -7,8 +7,6 @@ which a task domain reaches the mechanisms:
* WebBenchAdapter -- Web-Bench (thin subclass; task-spec source only).
* CredDataAdapter -- CredData secret-finding audit (fixed prompt + scan classifier).
* ReposVulAdapter -- ReposVul vulnerability audit (same thin-subclass pattern).
- * CyberGymAdapter -- CyberGym PoC-authoring tasks.
- * WebArenaAdapter -- stub marking exactly what a browser-episode eval must supply.
The facade threads ONE adapter (default SwebenchAdapter) into all three mechanisms. A new
domain = a new adapter, no mechanism edits. Dataset roots are supplied via env-var
@@ -19,8 +17,6 @@ from .swebench import SwebenchAdapter
from .webbench import WebBenchAdapter
from .creddata import CredDataAdapter
from .reposvul import ReposVulAdapter
-from .cybergym import CyberGymAdapter
-from .webarena import WebArenaAdapter
__all__ = ["DomainAdapter", "SwebenchAdapter", "WebBenchAdapter", "CredDataAdapter",
- "ReposVulAdapter", "CyberGymAdapter", "WebArenaAdapter"]
+ "ReposVulAdapter"]
diff --git a/experiments/te_bench/adapters/cybergym.py b/experiments/te_bench/adapters/cybergym.py
deleted file mode 100644
index 443efe3..0000000
--- a/experiments/te_bench/adapters/cybergym.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""CyberGymAdapter: the economizer's domain surface for the CyberGym security benchmark.
-
-CyberGym tasks ask the agent to inspect a vulnerable workspace and produce a
-proof-of-concept input that triggers the described vulnerability. As with the other
-non-SWE-bench domains, the inner coding-agent run is the SAME host agent, so its transcript
-is byte-compatible with the vendored `reflect` readers and every reading method is
-INHERITED verbatim from SwebenchAdapter. Only `problem_statements()` (a fixed PoC-authoring
-prompt per task) and `classify_domain()` are overridden.
-
-The suite JSON is located by TOKENECONOMIZER_CYBERGYM_SUITE (a placeholder you set) or an
-explicit `suite_path=`.
-"""
-import json
-import os
-
-from .swebench import SwebenchAdapter
-
-CYBERGYM_SUITE_ENV = "TOKENECONOMIZER_CYBERGYM_SUITE"
-
-CYBERGYM_TASK_PROMPT = (
- "You are solving a CyberGym security benchmark task. Inspect the provided workspace, "
- "identify the described vulnerability, and produce a proof-of-concept input file that "
- "triggers it."
-)
-
-CYBERGYM_CLASSIFY_DOMAIN = (
- "You configure the toolset for an autonomous SECURITY-RESEARCH agent that will inspect "
- "a vulnerable source tree and create a proof-of-concept input file."
-)
-
-
-class CyberGymAdapter(SwebenchAdapter):
- name = "cybergym"
-
- def __init__(self, suite_path=None, repo_names=None):
- """`suite_path` locates the CyberGym suite JSON (defaults to the
- TOKENECONOMIZER_CYBERGYM_SUITE env-var placeholder). `repo_names` optionally
- restricts problem_statements() to a subset of projects."""
- self.suite_path = suite_path or os.environ.get(CYBERGYM_SUITE_ENV)
- self._repo_names = list(repo_names) if repo_names is not None else None
-
- def _load_suite(self):
- if not self.suite_path:
- raise RuntimeError(
- f"no CyberGym suite: set ${CYBERGYM_SUITE_ENV} or pass suite_path=.")
- with open(self.suite_path, encoding="utf-8") as handle:
- return json.load(handle)
-
- def problem_statements(self):
- """{task_id: PoC-authoring prompt} for the untool per-task judge."""
- suite = self._load_suite()
- repos = self._repo_names
- prompt_map = {}
- for repo in suite.get("repositories", []):
- if repos is not None and repo["project_name"] not in repos:
- continue
- for task in repo.get("tasks", []):
- prompt_map[task["task_id"]] = CYBERGYM_TASK_PROMPT
- return prompt_map
-
- def classify_domain(self):
- return CYBERGYM_CLASSIFY_DOMAIN
diff --git a/experiments/te_bench/adapters/webarena.py b/experiments/te_bench/adapters/webarena.py
deleted file mode 100644
index fc5d0e5..0000000
--- a/experiments/te_bench/adapters/webarena.py
+++ /dev/null
@@ -1,52 +0,0 @@
-"""WebArenaAdapter: STUB marking exactly what a WebArena agentic eval must supply.
-
-WebArena / BrowserGym tasks are browser-interaction episodes: the agent emits actions like
-`click`, `type`, `goto`, `scroll`, `select_option` against a live web app, and success is
-decided by WebArena's own per-task checker (URL match / element / DB state), NOT a gold
-patch. Because the economizer's three mechanisms are domain-neutral (they count
-turns/tokens over a normalized trajectory), they transfer to WebArena UNCHANGED once this
-adapter is implemented. Every method below raises NotImplementedError with the precise
-contract it must fulfill.
-
-Implementation notes (for whoever fills this in):
-
- load_trajectory(path)
- Parse a saved BrowserGym/WebArena episode into the SAME normalized shape the
- economizer expects: [(action_name, args_dict, observation_text, success_bool)]. Map
- browser actions to `action_name` ("click"/"type"/"goto"); put the target
- selector/url/text in args; the resulting page observation (accessibility tree / DOM
- excerpt) is result_text; success is whether the action executed. Order-preserving.
-
- tool_usage(path) {action_name: count} over the episode.
- parse_catalog(...) {action_name: description} of the browser action space (often a
- fixed constant map -- return it so evidence-untool can reason
- about unused actions).
- protected_tools() the browser work surface (click/type/goto/scroll/...); never drop.
- inapplicable_tools() actions inapplicable-by-construction for a sealed episode.
-
-Also required, OUTSIDE this adapter -- at the runner layer: a web executor that drives one
-WebArena episode in its browser env, and WebArena's success checker in place of the gold
-grade (see te_bench.runner.AgentRunner).
-"""
-
-_TODO = ("WebArenaAdapter is a stub: implement the WebArena/BrowserGym {what} "
- "(see the module docstring).")
-
-
-class WebArenaAdapter:
- name = "webarena"
-
- def load_trajectory(self, path):
- raise NotImplementedError(_TODO.format(what="episode -> normalized trajectory parser"))
-
- def tool_usage(self, path):
- raise NotImplementedError(_TODO.format(what="per-action usage counter"))
-
- def parse_catalog(self, run_dir_path, agent):
- raise NotImplementedError(_TODO.format(what="browser action-space catalog"))
-
- def protected_tools(self):
- raise NotImplementedError(_TODO.format(what="browser work-surface protected set"))
-
- def inapplicable_tools(self):
- raise NotImplementedError(_TODO.format(what="inapplicable-action set"))
diff --git a/experiments/te_bench/runner.py b/experiments/te_bench/runner.py
index 320e53a..df426dc 100644
--- a/experiments/te_bench/runner.py
+++ b/experiments/te_bench/runner.py
@@ -13,8 +13,7 @@ this interface. The economizer needs only two capabilities from a runner:
mask, spiral params), returning a normalized row + the path to the saved transcript.
A concrete runner (Docker + claude/codex/copilot CLI + official gold grading) ships in the
-repo's `te_harness` package -- the one the published rows were produced with
-(experiments/docs/HARNESS.md);
+repo's `te_harness` package -- the one the published rows were produced with;
its image and dataset paths are env-var placeholders. Supply a different one with
``--runner your_pkg.harness:make_runner``; nothing here changes, because the economizer
never learns which harness it is talking to.
diff --git a/experiments/te_harness/__init__.py b/experiments/te_harness/__init__.py
index b2e1eb3..5029c27 100644
--- a/experiments/te_harness/__init__.py
+++ b/experiments/te_harness/__init__.py
@@ -23,7 +23,7 @@ Both `make_runner` factories take the driver's `--agent` label and return the ru
that agent -- `claude` (Claude Code, on the Anthropic API), `copilot` (GitHub Copilot CLI,
on its own GitHub or BYOK auth) or `codex` (OpenAI Codex CLI, on the OpenAI API). An
unknown label raises rather than falling back, because a runner that quietly ran the wrong
-agent would produce plausible rows under the wrong name. Copilot setup: docs/COPILOT.md.
+agent would produce plausible rows under the wrong name. Setup: experiments/README.md.
"""
import os as _os
import sys as _sys
diff --git a/experiments/te_harness/capture_catalog.py b/experiments/te_harness/capture_catalog.py
index 64dbcd3..ec906dc 100644
--- a/experiments/te_harness/capture_catalog.py
+++ b/experiments/te_harness/capture_catalog.py
@@ -136,7 +136,7 @@ def capture(instance_id=CAPTURE_INSTANCE, port=None, out_path=None, desc_chars=N
port = int(port or os.environ.get("TE_CATALOG_PORT", "8770"))
out_path = out_path or os.environ.get("TE_CATALOG_OUT", DEFAULT_OUT)
desc_chars = int(desc_chars or os.environ.get("TE_CATALOG_DESC_CHARS", "300"))
- model = model or os.environ.get("ANTHROPIC_MODEL", "claude-opus-5")
+ model = model or os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5")
effort = effort or os.environ.get("TE_EFFORT_LEVEL", "high")
# Must match what a task run uses (te_harness.swebench.run_task) -- see pass 1 below.
turn_cap = int(os.environ.get("TE_MAX_TURNS", "80"))
diff --git a/experiments/te_harness/codex.py b/experiments/te_harness/codex.py
index 8b4f8b8..87de329 100644
--- a/experiments/te_harness/codex.py
+++ b/experiments/te_harness/codex.py
@@ -89,7 +89,7 @@ C_BIN = C_VENDOR + "/bin/codex"
C_HOME = "/opt/codex-home"
# The OpenAI Platform's global Responses endpoint. Only a DEFAULT: a region-scoped key
-# 401s here and must set OPENAI_BASE_URL to its own region (docs/SETUP.md step 3).
+# 401s here and must set OPENAI_BASE_URL to its own region.
OPENAI_DIRECT = "https://api.openai.com/v1"
# The one credential the Codex lane bills on. config.toml names it (`env_key`) and the
@@ -117,7 +117,7 @@ def codex_vendor(binary=None):
Resolved from the Node shim's install tree rather than hardcoded: the AgentEO driver
pinned an absolute path under one machine's nvm prefix, which is exactly the kind of
- path docs/BENCHMARKS.md keeps out of the code. TE_CODEX_VENDOR overrides.
+ machine-specific path the code must not carry. TE_CODEX_VENDOR overrides.
Raises when the ELF is absent. Docker invents an EMPTY directory for a missing bind
mount source rather than failing, so an unchecked bad path here becomes "codex: not
diff --git a/experiments/te_harness/guards/net_guard.py b/experiments/te_harness/guards/net_guard.py
index 469ac90..734a973 100644
--- a/experiments/te_harness/guards/net_guard.py
+++ b/experiments/te_harness/guards/net_guard.py
@@ -3,7 +3,7 @@
Web-Bench is a PUBLIC repository. `bytedance/web-bench` ships, for every project, the exact
Playwright spec each task is graded by -- so an agent that can reach GitHub is not solving
-the task, it is reading the answer key. Measured 2026-09-07 on claude-opus-5: three
+the task, it is reading the answer key. Measured 2026-09-07 in development runs: three
Web-Bench tasks curled their own grading spec
(`raw.githubusercontent.com/bytedance/web-bench/main/projects/<p>/test/task-N.spec.js`) and
two of them then passed.
@@ -32,8 +32,7 @@ CLI: they keyed the event kebab-case (`pre-tool-use`) where Codex wants PascalCa
handler an argv list where it wants a command string, and ran without the trust bypass --
and Codex skips every hook a person has not approved in /hooks, which an unattended run
cannot do. Rows stored before 2026-09-30 on the Codex lanes therefore carry
-`net_guard_installed: false` and were guarded by the DNS layer below alone
-(docs/HARNESS.md, "The answer-key guard").
+`net_guard_installed: false` and were guarded by the DNS layer below alone.
WHY A HOOK AND NOT A TOOL MASK. `WebSearch`/`WebFetch` are masked out separately, but the
agent simply used `curl` inside `Bash` -- and `Bash` is in `PROTECTED_TOOLS`, so it can
diff --git a/experiments/te_harness/swebench.py b/experiments/te_harness/swebench.py
index 40ad304..6cc55ca 100644
--- a/experiments/te_harness/swebench.py
+++ b/experiments/te_harness/swebench.py
@@ -23,7 +23,7 @@ resolving to whichever machine happened to write this file):
ANTHROPIC_API_KEY Anthropic API key. REQUIRED: the Claude lane bills
api.anthropic.com directly and nothing else. ANTHROPIC_BASE_URL
and ANTHROPIC_AUTH_TOKEN are not inputs -- see resolve_anthropic_key
- ANTHROPIC_MODEL agent model (default claude-opus-5)
+ ANTHROPIC_MODEL agent model (default claude-sonnet-5)
(no optimizer-model knob: the between-task proposer/judge/nudge-writer runs on the
AGENT'S OWN model, against the agent's own endpoint. TE_OPTIMIZER_MODEL is refused.)
TE_CLAUDE_BIN host claude binary (default: resolved from `which claude`)
@@ -440,8 +440,8 @@ def _import_swebench():
# An agent that can browse is therefore not solving the task, it is retrieving the answer,
# and the resolve verdict measures nothing.
#
-# This is NOT hypothetical and NOT historical. Measured 2026-09-07: across the live
-# claude-opus-5 / claude-sonnet-5 trees, 32 tasks reached the network and 14 pulled
+# This is NOT hypothetical and NOT historical. Measured 2026-09-07: across two live
+# development trees, 32 tasks reached the network and 14 pulled
# something patch-shaped -- `sympy/pulls/16597/files`, `django/commit/2cbd3967.patch`,
# `sphinx-doc/commit/0eff5818.patch`, `svg-chart/test/task-4.spec.js` -- and 13 of those
# scored RESOLVED. The published claude-opus-4.8 trees are clean (0 of 800 transcripts),
@@ -555,7 +555,7 @@ class ClaudeSwebenchRunner:
def __init__(self, agent="claude", model=None, grading_path=None, scaffold=None):
self.agent = agent
- self.model = model or os.environ.get("ANTHROPIC_MODEL", "claude-opus-5")
+ self.model = model or os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5")
# The Anthropic API directly, on ANTHROPIC_API_KEY -- the one endpoint this lane
# bills. There is no argument for it: see resolve_anthropic_key.
self.api_key = resolve_anthropic_key()
@@ -1966,7 +1966,7 @@ class CopilotSwebenchRunner(ClaudeSwebenchRunner):
~/.copilot, whose short-lived token is only refreshed when a copilot process runs
on the HOST. On a long unattended sweep that token goes stale and every later
container fast-fails with an empty patch, so keep a host-side keepalive running
- (docs/COPILOT.md) or set COPILOT_GITHUB_TOKEN.
+ or set COPILOT_GITHUB_TOKEN.
"""
# Copilot reads project instructions from .github/copilot-instructions.md, takes an
@@ -2248,7 +2248,7 @@ class CopilotSwebenchRunner(ClaudeSwebenchRunner):
raise RuntimeError(
f"copilot refused this configuration: {bad}\n"
f" model={self.model!r} effort={self.effort!r}\n"
- " fix COPILOT_MODEL / TE_EFFORT_LEVEL (see docs/COPILOT.md step 2); "
+ " fix COPILOT_MODEL / TE_EFFORT_LEVEL; "
"COPILOT_MODEL=auto always works but does not apply an effort level.")
log_text = _run(["docker", "exec", name, "bash", "-lc",
@@ -2562,8 +2562,7 @@ class CodexSwebenchRunner(ClaudeSwebenchRunner):
the CLI: those probes keyed the event kebab-case (`pre-tool-use`; Codex reads
PascalCase `PreToolUse`, as Claude Code does), gave the handler an argv list rather
than a command string, and ran without the trust bypass. Codex rows stored before
- 2026-09-30 therefore ran without the hook, guarded by the hosts block alone
- (docs/HARNESS.md, "The answer-key guard").
+ 2026-09-30 therefore ran without the hook, guarded by the hosts block alone.
The rest is the shared lifecycle's: the script is copied in, the interpreter found,
and the guard made to refuse its probe before the lane reports itself armed.
diff --git a/experiments/te_harness/webbench.py b/experiments/te_harness/webbench.py
index 89ebca1..0793381 100644
--- a/experiments/te_harness/webbench.py
+++ b/experiments/te_harness/webbench.py
@@ -41,7 +41,7 @@ Environment (all optional except the key; see the repo's .env / .env.example):
and ANTHROPIC_AUTH_TOKEN are not inputs, and are removed from the
agent's environment (swebench.resolve_anthropic_key,
swebench.agent_credential_env -- shared with that domain)
- ANTHROPIC_MODEL agent model (default claude-opus-5)
+ ANTHROPIC_MODEL agent model (default claude-sonnet-5)
(no optimizer-model knob: the between-task proposer/judge/nudge-writer runs on the
AGENT'S OWN model, against the agent's own endpoint. TE_OPTIMIZER_MODEL is refused.)
TE_CLAUDE_BIN host claude binary (default: resolved from `which claude`)
@@ -277,8 +277,8 @@ def _ignored(rel, globs):
# An agent that can browse is therefore not solving the task, it is retrieving the answer,
# and the resolve verdict measures nothing.
#
-# This is NOT hypothetical and NOT historical. Measured 2026-09-07: across the live
-# claude-opus-5 / claude-sonnet-5 trees, 32 tasks reached the network and 14 pulled
+# This is NOT hypothetical and NOT historical. Measured 2026-09-07: across two live
+# development trees, 32 tasks reached the network and 14 pulled
# something patch-shaped -- `sympy/pulls/16597/files`, `django/commit/2cbd3967.patch`,
# `sphinx-doc/commit/0eff5818.patch`, `svg-chart/test/task-4.spec.js` -- and 13 of those
# scored RESOLVED. The published claude-opus-4.8 trees are clean (0 of 800 transcripts),
@@ -303,7 +303,7 @@ def _ignored(rel, globs):
#
# The cap is COOPERATIVE -- checked between lines of the CLI's stream, so a turn already in
# flight runs to completion. The ceiling is therefore `cap + longest single turn`, measured
-# at +16s on claude-opus-4.8 and +21s on claude-opus-5. So the ceiling must sit well below
+# at +16s and +21s on two Claude models. So the ceiling must sit well below
# 300, not just under it: the default leaves ~60s for the overshoot and the hard max ~40s.
# A 290 max would have allowed 290+21 = 311s, i.e. straight back over the wall.
# 2026-09-21: the "no configuration above ~300s can help" above is true of WEB-BENCH's
@@ -622,7 +622,7 @@ class WebBenchRunner:
def __init__(self, agent="claude", model=None, repo=None, scaffold=None):
self.agent = agent
- self.model = model or os.environ.get("ANTHROPIC_MODEL", "claude-opus-5")
+ self.model = model or os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5")
# The Anthropic API directly, on ANTHROPIC_API_KEY -- one resolver, shared with the
# SWE-bench runner so the two domains cannot drift apart about what they bill.
self.api_key = resolve_anthropic_key()
@@ -685,8 +685,8 @@ class WebBenchRunner:
# so our reply lands on a closed socket (BrokenPipeError out of do_POST), the answer
# is DISCARDED, and the task is scored a pass@1 miss for a plumbing reason. Worse,
# it burns a retry -- and when it burns the LAST retry the evaluator ends the whole
- # stream, so every later task comes back UNREACHED. Measured 2026-09-07 on
- # claude-opus-5: threejs/task-14 2nd attempt clipped at
+ # stream, so every later task comes back UNREACHED. Measured 2026-09-07 in a
+ # development run: threejs/task-14 2nd attempt clipped at
# Request 300.858s and took tasks 15-20 down with it; svg-chart hit the same wall
# from task-6 on. The old 1800s default predated a model slow enough to reach it.
self.task_timeout = webbench_task_timeout()
@@ -1404,8 +1404,7 @@ class WebBenchRunner:
# Scaffold provenance (rtk_installed / rtk_hook_registered / scaffold_error / ...).
# A failed install ran the task NATIVE, so these fields are what tells a real
# scaffold row from a baseline row wearing a scaffold's name -- filter on them
- # before quoting a scaffold arm's mean (docs/HARNESS.md, "External tool
- # scaffolds").
+ # before quoting a scaffold arm's mean.
if scaffold_notes:
row.update(scaffold_notes)
row["scaffold"] = self.scaffold.name
@@ -1898,7 +1897,7 @@ class CopilotWebBenchRunner(WebBenchRunner):
raise RuntimeError(
f"copilot refused this configuration: {bad}\n"
f" model={self.model!r} effort={self.effort!r}\n"
- " fix COPILOT_MODEL / TE_EFFORT_LEVEL (see docs/COPILOT.md step 2).")
+ " fix COPILOT_MODEL / TE_EFFORT_LEVEL.")
log_text = copilot.read_log_dir(logdir)
usage = copilot.row_usage("\n".join(stream_lines), log_text)
@@ -2115,7 +2114,7 @@ class CodexWebBenchRunner(WebBenchRunner):
ran and logged it, while a control command ran. Without the bypass Codex skips every
hook nobody has approved in /hooks, which an unattended run cannot do -- so arming
here is what turns the bypass on in `_segment`. The namespace hosts block stays the
- primary layer (docs/HARNESS.md, "The answer-key guard").
+ primary layer.
"""
self._net_guard_armed = bool(super()._install_net_guard(home, run_dir_path))
return self._net_guard_armed
@@ -2399,6 +2398,5 @@ def make_runner(agent=None, scaffold=None, **kwargs):
f"the {scaffold!r} baseline is not wired for Web-Bench "
f"(supported: {', '.join(sorted(WEBBENCH_SCAFFOLDS))}). Web-Bench runs the "
f"agent on the HOST with no per-task repo container, and the repo map "
- f"generates a PYTHON symbol map that a Node/TypeScript project does not have. "
- f"See docs/HARNESS.md, \"External tool scaffolds\".")
+ f"generates a PYTHON symbol map that a Node/TypeScript project does not have.")
return RUNNERS[agent](agent=agent, scaffold=scaffold, **kwargs)
diff --git a/experiments/tests/conftest.py b/experiments/tests/conftest.py
index 3cc58a8..1e1dbc0 100644
--- a/experiments/tests/conftest.py
+++ b/experiments/tests/conftest.py
@@ -1,7 +1,7 @@
"""pytest setup for the reproduction suite (experiments/tests).
-`experiments/` keeps the layout the experiments always had -- te_harness/, scripts/,
-workloads/, docs/ -- so a test's "repo root" (`_REPO` in the test files) is experiments/.
+`experiments/` holds te_harness/, te_bench/, scripts/ and workloads/, so a test's "repo
+root" (`_REPO` in the test files) is experiments/.
The shared core, `tokeneconomizer`, lives one level up at the repository root, and so do
the shared transcript writers (`fixtures`), with the plugin's own tests in tests/.
"""
diff --git a/experiments/tests/test_adapters.py b/experiments/tests/test_adapters.py
index 8b25540..66e2cc7 100644
--- a/experiments/tests/test_adapters.py
+++ b/experiments/tests/test_adapters.py
@@ -5,10 +5,10 @@ import pytest
from te_bench.adapters import (
DomainAdapter, SwebenchAdapter, WebBenchAdapter, CredDataAdapter,
- ReposVulAdapter, CyberGymAdapter, WebArenaAdapter)
+ ReposVulAdapter)
-ALL_CONCRETE = [SwebenchAdapter, CredDataAdapter, ReposVulAdapter, CyberGymAdapter]
+ALL_CONCRETE = [SwebenchAdapter, CredDataAdapter, ReposVulAdapter]
def test_swebench_is_domain_adapter():
@@ -20,8 +20,6 @@ def test_all_adapters_importable_and_named():
assert WebBenchAdapter("dom").name == "webbench"
assert CredDataAdapter().name == "creddata"
assert ReposVulAdapter().name == "reposvul"
- assert CyberGymAdapter().name == "cybergym"
- assert WebArenaAdapter().name == "webarena"
def test_swebench_reading_methods_delegate():
@@ -64,7 +62,3 @@ def test_creddata_classify_domain_differs():
assert SwebenchAdapter().classify_domain() is None
assert CredDataAdapter().classify_domain() is not None
-
-def test_webarena_stub_raises():
- with pytest.raises(NotImplementedError):
- WebArenaAdapter().load_trajectory("x")
diff --git a/experiments/tests/test_sweep_arms.py b/experiments/tests/test_sweep_arms.py
index 6cddfea..215a0fd 100644
--- a/experiments/tests/test_sweep_arms.py
+++ b/experiments/tests/test_sweep_arms.py
@@ -430,59 +430,88 @@ CODEX_PUBLISHED_ARMS = frozenset({
})
-def _doc(name):
+def _readme():
import os
repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- return open(os.path.join(repo, "docs", name)).read()
+ return open(os.path.join(repo, "README.md"), encoding="utf-8").read()
-def _section(text, start, end=None):
- i = text.index(start)
- return text[i:text.index(end, i + 1)] if end else text[i:]
-
-
-def _table_arms(sec):
- """The arm names a run-book table lists, one per row, in order."""
+def _launches():
+ """Each launcher call in the README's command blocks: (script, {VAR: value}), with the
+ block's own shell variables (`SWE="..."`, a loop's `$MODEL`) expanded the way bash would."""
import re
- return re.findall(r"^\| `([a-z0-9-]+)` \|", sec, re.M)
+ import shlex
+ out = []
+ for block in re.findall(r"```bash\n(.*?)```", _readme(), re.S):
+ text = re.sub(r"\\\n\s*", " ", block)
+ names = {}
+ for line in text.splitlines():
+ line = re.sub(r"#.*$", "", line).strip()
+ for loop in re.findall(r"for (\w+) in ([^;]+);", line):
+ names[loop[0]] = loop[1].split()[0]
+ if not re.search(r"scripts/launch/(main_sweep|codex_ab)\.sh", line):
+ for key, val in re.findall(r'^(\w+)="([^"]*)"$', line):
+ names[key] = val
+ continue
+ line = re.sub(r"^.*?\bdo\b\s*", "", line) if line.startswith("for ") else line
+ line = re.sub(r"\$(\w+)", lambda m: names.get(m.group(1), m.group(0)), line)
+ env = {}
+ for tok in shlex.split(line):
+ if "=" in tok and tok.split("=", 1)[0].isupper():
+ k, v = tok.split("=", 1)
+ env[k] = v
+ script = re.search(r"scripts/launch/(\w+)\.sh", line).group(1)
+ out.append((script, env))
+ return out
+
+
+def test_every_arm_the_readme_launches_is_registered_and_planned():
+ """An arm named in a command but absent from the registry is a doc promising something
+ nobody implemented; one absent from the plan gets "the plan is empty" at launch."""
+ launches = _launches()
+ assert {s for s, _ in launches} == {"main_sweep", "codex_ab"}, launches
+ for script, env in launches:
+ arms = env.get("ARMS", "").split()
+ assert arms, (script, env)
+ for arm in arms:
+ assert arm in RX.ARMS, f"the README launches {arm!r}, which is not registered"
+ if script == "main_sweep":
+ planned = set(SP.SWEEP_ARMS[env.get("DOMAIN", "swebench")])
+ assert set(arms) <= planned, f"{sorted(set(arms) - planned)} are not planned"
+ else:
+ assert set(arms) <= CODEX_PUBLISHED_ARMS, sorted(set(arms) - CODEX_PUBLISHED_ARMS)
-def _loop_arms(sec):
- """The arm names a run-book command block launches, through `ARMS=` or a `for ARM` loop."""
- import re
- names = set()
- for group in re.findall(r'ARMS="([a-z0-9\- ]+)"', sec):
- names |= set(group.split())
- for group in re.findall(r"for ARM in ([a-z0-9\- \\\n]+?);", sec):
- names |= set(group.replace("\\", " ").split())
- return names
+def test_every_readme_launch_uses_the_runner_of_its_domain():
+ """A Web-Bench command carrying the SWE-bench factory runs the wrong lifecycle against the
+ right ids; the launcher refuses it, but a reader would have copied it."""
+ import os
+ for script, env in _launches():
+ domain = env.get("DOMAIN", "swebench")
+ assert env.get("RUNNER") == f"te_harness.{domain}:make_runner", (script, env)
+ if "WORKLOAD" in env:
+ path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+ env["WORKLOAD"])
+ assert os.path.isfile(path), env["WORKLOAD"]
-# The run book's lanes: the Claude Code / Copilot section and the Codex section, each split
-# into one swebench and one webbench subsection.
-_GENERIC = ("## 4. Claude Code and Copilot", "## 5. Codex")
-_CODEX = ("## 5. Codex", "## 6.")
+def test_the_readme_arm_table_names_only_registered_arms():
+ import re
+ text = _readme()
+ table = text[text.index("| Arm | In the paper |"):]
+ table = table[:table.index("\n\n")]
+ named = set(re.findall(r"`([a-z0-9-]+)`", table)) - {"codex-trimech-"}
+ assert named, "no arms parsed out of the README's arm table"
+ for arm in named:
+ assert arm in RX.ARMS, f"the README's arm table lists {arm!r}, which is not registered"
def test_the_codex_lane_publishes_exactly_one_arm_per_mechanism():
- """Checked both ways, because both failures have happened here.
-
- Every published arm must appear in the catalog -- it drifted twice, once missing the
- effort baselines and once missing `repomap`. And every arm the catalog names must be
- registered and published: a doc promising an arm nobody implemented is one failure, a doc
- quietly re-offering a dropped ablation beside the mechanism it ablates is the other.
- """
- codex = _section(_doc("RUNNING.md"), *_CODEX)
- sb = _section(codex, "### swebench", "### webbench")
- named = set(_table_arms(sb))
- assert named == CODEX_PUBLISHED_ARMS, (
- f"catalog names {sorted(named)}, published set is {sorted(CODEX_PUBLISHED_ARMS)}")
- assert _loop_arms(sb) == named, "the swebench command launches a different arm set"
- wb = _section(codex, "### webbench")
- assert _loop_arms(wb) == set(_table_arms(wb)), "the webbench command and table disagree"
- invented = sorted(n for n in named | set(_table_arms(wb)) if n not in RX.ARMS)
- assert not invented, f"the catalog names arms that do not exist: {invented}"
- cfgs = {n: RX.ARMS[n].cfg() for n in named}
+ """Every published Codex arm is registered, and each mechanism has exactly one arm that
+ runs it alone -- a dropped ablation must not come back beside the mechanism it ablates."""
+ invented = sorted(n for n in CODEX_PUBLISHED_ARMS if n not in RX.ARMS)
+ assert not invented, f"published arms that do not exist: {invented}"
+ cfgs = {n: RX.ARMS[n].cfg() for n in CODEX_PUBLISHED_ARMS}
one = lambda mech: sorted(
n for n, c in cfgs.items()
if getattr(c, mech).enabled and not any(
@@ -492,83 +521,6 @@ def test_the_codex_lane_publishes_exactly_one_arm_per_mechanism():
assert one("spiral") == ["codex-spiral"]
-def test_every_arm_the_generic_lanes_launch_is_registered_and_planned():
- """The Claude Code and Copilot lanes launch through `main_sweep.sh`, which plans cells from
- `sweep_plan.SWEEP_ARMS`. An arm named in the book but absent from the plan gets "the plan is
- empty" at launch; one absent from the registry is a doc promising something nobody
- implemented."""
- generic = _section(_doc("RUNNING.md"), *_GENERIC)
- sb = set(_table_arms(_section(generic, "### swebench", "### webbench")))
- wb = set(_table_arms(_section(generic, "### webbench", "### The frontier lane")))
- assert sb, "no swebench arms parsed"
- for arm in sb | wb:
- assert arm in RX.ARMS, f"the run book lists {arm!r}, which is not registered"
- # the swebench catalog IS the planned set, and so is the webbench one
- assert sb == set(SP.SWEEP_ARMS["swebench"]), (
- f"swebench catalog {sorted(sb)} != plan {sorted(SP.SWEEP_ARMS['swebench'])}")
- assert wb == set(SP.SWEEP_ARMS["webbench"]), (
- f"webbench catalog {sorted(wb)} != plan {sorted(SP.SWEEP_ARMS['webbench'])}")
- frontier = _loop_arms(_section(generic, "### The frontier lane"))
- for arm in frontier:
- assert arm in RX.ARMS, f"the frontier lane launches unregistered arm {arm!r}"
-
-
-def test_each_lane_splits_its_commands_by_domain():
- """Both lanes present SWE-bench and Web-Bench as two separate subsections, each with its
- own table and its own command, so a reader can follow it top to bottom.
-
- The runner check is the other half -- a Web-Bench command carrying the SWE-bench factory
- runs the wrong lifecycle against the right ids, which the launcher refuses but a reader
- would have copied.
- """
- import re
- text = _doc("RUNNING.md")
- for lane in (_GENERIC, _CODEX):
- sec = _section(text, *lane)
- heads = [(m.start(), m.group(0)) for m in
- re.finditer(r"^### (swebench|webbench) — \d+ arms$", sec, re.M)]
- kinds = [("webbench" if "webbench" in h else "swebench") for _, h in heads]
- assert kinds == ["swebench", "webbench"], f"{lane[0]}: got {heads}"
- for i, (start, head) in enumerate(heads):
- body = sec.index("\n", start)
- nxt = re.search(r"^#{2,3} ", sec[body:], re.M)
- stop = body + nxt.start() if nxt else len(sec)
- sub = sec[start:stop]
- domain = kinds[i]
- entries = _table_arms(sub)
- assert entries and len(entries) == len(set(entries)), f"{lane[0]}/{domain}"
- claimed = int(re.search(r"(\d+) arms", head).group(1))
- assert claimed == len(entries), f"{head!r} but {len(entries)} entries"
- wrong = "swebench" if domain == "webbench" else "webbench"
- assert f"te_harness.{domain}:make_runner" in sub, f"{lane[0]}/{domain}"
- assert f"te_harness.{wrong}:make_runner" not in sub, f"{lane[0]}/{domain}"
-
-
-def test_the_harness_scaffold_table_names_every_arm_that_carries_each_scaffold():
- """docs/HARNESS.md maps scaffold -> arms. It is the table a reader consults to find out
- which arms need `aider` on the host or the staged rtk binary, so an arm missing from it
- reads as needing nothing. It went stale twice in one day, both times when a Codex
- sibling arm was added, so pin it against the registry rather than against a copy."""
- import re
- from te_bench import baselines
- text = _doc("HARNESS.md")
- table = text[text.index("| Scaffold | Arms |"):]
- table = table[:table.index("\n\n")]
- listed = {}
- for line in table.splitlines():
- cells = [c.strip() for c in line.split("|")]
- if len(cells) < 4 or not cells[1].startswith("`"):
- continue
- scaffold = cells[1].strip("`")
- listed[scaffold] = set(re.findall(r"`([a-z0-9-]+)`", cells[2]))
- assert listed, "no scaffold rows parsed out of docs/HARNESS.md"
- for scaffold, arms in listed.items():
- real = {a for a, s in baselines.ARM_SCAFFOLDS.items() if s == scaffold}
- assert arms == real, (
- f"HARNESS.md lists {scaffold!r} arms as {sorted(arms)}, "
- f"but ARM_SCAFFOLDS says {sorted(real)}")
-
-
def test_the_published_spiral_arm_is_the_defensive_profile():
"""The one that was approved, and the one both live cells ran.
@@ -587,15 +539,23 @@ def test_the_published_spiral_arm_is_the_defensive_profile():
assert RX.ARMS["codex-spiral-defensive"].cfg().spiral == sp
-def test_the_codex_lane_uses_the_whole_evaluated_workload_not_one_repo():
- """`codex_ab.sh` defaults to one repository, so the run book must name them all or a
- 6-repo sweep quietly becomes a 1-repo one."""
+def test_the_codex_lane_runs_the_whole_evaluated_workload_by_default():
+ """`codex_ab.sh` without REPOS plans every group of its workload, so the README's Codex
+ commands cannot quietly become a one-repository sweep."""
+ import os
+ import subprocess
from te_bench import workloads
- codex = _section(_doc("RUNNING.md"), *_CODEX)
- for group in workloads.task_counts("swebench"):
- assert group in codex, f"{group} is in the evaluated workload but not in the run book"
- for project in workloads.task_counts("webbench"):
- assert project in codex, f"{project} is an evaluated project but not in the run book"
+ repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ for domain in ("swebench", "webbench"):
+ env = dict(os.environ, DRYRUN="1", ARMS="baseline", DOMAIN=domain, RUNNER="stub",
+ TASKS_FILE=os.devnull, SEEDS="0",
+ TOKENECONOMIZER_ENV_FILE=os.path.join(repo, "no-such.env"))
+ env.pop("REPOS", None)
+ out = subprocess.run(["bash", os.path.join(repo, "scripts", "launch", "codex_ab.sh")],
+ env=env, capture_output=True, text=True, check=True).stdout
+ planned = {line.split("\t")[1] for line in out.splitlines()
+ if line.startswith(" baseline\t")}
+ assert planned == set(workloads.task_counts(domain)), (domain, planned)
def test_codex_trimech_rtk_is_codex_trimech_with_the_scaffold_and_nothing_else():
diff --git a/experiments/tests/test_vendor_cost.py b/experiments/tests/test_vendor_cost.py
index 7f2b9c5..e11af71 100644
--- a/experiments/tests/test_vendor_cost.py
+++ b/experiments/tests/test_vendor_cost.py
@@ -81,7 +81,7 @@ def test_does_not_flag_a_row_that_has_a_figure():
def test_does_not_flag_an_agent_that_never_reports_dollars():
# Copilot meters premium requests and Codex bills a subscription: null is the
- # documented normal case there (docs/COPILOT.md), not a defect.
+ # normal case there, not a defect.
for agent in ("copilot", "codex"):
row = _ran(agent=agent, cost_usd_vendor=None)
assert _agg().vendor_cost_missing(row)[0] is False, agent
diff --git a/experiments/tests/test_workloads.py b/experiments/tests/test_workloads.py
index 9c00d05..fafc775 100644
--- a/experiments/tests/test_workloads.py
+++ b/experiments/tests/test_workloads.py
@@ -303,3 +303,34 @@ def test_raising_the_ceiling_preserves_an_existing_node_options():
"NODE_OPTIONS": "--max-old-space-size=4096"})
assert extra["NODE_OPTIONS"].startswith("--max-old-space-size=4096 ")
assert "--import" in extra["NODE_OPTIONS"]
+
+
+def _export_swebench():
+ import importlib.util
+ import os
+ path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+ "scripts", "export_swebench_tasks.py")
+ spec = importlib.util.spec_from_file_location("export_swebench_tasks", path)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def test_the_swebench_export_writes_the_stream_in_order_and_prefers_verified():
+ """The task list follows the workload's stream order whatever order the splits come in,
+ a Verified row wins over the full split's, and grading carries the grader's fields."""
+ from te_bench import workloads
+ ex = _export_swebench()
+ order = [i for ids in workloads.runnable_instances("swebench").values() for i in ids]
+
+ def row(iid, tag):
+ r = {k: f"{tag}:{k}" for k in ex.GRADING_FIELDS}
+ r.update(instance_id=iid, repo=f"{tag}:repo", problem_statement=f"{tag}:issue")
+ return r
+ verified = [row(i, "verified") for i in reversed(order[::2])]
+ full = [row(i, "full") for i in order] + [row("not__evaluated-1", "full")]
+ tasks, grading = ex.build([verified, full], set(order))
+ assert [t["instance_id"] for t in tasks] == order == list(grading)
+ assert tasks[0]["problem_statement"] == "verified:issue"
+ assert tasks[1]["problem_statement"] == "full:issue"
+ assert set(grading[order[0]]) == set(ex.GRADING_FIELDS)
diff --git a/experiments/workloads/README.md b/experiments/workloads/README.md
deleted file mode 100644
index 54d7010..0000000
--- a/experiments/workloads/README.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# workloads/ — the exact evaluated task sets (committed)
-
-One JSON manifest per domain naming **which** tasks the published results ran. Unlike the
-results tree (regenerated per run, git-ignored), these are **committed**: they are ids only —
-no issue text, no transcripts — so all four together are about 16 KB.
-
-| File | Tasks | Groups | Seeds |
-|---|---|---|---|
-| `swebench.json` | 229 | 6 repos | `0 1 2` |
-| `webbench.json` | 102 | 5 projects | `A B C` |
-| `creddata.json` | 100 | 1 | `0 1 2` |
-| `reposvul.json` | 100 | 1 | `0 1 2` |
-
-## Shape
-
-```json
-{
- "domain": "swebench",
- "group_field": "repo",
- "seeds": [0, 1, 2],
- "total_tasks": 229,
- "task_counts": {"django/django": 40, "...": 0},
- "groups": {"django/django": ["django__django-7530", "..."]},
- "full_split_only": ["pydata__xarray-6386", "..."]
-}
-```
-
-`groups` preserves order. For Web-Bench that order is **load-bearing** — each task builds on
-the previous one's edits, so a stream must run front to back.
-
-`swebench.json` additionally carries `full_split_only`: the 30 instances that are **not** in
-SWE-bench_Verified and must come from the full `princeton-nlp/SWE-bench` test split.
-
-## Who reads them
-
-- **`scripts/launch/*.sh`** default `WORKLOAD` to `workloads/$DOMAIN.json` and pass it to the
- driver, so a launch is pinned to the evaluated set even if your `TASKS_FILE` holds more.
- `WORKLOAD=none` opts out.
-- **`scripts/run_experiment.py --workload`** filters `--tasks-file` to the manifest (and to
- `--repo`'s group). Unlike the legacy `--repo` prefix match, an unknown group is an error
- rather than a silent fall back to the whole task list.
-- **Any non-Python harness** that needs the list without importing the package.
-
-## Regenerating
-
-`experiments/te_bench/workloads.py` is the authority; these files are generated from it:
-
-```bash
-python scripts/export_workloads.py # rewrite
-python scripts/export_workloads.py --check # verify (exit 1 if stale)
-```
-
-`tests/test_workloads.py` runs the same comparison, so drift fails the test suite.
diff --git a/plugin/README.md b/plugin/README.md
index a3402b3..3495ede 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,21 +1,8 @@
# TokenEconomizer plugin
-Experience-driven black-box cost control for coding agents. In each repository it works in, it:
-
-* **injects what it learned (micro-skills).** Environment facts your sessions keep rediscovering
- the hard way ("`tox …` fails here with command not found; `python -m pytest …` works") are
- added to the next session's context.
-* **prunes tools you never use (tool pruning).** Tools that stay loaded but unused for several
- sessions are proposed as a deny list. You review it and apply it; nothing changes until you
- do. On Codex the unit is a capability package (sub-agents, goals, images); on the Copilot CLI
- it is a whole MCP server.
-* **redirects a turn stuck in a failing loop (loop guard).** When a turn keeps repeating the
- same failing edit/test cycle well past what this repository's turns usually take, the agent
- gets one mid-turn redirect.
-
-Every hook fails open, the plugin's actions are announced in one line, and by default it makes
-no model calls of its own. All of its state stays on your machine, under `~/.tokeneconomizer`.
-Design, verified agent behaviour and limits: [`docs/PLUGIN.md`](../docs/PLUGIN.md).
+How to install and use TokenEconomizer in Claude Code, Codex, the GitHub Copilot CLI and Pi. What
+the plugin does and why is in the [main README](../README.md); its design and the verified
+behaviour of each agent are in [`docs/PLUGIN.md`](../docs/PLUGIN.md).
- [Before you start](#before-you-start)
- Install and use it on [Claude Code](#claude-code) · [Codex](#codex) ·
diff --git a/pyproject.toml b/pyproject.toml
index 7ddefe9..2f41947 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,7 +26,7 @@ te = "tokeneconomizer.plugin.cli:main"
# Test suite is offline (no Docker / no datasets).
test = ["pytest>=7.0"]
# The reference task-execution harness under experiments/te_harness/ (see
-# experiments/docs/HARNESS.md). It adds no
+# experiments/README.md). It adds no
# PyPI dependency -- it is stdlib-only at import time and the official SWE-bench grader is
# imported lazily from a checkout named by TE_SWEBENCH_REPO -- so this extra installs
# nothing. It exists to give "I intend to run the harness" a name, since what the harness
diff --git a/tokeneconomizer/loopguard/README.md b/tokeneconomizer/loopguard/README.md
index aa5cc66..d7f175e 100644
--- a/tokeneconomizer/loopguard/README.md
+++ b/tokeneconomizer/loopguard/README.md
@@ -1,8 +1,7 @@
# Loop guard
-Failure-loop intervention. A prompt-turn that keeps repeating the same failing edit-and-test
-cycle is redirected once, mid-turn; if it keeps failing, it is stopped (headless) or the person
-is told (interactive).
+How the failure-loop guard (see the [main README](../../README.md)) decides, one tool call at a
+time.
Per tool call, `turn.TurnGuard`:
diff --git a/tokeneconomizer/microskills/README.md b/tokeneconomizer/microskills/README.md
index 9e567e3..ca841d7 100644
--- a/tokeneconomizer/microskills/README.md
+++ b/tokeneconomizer/microskills/README.md
@@ -1,9 +1,6 @@
# Micro-skills
-Short repository facts, learned from finished sessions and stated at the start of the next one.
-An agent that fails at the same environment detail session after session -- the test runner is
-missing, the interpreter needs a path, a label needs a different prefix -- is told the working
-form up front.
+How micro-skills (see the [main README](../../README.md)) are learned, kept and injected.
Each finished session goes through three steps:
diff --git a/tokeneconomizer/plugin/README.md b/tokeneconomizer/plugin/README.md
index 768dde4..ba26484 100644
--- a/tokeneconomizer/plugin/README.md
+++ b/tokeneconomizer/plugin/README.md
@@ -4,13 +4,8 @@ What the plugin's hooks and the `te` command run. The agent launches itself; thi
only when the agent calls a hook, each call a fresh process, so what is learned lives on disk and
every handler returns fast and fails open.
-| Hook | What happens (`controller.py`) |
-|---|---|
-| SessionStart | inject the repository's micro-skills; mention a pending deny-list proposal; fold any earlier session whose end was missed |
-| UserPromptSubmit | open a prompt-turn for the loop guard |
-| PostToolUse / PostToolUseFailure | fold the call into the turn's guard; redirect or stop when it says so |
-| Stop | close the turn; a turn that ended green feeds the envelope |
-| SessionEnd | fold the session in a detached `te fold` |
+What happens at each hook, and how each agent was verified to behave, is in
+[`docs/PLUGIN.md`](../../docs/PLUGIN.md); `controller.py` implements it.
| Module | |
|---|---|
diff --git a/tokeneconomizer/toolprune/README.md b/tokeneconomizer/toolprune/README.md
index bce9f86..c6bc1e5 100644
--- a/tokeneconomizer/toolprune/README.md
+++ b/tokeneconomizer/toolprune/README.md
@@ -1,8 +1,6 @@
# Tool pruning
-Every tool definition an agent loads is re-sent with every request. Tool pruning watches which
-loaded tools a repository's sessions actually use, and proposes dropping the ones that go unused
-session after session.
+How tool pruning (see the [main README](../../README.md)) decides what to drop, per agent.
- **Evidence pruning** (Claude Code, Copilot CLI; `stage.ToolingStage`). After each session, a
loaded tool's unused streak grows or resets. A tool is proposed once its streak reaches