Skip to content

Experience-Driven Black-Box Cost Control for Coding Agents

Migrate the plugin from main

Aaron40b92d611099
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index fbc93c0..fb76a9a 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -3,12 +3,12 @@
"owner": {
"name": "TokenEconomizer authors"
},
- "description": "TokenEconomizer: runtime cost control for coding agents.",
+ "description": "TokenEconomizer: experience-driven black-box cost control for coding agents.",
"plugins": [
{
"name": "tokeneconomizer",
"source": "./plugin",
- "description": "Learned per-repo facts at session start, approved unused-tool deny lists, and a spiral guard for failing loops."
+ "description": "Micro-skills learned per repository, tool pruning through a deny list you approve, and a failure-loop guard."
}
]
}
diff --git a/.gitignore b/.gitignore
index 256833d..4d65330 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,6 +27,9 @@ experiments/figures/
*.png
*.pdf
*.svg
+# ...except the figures the README and docs show.
+!docs/assets/*.png
+!docs/assets/*.svg
# Aggregated tables derived from results/.
*.csv
@@ -37,3 +40,6 @@ experiments/figures/
.env.*
!.env.example
*.key
+
+# Pi installs this repository as a package and runs `npm install` in its checkout.
+/package-lock.json
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..23e7a69
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,41 @@
+# TokenEconomizer
+
+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.
+
+## Layout
+- `tokeneconomizer/` — the one Python package, standard library only
+ - `microskills/` — learn repository facts from finished sessions; render the injected block
+ - `toolprune/` — unused-tool evidence and the deny-list proposal; Codex capability packages
+ - `loopguard/` — the per-call failure-loop guard and its per-repository envelope
+ - `trace/` — each agent's session-log format (Claude Code, Codex, Copilot CLI, Pi)
+ - `plugin/` — the runtime: hook dispatch, per-repository state, settings, the `te` CLI
+ - `config.py`, `ledger.py`, `pricing.py`, `domain.py`, `stage.py` — shared by all three
+- `plugin/` — the installable plugin directory: manifests per agent, hook files, launchers
+ (`scripts/te`, `scripts/te-hook`), slash commands, Codex 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/`
+- `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
+- `tests/` — offline tests for the package and the plugin
+
+## Conventions
+- The mechanisms (`microskills`, `toolprune`, `loopguard`, `trace`) never import
+ `tokeneconomizer.plugin`, and nothing under `tokeneconomizer/` imports `experiments/`; both
+ are pinned by `tests/test_plugin_package.py`.
+- Standard library only, Python >= 3.10. A hook must start fast and fail open: any exception in
+ a hook becomes `{}` and a line in `~/.tokeneconomizer/errors.log`.
+- On-disk state names (`injection.json`, `untool.json`, `envelope.json`, event kinds) are a
+ compatibility surface; renaming them strands what users have learned.
+- Settings keep their earlier names as aliases (`inject`, `untool`, `spiral`, ...; see
+ `plugin/config.py`); write new code against the current names.
+- No measured results in the repository: run outputs, figures from runs and tables stay out of
+ git (`.gitignore`), and shipped text makes no claims of effect.
+- Tests: `python -m pytest tests experiments/tests`. A change to what the plugin learns or
+ decides should be checked against recorded sessions, not only the unit tests.
+- Every model-backed test goes through the agent's own CLI on a provider you control
+ (OpenRouter in development); never hard-code a key.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..9e841e7
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+ MIT License
+
+ Copyright (c) Microsoft Corporation.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE
diff --git a/README.md b/README.md
index 1fe2ad8..64353f2 100644
--- a/README.md
+++ b/README.md
@@ -1,130 +1,168 @@
-# TokenEconomizer
+# TokenEconomizer: Experience-Driven Black-Box Cost Control for Coding Agents
+
+<p align="center">
+ Aaron J. Li<sup>1</sup>,
+ Weijia Xu<sup>2</sup>,
+ Chandan Singh<sup>2</sup>,
+ Zixiao Chen<sup>3</sup>,
+ Jeevana Priya Inala<sup>2</sup>,
+ Charlotte Siska<sup>3</sup>,
+ <br>
+ Acar Tamersoy<sup>3</sup>,
+ Bin Yu<sup>1</sup>,
+ Ion Stoica<sup>1</sup>,
+ Michel Galley<sup>2</sup>,
+ Jianfeng Gao<sup>2</sup>
+</p>
+<p align="center">
+ <sup>1</sup>UC Berkeley &nbsp; <sup>2</sup>Microsoft Research &nbsp; <sup>3</sup>Microsoft Security
+</p>
+
+<p align="center">
+ <a href="https://arxiv.org/abs/XXXX.XXXXX"><img src="https://img.shields.io/badge/arXiv-XXXX.XXXXX-b31b1b.svg" alt="arXiv"></a>
+ <a href="https://tokeneconomizer.github.io"><img src="https://img.shields.io/badge/project-page-2f6fb0.svg" alt="Project page"></a>
+ <img src="https://img.shields.io/badge/python-3.10%2B-3776ab.svg" alt="Python 3.10+">
+ <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT license">
+</p>
+
+<p align="center"><img src="docs/assets/framework_overview.png" width="100%" alt="TokenEconomizer: the plugin keeps what it knows about a repository and applies micro-skills, tool pruning and failure-loop intervention to your unchanged coding agent; each finished session's log updates all three"></p>
+
+TokenEconomizer is a plugin for **Claude Code**, **Codex**, the **GitHub Copilot CLI** and
+**Pi**. It leaves the agent as it is, reads each finished session in a repository, and changes
+what the next sessions in that repository pay for:
+
+- **Micro-skills.** Environment facts your sessions keep rediscovering by failing at them --
+ that `pytest` is missing here and `python -m pytest` works, that the test runner wants labels
+ without a `tests.` prefix -- are learned from recurring evidence and stated at the start of
+ the next session. Learning them makes no model call.
+- **Tool pruning.** Tools that stay loaded but go unused, session after session, are proposed
+ as a deny list. Nothing changes until you approve it, and it applies from the next session.
+- **Failure-loop intervention.** A turn that keeps repeating the same failing edit-and-test
+ cycle, well past how long this repository's turns usually take, gets one redirect, then a
+ stop (headless) or a notice.
+
+Each mechanism can be switched off or tuned on its own. The plugin's actions are announced in
+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`.
+
+## Supported agents
-Runtime cost control for coding agents, from outside the agent. TokenEconomizer is a plugin
-for **Claude Code**, **Codex**, the **GitHub Copilot CLI** and **Pi**. It watches your sessions
-in each repository and, from one session to the next, targets three kinds of token waste:
-
-| Mechanism | What it does | Setting |
-|---|---|---|
-| **Learned facts** | Environment facts your sessions keep rediscovering the hard way (for example, that `tox` is missing here and `python -m pytest` works) are added to the next session's context. | `inject` |
-| **Unused-tool deny list** | Tools that stay loaded but go unused for several sessions are proposed as a deny list. Nothing changes until you apply it. | `untool` |
-| **Stuck-turn guard** | A turn that keeps repeating the same failing edit-and-test cycle, well past how long this repository's turns usually take, gets one mid-turn redirect. | `spiral` |
+| Agent | Install |
+|---|---|
+| Claude Code | `claude plugin marketplace add /path/to/TokenEconomizer`<br>`claude plugin install tokeneconomizer@tokeneconomizer` |
+| Codex | `codex plugin marketplace add /path/to/TokenEconomizer`<br>`codex plugin add tokeneconomizer@tokeneconomizer`, then trust its hooks when Codex asks |
+| Copilot CLI | `copilot plugin marketplace add /path/to/TokenEconomizer`<br>`copilot plugin install tokeneconomizer@tokeneconomizer` |
+| Pi | `pi install git:github.com/microsoft/TokenEconomizer` |
-Each mechanism can be turned off or tuned on its own ([Settings](#settings)). Every action is
-announced in one line, every hook fails open, and by default the plugin makes no model calls of
-its own. What it learns stays on your machine, under `~/.tokeneconomizer`.
+**Any plan or login works.** The plugin runs inside your agent's own sessions and never handles
+credentials, so it works with whatever your agent is signed in with: a Claude subscription or an
+Anthropic API key for Claude Code, a ChatGPT plan or an OpenAI API key for Codex, a Copilot
+subscription or a bring-your-own-key provider for the Copilot CLI, and any provider Pi is set up
+with. It needs no API key of its own.
-## Install
+Claude Code, Codex and the Copilot CLI install from a clone of this repository, through their
+own plugin commands; Pi installs the package straight from GitHub, as any Pi package does. You
+need Python 3.10 or newer on `PATH`, and nothing else. Plugins load when a session starts, so
+start a new one. **[`plugin/README.md`](plugin/README.md)** walks through each agent: the first
+run, its commands, updating, uninstalling, Copilot with your own model key, and troubleshooting.
-You need Python 3.10 or newer on `PATH`. Clone the repository:
+## Quick start
```bash
git clone https://github.com/microsoft/TokenEconomizer.git
+claude plugin marketplace add ./TokenEconomizer
+claude plugin install tokeneconomizer@tokeneconomizer
```
-Then install it into your agent (use the path of your clone):
-
-| Agent | Install |
-|---|---|
-| Claude Code | `claude plugin marketplace add /path/to/TokenEconomizer`<br>`claude plugin install tokeneconomizer@tokeneconomizer` |
-| Copilot CLI | `copilot plugin marketplace add /path/to/TokenEconomizer`<br>`copilot plugin install tokeneconomizer@tokeneconomizer` |
-| Codex | `python /path/to/TokenEconomizer/scripts/build_plugin.py --out ~/te-marketplace`<br>`codex plugin marketplace add ~/te-marketplace`<br>`codex plugin add tokeneconomizer@tokeneconomizer`<br>then approve its hooks once in `/hooks` inside Codex |
-| Pi | `pi install /path/to/TokenEconomizer/plugin` |
-
-Plugins load when a session starts, so start a new one. On Claude Code and the Copilot CLI, run
-`/tokeneconomizer:untool refresh-catalog` once in each repository (Copilot from a terminal:
-`~/.tokeneconomizer/bin/te --host copilot untool refresh-catalog`); without it the deny list
-cannot see the tools every session loads.
+Then, in a new Claude Code session inside one of your repositories:
-**[`plugin/README.md`](plugin/README.md)** walks through the first run on each agent, updating
-and uninstalling, using Copilot with your own model key, and troubleshooting.
-
-## Use
+```text
+/tokeneconomizer:toolprune refresh-catalog # once on this machine: record the tools a session loads
+```
-Work as usual; the plugin needs nothing from you. To see what it is doing, in Claude Code or
-the Copilot CLI's interactive mode:
+Work as usual; the plugin needs nothing from you. To see what it is doing:
| Command | What it shows or does |
|---|---|
| `/tokeneconomizer:status` | what it learned in this repository, what it did, and what your sessions cost |
-| `/tokeneconomizer:facts` | the facts it injects at session start, and those still forming |
-| `/tokeneconomizer:untool` | the proposed deny list and its evidence; `… apply` accepts it, `… restore` undoes it |
+| `/tokeneconomizer:microskills` | the facts it injects at session start, and those still forming |
+| `/tokeneconomizer:toolprune` | the proposed deny list and its evidence; `… apply` accepts it, `… restore` undoes it |
| `/tokeneconomizer:config` | the settings: what is on, and every value in effect |
-On Codex, run the same commands from a terminal inside the repository, as
-`~/.tokeneconomizer/bin/te --host codex <command>` (for example `… untool apply`). On Pi they
-are `/te <command>`.
+On Codex, ask for them or name the skill (`$tokeneconomizer-status`, `-microskills`,
+`-toolprune`, `-config`); on Pi they are `/te <command>`. On any agent they are also free from a
+terminal inside the repository, as `~/.tokeneconomizer/bin/te <command>`.
## Settings
-Turn a mechanism on or off, in this repository or, with `--global`, in all of them:
-
```text
-/tokeneconomizer:config set spiral=off
-/tokeneconomizer:config set untool=off inject=on
+/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
```
-Tune one by hand:
-
-```text
-/tokeneconomizer:config set inject_max_facts=2 # inject at most two facts
-/tokeneconomizer:config set untool_evidence=10 # wait ten unused sessions before proposing
-/tokeneconomizer:config set spiral_nudges=2 # allow two redirects per turn
-/tokeneconomizer:config set spiral.min_turns=30 # let a turn run 30 tool calls before it can count as stuck
-/tokeneconomizer:config unset spiral.min_turns # back to the default
-```
-
-`/tokeneconomizer:config` shows every value in effect. Every setting, its default, and how to
-set one for a single session: [Settings in `plugin/README.md`](plugin/README.md#settings).
+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.
## What it does on each agent
-| | Learned facts | Unused-tool deny list | Stuck-turn guard |
+| | Micro-skills | Tool pruning | Loop guard |
|---|---|---|---|
| Claude Code | at session start | tools, in `.claude/settings.local.json` | redirect; can stop a headless turn |
| Codex | at session start | capability packages, in the project's `.codex/config.toml` | redirect, then a notice |
| Copilot CLI | at session start | whole MCP servers, in `.github/copilot/settings.local.json` | redirect, then a notice |
| Pi | at session start | — (Pi loads four tools) | redirect; can stop a headless turn |
-Nothing is written to your settings until you approve it, and `untool restore` removes only
-what the plugin added. The design, and how each agent's hooks and settings were verified to
-behave, are in **[`docs/PLUGIN.md`](docs/PLUGIN.md)**.
+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)**.
-## Repository layout
+## Repository
+| | |
+|---|---|
+| [`tokeneconomizer/microskills`](tokeneconomizer/microskills/) | Micro-skill synthesis and injection: facts learned from finished sessions |
+| [`tokeneconomizer/toolprune`](tokeneconomizer/toolprune/) | Tool pruning: unused tools and Codex capability packages |
+| [`tokeneconomizer/loopguard`](tokeneconomizer/loopguard/) | Failure-loop intervention: the per-call guard and its per-repository envelope |
+| [`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) |
+| [`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
+`experiments/tests` for the benchmark side), and build a self-contained plugin bundle with
+`python3 scripts/build_plugin.py --out dist/marketplace`.
+
+## 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/`.
+
+## Citation
+
+```bibtex
+@article{li2026tokeneconomizer,
+ title = {{TokenEconomizer}: Experience-Driven Black-Box Cost Control for Coding Agents},
+ author = {Li, Aaron J. and Xu, Weijia and Singh, Chandan and Chen, Zixiao and
+ Inala, Jeevana Priya and Siska, Charlotte and Tamersoy, Acar and Yu, Bin and
+ Stoica, Ion and Galley, Michel and Gao, Jianfeng},
+ journal = {arXiv preprint arXiv:XXXX.XXXXX},
+ year = {2026}
+}
```
-plugin/ the installable plugin: manifests and hook files per agent, the Pi
- extension, launchers, slash commands
-te_live/ the live harness the plugin runs: hook dispatch, per-repository state,
- host adapters, the `te` command line
-tokeneconomizer/ the shared core: the three mechanisms, the trace reader, the cost ledger
- (stdlib-only, no dependencies)
-tests/ offline tests for the plugin and the core
-docs/ PLUGIN.md (design and verified agent behaviour), METHOD.md (the method
- and the core's seams)
-scripts/ build_plugin.py: a self-contained bundle for marketplace installs
-experiments/ the paper's reproduction code (see below)
-```
-
-## Development
-
-Python ≥ 3.10, no runtime dependencies. Run the plugin and core tests with
-`python -m pytest tests`, or `python -m pytest` to include the experiments' suite. Build an
-installable bundle with `python scripts/build_plugin.py --out dist/marketplace`.
-
-## Reproducing the paper
-
-The benchmark experiments behind the research — the Docker harness that runs sealed agents on
-SWE-bench and Web-Bench, the sweep and aggregation pipeline, the evaluated task sets, and the
-run book — live in **[`experiments/`](experiments/README.md)**. They are separate
-from the plugin and not packaged with it; they share only the core in `tokeneconomizer/`.
-
-The same research code in its original layout, without the plugin, is on the
-[`paper`](https://github.com/microsoft/TokenEconomizer/tree/paper) branch.
-
-## Limitations
-TokenEconomizer was developed for research and experimental purposes. Further testing and validation are needed before considering its application in commercial or real-world scenarios.
-There has not been a systematic effort to ensure that systems using TokenEconomizer are protected from security vulnerabilities such as indirect prompt injection attacks. Content in a repository, issue text, or tool output could influence a synthesized micro-skill that persists across later tasks. Any systems using it should take proactive measures to harden their systems as appropriate.
+## License
-Downstream developers remain responsible for ensuring that the underlying coding agent, its tool permissions, execution sandbox, generated code, and deployment environment are appropriate to their use case.
+MIT; see [`LICENSE`](LICENSE).
diff --git a/docs/METHOD.md b/docs/METHOD.md
index 45ccb69..20acac6 100644
--- a/docs/METHOD.md
+++ b/docs/METHOD.md
@@ -2,79 +2,81 @@
## Thesis
-Hold the **sealed agent fixed** (Claude Code, Copilot CLI, Codex) and make the
-**environment learn a cheaper interface to itself**, so the agent solves tasks at lower
-token cost with **no regression in task success**. The optimization is delivered
-**externally** (no agent changes) and must **transfer across agents**.
+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 we optimize is amortized over a **stream** of tasks on one repository, not any
-single task. Some mechanism cost is paid once (a between-task proposer tick) and reused by
-every later task, so the metric is the **amortized accuracy–cost curve** over the stream,
-not per-task overhead in isolation.
+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 (learned empirically)
+## 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.
-- **Displacement is hard.** Sealed agents under-adopt nudged tools; prefer environment-side
- levers the agent already uses over ones it must opt into.
-- **Cache-aware cost or nothing.** Most raw tokens in an agent session are cached re-reads,
- so comparing on `tokens_total` flatters methods that prune cheap re-reads. Everything is
- measured on `pricing.effective_tokens + ledger.overhead`.
-- **Resolve is a hard guardrail.** A cheaper arm that loses task success is not shipped. The
- spiral finalize/abort rules are gated to be resolve-safe by construction.
+ 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 in a task's lifecycle and is independently switchable:
-
-| Mechanism | Lifecycle point | What it does |
-|---|---|---|
-| **injection** | before the task | Inject a firing-gated, learned per-repo operating manual (canonical test command, "a repro is redundant", required env var, …). Two layers share one lifecycle: an LLM-free environment-fact layer (`envfacts`: recurring failure→repair shapes, refused hosts, empty probes; vocabulary from the domain adapter) and a paid proposer that authors open-vocabulary facts + extractors over a compact digest. Profiles `distiller` (Claude/Copilot default), `envfacts` (Codex default, no paid call) and `envfacts+distiller` (both; the proposer is told what is already injected). A validated lifecycle (formation / decay / firing gate) keeps only facts that actually fire. |
-| **tooling** | at task construction | Drop inapplicable tool schemas. Generic: evidence untooling (drop a tool loaded-but-unused for N tasks) + an optional per-task instruction-aware judge. Codex-native: remove whole inapplicable capability packages from the request contract, evidence-gated and resolve-safe. |
-| **spiral** | in flight / at finalize | Kill or nudge a stuck rollout against a learned per-repo resolved-turn envelope. Generic: cheap gate → sampled LLM judge → nudge-then-abort. Codex-native: one same-thread finalize nudge once a trustworthy green passes and every failed scope is cleared. |
-
-## The two seams that keep the core self-contained
-
-The mechanisms are harness- and domain-agnostic. Everything environment-specific enters
-through two small, named surfaces:
-
-### 1. Trajectory + cost — vendored, stdlib-only
-
-- `tokeneconomizer.trace` — the ONE place a saved rollout transcript is read
- (`load_trajectory` / `tool_usage` / `detect` / `parse_catalog`); auto-detects the
- supported agent transcript schemas.
-- `tokeneconomizer.ledger` — the ONE definition of amortized cost, over the vendored
- `pricing` table. Mechanisms write per-task overhead fields; aggregation reads them back
- through the same module, so emitted and reported ledgers cannot drift.
-- `tokeneconomizer.vendor` — `pricing` / `reflect` / `spiral`, copied in verbatim
- (stdlib-only), so `import tokeneconomizer` needs no external benchmark tree.
-
-### 2. Execution + domain — behind interfaces
-
-- `tokeneconomizer.runner.AgentRunner` — the seam to the task-execution harness. The
- economizer never launches Docker, calls an LLM API, or shells out to an agent CLI itself;
- it needs only (a) a paid **optimizer call** for the proposer/judge/nudge, and (b) an
- optional **task executor**. A concrete Docker + CLI + gold-grading runner is an external
- plugin (see [`experiments/`](../experiments/README.md)), with image/dataset paths as
- placeholders.
-- `tokeneconomizer.adapters.DomainAdapter` — the seam to the task domain. The mechanisms
- read the domain only through this (trajectory reading, waste signals, untool tool-sets,
- spiral snapshot, per-task issue text). A new benchmark = a new adapter, no mechanism
- edits. Ships with SWE-bench (canonical), Web-Bench, CredData, ReposVul, CyberGym, and a
- WebArena stub; dataset roots are env-var placeholders.
-
-## Entry point
+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 tokeneconomizer import Economizer, EconomizerConfig
+from te_bench.facade import Economizer
econ = Economizer.from_args(args, repo=repo, results_root=root, fresh=True,
- runner=my_runner) # my_runner: AgentRunner or optimizer callable
+ 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 via the runner with those decisions ...
+# ... 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 376dc79..df8faca 100644
--- a/docs/PLUGIN.md
+++ b/docs/PLUGIN.md
@@ -7,13 +7,13 @@ Copilot CLI and Pi — through the hooks (or, on Pi, the extension events) the a
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 `te_live/` (the live harness: the session-oriented controller,
-a sibling of `experiments/te_harness/`) and `plugin/` (the host packaging).
+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. To see what the plugin would do on your own history before
-> turning anything on, run `te replay` (§4).
+> differs in the ways listed in §2. Each mechanism can be switched off on its own (§5).
---
@@ -21,23 +21,24 @@ a sibling of `experiments/te_harness/`) and `plugin/` (the host packaging).
| Hook | What the plugin does | Mechanism it drives |
|---|---|---|
-| `SessionStart` | Injects the repository's learned manual (a cached render) as `additionalContext`; announces a changed manual or a new untool proposal in one `systemMessage` line; folds any earlier session whose end was never seen | injection |
-| `UserPromptSubmit` | Opens a prompt-turn for the spiral guard | spiral |
-| `PostToolUse` | Folds the call into the turn's guard; delivers a nudge as `additionalContext`, or stops the turn | spiral |
-| `Stop` | Closes the turn; a turn that *ended green* feeds the per-repository envelope | spiral |
-| `SessionEnd` | Hands the session to a detached `te fold` and returns at once | injection, untooling, ledger |
+| `SessionStart` | Injects the repository's micro-skills (a cached render) as `additionalContext`; announces changed facts or a new deny-list proposal in one `systemMessage` line; folds any earlier session whose end was never seen | microskills |
+| `UserPromptSubmit` | Opens a prompt-turn for the loop guard | loopguard |
+| `PostToolUse` | Folds the call into the turn's guard; delivers a nudge as `additionalContext`, or stops the turn | loopguard |
+| `PostToolUseFailure` | The same, for a call that failed (Claude Code and Copilot report a failed call only here) | loopguard |
+| `Stop` | Closes the turn; a turn that *ended green* feeds the per-repository envelope | loopguard |
+| `SessionEnd` | Hands the session to a detached `te fold` and returns at once | microskills, toolprune, ledger |
`te fold` runs the **same classes the experiments ran** over the finished session's log:
`PrefixStage` (envfacts, plus the paid proposer when allowed) and `ToolingStage` (evidence
-untooling). The spiral guard (`te_live/guard.py`) is `vendor.spiral.NudgeGuard`'s control flow —
-`SpiralState.update`, `assess_abort`, `is_stuck`, `nudge_text`, the cumulative backstop — one
-tool call at a time. None of the thresholds were re-tuned. Three things it adds:
+pruning). The loop guard (`loopguard.TurnGuard`) is the benchmark harness's `NudgeGuard` control
+flow — `SpiralState.update`, `assess_abort`, `is_stuck`, `nudge_text`, the cumulative backstop —
+one tool call at a time. None of the thresholds were re-tuned. Three things it adds:
* It counts **edits made through the shell**: `sed -i`, `perl -pi`, a redirect or `tee` into a
- source file, an inline Python script that writes a file back, `patch`/`git apply`. The vendored
+ source file, an inline Python script that writes a file back, `patch`/`git apply`. The loop
state counts only edit tools, and agents that edit through Bash then looked as if they had
edited nothing.
-* **The nudge always comes before the stop.** The vendored ladder checks a hard backstop (a
+* **The nudge always comes before the stop.** The benchmark ladder checks a hard backstop (a
multiple of the learned envelope: 2.5 × at the default level, 1.8 × at `aggressive`) before
anything else. With the large envelopes of the benchmark streams, the backstop lay well past
the stuck rule's own floor (20 calls at the default level, 14 at `aggressive`), and the nudge
@@ -56,14 +57,14 @@ Every hook fails open: any error becomes an empty output (no change) and a trace
| | Experiments | Plugin | Why |
|---|---|---|---|
-| Unit of work | one benchmark task | a **session** for injection and untooling; a **prompt-turn** for the spiral guard | In interactive use a person already splits work into short turns. A whole session folded as one trajectory would look stuck merely by being long |
-| Learning signal | the official grader's `resolved` | the envelope learns from turns that **ended green**: the agent stopped on its own, was not stopped by the guard, and no verification after its last edit failed | There is no grader. Injection and evidence untooling never needed one |
+| Unit of work | one benchmark task | a **session** for micro-skills and tool pruning; a **prompt-turn** for the loop guard | In interactive use a person already splits work into short turns. A whole session folded as one trajectory would look stuck merely by being long |
+| Learning signal | the official grader's `resolved` | the envelope learns from turns that **ended green**: the agent stopped on its own, was not stopped by the guard, and no verification after its last edit failed | There is no grader. Micro-skills and evidence pruning never needed one |
| Injection channel | a prefix on the task prompt | `SessionStart` `additionalContext` | Verified to reach the model (§3) |
| Tool removal | `--disallowed-tools` / Codex config at launch | a **deny list you approve**, written to the repository's own settings file — tools in `.claude/settings.local.json`, Codex capability packages in `.codex/config.toml`, Copilot MCP servers in `.github/copilot/settings.local.json` — effective from the **next** session | The plugin launches nothing. Tools are fixed at session start, and changing them mid-session would re-write the cached prompt prefix. Each agent's file can express a different unit (§3) |
-| Untool candidates | `reflect.INAPPLICABLE_TOOLS` — orchestration, Q&A, plan mode, web — "inapplicable by construction" for a sealed headless task | nothing is inapplicable by construction; only **evidence** (loaded but unused for N sessions) proposes a tool, and a person's tools — AskUserQuestion, plan mode, sub-agents, the web — are protected | A person asks questions, plans and browses in a real session. A deny rule the plugin wrote for a tool that has since become protected is given back at the next fold |
+| Pruning candidates | `toolprune.tools.INAPPLICABLE_TOOLS` — orchestration, Q&A, plan mode, web — "inapplicable by construction" for a sealed headless task | nothing is inapplicable by construction; only **evidence** (loaded but unused for N sessions) proposes a tool, and a person's tools — AskUserQuestion, plan mode, sub-agents, the web — are protected | A person asks questions, plans and browses in a real session. A deny rule the plugin wrote for a tool that has since become protected is given back at the next fold |
| Network | every arm, baseline included, carries an answer-key guard — a `PreToolUse` hook and an `/etc/hosts` block refuse the benchmarks' upstream sources — and drops the web tools | **no guard**: no `PreToolUse` hook (on Pi, no `tool_call` handler), no blocked command or host; the web tools stay | A benchmark's answer is a fetch away. A real session has no answer key, and the web is part of the work |
| Nudge | kill the agent, resume it with a continuation prompt | a mid-turn reminder attached to the tool result | Different intervention, so its effect is not inherited from the experiments |
-| Abort | terminal, in autonomous runs | a `continue: false` stop only in **headless** sessions with `spiral: guard`; in an interactive session, a one-line notice — the person is already the abort | The vendored module says so itself: "interactive callers should map it to a hand-off" |
+| Abort | terminal, in autonomous runs | a `continue: false` stop only in **headless** sessions with `loopguard: stop`; in an interactive session, a one-line notice — the person is already the abort | The benchmark guard's own design note: "interactive callers should map it to a hand-off" |
| Optimizer model | the agent's own model, so overhead could not look cheaper than its arm | the cheapest capable model on the user's own agent CLI (`paid_model`, default `haiku`), and only when `paid` is on | Every paid call is still charged to the session ledger |
## 3. Verified agent behaviour
@@ -83,14 +84,19 @@ and date it was verified on; §7 says what has not been exercised.
* A bare-name `permissions.deny` rule **removes the tool from the session's tool list**, the same
list `--disallowed-tools` produces, whether the rule comes from `--settings` or from a
project's `.claude/settings.local.json`. A plugin's own `settings.json` cannot carry deny rules
- (only `agent` and `subagentStatusLine` take effect), which is why the untool writer edits the
+ (only `agent` and `subagentStatusLine` take effect), which is why the deny-list writer edits the
project-local file, with approval.
* An interactive transcript does not record the tool list a session loaded. Without a recorded
- catalog, evidence untooling sees only the tools Claude Code defers (one listing line each) and
- those a session used; `te untool refresh-catalog` records the always-loaded set, with no model
+ catalog, evidence pruning sees only the tools Claude Code defers (one listing line each) and
+ those a session used; `te toolprune refresh-catalog` records the always-loaded set, with no model
call.
+* **A call that fails fires `PostToolUseFailure`, not `PostToolUse`** (verified on 2.1.299,
+ 2026-10-14): `{tool_name, tool_input, tool_use_id, error, is_interrupt, duration_ms}`, where
+ `error` is the text the model saw (`"Exit code 2\nls: cannot access ..."`). Until the hook
+ file registered it, the guard never saw a failing call: live sessions counted 39 of 47
+ calls, and a failing test run after the last edit could not make a turn end red.
* Bash `tool_response` is `{stdout, stderr, interrupted, isImage, noOutputExpected}` — **no exit
- code**, so on Claude Code failure is read from the output text, as the vendored detectors do.
+ code**, so on Claude Code failure is read from the output text, as the loop state's detectors do.
* Interactive transcripts parse with the existing `trace.load_trajectory`, but write **one entry
per content block, each repeating its message's usage**, so an assistant message id can repeat
many times; the ledger de-duplicates by message id. Subagents log to
@@ -109,8 +115,9 @@ isolated `CODEX_HOME`, `--dangerously-bypass-hook-trust`; 2026-09-30):
Code Mode) did not reproduce on this build and model.
* The plugin installs through Codex's own commands: `codex plugin marketplace add <dir>` reads
`.claude-plugin/marketplace.json`, and `codex plugin add tokeneconomizer@tokeneconomizer`
- **copies** the plugin into `$CODEX_HOME/plugins/cache/…` and enables it — so Codex needs the
- bundle, exactly as a Claude Code marketplace install does. `"${PLUGIN_ROOT:-…}"` in the hook
+ **copies** the plugin into `$CODEX_HOME/plugins/cache/…` and enables it, dropping the `lib`
+ symlink to the package; the bootstrap then finds the package in the checkout `config.toml`
+ records as the marketplace's `source` (verified 2026-10-14). `"${PLUGIN_ROOT:-…}"` in the hook
command resolves to that copy.
* End to end: four synthetic rollouts taught it that bare `pytest` is missing; a real Codex
session then answered "Run tests with `python -m pytest …` because the `pytest` command is
@@ -128,22 +135,22 @@ That gate, kebab-case event names and an argv-list handler are why `te_harness`
that Codex "honours no PreToolUse hook"; with PascalCase events, a command string and trust,
every hook fires. Not exercised, from the binary's schemas and the docs: `PostToolUse`
`continue: false` does **not** stop a Codex turn mid-flight, so on Codex the guard's last rung
-is a notice, matching the Codex-native spiral policies, which never abort. Code Mode presents
-one `exec` tool with nested descriptions and defers MCP tools, so Codex untooling works on
+is a notice, matching the Codex-native finalize policies, which never abort. Code Mode presents
+one `exec` tool with nested descriptions and defers MCP tools, so Codex pruning works on
capability packages (below), not on single tool schemas.
-**Codex untooling — verified on 0.153.1, 2026-10-07** (`codex debug prompt-input` renders a
+**Codex pruning — verified on 0.153.1, 2026-10-07** (`codex debug prompt-input` renders a
session's prompt input locally, with no model call; `codex features list` prints the effective
feature flags):
* A project's `.codex/config.toml` is read **only in a trusted project**. The same toggles
changed the rendered prompt input under a `CODEX_HOME` that trusted the checkout, and changed
nothing in an untrusted one, including a subdirectory of a trusted path. `te --host codex
- untool apply` checks trust and runs `codex features list` to confirm.
+ toolprune apply` checks trust and runs `codex features list` to confirm.
* The project-local toggles for `collaboration` (`[agents] enabled`, `[features] multi_agent`,
`include_collaboration_mode_instructions`), `goals` and `image_media` take effect. `goals` and
`view_image` remove declarations inside the code-mode tool description, which the render does
- not show, so `untool measure` understates them, and its output says so.
+ not show, so `toolprune measure` understates them, and its output says so.
* `[[skills.config]] enabled = false` hides the bundled skills listing from the user-level
config only. A per-repository decision does not belong there, so `skills` is not offered.
* The plugin writes each toggle as a line marked `# tokeneconomizer:<capability>` into the
@@ -151,23 +158,21 @@ feature flags):
* Code mode routes every call through one `exec` tool (`tools.view_image(…)`,
`tools.web__run(…)`), recorded as `response_item` `custom_tool_call` records, not as rollout
items. The fold therefore reads a capability trace that includes them.
-* In a live session (gpt-5.6-sol on a Codex login), after `te --host codex untool apply
+* In a live session (gpt-5.6-sol on a Codex login), after `te --host codex toolprune apply
collaboration goals image_media` the model reported no sub-agents, image viewer or goals, and
- could no longer view an image in the repository; `untool restore` returned the folder to its
+ could no longer view an image in the repository; `toolprune restore` returned the folder to its
earlier state. Codex loaded those runs' hooks from the repository's `.codex/hooks.json`. A run
trusts a project with `-c 'projects={"<path>"={trust_level="trusted"}}'`; the dotted `-c` form
does not take.
-**Copilot with a real model — 2026-10-07, over BYOK.** This machine's organization policy
-refuses the Copilot subscription's models ("Access denied by policy settings"). Copilot's BYOK
-mode (`COPILOT_PROVIDER_TYPE=anthropic`, `_BASE_URL`, `_API_KEY`) bypasses that, and these
-checks ran on `claude-haiku-4-5`, through `te --host copilot probe` (`te_live/probe.py`, which
-any user can run on their own setup):
+**Copilot with a real model — 2026-10-07, over BYOK.** These checks ran on Copilot's BYOK mode
+(`COPILOT_PROVIDER_TYPE=anthropic`, `_BASE_URL`, `_API_KEY`) with `claude-haiku-4-5`, through
+`te --host copilot probe` (`plugin/probe.py`, which any user can run on their own setup):
* **Settings apply only in a trusted folder.** Copilot ignores a repository's `.github/copilot`
settings outside its `trustedFolders`: a deny list applied in an untrusted directory under
`/tmp` changed nothing, and a local capture showed the same file taking effect under a trusted
- folder. `untool apply` therefore warns about an untrusted folder and confirms the effect with a
+ folder. `toolprune apply` therefore warns about an untrusted folder and confirms the effect with a
local capture, `doctor` reports trust, and the probe builds its repository inside a trusted
folder.
* Copilot's `session.shutdown` records the request's tool-definition size as
@@ -257,6 +262,52 @@ isolated `PI_CODING_AGENT_DIR`):
(`ctx.abort()`) — the dispatcher's side is covered by the offline tests, Pi's by its API.
Untooling does not apply: Pi declares four tools by default.
+**Pi 1.2.0 — verified live, 2026-10-14** (Haiku 4.5 through Pi's built-in OpenRouter provider,
+set as the default provider and model in an isolated `PI_CODING_AGENT_DIR`, as a Pi user's own
+settings would be):
+
+* `pi install` of the repository root — the manifest a `git:` source reads after cloning —
+ listed the package and loaded the extension. In a `--print` session its events reached the
+ dispatcher, the turn closed green, the session folded and was priced from Pi's own session
+ file, and `errors.log` stayed empty.
+* `/te status` answered as a `notify` over RPC (the terminal UI's notice), and on stderr in
+ print mode, leaving stdout to the reply.
+* A paid side call — `pi --print --mode json` with no tools, extensions, skills, prompt
+ templates, context files, MCP servers or saved session, and no `--model` — ran on the default
+ model and returned its text and usage; the plugin's own extension did not load inside it. Pi
+ 0.99.2 rejects `--no-mcp`, so the call retries without it.
+* Not yet exercised: `pi install git:github.com/…` against GitHub itself, which needs the
+ root manifest pushed.
+
+**End to end, as a new user, 2026-10-14** — on each agent a fresh home followed `README.md` and
+this plugin's guide step by step (Claude Code 2.1.300, Codex 0.153.1, Copilot CLI 1.0.83, Pi
+1.2.0; every model through OpenRouter; a small Python repository where `pytest` is missing and
+`python -m pytest` works):
+
+* Every agent: native install, hooks firing in new sessions, every session folded and priced,
+ facts injected and changing the first test command, every command and its earlier name,
+ settings under old and new names, uninstall leaving no hook running.
+* The deny list end to end on Claude Code (20 → 10 tools), Codex (`codex debug prompt-input`
+ 7,021 vs 10,397 characters) and Copilot (a user MCP server gone from the next session);
+ `restore` gave each back and kept the person's own entries.
+* The loop guard's redirect reached the model mid-turn on all four; on Pi a `steer` message, and
+ with `loopguard=stop` a headless turn ended at the next stuck verdict (nudged at call 17,
+ stopped at 35) — the first live check of both on Pi. On Codex and Copilot the second fire is
+ a notice.
+* Paid side calls ran through each agent's own CLI (Copilot's only off BYOK, above) and were
+ charged to the ledger, without recursing into the plugin.
+* Pi's real git install (a local git daemon standing in for GitHub): cloned, `npm install`ed,
+ listed, loaded; `pi update --extensions` fast-forwarded it; `pi remove` removed it.
+
+What the run found, now fixed: Claude Code 2.1.300's `api-request-blob` entries doubled every
+call read from its transcript; a working form was credited from runs that needed a
+`VAR=value` it leaves out, once per failure × success, and never debited; Pi's and Copilot's
+logs gave no per-call directory, so `cd <repo> && …` was learned as a separate form; the guard
+counted file reads as failures; an absolute-path test runner was not a verification; facts
+needed sessions that edited different files and, once injected, decayed (the fold never knew
+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
@@ -264,8 +315,8 @@ The plugin directory is `plugin/`; the repository root is also a Claude Code mar
**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:untool refresh-catalog` once per
-repository; without it, evidence untooling sees only deferred tools:
+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
@@ -274,32 +325,36 @@ claude --plugin-dir /path/to/TokenEconomizer/plugin # one session
/plugin install tokeneconomizer@tokeneconomizer
```
-**From a bundle** — a marketplace install copies only the plugin directory, so it needs the core
-vendored inside it. `python scripts/build_plugin.py` writes a self-contained marketplace to
+**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` and `hooks/codex-hooks.json`. Codex
-always copies an installed plugin, so install from the bundle:
+**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 copies an installed plugin; the copy finds the package in the
+checkout it was added from (or carries it, from the bundle):
```bash
-python scripts/build_plugin.py --out ~/te-marketplace
-codex plugin marketplace add ~/te-marketplace
+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
-core vendored in `lib/`. Until trusted, the hooks do not run, and a session leaves no plugin
+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, `untool
+`~/.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 untool …`) writes the project's `.codex/config.toml`, which Codex reads only
+(`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`.
@@ -308,28 +363,28 @@ Copilot loads a local marketplace in place, so the checkout itself is the instal
```bash
copilot plugin marketplace add /path/to/TokenEconomizer
copilot plugin install tokeneconomizer@tokeneconomizer
-te --host copilot untool refresh-catalog # once: the tools a session loads, no model call
+/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`. 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 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** — `plugin/` is also a Pi package (`package.json` → `pi.extensions`). Pi loads a local
-package in place, so from a checkout:
+**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 /path/to/TokenEconomizer/plugin # or, for one run: pi -e plugin/pi/tokeneconomizer.ts
+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
```
-Elsewhere, install the bundle's plugin directory the same way (it carries the core in `lib/`).
-Inside Pi, `/te status` (and `facts`, `replay`, `config`) runs the command line.
-
-**First run.** Before turning anything on, see what it would do on your own history:
-
-```text
-/tokeneconomizer:replay # or: plugin/scripts/te replay
-```
+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
@@ -338,30 +393,34 @@ below). The defaults are the conservative end of each:
| Key | Default | Values |
|---|---|---|
-| `inject` | `envfacts` | `off`, `envfacts`, `envfacts+distiller`, `distiller` (the last two make paid calls) |
-| `untool` | `propose` | `off`, `propose`, `auto` (apply proposals as they form) |
-| `spiral` | `nudge` | `off`, `nudge`, `guard` (nudge, then stop — headless only) |
+| `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) |
+| `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 |
|---|---|---|
-| `inject_max_facts`, `inject_max_tokens` | `4`, `150` | caps on the injected fact block (`InjectionConfig.max_facts` / `max_tokens`, passed to `EnvFactsDistiller`) |
-| `propose_every` | `5` | sessions between paid proposer runs |
-| `untool_evidence` | `5` | sessions a tool must go unused (×3 for NotebookEdit and Codex's `image_media`; WebFetch / WebSearch are never proposed) |
-| `spiral_aggr` | `default` | `conservative`, `default`, `aggressive` (the vendored `SPIRAL_LEVELS`) |
-| `spiral_nudges` | `1` | the guard's nudge budget per prompt-turn |
-| `spiral.<name>` | the preset | one key of `DEFAULT_THRESHOLDS`, pinned: `te_live.guard.thresholds` applies it over the preset and over what the repository's envelope learned; the `envelope_*` keys go to the `EnvelopeTracker` itself |
+| `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_SPIRAL_THRESHOLDS` takes JSON);
-`TE_DISABLE=1` turns the plugin off. `te config show` prints each mechanism's state and the
-guard's thresholds in effect. Commands: `/tokeneconomizer:status`, `:facts`, `:untool`,
-`:replay`, `:config` in Claude Code and Copilot; `plugin/scripts/te <command>` anywhere. The
+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
@@ -376,10 +435,10 @@ files `0600`, and tightens a looser one it finds.
Nothing leaves the machine unless `paid` is on. Then the proposer, judge and nudge writer send
**digests** — command templates, edited file basenames, error signatures, never file contents —
-through your own agent CLI (`claude -p` / `codex exec` / `copilot -p`), billed where your
-session is.
+through your own agent CLI (`claude -p` / `codex exec` / `copilot -p` / `pi -p`), billed where
+your session is.
-The untool writer adds and removes only deny rules it recorded adding, never one you wrote, and
+The deny-list writer adds and removes only deny rules it recorded adding, never one you wrote, and
adds a `settings.local.json` it creates to `.git/info/exclude`. A repository decides what its
`.claude`, `.codex` and `.github` paths are, so the writer refuses one that is, or goes through,
a symlink leading out of the repository, and refuses to edit a settings file that does not
@@ -388,18 +447,18 @@ parse rather than write over it.
A learned fact is text injected into your agent's context, derived from your sessions' command
output — which a repository controls. The free layer only fills fixed templates with observed
command forms and hosts, and lints out completion advice; the paid proposer's facts are
-open-vocabulary. Read them with `te facts` before enabling the proposer on a repository you do
+open-vocabulary. Read them with `te microskills` before enabling the proposer on a repository you do
not trust.
## 7. Not done yet
* **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.
-* **The stuck-turn guard, live** — the stop rung has not run on a real spiral, and whether a
+* **The loop guard, live** — the stop rung has not run on a real spiral, and whether a
nudge changes a looping model's course is not established. The guard counts edits and
repeated failures, not understanding, so with a small learned envelope it can fire on a turn
that has already found its cause and is working around it.
-* **Pi** — a live nudge and stop (steer message, `ctx.abort()`); untooling is not planned there,
+* **Pi** — a live nudge and stop (steer message, `ctx.abort()`); tool pruning is not planned there,
since Pi declares only four tools by default.
* **Known gaps:**
* A turn that ran no recognised verification counts as ended green, so a failed turn without
@@ -407,7 +466,7 @@ not trust.
* The free fact layer has no family for "this tool is absent here, with no working
alternative" (a missing `ruff`, `mypy` or `pre-commit`, say).
* Test runs launched from a script are not recognised as verification.
- * `refresh-catalog` is manual; until it runs in a repository, evidence untooling sees only
+ * `refresh-catalog` is manual; until it runs in a repository, evidence pruning sees only
deferred tools. Running it at a repository's first session would close that gap.
* Windows (the launcher is POSIX `sh`), Python 3.9, and compressed Codex rollouts (`.zst`).
* Transcript formats are internal to each agent and change between versions; the readers are
diff --git a/docs/assets/framework_overview.png b/docs/assets/framework_overview.png
new file mode 100644
index 0000000..e27f128
Binary files /dev/null and b/docs/assets/framework_overview.png differ
diff --git a/docs/assets/framework_overview.py b/docs/assets/framework_overview.py
new file mode 100644
index 0000000..8cd39b3
--- /dev/null
+++ b/docs/assets/framework_overview.py
@@ -0,0 +1,462 @@
+#!/usr/bin/env python3
+"""The README figure: the paper's framework overview, in the plugin's words.
+
+ python docs/assets/framework_overview.py # needs matplotlib; writes the PNG and SVG here
+
+Left column what the plugin keeps for a repository, the three mechanisms that act on the
+ next session, and the fold that updates them when a session ends.
+Right column the agent, unchanged, drawn as the three surfaces the plugin reaches. Each
+ mechanism is shown by what it adds to or removes from its surface: facts added
+ to the session's context, tools struck out of the loaded set, and calls struck
+ out of a turn the guard stopped.
+
+The layout is the paper figure's. Every row sits on one pitch, so a card, its arrow and its
+surface share one horizontal axis; the gaps inside a row are solved for, so the three surfaces
+end flush; and text placed next to other text is measured, with anything that could outgrow
+its box asserted, so a re-wording cannot silently overlap.
+"""
+
+from pathlib import Path
+
+import matplotlib
+
+matplotlib.use("Agg")
+import matplotlib.pyplot as plt
+from matplotlib.patches import Circle, FancyArrowPatch, FancyBboxPatch, Rectangle
+
+OUT_DIR = Path(__file__).resolve().parent
+PNG_DPI = 600
+
+# Drawn at the placed size: 10 units per inch on both axes, so circles stay round.
+FIG_W, FIG_H = 5.5, 2.775
+XMAX, YMAX = 55.0, 27.75
+UNITS_PER_INCH = 10.0
+
+# Colorblind-friendly, print-safe palette.
+INK = "#20303C"
+MUTED = "#63727D"
+LINE = "#C6D0D6"
+PANEL = "#FBFCFD"
+SKILL = "#3E73A8"
+SKILL_LIGHT = "#DFEAF4"
+TOOLS = "#BC7D14"
+TOOLS_LIGHT = "#F7E8C9"
+SPIRAL = "#BF4F4B"
+SPIRAL_LIGHT = "#F4DCDA"
+NEUTRAL_FC, NEUTRAL_EC = "#EDF0F2", "#B7C2C9"
+DROPPED_FC, DROPPED_EC, DROPPED_TC = "#EDEFF1", "#BAC4CA", "#98A4AC"
+
+# One type scale for the whole drawing; nothing is rescaled after export.
+FS_PANEL = 6.0 # panel headers
+FS_ROW = 5.6 # row titles inside the agent panel
+FS_CHIP = 5.8 # mechanism names
+FS_BODY = 4.6 # explanatory copy
+FS_SMALL = 4.4 # annotations
+FS_TAG = 4.5 # lifecycle tags
+FS_MONO = 4.1 # tool names and turn actions
+FS_MARK = 4.3 # the two runtime interventions
+FS_DOTS = 6.2 # the ellipsis standing in for turns not drawn
+
+MONO = "DejaVu Sans Mono"
+ELLIPSIS = "…"
+
+# ---- layout -----------------------------------------------------------------
+# The three rows sit on one pitch and every surface is drawn at one height, so a
+# mechanism card, its arrow and the object it acts on share a horizontal axis.
+CTRL_X0, CTRL_X1 = 0.50, 15.90
+AGENT_X0, AGENT_X1 = 17.60, 54.50
+PANEL_Y0, PANEL_Y1 = 6.15, 27.35
+PAD = 0.85 # one padding value inside both panels
+
+AIN_X0, AIN_X1 = 19.20, 53.20 # content area inside the agent panel
+CHIP_X0, CHIP_X1 = CTRL_X0 + PAD, CTRL_X1 - PAD
+HDR_TITLE_Y, HDR_SUB_Y, HDR_RULE = 26.40, 25.70, 23.85
+
+ROW_TOP, ROW_PITCH, ROW_H = 23.30, 5.95, 4.85
+ROWS = {n: (ROW_TOP - (n - 1) * ROW_PITCH - ROW_H,
+ ROW_TOP - (n - 1) * ROW_PITCH) for n in (1, 2, 3)}
+BAR_OFFSET, BAR_H = 1.70, 1.50 # bar top below the row title
+CHIP_H = 4.30
+
+LEARN_Y0, LEARN_Y1 = 0.25, 4.55 # learner box, below the controller
+LEG_Y, LEG_X = 2.40, 50.00 # the completed trace travels back along this
+
+
+def bar_y(number):
+ return ROWS[number][1] - BAR_OFFSET - BAR_H
+
+
+def axis_y(number):
+ """The one horizontal axis a mechanism, its arrow and its surface share."""
+ return bar_y(number) + BAR_H / 2
+
+
+def flush_gap(widths):
+ """Gap that makes a run of boxes span the content width exactly.
+
+ Solving for the gap rather than hand-picking one is what keeps the three
+ surfaces ending flush with each other after any width is edited."""
+ gap = (AIN_X1 - AIN_X0 - sum(widths)) / (len(widths) - 1)
+ assert 0.35 <= gap <= 1.20, f"box widths leave a {gap:.2f} unit gap"
+ return gap
+
+
+def rounded(ax, xy, width, height, *, fc="white", ec=LINE, lw=0.7,
+ radius=0.32, zorder=1, alpha=1.0, ls="solid"):
+ patch = FancyBboxPatch(
+ xy, width, height,
+ boxstyle=f"round,pad=0,rounding_size={radius}",
+ facecolor=fc, edgecolor=ec, linewidth=lw, zorder=zorder,
+ alpha=alpha, linestyle=ls,
+ )
+ ax.add_patch(patch)
+ return patch
+
+
+def arrow(ax, p0, p1, *, color=MUTED, lw=0.85, mutation=4.5, zorder=6):
+ a = FancyArrowPatch(
+ p0, p1, arrowstyle="-|>", mutation_scale=mutation, linewidth=lw,
+ color=color, shrinkA=0, shrinkB=0, zorder=zorder,
+ )
+ ax.add_patch(a)
+ return a
+
+
+def width_of(fig, text, fontsize, *, weight="normal", family=None):
+ """Measured width of a label, in drawing units.
+
+ Several labels are laid out end to end on one line (a row title next to its
+ eyebrow, a right-aligned tag). Estimating their widths from a character count
+ is what let an earlier revision overlap its own text, so the real renderer is
+ asked instead."""
+ probe = fig.text(0, 0, text, fontsize=fontsize, fontweight=weight,
+ family=family)
+ extent = probe.get_window_extent(renderer=fig.canvas.get_renderer())
+ probe.remove()
+ return extent.width / fig.dpi * UNITS_PER_INCH
+
+
+def badge(ax, x, y, number, color, *, radius=0.72, fs=4.6):
+ """The numbered token that ties a mechanism card to the surface it acts on."""
+ ax.add_patch(Circle((x, y), radius, facecolor=color, edgecolor="none", zorder=7))
+ ax.text(x, y, number, ha="center", va="center", fontsize=fs,
+ color="white", fontweight="bold", zorder=8)
+
+
+def tag(fig, ax, x_right, y, text, color, light, *, fs=FS_TAG, weight="bold"):
+ """Right-aligned lifecycle tag; it never shares a line with body copy."""
+ width = width_of(fig, text, fs, weight=weight) + 1.10
+ rounded(ax, (x_right - width, y - 0.62), width, 1.24, fc=light, ec="none",
+ radius=0.62, zorder=5)
+ ax.text(x_right - width / 2, y, text, ha="center", va="center",
+ fontsize=fs, color=color, fontweight=weight, zorder=6)
+ return x_right - width
+
+
+def annotate(ax, number, x0, x1, text, color, *, fs=FS_SMALL):
+ """Range note under the part of a surface a mechanism changes.
+
+ All three rows annotate at the same offset, so the notes read as one band."""
+ y = bar_y(number) - 0.35
+ ax.plot([x0, x1], [y, y], color=color, lw=0.7, zorder=6)
+ for x in (x0, x1):
+ ax.plot([x, x], [y, y + 0.36], color=color, lw=0.7, zorder=6)
+ ax.text((x0 + x1) / 2, y - 0.42, text, fontsize=fs, color=color,
+ ha="center", va="top", fontweight="bold", zorder=6)
+
+
+# ---- left column ------------------------------------------------------------
+
+MECHANISMS = [
+ (1, "Micro-skills", SKILL, SKILL_LIGHT,
+ ("repository facts learned from failures",
+ "that recur across finished sessions")),
+ (2, "Tool pruning", TOOLS, TOOLS_LIGHT,
+ ("tools left unused session after session",
+ "go on a deny list once you approve it")),
+ (3, "Failure-loop intervention", SPIRAL, SPIRAL_LIGHT,
+ ("learns how long turns here usually run;",
+ "one redirect, then a stop or a notice")),
+]
+
+
+def draw_controller(fig, ax):
+ rounded(ax, (CTRL_X0, PANEL_Y0), CTRL_X1 - CTRL_X0, PANEL_Y1 - PANEL_Y0,
+ fc=PANEL, ec="#9FADB6", lw=0.9, radius=0.55, zorder=1)
+
+ ax.text(CHIP_X0, HDR_TITLE_Y, "PLUGIN", fontsize=FS_PANEL, color=INK,
+ fontweight="bold", ha="left", va="center", zorder=5)
+ ax.text(CHIP_X0, HDR_SUB_Y,
+ "what it knows about this repository,\nfrom the sessions before this one",
+ fontsize=FS_BODY, color=MUTED, ha="left", va="top",
+ linespacing=1.30, zorder=5)
+ ax.plot([CHIP_X0, CHIP_X1], [HDR_RULE] * 2, color=LINE, lw=0.6, zorder=4)
+
+ for number, title, color, light, body in MECHANISMS:
+ top = axis_y(number) + CHIP_H / 2
+ rounded(ax, (CHIP_X0, top - CHIP_H), CHIP_X1 - CHIP_X0, CHIP_H,
+ fc="white", ec=color, lw=0.85, radius=0.40, zorder=3)
+ badge(ax, CHIP_X0 + 0.75, top - 1.05, str(number), color)
+ room = CHIP_X1 - (CHIP_X0 + 1.80) - 0.30
+ used = width_of(fig, title, FS_CHIP, weight="bold")
+ assert used <= room, f"card {number} title is {used:.2f} units, room {room:.2f}"
+ ax.text(CHIP_X0 + 1.80, top - 1.05, title, fontsize=FS_CHIP, color=color,
+ fontweight="bold", ha="left", va="center", zorder=5)
+ body_room = CHIP_X1 - CHIP_X0 - 0.70
+ body_used = max(width_of(fig, line, FS_BODY) for line in body)
+ assert body_used <= body_room, (
+ f"card {number} body is {body_used:.2f} units, room {body_room:.2f}")
+ ax.text(CHIP_X0 + 0.35, top - 2.25, "\n".join(body), fontsize=FS_BODY,
+ color=MUTED, ha="left", va="top", linespacing=1.30, zorder=5)
+
+
+def draw_learners(fig, ax):
+ rounded(ax, (CTRL_X0, LEARN_Y0), CTRL_X1 - CTRL_X0, LEARN_Y1 - LEARN_Y0,
+ fc="white", ec="#9FADB6", lw=0.85, radius=0.45, zorder=3)
+ header = "SESSION END"
+ ax.text(CHIP_X0, LEARN_Y1 - 1.00, header, fontsize=FS_ROW, color=INK,
+ fontweight="bold", ha="left", va="center", zorder=5)
+ first_badge = CHIP_X1 - 0.58 - 2 * 1.45 - 0.58
+ assert CHIP_X0 + width_of(fig, header, FS_ROW, weight="bold") <= first_badge - 0.30, header
+ for i, (number, _, color, _, _) in enumerate(MECHANISMS):
+ badge(ax, CHIP_X1 - 0.58 - (2 - i) * 1.45, LEARN_Y1 - 1.00, str(number),
+ color, radius=0.58, fs=4.0)
+ ax.text(CHIP_X0, LEARN_Y1 - 2.05,
+ "its log updates what all three\nmechanisms know about the repository",
+ fontsize=FS_BODY, color=MUTED, ha="left", va="top",
+ linespacing=1.30, zorder=5)
+
+ arrow(ax, (CHIP_X0 + 1.55, LEARN_Y1 + 0.05), (CHIP_X0 + 1.55, PANEL_Y0 - 0.05),
+ color=MUTED, zorder=7)
+ ax.text(CHIP_X0 + 2.30, (LEARN_Y1 + PANEL_Y0) / 2, "for the next session",
+ fontsize=FS_SMALL, color=MUTED, ha="left", va="center", zorder=7)
+
+
+# ---- right column -----------------------------------------------------------
+
+def draw_agent_header(fig, ax):
+ title = "YOUR CODING AGENT"
+ ax.text(AIN_X0, HDR_TITLE_Y, title, fontsize=FS_PANEL, color=INK,
+ fontweight="bold", ha="left", va="center", zorder=5)
+ note_x = AIN_X0 + width_of(fig, title, FS_PANEL, weight="bold") + 0.70
+ ax.text(note_x, HDR_TITLE_Y, "(unchanged)", fontsize=FS_BODY, color=MUTED,
+ ha="left", va="center", zorder=5)
+ left = tag(fig, ax, AIN_X1, HDR_TITLE_Y, "Claude Code · Codex · Copilot CLI · Pi",
+ INK, "#E7ECEF", weight="normal")
+ assert note_x + width_of(fig, "(unchanged)", FS_BODY) <= left - 0.50, "header collides"
+ ax.plot([AIN_X0, AIN_X1], [HDR_RULE] * 2, color=LINE, lw=0.6, zorder=4)
+
+
+def row_title(fig, ax, number, eyebrow, title, color, timing, light):
+ y = ROWS[number][1] - 0.65
+ badge(ax, AIN_X0 + 0.55, y, str(number), color, radius=0.62, fs=4.2)
+ x = AIN_X0 + 1.50
+ ax.text(x, y, eyebrow, fontsize=FS_ROW, color=color, fontweight="bold",
+ ha="left", va="center", zorder=5)
+ x += width_of(fig, eyebrow, FS_ROW, weight="bold") + 0.65
+ ax.text(x, y, title, fontsize=FS_ROW, color=INK, ha="left", va="center",
+ zorder=5)
+ tag(fig, ax, AIN_X1, y, timing, color, light)
+
+
+def draw_prefix_row(fig, ax):
+ row_title(fig, ax, 1, "KNOWLEDGE", "session context", SKILL,
+ "at session start", SKILL_LIGHT)
+
+ y = bar_y(1)
+ skill_x, skill_w = AIN_X0 + 13.40, 10.40
+ segments = [
+ (AIN_X0, 13.40, NEUTRAL_FC, NEUTRAL_EC, "system prompt + your instructions",
+ MUTED, "normal"),
+ (skill_x, skill_w, SKILL_LIGHT, SKILL, "+ learned micro-skills",
+ SKILL, "bold"),
+ (skill_x + skill_w, AIN_X1 - skill_x - skill_w, "white", NEUTRAL_EC,
+ "your prompt", MUTED, "normal"),
+ ]
+ for x, w, fc, ec, label, tc, weight in segments:
+ ax.add_patch(Rectangle((x, y), w, BAR_H, facecolor=fc, edgecolor=ec,
+ linewidth=0.7, zorder=4))
+ assert width_of(fig, label, FS_SMALL, weight=weight) <= w - 0.30, label
+ ax.text(x + w / 2, y + BAR_H / 2, label, fontsize=FS_SMALL, color=tc,
+ ha="center", va="center", fontweight=weight, zorder=5)
+ annotate(ax, 1, skill_x, skill_x + skill_w,
+ "active facts only", SKILL)
+
+
+# Claude Code's names. The kept ones are the work surface the plugin never proposes; the
+# dropped ones are tools it has proposed in practice. The web tools are never proposed.
+TOOLCHIPS = [
+ ("Bash", "kept"), ("Read", "kept"), ("Edit", "kept"), ("Write", "kept"),
+ ("Grep", "kept"), ("Glob", "kept"),
+ ("CronCreate", "dropped"), ("Workflow", "dropped"), ("NotebookEdit", "dropped"),
+ (ELLIPSIS, "more"),
+]
+TOOL_GAP = 0.70
+
+
+def draw_tools_row(fig, ax):
+ row_title(fig, ax, 2, "INTERFACE", "loaded tool set", TOOLS,
+ "from the next session", TOOLS_LIGHT)
+
+ y = bar_y(2)
+ # Chips are sized to their names; the padding is solved so the row ends flush.
+ names = [width_of(fig, name, FS_MONO, family=MONO) for name, _ in TOOLCHIPS]
+ pad = (AIN_X1 - AIN_X0 - TOOL_GAP * (len(names) - 1) - sum(names)) / len(names)
+ assert pad >= 0.45, f"tool names leave {pad:.2f} units of padding"
+ x, dropped = AIN_X0, []
+ for (name, state), used in zip(TOOLCHIPS, names):
+ w = used + pad
+ if state == "more":
+ # Drawn without a box: the rest of the proposal, not one more tool.
+ ax.text(x + w / 2, y + BAR_H / 2, name, fontsize=FS_DOTS, color=DROPPED_TC,
+ ha="center", va="center", zorder=5)
+ dropped.append((x, x + w))
+ x += w + TOOL_GAP
+ continue
+ if state == "kept":
+ fc, ec, tc = TOOLS_LIGHT, TOOLS, "#74500C"
+ else:
+ fc, ec, tc = DROPPED_FC, DROPPED_EC, DROPPED_TC
+ dropped.append((x, x + w))
+ rounded(ax, (x, y), w, BAR_H, fc=fc, ec=ec, lw=0.7, radius=0.26, zorder=4)
+ ax.text(x + w / 2, y + BAR_H / 2, name, fontsize=FS_MONO, color=tc,
+ family=MONO, ha="center", va="center", zorder=5)
+ if state == "dropped":
+ ax.plot([x + 0.28, x + w - 0.28], [y + BAR_H / 2] * 2,
+ color=DROPPED_TC, lw=0.6, zorder=6)
+ x += w + TOOL_GAP
+ annotate(ax, 2, dropped[0][0], dropped[-1][1], "denied, once you approve", DROPPED_TC)
+
+
+# One prompt-turn, read left to right, in the order the guard acts: the same failure comes
+# back, and only then is one redirect attached to a tool result; when it comes back again
+# the turn is stopped (headless; interactive use gets a notice instead), so the calls after
+# it are struck out exactly like a pruned tool. An ellipsis stands for the repetitions a
+# schematic cannot show, so the two groups are not read as exactly two calls each.
+TURNBOXES = [
+ (ELLIPSIS, "earlier", 1.40, None),
+ ("edit", "repeat", 2.55, "loop"),
+ ("test", "repeat", 2.55, "loop"),
+ (ELLIPSIS, "more", 1.40, "loop"),
+ ("REDIRECT", "redirect", 3.70, None),
+ ("edit", "repeat", 2.55, "again"),
+ ("test", "repeat", 2.55, "again"),
+ (ELLIPSIS, "more", 1.40, "again"),
+ ("STOP", "abort", 3.30, None),
+ ("edit", "dropped", 2.50, "dropped"),
+ ("test", "dropped", 2.50, "dropped"),
+]
+ROLLOUT_NOTES = [
+ ("loop", "repeated failures", SPIRAL),
+ ("again", "still repeating", SPIRAL),
+ ("dropped", "never run", DROPPED_TC),
+]
+
+BOX_STYLES = { # fill, edge, text, family, weight
+ "repeat": (SPIRAL_LIGHT, SPIRAL, SPIRAL, MONO, "normal"),
+ "redirect": (SPIRAL, SPIRAL, "white", None, "bold"),
+ "abort": ("white", SPIRAL, SPIRAL, None, "bold"),
+ "dropped": (DROPPED_FC, DROPPED_EC, DROPPED_TC, MONO, "normal"),
+}
+
+
+def draw_rollout_row(fig, ax):
+ row_title(fig, ax, 3, "CONTROL", "one prompt-turn", SPIRAL,
+ "during each turn", SPIRAL_LIGHT)
+
+ y = bar_y(3)
+ gap = flush_gap([w for _, _, w, _ in TURNBOXES])
+ spans, x = {}, AIN_X0
+ for label, state, w, group in TURNBOXES:
+ if state in ("earlier", "more"):
+ # Drawn without a box, so it reads as continuation rather than one turn.
+ ax.text(x + w / 2, y + BAR_H / 2, label, fontsize=FS_DOTS,
+ color=SPIRAL if state == "more" else DROPPED_TC,
+ ha="center", va="center", zorder=5)
+ else:
+ fc, ec, tc, family, weight = BOX_STYLES[state]
+ rounded(ax, (x, y), w, BAR_H, fc=fc, ec=ec,
+ lw=1.1 if state == "abort" else 0.7, radius=0.26, zorder=4)
+ fs = FS_MARK if state in ("redirect", "abort") else FS_MONO
+ assert width_of(fig, label, fs, weight=weight,
+ family=family) <= w - 0.30, label
+ ax.text(x + w / 2, y + BAR_H / 2, label, fontsize=fs, color=tc,
+ family=family, fontweight=weight, ha="center", va="center",
+ zorder=5)
+ if state == "dropped":
+ ax.plot([x + 0.28, x + w - 0.28], [y + BAR_H / 2] * 2,
+ color=DROPPED_TC, lw=0.6, zorder=6)
+ if group:
+ spans.setdefault(group, [x, x + w])[1] = x + w
+ x += w + gap
+
+ placed = []
+ for group, text, color in ROLLOUT_NOTES:
+ x0, x1 = spans[group]
+ annotate(ax, 3, x0, x1, text, color)
+ half = width_of(fig, text, FS_SMALL, weight="bold") / 2
+ placed.append(((x0 + x1) / 2 - half, (x0 + x1) / 2 + half))
+ for (_, left_end), (right_start, _) in zip(placed, placed[1:]):
+ assert right_start > left_end + 0.30, "rollout notes collide"
+
+
+def draw_agent(fig, ax):
+ rounded(ax, (AGENT_X0, PANEL_Y0), AGENT_X1 - AGENT_X0, PANEL_Y1 - PANEL_Y0,
+ fc="white", ec="#9FADB6", lw=0.9, radius=0.55, zorder=1)
+ draw_agent_header(fig, ax)
+ draw_prefix_row(fig, ax)
+ draw_tools_row(fig, ax)
+ draw_rollout_row(fig, ax)
+
+
+# ---- wiring -----------------------------------------------------------------
+
+def draw_control_arrows(ax):
+ for number, _, color, _, _ in MECHANISMS:
+ y = axis_y(number)
+ arrow(ax, (CTRL_X1 + 0.10, y), (AGENT_X0 + 1.05, y), color=color, zorder=7)
+
+
+def draw_return(ax):
+ ax.plot([LEG_X, LEG_X], [PANEL_Y0, LEG_Y], color=MUTED, lw=0.85, zorder=6)
+ arrow(ax, (LEG_X, LEG_Y), (CTRL_X1 + 0.20, LEG_Y), color=MUTED, zorder=6)
+ ax.text((CTRL_X1 + LEG_X) / 2, LEG_Y + 0.55, "the finished session's log",
+ fontsize=FS_SMALL, color=MUTED, ha="center", va="bottom", zorder=6)
+
+
+def main():
+ plt.rcParams.update({
+ "font.family": "DejaVu Sans",
+ "font.size": 10,
+ # Outline SVG glyphs so the vector asset is portable and cannot fall back
+ # to a substituted/rasterized font in downstream viewers.
+ "svg.fonttype": "path",
+ "svg.hashsalt": "framework_overview", # stable element ids across runs
+ "pdf.fonttype": 42, # embed TrueType text in PDF
+ "ps.fonttype": 42,
+ "axes.unicode_minus": False,
+ })
+
+ fig = plt.figure(figsize=(FIG_W, FIG_H))
+ ax = fig.add_axes((0, 0, 1, 1))
+ ax.set_xlim(0, XMAX)
+ ax.set_ylim(0, YMAX)
+ ax.axis("off")
+ fig.patch.set_facecolor("white")
+
+ draw_controller(fig, ax)
+ draw_learners(fig, ax)
+ draw_agent(fig, ax)
+ draw_control_arrows(ax)
+ draw_return(ax)
+
+ base = OUT_DIR / "framework_overview"
+ # No creation date in the SVG, so regenerating an unchanged figure changes no file.
+ fig.savefig(base.with_suffix(".png"), dpi=PNG_DPI, facecolor="white")
+ fig.savefig(base.with_suffix(".svg"), facecolor="white", metadata={"Date": None})
+ print(f"wrote {base.with_suffix('.png')}")
+ print(f" {base.with_suffix('.svg')}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/assets/framework_overview.svg b/docs/assets/framework_overview.svg
new file mode 100644
index 0000000..326f18a
--- /dev/null
+++ b/docs/assets/framework_overview.svg
@@ -0,0 +1,4041 @@
+<?xml version="1.0" encoding="utf-8" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="396pt" height="199.8pt" viewBox="0 0 396 199.8" xmlns="http://www.w3.org/2000/svg" version="1.1">
+ <metadata>
+ <rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
+ <cc:Work>
+ <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
+ <dc:format>image/svg+xml</dc:format>
+ <dc:creator>
+ <cc:Agent>
+ <dc:title>Matplotlib v3.10.9, https://matplotlib.org/</dc:title>
+ </cc:Agent>
+ </dc:creator>
+ </cc:Work>
+ </rdf:RDF>
+ </metadata>
+ <defs>
+ <style type="text/css">*{stroke-linejoin: round; stroke-linecap: butt}</style>
+ </defs>
+ <g id="figure_1">
+ <g id="patch_1">
+ <path d="M 0 199.8
+L 396 199.8
+L 396 0
+L 0 0
+z
+" style="fill: #ffffff"/>
+ </g>
+ <g id="axes_1">
+ <g id="patch_2">
+ <path d="M 7.56 155.52
+L 110.52 155.52
+Q 114.48 155.52 114.48 151.56
+L 114.48 6.84
+Q 114.48 2.88 110.52 2.88
+L 7.56 2.88
+Q 3.6 2.88 3.6 6.84
+L 3.6 151.56
+Q 3.6 155.52 7.56 155.52
+z
+" clip-path="url(#p37831d8287)" style="fill: #fbfcfd; stroke: #9fadb6; stroke-width: 0.9; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_3">
+ <path d="M 130.68 155.52
+L 388.44 155.52
+Q 392.4 155.52 392.4 151.56
+L 392.4 6.84
+Q 392.4 2.88 388.44 2.88
+L 130.68 2.88
+Q 126.72 2.88 126.72 6.84
+L 126.72 151.56
+Q 126.72 155.52 130.68 155.52
+z
+" clip-path="url(#p37831d8287)" style="fill: #ffffff; stroke: #9fadb6; stroke-width: 0.9; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_4">
+ <path d="M 12.6 65.16
+L 105.48 65.16
+Q 108.36 65.16 108.36 62.28
+L 108.36 37.08
+Q 108.36 34.2 105.48 34.2
+L 12.6 34.2
+Q 9.72 34.2 9.72 37.08
+L 9.72 62.28
+Q 9.72 65.16 12.6 65.16
+z
+" clip-path="url(#p37831d8287)" style="fill: #ffffff; stroke: #3e73a8; stroke-width: 0.85; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_5">
+ <path d="M 12.6 108
+L 105.48 108
+Q 108.36 108 108.36 105.12
+L 108.36 79.92
+Q 108.36 77.04 105.48 77.04
+L 12.6 77.04
+Q 9.72 77.04 9.72 79.92
+L 9.72 105.12
+Q 9.72 108 12.6 108
+z
+" clip-path="url(#p37831d8287)" style="fill: #ffffff; stroke: #bc7d14; stroke-width: 0.85; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_6">
+ <path d="M 12.6 150.84
+L 105.48 150.84
+Q 108.36 150.84 108.36 147.96
+L 108.36 122.76
+Q 108.36 119.88 105.48 119.88
+L 12.6 119.88
+Q 9.72 119.88 9.72 122.76
+L 9.72 147.96
+Q 9.72 150.84 12.6 150.84
+z
+" clip-path="url(#p37831d8287)" style="fill: #ffffff; stroke: #bf4f4b; stroke-width: 0.85; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_7">
+ <path d="M 6.84 198
+L 111.24 198
+Q 114.48 198 114.48 194.76
+L 114.48 170.28
+Q 114.48 167.04 111.24 167.04
+L 6.84 167.04
+Q 3.6 167.04 3.6 170.28
+L 3.6 194.76
+Q 3.6 198 6.84 198
+z
+" clip-path="url(#p37831d8287)" style="fill: #ffffff; stroke: #9fadb6; stroke-width: 0.85; stroke-linejoin: miter"/>
+ </g>
+ <g id="line2d_1">
+ <path d="M 9.72 28.08
+L 108.36 28.08
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #c6d0d6; stroke-width: 0.6; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_2">
+ <path d="M 138.24 28.08
+L 383.04 28.08
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #c6d0d6; stroke-width: 0.6; stroke-linecap: square"/>
+ </g>
+ <g id="patch_8">
+ <path d="M 138.24 55.08
+L 234.72 55.08
+L 234.72 44.28
+L 138.24 44.28
+z
+" clip-path="url(#p37831d8287)" style="fill: #edf0f2; stroke: #b7c2c9; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_9">
+ <path d="M 234.72 55.08
+L 309.6 55.08
+L 309.6 44.28
+L 234.72 44.28
+z
+" clip-path="url(#p37831d8287)" style="fill: #dfeaf4; stroke: #3e73a8; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_10">
+ <path d="M 309.6 55.08
+L 383.04 55.08
+L 383.04 44.28
+L 309.6 44.28
+z
+" clip-path="url(#p37831d8287)" style="fill: #ffffff; stroke: #b7c2c9; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_11">
+ <path d="M 140.112 97.92
+L 152.424 97.92
+Q 154.296 97.92 154.296 96.048
+L 154.296 88.992
+Q 154.296 87.12 152.424 87.12
+L 140.112 87.12
+Q 138.24 87.12 138.24 88.992
+L 138.24 96.048
+Q 138.24 97.92 140.112 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #f7e8c9; stroke: #bc7d14; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_12">
+ <path d="M 161.208 97.92
+L 173.52 97.92
+Q 175.392 97.92 175.392 96.048
+L 175.392 88.992
+Q 175.392 87.12 173.52 87.12
+L 161.208 87.12
+Q 159.336 87.12 159.336 88.992
+L 159.336 96.048
+Q 159.336 97.92 161.208 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #f7e8c9; stroke: #bc7d14; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_13">
+ <path d="M 182.304 97.92
+L 194.616 97.92
+Q 196.488 97.92 196.488 96.048
+L 196.488 88.992
+Q 196.488 87.12 194.616 87.12
+L 182.304 87.12
+Q 180.432 87.12 180.432 88.992
+L 180.432 96.048
+Q 180.432 97.92 182.304 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #f7e8c9; stroke: #bc7d14; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_14">
+ <path d="M 203.4 97.92
+L 218.142 97.92
+Q 220.014 97.92 220.014 96.048
+L 220.014 88.992
+Q 220.014 87.12 218.142 87.12
+L 203.4 87.12
+Q 201.528 87.12 201.528 88.992
+L 201.528 96.048
+Q 201.528 97.92 203.4 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #f7e8c9; stroke: #bc7d14; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_15">
+ <path d="M 226.926 97.92
+L 239.238 97.92
+Q 241.11 97.92 241.11 96.048
+L 241.11 88.992
+Q 241.11 87.12 239.238 87.12
+L 226.926 87.12
+Q 225.054 87.12 225.054 88.992
+L 225.054 96.048
+Q 225.054 97.92 226.926 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #f7e8c9; stroke: #bc7d14; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_16">
+ <path d="M 248.022 97.92
+L 260.334 97.92
+Q 262.206 97.92 262.206 96.048
+L 262.206 88.992
+Q 262.206 87.12 260.334 87.12
+L 248.022 87.12
+Q 246.15 87.12 246.15 88.992
+L 246.15 96.048
+Q 246.15 97.92 248.022 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #f7e8c9; stroke: #bc7d14; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_17">
+ <path d="M 269.118 97.92
+L 296.01 97.92
+Q 297.882 97.92 297.882 96.048
+L 297.882 88.992
+Q 297.882 87.12 296.01 87.12
+L 269.118 87.12
+Q 267.246 87.12 267.246 88.992
+L 267.246 96.048
+Q 267.246 97.92 269.118 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #edeff1; stroke: #bac4ca; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_18">
+ <path d="M 304.794 97.92
+L 326.826 97.92
+Q 328.698 97.92 328.698 96.048
+L 328.698 88.992
+Q 328.698 87.12 326.826 87.12
+L 304.794 87.12
+Q 302.922 87.12 302.922 88.992
+L 302.922 96.048
+Q 302.922 97.92 304.794 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #edeff1; stroke: #bac4ca; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_19">
+ <path d="M 335.61 97.92
+L 367.362 97.92
+Q 369.234 97.92 369.234 96.048
+L 369.234 88.992
+Q 369.234 87.12 367.362 87.12
+L 335.61 87.12
+Q 333.738 87.12 333.738 88.992
+L 333.738 96.048
+Q 333.738 97.92 335.61 97.92
+z
+" clip-path="url(#p37831d8287)" style="fill: #edeff1; stroke: #bac4ca; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_20">
+ <path d="M 155.664 140.76
+L 170.28 140.76
+Q 172.152 140.76 172.152 138.888
+L 172.152 131.832
+Q 172.152 129.96 170.28 129.96
+L 155.664 129.96
+Q 153.792 129.96 153.792 131.832
+L 153.792 138.888
+Q 153.792 140.76 155.664 140.76
+z
+" clip-path="url(#p37831d8287)" style="fill: #f4dcda; stroke: #bf4f4b; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_21">
+ <path d="M 179.496 140.76
+L 194.112 140.76
+Q 195.984 140.76 195.984 138.888
+L 195.984 131.832
+Q 195.984 129.96 194.112 129.96
+L 179.496 129.96
+Q 177.624 129.96 177.624 131.832
+L 177.624 138.888
+Q 177.624 140.76 179.496 140.76
+z
+" clip-path="url(#p37831d8287)" style="fill: #f4dcda; stroke: #bf4f4b; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_22">
+ <path d="M 218.88 140.76
+L 241.776 140.76
+Q 243.648 140.76 243.648 138.888
+L 243.648 131.832
+Q 243.648 129.96 241.776 129.96
+L 218.88 129.96
+Q 217.008 129.96 217.008 131.832
+L 217.008 138.888
+Q 217.008 140.76 218.88 140.76
+z
+" clip-path="url(#p37831d8287)" style="fill: #bf4f4b; stroke: #bf4f4b; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_23">
+ <path d="M 250.992 140.76
+L 265.608 140.76
+Q 267.48 140.76 267.48 138.888
+L 267.48 131.832
+Q 267.48 129.96 265.608 129.96
+L 250.992 129.96
+Q 249.12 129.96 249.12 131.832
+L 249.12 138.888
+Q 249.12 140.76 250.992 140.76
+z
+" clip-path="url(#p37831d8287)" style="fill: #f4dcda; stroke: #bf4f4b; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_24">
+ <path d="M 274.824 140.76
+L 289.44 140.76
+Q 291.312 140.76 291.312 138.888
+L 291.312 131.832
+Q 291.312 129.96 289.44 129.96
+L 274.824 129.96
+Q 272.952 129.96 272.952 131.832
+L 272.952 138.888
+Q 272.952 140.76 274.824 140.76
+z
+" clip-path="url(#p37831d8287)" style="fill: #f4dcda; stroke: #bf4f4b; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_25">
+ <path d="M 314.208 140.76
+L 334.224 140.76
+Q 336.096 140.76 336.096 138.888
+L 336.096 131.832
+Q 336.096 129.96 334.224 129.96
+L 314.208 129.96
+Q 312.336 129.96 312.336 131.832
+L 312.336 138.888
+Q 312.336 140.76 314.208 140.76
+z
+" clip-path="url(#p37831d8287)" style="fill: #ffffff; stroke: #bf4f4b; stroke-width: 1.1; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_26">
+ <path d="M 343.44 140.76
+L 357.696 140.76
+Q 359.568 140.76 359.568 138.888
+L 359.568 131.832
+Q 359.568 129.96 357.696 129.96
+L 343.44 129.96
+Q 341.568 129.96 341.568 131.832
+L 341.568 138.888
+Q 341.568 140.76 343.44 140.76
+z
+" clip-path="url(#p37831d8287)" style="fill: #edeff1; stroke: #bac4ca; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="patch_27">
+ <path d="M 366.912 140.76
+L 381.168 140.76
+Q 383.04 140.76 383.04 138.888
+L 383.04 131.832
+Q 383.04 129.96 381.168 129.96
+L 366.912 129.96
+Q 365.04 129.96 365.04 131.832
+L 365.04 138.888
+Q 365.04 140.76 366.912 140.76
+z
+" clip-path="url(#p37831d8287)" style="fill: #edeff1; stroke: #bac4ca; stroke-width: 0.7; stroke-linejoin: miter"/>
+ </g>
+ <g id="text_1">
+ <!-- PLUGIN -->
+ <g style="fill: #20303c" transform="translate(9.72 11.375625) scale(0.06 -0.06)">
+ <defs>
+ <path id="DejaVuSans-Bold-50" d="M 588 4666
+L 2584 4666
+Q 3475 4666 3951 4270
+Q 4428 3875 4428 3144
+Q 4428 2409 3951 2014
+Q 3475 1619 2584 1619
+L 1791 1619
+L 1791 0
+L 588 0
+L 588 4666
+z
+M 1791 3794
+L 1791 2491
+L 2456 2491
+Q 2806 2491 2997 2661
+Q 3188 2831 3188 3144
+Q 3188 3456 2997 3625
+Q 2806 3794 2456 3794
+L 1791 3794
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-4c" d="M 588 4666
+L 1791 4666
+L 1791 909
+L 3903 909
+L 3903 0
+L 588 0
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-55" d="M 588 4666
+L 1791 4666
+L 1791 1869
+Q 1791 1291 1980 1042
+Q 2169 794 2597 794
+Q 3028 794 3217 1042
+Q 3406 1291 3406 1869
+L 3406 4666
+L 4609 4666
+L 4609 1869
+Q 4609 878 4112 393
+Q 3616 -91 2597 -91
+Q 1581 -91 1084 393
+Q 588 878 588 1869
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-47" d="M 4781 347
+Q 4331 128 3847 18
+Q 3363 -91 2847 -91
+Q 1681 -91 1000 561
+Q 319 1213 319 2328
+Q 319 3456 1012 4103
+Q 1706 4750 2913 4750
+Q 3378 4750 3804 4662
+Q 4231 4575 4609 4403
+L 4609 3438
+Q 4219 3659 3833 3768
+Q 3447 3878 3059 3878
+Q 2341 3878 1952 3476
+Q 1563 3075 1563 2328
+Q 1563 1588 1938 1184
+Q 2313 781 3003 781
+Q 3191 781 3352 804
+Q 3513 828 3641 878
+L 3641 1784
+L 2906 1784
+L 2906 2591
+L 4781 2591
+L 4781 347
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-49" d="M 588 4666
+L 1791 4666
+L 1791 0
+L 588 0
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-4e" d="M 588 4666
+L 1931 4666
+L 3628 1466
+L 3628 4666
+L 4769 4666
+L 4769 0
+L 3425 0
+L 1728 3200
+L 1728 0
+L 588 0
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-50"/>
+ <use xlink:href="#DejaVuSans-Bold-4c" transform="translate(73.291016 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-55" transform="translate(133.386719 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-47" transform="translate(214.587891 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-49" transform="translate(296.667969 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4e" transform="translate(333.875 0)"/>
+ </g>
+ </g>
+ <g id="text_2">
+ <!-- what it knows about this repository, -->
+ <g style="fill: #63727d" transform="translate(9.72 18.255281) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-77" d="M 269 3500
+L 844 3500
+L 1563 769
+L 2278 3500
+L 2956 3500
+L 3675 769
+L 4391 3500
+L 4966 3500
+L 4050 0
+L 3372 0
+L 2619 2869
+L 1863 0
+L 1184 0
+L 269 3500
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-68" d="M 3513 2113
+L 3513 0
+L 2938 0
+L 2938 2094
+Q 2938 2591 2744 2837
+Q 2550 3084 2163 3084
+Q 1697 3084 1428 2787
+Q 1159 2491 1159 1978
+L 1159 0
+L 581 0
+L 581 4863
+L 1159 4863
+L 1159 2956
+Q 1366 3272 1645 3428
+Q 1925 3584 2291 3584
+Q 2894 3584 3203 3211
+Q 3513 2838 3513 2113
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-61" d="M 2194 1759
+Q 1497 1759 1228 1600
+Q 959 1441 959 1056
+Q 959 750 1161 570
+Q 1363 391 1709 391
+Q 2188 391 2477 730
+Q 2766 1069 2766 1631
+L 2766 1759
+L 2194 1759
+z
+M 3341 1997
+L 3341 0
+L 2766 0
+L 2766 531
+Q 2569 213 2275 61
+Q 1981 -91 1556 -91
+Q 1019 -91 701 211
+Q 384 513 384 1019
+Q 384 1609 779 1909
+Q 1175 2209 1959 2209
+L 2766 2209
+L 2766 2266
+Q 2766 2663 2505 2880
+Q 2244 3097 1772 3097
+Q 1472 3097 1187 3025
+Q 903 2953 641 2809
+L 641 3341
+Q 956 3463 1253 3523
+Q 1550 3584 1831 3584
+Q 2591 3584 2966 3190
+Q 3341 2797 3341 1997
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-74" d="M 1172 4494
+L 1172 3500
+L 2356 3500
+L 2356 3053
+L 1172 3053
+L 1172 1153
+Q 1172 725 1289 603
+Q 1406 481 1766 481
+L 2356 481
+L 2356 0
+L 1766 0
+Q 1100 0 847 248
+Q 594 497 594 1153
+L 594 3053
+L 172 3053
+L 172 3500
+L 594 3500
+L 594 4494
+L 1172 4494
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-20" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-69" d="M 603 3500
+L 1178 3500
+L 1178 0
+L 603 0
+L 603 3500
+z
+M 603 4863
+L 1178 4863
+L 1178 4134
+L 603 4134
+L 603 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-6b" d="M 581 4863
+L 1159 4863
+L 1159 1991
+L 2875 3500
+L 3609 3500
+L 1753 1863
+L 3688 0
+L 2938 0
+L 1159 1709
+L 1159 0
+L 581 0
+L 581 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-6e" d="M 3513 2113
+L 3513 0
+L 2938 0
+L 2938 2094
+Q 2938 2591 2744 2837
+Q 2550 3084 2163 3084
+Q 1697 3084 1428 2787
+Q 1159 2491 1159 1978
+L 1159 0
+L 581 0
+L 581 3500
+L 1159 3500
+L 1159 2956
+Q 1366 3272 1645 3428
+Q 1925 3584 2291 3584
+Q 2894 3584 3203 3211
+Q 3513 2838 3513 2113
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-6f" d="M 1959 3097
+Q 1497 3097 1228 2736
+Q 959 2375 959 1747
+Q 959 1119 1226 758
+Q 1494 397 1959 397
+Q 2419 397 2687 759
+Q 2956 1122 2956 1747
+Q 2956 2369 2687 2733
+Q 2419 3097 1959 3097
+z
+M 1959 3584
+Q 2709 3584 3137 3096
+Q 3566 2609 3566 1747
+Q 3566 888 3137 398
+Q 2709 -91 1959 -91
+Q 1206 -91 779 398
+Q 353 888 353 1747
+Q 353 2609 779 3096
+Q 1206 3584 1959 3584
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-73" d="M 2834 3397
+L 2834 2853
+Q 2591 2978 2328 3040
+Q 2066 3103 1784 3103
+Q 1356 3103 1142 2972
+Q 928 2841 928 2578
+Q 928 2378 1081 2264
+Q 1234 2150 1697 2047
+L 1894 2003
+Q 2506 1872 2764 1633
+Q 3022 1394 3022 966
+Q 3022 478 2636 193
+Q 2250 -91 1575 -91
+Q 1294 -91 989 -36
+Q 684 19 347 128
+L 347 722
+Q 666 556 975 473
+Q 1284 391 1588 391
+Q 1994 391 2212 530
+Q 2431 669 2431 922
+Q 2431 1156 2273 1281
+Q 2116 1406 1581 1522
+L 1381 1569
+Q 847 1681 609 1914
+Q 372 2147 372 2553
+Q 372 3047 722 3315
+Q 1072 3584 1716 3584
+Q 2034 3584 2315 3537
+Q 2597 3491 2834 3397
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-62" d="M 3116 1747
+Q 3116 2381 2855 2742
+Q 2594 3103 2138 3103
+Q 1681 3103 1420 2742
+Q 1159 2381 1159 1747
+Q 1159 1113 1420 752
+Q 1681 391 2138 391
+Q 2594 391 2855 752
+Q 3116 1113 3116 1747
+z
+M 1159 2969
+Q 1341 3281 1617 3432
+Q 1894 3584 2278 3584
+Q 2916 3584 3314 3078
+Q 3713 2572 3713 1747
+Q 3713 922 3314 415
+Q 2916 -91 2278 -91
+Q 1894 -91 1617 61
+Q 1341 213 1159 525
+L 1159 0
+L 581 0
+L 581 4863
+L 1159 4863
+L 1159 2969
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-75" d="M 544 1381
+L 544 3500
+L 1119 3500
+L 1119 1403
+Q 1119 906 1312 657
+Q 1506 409 1894 409
+Q 2359 409 2629 706
+Q 2900 1003 2900 1516
+L 2900 3500
+L 3475 3500
+L 3475 0
+L 2900 0
+L 2900 538
+Q 2691 219 2414 64
+Q 2138 -91 1772 -91
+Q 1169 -91 856 284
+Q 544 659 544 1381
+z
+M 1991 3584
+L 1991 3584
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-72" d="M 2631 2963
+Q 2534 3019 2420 3045
+Q 2306 3072 2169 3072
+Q 1681 3072 1420 2755
+Q 1159 2438 1159 1844
+L 1159 0
+L 581 0
+L 581 3500
+L 1159 3500
+L 1159 2956
+Q 1341 3275 1631 3429
+Q 1922 3584 2338 3584
+Q 2397 3584 2469 3576
+Q 2541 3569 2628 3553
+L 2631 2963
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-65" d="M 3597 1894
+L 3597 1613
+L 953 1613
+Q 991 1019 1311 708
+Q 1631 397 2203 397
+Q 2534 397 2845 478
+Q 3156 559 3463 722
+L 3463 178
+Q 3153 47 2828 -22
+Q 2503 -91 2169 -91
+Q 1331 -91 842 396
+Q 353 884 353 1716
+Q 353 2575 817 3079
+Q 1281 3584 2069 3584
+Q 2775 3584 3186 3129
+Q 3597 2675 3597 1894
+z
+M 3022 2063
+Q 3016 2534 2758 2815
+Q 2500 3097 2075 3097
+Q 1594 3097 1305 2825
+Q 1016 2553 972 2059
+L 3022 2063
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-70" d="M 1159 525
+L 1159 -1331
+L 581 -1331
+L 581 3500
+L 1159 3500
+L 1159 2969
+Q 1341 3281 1617 3432
+Q 1894 3584 2278 3584
+Q 2916 3584 3314 3078
+Q 3713 2572 3713 1747
+Q 3713 922 3314 415
+Q 2916 -91 2278 -91
+Q 1894 -91 1617 61
+Q 1341 213 1159 525
+z
+M 3116 1747
+Q 3116 2381 2855 2742
+Q 2594 3103 2138 3103
+Q 1681 3103 1420 2742
+Q 1159 2381 1159 1747
+Q 1159 1113 1420 752
+Q 1681 391 2138 391
+Q 2594 391 2855 752
+Q 3116 1113 3116 1747
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-79" d="M 2059 -325
+Q 1816 -950 1584 -1140
+Q 1353 -1331 966 -1331
+L 506 -1331
+L 506 -850
+L 844 -850
+Q 1081 -850 1212 -737
+Q 1344 -625 1503 -206
+L 1606 56
+L 191 3500
+L 800 3500
+L 1894 763
+L 2988 3500
+L 3597 3500
+L 2059 -325
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-2c" d="M 750 794
+L 1409 794
+L 1409 256
+L 897 -744
+L 494 -744
+L 750 256
+L 750 794
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-77"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(81.787109 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(145.166016 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(206.445312 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(245.654297 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(277.441406 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(305.224609 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(344.433594 0)"/>
+ <use xlink:href="#DejaVuSans-6b" transform="translate(376.220703 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(434.130859 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(497.509766 0)"/>
+ <use xlink:href="#DejaVuSans-77" transform="translate(558.691406 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(640.478516 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(692.578125 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(724.365234 0)"/>
+ <use xlink:href="#DejaVuSans-62" transform="translate(785.644531 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(849.121094 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(910.302734 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(973.681641 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1012.890625 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1044.677734 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(1083.886719 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1147.265625 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1175.048828 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1227.148438 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1258.935547 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1297.798828 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(1359.322266 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1422.798828 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1483.980469 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1536.080078 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1563.863281 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1603.072266 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1664.253906 0)"/>
+ <use xlink:href="#DejaVuSans-79" transform="translate(1705.367188 0)"/>
+ <use xlink:href="#DejaVuSans-2c" transform="translate(1764.546875 0)"/>
+ </g>
+ <!-- from the sessions before this one -->
+ <g style="fill: #63727d" transform="translate(9.72 23.755803) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-66" d="M 2375 4863
+L 2375 4384
+L 1825 4384
+Q 1516 4384 1395 4259
+Q 1275 4134 1275 3809
+L 1275 3500
+L 2222 3500
+L 2222 3053
+L 1275 3053
+L 1275 0
+L 697 0
+L 697 3053
+L 147 3053
+L 147 3500
+L 697 3500
+L 697 3744
+Q 697 4328 969 4595
+Q 1241 4863 1831 4863
+L 2375 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-6d" d="M 3328 2828
+Q 3544 3216 3844 3400
+Q 4144 3584 4550 3584
+Q 5097 3584 5394 3201
+Q 5691 2819 5691 2113
+L 5691 0
+L 5113 0
+L 5113 2094
+Q 5113 2597 4934 2840
+Q 4756 3084 4391 3084
+Q 3944 3084 3684 2787
+Q 3425 2491 3425 1978
+L 3425 0
+L 2847 0
+L 2847 2094
+Q 2847 2600 2669 2842
+Q 2491 3084 2119 3084
+Q 1678 3084 1418 2786
+Q 1159 2488 1159 1978
+L 1159 0
+L 581 0
+L 581 3500
+L 1159 3500
+L 1159 2956
+Q 1356 3278 1631 3431
+Q 1906 3584 2284 3584
+Q 2666 3584 2933 3390
+Q 3200 3197 3328 2828
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-66"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(35.205078 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(74.068359 0)"/>
+ <use xlink:href="#DejaVuSans-6d" transform="translate(135.25 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(232.662109 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(264.449219 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(303.658203 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(367.037109 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(428.560547 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(460.347656 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(512.447266 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(573.970703 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(626.070312 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(678.169922 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(705.953125 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(767.134766 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(830.513672 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(882.613281 0)"/>
+ <use xlink:href="#DejaVuSans-62" transform="translate(914.400391 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(977.876953 0)"/>
+ <use xlink:href="#DejaVuSans-66" transform="translate(1039.400391 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1074.605469 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1135.787109 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1174.650391 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1236.173828 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1267.960938 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(1307.169922 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1370.548828 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1398.332031 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1450.431641 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1482.21875 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1543.400391 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1606.779297 0)"/>
+ </g>
+ </g>
+ <g id="text_3">
+ <!-- Micro-skills -->
+ <g style="fill: #3e73a8" transform="translate(22.68 43.360437) scale(0.058 -0.058)">
+ <defs>
+ <path id="DejaVuSans-Bold-4d" d="M 588 4666
+L 2119 4666
+L 3181 2169
+L 4250 4666
+L 5778 4666
+L 5778 0
+L 4641 0
+L 4641 3413
+L 3566 897
+L 2803 897
+L 1728 3413
+L 1728 0
+L 588 0
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-69" d="M 538 3500
+L 1656 3500
+L 1656 0
+L 538 0
+L 538 3500
+z
+M 538 4863
+L 1656 4863
+L 1656 3950
+L 538 3950
+L 538 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-63" d="M 3366 3391
+L 3366 2478
+Q 3138 2634 2908 2709
+Q 2678 2784 2431 2784
+Q 1963 2784 1702 2511
+Q 1441 2238 1441 1747
+Q 1441 1256 1702 982
+Q 1963 709 2431 709
+Q 2694 709 2930 787
+Q 3166 866 3366 1019
+L 3366 103
+Q 3103 6 2833 -42
+Q 2563 -91 2291 -91
+Q 1344 -91 809 395
+Q 275 881 275 1747
+Q 275 2613 809 3098
+Q 1344 3584 2291 3584
+Q 2566 3584 2833 3536
+Q 3100 3488 3366 3391
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-72" d="M 3138 2547
+Q 2991 2616 2845 2648
+Q 2700 2681 2553 2681
+Q 2122 2681 1889 2404
+Q 1656 2128 1656 1613
+L 1656 0
+L 538 0
+L 538 3500
+L 1656 3500
+L 1656 2925
+Q 1872 3269 2151 3426
+Q 2431 3584 2822 3584
+Q 2878 3584 2943 3579
+Q 3009 3575 3134 3559
+L 3138 2547
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-6f" d="M 2203 2784
+Q 1831 2784 1636 2517
+Q 1441 2250 1441 1747
+Q 1441 1244 1636 976
+Q 1831 709 2203 709
+Q 2569 709 2762 976
+Q 2956 1244 2956 1747
+Q 2956 2250 2762 2517
+Q 2569 2784 2203 2784
+z
+M 2203 3584
+Q 3106 3584 3614 3096
+Q 4122 2609 4122 1747
+Q 4122 884 3614 396
+Q 3106 -91 2203 -91
+Q 1297 -91 786 396
+Q 275 884 275 1747
+Q 275 2609 786 3096
+Q 1297 3584 2203 3584
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-2d" d="M 347 2297
+L 2309 2297
+L 2309 1388
+L 347 1388
+L 347 2297
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-73" d="M 3272 3391
+L 3272 2541
+Q 2913 2691 2578 2766
+Q 2244 2841 1947 2841
+Q 1628 2841 1473 2761
+Q 1319 2681 1319 2516
+Q 1319 2381 1436 2309
+Q 1553 2238 1856 2203
+L 2053 2175
+Q 2913 2066 3209 1816
+Q 3506 1566 3506 1031
+Q 3506 472 3093 190
+Q 2681 -91 1863 -91
+Q 1516 -91 1145 -36
+Q 775 19 384 128
+L 384 978
+Q 719 816 1070 734
+Q 1422 653 1784 653
+Q 2113 653 2278 743
+Q 2444 834 2444 1013
+Q 2444 1163 2330 1236
+Q 2216 1309 1875 1350
+L 1678 1375
+Q 931 1469 631 1722
+Q 331 1975 331 2491
+Q 331 3047 712 3315
+Q 1094 3584 1881 3584
+Q 2191 3584 2531 3537
+Q 2872 3491 3272 3391
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-6b" d="M 538 4863
+L 1656 4863
+L 1656 2216
+L 2944 3500
+L 4244 3500
+L 2534 1894
+L 4378 0
+L 3022 0
+L 1656 1459
+L 1656 0
+L 538 0
+L 538 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-6c" d="M 538 4863
+L 1656 4863
+L 1656 0
+L 538 0
+L 538 4863
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-4d"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(99.511719 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-63" transform="translate(133.789062 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(193.066406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(242.382812 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-2d" transform="translate(311.083984 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(352.587891 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6b" transform="translate(412.109375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(478.613281 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(512.890625 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(547.167969 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(581.445312 0)"/>
+ </g>
+ </g>
+ <g id="text_4">
+ <!-- repository facts learned from failures -->
+ <g style="fill: #63727d" transform="translate(12.24 53.895281) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-63" d="M 3122 3366
+L 3122 2828
+Q 2878 2963 2633 3030
+Q 2388 3097 2138 3097
+Q 1578 3097 1268 2742
+Q 959 2388 959 1747
+Q 959 1106 1268 751
+Q 1578 397 2138 397
+Q 2388 397 2633 464
+Q 2878 531 3122 666
+L 3122 134
+Q 2881 22 2623 -34
+Q 2366 -91 2075 -91
+Q 1284 -91 818 406
+Q 353 903 353 1747
+Q 353 2603 823 3093
+Q 1294 3584 2113 3584
+Q 2378 3584 2631 3529
+Q 2884 3475 3122 3366
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-6c" d="M 603 4863
+L 1178 4863
+L 1178 0
+L 603 0
+L 603 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-64" d="M 2906 2969
+L 2906 4863
+L 3481 4863
+L 3481 0
+L 2906 0
+L 2906 525
+Q 2725 213 2448 61
+Q 2172 -91 1784 -91
+Q 1150 -91 751 415
+Q 353 922 353 1747
+Q 353 2572 751 3078
+Q 1150 3584 1784 3584
+Q 2172 3584 2448 3432
+Q 2725 3281 2906 2969
+z
+M 947 1747
+Q 947 1113 1208 752
+Q 1469 391 1925 391
+Q 2381 391 2643 752
+Q 2906 1113 2906 1747
+Q 2906 2381 2643 2742
+Q 2381 3103 1925 3103
+Q 1469 3103 1208 2742
+Q 947 2381 947 1747
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-72"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(38.863281 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(100.386719 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(163.863281 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(225.044922 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(277.144531 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(304.927734 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(344.136719 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(405.318359 0)"/>
+ <use xlink:href="#DejaVuSans-79" transform="translate(446.431641 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(505.611328 0)"/>
+ <use xlink:href="#DejaVuSans-66" transform="translate(537.398438 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(572.603516 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(633.882812 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(688.863281 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(728.072266 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(780.171875 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(811.958984 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(839.742188 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(901.265625 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(962.544922 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1001.908203 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1065.287109 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(1126.810547 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1190.287109 0)"/>
+ <use xlink:href="#DejaVuSans-66" transform="translate(1222.074219 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1257.279297 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1296.142578 0)"/>
+ <use xlink:href="#DejaVuSans-6d" transform="translate(1357.324219 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1454.736328 0)"/>
+ <use xlink:href="#DejaVuSans-66" transform="translate(1486.523438 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(1521.728516 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1583.007812 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(1610.791016 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(1638.574219 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1701.953125 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1740.816406 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1802.339844 0)"/>
+ </g>
+ <!-- that recur across finished sessions -->
+ <g style="fill: #63727d" transform="translate(12.24 59.395803) scale(0.046 -0.046)">
+ <use xlink:href="#DejaVuSans-74"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(39.208984 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(102.587891 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(163.867188 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(203.076172 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(234.863281 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(273.726562 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(335.25 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(390.230469 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(453.609375 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(494.722656 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(526.509766 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(587.789062 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(642.769531 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(681.632812 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(742.814453 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(794.914062 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(847.013672 0)"/>
+ <use xlink:href="#DejaVuSans-66" transform="translate(878.800781 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(914.005859 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(941.789062 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1005.167969 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1032.951172 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(1085.050781 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1148.429688 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(1209.953125 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1273.429688 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1305.216797 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1357.316406 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1418.839844 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1470.939453 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1523.039062 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1550.822266 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1612.003906 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1675.382812 0)"/>
+ </g>
+ </g>
+ <g id="text_5">
+ <!-- Tool pruning -->
+ <g style="fill: #bc7d14" transform="translate(22.68 86.177781) scale(0.058 -0.058)">
+ <defs>
+ <path id="DejaVuSans-Bold-54" d="M 31 4666
+L 4331 4666
+L 4331 3756
+L 2784 3756
+L 2784 0
+L 1581 0
+L 1581 3756
+L 31 3756
+L 31 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-20" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-70" d="M 1656 506
+L 1656 -1331
+L 538 -1331
+L 538 3500
+L 1656 3500
+L 1656 2988
+Q 1888 3294 2169 3439
+Q 2450 3584 2816 3584
+Q 3463 3584 3878 3070
+Q 4294 2556 4294 1747
+Q 4294 938 3878 423
+Q 3463 -91 2816 -91
+Q 2450 -91 2169 54
+Q 1888 200 1656 506
+z
+M 2400 2772
+Q 2041 2772 1848 2508
+Q 1656 2244 1656 1747
+Q 1656 1250 1848 986
+Q 2041 722 2400 722
+Q 2759 722 2948 984
+Q 3138 1247 3138 1747
+Q 3138 2247 2948 2509
+Q 2759 2772 2400 2772
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-75" d="M 500 1363
+L 500 3500
+L 1625 3500
+L 1625 3150
+Q 1625 2866 1622 2436
+Q 1619 2006 1619 1863
+Q 1619 1441 1641 1255
+Q 1663 1069 1716 984
+Q 1784 875 1895 815
+Q 2006 756 2150 756
+Q 2500 756 2700 1025
+Q 2900 1294 2900 1772
+L 2900 3500
+L 4019 3500
+L 4019 0
+L 2900 0
+L 2900 506
+Q 2647 200 2364 54
+Q 2081 -91 1741 -91
+Q 1134 -91 817 281
+Q 500 653 500 1363
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-6e" d="M 4056 2131
+L 4056 0
+L 2931 0
+L 2931 347
+L 2931 1631
+Q 2931 2084 2911 2256
+Q 2891 2428 2841 2509
+Q 2775 2619 2662 2680
+Q 2550 2741 2406 2741
+Q 2056 2741 1856 2470
+Q 1656 2200 1656 1722
+L 1656 0
+L 538 0
+L 538 3500
+L 1656 3500
+L 1656 2988
+Q 1909 3294 2193 3439
+Q 2478 3584 2822 3584
+Q 3428 3584 3742 3212
+Q 4056 2841 4056 2131
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-67" d="M 2919 594
+Q 2688 288 2409 144
+Q 2131 0 1766 0
+Q 1125 0 706 504
+Q 288 1009 288 1791
+Q 288 2575 706 3076
+Q 1125 3578 1766 3578
+Q 2131 3578 2409 3434
+Q 2688 3291 2919 2981
+L 2919 3500
+L 4044 3500
+L 4044 353
+Q 4044 -491 3511 -936
+Q 2978 -1381 1966 -1381
+Q 1638 -1381 1331 -1331
+Q 1025 -1281 716 -1178
+L 716 -306
+Q 1009 -475 1290 -558
+Q 1572 -641 1856 -641
+Q 2406 -641 2662 -400
+Q 2919 -159 2919 353
+L 2919 594
+z
+M 2181 2772
+Q 1834 2772 1640 2515
+Q 1447 2259 1447 1791
+Q 1447 1309 1634 1061
+Q 1822 813 2181 813
+Q 2531 813 2725 1069
+Q 2919 1325 2919 1791
+Q 2919 2259 2725 2515
+Q 2531 2772 2181 2772
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-54"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(54.962891 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(123.664062 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(192.365234 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(226.642578 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-70" transform="translate(261.457031 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(333.039062 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-75" transform="translate(382.355469 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(453.546875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(524.738281 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(559.015625 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-67" transform="translate(630.207031 0)"/>
+ </g>
+ </g>
+ <g id="text_6">
+ <!-- tools left unused session after session -->
+ <g style="fill: #63727d" transform="translate(12.24 96.735281) scale(0.046 -0.046)">
+ <use xlink:href="#DejaVuSans-74"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(39.208984 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(100.390625 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(161.572266 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(189.355469 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(241.455078 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(273.242188 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(301.025391 0)"/>
+ <use xlink:href="#DejaVuSans-66" transform="translate(362.548828 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(396.003906 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(435.212891 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(467 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(530.378906 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(593.757812 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(657.136719 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(709.236328 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(770.759766 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(834.236328 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(866.023438 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(918.123047 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(979.646484 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1031.746094 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1083.845703 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1111.628906 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1172.810547 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1236.189453 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(1267.976562 0)"/>
+ <use xlink:href="#DejaVuSans-66" transform="translate(1329.255859 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1362.710938 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1401.919922 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1463.443359 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1504.556641 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1536.34375 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1588.443359 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1649.966797 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1702.066406 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1754.166016 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1781.949219 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1843.130859 0)"/>
+ </g>
+ <!-- go on a deny list once you approve it -->
+ <g style="fill: #63727d" transform="translate(12.24 102.235803) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-67" d="M 2906 1791
+Q 2906 2416 2648 2759
+Q 2391 3103 1925 3103
+Q 1463 3103 1205 2759
+Q 947 2416 947 1791
+Q 947 1169 1205 825
+Q 1463 481 1925 481
+Q 2391 481 2648 825
+Q 2906 1169 2906 1791
+z
+M 3481 434
+Q 3481 -459 3084 -895
+Q 2688 -1331 1869 -1331
+Q 1566 -1331 1297 -1286
+Q 1028 -1241 775 -1147
+L 775 -588
+Q 1028 -725 1275 -790
+Q 1522 -856 1778 -856
+Q 2344 -856 2625 -561
+Q 2906 -266 2906 331
+L 2906 616
+Q 2728 306 2450 153
+Q 2172 0 1784 0
+Q 1141 0 747 490
+Q 353 981 353 1791
+Q 353 2603 747 3093
+Q 1141 3584 1784 3584
+Q 2172 3584 2450 3431
+Q 2728 3278 2906 2969
+L 2906 3500
+L 3481 3500
+L 3481 434
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-76" d="M 191 3500
+L 800 3500
+L 1894 563
+L 2988 3500
+L 3597 3500
+L 2284 0
+L 1503 0
+L 191 3500
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-67"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(63.476562 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(124.658203 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(156.445312 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(217.626953 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(281.005859 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(312.792969 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(374.072266 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(405.859375 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(469.335938 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(530.859375 0)"/>
+ <use xlink:href="#DejaVuSans-79" transform="translate(594.238281 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(653.417969 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(685.205078 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(712.988281 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(740.771484 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(792.871094 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(832.080078 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(863.867188 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(925.048828 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(988.427734 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1043.408203 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1104.931641 0)"/>
+ <use xlink:href="#DejaVuSans-79" transform="translate(1136.71875 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1195.898438 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(1257.080078 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1320.458984 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(1352.246094 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(1413.525391 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(1477.001953 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1540.478516 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1579.341797 0)"/>
+ <use xlink:href="#DejaVuSans-76" transform="translate(1640.523438 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1699.703125 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1761.226562 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1793.013672 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1820.796875 0)"/>
+ </g>
+ </g>
+ <g id="text_7">
+ <!-- Failure-loop intervention -->
+ <g style="fill: #bf4f4b" transform="translate(22.68 129.040437) scale(0.058 -0.058)">
+ <defs>
+ <path id="DejaVuSans-Bold-46" d="M 588 4666
+L 3834 4666
+L 3834 3756
+L 1791 3756
+L 1791 2888
+L 3713 2888
+L 3713 1978
+L 1791 1978
+L 1791 0
+L 588 0
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-61" d="M 2106 1575
+Q 1756 1575 1579 1456
+Q 1403 1338 1403 1106
+Q 1403 894 1545 773
+Q 1688 653 1941 653
+Q 2256 653 2472 879
+Q 2688 1106 2688 1447
+L 2688 1575
+L 2106 1575
+z
+M 3816 1997
+L 3816 0
+L 2688 0
+L 2688 519
+Q 2463 200 2181 54
+Q 1900 -91 1497 -91
+Q 953 -91 614 226
+Q 275 544 275 1050
+Q 275 1666 698 1953
+Q 1122 2241 2028 2241
+L 2688 2241
+L 2688 2328
+Q 2688 2594 2478 2717
+Q 2269 2841 1825 2841
+Q 1466 2841 1156 2769
+Q 847 2697 581 2553
+L 581 3406
+Q 941 3494 1303 3539
+Q 1666 3584 2028 3584
+Q 2975 3584 3395 3211
+Q 3816 2838 3816 1997
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-65" d="M 4031 1759
+L 4031 1441
+L 1416 1441
+Q 1456 1047 1700 850
+Q 1944 653 2381 653
+Q 2734 653 3104 758
+Q 3475 863 3866 1075
+L 3866 213
+Q 3469 63 3072 -14
+Q 2675 -91 2278 -91
+Q 1328 -91 801 392
+Q 275 875 275 1747
+Q 275 2603 792 3093
+Q 1309 3584 2216 3584
+Q 3041 3584 3536 3087
+Q 4031 2591 4031 1759
+z
+M 2881 2131
+Q 2881 2450 2695 2645
+Q 2509 2841 2209 2841
+Q 1884 2841 1681 2658
+Q 1478 2475 1428 2131
+L 2881 2131
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-74" d="M 1759 4494
+L 1759 3500
+L 2913 3500
+L 2913 2700
+L 1759 2700
+L 1759 1216
+Q 1759 972 1856 886
+Q 1953 800 2241 800
+L 2816 800
+L 2816 0
+L 1856 0
+Q 1194 0 917 276
+Q 641 553 641 1216
+L 641 2700
+L 84 2700
+L 84 3500
+L 641 3500
+L 641 4494
+L 1759 4494
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-76" d="M 97 3500
+L 1216 3500
+L 2088 1081
+L 2956 3500
+L 4078 3500
+L 2700 0
+L 1472 0
+L 97 3500
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-46"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(62.435547 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(129.916016 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(164.193359 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-75" transform="translate(198.470703 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(269.662109 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(318.978516 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-2d" transform="translate(386.800781 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(428.304688 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(462.582031 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(531.283203 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-70" transform="translate(599.984375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(671.566406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(706.380859 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(740.658203 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(811.849609 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(859.652344 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(927.474609 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-76" transform="translate(976.791016 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(1041.976562 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(1109.798828 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(1180.990234 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(1228.792969 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(1263.070312 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(1331.771484 0)"/>
+ </g>
+ </g>
+ <g id="text_8">
+ <!-- learns how long turns here usually run; -->
+ <g style="fill: #63727d" transform="translate(12.24 139.575281) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-3b" d="M 750 3309
+L 1409 3309
+L 1409 2516
+L 750 2516
+L 750 3309
+z
+M 750 794
+L 1409 794
+L 1409 256
+L 897 -744
+L 494 -744
+L 750 256
+L 750 794
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-6c"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(27.783203 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(89.306641 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(150.585938 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(189.949219 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(253.328125 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(305.427734 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(337.214844 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(400.59375 0)"/>
+ <use xlink:href="#DejaVuSans-77" transform="translate(461.775391 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(543.5625 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(575.349609 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(603.132812 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(664.314453 0)"/>
+ <use xlink:href="#DejaVuSans-67" transform="translate(727.693359 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(791.169922 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(822.957031 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(862.166016 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(925.544922 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(964.908203 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1028.287109 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1080.386719 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(1112.173828 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1175.552734 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1237.076172 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1275.939453 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1337.462891 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(1369.25 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1432.628906 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(1484.728516 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(1548.107422 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(1609.386719 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(1637.169922 0)"/>
+ <use xlink:href="#DejaVuSans-79" transform="translate(1664.953125 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1724.132812 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1755.919922 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(1797.033203 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1860.412109 0)"/>
+ <use xlink:href="#DejaVuSans-3b" transform="translate(1923.791016 0)"/>
+ </g>
+ <!-- one redirect, then a stop or a notice -->
+ <g style="fill: #63727d" transform="translate(12.24 145.075803) scale(0.046 -0.046)">
+ <use xlink:href="#DejaVuSans-6f"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(61.181641 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(124.560547 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(186.083984 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(217.871094 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(256.734375 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(318.257812 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(381.734375 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(409.517578 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(448.380859 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(509.904297 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(564.884766 0)"/>
+ <use xlink:href="#DejaVuSans-2c" transform="translate(604.09375 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(635.880859 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(667.667969 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(706.876953 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(770.255859 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(831.779297 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(895.158203 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(926.945312 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(988.224609 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1020.011719 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1072.111328 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1111.320312 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(1172.501953 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1235.978516 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1267.765625 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1328.947266 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1370.060547 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(1401.847656 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1463.126953 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1494.914062 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1558.292969 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1619.474609 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1658.683594 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(1686.466797 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1741.447266 0)"/>
+ </g>
+ </g>
+ <g id="text_9">
+ <!-- SESSION END -->
+ <g style="fill: #20303c" transform="translate(9.72 175.78525) scale(0.056 -0.056)">
+ <defs>
+ <path id="DejaVuSans-Bold-53" d="M 3834 4519
+L 3834 3531
+Q 3450 3703 3084 3790
+Q 2719 3878 2394 3878
+Q 1963 3878 1756 3759
+Q 1550 3641 1550 3391
+Q 1550 3203 1689 3098
+Q 1828 2994 2194 2919
+L 2706 2816
+Q 3484 2659 3812 2340
+Q 4141 2022 4141 1434
+Q 4141 663 3683 286
+Q 3225 -91 2284 -91
+Q 1841 -91 1394 -6
+Q 947 78 500 244
+L 500 1259
+Q 947 1022 1364 901
+Q 1781 781 2169 781
+Q 2563 781 2772 912
+Q 2981 1044 2981 1288
+Q 2981 1506 2839 1625
+Q 2697 1744 2272 1838
+L 1806 1941
+Q 1106 2091 782 2419
+Q 459 2747 459 3303
+Q 459 4000 909 4375
+Q 1359 4750 2203 4750
+Q 2588 4750 2994 4692
+Q 3400 4634 3834 4519
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-45" d="M 588 4666
+L 3834 4666
+L 3834 3756
+L 1791 3756
+L 1791 2888
+L 3713 2888
+L 3713 1978
+L 1791 1978
+L 1791 909
+L 3903 909
+L 3903 0
+L 588 0
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-4f" d="M 2719 3878
+Q 2169 3878 1866 3472
+Q 1563 3066 1563 2328
+Q 1563 1594 1866 1187
+Q 2169 781 2719 781
+Q 3272 781 3575 1187
+Q 3878 1594 3878 2328
+Q 3878 3066 3575 3472
+Q 3272 3878 2719 3878
+z
+M 2719 4750
+Q 3844 4750 4481 4106
+Q 5119 3463 5119 2328
+Q 5119 1197 4481 553
+Q 3844 -91 2719 -91
+Q 1597 -91 958 553
+Q 319 1197 319 2328
+Q 319 3463 958 4106
+Q 1597 4750 2719 4750
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-44" d="M 1791 3756
+L 1791 909
+L 2222 909
+Q 2959 909 3348 1275
+Q 3738 1641 3738 2338
+Q 3738 3031 3350 3393
+Q 2963 3756 2222 3756
+L 1791 3756
+z
+M 588 4666
+L 1856 4666
+Q 2919 4666 3439 4514
+Q 3959 4363 4331 4000
+Q 4659 3684 4818 3271
+Q 4978 2859 4978 2338
+Q 4978 1809 4818 1395
+Q 4659 981 4331 666
+Q 3956 303 3431 151
+Q 2906 0 1856 0
+L 588 0
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-53"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(72.021484 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-53" transform="translate(140.332031 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-53" transform="translate(207.853516 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-49" transform="translate(279.875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4f" transform="translate(317.082031 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4e" transform="translate(402.091797 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(485.783203 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(520.597656 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4e" transform="translate(588.908203 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-44" transform="translate(672.599609 0)"/>
+ </g>
+ </g>
+ <g id="text_10">
+ <!-- its log updates what all three -->
+ <g style="fill: #63727d" transform="translate(9.72 185.295281) scale(0.046 -0.046)">
+ <use xlink:href="#DejaVuSans-69"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(27.783203 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(66.992188 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(119.091797 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(150.878906 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(178.662109 0)"/>
+ <use xlink:href="#DejaVuSans-67" transform="translate(239.84375 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(303.320312 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(335.107422 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(398.486328 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(461.962891 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(525.439453 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(586.71875 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(625.927734 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(687.451172 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(739.550781 0)"/>
+ <use xlink:href="#DejaVuSans-77" transform="translate(771.337891 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(853.125 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(916.503906 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(977.783203 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1016.992188 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(1048.779297 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(1110.058594 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(1137.841797 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1165.625 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1197.412109 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(1236.621094 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1300 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1338.863281 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1400.386719 0)"/>
+ </g>
+ <!-- mechanisms know about the repository -->
+ <g style="fill: #63727d" transform="translate(9.72 190.795803) scale(0.046 -0.046)">
+ <use xlink:href="#DejaVuSans-6d"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(97.412109 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(158.935547 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(213.916016 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(277.294922 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(338.574219 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(401.953125 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(429.736328 0)"/>
+ <use xlink:href="#DejaVuSans-6d" transform="translate(481.835938 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(579.248047 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(631.347656 0)"/>
+ <use xlink:href="#DejaVuSans-6b" transform="translate(663.134766 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(721.044922 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(784.423828 0)"/>
+ <use xlink:href="#DejaVuSans-77" transform="translate(845.605469 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(927.392578 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(959.179688 0)"/>
+ <use xlink:href="#DejaVuSans-62" transform="translate(1020.458984 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1083.935547 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(1145.117188 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1208.496094 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1247.705078 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1279.492188 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(1318.701172 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1382.080078 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1443.603516 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1475.390625 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(1514.253906 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(1575.777344 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1639.253906 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1700.435547 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1752.535156 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1780.318359 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1819.527344 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1880.708984 0)"/>
+ <use xlink:href="#DejaVuSans-79" transform="translate(1921.822266 0)"/>
+ </g>
+ </g>
+ <g id="text_11">
+ <!-- YOUR CODING AGENT -->
+ <g style="fill: #20303c" transform="translate(138.24 11.375625) scale(0.06 -0.06)">
+ <defs>
+ <path id="DejaVuSans-Bold-59" d="M -63 4666
+L 1253 4666
+L 2316 3003
+L 3378 4666
+L 4697 4666
+L 2919 1966
+L 2919 0
+L 1716 0
+L 1716 1966
+L -63 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-52" d="M 2297 2597
+Q 2675 2597 2839 2737
+Q 3003 2878 3003 3200
+Q 3003 3519 2839 3656
+Q 2675 3794 2297 3794
+L 1791 3794
+L 1791 2597
+L 2297 2597
+z
+M 1791 1766
+L 1791 0
+L 588 0
+L 588 4666
+L 2425 4666
+Q 3347 4666 3776 4356
+Q 4206 4047 4206 3378
+Q 4206 2916 3982 2619
+Q 3759 2322 3309 2181
+Q 3556 2125 3751 1926
+Q 3947 1728 4147 1325
+L 4800 0
+L 3519 0
+L 2950 1159
+Q 2778 1509 2601 1637
+Q 2425 1766 2131 1766
+L 1791 1766
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-43" d="M 4288 256
+Q 3956 84 3597 -3
+Q 3238 -91 2847 -91
+Q 1681 -91 1000 561
+Q 319 1213 319 2328
+Q 319 3447 1000 4098
+Q 1681 4750 2847 4750
+Q 3238 4750 3597 4662
+Q 3956 4575 4288 4403
+L 4288 3438
+Q 3953 3666 3628 3772
+Q 3303 3878 2944 3878
+Q 2300 3878 1931 3465
+Q 1563 3053 1563 2328
+Q 1563 1606 1931 1193
+Q 2300 781 2944 781
+Q 3303 781 3628 887
+Q 3953 994 4288 1222
+L 4288 256
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-41" d="M 3419 850
+L 1538 850
+L 1241 0
+L 31 0
+L 1759 4666
+L 3194 4666
+L 4922 0
+L 3713 0
+L 3419 850
+z
+M 1838 1716
+L 3116 1716
+L 2478 3572
+L 1838 1716
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-59"/>
+ <use xlink:href="#DejaVuSans-Bold-4f" transform="translate(68.787109 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-55" transform="translate(153.796875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-52" transform="translate(234.998047 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(312 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-43" transform="translate(346.814453 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4f" transform="translate(420.203125 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-44" transform="translate(505.212891 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-49" transform="translate(588.220703 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4e" transform="translate(625.427734 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-47" transform="translate(709.119141 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(791.199219 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-41" transform="translate(826.013672 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-47" transform="translate(903.40625 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(985.486328 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4e" transform="translate(1053.796875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-54" transform="translate(1137.488281 0)"/>
+ </g>
+ </g>
+ <g id="text_12">
+ <!-- (unchanged) -->
+ <g style="fill: #63727d" transform="translate(215.73 10.989313) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-28" d="M 1984 4856
+Q 1566 4138 1362 3434
+Q 1159 2731 1159 2009
+Q 1159 1288 1364 580
+Q 1569 -128 1984 -844
+L 1484 -844
+Q 1016 -109 783 600
+Q 550 1309 550 2009
+Q 550 2706 781 3412
+Q 1013 4119 1484 4856
+L 1984 4856
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-29" d="M 513 4856
+L 1013 4856
+Q 1481 4119 1714 3412
+Q 1947 2706 1947 2009
+Q 1947 1309 1714 600
+Q 1481 -109 1013 -844
+L 513 -844
+Q 928 -128 1133 580
+Q 1338 1288 1338 2009
+Q 1338 2731 1133 3434
+Q 928 4138 513 4856
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-28"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(39.013672 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(102.392578 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(165.771484 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(220.751953 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(284.130859 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(345.410156 0)"/>
+ <use xlink:href="#DejaVuSans-67" transform="translate(408.789062 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(472.265625 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(533.789062 0)"/>
+ <use xlink:href="#DejaVuSans-29" transform="translate(597.265625 0)"/>
+ </g>
+ </g>
+ <g id="patch_28">
+ <path d="M 286.794 14.184
+L 378.576 14.184
+Q 383.04 14.184 383.04 9.72
+L 383.04 9.72
+Q 383.04 5.256 378.576 5.256
+L 286.794 5.256
+Q 282.33 5.256 282.33 9.72
+L 282.33 9.72
+Q 282.33 14.184 286.794 14.184
+z
+" clip-path="url(#p37831d8287)" style="fill: #e7ecef"/>
+ </g>
+ <g id="text_13">
+ <!-- KNOWLEDGE -->
+ <g style="fill: #3e73a8" transform="translate(149.04 38.26525) scale(0.056 -0.056)">
+ <defs>
+ <path id="DejaVuSans-Bold-4b" d="M 588 4666
+L 1791 4666
+L 1791 2963
+L 3525 4666
+L 4922 4666
+L 2675 2456
+L 5153 0
+L 3647 0
+L 1791 1838
+L 1791 0
+L 588 0
+L 588 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-57" d="M 191 4666
+L 1344 4666
+L 2150 1275
+L 2950 4666
+L 4109 4666
+L 4909 1275
+L 5716 4666
+L 6859 4666
+L 5759 0
+L 4372 0
+L 3525 3547
+L 2688 0
+L 1300 0
+L 191 4666
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-4b"/>
+ <use xlink:href="#DejaVuSans-Bold-4e" transform="translate(77.490234 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4f" transform="translate(161.181641 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-57" transform="translate(246.191406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4c" transform="translate(356.494141 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(420.214844 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-44" transform="translate(488.525391 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-47" transform="translate(571.533203 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(653.613281 0)"/>
+ </g>
+ </g>
+ <g id="text_14">
+ <!-- session context -->
+ <g style="fill: #20303c" transform="translate(193.86 38.26525) scale(0.056 -0.056)">
+ <defs>
+ <path id="DejaVuSans-78" d="M 3513 3500
+L 2247 1797
+L 3578 0
+L 2900 0
+L 1881 1375
+L 863 0
+L 184 0
+L 1544 1831
+L 300 3500
+L 978 3500
+L 1906 2253
+L 2834 3500
+L 3513 3500
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-73"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(52.099609 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(113.623047 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(165.722656 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(217.822266 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(245.605469 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(306.787109 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(370.166016 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(401.953125 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(456.933594 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(518.115234 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(581.494141 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(620.703125 0)"/>
+ <use xlink:href="#DejaVuSans-78" transform="translate(680.476562 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(739.65625 0)"/>
+ </g>
+ </g>
+ <g id="patch_29">
+ <path d="M 340.164 41.184
+L 378.576 41.184
+Q 383.04 41.184 383.04 36.72
+L 383.04 36.72
+Q 383.04 32.256 378.576 32.256
+L 340.164 32.256
+Q 335.7 32.256 335.7 36.72
+L 335.7 36.72
+Q 335.7 41.184 340.164 41.184
+z
+" clip-path="url(#p37831d8287)" style="fill: #dfeaf4"/>
+ </g>
+ <g id="text_15">
+ <!-- system prompt + your instructions -->
+ <g style="fill: #63727d" transform="translate(148.057344 50.894125) scale(0.044 -0.044)">
+ <defs>
+ <path id="DejaVuSans-2b" d="M 2944 4013
+L 2944 2272
+L 4684 2272
+L 4684 1741
+L 2944 1741
+L 2944 0
+L 2419 0
+L 2419 1741
+L 678 1741
+L 678 2272
+L 2419 2272
+L 2419 4013
+L 2944 4013
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-73"/>
+ <use xlink:href="#DejaVuSans-79" transform="translate(52.099609 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(111.279297 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(163.378906 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(202.587891 0)"/>
+ <use xlink:href="#DejaVuSans-6d" transform="translate(264.111328 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(361.523438 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(393.310547 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(456.787109 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(495.650391 0)"/>
+ <use xlink:href="#DejaVuSans-6d" transform="translate(556.832031 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(654.244141 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(717.720703 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(756.929688 0)"/>
+ <use xlink:href="#DejaVuSans-2b" transform="translate(788.716797 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(872.505859 0)"/>
+ <use xlink:href="#DejaVuSans-79" transform="translate(904.292969 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(963.472656 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(1024.654297 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1088.033203 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1129.146484 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1160.933594 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1188.716797 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1252.095703 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1304.195312 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(1343.404297 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(1384.517578 0)"/>
+ <use xlink:href="#DejaVuSans-63" transform="translate(1447.896484 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1502.876953 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1542.085938 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1569.869141 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(1631.050781 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1694.429688 0)"/>
+ </g>
+ </g>
+ <g id="text_16">
+ <!-- + learned micro-skills -->
+ <g style="fill: #3e73a8" transform="translate(245.131281 50.894125) scale(0.044 -0.044)">
+ <defs>
+ <path id="DejaVuSans-Bold-2b" d="M 3053 4013
+L 3053 2375
+L 4684 2375
+L 4684 1638
+L 3053 1638
+L 3053 0
+L 2309 0
+L 2309 1638
+L 678 1638
+L 678 2375
+L 2309 2375
+L 2309 4013
+L 3053 4013
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-64" d="M 2919 2988
+L 2919 4863
+L 4044 4863
+L 4044 0
+L 2919 0
+L 2919 506
+Q 2688 197 2409 53
+Q 2131 -91 1766 -91
+Q 1119 -91 703 423
+Q 288 938 288 1747
+Q 288 2556 703 3070
+Q 1119 3584 1766 3584
+Q 2128 3584 2408 3439
+Q 2688 3294 2919 2988
+z
+M 2181 722
+Q 2541 722 2730 984
+Q 2919 1247 2919 1747
+Q 2919 2247 2730 2509
+Q 2541 2772 2181 2772
+Q 1825 2772 1636 2509
+Q 1447 2247 1447 1747
+Q 1447 1247 1636 984
+Q 1825 722 2181 722
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-6d" d="M 3781 2919
+Q 3994 3244 4286 3414
+Q 4578 3584 4928 3584
+Q 5531 3584 5847 3212
+Q 6163 2841 6163 2131
+L 6163 0
+L 5038 0
+L 5038 1825
+Q 5041 1866 5042 1909
+Q 5044 1953 5044 2034
+Q 5044 2406 4934 2573
+Q 4825 2741 4581 2741
+Q 4263 2741 4089 2478
+Q 3916 2216 3909 1719
+L 3909 0
+L 2784 0
+L 2784 1825
+Q 2784 2406 2684 2573
+Q 2584 2741 2328 2741
+Q 2006 2741 1831 2477
+Q 1656 2213 1656 1722
+L 1656 0
+L 531 0
+L 531 3500
+L 1656 3500
+L 1656 2988
+Q 1863 3284 2130 3434
+Q 2397 3584 2719 3584
+Q 3081 3584 3359 3409
+Q 3638 3234 3781 2919
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-2b"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(83.789062 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(118.603516 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(152.880859 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(220.703125 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(288.183594 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(337.5 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(408.691406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-64" transform="translate(476.513672 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(548.095703 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6d" transform="translate(582.910156 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(687.109375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-63" transform="translate(721.386719 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(780.664062 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(829.980469 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-2d" transform="translate(898.681641 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(940.185547 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6b" transform="translate(999.707031 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(1066.210938 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(1100.488281 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(1134.765625 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(1169.042969 0)"/>
+ </g>
+ </g>
+ <g id="text_17">
+ <!-- your prompt -->
+ <g style="fill: #63727d" transform="translate(332.674156 50.894125) scale(0.044 -0.044)">
+ <use xlink:href="#DejaVuSans-79"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(59.179688 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(120.361328 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(183.740234 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(224.853516 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(256.640625 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(320.117188 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(358.980469 0)"/>
+ <use xlink:href="#DejaVuSans-6d" transform="translate(420.162109 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(517.574219 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(581.050781 0)"/>
+ </g>
+ </g>
+ <g id="text_18">
+ <!-- INTERFACE -->
+ <g style="fill: #bc7d14" transform="translate(149.04 81.10525) scale(0.056 -0.056)">
+ <use xlink:href="#DejaVuSans-Bold-49"/>
+ <use xlink:href="#DejaVuSans-Bold-4e" transform="translate(37.207031 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-54" transform="translate(120.898438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(189.111328 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-52" transform="translate(257.421875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-46" transform="translate(334.423828 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-41" transform="translate(391.234375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-43" transform="translate(468.626953 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(542.015625 0)"/>
+ </g>
+ </g>
+ <g id="text_19">
+ <!-- loaded tool set -->
+ <g style="fill: #20303c" transform="translate(187.83 81.10525) scale(0.056 -0.056)">
+ <use xlink:href="#DejaVuSans-6c"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(27.783203 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(88.964844 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(150.244141 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(213.720703 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(275.244141 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(338.720703 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(370.507812 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(409.716797 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(470.898438 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(532.080078 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(559.863281 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(591.650391 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(643.75 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(705.273438 0)"/>
+ </g>
+ </g>
+ <g id="patch_30">
+ <path d="M 324.144 84.024
+L 378.576 84.024
+Q 383.04 84.024 383.04 79.56
+L 383.04 79.56
+Q 383.04 75.096 378.576 75.096
+L 324.144 75.096
+Q 319.68 75.096 319.68 79.56
+L 319.68 79.56
+Q 319.68 84.024 324.144 84.024
+z
+" clip-path="url(#p37831d8287)" style="fill: #f7e8c9"/>
+ </g>
+ <g id="text_20">
+ <!-- Bash -->
+ <g style="fill: #74500c" transform="translate(141.331344 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-42" d="M 1153 2228
+L 1153 519
+L 1900 519
+Q 2450 519 2684 711
+Q 2919 903 2919 1344
+Q 2919 1800 2672 2014
+Q 2425 2228 1900 2228
+L 1153 2228
+z
+M 1153 4147
+L 1153 2741
+L 1888 2741
+Q 2344 2741 2548 2916
+Q 2753 3091 2753 3481
+Q 2753 3834 2551 3990
+Q 2350 4147 1888 4147
+L 1153 4147
+z
+M 519 4666
+L 1900 4666
+Q 2616 4666 3003 4356
+Q 3391 4047 3391 3481
+Q 3391 3053 3186 2806
+Q 2981 2559 2572 2497
+Q 3031 2428 3292 2104
+Q 3553 1781 3553 1281
+Q 3553 647 3137 323
+Q 2722 0 1900 0
+L 519 0
+L 519 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-61" d="M 2194 1759
+L 2003 1759
+Q 1500 1759 1245 1582
+Q 991 1406 991 1056
+Q 991 741 1181 566
+Q 1372 391 1709 391
+Q 2184 391 2456 720
+Q 2728 1050 2731 1631
+L 2731 1759
+L 2194 1759
+z
+M 3309 1997
+L 3309 0
+L 2731 0
+L 2731 519
+Q 2547 206 2267 57
+Q 1988 -91 1588 -91
+Q 1053 -91 734 211
+Q 416 513 416 1019
+Q 416 1603 808 1906
+Q 1200 2209 1959 2209
+L 2731 2209
+L 2731 2300
+Q 2728 2719 2518 2908
+Q 2309 3097 1850 3097
+Q 1556 3097 1256 3012
+Q 956 2928 672 2766
+L 672 3341
+Q 991 3463 1283 3523
+Q 1575 3584 1850 3584
+Q 2284 3584 2592 3456
+Q 2900 3328 3091 3072
+Q 3209 2916 3259 2686
+Q 3309 2456 3309 1997
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-73" d="M 3041 3378
+L 3041 2816
+Q 2794 2959 2544 3031
+Q 2294 3103 2034 3103
+Q 1644 3103 1451 2976
+Q 1259 2850 1259 2591
+Q 1259 2356 1403 2240
+Q 1547 2125 2119 2016
+L 2350 1972
+Q 2778 1891 2998 1647
+Q 3219 1403 3219 1013
+Q 3219 494 2850 201
+Q 2481 -91 1825 -91
+Q 1566 -91 1281 -36
+Q 997 19 666 128
+L 666 722
+Q 988 556 1281 473
+Q 1575 391 1838 391
+Q 2219 391 2428 545
+Q 2638 700 2638 978
+Q 2638 1378 1872 1531
+L 1847 1538
+L 1631 1581
+Q 1134 1678 906 1908
+Q 678 2138 678 2534
+Q 678 3038 1018 3311
+Q 1359 3584 1991 3584
+Q 2272 3584 2531 3532
+Q 2791 3481 3041 3378
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-68" d="M 3284 2169
+L 3284 0
+L 2706 0
+L 2706 2169
+Q 2706 2641 2540 2862
+Q 2375 3084 2022 3084
+Q 1619 3084 1401 2798
+Q 1184 2513 1184 1978
+L 1184 0
+L 609 0
+L 609 4863
+L 1184 4863
+L 1184 2975
+Q 1338 3275 1600 3429
+Q 1863 3584 2222 3584
+Q 2756 3584 3020 3232
+Q 3284 2881 3284 2169
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-42"/>
+ <use xlink:href="#DejaVuSansMono-61" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-73" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-68" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_21">
+ <!-- Read -->
+ <g style="fill: #74500c" transform="translate(162.427344 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-52" d="M 2375 2203
+Q 2619 2141 2791 1967
+Q 2963 1794 3219 1275
+L 3853 0
+L 3175 0
+L 2619 1178
+Q 2378 1681 2186 1826
+Q 1994 1972 1684 1972
+L 1081 1972
+L 1081 0
+L 447 0
+L 447 4666
+L 1747 4666
+Q 2516 4666 2925 4319
+Q 3334 3972 3334 3316
+Q 3334 2853 3082 2561
+Q 2831 2269 2375 2203
+z
+M 1081 4147
+L 1081 2491
+L 1772 2491
+Q 2225 2491 2447 2694
+Q 2669 2897 2669 3316
+Q 2669 3719 2433 3933
+Q 2197 4147 1747 4147
+L 1081 4147
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-65" d="M 3475 1894
+L 3475 1613
+L 984 1613
+L 984 1594
+Q 984 1022 1282 709
+Q 1581 397 2125 397
+Q 2400 397 2700 484
+Q 3000 572 3341 750
+L 3341 178
+Q 3013 44 2708 -23
+Q 2403 -91 2119 -91
+Q 1303 -91 843 398
+Q 384 888 384 1747
+Q 384 2584 834 3084
+Q 1284 3584 2034 3584
+Q 2703 3584 3089 3131
+Q 3475 2678 3475 1894
+z
+M 2900 2063
+Q 2888 2569 2661 2833
+Q 2434 3097 2009 3097
+Q 1594 3097 1325 2822
+Q 1056 2547 1006 2059
+L 2900 2063
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-64" d="M 2681 3053
+L 2681 4863
+L 3256 4863
+L 3256 0
+L 2681 0
+L 2681 441
+Q 2538 181 2298 45
+Q 2059 -91 1747 -91
+Q 1113 -91 748 401
+Q 384 894 384 1759
+Q 384 2613 750 3098
+Q 1116 3584 1747 3584
+Q 2063 3584 2303 3448
+Q 2544 3313 2681 3053
+z
+M 991 1747
+Q 991 1078 1203 737
+Q 1416 397 1831 397
+Q 2247 397 2464 740
+Q 2681 1084 2681 1747
+Q 2681 2413 2464 2755
+Q 2247 3097 1831 3097
+Q 1416 3097 1203 2756
+Q 991 2416 991 1747
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-52"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-61" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-64" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_22">
+ <!-- Edit -->
+ <g style="fill: #74500c" transform="translate(183.523344 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-45" d="M 616 4666
+L 3384 4666
+L 3384 4134
+L 1247 4134
+L 1247 2753
+L 3291 2753
+L 3291 2222
+L 1247 2222
+L 1247 531
+L 3444 531
+L 3444 0
+L 616 0
+L 616 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-69" d="M 800 3500
+L 2272 3500
+L 2272 447
+L 3413 447
+L 3413 0
+L 556 0
+L 556 447
+L 1697 447
+L 1697 3053
+L 800 3053
+L 800 3500
+z
+M 1697 4863
+L 2272 4863
+L 2272 4134
+L 1697 4134
+L 1697 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-74" d="M 1919 4494
+L 1919 3500
+L 3225 3500
+L 3225 3053
+L 1919 3053
+L 1919 1153
+Q 1919 766 2066 612
+Q 2213 459 2578 459
+L 3225 459
+L 3225 0
+L 2522 0
+Q 1875 0 1609 259
+Q 1344 519 1344 1153
+L 1344 3053
+L 409 3053
+L 409 3500
+L 1344 3500
+L 1344 4494
+L 1919 4494
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-45"/>
+ <use xlink:href="#DejaVuSansMono-64" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-69" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_23">
+ <!-- Write -->
+ <g style="fill: #74500c" transform="translate(204.60018 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-57" d="M 0 4666
+L 616 4666
+L 1063 878
+L 1594 3384
+L 2253 3384
+L 2791 872
+L 3238 4666
+L 3853 4666
+L 3156 0
+L 2559 0
+L 1925 2772
+L 1294 0
+L 697 0
+L 0 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-72" d="M 3609 2778
+Q 3425 2922 3234 2987
+Q 3044 3053 2816 3053
+Q 2278 3053 1993 2715
+Q 1709 2378 1709 1741
+L 1709 0
+L 1131 0
+L 1131 3500
+L 1709 3500
+L 1709 2816
+Q 1853 3188 2151 3386
+Q 2450 3584 2859 3584
+Q 3072 3584 3256 3531
+Q 3441 3478 3609 3366
+L 3609 2778
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-57"/>
+ <use xlink:href="#DejaVuSansMono-72" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-69" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(180.615234 0)"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(240.820312 0)"/>
+ </g>
+ </g>
+ <g id="text_24">
+ <!-- Grep -->
+ <g style="fill: #74500c" transform="translate(228.145344 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-47" d="M 3450 384
+Q 3197 150 2880 29
+Q 2563 -91 2194 -91
+Q 1306 -91 812 545
+Q 319 1181 319 2328
+Q 319 3472 819 4111
+Q 1319 4750 2209 4750
+Q 2503 4750 2772 4667
+Q 3041 4584 3291 4416
+L 3291 3769
+Q 3038 4009 2772 4123
+Q 2506 4238 2209 4238
+Q 1594 4238 1286 3761
+Q 978 3284 978 2328
+Q 978 1356 1276 889
+Q 1575 422 2194 422
+Q 2403 422 2561 470
+Q 2719 519 2847 622
+L 2847 1875
+L 2169 1875
+L 2169 2394
+L 3450 2394
+L 3450 384
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-70" d="M 1172 441
+L 1172 -1331
+L 594 -1331
+L 594 3500
+L 1172 3500
+L 1172 3053
+Q 1316 3313 1555 3448
+Q 1794 3584 2106 3584
+Q 2741 3584 3102 3093
+Q 3463 2603 3463 1734
+Q 3463 881 3100 395
+Q 2738 -91 2106 -91
+Q 1788 -91 1548 45
+Q 1309 181 1172 441
+z
+M 2859 1747
+Q 2859 2416 2648 2756
+Q 2438 3097 2022 3097
+Q 1603 3097 1387 2755
+Q 1172 2413 1172 1747
+Q 1172 1084 1387 740
+Q 1603 397 2022 397
+Q 2438 397 2648 737
+Q 2859 1078 2859 1747
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-47"/>
+ <use xlink:href="#DejaVuSansMono-72" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-70" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_25">
+ <!-- Glob -->
+ <g style="fill: #74500c" transform="translate(249.241344 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-6c" d="M 1997 1269
+Q 1997 881 2139 684
+Q 2281 488 2559 488
+L 3231 488
+L 3231 0
+L 2503 0
+Q 1988 0 1705 331
+Q 1422 663 1422 1269
+L 1422 4447
+L 500 4447
+L 500 4897
+L 1997 4897
+L 1997 1269
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-6f" d="M 1925 3097
+Q 1488 3097 1263 2756
+Q 1038 2416 1038 1747
+Q 1038 1081 1263 739
+Q 1488 397 1925 397
+Q 2366 397 2591 739
+Q 2816 1081 2816 1747
+Q 2816 2416 2591 2756
+Q 2366 3097 1925 3097
+z
+M 1925 3584
+Q 2653 3584 3039 3112
+Q 3425 2641 3425 1747
+Q 3425 850 3040 379
+Q 2656 -91 1925 -91
+Q 1197 -91 812 379
+Q 428 850 428 1747
+Q 428 2641 812 3112
+Q 1197 3584 1925 3584
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-62" d="M 2869 1747
+Q 2869 2416 2656 2756
+Q 2444 3097 2028 3097
+Q 1609 3097 1393 2755
+Q 1178 2413 1178 1747
+Q 1178 1084 1393 740
+Q 1609 397 2028 397
+Q 2444 397 2656 737
+Q 2869 1078 2869 1747
+z
+M 1178 3053
+Q 1316 3309 1558 3446
+Q 1800 3584 2119 3584
+Q 2750 3584 3112 3098
+Q 3475 2613 3475 1759
+Q 3475 894 3111 401
+Q 2747 -91 2113 -91
+Q 1800 -91 1561 45
+Q 1322 181 1178 441
+L 1178 0
+L 603 0
+L 603 4863
+L 1178 4863
+L 1178 3053
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-47"/>
+ <use xlink:href="#DejaVuSansMono-6c" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-6f" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-62" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_26">
+ <!-- CronCreate -->
+ <g style="fill: #98a4ac" transform="translate(270.222359 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-43" d="M 3353 166
+Q 3113 38 2859 -26
+Q 2606 -91 2322 -91
+Q 1425 -91 929 543
+Q 434 1178 434 2328
+Q 434 3472 932 4111
+Q 1431 4750 2322 4750
+Q 2606 4750 2859 4686
+Q 3113 4622 3353 4494
+L 3353 3847
+Q 3122 4038 2856 4138
+Q 2591 4238 2322 4238
+Q 1706 4238 1400 3763
+Q 1094 3288 1094 2328
+Q 1094 1372 1400 897
+Q 1706 422 2322 422
+Q 2597 422 2861 522
+Q 3125 622 3353 813
+L 3353 166
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-6e" d="M 3284 2169
+L 3284 0
+L 2706 0
+L 2706 2169
+Q 2706 2641 2540 2862
+Q 2375 3084 2022 3084
+Q 1619 3084 1401 2798
+Q 1184 2513 1184 1978
+L 1184 0
+L 609 0
+L 609 3500
+L 1184 3500
+L 1184 2975
+Q 1338 3275 1600 3429
+Q 1863 3584 2222 3584
+Q 2756 3584 3020 3232
+Q 3284 2881 3284 2169
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-43"/>
+ <use xlink:href="#DejaVuSansMono-72" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-6f" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-6e" transform="translate(180.615234 0)"/>
+ <use xlink:href="#DejaVuSansMono-43" transform="translate(240.820312 0)"/>
+ <use xlink:href="#DejaVuSansMono-72" transform="translate(301.025391 0)"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(361.230469 0)"/>
+ <use xlink:href="#DejaVuSansMono-61" transform="translate(421.435547 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(481.640625 0)"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(541.845703 0)"/>
+ </g>
+ </g>
+ <g id="text_27">
+ <!-- Workflow -->
+ <g style="fill: #98a4ac" transform="translate(305.936687 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-6b" d="M 738 4863
+L 1331 4863
+L 1331 2047
+L 2841 3500
+L 3541 3500
+L 2163 2181
+L 3756 0
+L 3053 0
+L 1759 1806
+L 1331 1403
+L 1331 0
+L 738 0
+L 738 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-66" d="M 3322 4863
+L 3322 4384
+L 2669 4384
+Q 2359 4384 2239 4257
+Q 2119 4131 2119 3809
+L 2119 3500
+L 3322 3500
+L 3322 3053
+L 2119 3053
+L 2119 0
+L 1544 0
+L 1544 3053
+L 609 3053
+L 609 3500
+L 1544 3500
+L 1544 3744
+Q 1544 4319 1808 4591
+Q 2072 4863 2631 4863
+L 3322 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSansMono-77" d="M 0 3500
+L 569 3500
+L 1178 672
+L 1678 2478
+L 2169 2478
+L 2675 672
+L 3284 3500
+L 3853 3500
+L 3034 0
+L 2484 0
+L 1925 1919
+L 1369 0
+L 819 0
+L 0 3500
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-57"/>
+ <use xlink:href="#DejaVuSansMono-6f" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-72" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-6b" transform="translate(180.615234 0)"/>
+ <use xlink:href="#DejaVuSansMono-66" transform="translate(240.820312 0)"/>
+ <use xlink:href="#DejaVuSansMono-6c" transform="translate(301.025391 0)"/>
+ <use xlink:href="#DejaVuSansMono-6f" transform="translate(361.230469 0)"/>
+ <use xlink:href="#DejaVuSansMono-77" transform="translate(421.435547 0)"/>
+ </g>
+ </g>
+ <g id="text_28">
+ <!-- NotebookEdit -->
+ <g style="fill: #98a4ac" transform="translate(336.676031 93.662234) scale(0.041 -0.041)">
+ <defs>
+ <path id="DejaVuSansMono-4e" d="M 434 4666
+L 1234 4666
+L 2809 825
+L 2809 4666
+L 3419 4666
+L 3419 0
+L 2619 0
+L 1044 3841
+L 1044 0
+L 434 0
+L 434 4666
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSansMono-4e"/>
+ <use xlink:href="#DejaVuSansMono-6f" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(180.615234 0)"/>
+ <use xlink:href="#DejaVuSansMono-62" transform="translate(240.820312 0)"/>
+ <use xlink:href="#DejaVuSansMono-6f" transform="translate(301.025391 0)"/>
+ <use xlink:href="#DejaVuSansMono-6f" transform="translate(361.230469 0)"/>
+ <use xlink:href="#DejaVuSansMono-6b" transform="translate(421.435547 0)"/>
+ <use xlink:href="#DejaVuSansMono-45" transform="translate(481.640625 0)"/>
+ <use xlink:href="#DejaVuSansMono-64" transform="translate(541.845703 0)"/>
+ <use xlink:href="#DejaVuSansMono-69" transform="translate(602.050781 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(662.255859 0)"/>
+ </g>
+ </g>
+ <g id="text_29">
+ <!-- … -->
+ <g style="fill: #98a4ac" transform="translate(375.557 94.230812) scale(0.062 -0.062)">
+ <defs>
+ <path id="DejaVuSans-2026" d="M 2869 794
+L 3531 794
+L 3531 0
+L 2869 0
+L 2869 794
+z
+M 4997 794
+L 5663 794
+L 5663 0
+L 4997 0
+L 4997 794
+z
+M 738 794
+L 1403 794
+L 1403 0
+L 738 0
+L 738 794
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-2026"/>
+ </g>
+ </g>
+ <g id="text_30">
+ <!-- CONTROL -->
+ <g style="fill: #bf4f4b" transform="translate(149.04 123.94525) scale(0.056 -0.056)">
+ <use xlink:href="#DejaVuSans-Bold-43"/>
+ <use xlink:href="#DejaVuSans-Bold-4f" transform="translate(73.388672 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4e" transform="translate(158.398438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-54" transform="translate(242.089844 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-52" transform="translate(310.302734 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4f" transform="translate(387.304688 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4c" transform="translate(472.314453 0)"/>
+ </g>
+ </g>
+ <g id="text_31">
+ <!-- one prompt-turn -->
+ <g style="fill: #20303c" transform="translate(183.6 123.94525) scale(0.056 -0.056)">
+ <defs>
+ <path id="DejaVuSans-2d" d="M 313 2009
+L 1997 2009
+L 1997 1497
+L 313 1497
+L 313 2009
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-6f"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(61.181641 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(124.560547 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(186.083984 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(217.871094 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(281.347656 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(320.210938 0)"/>
+ <use xlink:href="#DejaVuSans-6d" transform="translate(381.392578 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(478.804688 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(542.28125 0)"/>
+ <use xlink:href="#DejaVuSans-2d" transform="translate(581.490234 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(617.574219 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(656.783203 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(720.162109 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(759.525391 0)"/>
+ </g>
+ </g>
+ <g id="patch_31">
+ <path d="M 337.104 126.864
+L 378.576 126.864
+Q 383.04 126.864 383.04 122.4
+L 383.04 122.4
+Q 383.04 117.936 378.576 117.936
+L 337.104 117.936
+Q 332.64 117.936 332.64 122.4
+L 332.64 122.4
+Q 332.64 126.864 337.104 126.864
+z
+" clip-path="url(#p37831d8287)" style="fill: #f4dcda"/>
+ </g>
+ <g id="text_32">
+ <!-- … -->
+ <g style="fill: #98a4ac" transform="translate(140.18 137.070812) scale(0.062 -0.062)">
+ <use xlink:href="#DejaVuSans-2026"/>
+ </g>
+ </g>
+ <g id="text_33">
+ <!-- edit -->
+ <g style="fill: #bf4f4b" transform="translate(158.035344 136.502234) scale(0.041 -0.041)">
+ <use xlink:href="#DejaVuSansMono-65"/>
+ <use xlink:href="#DejaVuSansMono-64" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-69" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_34">
+ <!-- test -->
+ <g style="fill: #bf4f4b" transform="translate(181.867344 136.502234) scale(0.041 -0.041)">
+ <use xlink:href="#DejaVuSansMono-74"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-73" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_35">
+ <!-- … -->
+ <g style="fill: #bf4f4b" transform="translate(203.396 137.070812) scale(0.062 -0.062)">
+ <use xlink:href="#DejaVuSans-2026"/>
+ </g>
+ </g>
+ <g id="text_36">
+ <!-- REDIRECT -->
+ <g style="fill: #ffffff" transform="translate(218.450258 136.546531) scale(0.043 -0.043)">
+ <use xlink:href="#DejaVuSans-Bold-52"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(77.001953 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-44" transform="translate(145.3125 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-49" transform="translate(228.320312 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-52" transform="translate(265.527344 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-45" transform="translate(342.529297 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-43" transform="translate(410.839844 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-54" transform="translate(484.228516 0)"/>
+ </g>
+ </g>
+ <g id="text_37">
+ <!-- edit -->
+ <g style="fill: #bf4f4b" transform="translate(253.363344 136.502234) scale(0.041 -0.041)">
+ <use xlink:href="#DejaVuSansMono-65"/>
+ <use xlink:href="#DejaVuSansMono-64" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-69" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_38">
+ <!-- test -->
+ <g style="fill: #bf4f4b" transform="translate(277.195344 136.502234) scale(0.041 -0.041)">
+ <use xlink:href="#DejaVuSansMono-74"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-73" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_39">
+ <!-- … -->
+ <g style="fill: #bf4f4b" transform="translate(298.724 137.070812) scale(0.062 -0.062)">
+ <use xlink:href="#DejaVuSans-2026"/>
+ </g>
+ </g>
+ <g id="text_40">
+ <!-- STOP -->
+ <g style="fill: #bf4f4b" transform="translate(317.797242 136.546531) scale(0.043 -0.043)">
+ <use xlink:href="#DejaVuSans-Bold-53"/>
+ <use xlink:href="#DejaVuSans-Bold-54" transform="translate(72.021484 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-4f" transform="translate(140.234375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-50" transform="translate(225.244141 0)"/>
+ </g>
+ </g>
+ <g id="text_41">
+ <!-- edit -->
+ <g style="fill: #98a4ac" transform="translate(345.631344 136.502234) scale(0.041 -0.041)">
+ <use xlink:href="#DejaVuSansMono-65"/>
+ <use xlink:href="#DejaVuSansMono-64" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-69" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_42">
+ <!-- test -->
+ <g style="fill: #98a4ac" transform="translate(369.103344 136.502234) scale(0.041 -0.041)">
+ <use xlink:href="#DejaVuSansMono-74"/>
+ <use xlink:href="#DejaVuSansMono-65" transform="translate(60.205078 0)"/>
+ <use xlink:href="#DejaVuSansMono-73" transform="translate(120.410156 0)"/>
+ <use xlink:href="#DejaVuSansMono-74" transform="translate(180.615234 0)"/>
+ </g>
+ </g>
+ <g id="text_43">
+ <!-- Claude Code · Codex · Copilot CLI · Pi -->
+ <g style="fill: #20303c" transform="translate(286.596211 10.961719) scale(0.045 -0.045)">
+ <defs>
+ <path id="DejaVuSans-43" d="M 4122 4306
+L 4122 3641
+Q 3803 3938 3442 4084
+Q 3081 4231 2675 4231
+Q 1875 4231 1450 3742
+Q 1025 3253 1025 2328
+Q 1025 1406 1450 917
+Q 1875 428 2675 428
+Q 3081 428 3442 575
+Q 3803 722 4122 1019
+L 4122 359
+Q 3791 134 3420 21
+Q 3050 -91 2638 -91
+Q 1578 -91 968 557
+Q 359 1206 359 2328
+Q 359 3453 968 4101
+Q 1578 4750 2638 4750
+Q 3056 4750 3426 4639
+Q 3797 4528 4122 4306
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-b7" d="M 684 2619
+L 1344 2619
+L 1344 1825
+L 684 1825
+L 684 2619
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-4c" d="M 628 4666
+L 1259 4666
+L 1259 531
+L 3531 531
+L 3531 0
+L 628 0
+L 628 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-49" d="M 628 4666
+L 1259 4666
+L 1259 0
+L 628 0
+L 628 4666
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-50" d="M 1259 4147
+L 1259 2394
+L 2053 2394
+Q 2494 2394 2734 2622
+Q 2975 2850 2975 3272
+Q 2975 3691 2734 3919
+Q 2494 4147 2053 4147
+L 1259 4147
+z
+M 628 4666
+L 2053 4666
+Q 2838 4666 3239 4311
+Q 3641 3956 3641 3272
+Q 3641 2581 3239 2228
+Q 2838 1875 2053 1875
+L 1259 1875
+L 1259 0
+L 628 0
+L 628 4666
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-43"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(69.824219 0)"/>
+ <use xlink:href="#DejaVuSans-61" transform="translate(97.607422 0)"/>
+ <use xlink:href="#DejaVuSans-75" transform="translate(158.886719 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(222.265625 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(285.742188 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(347.265625 0)"/>
+ <use xlink:href="#DejaVuSans-43" transform="translate(379.052734 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(448.876953 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(510.058594 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(573.535156 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(635.058594 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(666.845703 0)"/>
+ <use xlink:href="#DejaVuSans-b7" transform="translate(698.632812 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(730.419922 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(762.207031 0)"/>
+ <use xlink:href="#DejaVuSans-43" transform="translate(793.994141 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(863.818359 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(925 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(988.476562 0)"/>
+ <use xlink:href="#DejaVuSans-78" transform="translate(1048.25 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1107.429688 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1139.216797 0)"/>
+ <use xlink:href="#DejaVuSans-b7" transform="translate(1171.003906 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1202.791016 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1234.578125 0)"/>
+ <use xlink:href="#DejaVuSans-43" transform="translate(1266.365234 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1336.189453 0)"/>
+ <use xlink:href="#DejaVuSans-70" transform="translate(1397.371094 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(1460.847656 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(1488.630859 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1516.414062 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(1577.595703 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1616.804688 0)"/>
+ <use xlink:href="#DejaVuSans-43" transform="translate(1648.591797 0)"/>
+ <use xlink:href="#DejaVuSans-4c" transform="translate(1718.416016 0)"/>
+ <use xlink:href="#DejaVuSans-49" transform="translate(1774.128906 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1803.621094 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1835.408203 0)"/>
+ <use xlink:href="#DejaVuSans-b7" transform="translate(1867.195312 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1898.982422 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1930.769531 0)"/>
+ <use xlink:href="#DejaVuSans-50" transform="translate(1962.556641 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(2020.609375 0)"/>
+ </g>
+ </g>
+ <g id="text_44">
+ <!-- at session start -->
+ <g style="fill: #3e73a8" transform="translate(339.629414 37.961719) scale(0.045 -0.045)">
+ <use xlink:href="#DejaVuSans-Bold-61"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(67.480469 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(115.283203 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(150.097656 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(209.619141 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(277.441406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(336.962891 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(396.484375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(430.761719 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(499.462891 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(570.654297 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(605.46875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(664.990234 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(712.792969 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(780.273438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(829.589844 0)"/>
+ </g>
+ </g>
+ <g id="line2d_3">
+ <path d="M 234.72 57.6
+L 309.6 57.6
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #3e73a8; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_4">
+ <path d="M 234.72 57.6
+L 234.72 55.008
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #3e73a8; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_5">
+ <path d="M 309.6 57.6
+L 309.6 55.008
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #3e73a8; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="text_45">
+ <!-- active facts only -->
+ <g style="fill: #3e73a8" transform="translate(251.734719 63.967312) scale(0.044 -0.044)">
+ <defs>
+ <path id="DejaVuSans-Bold-66" d="M 2841 4863
+L 2841 4128
+L 2222 4128
+Q 1984 4128 1890 4042
+Q 1797 3956 1797 3744
+L 1797 3500
+L 2753 3500
+L 2753 2700
+L 1797 2700
+L 1797 0
+L 678 0
+L 678 2700
+L 122 2700
+L 122 3500
+L 678 3500
+L 678 3744
+Q 678 4316 997 4589
+Q 1316 4863 1984 4863
+L 2841 4863
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-79" d="M 78 3500
+L 1197 3500
+L 2138 1125
+L 2938 3500
+L 4056 3500
+L 2584 -331
+Q 2363 -916 2067 -1148
+Q 1772 -1381 1288 -1381
+L 641 -1381
+L 641 -647
+L 991 -647
+Q 1275 -647 1404 -556
+Q 1534 -466 1606 -231
+L 1638 -134
+L 78 3500
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-61"/>
+ <use xlink:href="#DejaVuSans-Bold-63" transform="translate(67.480469 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(126.757812 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(174.560547 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-76" transform="translate(208.837891 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(274.023438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(341.845703 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-66" transform="translate(376.660156 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(420.166016 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-63" transform="translate(487.646484 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(546.923828 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(594.726562 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(654.248047 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(689.0625 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(757.763672 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(828.955078 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-79" transform="translate(863.232422 0)"/>
+ </g>
+ </g>
+ <g id="text_46">
+ <!-- from the next session -->
+ <g style="fill: #bc7d14" transform="translate(323.711367 80.801719) scale(0.045 -0.045)">
+ <defs>
+ <path id="DejaVuSans-Bold-68" d="M 4056 2131
+L 4056 0
+L 2931 0
+L 2931 347
+L 2931 1625
+Q 2931 2084 2911 2256
+Q 2891 2428 2841 2509
+Q 2775 2619 2662 2680
+Q 2550 2741 2406 2741
+Q 2056 2741 1856 2470
+Q 1656 2200 1656 1722
+L 1656 0
+L 538 0
+L 538 4863
+L 1656 4863
+L 1656 2988
+Q 1909 3294 2193 3439
+Q 2478 3584 2822 3584
+Q 3428 3584 3742 3212
+Q 4056 2841 4056 2131
+z
+" transform="scale(0.015625)"/>
+ <path id="DejaVuSans-Bold-78" d="M 1422 1791
+L 159 3500
+L 1344 3500
+L 2059 2463
+L 2784 3500
+L 3969 3500
+L 2706 1797
+L 4031 0
+L 2847 0
+L 2059 1106
+L 1281 0
+L 97 0
+L 1422 1791
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-66"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(43.505859 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(92.822266 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6d" transform="translate(161.523438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(265.722656 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(300.537109 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-68" transform="translate(348.339844 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(419.53125 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(487.353516 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(522.167969 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(593.359375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-78" transform="translate(661.181641 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(725.683594 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(773.486328 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(808.300781 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(867.822266 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(935.644531 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(995.166016 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(1054.6875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(1088.964844 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(1157.666016 0)"/>
+ </g>
+ </g>
+ <g id="line2d_6">
+ <path d="M 269.262 92.52
+L 295.866 92.52
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.6; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_7">
+ <path d="M 304.938 92.52
+L 326.682 92.52
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.6; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_8">
+ <path d="M 335.754 92.52
+L 367.218 92.52
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.6; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_9">
+ <path d="M 267.246 100.44
+L 383.04 100.44
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_10">
+ <path d="M 267.246 100.44
+L 267.246 97.848
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_11">
+ <path d="M 383.04 100.44
+L 383.04 97.848
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="text_47">
+ <!-- denied, once you approve -->
+ <g style="fill: #98a4ac" transform="translate(293.013031 106.807312) scale(0.044 -0.044)">
+ <defs>
+ <path id="DejaVuSans-Bold-2c" d="M 653 1209
+L 1778 1209
+L 1778 256
+L 1006 -909
+L 341 -909
+L 653 256
+L 653 1209
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-64"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(71.582031 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(139.404297 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(210.595703 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(244.873047 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-64" transform="translate(312.695312 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-2c" transform="translate(384.277344 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(422.265625 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(457.080078 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(525.78125 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-63" transform="translate(596.972656 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(656.25 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(724.072266 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-79" transform="translate(758.886719 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(824.072266 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-75" transform="translate(892.773438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(963.964844 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(998.779297 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-70" transform="translate(1066.259766 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-70" transform="translate(1137.841797 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(1209.423828 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6f" transform="translate(1258.740234 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-76" transform="translate(1327.441406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(1392.626953 0)"/>
+ </g>
+ </g>
+ <g id="text_48">
+ <!-- during each turn -->
+ <g style="fill: #bf4f4b" transform="translate(336.599648 123.624141) scale(0.045 -0.045)">
+ <use xlink:href="#DejaVuSans-Bold-64"/>
+ <use xlink:href="#DejaVuSans-Bold-75" transform="translate(71.582031 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(142.773438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(192.089844 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(226.367188 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-67" transform="translate(297.558594 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(369.140625 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(403.955078 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(471.777344 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-63" transform="translate(539.257812 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-68" transform="translate(598.535156 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(669.726562 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(704.541016 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-75" transform="translate(752.34375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(823.535156 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(872.851562 0)"/>
+ </g>
+ </g>
+ <g id="line2d_12">
+ <path d="M 343.584 135.36
+L 357.552 135.36
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.6; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_13">
+ <path d="M 367.056 135.36
+L 381.024 135.36
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.6; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_14">
+ <path d="M 153.792 143.28
+L 211.536 143.28
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #bf4f4b; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_15">
+ <path d="M 153.792 143.28
+L 153.792 140.688
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #bf4f4b; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_16">
+ <path d="M 211.536 143.28
+L 211.536 140.688
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #bf4f4b; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="text_49">
+ <!-- repeated failures -->
+ <g style="fill: #bf4f4b" transform="translate(161.248375 149.647312) scale(0.044 -0.044)">
+ <use xlink:href="#DejaVuSans-Bold-72"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(49.316406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-70" transform="translate(117.138672 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(188.720703 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(256.542969 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(324.023438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(371.826172 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-64" transform="translate(439.648438 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(511.230469 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-66" transform="translate(546.044922 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(589.550781 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(657.03125 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(691.308594 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-75" transform="translate(725.585938 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(796.777344 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(846.09375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-73" transform="translate(913.916016 0)"/>
+ </g>
+ </g>
+ <g id="line2d_17">
+ <path d="M 249.12 143.28
+L 306.864 143.28
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #bf4f4b; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_18">
+ <path d="M 249.12 143.28
+L 249.12 140.688
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #bf4f4b; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_19">
+ <path d="M 306.864 143.28
+L 306.864 140.688
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #bf4f4b; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="text_50">
+ <!-- still repeating -->
+ <g style="fill: #bf4f4b" transform="translate(260.527437 149.647312) scale(0.044 -0.044)">
+ <use xlink:href="#DejaVuSans-Bold-73"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(59.521484 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(107.324219 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(141.601562 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6c" transform="translate(175.878906 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(210.15625 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(244.970703 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(294.287109 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-70" transform="translate(362.109375 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(433.691406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-61" transform="translate(501.513672 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-74" transform="translate(568.994141 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-69" transform="translate(616.796875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(651.074219 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-67" transform="translate(722.265625 0)"/>
+ </g>
+ </g>
+ <g id="line2d_20">
+ <path d="M 341.568 143.28
+L 383.04 143.28
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_21">
+ <path d="M 341.568 143.28
+L 341.568 140.688
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="line2d_22">
+ <path d="M 383.04 143.28
+L 383.04 140.688
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #98a4ac; stroke-width: 0.7; stroke-linecap: square"/>
+ </g>
+ <g id="text_51">
+ <!-- never run -->
+ <g style="fill: #98a4ac" transform="translate(350.251437 149.647312) scale(0.044 -0.044)">
+ <use xlink:href="#DejaVuSans-Bold-6e"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(71.191406 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-76" transform="translate(139.013672 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-65" transform="translate(204.199219 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(272.021484 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-20" transform="translate(321.337891 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-72" transform="translate(356.152344 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-75" transform="translate(405.46875 0)"/>
+ <use xlink:href="#DejaVuSans-Bold-6e" transform="translate(476.660156 0)"/>
+ </g>
+ </g>
+ <g id="line2d_23">
+ <path d="M 360 155.52
+L 360 182.52
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #63727d; stroke-width: 0.85; stroke-linecap: square"/>
+ </g>
+ <g id="patch_32">
+ <path d="M 360 182.52
+Q 237.96 182.52 116.870329 182.52
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #63727d; stroke-width: 0.85; stroke-linecap: round"/>
+ <path d="M 118.670329 183.42
+L 116.870329 182.52
+L 118.670329 181.62
+z
+" clip-path="url(#p37831d8287)" style="fill: #63727d; stroke: #63727d; stroke-width: 0.85; stroke-linecap: round"/>
+ </g>
+ <g id="text_52">
+ <!-- the finished session's log -->
+ <g style="fill: #63727d" transform="translate(209.602156 177.644937) scale(0.044 -0.044)">
+ <defs>
+ <path id="DejaVuSans-27" d="M 1147 4666
+L 1147 2931
+L 616 2931
+L 616 4666
+L 1147 4666
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-74"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(39.208984 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(102.587891 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(164.111328 0)"/>
+ <use xlink:href="#DejaVuSans-66" transform="translate(195.898438 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(231.103516 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(258.886719 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(322.265625 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(350.048828 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(402.148438 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(465.527344 0)"/>
+ <use xlink:href="#DejaVuSans-64" transform="translate(527.050781 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(590.527344 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(622.314453 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(674.414062 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(735.9375 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(788.037109 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(840.136719 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(867.919922 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(929.101562 0)"/>
+ <use xlink:href="#DejaVuSans-27" transform="translate(992.480469 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(1019.970703 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(1072.070312 0)"/>
+ <use xlink:href="#DejaVuSans-6c" transform="translate(1103.857422 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(1131.640625 0)"/>
+ <use xlink:href="#DejaVuSans-67" transform="translate(1192.822266 0)"/>
+ </g>
+ </g>
+ <g id="patch_33">
+ <path d="M 15.12 46.944
+C 16.494813 46.944 17.813502 46.397781 18.785642 45.425642
+C 19.757781 44.453502 20.304 43.134813 20.304 41.76
+C 20.304 40.385187 19.757781 39.066498 18.785642 38.094358
+C 17.813502 37.122219 16.494813 36.576 15.12 36.576
+C 13.745187 36.576 12.426498 37.122219 11.454358 38.094358
+C 10.482219 39.066498 9.936 40.385187 9.936 41.76
+C 9.936 43.134813 10.482219 44.453502 11.454358 45.425642
+C 12.426498 46.397781 13.745187 46.944 15.12 46.944
+z
+" clip-path="url(#p37831d8287)" style="fill: #3e73a8"/>
+ </g>
+ <g id="patch_34">
+ <path d="M 15.12 89.784
+C 16.494813 89.784 17.813502 89.237781 18.785642 88.265642
+C 19.757781 87.293502 20.304 85.974813 20.304 84.6
+C 20.304 83.225187 19.757781 81.906498 18.785642 80.934358
+C 17.813502 79.962219 16.494813 79.416 15.12 79.416
+C 13.745187 79.416 12.426498 79.962219 11.454358 80.934358
+C 10.482219 81.906498 9.936 83.225187 9.936 84.6
+C 9.936 85.974813 10.482219 87.293502 11.454358 88.265642
+C 12.426498 89.237781 13.745187 89.784 15.12 89.784
+z
+" clip-path="url(#p37831d8287)" style="fill: #bc7d14"/>
+ </g>
+ <g id="patch_35">
+ <path d="M 15.12 132.624
+C 16.494813 132.624 17.813502 132.077781 18.785642 131.105642
+C 19.757781 130.133502 20.304 128.814813 20.304 127.44
+C 20.304 126.065187 19.757781 124.746498 18.785642 123.774358
+C 17.813502 122.802219 16.494813 122.256 15.12 122.256
+C 13.745187 122.256 12.426498 122.802219 11.454358 123.774358
+C 10.482219 124.746498 9.936 126.065187 9.936 127.44
+C 9.936 128.814813 10.482219 130.133502 11.454358 131.105642
+C 12.426498 132.077781 13.745187 132.624 15.12 132.624
+z
+" clip-path="url(#p37831d8287)" style="fill: #bf4f4b"/>
+ </g>
+ <g id="patch_36">
+ <path d="M 83.304 178.416
+C 84.411488 178.416 85.473766 177.97599 86.256878 177.192878
+C 87.03999 176.409766 87.48 175.347488 87.48 174.24
+C 87.48 173.132512 87.03999 172.070234 86.256878 171.287122
+C 85.473766 170.50401 84.411488 170.064 83.304 170.064
+C 82.196512 170.064 81.134234 170.50401 80.351122 171.287122
+C 79.56801 172.070234 79.128 173.132512 79.128 174.24
+C 79.128 175.347488 79.56801 176.409766 80.351122 177.192878
+C 81.134234 177.97599 82.196512 178.416 83.304 178.416
+z
+" clip-path="url(#p37831d8287)" style="fill: #3e73a8"/>
+ </g>
+ <g id="patch_37">
+ <path d="M 93.744 178.416
+C 94.851488 178.416 95.913766 177.97599 96.696878 177.192878
+C 97.47999 176.409766 97.92 175.347488 97.92 174.24
+C 97.92 173.132512 97.47999 172.070234 96.696878 171.287122
+C 95.913766 170.50401 94.851488 170.064 93.744 170.064
+C 92.636512 170.064 91.574234 170.50401 90.791122 171.287122
+C 90.00801 172.070234 89.568 173.132512 89.568 174.24
+C 89.568 175.347488 90.00801 176.409766 90.791122 177.192878
+C 91.574234 177.97599 92.636512 178.416 93.744 178.416
+z
+" clip-path="url(#p37831d8287)" style="fill: #bc7d14"/>
+ </g>
+ <g id="patch_38">
+ <path d="M 104.184 178.416
+C 105.291488 178.416 106.353766 177.97599 107.136878 177.192878
+C 107.91999 176.409766 108.36 175.347488 108.36 174.24
+C 108.36 173.132512 107.91999 172.070234 107.136878 171.287122
+C 106.353766 170.50401 105.291488 170.064 104.184 170.064
+C 103.076512 170.064 102.014234 170.50401 101.231122 171.287122
+C 100.44801 172.070234 100.008 173.132512 100.008 174.24
+C 100.008 175.347488 100.44801 176.409766 101.231122 177.192878
+C 102.014234 177.97599 103.076512 178.416 104.184 178.416
+z
+" clip-path="url(#p37831d8287)" style="fill: #bf4f4b"/>
+ </g>
+ <g id="patch_39">
+ <path d="M 20.88 166.68
+Q 20.88 161.28 20.88 156.830329
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #63727d; stroke-width: 0.85; stroke-linecap: round"/>
+ <path d="M 19.98 158.630329
+L 20.88 156.830329
+L 21.78 158.630329
+z
+" clip-path="url(#p37831d8287)" style="fill: #63727d; stroke: #63727d; stroke-width: 0.85; stroke-linecap: round"/>
+ </g>
+ <g id="text_53">
+ <!-- for the next session -->
+ <g style="fill: #63727d" transform="translate(26.28 162.494125) scale(0.044 -0.044)">
+ <use xlink:href="#DejaVuSans-66"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(35.205078 0)"/>
+ <use xlink:href="#DejaVuSans-72" transform="translate(96.386719 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(137.5 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(169.287109 0)"/>
+ <use xlink:href="#DejaVuSans-68" transform="translate(208.496094 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(271.875 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(333.398438 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(365.185547 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(428.564453 0)"/>
+ <use xlink:href="#DejaVuSans-78" transform="translate(488.337891 0)"/>
+ <use xlink:href="#DejaVuSans-74" transform="translate(547.517578 0)"/>
+ <use xlink:href="#DejaVuSans-20" transform="translate(586.726562 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(618.513672 0)"/>
+ <use xlink:href="#DejaVuSans-65" transform="translate(670.613281 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(732.136719 0)"/>
+ <use xlink:href="#DejaVuSans-73" transform="translate(784.236328 0)"/>
+ <use xlink:href="#DejaVuSans-69" transform="translate(836.335938 0)"/>
+ <use xlink:href="#DejaVuSans-6f" transform="translate(864.119141 0)"/>
+ <use xlink:href="#DejaVuSans-6e" transform="translate(925.300781 0)"/>
+ </g>
+ </g>
+ <g id="patch_40">
+ <path d="M 142.2 41.184
+C 143.383867 41.184 144.519405 40.713645 145.356525 39.876525
+C 146.193645 39.039405 146.664 37.903867 146.664 36.72
+C 146.664 35.536133 146.193645 34.400595 145.356525 33.563475
+C 144.519405 32.726355 143.383867 32.256 142.2 32.256
+C 141.016133 32.256 139.880595 32.726355 139.043475 33.563475
+C 138.206355 34.400595 137.736 35.536133 137.736 36.72
+C 137.736 37.903867 138.206355 39.039405 139.043475 39.876525
+C 139.880595 40.713645 141.016133 41.184 142.2 41.184
+z
+" clip-path="url(#p37831d8287)" style="fill: #3e73a8"/>
+ </g>
+ <g id="patch_41">
+ <path d="M 142.2 84.024
+C 143.383867 84.024 144.519405 83.553645 145.356525 82.716525
+C 146.193645 81.879405 146.664 80.743867 146.664 79.56
+C 146.664 78.376133 146.193645 77.240595 145.356525 76.403475
+C 144.519405 75.566355 143.383867 75.096 142.2 75.096
+C 141.016133 75.096 139.880595 75.566355 139.043475 76.403475
+C 138.206355 77.240595 137.736 78.376133 137.736 79.56
+C 137.736 80.743867 138.206355 81.879405 139.043475 82.716525
+C 139.880595 83.553645 141.016133 84.024 142.2 84.024
+z
+" clip-path="url(#p37831d8287)" style="fill: #bc7d14"/>
+ </g>
+ <g id="patch_42">
+ <path d="M 142.2 126.864
+C 143.383867 126.864 144.519405 126.393645 145.356525 125.556525
+C 146.193645 124.719405 146.664 123.583867 146.664 122.4
+C 146.664 121.216133 146.193645 120.080595 145.356525 119.243475
+C 144.519405 118.406355 143.383867 117.936 142.2 117.936
+C 141.016133 117.936 139.880595 118.406355 139.043475 119.243475
+C 138.206355 120.080595 137.736 121.216133 137.736 122.4
+C 137.736 123.583867 138.206355 124.719405 139.043475 125.556525
+C 139.880595 126.393645 141.016133 126.864 142.2 126.864
+z
+" clip-path="url(#p37831d8287)" style="fill: #bf4f4b"/>
+ </g>
+ <g id="patch_43">
+ <path d="M 115.2 49.68
+Q 124.74 49.68 133.329671 49.68
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #3e73a8; stroke-width: 0.85; stroke-linecap: round"/>
+ <path d="M 131.529671 48.78
+L 133.329671 49.68
+L 131.529671 50.58
+z
+" clip-path="url(#p37831d8287)" style="fill: #3e73a8; stroke: #3e73a8; stroke-width: 0.85; stroke-linecap: round"/>
+ </g>
+ <g id="patch_44">
+ <path d="M 115.2 92.52
+Q 124.74 92.52 133.329671 92.52
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #bc7d14; stroke-width: 0.85; stroke-linecap: round"/>
+ <path d="M 131.529671 91.62
+L 133.329671 92.52
+L 131.529671 93.42
+z
+" clip-path="url(#p37831d8287)" style="fill: #bc7d14; stroke: #bc7d14; stroke-width: 0.85; stroke-linecap: round"/>
+ </g>
+ <g id="patch_45">
+ <path d="M 115.2 135.36
+Q 124.74 135.36 133.329671 135.36
+" clip-path="url(#p37831d8287)" style="fill: none; stroke: #bf4f4b; stroke-width: 0.85; stroke-linecap: round"/>
+ <path d="M 131.529671 134.46
+L 133.329671 135.36
+L 131.529671 136.26
+z
+" clip-path="url(#p37831d8287)" style="fill: #bf4f4b; stroke: #bf4f4b; stroke-width: 0.85; stroke-linecap: round"/>
+ </g>
+ <g id="text_54">
+ <!-- 1 -->
+ <g style="fill: #ffffff" transform="translate(13.519703 43.029313) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-Bold-31" d="M 750 831
+L 1813 831
+L 1813 3847
+L 722 3622
+L 722 4441
+L 1806 4666
+L 2950 4666
+L 2950 831
+L 4013 831
+L 4013 0
+L 750 0
+L 750 831
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-31"/>
+ </g>
+ </g>
+ <g id="text_55">
+ <!-- 2 -->
+ <g style="fill: #ffffff" transform="translate(13.519703 85.869312) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-Bold-32" d="M 1844 884
+L 3897 884
+L 3897 0
+L 506 0
+L 506 884
+L 2209 2388
+Q 2438 2594 2547 2791
+Q 2656 2988 2656 3200
+Q 2656 3528 2436 3728
+Q 2216 3928 1850 3928
+Q 1569 3928 1234 3808
+Q 900 3688 519 3450
+L 519 4475
+Q 925 4609 1322 4679
+Q 1719 4750 2100 4750
+Q 2938 4750 3402 4381
+Q 3866 4013 3866 3353
+Q 3866 2972 3669 2642
+Q 3472 2313 2841 1759
+L 1844 884
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-32"/>
+ </g>
+ </g>
+ <g id="text_56">
+ <!-- 3 -->
+ <g style="fill: #ffffff" transform="translate(13.519703 128.709312) scale(0.046 -0.046)">
+ <defs>
+ <path id="DejaVuSans-Bold-33" d="M 2981 2516
+Q 3453 2394 3698 2092
+Q 3944 1791 3944 1325
+Q 3944 631 3412 270
+Q 2881 -91 1863 -91
+Q 1503 -91 1142 -33
+Q 781 25 428 141
+L 428 1069
+Q 766 900 1098 814
+Q 1431 728 1753 728
+Q 2231 728 2486 893
+Q 2741 1059 2741 1369
+Q 2741 1688 2480 1852
+Q 2219 2016 1709 2016
+L 1228 2016
+L 1228 2791
+L 1734 2791
+Q 2188 2791 2409 2933
+Q 2631 3075 2631 3366
+Q 2631 3634 2415 3781
+Q 2200 3928 1806 3928
+Q 1516 3928 1219 3862
+Q 922 3797 628 3669
+L 628 4550
+Q 984 4650 1334 4700
+Q 1684 4750 2022 4750
+Q 2931 4750 3382 4451
+Q 3834 4153 3834 3553
+Q 3834 3144 3618 2883
+Q 3403 2622 2981 2516
+z
+" transform="scale(0.015625)"/>
+ </defs>
+ <use xlink:href="#DejaVuSans-Bold-33"/>
+ </g>
+ </g>
+ <g id="text_57">
+ <!-- 1 -->
+ <g style="fill: #ffffff" transform="translate(81.912437 175.34375) scale(0.04 -0.04)">
+ <use xlink:href="#DejaVuSans-Bold-31"/>
+ </g>
+ </g>
+ <g id="text_58">
+ <!-- 2 -->
+ <g style="fill: #ffffff" transform="translate(92.352437 175.34375) scale(0.04 -0.04)">
+ <use xlink:href="#DejaVuSans-Bold-32"/>
+ </g>
+ </g>
+ <g id="text_59">
+ <!-- 3 -->
+ <g style="fill: #ffffff" transform="translate(102.792437 175.34375) scale(0.04 -0.04)">
+ <use xlink:href="#DejaVuSans-Bold-33"/>
+ </g>
+ </g>
+ <g id="text_60">
+ <!-- 1 -->
+ <g style="fill: #ffffff" transform="translate(140.738859 37.878937) scale(0.042 -0.042)">
+ <use xlink:href="#DejaVuSans-Bold-31"/>
+ </g>
+ </g>
+ <g id="text_61">
+ <!-- 2 -->
+ <g style="fill: #ffffff" transform="translate(140.738859 80.718937) scale(0.042 -0.042)">
+ <use xlink:href="#DejaVuSans-Bold-32"/>
+ </g>
+ </g>
+ <g id="text_62">
+ <!-- 3 -->
+ <g style="fill: #ffffff" transform="translate(140.738859 123.558937) scale(0.042 -0.042)">
+ <use xlink:href="#DejaVuSans-Bold-33"/>
+ </g>
+ </g>
+ </g>
+ </g>
+ <defs>
+ <clipPath id="p37831d8287">
+ <rect x="0" y="0" width="396" height="199.8"/>
+ </clipPath>
+ </defs>
+</svg>
diff --git a/experiments/README.md b/experiments/README.md
index 3be78d9..6a25e1e 100644
--- a/experiments/README.md
+++ b/experiments/README.md
@@ -12,7 +12,7 @@ themselves (an editable install, `pip install -e ..`, works too). Run commands f
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.
-### Proactive runtime cost control for sealed coding agents
+### 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.**
@@ -69,9 +69,9 @@ combined stack rather than as a separate system.
| Mechanism | Module | What it does |
|---|---|---|
-| **injection** | `mechanisms/injection.py` | 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** | `mechanisms/tooling.py`, `mechanisms/codex_untool.py` | 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** | `mechanisms/spiral.py`, `mechanisms/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. |
+| **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. |
## What is actually measured
@@ -118,12 +118,11 @@ distributed wheel — which is precisely what keeps Layer 1's guarantee structur
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.
-`te_live/` (at the repository root) is the second harness, and the proof of that claim: the
-**live harness** 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/` packages it for
-installation. It is a sibling of the core for the same reason `te_harness` is — it reaches an
-agent CLI — but it ships in the wheel, because it is what `te` runs. See
-[`../docs/PLUGIN.md`](../docs/PLUGIN.md).
+`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).
**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
@@ -137,8 +136,8 @@ harness, or benchmark is an addition rather than an edit:
| Seam | Module | Separates |
|---|---|---|
| `AgentRunner` | `runner.py` | the controller from task execution and paid LLM calls |
-| `DomainAdapter` | `adapters/` | the controller from what a "task" is |
-| trace | `trace.py` | every mechanism from the shape of a rollout's event stream |
+| `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 |
The mechanisms read rollouts through the one trace seam and charge cost through the one
@@ -149,6 +148,19 @@ its own accounting.
```
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
@@ -164,20 +176,18 @@ experiments/ the paper's reproduction code (this directory)
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), shared with the plugin
- facade.py Economizer, the orchestration entry point
- config.py three independent on/off switches, one per mechanism
- arms.py _armspec.py named arm → exact configuration (the experiment's vocabulary)
- ledger.py trace.py the one cost definition + the one trace seam
- runner.py AgentRunner interface — the harness seam
- workloads.py the evaluated task set, as data (which instances, per domain)
- mechanisms/ injection · tooling · spiral (+ the Codex-native variants)
- baselines/ third-party tool scaffolds (rtk · serena · aider repo-map) —
- comparison points, not mechanisms
- adapters/ DomainAdapter + swebench · webbench · creddata · reposvul ·
- cybergym · webarena
- vendor/ pricing · reflect · spiral, vendored verbatim, stdlib-only
-../te_live/ ../plugin/ the plugin (see ../README.md)
+../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
diff --git a/experiments/docs/BENCHMARKS.md b/experiments/docs/BENCHMARKS.md
index e237653..673691b 100644
--- a/experiments/docs/BENCHMARKS.md
+++ b/experiments/docs/BENCHMARKS.md
@@ -40,13 +40,13 @@ the driver's task list and the adapter's instance source. For every other domain
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 — `tokeneconomizer.workloads`
+### 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 tokeneconomizer import workloads
+from te_bench import workloads
workloads.task_counts("swebench") # {'django/django': 40, ..., 'pydata/xarray': 39}
workloads.total_tasks("swebench") # 229 tasks per seed
@@ -136,7 +136,7 @@ mkdir -p "$DATA/swebench"
python - <<'PY'
import json, os
from datasets import load_dataset # pip install datasets (provisioning only)
-from tokeneconomizer import workloads
+from te_bench import workloads
wanted = {i for ids in workloads.runnable_instances("swebench").values() for i in ids} # 277
rows, seen = [], set()
@@ -167,7 +167,7 @@ Note the tag convention: the `__` in an instance id becomes `_1776_` in the imag
```bash
python - > "$DATA/swebench/image_tags.txt" <<'PY'
-from tokeneconomizer import workloads
+from te_bench import workloads
for ids in workloads.runnable_instances("swebench").values():
for iid in ids:
print(workloads.swebench_image_tag(iid))
@@ -292,7 +292,7 @@ python scripts/export_webbench_tasks.py --check # verify only; exit 1 if stal
```
> **Three registries have to agree, and only one of them is the authority.**
-> `tokeneconomizer/workloads.py` decides which projects and tasks are in the sweep; (A) the
+> `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:
@@ -369,12 +369,12 @@ 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
-`tokeneconomizer/adapters/creddata.py:CREDDATA_TASK_PROMPT`):
+`experiments/te_bench/adapters/creddata.py:CREDDATA_TASK_PROMPT`):
```bash
python - <<'PY'
import glob, json, os
-from tokeneconomizer.adapters.creddata import CREDDATA_TASK_PROMPT
-from tokeneconomizer import workloads
+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
@@ -415,12 +415,12 @@ prepared instance each). Every instance gets the **same** vulnerability-audit pr
is line-level **F1**. No Docker image.
**Export the driver task list (A)** (prompt from
-`tokeneconomizer/adapters/reposvul.py:REPOSVUL_TASK_PROMPT`):
+`experiments/te_bench/adapters/reposvul.py:REPOSVUL_TASK_PROMPT`):
```bash
python - <<'PY'
import glob, json, os
-from tokeneconomizer.adapters.reposvul import REPOSVUL_TASK_PROMPT
-from tokeneconomizer import workloads
+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
@@ -459,7 +459,7 @@ 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 tokeneconomizer/adapters/cybergym.py).
+# 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 \
diff --git a/experiments/docs/COPILOT.md b/experiments/docs/COPILOT.md
index 9d496eb..5997a64 100644
--- a/experiments/docs/COPILOT.md
+++ b/experiments/docs/COPILOT.md
@@ -130,7 +130,7 @@ ValueError: pricing: no weight entry for billed model 'my-model' (agent='copilot
Add it to pricing.MODEL_WEIGHTS
```
-Add the id to `tokeneconomizer/vendor/pricing.py` before pinning it. Ids containing
+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.
@@ -270,7 +270,7 @@ That distinction decides which mechanism to run:
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 `vendor/claude_tool_catalog.json` does for
+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
diff --git a/experiments/docs/HARNESS.md b/experiments/docs/HARNESS.md
index ce2f173..ba351af 100644
--- a/experiments/docs/HARNESS.md
+++ b/experiments/docs/HARNESS.md
@@ -1,7 +1,7 @@
# te_harness — Layer-2 task-execution harness for TokenEconomizer
Everything that touches Docker, an agent CLI, or a credential lives **below**
-`tokeneconomizer.runner.AgentRunner`. [`te_harness/`](../te_harness) is this repo's
+`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.
@@ -356,7 +356,7 @@ loaded. The Copilot CLI dumps tool schemas into its debug log; Claude Code does
transcript carries only the tool *names* — so the descriptions are captured off the wire:
```bash
-python -m te_harness.capture_catalog # -> tokeneconomizer/vendor/claude_tool_catalog.json
+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 —
@@ -392,7 +392,7 @@ 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 `tokeneconomizer/baselines/`, and
+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
@@ -406,7 +406,7 @@ carried by `AgentProfile.home` / `AgentProfile.bin_dir`, so a scaffold never bra
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 anything under `mechanisms/` — so `import tokeneconomizer` stays
+`__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 |
@@ -475,7 +475,7 @@ name.
### Adding one
-Subclass `Scaffold` (`tokeneconomizer/baselines/base.py`), implement `setup(ctx)` returning a
+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
diff --git a/experiments/scripts/README.md b/experiments/scripts/README.md
index e9c9f97..1f56851 100644
--- a/experiments/scripts/README.md
+++ b/experiments/scripts/README.md
@@ -42,7 +42,7 @@ only.
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 `tokeneconomizer.runner.AgentRunner` interface**, in
+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.
@@ -50,7 +50,7 @@ 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 (`tokeneconomizer.facade.Economizer`);
+- 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
diff --git a/experiments/scripts/aggregate.py b/experiments/scripts/aggregate.py
index 57f8105..aee2ae7 100644
--- a/experiments/scripts/aggregate.py
+++ b/experiments/scripts/aggregate.py
@@ -35,7 +35,7 @@ import sys
_EXPERIMENTS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path[:0] = [_EXPERIMENTS, os.path.dirname(_EXPERIMENTS)] # te_harness; the core at the root
from tokeneconomizer import ledger # noqa: E402
-from tokeneconomizer.vendor import pricing # noqa: E402
+from tokeneconomizer import pricing # noqa: E402
FIELDS = [
"arm", "repo", "seed", "instance", "repo_full", "mode",
diff --git a/experiments/scripts/compare_arms.py b/experiments/scripts/compare_arms.py
index e82e198..f4a85e2 100644
--- a/experiments/scripts/compare_arms.py
+++ b/experiments/scripts/compare_arms.py
@@ -26,7 +26,7 @@ import sys
_EXPERIMENTS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path[:0] = [_EXPERIMENTS, os.path.dirname(_EXPERIMENTS)] # te_harness; the core at the root
from tokeneconomizer import ledger # noqa: E402
-from tokeneconomizer.vendor import pricing # noqa: E402
+from tokeneconomizer import pricing # noqa: E402
def load_cell(cell):
@@ -140,7 +140,7 @@ def main():
print(f" {life['state']:9s} fire={life['fire_num']}/{life['fire_den']} "
f"promoted@{life.get('promoted_at')} retired@{life.get('retired_at')} {fid}")
# the block that would be rendered next, from the saved state
- from tokeneconomizer.mechanisms.envfacts import EnvFactsDistiller
+ from tokeneconomizer.microskills import EnvFactsDistiller
dist = EnvFactsDistiller.load(d["repo"], args.arm)
block = dist.render()
print(" current block:" + ("\n " + block.replace("\n", "\n ") if block else " (none)"))
diff --git a/experiments/scripts/export_webbench_tasks.py b/experiments/scripts/export_webbench_tasks.py
old mode 100644
new mode 100755
index 2712b40..c1c5804
--- a/experiments/scripts/export_webbench_tasks.py
+++ b/experiments/scripts/export_webbench_tasks.py
@@ -9,7 +9,7 @@ nor derivable at run time:
B projects tree the Web-Bench checkout, $TOKENECONOMIZER_WEBBENCH_PROJECTS
C workload record workloads/webbench.json, via scripts/export_workloads.py
-`tokeneconomizer/workloads.py` is the authority for WHICH projects and tasks are in the
+`experiments/te_bench/workloads.py` is the authority for WHICH projects and tasks are in the
sweep; A and C are both projections of it. Changing the project list therefore means three
commands, in this order:
@@ -32,7 +32,7 @@ import sys
_EXPERIMENTS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path[:0] = [_EXPERIMENTS, os.path.dirname(_EXPERIMENTS)] # te_harness; the core at the root
-from tokeneconomizer import workloads # noqa: E402
+from te_bench import workloads # noqa: E402
PROJECTS_ENV = "TOKENECONOMIZER_WEBBENCH_PROJECTS"
TASKS_ENV = "TOKENECONOMIZER_WEBBENCH_TASKS"
diff --git a/experiments/scripts/export_workloads.py b/experiments/scripts/export_workloads.py
index 4db8cc3..56a9003 100644
--- a/experiments/scripts/export_workloads.py
+++ b/experiments/scripts/export_workloads.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Export the canonical workloads to ``workloads/<domain>.json`` (committed, not ignored).
-``tokeneconomizer/workloads.py`` is the authority; these JSON files are the machine-readable
+``experiments/te_bench/workloads.py`` is the authority; these JSON files are the machine-readable
copy the shell launchers and any non-Python harness can read without importing the package.
They are tiny (ids only, no issue text) and therefore **committed** — unlike the results
tree, which is regenerated per run and git-ignored.
@@ -19,7 +19,7 @@ import sys
_EXPERIMENTS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path[:0] = [_EXPERIMENTS, os.path.dirname(_EXPERIMENTS)] # te_harness; the core at the root
-from tokeneconomizer import workloads # noqa: E402
+from te_bench import workloads # noqa: E402
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT_DIR = os.path.join(REPO, "workloads")
@@ -54,7 +54,7 @@ def build(domain):
doc = {
"domain": domain,
"description": _DOC[domain],
- "source": "tokeneconomizer/workloads.py (regenerate: python scripts/export_workloads.py)",
+ "source": "experiments/te_bench/workloads.py (regenerate: python scripts/export_workloads.py)",
"group_field": _GROUP_FIELD[domain],
"seeds": _SEEDS[domain],
"total_tasks": sum(len(v) for v in groups.values()),
@@ -72,7 +72,7 @@ def build(domain):
"instances that exist only in the full princeton-nlp/SWE-bench test split. "
"Docker image tag: swebench/sweb.eval.x86_64.<id with __ -> _1776_>:latest. "
"'excluded' lists ids dropped from THIS run list with the reason; they are "
- "still part of the recorded workload in tokeneconomizer/workloads.py "
+ "still part of the recorded workload in experiments/te_bench/workloads.py "
"(SWEBENCH_INSTANCES) and were run by the published results, so a cell that "
"skips them is not directly comparable to one that did not. "
"'added' lists ids that EXTEND a stream beyond the published workload to "
diff --git a/experiments/scripts/launch/README.md b/experiments/scripts/launch/README.md
index ce5abc6..20e2220 100644
--- a/experiments/scripts/launch/README.md
+++ b/experiments/scripts/launch/README.md
@@ -11,7 +11,7 @@ command per lane, is [`../../docs/RUNNING.md`](../../docs/RUNNING.md).
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 `tokeneconomizer.runner.AgentRunner`**, in
+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:
@@ -151,7 +151,7 @@ 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 `tokeneconomizer/runner.py`). Runners that do not define them are called as usual.
+ (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
diff --git a/experiments/scripts/launch/codex_ab.sh b/experiments/scripts/launch/codex_ab.sh
old mode 100644
new mode 100755
index 31cb053..fa3aa8e
--- a/experiments/scripts/launch/codex_ab.sh
+++ b/experiments/scripts/launch/codex_ab.sh
@@ -23,7 +23,7 @@
# (SWE-bench only). Rows carry map_ok / map_chars: map_ok false means
# the task ran as plain codex-trimech.
#
-# The heavy harness lives below tokeneconomizer.runner.AgentRunner, in the repo's te_harness
+# The heavy harness lives below te_bench.runner.AgentRunner, in the repo's te_harness
# package (RUNNER=te_harness.swebench:make_runner, no PYTHONPATH needed). Point RUNNER at
# another factory ("module:make_runner") to substitute one; RUNNER=stub uses the offline
# StubRunner (synthetic).
diff --git a/experiments/scripts/launch/fleet_budget.sh b/experiments/scripts/launch/fleet_budget.sh
old mode 100644
new mode 100755
diff --git a/experiments/scripts/launch/full_sweep.sh b/experiments/scripts/launch/full_sweep.sh
old mode 100644
new mode 100755
diff --git a/experiments/scripts/launch/main_sweep.sh b/experiments/scripts/launch/main_sweep.sh
old mode 100644
new mode 100755
index d442652..747513b
--- a/experiments/scripts/launch/main_sweep.sh
+++ b/experiments/scripts/launch/main_sweep.sh
@@ -21,7 +21,7 @@
# trimech-rtk all three + rtk (SWE-bench only)
# trimech-repomap all three + the repo map (SWE-bench only)
#
-# The last five install an EXTERNAL TOOL (tokeneconomizer/baselines/) into the agent's
+# The last five install an EXTERNAL TOOL (experiments/te_bench/baselines/) into the agent's
# container -- baselines, not mechanisms. They are SWE-bench only: Web-Bench reaches its
# agent through the evaluator's HTTP seam with no per-task repo container. Asking for one
# on DOMAIN=webbench fails in the plan rather than enumerating cells that cannot run.
diff --git a/experiments/scripts/launch/smoke_test.sh b/experiments/scripts/launch/smoke_test.sh
old mode 100644
new mode 100755
diff --git a/experiments/scripts/launch/trimech_ab.sh b/experiments/scripts/launch/trimech_ab.sh
old mode 100644
new mode 100755
index 9b910ed..7f495a0
--- a/experiments/scripts/launch/trimech_ab.sh
+++ b/experiments/scripts/launch/trimech_ab.sh
@@ -11,7 +11,7 @@
# --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
-# tokeneconomizer.runner.AgentRunner, in the repo's te_harness package, so
+# 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.
diff --git a/experiments/scripts/run_experiment.py b/experiments/scripts/run_experiment.py
index 74aa605..e4bf6ce 100644
--- a/experiments/scripts/run_experiment.py
+++ b/experiments/scripts/run_experiment.py
@@ -32,18 +32,18 @@ original launches used:
The single-mechanism arms use the SAME parameters trimech co-activates, so each is a true
ablation of it rather than a separately tuned arm. The external tool scaffolds are
-implemented in `tokeneconomizer/baselines/` and install into the task container; a
+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).
-The arm tables live next to the code they configure -- `tokeneconomizer/mechanisms/arms.py`
+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
-beside `trimech`) and `tokeneconomizer/baselines/arms.py` for the pure-baseline arms. They
-are assembled in `tokeneconomizer/arms.py` and re-exported here, so this module stays the
+beside `trimech`) and `experiments/te_bench/baselines/arms.py` for the pure-baseline arms. They
+are assembled in `experiments/te_bench/arms.py` and re-exported here, so this module stays the
entry point the docs point at.
The heavy task-execution harness (Docker + agent CLI + official gold grading) lives BELOW
-the ``tokeneconomizer.runner.AgentRunner`` seam, in the repo's ``te_harness`` package -- the
+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
``--runner module:factory`` (a zero-arg callable returning an AgentRunner). ``--runner stub``
@@ -75,7 +75,8 @@ sys.path[:0] = [os.path.dirname(os.path.abspath(__file__)), # _env, sweep_plan
_EXPERIMENTS, # te_harness
os.path.dirname(_EXPERIMENTS)] # the core, at the repository root
from _env import load_env # noqa: E402
-from tokeneconomizer import Economizer, EconomizerConfig # noqa: E402
+from te_bench.facade import Economizer # noqa: E402
+from tokeneconomizer import EconomizerConfig # noqa: E402
from tokeneconomizer import ledger # noqa: E402
from tokeneconomizer.config import needs_optimizer # noqa: E402
@@ -84,16 +85,16 @@ from tokeneconomizer.config import needs_optimizer # noqa: E402
# Re-exported so this module stays the entry point the docs and every existing import point
# at. The definitions moved next to the code they configure:
#
-# tokeneconomizer/mechanisms/arms.py naive, effort variants, single-mechanism ablations,
+# experiments/te_bench/mechanism_arms.py naive, effort variants, single-mechanism ablations,
# trimech, trimech-web, the two trimech-<scaffold>
# integrations (siblings of trimech), codex-*
-# tokeneconomizer/baselines/arms.py rtk / serena / repomap -- external tool only
-# tokeneconomizer/arms.py assembles both in canonical order
+# experiments/te_bench/baselines/arms.py rtk / serena / repomap -- external tool only
+# experiments/te_bench/arms.py assembles both in canonical order
#
-# `Arm`, `cfg` and `arm` come from tokeneconomizer._armspec; `_cfg`/`_arm` remain as aliases
+# `Arm`, `cfg` and `arm` come from te_bench._armspec; `_cfg`/`_arm` remain as aliases
# because tests and older callers refer to them by those names.
-from tokeneconomizer.arms import ARMS, SCAFFOLD_ARMS # noqa: E402,F401
-from tokeneconomizer._armspec import Arm, arm as _arm, cfg as _cfg # noqa: E402,F401
+from te_bench.arms import ARMS, SCAFFOLD_ARMS # noqa: E402,F401
+from te_bench._armspec import Arm, arm as _arm, cfg as _cfg # noqa: E402,F401
# ---- built-in offline StubRunner (smoke test only) ---------------------------------------
@@ -209,13 +210,13 @@ def load_runner(spec, agent, model=None, scaffold=None):
f"runner {spec!r} does not accept a scaffold, but this arm needs "
f"{scaffold!r}. A harness that ignored it would run NATIVE and file the "
f"rows under the scaffold's name. Add a `scaffold=` parameter (see "
- f"tokeneconomizer/baselines/) or pick an arm without one.")
+ f"experiments/te_bench/baselines/) or pick an arm without one.")
os.environ.setdefault("TE_SCAFFOLD", scaffold)
return factory(**kw) if kw else factory()
def load_adapter(name, tasks_file, repo=""):
- from tokeneconomizer.adapters import (
+ from te_bench.adapters import (
SwebenchAdapter, WebBenchAdapter, CredDataAdapter, ReposVulAdapter,
CyberGymAdapter)
if name == "swebench":
@@ -327,7 +328,7 @@ def main():
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--arm", required=True, choices=sorted(ARMS),
help="arm to run; %s additionally install an external tool scaffold "
- "(tokeneconomizer/baselines/)"
+ "(experiments/te_bench/baselines/)"
% ", ".join(sorted(SCAFFOLD_ARMS)))
ap.add_argument("--agent", default="claude", choices=["claude", "copilot", "codex"],
help="the sealed agent (selects transcript schema + generic-vs-codex "
diff --git a/experiments/scripts/summarize_stream.py b/experiments/scripts/summarize_stream.py
index 785a836..f4f568f 100644
--- a/experiments/scripts/summarize_stream.py
+++ b/experiments/scripts/summarize_stream.py
@@ -33,7 +33,7 @@ import argparse, glob, json, os, sys
_EXPERIMENTS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path[:0] = [_EXPERIMENTS, os.path.dirname(_EXPERIMENTS)] # te_harness; the core at the root
from tokeneconomizer import ledger
-from tokeneconomizer.vendor import pricing
+from tokeneconomizer import pricing
def _num(x):
diff --git a/experiments/scripts/sweep_plan.py b/experiments/scripts/sweep_plan.py
old mode 100644
new mode 100755
index e8d4b76..027a146
--- a/experiments/scripts/sweep_plan.py
+++ b/experiments/scripts/sweep_plan.py
@@ -34,7 +34,7 @@ import sys
_EXPERIMENTS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path[:0] = [_EXPERIMENTS, os.path.dirname(_EXPERIMENTS)] # te_harness; the core at the root
-from tokeneconomizer import workloads # noqa: E402
+from te_bench import workloads # noqa: E402
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from run_experiment import ARMS, SCAFFOLD_ARMS # noqa: E402
@@ -91,7 +91,7 @@ SWEEP_ARMS_WEBBENCH_OUT_OF_SCOPE = ("inject-only", "untool-only", "spiral-only-w
# commands. te_harness.webbench.WEBBENCH_SCAFFOLDS is the runner-side twin of this set.
#
# The other two do not:
-# repomap -- its generator walks `*.py` (baselines/_repomap_gen.py) and a Web-Bench
+# repomap -- its generator walks `*.py` (tokeneconomizer/plugin/repomap_gen.py) and a Web-Bench
# project is TypeScript/JavaScript, so the map would come back empty. Needs a
# language change, not a wiring change.
# serena -- an MCP navigation server for a codebase. Web-Bench hands the agent a file
@@ -110,7 +110,7 @@ SWEEP_ARMS_WEBBENCH_SUPERSEDED = {"trimech": "trimech-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 tokeneconomizer.baselines import ARM_SCAFFOLDS as _ARM_SCAFFOLDS
+ 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()
diff --git a/experiments/scripts/webbench_tasks_from_yaml.py b/experiments/scripts/webbench_tasks_from_yaml.py
old mode 100644
new mode 100755
index 2302746..831e5a3
--- a/experiments/scripts/webbench_tasks_from_yaml.py
+++ b/experiments/scripts/webbench_tasks_from_yaml.py
@@ -3,7 +3,7 @@
Some Web-Bench projects ship only `tasks.yml`. Two readers on our side take `tasks.jsonl`
and nothing else -- `te_harness.webbench.WebBenchStream._tasks` and
-`tokeneconomizer.adapters.webbench.WebBenchAdapter.tasks_path` -- so those projects need a
+`te_bench.adapters.webbench.WebBenchAdapter.tasks_path` -- so those projects need a
derived jsonl before they can be run or judged.
The yml is left in place ON PURPOSE. Web-Bench's own evaluator prefers it when both exist
@@ -80,7 +80,7 @@ def swept_yml_projects(root):
Deliberately not "every project with a tasks.yml": the checkout has ~18 of those, most of
them outside the sweep, and one (`prisma`) ships both files. Writing to those would mutate
a checkout the sweep never reads."""
- from tokeneconomizer import workloads
+ from te_bench import workloads
for name in workloads.WEBBENCH_TASKS:
if os.path.isfile(os.path.join(root, name, "tasks.yml")):
yield name
diff --git a/experiments/te_bench/__init__.py b/experiments/te_bench/__init__.py
new file mode 100644
index 0000000..d8e8306
--- /dev/null
+++ b/experiments/te_bench/__init__.py
@@ -0,0 +1,13 @@
+"""The benchmark side of TokenEconomizer: what the experiments run the core with.
+
+The core (`tokeneconomizer`, at the repository root) is what the plugin ships: the three
+mechanisms, the trace seam, the ledger and their configuration. Everything here exists only to
+run those mechanisms over benchmark streams, and nothing in the core or the plugin imports it:
+
+ * `adapters/` -- the benchmark domains (SWE-bench, Web-Bench, CredData, ReposVul, ...).
+ * `facade` -- `Economizer`, the three mechanisms wired around one adapter.
+ * `runner` -- the `AgentRunner` seam a harness implements (te_harness is the reference).
+ * `workloads` -- the exact task sets the experiments ran.
+ * `arms`, `mechanism_arms`, `_armspec` -- the named experiment arms.
+ * `baselines/` -- the external-scaffold comparisons (rtk, Serena, aider's repo map).
+"""
diff --git a/tokeneconomizer/_armspec.py b/experiments/te_bench/_armspec.py
similarity index 85%
rename from tokeneconomizer/_armspec.py
rename to experiments/te_bench/_armspec.py
index 44f47df..790f40a 100644
--- a/tokeneconomizer/_armspec.py
+++ b/experiments/te_bench/_armspec.py
@@ -1,7 +1,7 @@
"""The `Arm` type and its two constructors, shared by the arm tables.
-A leaf module on purpose: `mechanisms/arms.py` and `baselines/arms.py` both import from
-here, and `tokeneconomizer/arms.py` imports both of them, so the primitives cannot live in
+A leaf module on purpose: `mechanism_arms.py` and `baselines/arms.py` both import from
+here, and `experiments/te_bench/arms.py` imports both of them, so the primitives cannot live in
either of those without a cycle.
An `Arm` is (mode, config-factory, env-overlay, scaffold):
@@ -18,7 +18,7 @@ An `Arm` is (mode, config-factory, env-overlay, scaffold):
agent CLI, not in a mechanism).
* ``scaffold`` -- names an EXTERNAL TOOL BASELINE the harness installs into every task
container. **A name, not an object**: the string is resolved lazily by
- the harness through ``tokeneconomizer.baselines.get()``. That is what lets
+ the harness through ``te_bench.baselines.get()``. That is what lets
an arm table mention `rtk` without importing the baselines package, which
in turn is what keeps `import tokeneconomizer` free of their dependencies.
@@ -28,7 +28,7 @@ meet, and the only place an arm name maps to either.
"""
import collections
-from .config import EconomizerConfig, InjectionConfig, ToolingConfig, SpiralConfig
+from tokeneconomizer.config import EconomizerConfig, InjectionConfig, ToolingConfig, SpiralConfig
__all__ = ["Arm", "cfg", "arm"]
diff --git a/tokeneconomizer/adapters/__init__.py b/experiments/te_bench/adapters/__init__.py
similarity index 77%
rename from tokeneconomizer/adapters/__init__.py
rename to experiments/te_bench/adapters/__init__.py
index 18cbb69..62f7d71 100644
--- a/tokeneconomizer/adapters/__init__.py
+++ b/experiments/te_bench/adapters/__init__.py
@@ -1,8 +1,7 @@
-"""Domain adapters for the economizer.
+"""The benchmark domain adapters the experiments ran.
-The three mechanisms (injection / tooling / spiral) are domain-neutral: they read a
-normalized trajectory and count turns/tokens. Everything domain-specific enters through a
-small, named surface -- a `DomainAdapter` (see `base.py`):
+Each implements the core's `tokeneconomizer.domain.DomainAdapter`, the whole surface through
+which a task domain reaches the mechanisms:
* SwebenchAdapter -- SWE-bench (the canonical domain).
* WebBenchAdapter -- Web-Bench (thin subclass; task-spec source only).
@@ -15,7 +14,7 @@ The facade threads ONE adapter (default SwebenchAdapter) into all three mechanis
domain = a new adapter, no mechanism edits. Dataset roots are supplied via env-var
placeholders (TOKENECONOMIZER_*), so no host paths are baked in.
"""
-from .base import DomainAdapter
+from tokeneconomizer.domain import DomainAdapter
from .swebench import SwebenchAdapter
from .webbench import WebBenchAdapter
from .creddata import CredDataAdapter
diff --git a/tokeneconomizer/adapters/creddata.py b/experiments/te_bench/adapters/creddata.py
similarity index 100%
rename from tokeneconomizer/adapters/creddata.py
rename to experiments/te_bench/adapters/creddata.py
diff --git a/tokeneconomizer/adapters/cybergym.py b/experiments/te_bench/adapters/cybergym.py
similarity index 100%
rename from tokeneconomizer/adapters/cybergym.py
rename to experiments/te_bench/adapters/cybergym.py
diff --git a/tokeneconomizer/adapters/reposvul.py b/experiments/te_bench/adapters/reposvul.py
similarity index 100%
rename from tokeneconomizer/adapters/reposvul.py
rename to experiments/te_bench/adapters/reposvul.py
diff --git a/tokeneconomizer/adapters/swebench.py b/experiments/te_bench/adapters/swebench.py
similarity index 70%
rename from tokeneconomizer/adapters/swebench.py
rename to experiments/te_bench/adapters/swebench.py
index 6625f78..6621d59 100644
--- a/tokeneconomizer/adapters/swebench.py
+++ b/experiments/te_bench/adapters/swebench.py
@@ -1,6 +1,6 @@
"""SwebenchAdapter: the SWE-bench task domain, as a DomainAdapter.
-Every reading method delegates to the vendored `reflect` signals + the `trace` seam, so
+Every reading method delegates to the core's `trace` reader and tool sets, so
this adapter carries the canonical SWE-bench behavior with no dependency on the Docker/CLI
harness. The only domain-specific I/O is `problem_statements()`, which loads the task-spec
JSON (issue text per instance) named by the `TOKENECONOMIZER_SWEBENCH_TASKS` env var. That
@@ -11,8 +11,8 @@ import json
import os
import re
-from .. import trace
-from ..vendor import reflect
+from tokeneconomizer import trace
+from tokeneconomizer.toolprune.tools import INAPPLICABLE_TOOLS, PROTECTED_TOOLS
# Task-spec source for the per-task tool judge. PLACEHOLDER: set this env var to the path
# of your SWE-bench instances JSON (list of {instance_id, problem_statement, ...}).
@@ -26,12 +26,31 @@ _GOLD_URL_RE = re.compile(
r"(?:pull|pulls|issues|issue|commit|commits|compare|blob|tree)/\S+", re.I)
+def untool_exclusions(used_tools=None, extra_inapplicable=()):
+ """The tools to exclude from one sealed task's schema.
+
+ The static `INAPPLICABLE_TOOLS` set (inapplicable by construction for a sealed single
+ task), widened by `extra_inapplicable`, less any tool `used_tools` shows in use across the
+ stream so far (a repository that genuinely uses one is never starved). `PROTECTED_TOOLS`
+ are never excluded."""
+ used = set(used_tools or ())
+ cand = list(INAPPLICABLE_TOOLS) + [t for t in extra_inapplicable
+ if t not in INAPPLICABLE_TOOLS]
+ return [t for t in cand if t not in PROTECTED_TOOLS and t not in used]
+
+
def redact_gold_pointers(text):
"""Return (redacted_text, n_redacted) with gold-solution URLs masked."""
n = len(_GOLD_URL_RE.findall(text or ""))
return _GOLD_URL_RE.sub("[link redacted]", text or ""), n
+# SWE-bench's task containers have no network, so on this benchmark the web tools cannot work;
+# they join the static inapplicable set here, in the benchmark's own adapter, rather than in
+# the shared list every domain reads.
+NETWORK_TOOLS = ("WebSearch", "WebFetch")
+
+
class SwebenchAdapter:
name = "swebench"
@@ -53,24 +72,20 @@ class SwebenchAdapter:
def parse_catalog_with_source(self, run_dir_path, agent):
return trace.parse_catalog_with_source(run_dir_path, agent)
- # ---- waste signals ----
- def detect(self, path):
- return reflect.detect(path)
-
# ---- untooling tool-sets ----
def protected_tools(self):
- return reflect.PROTECTED_TOOLS
+ return PROTECTED_TOOLS
def inapplicable_tools(self):
- return reflect.INAPPLICABLE_TOOLS
+ return tuple(INAPPLICABLE_TOOLS) + NETWORK_TOOLS
def hardcoded_exclusions(self, used_tools):
- return reflect.untool_exclusions(used_tools)
+ return untool_exclusions(used_tools, extra_inapplicable=NETWORK_TOOLS)
# ---- spiral envelope ----
def spiral_snapshot(self, path):
- from ..vendor import spiral
- return spiral.state_from_trajectory(path).snapshot()
+ from tokeneconomizer.loopguard import state_from_trajectory
+ return state_from_trajectory(path).snapshot()
# ---- per-task judge inputs ----
def problem_statements(self):
@@ -92,7 +107,7 @@ class SwebenchAdapter:
def env_vocabulary(self):
"""SWE-bench repositories are Python projects in git checkouts."""
- from ..mechanisms.envfacts import PYTHON_GIT
+ from tokeneconomizer.microskills import PYTHON_GIT
return PYTHON_GIT
def classify_domain(self):
diff --git a/tokeneconomizer/adapters/webarena.py b/experiments/te_bench/adapters/webarena.py
similarity index 88%
rename from tokeneconomizer/adapters/webarena.py
rename to experiments/te_bench/adapters/webarena.py
index 34285bc..fc5d0e5 100644
--- a/tokeneconomizer/adapters/webarena.py
+++ b/experiments/te_bench/adapters/webarena.py
@@ -21,14 +21,12 @@ Implementation notes (for whoever fills this in):
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).
- detect(path) web waste families (repeated navigation, redundant observation,
- failed selectors) in the shape reflect.detect emits.
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 tokeneconomizer.runner.AgentRunner).
+grade (see te_bench.runner.AgentRunner).
"""
_TODO = ("WebArenaAdapter is a stub: implement the WebArena/BrowserGym {what} "
@@ -47,9 +45,6 @@ class WebArenaAdapter:
def parse_catalog(self, run_dir_path, agent):
raise NotImplementedError(_TODO.format(what="browser action-space catalog"))
- def detect(self, path):
- raise NotImplementedError(_TODO.format(what="web waste-signal detector"))
-
def protected_tools(self):
raise NotImplementedError(_TODO.format(what="browser work-surface protected set"))
diff --git a/tokeneconomizer/adapters/webbench.py b/experiments/te_bench/adapters/webbench.py
similarity index 98%
rename from tokeneconomizer/adapters/webbench.py
rename to experiments/te_bench/adapters/webbench.py
index 3c27527..71c038c 100644
--- a/tokeneconomizer/adapters/webbench.py
+++ b/experiments/te_bench/adapters/webbench.py
@@ -50,7 +50,7 @@ class WebBenchAdapter(SwebenchAdapter):
"""Web-Bench projects are Node/npm workspaces: the same families, a different
vocabulary (node/deno as interpreters, jest/vitest/playwright as runners, npm/yarn/
pnpm as package tools)."""
- from ..mechanisms.envfacts import NODE_WEB
+ from tokeneconomizer.microskills import NODE_WEB
return NODE_WEB
def problem_statements(self):
diff --git a/tokeneconomizer/arms.py b/experiments/te_bench/arms.py
similarity index 89%
rename from tokeneconomizer/arms.py
rename to experiments/te_bench/arms.py
index cc0c8ee..b9948f2 100644
--- a/tokeneconomizer/arms.py
+++ b/experiments/te_bench/arms.py
@@ -3,7 +3,7 @@
This is the single source of truth. It assembles two tables that live next to the code they
configure:
-* `mechanisms/arms.py` -- everything the economizer drives: naive, the effort variants, the
+* `mechanism_arms.py` -- everything the economizer drives: naive, the effort variants, the
single-mechanism ablations, `trimech`, and the two scaffold **integrations**, which sit
beside `trimech` because that is what they are.
* `baselines/arms.py` -- arms that are only an external tool, with no mechanism active.
@@ -14,12 +14,12 @@ remains the entry point the docs point at and every existing import keeps workin
**Importing this module does not pull a baseline's dependencies.** The arm tables name a
scaffold with a string and the harness resolves it lazily, so `import tokeneconomizer` and
-`import tokeneconomizer.arms` both stay light -- and `tokeneconomizer/__init__.py`
+`import te_bench.arms` both stay light -- and `tokeneconomizer/__init__.py`
deliberately does not import this module, so the zero-dependency core import is unchanged.
"""
from ._armspec import Arm, arm, cfg
from .baselines.arms import BASELINE_ARMS
-from .mechanisms.arms import MECHANISM_ARMS
+from .mechanism_arms import MECHANISM_ARMS
__all__ = ["ARMS", "SCAFFOLD_ARMS", "ARM_ORDER", "Arm", "arm", "cfg"]
@@ -51,5 +51,5 @@ ARMS = {name: _MERGED[name] for name in ARM_ORDER}
# Arms carrying an external tool scaffold, derived rather than restated so it cannot fall
# out of step with ARMS. `tests/test_sweep_arms.py` pins this against
-# `tokeneconomizer.baselines.ARM_SCAFFOLDS`, which is what the harness reads.
+# `te_bench.baselines.ARM_SCAFFOLDS`, which is what the harness reads.
SCAFFOLD_ARMS = {name: a.scaffold for name, a in ARMS.items() if a.scaffold}
diff --git a/tokeneconomizer/baselines/__init__.py b/experiments/te_bench/baselines/__init__.py
similarity index 92%
rename from tokeneconomizer/baselines/__init__.py
rename to experiments/te_bench/baselines/__init__.py
index a4363fe..2ab4cf0 100644
--- a/tokeneconomizer/baselines/__init__.py
+++ b/experiments/te_bench/baselines/__init__.py
@@ -14,11 +14,10 @@ convention:
whichever harness is driving. No module in this package imports Docker, or subprocess-
invokes it, or imports `te_harness` -- so any harness that can implement those four can
run these baselines, and `tests/test_baselines.py` asserts the import surface.
- * **Nothing imports this package unless it is asked to.** `tokeneconomizer/__init__.py`
- does not, and neither does anything under `mechanisms/`, so `import tokeneconomizer`
- still pulls in nothing heavy and the economizer cannot see a baseline even by accident.
- The one non-stdlib import in the tree is `_repomap_gen.py`, which is a subprocess entry
- point rather than a module and is never imported by anything.
+ * **The core never imports this package.** It lives with the experiments, outside
+ `tokeneconomizer`, so the economizer -- and the plugin built on it -- cannot see a
+ baseline even by accident. The one non-stdlib import the repo-map arm needs is in the
+ core's `repomap_gen.py`, a subprocess entry point that nothing imports.
One scaffold answers three questions, and nothing else:
diff --git a/tokeneconomizer/baselines/arms.py b/experiments/te_bench/baselines/arms.py
similarity index 84%
rename from tokeneconomizer/baselines/arms.py
rename to experiments/te_bench/baselines/arms.py
index 832ceda..5589974 100644
--- a/tokeneconomizer/baselines/arms.py
+++ b/experiments/te_bench/baselines/arms.py
@@ -6,11 +6,11 @@ names which one, and `ARM_SCAFFOLDS` in this package's `__init__` maps arm -> sc
the harness.
The `trimech-rtk` / `trimech-repomap` arms are NOT here. They are `trimech` with a scaffold
-co-activated, so they live beside `trimech` in `mechanisms/arms.py` -- the mechanisms are
+co-activated, so they live beside `trimech` in `mechanism_arms.py` -- the mechanisms are
the subject of those arms and the scaffold is the control, not the other way round.
Nothing here imports a scaffold class: `scaffold=` is a string the harness resolves lazily
-through `tokeneconomizer.baselines.get()`, so importing this module costs nothing.
+through `te_bench.baselines.get()`, so importing this module costs nothing.
"""
from .._armspec import arm, cfg
diff --git a/tokeneconomizer/baselines/base.py b/experiments/te_bench/baselines/base.py
similarity index 100%
rename from tokeneconomizer/baselines/base.py
rename to experiments/te_bench/baselines/base.py
diff --git a/tokeneconomizer/baselines/repomap.py b/experiments/te_bench/baselines/repomap.py
similarity index 96%
rename from tokeneconomizer/baselines/repomap.py
rename to experiments/te_bench/baselines/repomap.py
index f9860fc..76b87a3 100644
--- a/tokeneconomizer/baselines/repomap.py
+++ b/experiments/te_bench/baselines/repomap.py
@@ -28,10 +28,14 @@ import subprocess
import sys
import tarfile
+import tokeneconomizer.plugin
+
from .base import Scaffold, ScaffoldError
DEFAULT_MAP_TOKENS = 2048
-GEN = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_repomap_gen.py")
+# The generator lives in the core package: the plugin's opt-in repository map runs it too.
+GEN = os.path.join(os.path.dirname(os.path.abspath(tokeneconomizer.plugin.__file__)),
+ "repomap_gen.py")
HEADER = ("# Repository map\n"
"Ranked key files and symbols (signatures only) for this repository. Consult "
diff --git a/tokeneconomizer/baselines/rtk.py b/experiments/te_bench/baselines/rtk.py
similarity index 100%
rename from tokeneconomizer/baselines/rtk.py
rename to experiments/te_bench/baselines/rtk.py
diff --git a/tokeneconomizer/baselines/serena.py b/experiments/te_bench/baselines/serena.py
similarity index 100%
rename from tokeneconomizer/baselines/serena.py
rename to experiments/te_bench/baselines/serena.py
diff --git a/tokeneconomizer/mechanisms/codex_spiral.py b/experiments/te_bench/codex_spiral.py
similarity index 100%
rename from tokeneconomizer/mechanisms/codex_spiral.py
rename to experiments/te_bench/codex_spiral.py
diff --git a/tokeneconomizer/facade.py b/experiments/te_bench/facade.py
similarity index 96%
rename from tokeneconomizer/facade.py
rename to experiments/te_bench/facade.py
index c0e1526..d2da243 100644
--- a/tokeneconomizer/facade.py
+++ b/experiments/te_bench/facade.py
@@ -17,12 +17,12 @@ runner is threaded) and calls each mechanism's post-task hook in a fixed order
SwebenchAdapter). `runner` may be an AgentRunner or a bare ``(prompt, model) ->
(text, eff_tokens)`` optimizer callable; it is adapted for the mechanisms automatically.
"""
-from .config import EconomizerConfig
+from tokeneconomizer.config import EconomizerConfig
from .runner import as_optimizer_callable
from .adapters.swebench import SwebenchAdapter
-from .mechanisms.injection import PrefixStage
-from .mechanisms.tooling import ToolingStage
-from .mechanisms.spiral import SpiralStage
+from tokeneconomizer.microskills import PrefixStage
+from tokeneconomizer.toolprune import ToolingStage
+from .spiral_stage import SpiralStage
class Economizer:
diff --git a/tokeneconomizer/mechanisms/arms.py b/experiments/te_bench/mechanism_arms.py
similarity index 97%
rename from tokeneconomizer/mechanisms/arms.py
rename to experiments/te_bench/mechanism_arms.py
index 4d17228..16fcf41 100644
--- a/tokeneconomizer/mechanisms/arms.py
+++ b/experiments/te_bench/mechanism_arms.py
@@ -5,13 +5,13 @@ The `trimech-rtk` / `trimech-repomap` arms live **here, beside `trimech`**, not
co-activated. Filing them under the baselines would make them read as scaffold arms that
happen to have mechanisms, which is backwards — the mechanisms are the subject and the
scaffold is the comparison. They name their scaffold with a string, so this module still
-imports nothing from `tokeneconomizer.baselines`.
+imports nothing from `te_bench.baselines`.
`baselines/arms.py` holds only the arms that are *purely* an external tool with no
mechanism active (`rtk`, `serena`, `repomap`).
"""
-from .._armspec import arm, cfg
-from ..config import InjectionConfig, ToolingConfig, SpiralConfig
+from ._armspec import arm, cfg
+from tokeneconomizer.config import InjectionConfig, ToolingConfig, SpiralConfig
__all__ = ["MECHANISM_ARMS", "INJECT", "ENVFACTS", "ENVFACTS_PLUS", "UNTOOL", "SPIRAL",
"SPIRAL_WEB", "CODEX_UNTOOL", "CODEX_SPIRAL", "CODEX_SPIRAL_POSTGREEN"]
@@ -20,7 +20,7 @@ __all__ = ["MECHANISM_ARMS", "INJECT", "ENVFACTS", "ENVFACTS_PLUS", "UNTOOL", "S
# measured on its own. They are the SAME parameters trimech co-activates -- an arm that
# retuned its mechanism would not be an ablation of trimech, it would be a different arm.
INJECT = dict(enabled=True, propose_every=5) # micro-skill synthesis + injection
-# The LLM-free environment-fact layer alone (mechanisms/envfacts). No paid call, so
+# The LLM-free environment-fact layer alone (microskills/envfacts). No paid call, so
# `needs_optimizer` is False. An ablation of the default below, not the default itself.
ENVFACTS = dict(enabled=True, profile="envfacts")
# THE CODEX INJECTION DEFAULT (2026-09-12): the free layer plus the paid proposer at half
@@ -35,6 +35,10 @@ ENVFACTS = dict(enabled=True, profile="envfacts")
# open-vocabulary proposer is what is left to find repository facts; its spend is charged
# to the arm.
ENVFACTS_PLUS = dict(enabled=True, profile="envfacts+distiller", propose_every=10)
+# The Codex lane's injection profiles by name: the default, and its LLM-free ablation
+# (arm `codex-inject-envfacts`).
+CODEX_DEFAULT_PROFILE = ENVFACTS_PLUS["profile"]
+CODEX_FREE_PROFILE = ENVFACTS["profile"]
# The Codex-native flag sets, split out for exactly the reason the generic ones above are:
# `codex-trimech` co-activates THESE, so each Codex single-mechanism arm is a true ablation
# of it rather than a separately tuned arm.
diff --git a/experiments/te_bench/nudge_guard.py b/experiments/te_bench/nudge_guard.py
new file mode 100644
index 0000000..7cdeefd
--- /dev/null
+++ b/experiments/te_bench/nudge_guard.py
@@ -0,0 +1,195 @@
+"""`NudgeGuard`: the loop guard as the benchmark harness ran it, over a streamed rollout.
+
+The rollout is single-shot (`claude -p`, `copilot -p`), so a redirect cannot be injected into the
+running context. The guard folds each streamed line, STOPS the stream the moment the trajectory
+looks stuck (the container keeps the agent's edits), and the harness re-invokes the agent with
+a continuation prompt: the original task + `RESUME_HEADER` + the redirect. The plugin's
+`tokeneconomizer.loopguard.TurnGuard` is the same control flow, one hook call at a time.
+"""
+from tokeneconomizer.loopguard.rules import DEFAULT_THRESHOLDS, assess_abort, is_stuck, nudge_text
+from tokeneconomizer.loopguard.state import SpiralState, completed_calls
+
+RESUME_HEADER = (
+ "\n\n---\nNOTE: you are RESUMING this same task. The repository at /testbed already "
+ "contains your OWN in-progress edits from your previous attempt (inspect them with "
+ "`git diff`); do not discard that work, build on it. The tests are still not passing.\n")
+
+
+class NudgeGuard:
+ """Live rung-1 controller: run the sealed agent as a sequence of streamed SEGMENTS in
+ ONE container, delivering the leakage-safe NUDGE between segments.
+
+ Why segments: the rollout is single-shot `copilot -p`, so a nudge cannot be injected
+ into the running context. Instead the guard STOPS the current stream the moment the
+ trajectory looks stuck (freezing the container's working tree with the agent's edits
+ intact) and the harness RE-INVOKES the agent with a continuation prompt = original task
+ + RESUME_HEADER + nudge_text(). The agent resumes on top of its own on-disk edits.
+
+ Ladder realized here (compact/restart remain P2): the FIRST stuck detection NUDGES; a
+ subsequent stuck detection (or the cumulative backstop) ABORTS. Each new segment starts
+ with a FRESH per-segment SpiralState, so the post-nudge behavior must independently
+ re-accumulate churn/errors/stagnation past the gate before it can be judged stuck again
+ — that reset IS the nudge's fair grace window (assess_abort's gate needs >=18 turns).
+ A cumulative backstop (turns summed across segments) bounds total cost regardless.
+
+ Usage (harness side):
+ guard = NudgeGuard(envelope=env, judge=spiral_judge, verbose=True)
+ rec, wall = run_agent(..., monitor=guard.monitor,
+ continuation=lambda: guard.continuation(prompt))
+ # then read guard.nudges_done / guard.aborted / guard.events for telemetry.
+ """
+
+ def __init__(self, envelope=None, judge=None, thr=None, nudge_budget=1,
+ verbose=False, nudge_writer=None, resume_header=None):
+ self.envelope = envelope
+ self.judge = judge # raw digest->verdict callable (rate-limited HERE)
+ self.thr = thr or DEFAULT_THRESHOLDS
+ self.nudge_budget = nudge_budget
+ self.verbose = verbose
+ # v6.1: optional LLM-targeted nudge writer (digest -> {"text","_tokens"}). When
+ # set, continuation() uses it to build a TARGETED redirect from the same leakage-
+ # safe digest the judge sees, falling back to the generic nudge_text template on
+ # any empty/failed result. None => the fixed count-template (v4.3 behavior).
+ self.nudge_writer = nudge_writer
+ self.resume_header = resume_header if resume_header is not None else RESUME_HEADER
+ self.nudge_writer_tokens = 0 # REAL token cost of paid nudge-writer calls
+ # per-segment stuck-detection state (reset by continuation() after each nudge)
+ self.st = SpiralState()
+ self.pend = {} # toolCallId -> {name,args} within the segment
+ # cross-segment accounting
+ self.cum_turns = 0 # turns summed over ALL segments (cumulative backstop)
+ self.segment = 0
+ self.nudges_done = 0
+ self.aborted = False # terminal abort fired
+ self.pending_action = None # 'nudge' | 'abort' set when a segment should stop
+ self.events = [] # telemetry: nudge/abort decisions
+ # sampled-judge cadence (mirror run_agent's _sampled_judge: backoff on productive)
+ self._judge_last = -999
+ self._judge_gap = 5
+ self._judge_calls = 0
+ self.judge_tokens = 0 # REAL token cost of all paid judge calls (mechanism
+ # overhead folded into amortized task cost by callers)
+ self._JUDGE_BASE_GAP = 5
+ self._JUDGE_MAX_GAP = 20
+
+ # ---- the paid judge, rate-limited with backoff (keyed on per-segment turns) -------
+ def _sampled_judge(self, digest):
+ if self.judge is None:
+ return None
+ if self.st.turns - self._judge_last < self._judge_gap:
+ return None
+ self._judge_last = self.st.turns
+ self._judge_calls += 1
+ try:
+ v = self.judge(digest)
+ except Exception:
+ v = None
+ if v:
+ self.judge_tokens += v.get("_tokens") or 0
+ if v and v.get("stuck") is False:
+ self._judge_gap = min(self._JUDGE_MAX_GAP, self._judge_gap + self._JUDGE_BASE_GAP)
+ else:
+ self._judge_gap = self._JUDGE_BASE_GAP
+ if self.verbose and v:
+ print(f" [nudge-judge] seg{self.segment} turn {self.st.turns} "
+ f"(call #{self._judge_calls}, next>={self._judge_gap}): "
+ f"stuck={v.get('stuck')} conf={v.get('confidence')} "
+ f"{str(v.get('reason', ''))[:50]}")
+ return v
+
+ # ---- STREAM monitor: fold one JSONL event, return True to STOP this segment -------
+ def monitor(self, line):
+ # completed_calls handles BOTH the Copilot schema (tool.execution_start/complete)
+ # and Claude Code's stream-json (assistant.tool_use / user.tool_result). A single
+ # Claude user message can batch several tool_results, so fold+assess EACH in order
+ # and stop on the first that trips the gate.
+ for name, args, result in completed_calls(line, self.pend):
+ self.st.update(name, args, result)
+ self.cum_turns += 1
+
+ # cumulative hard backstop across segments (per-segment st resets, so
+ # assess_abort's own backstop only sees within-segment turns; this catches a
+ # task that keeps spiraling across a nudge without any single segment exceeding
+ # the envelope). Prefer the learned cap-aware `backstop_turns` (so it stays
+ # reachable under a tight turn cap); else fall back to backstop_mult*envelope.
+ backstop_turns = self.thr.get("backstop_turns")
+ if backstop_turns is None and self.envelope is not None:
+ backstop_turns = self.envelope * self.thr["backstop_mult"]
+ if (backstop_turns is not None
+ and self.cum_turns >= backstop_turns
+ and is_stuck(self.st, self.thr)):
+ return self._stop("abort",
+ f"cum-backstop:{self.cum_turns}>={backstop_turns:.0f}t")
+
+ abort, reason = assess_abort(self.st, envelope=self.envelope,
+ judge=(self._sampled_judge if self.judge else None),
+ thr=self.thr)
+ if not abort:
+ # v6.1 aggressive knob: a judge-AMBIGUOUS trajectory PAST the envelope is
+ # spared from ABORT by assess_abort (resolve-safety), but under this level we
+ # still fire the RESOLVE-SAFE nudge on it (redirect only, never a kill) — this
+ # is what wakes the otherwise-dormant nudge on the middle band of long-running
+ # unresolved tasks. Never escalates to abort here.
+ if (self.thr.get("nudge_on_ambiguous")
+ and reason == "judge-ambiguous-spared"
+ and self.nudges_done < self.nudge_budget):
+ return self._stop("nudge", "ambiguous-past-envelope")
+ continue
+ # stuck: nudge first (while budget remains), else abort.
+ if self.nudges_done < self.nudge_budget:
+ return self._stop("nudge", reason)
+ return self._stop("abort", reason)
+ return False
+
+ def _stop(self, action, reason):
+ self.pending_action = action
+ rec = {"segment": self.segment, "action": action,
+ "turn_in_segment": self.st.turns, "cum_turns": self.cum_turns,
+ "envelope": self.envelope, "reason": reason,
+ "snapshot": self.st.snapshot()}
+ self.events.append(rec)
+ if action == "abort":
+ self.aborted = True
+ if self.verbose:
+ print(f" [nudge-guard] seg{self.segment} {action.upper()} at "
+ f"turn {self.st.turns} (cum {self.cum_turns}) ({reason}) "
+ f"{self.st.snapshot()}")
+ return True
+
+ # ---- nudge body: v6.1 LLM-targeted redirect, else the generic template ------------
+ def _nudge_body(self):
+ """Build the rung-1 nudge text. If an LLM nudge_writer is wired, feed it the SAME
+ leakage-safe recent digest the judge sees and use its targeted redirect; fold the
+ paid cost into nudge_writer_tokens. Fall back to the generic nudge_text template on
+ an absent writer or any empty/failed result (resolve-safe zero-LLM path)."""
+ if self.nudge_writer is not None:
+ try:
+ out = self.nudge_writer(self.st.recent_digest(envelope=self.envelope))
+ except Exception:
+ out = None
+ if out:
+ self.nudge_writer_tokens += out.get("_tokens") or 0
+ txt = (out.get("text") or "").strip()
+ if txt:
+ if self.verbose:
+ print(f" [nudge-writer] seg{self.segment} targeted redirect "
+ f"({len(txt)} chars, +{out.get('_tokens')} tok)")
+ return txt
+ return nudge_text(self.st)
+
+ # ---- CONTINUATION: called after a segment aborts; return next prompt or None ------
+ def continuation(self, base_prompt):
+ """Return the continuation prompt for the next segment, or None to stop for good.
+ Only a 'nudge' stop continues; an 'abort' stop (or a natural end) is terminal."""
+ if self.pending_action != "nudge":
+ return None
+ text = self._nudge_body()
+ self.nudges_done += 1
+ # fresh per-segment state -> the agent gets a fair, independent re-assessment.
+ self.st = SpiralState()
+ self.pend = {}
+ self.pending_action = None
+ self.segment += 1
+ self._judge_last = -999
+ self._judge_gap = self._JUDGE_BASE_GAP
+ return base_prompt + self.resume_header + text
diff --git a/tokeneconomizer/runner.py b/experiments/te_bench/runner.py
similarity index 100%
rename from tokeneconomizer/runner.py
rename to experiments/te_bench/runner.py
diff --git a/tokeneconomizer/mechanisms/spiral.py b/experiments/te_bench/spiral_stage.py
similarity index 95%
rename from tokeneconomizer/mechanisms/spiral.py
rename to experiments/te_bench/spiral_stage.py
index e368254..6992f8b 100644
--- a/tokeneconomizer/mechanisms/spiral.py
+++ b/experiments/te_bench/spiral_stage.py
@@ -25,8 +25,8 @@ envelope unconditionally once the task has run.
"""
import os
-from .base import Stage
-from ..vendor import reflect, spiral
+from tokeneconomizer.loopguard import EnvelopeTracker, llm_nudge_writer, llm_stuck_judge
+from tokeneconomizer.stage import Stage
from . import codex_spiral as cs
_CODEX_AGENTS = ("codex",)
@@ -43,18 +43,18 @@ class SpiralStage(Stage):
self.agent = agent
# ---- generic guard: per-repo envelope + host-side LLM closures ----
- self.envelope = spiral.EnvelopeTracker(
+ self.envelope = EnvelopeTracker(
level=cfg.aggr, frozen_envelope=getattr(cfg, "frozen_envelope", None))
self.spiral_judge = None
self.spiral_nudge_writer = None
if cfg.guard and cfg.judge:
self.spiral_judge = (
lambda digest, _r=runner, _m=optimizer_model:
- reflect.llm_stuck_judge(digest, _r, model=_m))
+ llm_stuck_judge(digest, _r, model=_m))
if cfg.nudge and cfg.nudge_llm:
self.spiral_nudge_writer = (
lambda digest, _r=runner, _m=optimizer_model:
- reflect.llm_nudge_writer(digest, _r, model=_m))
+ llm_nudge_writer(digest, _r, model=_m))
# ---- Codex-native post-green finalize: per-repo threshold tracker ----
self.codex_tracker = None
diff --git a/tokeneconomizer/workloads.py b/experiments/te_bench/workloads.py
similarity index 99%
rename from tokeneconomizer/workloads.py
rename to experiments/te_bench/workloads.py
index ce30f52..7171269 100644
--- a/tokeneconomizer/workloads.py
+++ b/experiments/te_bench/workloads.py
@@ -9,7 +9,7 @@ Stdlib-only and data-only, consistent with the rest of the core package: importi
pulls in no dependencies and touches no filesystem, so it works on a bare clone with no
results tree, no datasets, and no Docker.
- from tokeneconomizer import workloads
+ from te_bench import workloads
workloads.SWEBENCH_INSTANCES['pydata/xarray'] # the 39 xarray instances
workloads.task_counts('swebench') # {'django/django': 40, ...}
@@ -178,7 +178,7 @@ CODEX_SWEBENCH_RUNS: tuple[tuple[str, str], ...] = (
# a $29 lane that retired two projects):
#
# grounding -- the distiller admits a fact only if it can cite >= MIN_CITE=2 confirming
-# task-ids from the agent's own trajectory (mechanisms/injection.py `_admit`), and the
+# task-ids from the agent's own trajectory (microskills/distiller.py `_admit`), and the
# digests it reads are COMMAND-shaped. So a project where the agent barely runs anything
# starves it: every candidate dies as `grounding-fail`. `threejs` was retired for
# exactly this.
diff --git a/experiments/te_harness/__init__.py b/experiments/te_harness/__init__.py
index 14a4f54..b2e1eb3 100644
--- a/experiments/te_harness/__init__.py
+++ b/experiments/te_harness/__init__.py
@@ -1,6 +1,6 @@
"""te_harness — the Layer-2 task-execution harness for TokenEconomizer.
-This is the reference implementation of `tokeneconomizer.runner.AgentRunner`: the Docker- /
+This is the reference implementation of `te_bench.runner.AgentRunner`: the Docker- /
CLI- / credential-heavy machinery that sits BELOW that seam, and the one that produced every
published row. It is the harness the results are reproducible with, not a requirement of the
method -- the economizer above the seam never learns which harness it is talking to.
diff --git a/experiments/te_harness/capture_catalog.py b/experiments/te_harness/capture_catalog.py
index 520b594..64dbcd3 100644
--- a/experiments/te_harness/capture_catalog.py
+++ b/experiments/te_harness/capture_catalog.py
@@ -25,7 +25,7 @@ at all.)
python -m te_harness.capture_catalog
-Env: ANTHROPIC_API_KEY; TE_CATALOG_OUT (default: the repo's vendor/claude_tool_catalog.json),
+Env: ANTHROPIC_API_KEY; TE_CATALOG_OUT (default: the repo's tokeneconomizer/trace/claude_tool_catalog.json),
TE_CATALOG_PORT (default 8770), TE_CATALOG_DESC_CHARS (default 300 -- comfortably above
reflect's max_desc=200 default, keeps the committed file small).
"""
@@ -35,13 +35,13 @@ import subprocess
import sys
import time
-from tokeneconomizer import vendor as _vendor
+from tokeneconomizer import trace as _trace
from .swebench import (_ANTHROPIC_DIRECT, _LIVE_CONTAINERS, _log, _run, claude_bin,
image_for)
-# The vendored catalog the judge reads, inside the shared core:
-# <repo>/tokeneconomizer/vendor/claude_tool_catalog.json.
-DEFAULT_OUT = os.path.join(os.path.dirname(os.path.abspath(_vendor.__file__)),
+# The catalog snapshot the trace reader joins against, inside the core:
+# <repo>/tokeneconomizer/trace/claude_tool_catalog.json.
+DEFAULT_OUT = os.path.join(os.path.dirname(os.path.abspath(_trace.__file__)),
"claude_tool_catalog.json")
CAPTURE_INSTANCE = os.environ.get("TE_CATALOG_INSTANCE", "pydata__xarray-6461")
diff --git a/experiments/te_harness/codex.py b/experiments/te_harness/codex.py
index aaf3073..8b4f8b8 100644
--- a/experiments/te_harness/codex.py
+++ b/experiments/te_harness/codex.py
@@ -18,7 +18,7 @@ plausible rows instead of an error.
fresh input actually fresh; skipping that step prices ~90% cached re-reads at 1.0x and
every cost number downstream is wrong rather than missing. See `row_usage`.
4. **A capability mask, not a tool mask.** Codex has no `--disallowed-tools`. The
- Codex-native untooling mechanism (`tokeneconomizer.mechanisms.codex_untool`) emits
+ Codex-native untooling mechanism (`tokeneconomizer.toolprune.codex`) emits
logical CAPABILITY packages and leaves the mapping onto concrete Codex config toggles
to the runner, because the runner is what owns the request contract. `config_toggles`
is that mapping.
@@ -54,7 +54,7 @@ import time
import urllib.error
import urllib.request
-from tokeneconomizer.vendor import pricing
+from tokeneconomizer import pricing
# What `model_reasoning_effort` accepts. Validated by the runner at construction so a typo
# fails before the run rather than silently falling back to the CLI default -- effort is
diff --git a/experiments/te_harness/copilot.py b/experiments/te_harness/copilot.py
index 780e5de..c8a4265 100644
--- a/experiments/te_harness/copilot.py
+++ b/experiments/te_harness/copilot.py
@@ -37,7 +37,7 @@ import shutil
import subprocess
import tempfile
-from tokeneconomizer.vendor import pricing
+from tokeneconomizer import pricing
# What `copilot --effort` accepts. Validated by the runners at construction so a typo fails
# before the run rather than silently falling back to the CLI default (effort is part of
diff --git a/experiments/te_harness/swebench.py b/experiments/te_harness/swebench.py
index 97c3a1d..40ad304 100644
--- a/experiments/te_harness/swebench.py
+++ b/experiments/te_harness/swebench.py
@@ -64,12 +64,13 @@ import urllib.request
# The economizer package supplies the vendored spiral controller + pricing weights. It is
# stdlib-only, so importing it here pulls in nothing heavy.
from tokeneconomizer import trace
-from tokeneconomizer.vendor import pricing, spiral as spiral_vendor
+from tokeneconomizer import pricing
+from te_bench.nudge_guard import NudgeGuard
-from tokeneconomizer import baselines as scaffolds_pkg
+from te_bench import baselines as scaffolds_pkg
# The Codex-native spiral controller. Layer 1 and stdlib-only, like everything else this
# harness imports from the core -- it reads a transcript line and answers "resume or not".
-from tokeneconomizer.mechanisms import codex_spiral
+from te_bench import codex_spiral
from . import codex, copilot
from .guards import net_guard
@@ -168,11 +169,10 @@ EFFORT_LEVELS = frozenset({"low", "medium", "high", "xhigh", "max"})
def guard_accepts(param):
- """True if the VENDORED `spiral.NudgeGuard` takes `param` on this checkout.
+ """True if `te_bench.nudge_guard.NudgeGuard` takes `param` on this checkout.
- `spiral.NudgeGuard` is vendored into the core package, so its signature moves
- independently of this file: `never_abort` exists in some vendored versions and
- not in others. Passing a parameter it does not accept raises TypeError
+ The guard's signature moves independently of this file: `never_abort` exists in
+ some versions and not in others. Passing a parameter it does not accept raises TypeError
inside `_make_guard`/`run_task` -- i.e. at task 0, before a single row is written --
so every optional guard parameter must be probed rather than assumed. Both domain
runners go through this one helper so the two cannot drift apart again; webbench.py
@@ -180,7 +180,7 @@ def guard_accepts(param):
"""
try:
return param in inspect.signature(
- spiral_vendor.NudgeGuard.__init__).parameters
+ NudgeGuard.__init__).parameters
except (TypeError, ValueError): # not introspectable: assume it does not
return False
@@ -1249,7 +1249,7 @@ class ClaudeSwebenchRunner:
# branches without trimech-safe -- see guard_accepts() for why it is probed.
if guard_accepts("never_abort"):
guard_kwargs["never_abort"] = bool(run_kwargs.get("spiral_never_abort"))
- return spiral_vendor.NudgeGuard(**guard_kwargs)
+ return NudgeGuard(**guard_kwargs)
def _guard_continuation(self, guard, prompt):
"""The next segment's input after a guard stop, or falsey to stop."""
diff --git a/experiments/te_harness/webbench.py b/experiments/te_harness/webbench.py
index 1b26112..89ebca1 100644
--- a/experiments/te_harness/webbench.py
+++ b/experiments/te_harness/webbench.py
@@ -79,12 +79,13 @@ import time
from pathlib import Path
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from tokeneconomizer import baselines as scaffolds_pkg
-from tokeneconomizer.vendor import pricing, spiral as spiral_vendor
+from te_bench import baselines as scaffolds_pkg
+from tokeneconomizer import pricing
+from te_bench.nudge_guard import NudgeGuard
from . import copilot
from . import codex
-from tokeneconomizer.mechanisms import codex_spiral
+from te_bench import codex_spiral
from .guards import net_guard
from .swebench import (EFFORT_LEVELS, PROTECTED_TOOLS, _ANTHROPIC_DIRECT, _log,
@@ -101,7 +102,7 @@ from .swebench import (EFFORT_LEVELS, PROTECTED_TOOLS, _ANTHROPIC_DIRECT, _log,
# rtk -- YES. A static binary plus a PreToolUse hook; it rewrites `ls`/`find`/`grep`
# and compresses their output before it reaches context, which needs neither a
# container nor a language. The agent does issue those commands here.
-# repomap -- NO. Its generator walks `*.py` (baselines/_repomap_gen.py) and a Web-Bench
+# repomap -- NO. Its generator walks `*.py` (tokeneconomizer/plugin/repomap_gen.py) and a Web-Bench
# project is TypeScript/JavaScript, so the map would come back empty.
# serena -- NO. An MCP navigation server over a codebase; Web-Bench hands the agent a
# file set with no installed project, and the projects are 1-140 files.
@@ -1459,7 +1460,7 @@ class WebBenchRunner:
# run on such a branch die with a TypeError at task 0.
if guard_accepts("never_abort"):
guard_kwargs["never_abort"] = bool(run_kwargs.get("spiral_never_abort"))
- return spiral_vendor.NudgeGuard(**guard_kwargs)
+ return NudgeGuard(**guard_kwargs)
def _write_run_config(self, run_dir_path, task, arm, injected, exclude_tools,
max_turns, run_kwargs, sess, project):
diff --git a/experiments/te_harness/webbench_undici_preload.mjs b/experiments/te_harness/webbench_undici_preload.mjs
new file mode 100644
index 0000000..b2d7482
--- /dev/null
+++ b/experiments/te_harness/webbench_undici_preload.mjs
@@ -0,0 +1,27 @@
+// Raise undici's global headersTimeout so a slow agent turn is not destroyed by the
+// evaluator's fetch. No-op unless TE_WEBBENCH_UNDICI_ABORT_MS is set.
+import { createRequire } from 'node:module'
+import { readdirSync, existsSync } from 'node:fs'
+import { join } from 'node:path'
+const ms = Number(process.env.TE_WEBBENCH_UNDICI_ABORT_MS || 0)
+if (ms > 0) {
+ const root = process.env.TE_WEBBENCH_REPO
+ let mod = null
+ try { mod = createRequire(process.cwd() + '/').resolve('undici') } catch {}
+ if (!mod && root) {
+ const store = join(root, 'common', 'temp', 'node_modules', '.pnpm')
+ if (existsSync(store)) {
+ const hit = readdirSync(store).filter(d => d.startsWith('undici@')).sort().pop()
+ if (hit) {
+ const p = join(store, hit, 'node_modules', 'undici', 'index.js')
+ if (existsSync(p)) mod = p
+ }
+ }
+ }
+ if (!mod) { console.error('[te] WARNING: undici not found; evaluator keeps the 300s abort') }
+ else {
+ const { setGlobalDispatcher, Agent } = createRequire(import.meta.url)(mod)
+ setGlobalDispatcher(new Agent({ headersTimeout: ms, bodyTimeout: ms }))
+ console.error(`[te] undici global dispatcher raised: headersTimeout=${ms}ms`)
+ }
+}
diff --git a/tests/test_adapters.py b/experiments/tests/test_adapters.py
similarity index 98%
rename from tests/test_adapters.py
rename to experiments/tests/test_adapters.py
index a88bf13..8b25540 100644
--- a/tests/test_adapters.py
+++ b/experiments/tests/test_adapters.py
@@ -3,7 +3,7 @@ import os
import pytest
-from tokeneconomizer.adapters import (
+from te_bench.adapters import (
DomainAdapter, SwebenchAdapter, WebBenchAdapter, CredDataAdapter,
ReposVulAdapter, CyberGymAdapter, WebArenaAdapter)
diff --git a/experiments/tests/test_baselines.py b/experiments/tests/test_baselines.py
index 42dbc6f..425875f 100644
--- a/experiments/tests/test_baselines.py
+++ b/experiments/tests/test_baselines.py
@@ -4,7 +4,7 @@ Offline — no Docker, no network, no agent. Every container interaction goes th
callables on `ScaffoldContext`, so a fake context is enough to assert what a scaffold
*does*, which is the only way to test this without a task container.
-`tokeneconomizer.baselines` lives in the CORE package, so the first group of tests guards
+`te_bench.baselines` lives in the CORE package, so the first group of tests guards
the two invariants that buys: nothing in it imports Docker or `te_harness` (a baseline can
only reach a container through the context it is handed), and nothing in the core package
imports it on its own (so `import tokeneconomizer` stays stdlib-only and the economizer
@@ -33,9 +33,9 @@ import pytest
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-from tokeneconomizer import baselines as scaffolds
-from tokeneconomizer.baselines import repomap as repomap_mod
-from tokeneconomizer.baselines import rtk as rtk_mod
+from te_bench import baselines as scaffolds
+from te_bench.baselines import repomap as repomap_mod
+from te_bench.baselines import rtk as rtk_mod
CLAUDE = scaffolds.AgentProfile(
@@ -98,9 +98,10 @@ class FakeCtx(scaffolds.ScaffoldContext):
# ---- the package boundary ---------------------------------------------------------------
_PKG_DIR = os.path.dirname(scaffolds.__file__)
-# Non-stdlib at import time is a bug in every module here EXCEPT the repo-map generator,
-# which is a subprocess entry point (never imported) and deliberately does need aider.
-_SUBPROCESS_ENTRY_POINTS = {"_repomap_gen.py"}
+# Non-stdlib at import time is a bug in every module here. The repo-map generator, which
+# deliberately does need aider, is a subprocess entry point that lives in the core package
+# (tokeneconomizer/repomap_gen.py) and is never imported.
+_SUBPROCESS_ENTRY_POINTS = set()
def _module_sources():
@@ -151,7 +152,7 @@ def test_baseline_modules_are_stdlib_only_at_import_time():
def test_the_one_host_dependency_is_deferred_not_top_level():
"""aider must be imported inside preflight, never at module scope -- otherwise
- `import tokeneconomizer.baselines` would require it on every machine."""
+ `import te_bench.baselines` would require it on every machine."""
import ast
src = open(os.path.join(_PKG_DIR, "repomap.py"), encoding="utf-8").read()
top = {a.name for n in ast.parse(src).body if isinstance(n, ast.Import)
@@ -166,7 +167,7 @@ def test_the_core_package_does_not_import_baselines_by_itself():
import subprocess
import sys
probe = ("import sys, tokeneconomizer; "
- "print(any(m.startswith('tokeneconomizer.baselines') for m in sys.modules))")
+ "print(any(m.startswith('te_bench.baselines') for m in sys.modules))")
out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True,
cwd=os.path.dirname(_REPO)) # the repository root holds the core
assert out.stdout.strip() == "False", out.stdout + out.stderr
@@ -175,11 +176,14 @@ def test_the_core_package_does_not_import_baselines_by_itself():
def test_no_mechanism_imports_a_baseline():
"""A mechanism that reached for a baseline would make the comparison circular."""
import ast
- mech_dir = os.path.join(os.path.dirname(_REPO), "tokeneconomizer", "mechanisms")
- for name in sorted(os.listdir(mech_dir)):
- if not name.endswith(".py"):
- continue
- with open(os.path.join(mech_dir, name), encoding="utf-8") as fh:
+ pkg = os.path.join(os.path.dirname(_REPO), "tokeneconomizer")
+ paths = [os.path.join(pkg, sub, name)
+ for sub in ("microskills", "toolprune", "loopguard")
+ for name in sorted(os.listdir(os.path.join(pkg, sub))) if name.endswith(".py")]
+ assert paths
+ for path in paths:
+ name = os.path.relpath(path, pkg)
+ with open(path, encoding="utf-8") as fh:
src = fh.read()
for node in ast.walk(ast.parse(src)):
if isinstance(node, ast.ImportFrom):
diff --git a/experiments/tests/test_codex_routing.py b/experiments/tests/test_codex_routing.py
index 3ee8d4e..fe3fd0a 100644
--- a/experiments/tests/test_codex_routing.py
+++ b/experiments/tests/test_codex_routing.py
@@ -22,7 +22,8 @@ import pytest
from te_harness import codex
from te_harness.guards import net_guard
-from tokeneconomizer.mechanisms import codex_untool, spiral as spiral_mech, tooling
+from te_bench import spiral_stage as spiral_mech
+from tokeneconomizer.toolprune import codex as codex_untool, stage as tooling
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -494,7 +495,7 @@ def test_codex_trimech_names_no_endpoint():
channels (prompt prefix, config.toml, live stream) and each one could have grown an
endpoint assumption; the endpoint is the runner's to resolve.
"""
- from tokeneconomizer.arms import ARMS
+ from te_bench.arms import ARMS
import dataclasses
cfg = ARMS["codex-trimech"].cfg()
flat = repr(dataclasses.asdict(cfg)) if dataclasses.is_dataclass(cfg) else repr(cfg)
diff --git a/experiments/tests/test_codex_webbench.py b/experiments/tests/test_codex_webbench.py
index bc93d16..8d60024 100644
--- a/experiments/tests/test_codex_webbench.py
+++ b/experiments/tests/test_codex_webbench.py
@@ -205,7 +205,7 @@ def test_a_killed_segment_is_flagged_not_counted_as_free(tmp_path):
def test_the_codex_controller_is_selected_not_the_generic_guard(tmp_path):
"""The generic NudgeGuard parses a Claude stream and reprompts; feeding it a
`codex exec --json` stream would arm a guard that can never fire."""
- from tokeneconomizer.mechanisms import codex_spiral
+ from te_bench import codex_spiral
r = _stub(tmp_path)
assert r._make_guard({}) is None
assert r._make_guard({"spiral_guard": True}) is None # generic flags do not arm it
@@ -223,7 +223,7 @@ def test_only_rtk_is_hostable_and_it_is_the_instruction_mode(tmp_path, monkeypat
wb.CodexWebBenchRunner(agent="codex", scaffold=other)
# every Codex ARM that carries an unhostable scaffold is refused the same way -- today
# exactly one, the repomap variant of codex-trimech (its generator walks `*.py`)
- from tokeneconomizer import baselines
+ from te_bench import baselines
unhostable = sorted(a for a, s in baselines.ARM_SCAFFOLDS.items()
if a.startswith("codex-") and s not in wb.WEBBENCH_SCAFFOLDS)
assert unhostable == ["codex-trimech-repomap"], unhostable
diff --git a/tests/test_envfacts_profiles.py b/experiments/tests/test_envfacts_profiles.py
similarity index 80%
rename from tests/test_envfacts_profiles.py
rename to experiments/tests/test_envfacts_profiles.py
index 088b2e7..1cbfef6 100644
--- a/tests/test_envfacts_profiles.py
+++ b/experiments/tests/test_envfacts_profiles.py
@@ -2,11 +2,11 @@
proposer, and the arms that carry each profile."""
import os
-from tokeneconomizer.mechanisms import envfacts as ef
-from tokeneconomizer.mechanisms import codex_injection as ci
-from tokeneconomizer.mechanisms.injection import PrefixStage, ComposedDistiller
+from tokeneconomizer.microskills import envfacts as ef, observe
+from tokeneconomizer.microskills import ComposedDistiller, PrefixStage
+from te_bench import mechanism_arms as ci
from tokeneconomizer.config import InjectionConfig, needs_optimizer
-from tokeneconomizer.adapters.swebench import SwebenchAdapter
+from te_bench.adapters.swebench import SwebenchAdapter
from fixtures import write_codex_transcript
BASE = "/opt/env/base/bin/python"
@@ -31,39 +31,37 @@ def _broken(tmp_path, i):
return p
-# ---- the Codex module is a shim over the shared layer ------------------------------
-def test_codex_module_reexports_the_shared_layer():
- assert ci.EnvFactsDistiller is ef.EnvFactsDistiller
- assert ci.observe_task is ef.observe_task
- assert ci.CODEX_DEFAULT_PROFILE == "envfacts+distiller" # since 2026-09-12
+# ---- the Codex lane's injection profiles ---------------------------------------------
+def test_codex_injection_profiles():
+ assert ci.CODEX_DEFAULT_PROFILE == "envfacts+distiller"
assert ci.CODEX_FREE_PROFILE == "envfacts"
# ---- vocabulary plug-in ----------------------------------------------------------------
def test_node_vocabulary_reads_a_node_repository():
- obs = ef.classify_command("npx jest tests/ --ci", vocab=ef.NODE_WEB)
+ obs = observe.classify_command("npx jest tests/ --ci", vocab=observe.NODE_WEB)
assert [(o.intent, o.form) for o in obs] == [("run_tests", "npx jest")]
- obs = ef.classify_command("node scripts/build.js && npm test", vocab=ef.NODE_WEB)
+ obs = observe.classify_command("node scripts/build.js && npm test", vocab=observe.NODE_WEB)
assert [(o.intent, o.form) for o in obs] == [("run_interpreter", "node"),
("run_tests", "npm test")]
- obs = ef.classify_command("npm install left-pad", vocab=ef.NODE_WEB)
+ obs = observe.classify_command("npm install left-pad", vocab=observe.NODE_WEB)
assert obs[0].intent == "fetch_remote"
# the Python vocabulary does not know jest; the Node one does not know pytest
- assert ef.classify_command("npx jest", vocab=ef.PYTHON_GIT) == [] or \
- ef.classify_command("npx jest", vocab=ef.PYTHON_GIT)[0].intent != "run_tests"
- assert ef.classify_command("pytest -q", vocab=ef.NODE_WEB) == []
- assert ef.error_class("Error: Cannot find module 'left-pad'") == "module_missing"
- assert ef.error_class("connect ECONNREFUSED 127.0.0.1:443") == "connection_refused"
+ assert observe.classify_command("npx jest", vocab=observe.PYTHON_GIT) == [] or \
+ observe.classify_command("npx jest", vocab=observe.PYTHON_GIT)[0].intent != "run_tests"
+ assert observe.classify_command("pytest -q", vocab=observe.NODE_WEB) == []
+ assert observe.error_class("Error: Cannot find module 'left-pad'") == "module_missing"
+ assert observe.error_class("connect ECONNREFUSED 127.0.0.1:443") == "connection_refused"
def test_adapters_supply_a_vocabulary():
assert SwebenchAdapter().env_vocabulary().name == "python-git"
- from tokeneconomizer.adapters.webbench import WebBenchAdapter
+ from te_bench.adapters.webbench import WebBenchAdapter
assert WebBenchAdapter.env_vocabulary(None).name == "node-web"
def test_distiller_records_its_vocabulary(tmp_path):
- d = ef.EnvFactsDistiller("acme/widget", vocab=ef.NODE_WEB)
+ d = ef.EnvFactsDistiller("acme/widget", vocab=observe.NODE_WEB)
d.update(_broken(tmp_path, 0), iid="w-0")
d.save(str(tmp_path))
import json
@@ -127,8 +125,8 @@ def test_codex_arms_carry_the_intended_profiles():
defect; with that fixed it abstains, so `codex-inject` carries the paid proposer and
the LLM-free variant is the named ablation `codex-inject-envfacts`.
"""
- from tokeneconomizer.arms import ARMS, ARM_ORDER
- from tokeneconomizer.mechanisms import codex_injection as ci
+ from te_bench.arms import ARMS, ARM_ORDER
+ from te_bench import mechanism_arms as ci
default = ARMS["codex-inject"].cfg().injection
assert default.profile == ci.CODEX_DEFAULT_PROFILE == "envfacts+distiller"
assert default.paid and default.propose_every == 10
diff --git a/tests/test_facade.py b/experiments/tests/test_facade.py
similarity index 95%
rename from tests/test_facade.py
rename to experiments/tests/test_facade.py
index 4b6aeaf..4ff828d 100644
--- a/tests/test_facade.py
+++ b/experiments/tests/test_facade.py
@@ -1,9 +1,10 @@
"""Facade: the Economizer drives all three mechanisms end-to-end (offline)."""
import os
-from tokeneconomizer import Economizer, EconomizerConfig
+from te_bench.facade import Economizer
+from tokeneconomizer import EconomizerConfig
from tokeneconomizer.config import InjectionConfig, ToolingConfig, SpiralConfig
-from tokeneconomizer.adapters import SwebenchAdapter
+from te_bench.adapters import SwebenchAdapter
from fixtures import write_claude_transcript, write_codex_transcript
@@ -61,7 +62,7 @@ def test_codex_arm_end_to_end(tmp_path):
assert srow["codex_untool_active"] is True
assert srow["codex_spiral_active"] is True
# task 2: web should have been demoted (loaded-and-unused on task 1)
- assert "sealed_web" in econ.build_tools(task, 1)
+ assert "web" in econ.build_tools(task, 1)
def test_codex_trimech_end_to_end(tmp_path):
@@ -73,7 +74,7 @@ def test_codex_trimech_end_to_end(tmp_path):
runner its policy -- on the same task, in one `run_kwargs`, with all three telemetry
families landing on one stream row.
"""
- from tokeneconomizer.arms import ARMS
+ from te_bench.arms import ARMS
calls = []
def runner(prompt, model="agent"):
@@ -123,4 +124,4 @@ def test_codex_trimech_end_to_end(tmp_path):
# the proposer's spend crossed the ledger seam rather than being invisible
assert calls and total == 3.0 * len(calls)
# untooling still learns across tasks with the other two active
- assert "sealed_web" in econ.build_tools(task, 10)
+ assert "web" in econ.build_tools(task, 10)
diff --git a/experiments/tests/test_optimizer_basis.py b/experiments/tests/test_optimizer_basis.py
index c538ca4..449e964 100644
--- a/experiments/tests/test_optimizer_basis.py
+++ b/experiments/tests/test_optimizer_basis.py
@@ -204,7 +204,7 @@ def test_needs_optimizer_agrees_with_the_facade_for_every_arm():
The facade's three conditions are the definition; this asserts the aggregate matches
them arm by arm, so adding an arm cannot silently skip a preflight it needs.
"""
- from tokeneconomizer.arms import ARMS
+ from te_bench.arms import ARMS
from tokeneconomizer.config import needs_optimizer
for name, arm in sorted(ARMS.items()):
cfg = arm.cfg()
@@ -219,7 +219,7 @@ def test_arm_mode_is_not_the_test():
"""Guards the trap that made this non-obvious: `spiral-only` and `untool-only` carry
mode `standalone` and DO make paid calls, so gating on mode would skip their
preflight and hand back exactly the silent-fallback rows it exists to prevent."""
- from tokeneconomizer.arms import ARMS
+ from te_bench.arms import ARMS
from tokeneconomizer.config import needs_optimizer
for name in ("spiral-only", "untool-only"):
assert ARMS[name].mode == "standalone", name
diff --git a/experiments/tests/test_runner_registry.py b/experiments/tests/test_runner_registry.py
index 97d6c53..7b5bafd 100644
--- a/experiments/tests/test_runner_registry.py
+++ b/experiments/tests/test_runner_registry.py
@@ -152,5 +152,5 @@ def test_an_unregistered_label_is_refused_not_mapped(label, monkeypatch):
def test_the_webbench_adapter_carries_a_node_vocabulary():
"""The core's Web-Bench adapter describes a Node project, whichever agent runs it."""
- from tokeneconomizer.adapters.webbench import WebBenchAdapter
+ from te_bench.adapters.webbench import WebBenchAdapter
assert WebBenchAdapter.env_vocabulary(None).name == "node-web"
diff --git a/experiments/tests/test_spiral.py b/experiments/tests/test_spiral.py
index 2e26e69..abef81e 100644
--- a/experiments/tests/test_spiral.py
+++ b/experiments/tests/test_spiral.py
@@ -1,6 +1,6 @@
"""Spiral: generic envelope guard + Codex-native post-green policy."""
-from tokeneconomizer.mechanisms.spiral import SpiralStage
-from tokeneconomizer.mechanisms import codex_spiral as cs
+from te_bench.spiral_stage import SpiralStage
+from te_bench import codex_spiral as cs
from tokeneconomizer.config import SpiralConfig
@@ -62,7 +62,7 @@ def test_codex_spiral_after_task_telemetry(tmp_path):
# fires.
# ---------------------------------------------------------------------------------------
import json as _json
-from tokeneconomizer.mechanisms import codex_spiral as _cs
+from te_bench import codex_spiral as _cs
_PATCH_CMD = ("/bin/bash -lc \"apply_patch <<'PATCH'\n*** Begin Patch\n*** Update File: "
"django/core/validators.py\n@@\n-old\n+new\n*** End Patch\nPATCH\n\n"
@@ -109,7 +109,7 @@ def test_shipped_policy_can_fire_on_a_shell_patched_trajectory():
def test_trajectory_seam_surfaces_shell_patches_as_apply_patch_calls(tmp_path):
from tokeneconomizer import trace
- from tokeneconomizer.mechanisms.injection import edited_pyfiles
+ from tokeneconomizer.microskills.lifecycle import edited_pyfiles
p = tmp_path / "t.jsonl"
p.write_text("\n".join([
_line({"type": "command_execution", "command": _PATCH_CMD, "aggregated_output": "Success. Updated", "exit_code": 0}),
@@ -182,7 +182,7 @@ def test_defensive_guard_spends_its_budget_on_distinct_reasons_only():
def test_defensive_profile_is_selectable_and_unpaid(tmp_path):
- from tokeneconomizer.arms import ARMS, ARM_ORDER
+ from te_bench.arms import ARMS, ARM_ORDER
from tokeneconomizer.config import needs_optimizer, SpiralConfig
c = ARMS["codex-spiral-defensive"].cfg()
assert c.spiral.codex_spiral and c.spiral.codex_spiral_profile == "defensive"
@@ -194,7 +194,7 @@ def test_defensive_profile_is_selectable_and_unpaid(tmp_path):
import pytest
with pytest.raises(ValueError):
SpiralConfig(codex_spiral=True, codex_spiral_profile="bogus")
- from tokeneconomizer.mechanisms.spiral import SpiralStage
+ from te_bench.spiral_stage import SpiralStage
stage = SpiralStage(c.spiral, max_turns=80, agent="codex")
pol = stage.run_kwargs({"instance_id": "x"})["codex_spiral_policy"]
assert pol.reverify_loop_enabled and pol.runaway_enabled and pol.nudge_budget == 2
@@ -213,7 +213,7 @@ def test_both_guards_expose_everything_the_shared_task_loop_reads():
"""
import inspect, re
from te_harness import swebench as sw
- from tokeneconomizer.vendor import spiral as generic
+ from te_bench import nudge_guard as generic
src = inspect.getsource(sw.ClaudeSwebenchRunner.run_task)
names = set(re.findall(r"(?<![\w.])guard\.([a-z_][a-z0-9_]*)", src))
@@ -243,7 +243,7 @@ def test_the_codex_envelope_is_advanced_in_the_unit_its_trigger_compares(tmp_pat
could not fire.
"""
from tokeneconomizer.config import SpiralConfig
- from tokeneconomizer.mechanisms.spiral import SpiralStage
+ from te_bench.spiral_stage import SpiralStage
cfg = SpiralConfig(codex_spiral=True, codex_spiral_profile="defensive")
stage = SpiralStage(cfg, max_turns=80, agent="codex")
srow = {}
@@ -282,3 +282,16 @@ def test_the_resume_invocation_is_one_the_installed_cli_accepts():
assert "[SESSION_ID]" in text # the positional this argv relies on
for flag in [a for a in argv if a.startswith("--")]:
assert flag in text, f"`codex exec resume` does not accept {flag}"
+
+
+def test_the_codex_verification_detector_sees_through_rtks_command_prefix():
+ """`codex-trimech-rtk` runs the spiral on an agent told to type `rtk pytest`: the
+ verification detector must read the prefixed command as it reads the bare one."""
+ for bare in ("python -m pytest tests/ -q", "pytest -q", "bin/test sympy/x.py",
+ "K=1 pytest -q", "pip install foo", "git status"):
+ for pre in ("rtk ", "rtk proxy ", "rtk K=2 "):
+ assert cs.is_verification_command(pre + bare) == cs.is_verification_command(bare)
+ # a compound command keeps its second segment visible too
+ assert cs.is_verification_command("cd x && rtk pytest -q")
+ assert cs.is_verification_command("rtk pytest -q")
+ assert not cs.is_verification_command("rtk git status")
diff --git a/experiments/tests/test_sweep_arms.py b/experiments/tests/test_sweep_arms.py
index 7c9e372..6cddfea 100644
--- a/experiments/tests/test_sweep_arms.py
+++ b/experiments/tests/test_sweep_arms.py
@@ -13,7 +13,7 @@ Guarded specifically:
level is invisible in an EconomizerConfig and a mislabelled cell would be undetectable
after the fact;
* every arm the sweep plan names is registered, and the scaffold arms agree with
- tokeneconomizer/baselines' own arm->scaffold map -- an arm that named a scaffold the harness
+ experiments/te_bench/baselines' own arm->scaffold map -- an arm that named a scaffold the harness
does not have, or carried none where the harness expects one, would run NATIVE and file
the rows under the scaffold's name.
"""
@@ -170,14 +170,14 @@ def test_webbench_scaffold_arms_agree_with_the_harness():
def test_scaffold_arms_agree_with_the_harness_map():
- """The arm registry and tokeneconomizer/baselines must name the same pairs. Two places
+ """The arm registry and experiments/te_bench/baselines must name the same pairs. Two places
map an arm to a scaffold, and a disagreement runs native under a scaffold's name."""
- from tokeneconomizer import baselines as scaffolds
+ from te_bench import baselines as scaffolds
assert RX.SCAFFOLD_ARMS == scaffolds.ARM_SCAFFOLDS
def test_every_scaffold_arm_names_a_real_scaffold():
- from tokeneconomizer import baselines as scaffolds
+ from te_bench import baselines as scaffolds
for arm, name in RX.SCAFFOLD_ARMS.items():
assert name in scaffolds.SCAFFOLDS, f"{arm} -> {name}"
assert scaffolds.for_arm(arm).name == name
@@ -270,7 +270,7 @@ def test_group_sizes_exclude_what_a_new_run_must_skip():
"""The exclusion and extension tables are both forward-looking: an excluded id must not
be counted, an added one must be, and task_counts() must still report the historical
size either way."""
- from tokeneconomizer import workloads
+ from te_bench import workloads
sizes = SP.group_sizes("swebench")
for iid in workloads.SWEBENCH_EXCLUDED:
group = next(g for g, ids in workloads.SWEBENCH_INSTANCES.items() if iid in ids)
@@ -372,7 +372,7 @@ def test_the_codex_spiral_arms_have_the_shape_the_injection_arms_have():
# the generic guard stays off on all of them: the Codex controller is what runs
for n in ("codex-spiral", "codex-spiral-postgreen", "codex-spiral-defensive"):
assert S(n).codex_spiral and not S(n).guard and not S(n).nudge
- from tokeneconomizer.mechanisms import codex_spiral as cs
+ from te_bench import codex_spiral as cs
assert cs.CODEX_DEFAULT_PROFILE == "defensive"
assert cs.CODEX_SHIPPED_PROFILE == "post-green"
@@ -403,7 +403,7 @@ def test_the_codex_family_relates_to_codex_trimech_as_the_generic_one_does_to_tr
for name in (tri, inj, unt, spi):
assert not RX.ARMS[name].scaffold and not (RX.ARMS[name].env or {}), name
# 4. the three appear before trimech in the canonical order
- from tokeneconomizer.arms import ARM_ORDER
+ from te_bench.arms import ARM_ORDER
assert max(ARM_ORDER.index(n) for n in (inj, unt, spi)) < ARM_ORDER.index(tri)
@@ -550,7 +550,7 @@ def test_the_harness_scaffold_table_names_every_arm_that_carries_each_scaffold()
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 tokeneconomizer import baselines
+ from te_bench import baselines
text = _doc("HARNESS.md")
table = text[text.index("| Scaffold | Arms |"):]
table = table[:table.index("\n\n")]
@@ -577,7 +577,7 @@ def test_the_published_spiral_arm_is_the_defensive_profile():
ruled out on 2026-09-12. The superseded post-green rule keeps a registry name but is not
what the plain one runs.
"""
- from tokeneconomizer.mechanisms import codex_spiral as cs
+ from te_bench import codex_spiral as cs
sp = RX.ARMS["codex-spiral"].cfg().spiral
assert sp.codex_spiral_profile == "defensive" == cs.CODEX_DEFAULT_PROFILE
assert cs.profile_version("defensive") == "codex-native-spiral-defensive-v1"
@@ -590,7 +590,7 @@ def test_the_published_spiral_arm_is_the_defensive_profile():
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."""
- from tokeneconomizer import workloads
+ 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"
@@ -605,7 +605,7 @@ def test_codex_trimech_rtk_is_codex_trimech_with_the_scaffold_and_nothing_else()
a, b = RX.ARMS["codex-trimech-rtk"], RX.ARMS["codex-trimech"]
assert a.cfg() == b.cfg() and a.mode == b.mode == "manual4"
assert a.scaffold == "rtk" and b.scaffold is None
- from tokeneconomizer import baselines
+ from te_bench import baselines
assert baselines.ARM_SCAFFOLDS["codex-trimech-rtk"] == "rtk"
assert RX.SCAFFOLD_ARMS["codex-trimech-rtk"] == "rtk"
# and the plain scaffold arm is agent-agnostic: no mechanism, just the scaffold
@@ -619,7 +619,7 @@ def test_codex_trimech_repomap_is_codex_trimech_with_the_scaffold_and_nothing_el
a, b = RX.ARMS["codex-trimech-repomap"], RX.ARMS["codex-trimech"]
assert a.cfg() == b.cfg() and a.mode == b.mode == "manual4"
assert a.scaffold == "repomap" and b.scaffold is None
- from tokeneconomizer import baselines
+ from te_bench import baselines
assert baselines.ARM_SCAFFOLDS["codex-trimech-repomap"] == "repomap"
assert RX.SCAFFOLD_ARMS["codex-trimech-repomap"] == "repomap"
r = RX.ARMS["repomap"]
@@ -632,10 +632,24 @@ def test_every_generic_trimech_scaffold_arm_has_exactly_one_codex_sibling():
generic lane refuses `trimech-serena`, so a `codex-trimech-serena` would be a Codex-only
combination with no generic twin to compare against. `-web` is Web-Bench's spiral
tuning of the same scaffold arm, not a scaffold of its own."""
- from tokeneconomizer import baselines
+ from te_bench import baselines
generic = {a[len("trimech-"):]: s for a, s in baselines.ARM_SCAFFOLDS.items()
if a.startswith("trimech-") and not a.endswith("-web")}
codex = {a[len("codex-trimech-"):]: s for a, s in baselines.ARM_SCAFFOLDS.items()
if a.startswith("codex-trimech-")}
assert generic == codex == {"rtk": "rtk", "repomap": "repomap"}
+
+def test_the_llm_free_arm_is_registered_and_makes_no_paid_call():
+ """`codex-inject-envfacts` is the LLM-free ablation: the layer `codex_injection` implements,
+ with no proposer. (The DEFAULT Codex injection arm has carried the paid proposer on top
+ since 2026-09-12 -- see test_envfacts_profiles.py.)"""
+ from te_bench.arms import ARMS
+ from tokeneconomizer.config import EconomizerConfig, InjectionConfig, needs_optimizer
+ cfg = ARMS["codex-inject-envfacts"].cfg()
+ assert cfg.injection.enabled and cfg.injection.profile == "envfacts"
+ assert cfg.injection.paid is False
+ assert needs_optimizer(cfg) is False
+ assert ARMS["codex-inject-envfacts"].mode == "manual4"
+ assert ARMS["codex-inject-untool"].cfg().tooling.codex_untool is True
+ assert needs_optimizer(EconomizerConfig(injection=InjectionConfig(enabled=True))) is True
diff --git a/experiments/tests/test_tooling.py b/experiments/tests/test_tooling.py
index 55486cb..b320013 100644
--- a/experiments/tests/test_tooling.py
+++ b/experiments/tests/test_tooling.py
@@ -1,10 +1,10 @@
"""Tooling: generic evidence untooling + Codex-native capability untooling."""
import os
-from tokeneconomizer.mechanisms.tooling import ToolingStage
-from tokeneconomizer.mechanisms import codex_untool as cu
+from tokeneconomizer.toolprune import ToolingStage
+from tokeneconomizer.toolprune import codex as cu
from tokeneconomizer.config import ToolingConfig
-from tokeneconomizer.adapters import SwebenchAdapter
+from te_bench.adapters import SwebenchAdapter
from fixtures import write_codex_transcript
@@ -36,7 +36,7 @@ def test_codex_profile_demotes_unused_web(tmp_path):
p.observe({"attempted": {}, "completed": {}, "failed": {}}, resolved=True)
sel2 = p.begin_task("x-2")
# web needs only 1 unused exposure; it should now be in the pruned relay mask.
- assert "sealed_web" in sel2["relay_capabilities"]
+ assert "web" in sel2["relay_capabilities"]
def test_codex_profile_completed_use_protects(tmp_path):
@@ -47,7 +47,7 @@ def test_codex_profile_completed_use_protects(tmp_path):
resolved=True)
assert "web" in p.state["ever_completed"]
sel2 = p.begin_task("x-2")
- assert "sealed_web" not in sel2["relay_capabilities"]
+ assert "web" not in sel2["relay_capabilities"]
def test_inspect_usage_counts_web(tmp_path):
@@ -109,7 +109,7 @@ def test_evidence_untool_drops_after_streak(tmp_path):
# ---- the mask must be EARNED, never a prior ---------------------------------
# The stored Web-Bench arms were produced by an older `--untool` flag that applied
-# `reflect.untool_exclusions()` -- the static INAPPLICABLE_TOOLS set -- from the FIRST
+# `untool_exclusions()` -- the static INAPPLICABLE_TOOLS set -- from the FIRST
# rollout of the stream. Measured consequences: the mask was live at the `init` task before
# any task had completed, it cost zero LLM tokens so the honest ledger charged nothing for
# it, and the keep-set was byte-identical across all 15 cells (5 projects x 3 seeds). The
@@ -120,8 +120,8 @@ def test_evidence_untool_drops_after_streak(tmp_path):
# no longer reachable from the stage. These tests pin that shut, in BOTH domains, so it
# cannot regress silently -- the failure mode is invisible in aggregate numbers and only
# shows up as a suspiciously large cost win.
-from tokeneconomizer.adapters import WebBenchAdapter # noqa: E402
-from tokeneconomizer.vendor import reflect # noqa: E402
+from te_bench.adapters import WebBenchAdapter # noqa: E402
+from tokeneconomizer.toolprune import tools as reflect # noqa: E402
from fixtures import write_claude_transcript_with_catalog # noqa: E402
_CATALOG = ["Bash", "Edit", "Read", "Write", "WebFetch", "WebSearch", "Workflow",
@@ -221,7 +221,7 @@ def test_network_block_is_liftable_but_only_explicitly(monkeypatch):
def test_network_tools_are_not_protected():
"""PROTECTED_TOOLS survive every mask, so a network tool must never be listed there."""
- from tokeneconomizer.vendor import reflect
+ from tokeneconomizer.toolprune import tools as reflect
assert not ({"WebSearch", "WebFetch"} & set(reflect.PROTECTED_TOOLS))
diff --git a/experiments/tests/test_usage_recovery.py b/experiments/tests/test_usage_recovery.py
index c91ff68..c7e8bb3 100644
--- a/experiments/tests/test_usage_recovery.py
+++ b/experiments/tests/test_usage_recovery.py
@@ -126,7 +126,7 @@ def test_guard_accepts_probes_the_vendored_signature():
"""`never_abort` exists in some vendored versions of the guard and not in others.
webbench.py passed it unconditionally, which killed every guarded Web-Bench run at
task 0 before a row was written. Both runners now go through this one probe."""
- from tokeneconomizer.vendor import spiral as spiral_vendor
+ from te_bench import nudge_guard as spiral_vendor
from te_harness.swebench import guard_accepts
assert guard_accepts("envelope") is True
assert guard_accepts("no_such_parameter_exists") is False
diff --git a/experiments/tests/test_workloads.py b/experiments/tests/test_workloads.py
index e4c79ac..9c00d05 100644
--- a/experiments/tests/test_workloads.py
+++ b/experiments/tests/test_workloads.py
@@ -8,7 +8,7 @@ import importlib.util
import json
import os
-from tokeneconomizer import workloads
+from te_bench import workloads
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_EXPORTER = os.path.join(_REPO, "scripts", "export_workloads.py")
diff --git a/experiments/workloads/README.md b/experiments/workloads/README.md
index 2ee0bfd..54d7010 100644
--- a/experiments/workloads/README.md
+++ b/experiments/workloads/README.md
@@ -43,7 +43,7 @@ SWE-bench_Verified and must come from the full `princeton-nlp/SWE-bench` test sp
## Regenerating
-`tokeneconomizer/workloads.py` is the authority; these files are generated from it:
+`experiments/te_bench/workloads.py` is the authority; these files are generated from it:
```bash
python scripts/export_workloads.py # rewrite
diff --git a/experiments/workloads/creddata.json b/experiments/workloads/creddata.json
index feae27a..a13aca5 100644
--- a/experiments/workloads/creddata.json
+++ b/experiments/workloads/creddata.json
@@ -1,7 +1,7 @@
{
"domain": "creddata",
"description": "CredData repositories audited for secrets, graded to line-level F1.",
- "source": "tokeneconomizer/workloads.py (regenerate: python scripts/export_workloads.py)",
+ "source": "experiments/te_bench/workloads.py (regenerate: python scripts/export_workloads.py)",
"group_field": "instance",
"seeds": [
0,
diff --git a/experiments/workloads/reposvul.json b/experiments/workloads/reposvul.json
index 1523b59..1cf1cb7 100644
--- a/experiments/workloads/reposvul.json
+++ b/experiments/workloads/reposvul.json
@@ -1,7 +1,7 @@
{
"domain": "reposvul",
"description": "ReposVul instances (Python split) audited for vulnerabilities, graded to F1.",
- "source": "tokeneconomizer/workloads.py (regenerate: python scripts/export_workloads.py)",
+ "source": "experiments/te_bench/workloads.py (regenerate: python scripts/export_workloads.py)",
"group_field": "instance",
"seeds": [
0,
diff --git a/experiments/workloads/swebench.json b/experiments/workloads/swebench.json
index 2086dbc..e3b0a67 100644
--- a/experiments/workloads/swebench.json
+++ b/experiments/workloads/swebench.json
@@ -1,7 +1,7 @@
{
"domain": "swebench",
"description": "SWE-bench task streams for the Claude/Copilot trimech A/B and the Codex arms.",
- "source": "tokeneconomizer/workloads.py (regenerate: python scripts/export_workloads.py)",
+ "source": "experiments/te_bench/workloads.py (regenerate: python scripts/export_workloads.py)",
"group_field": "repo",
"seeds": [
0,
@@ -398,5 +398,5 @@
"pydata__xarray-7400",
"pydata__xarray-7444"
],
- "notes": "These ids are NOT all in SWE-bench_Verified: 'full_split_only' lists the instances that exist only in the full princeton-nlp/SWE-bench test split. Docker image tag: swebench/sweb.eval.x86_64.<id with __ -> _1776_>:latest. 'excluded' lists ids dropped from THIS run list with the reason; they are still part of the recorded workload in tokeneconomizer/workloads.py (SWEBENCH_INSTANCES) and were run by the published results, so a cell that skips them is not directly comparable to one that did not. 'added' lists ids that EXTEND a stream beyond the published workload to de-saturate it (scikit-learn and sympy, to 60 runnable tasks each); they are all outside SWE-bench_Verified, so provision them from the full test split, and results on an extended stream are not comparable to the published ones for that repo."
+ "notes": "These ids are NOT all in SWE-bench_Verified: 'full_split_only' lists the instances that exist only in the full princeton-nlp/SWE-bench test split. Docker image tag: swebench/sweb.eval.x86_64.<id with __ -> _1776_>:latest. 'excluded' lists ids dropped from THIS run list with the reason; they are still part of the recorded workload in experiments/te_bench/workloads.py (SWEBENCH_INSTANCES) and were run by the published results, so a cell that skips them is not directly comparable to one that did not. 'added' lists ids that EXTEND a stream beyond the published workload to de-saturate it (scikit-learn and sympy, to 60 runnable tasks each); they are all outside SWE-bench_Verified, so provision them from the full test split, and results on an extended stream are not comparable to the published ones for that repo."
}
diff --git a/experiments/workloads/webbench.json b/experiments/workloads/webbench.json
index 078d713..fe6b170 100644
--- a/experiments/workloads/webbench.json
+++ b/experiments/workloads/webbench.json
@@ -1,7 +1,7 @@
{
"domain": "webbench",
"description": "Web-Bench streams; task order is load-bearing (each task builds on the last).",
- "source": "tokeneconomizer/workloads.py (regenerate: python scripts/export_workloads.py)",
+ "source": "experiments/te_bench/workloads.py (regenerate: python scripts/export_workloads.py)",
"group_field": "project",
"seeds": [
"A",
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..04539b4
--- /dev/null
+++ b/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "tokeneconomizer",
+ "version": "0.1.0",
+ "private": true,
+ "description": "TokenEconomizer for Pi: micro-skills (short repository facts learned from earlier sessions) injected at session start, and a guard that redirects a turn stuck in a failing loop.",
+ "keywords": [
+ "pi-package",
+ "cost",
+ "tokens",
+ "context"
+ ],
+ "license": "MIT",
+ "repository": "https://github.com/microsoft/TokenEconomizer",
+ "pi": {
+ "extensions": [
+ "./plugin/pi/tokeneconomizer.ts"
+ ]
+ },
+ "peerDependencies": {
+ "@earendil-works/pi-coding-agent": "*"
+ }
+}
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index cd40162..c29a950 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -2,9 +2,19 @@
"name": "tokeneconomizer",
"displayName": "TokenEconomizer",
"version": "0.1.0",
- "description": "Cuts a coding agent's token bill from outside the agent: learned per-repo facts injected at session start, unused-tool deny lists you approve, and a guard that redirects a turn stuck in a failing loop.",
- "author": {"name": "TokenEconomizer authors"},
+ "description": "Experience-driven black-box cost control for coding agents: micro-skills (short repository facts learned from earlier sessions) injected at session start, tool pruning through a deny list of unused tools you approve, and a guard that redirects a turn stuck in a failing loop.",
+ "author": {
+ "name": "TokenEconomizer authors"
+ },
"repository": "https://github.com/microsoft/TokenEconomizer",
"license": "MIT",
- "keywords": ["cost", "tokens", "context", "hooks", "untooling", "spiral"]
+ "keywords": [
+ "cost",
+ "tokens",
+ "context",
+ "hooks",
+ "micro-skills",
+ "tool-pruning",
+ "failure-loops"
+ ]
}
diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json
index b5961fa..006a473 100644
--- a/plugin/.codex-plugin/plugin.json
+++ b/plugin/.codex-plugin/plugin.json
@@ -1,10 +1,21 @@
{
"name": "tokeneconomizer",
"version": "0.1.0",
- "description": "Cuts a coding agent's token bill from outside the agent: learned per-repo facts injected at session start, an unused-capability deny list you approve (written to the project's .codex/config.toml), and a guard that redirects a turn stuck in a failing loop.",
- "author": {"name": "TokenEconomizer authors"},
+ "description": "Experience-driven black-box cost control for coding agents: micro-skills (short repository facts learned from earlier sessions) injected at session start, tool pruning through a deny list of unused capabilities you approve (written to the project's .codex/config.toml), and a guard that redirects a turn stuck in a failing loop.",
+ "author": {
+ "name": "TokenEconomizer authors"
+ },
"repository": "https://github.com/microsoft/TokenEconomizer",
"license": "MIT",
- "keywords": ["cost", "tokens", "context", "hooks"],
- "hooks": "./hooks/codex-hooks.json"
+ "keywords": [
+ "cost",
+ "tokens",
+ "context",
+ "hooks",
+ "micro-skills",
+ "tool-pruning",
+ "failure-loops"
+ ],
+ "hooks": "./hooks/codex-hooks.json",
+ "skills": "./codex-skills"
}
diff --git a/plugin/.github/plugin/plugin.json b/plugin/.github/plugin/plugin.json
index c61c575..c67c1b6 100644
--- a/plugin/.github/plugin/plugin.json
+++ b/plugin/.github/plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "tokeneconomizer",
"version": "0.1.0",
- "description": "Cuts a coding agent's token bill from outside the agent: learned per-repo facts injected at session start, an unused-MCP-server deny list you approve, and a guard that redirects a turn stuck in a failing loop.",
+ "description": "Experience-driven black-box cost control for coding agents: micro-skills (short repository facts learned from earlier sessions) injected at session start, tool pruning through a deny list of unused MCP servers you approve, and a guard that redirects a turn stuck in a failing loop.",
"author": {
"name": "TokenEconomizer authors"
},
@@ -12,8 +12,9 @@
"tokens",
"context",
"hooks",
- "untooling",
- "spiral"
+ "micro-skills",
+ "tool-pruning",
+ "failure-loops"
],
"hooks": "hooks/copilot-hooks.json"
}
diff --git a/plugin/README.md b/plugin/README.md
index ca9889b..82cb145 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,40 +1,52 @@
# TokenEconomizer plugin
-Runtime cost control for coding agents, from outside the agent. In each repository it works
-in, it:
+Experience-driven black-box cost control for coding agents. In each repository it works in, it:
-* **proposes removing tools you never use.** Tools that stay loaded but unused for several
+* **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, such as the built-in GitHub server.
-* **injects what it learned.** 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.
-* **redirects a turn stuck in a failing loop.** 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 action is announced in one line, every hook fails open, and by default the plugin makes no
-model calls of its own. All of its state stays on your machine, under `~/.tokeneconomizer`.
+ 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).
+- [Before you start](#before-you-start)
+- Install and use it on [Claude Code](#claude-code) · [Codex](#codex) ·
+ [Copilot CLI](#copilot-cli) · [Pi](#pi)
+- [What to expect](#what-to-expect) · [Commands](#commands) · [Settings](#settings)
+- [Repository map](#repository-map) · [Using with rtk](#using-with-rtk) ·
+ [Model calls and API keys](#model-calls-and-api-keys) · [Troubleshooting](#troubleshooting)
+
## Before you start
-- [ ] Claude Code installed (Codex, the Copilot CLI and Pi: see [below](#codex-copilot-and-pi))
+- [ ] Your agent installed and signed in, any way it supports (a subscription or an API key)
- [ ] Python 3.10 or newer on `PATH` (or set `TE_PYTHON=/path/to/python3.10+`)
- [ ] Access to this repository on GitHub
+- [ ] Copilot CLI only: the repository's folder trusted by Copilot (it asks the first time you
+ start it there); Copilot ignores a folder's `.github/copilot` settings otherwise
-No extra API key is needed. See [Model calls and API keys](#model-calls-and-api-keys).
-
-## Steps (Claude Code)
-
-**1. Get the plugin.** In a terminal:
+No extra API key is needed. Plugins load when a session starts, so start a new session after
+installing. Claude Code, Codex and the Copilot CLI install from a clone of this repository:
```bash
git clone https://github.com/microsoft/TokenEconomizer.git
```
-**2. Install it.** In a terminal, using the path of the clone from step 1:
+Keep the clone where it is: the installed plugin runs from it.
+
+> **Where commands go.** Lines starting with `/` (`/plugin …`, `/tokeneconomizer:…`, `/te …`)
+> are typed into **the agent's prompt**, not your shell. Shell commands are in `bash` blocks.
+
+## Claude Code
+
+**1. Install.**
```bash
claude plugin marketplace add /path/to/TokenEconomizer
@@ -43,226 +55,105 @@ claude plugin list # should show tokeneconomizer@tokeneconomizer ... enab
```
(Inside Claude Code the same thing is `/plugin marketplace add …` and `/plugin install …`.)
-Plugins load when a session starts, so sessions already open won't have it; start a new one.
-> **Where commands go.** Lines starting with `/` (`/plugin …`, `/tokeneconomizer:…`) are typed
-> into **Claude Code's prompt**, not your shell. Shell commands are in `bash` blocks.
+**2. Check it.** Start Claude Code in any project (`cd my-project && claude`) and type
+`/tokeneconomizer:status`. It should print a short status block, not an error. Claude Code may ask
+permission to run the plugin's script; allow it always.
-**3. Check it.** Start Claude Code in any project (`cd my-project && claude`) and type:
+**3. Record the tool list, once.**
```text
-/tokeneconomizer:status
+/tokeneconomizer:toolprune refresh-catalog
```
-It should print a short status block for the project, not an error. The first time, Claude Code
-asks permission to run the plugin's script; choose to always allow it.
+This records which tools a Claude Code session loads, with no model call. Do it once on this
+machine, and again after Claude Code updates. **Don't skip it:** without it the deny list sees
+only the few tools Claude Code defers, not the ones every session loads.
-**4. Set up each repository, once.** In Claude Code, in the repository:
+**4. Work normally.** See [What to expect](#what-to-expect). When the deny list is ready, a
+session start says so; then:
```text
-/tokeneconomizer:untool refresh-catalog
+/tokeneconomizer:toolprune # the proposed tools and the evidence
+/tokeneconomizer:toolprune apply # accept them, from your next session
```
-This records which tools a session loads (no model call). **Don't skip it.** Without it the deny
-list can only see the few tools Claude Code defers, not the ones every session loads.
-
-Optional: `/tokeneconomizer:replay` estimates what the plugin would do on your past sessions in
-this repository, with no model calls.
-
-**5. Work normally.** You don't need to do anything. Across sessions the plugin learns which tools
-this repository uses, learns environment facts, and prices each session after it ends.
+The rules go into this repository's `.claude/settings.local.json`, which the plugin keeps out of
+git, and it never touches deny rules you wrote. `/tokeneconomizer:toolprune restore` undoes it.
-**6. Accept the deny list (after about five sessions).** When a session starts you'll see a
-notice like *"TokenEconomizer: N tool(s) went unused in this repository's recent sessions…"*.
-Then:
+Each slash command is one model turn. The same commands are free from a terminal, as
+`~/.tokeneconomizer/bin/te <command>` run inside the repository ([Commands](#commands)). For one
+session without installing anything: `claude --plugin-dir /path/to/TokenEconomizer/plugin`.
-```text
-/tokeneconomizer:untool # see the proposed tools and the evidence
-/tokeneconomizer:untool apply # accept them
-```
+**Update.** `git pull` in the clone, then start a new session (or `/reload-plugins`). Claude Code
+runs a plugin added from a local folder from that folder. If `/tokeneconomizer:status` still
+shows the old behaviour, run `claude plugin update tokeneconomizer@tokeneconomizer`.
-It takes effect **from your next session**. The rules are written to this repository's
-`.claude/settings.local.json`, which the plugin keeps out of git, and it never touches deny
-rules you wrote yourself. To undo it, run `/tokeneconomizer:untool restore`.
+**Uninstall.**
-**7. Check in whenever you like:** `/tokeneconomizer:status` and `/tokeneconomizer:facts`.
+1. In each repository where you accepted a deny list: `/tokeneconomizer:toolprune restore`.
+2. `claude plugin uninstall tokeneconomizer@tokeneconomizer`, then
+ `claude plugin marketplace remove tokeneconomizer`.
+3. Optional: `rm -rf ~/.tokeneconomizer` to delete what it learned. (A line the plugin added to a
+ repository's `.git/info/exclude` stays; it is harmless.)
-For one session without installing anything: `claude --plugin-dir /path/to/TokenEconomizer/plugin`.
+## Codex
-## Commands
-
-Inside Claude Code:
-
-| Command | What it does |
-|---|---|
-| `/tokeneconomizer:status` | what it has learned in this repository, what it did, and what your sessions cost |
-| `/tokeneconomizer:facts` | the facts it injects at session start, and those still forming |
-| `/tokeneconomizer:untool` | the proposed deny list and its evidence |
-| `/tokeneconomizer:untool apply` | accept the proposal (or `apply TOOL …` for specific tools); from the next session |
-| `/tokeneconomizer:untool restore` | remove the plugin's deny rules (or `restore TOOL …`) |
-| `/tokeneconomizer:untool refresh-catalog` | re-record the tools a session loads, e.g. after a Claude Code update |
-| `/tokeneconomizer:untool measure` | prompt tokens per request with and without the proposal (two small model calls) |
-| `/tokeneconomizer:replay` | what the plugin would do, replayed over this repository's past sessions |
-| `/tokeneconomizer:config` | the settings: what is on, and every value in effect |
-| `/tokeneconomizer:config set KEY=VALUE …` | change settings for this repository (add `--global` for all); see [Settings](#settings) |
-| `/tokeneconomizer:config unset KEY …` | put a setting back to its default |
-
-From a terminal, the same commands and the settings are
-`/path/to/TokenEconomizer/plugin/scripts/te <command>`, run inside the repository:
-
-| Command | What it does |
-|---|---|
-| `te status`, `te facts`, `te untool …`, `te replay`, `te config …` | as above |
-| `te doctor` | check Python, the state directory, and the tool catalogs |
-
-## Settings
+**1. Install.**
-Each of the three mechanisms can be turned on or off on its own, and each has numbers you can
-set by hand. Settings apply to the current repository, or to every repository with `--global`.
-
-**Turn a mechanism on or off:**
-
-```text
-/tokeneconomizer:config set spiral=off # the stuck-turn guard, in this repository
-/tokeneconomizer:config set untool=off inject=on
-/tokeneconomizer:config set spiral=off --global # in every repository
-/tokeneconomizer:config # what is on, and every value in effect
-```
-
-| Mechanism | Key | `on` means | Other values |
-|---|---|---|---|
-| Learned facts | `inject` | `envfacts`: facts found without model calls | `off`; `envfacts+distiller`, `distiller` add a paid fact proposer (need `paid=true`) |
-| Unused-tool deny list | `untool` | `propose`: proposed, applied only when you say so | `off`; `auto` applies a proposal as soon as it forms |
-| Stuck-turn guard | `spiral` | `nudge`: one mid-turn redirect | `off`; `guard` also stops a headless turn that keeps spinning after the redirect |
-
-**Tune a mechanism:**
-
-```text
-/tokeneconomizer:config set inject_max_facts=2 # inject at most two facts
-/tokeneconomizer:config set untool_evidence=10 # wait ten sessions before proposing
-/tokeneconomizer:config set spiral_nudges=2 spiral.min_turns=30
-/tokeneconomizer:config unset spiral.min_turns # back to the default
+```bash
+codex plugin marketplace add /path/to/TokenEconomizer
+codex plugin add tokeneconomizer@tokeneconomizer
```
-| Key | Default | What it sets |
-|---|---|---|
-| `inject_max_facts` | `4` | the most facts injected at session start |
-| `inject_max_tokens` | `150` | the size of the injected block, in tokens (about 4 characters each) |
-| `propose_every` | `5` | sessions between runs of the paid fact proposer |
-| `untool_evidence` | `5` | sessions a tool must go unused before it is proposed (three times as long for a few higher-risk tools; the web is never proposed) |
-| `spiral_aggr` | `default` | the guard's threshold preset: `conservative`, `default` or `aggressive` |
-| `spiral_nudges` | `1` | redirects per prompt-turn before the guard only notifies (or, with `spiral=guard`, stops) |
-| `spiral.<name>` | from the preset | one guard threshold, set by hand (below) |
-
-The guard calls a turn stuck when it keeps editing the same files and hitting the same
-failures, well past how long this repository's turns that end with passing tests usually take
-(the *envelope*). Until a repository has a few such turns, the preset's thresholds apply; after
-that, some are learned from the repository's own turns. A value you set with `spiral.<name>`
-wins over both. Defaults at each preset:
+**2. Approve its hooks.** Start `codex` in a repository. Codex asks whether to trust the project,
+then shows **Hooks need review**: choose **Trust all**. Hooks run from the next session on (the
+session in which you approve gets no session-start injection). To approve later: `/hooks`.
-| `spiral.<name>` | `conservative` | `default` | `aggressive` | What it sets |
-|---|---|---|---|---|
-| `min_turns` | 28 | 20 | 14 | tool calls in a turn before it can count as stuck |
-| `edit_churn` | 5 | 4 | 3 | edits to one file that count as churn |
-| `distinct_edit_files` | 3 | 3 | 3 | files edited that count as scattered |
-| `error_outputs` | 8 | 6 | 4 | failing tool results that count as sustained errors |
-| `stagnation` | 0.30 | 0.20 | 0.12 | share of failures that repeat an earlier one |
-| `envelope_pct` | 90 | 90 | 90 | percentile of the repository's passing turns the envelope starts from |
-| `envelope_margin` | 1.5 | 1.25 | 1.0 | multiplier on that percentile |
-| `envelope_min_samples` | 7 | 5 | 3 | passing turns needed before the envelope is used |
-| `backstop_mult` | 3.5 | 2.5 | 1.8 | past this multiple of the envelope, a stuck turn is redirected, then stopped or flagged |
-| `judge_confidence` | 0.85 | 0.7 | 0.55 | with `paid=true`: how sure the model judge must be |
-| `gate_min_turns` | 24 | 18 | 12 | with `paid=true`: tool calls before the judge is asked |
-| `gate_error_outputs` | 8 | 8 | 8 | with `paid=true`: failing results that ask the judge early |
+**3. Check it.** Ask Codex *"what has TokenEconomizer learned here?"*, or name the skill:
+`$tokeneconomizer-status`. Codex has no plugin slash commands; the plugin's commands are Codex
+skills: `$tokeneconomizer-status`, `$tokeneconomizer-microskills`, `$tokeneconomizer-toolprune` and
+`$tokeneconomizer-config`, each also used when you just ask. From a terminal, inside the
+repository: `~/.tokeneconomizer/bin/te --host codex <command>` (the launcher appears after the
+first session).
-**Other settings:**
+**4. Work normally.** See [What to expect](#what-to-expect). Codex's deny list removes the
+sub-agent (`collaboration`), `goals` and image (`image_media`) packages, each only after it went
+unused in every session where it was loaded; a package you used even once is kept. It is
+written to the project's `.codex/config.toml`, which Codex reads **only in a trusted project**
+(`toolprune apply` warns you otherwise, and runs `codex features list` to show the change took
+effect). The web, asking you questions and the bundled skills are never proposed.
+`toolprune measure` shows the difference with no model call.
-| Key | Default | Values |
-|---|---|---|
-| `paid` | `false` | allow the plugin's own model calls (see below) |
-| `paid_model` | `""` | model for those calls (`haiku` when empty) |
-| `shadow` | `false` | decide and log everything, act on nothing |
-| `mode` | `auto` | `interactive` or `headless` to override what the plugin detects |
-
-**Where settings live, and when they apply.** For one session, an environment variable wins:
-`TE_INJECT`, `TE_UNTOOL`, `TE_SPIRAL`, `TE_SPIRAL_NUDGES`, `TE_INJECT_MAX_FACTS`, and so on, and
-`TE_SPIRAL_THRESHOLDS='{"min_turns": 30}'` for the guard's thresholds; `TE_DISABLE=1` turns the
-whole plugin off. Otherwise the repository's settings win over the global ones, and those over
-the defaults; `unset` goes back one level. A change applies from the agent's next hook call: the
-guard at the next tool call, facts and the deny list at the next session start. A new fact-size
-cap shows once the next session has ended.
-
-## Model calls and API keys
-
-**By default the plugin makes no model calls.** Learned facts, the deny list and the stuck-turn
-check all run locally.
-
-With `paid=true`, three helpers can call a model: the fact proposer, the stuck-turn judge and
-the redirect writer. They run through **your own agent CLI** (`claude -p`; `codex exec` on
-Codex; `copilot -p`, with every tool removed, on Copilot), so they use whatever your sessions
-already use: a Claude subscription or Anthropic API key, your Codex login or OpenAI key, or
-Copilot's subscription or BYOK provider. Their cost is billed there too, and it is shown in
-`/tokeneconomizer:status`. `untool measure` makes its two calls the same way, and only when you
-run it.
-
-## Updating and uninstalling
-
-**Update:** `git pull` in the clone, then `/plugin marketplace update tokeneconomizer` and
-`/plugin install tokeneconomizer@tokeneconomizer`. Claude Code runs an installed **copy**, so
-the pull alone changes nothing.
+In `codex exec`, Codex does not print hook messages, so the plugin's notices are not shown
+there; a loop guard redirect still reaches the model. Codex cannot stop a turn from a hook, so
+`loopguard=stop` acts as `nudge` on Codex.
-**Uninstall:**
+**Update.** `git pull` in the clone, then `codex plugin add tokeneconomizer@tokeneconomizer`
+again to refresh Codex's installed copy (your hook approval is kept).
-1. In each repository where you accepted a deny list, run `/tokeneconomizer:untool restore`
- (Codex and Copilot: `te --host codex untool restore`, `te --host copilot untool restore`).
- The entries live in that repository's settings file and stay there otherwise.
-2. `/plugin uninstall tokeneconomizer@tokeneconomizer`
-3. Optional: `rm -rf ~/.tokeneconomizer` to delete what it learned.
+**Uninstall.**
-## Codex, Copilot and Pi
+1. In each repository where you accepted a deny list:
+ `~/.tokeneconomizer/bin/te --host codex toolprune restore` (it leaves an empty `.codex/`).
+2. `codex plugin remove tokeneconomizer@tokeneconomizer`, then
+ `codex plugin marketplace remove tokeneconomizer`.
+3. Optional: `rm -rf ~/.tokeneconomizer`.
-The plugin runs on all three. What it can remove differs by agent.
-
-| | Learned facts | Stuck-turn redirect | Removing unused tools |
-|---|---|---|---|
-| Claude Code | yes | yes; can also stop a headless turn | tools, in `.claude/settings.local.json` |
-| Codex | yes | yes; a notice instead of a stop | capability packages, in `.codex/config.toml` |
-| Copilot CLI | yes | yes; a notice instead of a stop | whole MCP servers, in `.github/copilot/settings.local.json` |
-| Pi | yes | yes | no (Pi loads four tools) |
-
-On every agent the deny list works the same way: it is proposed after about five sessions,
-nothing changes until you run `untool apply`, it takes effect from the next session, and
-`untool restore` removes only what the plugin added. A file the plugin creates is added to
-`.git/info/exclude`.
-
-**Codex.** Codex always copies an installed plugin, so install from the self-contained bundle:
+**A self-contained install.** Codex copies an installed plugin, and the copy uses the package in
+your clone. To install a copy that carries the package itself, so the clone can move or go:
```bash
-python /path/to/TokenEconomizer/scripts/build_plugin.py --out ~/te-marketplace
+python3 /path/to/TokenEconomizer/scripts/build_plugin.py --out ~/te-marketplace
codex plugin marketplace add ~/te-marketplace
codex plugin add tokeneconomizer@tokeneconomizer
```
-Then approve its hooks once in `/hooks` inside Codex. Commands are
-`~/.tokeneconomizer/bin/te --host codex <command>`, run inside the repository. The launcher is
-written at the first session; until then, use `~/te-marketplace/tokeneconomizer/scripts/te`.
-
-Codex's deny list removes the sub-agent (`collaboration`), `goals` and image (`image_media`)
-packages, each only after it went unused in every session where it was loaded. A package you
-used even once is kept. Two things to know:
+To update it, rebuild the bundle and run `codex plugin add tokeneconomizer@tokeneconomizer` again.
-- Codex reads a project's `.codex/config.toml` **only in a trusted project** (Codex asks the
- first time you start it in a repository). `te --host codex untool apply` warns you if the
- project is not trusted, and runs `codex features list` to show that the change took effect.
-- The web and asking you questions are never proposed. The bundled skills are not proposed
- either: Codex honours that switch only in your user-level config, and the plugin changes
- per-repository files only.
+## Copilot CLI
-`te --host codex untool measure` shows the difference with no model call. It costs nothing
-because Codex renders its prompt locally.
-
-**Copilot CLI.** Copilot loads a plugin from a local marketplace directly from the clone,
-without copying it:
+**1. Install.**
```bash
copilot plugin marketplace add /path/to/TokenEconomizer
@@ -270,28 +161,43 @@ copilot plugin install tokeneconomizer@tokeneconomizer
copilot plugin list # tokeneconomizer@tokeneconomizer ... (enabled)
```
-Copilot uses the plugin's own manifest (`plugin/.github/plugin/plugin.json`) and hook file. In
-Copilot's interactive mode the slash commands work as on Claude Code (`/tokeneconomizer:status`,
-`…:untool`, …), and the plugin's notices appear as status lines. `copilot -p` runs neither.
-From a terminal, run `~/.tokeneconomizer/bin/te --host copilot <command>` inside the
-repository. Every session start keeps that launcher pointing at the plugin.
+Copilot loads the plugin from the clone directly, without copying it.
-Set up each repository once, as on Claude Code:
+**2. Check it.** In Copilot's interactive mode, type `/tokeneconomizer:status`. Each slash command
+is a model turn and asks permission the first time; allow it always. Slash commands work only
+in interactive mode; the plugin's notices also appear under `copilot -p`.
-```bash
-~/.tokeneconomizer/bin/te --host copilot untool refresh-catalog # no model call
+**3. Record the tool list, once.**
+
+```text
+/tokeneconomizer:toolprune refresh-catalog
```
-Copilot has no setting that removes a single built-in tool; it only has one that turns off a
-whole MCP server. So the deny list proposes a server only when **none** of its tools was used
-in about five sessions. The built-in `github-mcp-server` (18 tools on 1.0.83) is the usual
-candidate. `te --host copilot untool measure` shows the difference for your setup. It costs
-nothing, because the plugin captures the request Copilot would send on your machine, and no
-model is called.
+With no model call. Do it once on this machine, and again after Copilot updates.
+
+**4. Work normally.** See [What to expect](#what-to-expect). Copilot has no setting that removes a
+single built-in tool, only one that turns off a whole MCP server, so the deny list proposes a
+server only when **none** of its tools was used in about five sessions: one of yours from
+`~/.copilot/mcp-config.json`, or the built-in `github-mcp-server`, which loads only when you are
+signed in to GitHub. It is written to `.github/copilot/settings.local.json`. `toolprune measure`
+shows the difference with no model call.
-**Copilot with your own model key (BYOK).** If Copilot answers *"Access denied by policy
-settings"*, your organization's policy refuses its models. Copilot can use your own provider
-instead, and the plugin works the same way there. Set this in your shell profile:
+From a terminal, inside the repository: `~/.tokeneconomizer/bin/te --host copilot <command>` (the
+launcher appears after the first session). Copilot cannot stop a turn from a hook, so
+`loopguard=stop` acts as `nudge` on Copilot.
+
+**Update.** `git pull` in the clone; Copilot loads the plugin from it, so nothing else is needed.
+
+**Uninstall.**
+
+1. In each repository where you accepted a deny list: `/tokeneconomizer:toolprune restore`.
+2. `copilot plugin uninstall tokeneconomizer@tokeneconomizer`, then
+ `copilot plugin marketplace remove tokeneconomizer`.
+3. Optional: `rm -rf ~/.tokeneconomizer`.
+
+**With your own model key (BYOK).** If Copilot answers *"Access denied by policy settings"*, your
+organization's policy refuses its models, and Copilot can use your own provider instead. The
+plugin works the same way there, except for its paid helpers (below). In your shell profile:
```bash
export COPILOT_PROVIDER_TYPE=anthropic # or openai, azure
@@ -301,10 +207,8 @@ export COPILOT_PROVIDER_API_KEY=... # your provider's key
Then start Copilot with a model id your provider knows, for example `copilot --model
claude-sonnet-5` (an Anthropic provider wants its own ids, such as `claude-haiku-4-5`, not the
-subscription's `claude-haiku-4.5`).
-
-Through **OpenRouter**, keep Copilot on the Anthropic wire, so prompt caching works, and give it
-both ids:
+subscription's `claude-haiku-4.5`). Through **OpenRouter**, keep Copilot on the Anthropic wire, so
+prompt caching works, and give it both ids:
```bash
export COPILOT_PROVIDER_TYPE=anthropic
@@ -314,13 +218,12 @@ export COPILOT_PROVIDER_MODEL_ID=claude-haiku-4.5 # the id Copilot config
export COPILOT_PROVIDER_WIRE_MODEL=anthropic/claude-haiku-4.5 # the id OpenRouter bills
```
-The plugin's hooks inherit the variables. Its paid helpers (`paid=true`) go to the same
-provider, on `paid_model`, or on your `COPILOT_MODEL` unless that is `auto`, or on
-`claude-haiku-4-5` for an Anthropic provider (`anthropic/claude-haiku-4.5` through OpenRouter).
-`refresh-catalog` and `measure` never call your provider. `te --host copilot doctor` shows the
-route it sees.
+Copilot does not pass these variables to the plugin's hooks, so under BYOK the paid helpers
+(`paid=true`) cannot reach your provider: their calls answer nothing, and each leaves a line in
+`~/.tokeneconomizer/errors.log`. Everything else, including `refresh-catalog` and `measure`,
+needs no provider. `~/.tokeneconomizer/bin/te --host copilot doctor` shows the route it sees.
-To check the whole plugin on your own setup, run it once:
+To check the whole plugin on your own setup:
```bash
~/.tokeneconomizer/bin/te --host copilot probe # 7 short real sessions, in a temp repo
@@ -334,20 +237,233 @@ applies the deny list it proposed, and shows the tool definition tokens of one m
before restoring. It makes real model calls on your key or quota, and leaves those sessions in
Copilot's history.
-**Pi.** This directory is also a Pi package:
+## Pi
+
+**1. Install.** The repository is a Pi package, so Pi installs it like any other:
+
+```bash
+pi install git:github.com/microsoft/TokenEconomizer
+```
+
+(Over SSH: `pi install git:[email protected]:microsoft/TokenEconomizer`. From a clone:
+`pi install /path/to/TokenEconomizer`.)
+
+**2. Check it.** Start a new Pi session and type `/te status`. The commands are `/te status`,
+`/te microskills` and `/te config …`; from a terminal, inside the repository,
+`~/.tokeneconomizer/bin/te --host pi <command>`. Tool pruning does not apply: Pi loads four
+tools. In print and JSON modes the plugin's notices go to stderr.
+
+**3. Work normally.** See [What to expect](#what-to-expect).
+
+**Update.** `pi update --extensions` (plain `pi update` does not update extensions).
+
+**Uninstall.** `pi remove git:github.com/microsoft/TokenEconomizer` (the source you installed
+from); `pi config` turns it off without removing it. Optional: `rm -rf ~/.tokeneconomizer`.
+
+## What to expect
+
+- **Facts.** A fact forms once the same environment failure has come up in a few sessions (three
+ confirming ones, among at least four where it applied), and is injected at every session start
+ after that while the failure keeps occurring or keeps being prevented. A session start that
+ adds facts says so once, in one line. `microskills` shows the facts injected and those forming.
+- **Deny list.** Proposed after about five sessions in which a tool, package or server went
+ unused. The session start after a new proposal forms says so once; nothing changes until you
+ apply it, and it takes effect from the next session. `toolprune restore` removes only what the
+ plugin added. A file the plugin creates is added to `.git/info/exclude`.
+- **Loop guard.** Quiet on normal turns. On a turn that keeps failing the same way well past this
+ repository's usual length, one redirect is attached to a tool result; after that, a notice (or,
+ with `loopguard=stop` on Claude Code and Pi, a stop of a headless turn).
+- **Cost.** `status` shows each session's tokens, priced after it ends, and the plugin's own
+ overhead, which is zero unless you turn on the paid helpers.
+
+## Commands
+
+| Command | What it does |
+|---|---|
+| `status` | what it has learned in this repository, what it did, and what your sessions cost |
+| `microskills` | the facts it injects at session start, and those still forming |
+| `toolprune` | the proposed deny list and its evidence |
+| `toolprune apply [ITEM …]` | accept the proposal (or the named items); from the next session |
+| `toolprune restore [ITEM …]` | remove the plugin's entries |
+| `toolprune refresh-catalog` | record the tools a session loads (Claude Code, Copilot) |
+| `toolprune measure` | the request with and without the proposal |
+| `config` | the settings: what is on, and every value in effect |
+| `config set KEY=VALUE … [--global]` | change settings for this repository (or every one); see [Settings](#settings) |
+| `config unset KEY … [--global]` | put a setting back to its default |
+| `repomap` / `repomap refresh` | the cached repository map / make it now (see [Repository map](#repository-map)) |
+| `doctor` | check Python, the state directory, the agents found and the error log |
+
+How to run them:
+
+| Agent | Inside the agent | From a terminal, in the repository |
+|---|---|---|
+| Claude Code | `/tokeneconomizer:<command>` | `~/.tokeneconomizer/bin/te <command>` |
+| Codex | ask, or `$tokeneconomizer-status` (`-microskills`, `-toolprune`, `-config`) | `~/.tokeneconomizer/bin/te --host codex <command>` |
+| Copilot CLI | `/tokeneconomizer:<command>` (interactive mode) | `~/.tokeneconomizer/bin/te --host copilot <command>` |
+| Pi | `/te <command>` | `~/.tokeneconomizer/bin/te --host pi <command>` |
+
+The launcher in `~/.tokeneconomizer/bin` is written by the first session; before that, use
+`/path/to/TokenEconomizer/plugin/scripts/te`. From a plain terminal, `--host` defaults to the
+agent that last worked in the repository.
+
+## Settings
+
+Each of the three mechanisms can be turned on or off on its own, and each has numbers you can
+set by hand. Settings apply to the current repository, or to every repository with `--global`.
+The examples use Claude Code's form; on the other agents run the same `config` command their way.
+
+**Turn a mechanism on or off:**
+
+```text
+/tokeneconomizer:config set loopguard=off # the loop guard, in this repository
+/tokeneconomizer:config set toolprune=off microskills=on
+/tokeneconomizer:config set loopguard=off --global # in every repository
+/tokeneconomizer:config # what is on, and every value in effect
+```
+
+| Mechanism | Key | `on` means | Other values |
+|---|---|---|---|
+| Micro-skills | `microskills` | `envfacts`: facts found without model calls | `off`; `envfacts+distiller`, `distiller` add a paid fact proposer (need `paid=true`) |
+| Tool pruning | `toolprune` | `propose`: proposed, applied only when you say so | `off`; `auto` applies a proposal as soon as it forms |
+| Loop guard | `loopguard` | `nudge`: one mid-turn redirect | `off`; `stop` also stops a headless turn that keeps failing after the redirect (Claude Code, Pi) |
+
+**Tune a mechanism:**
+
+```text
+/tokeneconomizer:config set microskills_max_facts=2 # inject at most two facts
+/tokeneconomizer:config set toolprune_evidence=10 # wait ten sessions before proposing
+/tokeneconomizer:config set loopguard_nudges=2 loopguard.min_turns=30
+/tokeneconomizer:config unset loopguard.min_turns # back to the default
+```
+
+| Key | Default | What it sets |
+|---|---|---|
+| `microskills_max_facts` | `4` | the most facts injected at session start |
+| `microskills_max_tokens` | `150` | the size of the injected block, in tokens (about 4 characters each) |
+| `microskills_propose_every` | `5` | sessions between runs of the paid fact proposer |
+| `toolprune_evidence` | `5` | sessions a tool must go unused before it is proposed (three times as long for a few higher-risk tools; the web is never proposed) |
+| `loopguard_aggr` | `default` | the guard's threshold preset: `conservative`, `default` or `aggressive` |
+| `loopguard_nudges` | `1` | redirects per prompt-turn before the guard only notifies (or, with `loopguard=stop`, stops) |
+| `loopguard.<name>` | from the preset | one guard threshold, set by hand (below) |
+
+The guard calls a turn stuck when it keeps editing the same files and hitting the same
+failures, well past how long this repository's turns that end with passing tests usually take
+(the *envelope*). Until a repository has a few such turns, the preset's thresholds apply; after
+that, some are learned from the repository's own turns. A value you set with `loopguard.<name>`
+wins over both. Defaults at each preset:
+
+| `loopguard.<name>` | `conservative` | `default` | `aggressive` | What it sets |
+|---|---|---|---|---|
+| `min_turns` | 28 | 20 | 14 | tool calls in a turn before it can count as stuck |
+| `edit_churn` | 5 | 4 | 3 | edits to one file that count as churn |
+| `distinct_edit_files` | 3 | 3 | 3 | files edited that count as scattered |
+| `error_outputs` | 8 | 6 | 4 | failing tool results that count as sustained errors |
+| `stagnation` | 0.30 | 0.20 | 0.12 | share of failures that repeat an earlier one |
+| `envelope_pct` | 90 | 90 | 90 | percentile of the repository's passing turns the envelope starts from |
+| `envelope_margin` | 1.5 | 1.25 | 1.0 | multiplier on that percentile |
+| `envelope_min_samples` | 7 | 5 | 3 | passing turns needed before the envelope is used |
+| `backstop_mult` | 3.5 | 2.5 | 1.8 | past this multiple of the envelope, a stuck turn is redirected, then stopped or flagged |
+| `judge_confidence` | 0.85 | 0.7 | 0.55 | with `paid=true`: how sure the model judge must be |
+| `gate_min_turns` | 24 | 18 | 12 | with `paid=true`: tool calls before the judge is asked |
+| `gate_error_outputs` | 8 | 8 | 8 | with `paid=true`: failing results that ask the judge early |
+
+**Repository map** (off by default; see [Repository map](#repository-map)):
+
+| Key | Default | What it sets |
+|---|---|---|
+| `repomap` | `off` | `on`: a map ranked toward the session's first prompt; `start`: the cached map at session start |
+| `repomap_tokens` | `2048` | the map's size, in tokens |
+| `repomap_python` | auto | the Python that has aider installed |
+| `repomap_timeout` | `8` | seconds the first prompt may wait for a ranked map before the cached one is used |
+
+**Other settings:**
+
+| Key | Default | Values |
+|---|---|---|
+| `paid` | `false` | allow the plugin's own model calls (see [Model calls](#model-calls-and-api-keys)) |
+| `paid_model` | `""` | model for those calls; empty: `haiku` on Claude Code, the agent's own default model on Codex and Pi, `COPILOT_MODEL` on Copilot (unless it is `auto`) |
+| `shadow` | `false` | decide and log everything, act on nothing |
+| `mode` | `auto` | `interactive` or `headless` to override what the plugin detects |
+
+**Where settings live, and when they apply.** For one session, an environment variable wins:
+`TE_MICROSKILLS`, `TE_TOOLPRUNE`, `TE_LOOPGUARD`, `TE_LOOPGUARD_NUDGES`,
+`TE_MICROSKILLS_MAX_FACTS`, and so on, and `TE_LOOPGUARD_THRESHOLDS='{"min_turns": 30}'` for the
+guard's thresholds; `TE_DISABLE=1` turns the whole plugin off. Otherwise the repository's
+settings win over the global ones, and those over the defaults; `unset` goes back one level. A
+change applies from the agent's next hook call: the guard at the next tool call, facts and the
+deny list at the next session start. A new fact-size cap shows once the next session has ended.
+
+**Earlier names.** Before the mechanisms were renamed they were `inject`, `untool` and `spiral`,
+with settings such as `inject_max_facts`, `untool_evidence`, `spiral_nudges`, `spiral.<name>` and
+variables `TE_INJECT`, `TE_UNTOOL`, `TE_SPIRAL`, ...; all of them are still read (`spiral=guard`
+as `loopguard=stop`), and a new name set alongside its old one wins. `config set` writes the new
+name. The earlier commands `te facts` and `te untool`, and `/tokeneconomizer:facts` and
+`/tokeneconomizer:untool`, still work.
+
+## Repository map
+
+An opt-in fourth mechanism: aider's map of the repository's key files and symbols (signatures
+only, ranked by how much of the code refers to them), added to the session's context so the
+agent knows where things are before it starts reading files. Turn it on per repository:
```bash
-pi install /path/to/TokenEconomizer/plugin
+pip install aider-chat # or: pipx install aider-chat / uv tool install aider-chat
+~/.tokeneconomizer/bin/te config set repomap=on # add --host for Codex, Copilot or Pi
```
-Inside Pi: `/te status`, `/te facts`, `/te replay`, `/te config …`.
+- **What goes in.** At most `repomap_tokens` tokens (default 2048), once per session. On Claude
+ Code, the Copilot CLI and Pi it is ranked toward the identifiers in your first prompt; if that
+ takes longer than `repomap_timeout` seconds (about 5 s on a repository of Django's size, well
+ under a second on a small one), the cached map is used instead. Codex gets the cached map at
+ session start. `repomap=start` does that on every agent and never delays a prompt.
+- **What it reads.** The files `git ls-files` lists, in every language aider understands,
+ without vendored code, minified files or files over 256 KB.
+- **Where it runs.** In whichever Python has aider: `repomap_python` if you set it, else the one
+ behind an installed `aider` command, else the plugin's own. `te doctor` says which it found.
+ The plugin never imports aider itself.
+- **What it writes.** Nothing in the repository. The map and aider's tag cache live in the
+ plugin's state directory. The map is cached per commit and remade in the background when
+ `HEAD` moves.
+- **What it costs.** No model calls. The map is part of every request of the session, so it
+ costs on sessions that already knew where to look and saves on those that would have searched.
+ `te status` shows its size.
+
+## Using with rtk
+
+[rtk](https://github.com/rtk-ai/rtk) compresses shell output. Install it on its own (`rtk init
+-g`); it does not need to be part of this plugin, and the two do not get in each other's way:
+rtk rewrites shell commands before they run, and this plugin reads sessions, injects context and
+watches tool results. The plugin reads `rtk`-prefixed commands as the commands they wrap, and
+rtk adds no tools for the deny list to see. `te doctor` reports an installed rtk.
+
+One interaction to know: with rtk 0.45.0, `rtk pytest` prints nothing when pytest is missing (it
+exits with code 1). The agent sees no error and the plugin cannot learn the "`pytest` fails here;
+`X` works" fact from it. Commands that name their interpreter (`.venv/bin/python -m pytest`) are
+not rewritten, so the commands that fact recommends keep working.
+
+## Model calls and API keys
+
+**By default the plugin makes no model calls.** Micro-skills, tool pruning and the loop guard
+all run locally.
+
+With `paid=true`, three helpers can call a model: the fact proposer, the loop guard's judge and
+the redirect writer. They run through **your own agent CLI** (`claude -p`; `codex exec` on
+Codex; `copilot -p`, with every tool removed, on Copilot; `pi -p`, with nothing loaded but the
+model, on Pi), so they use whatever your sessions already use: a Claude subscription or
+Anthropic API key, your Codex login or OpenAI key, Copilot's subscription, or the provider and
+login Pi is set up with. (Copilot with BYOK is the exception; see [Copilot CLI](#copilot-cli).)
+Their cost is billed there too, and shown in `status`. A call that gets no reply leaves a line in
+`~/.tokeneconomizer/errors.log`. `toolprune measure` on Claude Code makes its two calls the same
+way, and only when you run it.
## Troubleshooting
| Symptom | Fix |
|---|---|
-| `/tokeneconomizer:status` prints an import error | reinstall (see Updating); the copy is stale or incomplete |
-| it prints nothing useful, or the hooks seem to do nothing | run `te doctor`; check `~/.tokeneconomizer/errors.log` |
+| a command prints an import error, or the hooks seem to do nothing | run `~/.tokeneconomizer/bin/te doctor` (or `plugin/scripts/te doctor` in the clone) and read its errors.log lines |
+| errors.log says the package "was not found for the plugin" | the clone the plugin was installed from moved or is gone: add it again, or use the [self-contained install](#codex) |
| `python 3.x (needs >= 3.10)` | install Python 3.10+ or set `TE_PYTHON` to one |
-| the deny list proposes nothing after many sessions | run `/tokeneconomizer:untool refresh-catalog` (step 4); on Copilot, `te --host copilot untool refresh-catalog` |
-| a Codex deny list was applied but nothing changed | trust the project in Codex; `te --host codex doctor` says whether it is trusted |
+| the deny list proposes nothing after many sessions | run `toolprune refresh-catalog` (Claude Code, Copilot) |
+| a Codex deny list was applied but nothing changed | trust the project in Codex; `~/.tokeneconomizer/bin/te --host codex doctor` says whether it is trusted |
+| errors.log has `sidecall copilot: no reply` | the paid helpers cannot use a Copilot BYOK provider ([Copilot CLI](#copilot-cli)); turn `paid` off |
+| `te` shows another agent's state | add `--host claude`, `codex`, `copilot` or `pi` |
diff --git a/plugin/codex-skills/tokeneconomizer-config/SKILL.md b/plugin/codex-skills/tokeneconomizer-config/SKILL.md
new file mode 100644
index 0000000..8f837d4
--- /dev/null
+++ b/plugin/codex-skills/tokeneconomizer-config/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: "tokeneconomizer-config"
+description: >
+ Show or change TokenEconomizer's settings: turn micro-skills, tool pruning or the loop guard on or off, or tune them, for this repository or (with --global) every repository. Use when the user asks to configure, enable or disable TokenEconomizer or one of its mechanisms.
+---
+
+# tokeneconomizer-config
+
+Run this command in the repository's root directory:
+
+```
+"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$(pwd)" config ARGS
+```
+
+Use `show` as ARGS unless the user asked to change a setting; then `set KEY=VALUE ...` or `unset KEY ...`, adding `--global` only if they asked for every repository. Show the output verbatim in a code block; if a setting was rejected, say why in one sentence.
+
+The command reads and writes only TokenEconomizer's own state (under `~/.tokeneconomizer`)
+and, for `toolprune apply` or `restore`, the project's `.codex/config.toml`; it makes no model
+call. If it reports that the launcher does not exist, the plugin has not run in a session yet:
+ask the user to start a new Codex session in this repository first.
diff --git a/plugin/codex-skills/tokeneconomizer-microskills/SKILL.md b/plugin/codex-skills/tokeneconomizer-microskills/SKILL.md
new file mode 100644
index 0000000..29790e5
--- /dev/null
+++ b/plugin/codex-skills/tokeneconomizer-microskills/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: "tokeneconomizer-microskills"
+description: >
+ Show the repository facts (micro-skills) TokenEconomizer learned and injects at the start of each session here, and the ones still forming. Use when the user asks what TokenEconomizer learned or injects, or about its facts or micro-skills.
+---
+
+# tokeneconomizer-microskills
+
+Run this command in the repository's root directory:
+
+```
+"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$(pwd)" microskills
+```
+
+Show the output verbatim in a code block, with no commentary.
+
+The command reads and writes only TokenEconomizer's own state (under `~/.tokeneconomizer`)
+and, for `toolprune apply` or `restore`, the project's `.codex/config.toml`; it makes no model
+call. If it reports that the launcher does not exist, the plugin has not run in a session yet:
+ask the user to start a new Codex session in this repository first.
diff --git a/plugin/codex-skills/tokeneconomizer-status/SKILL.md b/plugin/codex-skills/tokeneconomizer-status/SKILL.md
new file mode 100644
index 0000000..0fe38db
--- /dev/null
+++ b/plugin/codex-skills/tokeneconomizer-status/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: "tokeneconomizer-status"
+description: >
+ Show what TokenEconomizer has learned for this repository, what it has done, and what this repository's sessions cost. Use when the user asks about TokenEconomizer, its status, its savings or overhead, or what it learned here.
+---
+
+# tokeneconomizer-status
+
+Run this command in the repository's root directory:
+
+```
+"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$(pwd)" status
+```
+
+Show the output verbatim in a code block. Add nothing unless it contains a warning; then explain the warning in one sentence.
+
+The command reads and writes only TokenEconomizer's own state (under `~/.tokeneconomizer`)
+and, for `toolprune apply` or `restore`, the project's `.codex/config.toml`; it makes no model
+call. If it reports that the launcher does not exist, the plugin has not run in a session yet:
+ask the user to start a new Codex session in this repository first.
diff --git a/plugin/codex-skills/tokeneconomizer-toolprune/SKILL.md b/plugin/codex-skills/tokeneconomizer-toolprune/SKILL.md
new file mode 100644
index 0000000..f5e3925
--- /dev/null
+++ b/plugin/codex-skills/tokeneconomizer-toolprune/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: "tokeneconomizer-toolprune"
+description: >
+ Review, apply or undo TokenEconomizer's proposed list of Codex capabilities this repository never uses (written to the project's .codex/config.toml). Use when the user asks about TokenEconomizer's tool pruning or deny list, or asks to apply or restore it.
+---
+
+# tokeneconomizer-toolprune
+
+Run this command in the repository's root directory:
+
+```
+"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$(pwd)" toolprune ARGS
+```
+
+Use `show` as ARGS unless the user asked to `apply`, `restore` or `measure` (optionally naming capabilities). Never run `apply` or `restore` unless the user asked for it. Show the output verbatim in a code block; if it is a proposal, end with one line saying how to apply it and that it takes effect from the next session.
+
+The command reads and writes only TokenEconomizer's own state (under `~/.tokeneconomizer`)
+and, for `toolprune apply` or `restore`, the project's `.codex/config.toml`; it makes no model
+call. If it reports that the launcher does not exist, the plugin has not run in a session yet:
+ask the user to start a new Codex session in this repository first.
diff --git a/plugin/commands/facts.md b/plugin/commands/facts.md
index 8c443d9..9bfc20e 100644
--- a/plugin/commands/facts.md
+++ b/plugin/commands/facts.md
@@ -1,8 +1,8 @@
---
-description: Show the learned repository facts TokenEconomizer injects at session start
+description: Earlier name of /tokeneconomizer:microskills - show the repository facts TokenEconomizer injects
---
Run this exact command with the Bash tool, then show me its output verbatim in a code block, with no commentary:
```
-te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" facts
+te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" microskills
```
diff --git a/plugin/commands/microskills.md b/plugin/commands/microskills.md
new file mode 100644
index 0000000..4f65110
--- /dev/null
+++ b/plugin/commands/microskills.md
@@ -0,0 +1,8 @@
+---
+description: Show the repository facts (micro-skills) TokenEconomizer learned and injects at session start
+---
+Run this exact command with the Bash tool, then show me its output verbatim in a code block, with no commentary:
+
+```
+te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" microskills
+```
diff --git a/plugin/commands/replay.md b/plugin/commands/replay.md
deleted file mode 100644
index 05bd71e..0000000
--- a/plugin/commands/replay.md
+++ /dev/null
@@ -1,11 +0,0 @@
----
-description: Estimate what TokenEconomizer would do, by replaying it over this repository's past sessions (no LLM calls)
-argument-hint: "[--limit N] [--commit]"
----
-Run this exact command with the Bash tool. It reads past session transcripts and can take a few minutes on a long history, so allow it a timeout of up to 10 minutes. Arguments given: "$ARGUMENTS".
-
-```
-te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" replay $ARGUMENTS
-```
-
-Show me the output verbatim in a code block, then summarize in at most three sentences what each mechanism would have done. Do not run anything else.
diff --git a/plugin/commands/toolprune.md b/plugin/commands/toolprune.md
new file mode 100644
index 0000000..edfe7e1
--- /dev/null
+++ b/plugin/commands/toolprune.md
@@ -0,0 +1,11 @@
+---
+description: Review or apply TokenEconomizer's proposed deny list of tools this repository never uses
+argument-hint: "[show | apply [TOOL ...] | restore [TOOL ...] | refresh-catalog | measure]"
+---
+Run this exact command with the Bash tool (use `show` when no arguments were given: "$ARGUMENTS"), then show me its output verbatim in a code block:
+
+```
+te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" toolprune $ARGUMENTS
+```
+
+Do not run `apply` or `restore` unless those words appear in the arguments above. If the output is a proposal, end with one line telling me how to apply it (`/tokeneconomizer:toolprune apply`) and that it takes effect from the next session.
diff --git a/plugin/commands/untool.md b/plugin/commands/untool.md
index 54f448c..19dceee 100644
--- a/plugin/commands/untool.md
+++ b/plugin/commands/untool.md
@@ -1,11 +1,11 @@
---
-description: Review or apply TokenEconomizer's proposed deny list of tools this repository never uses
+description: Earlier name of /tokeneconomizer:toolprune - review or apply the proposed deny list
argument-hint: "[show | apply [TOOL ...] | restore [TOOL ...] | refresh-catalog | measure]"
---
Run this exact command with the Bash tool (use `show` when no arguments were given: "$ARGUMENTS"), then show me its output verbatim in a code block:
```
-te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" untool $ARGUMENTS
+te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" toolprune $ARGUMENTS
```
-Do not run `apply` or `restore` unless those words appear in the arguments above. If the output is a proposal, end with one line telling me how to apply it (`/tokeneconomizer:untool apply`) and that it takes effect from the next session.
+Do not run `apply` or `restore` unless those words appear in the arguments above. If the output is a proposal, end with one line telling me how to apply it (`/tokeneconomizer:toolprune apply`) and that it takes effect from the next session.
diff --git a/plugin/hooks/copilot-hooks.json b/plugin/hooks/copilot-hooks.json
index 6dec24d..15c8fd8 100644
--- a/plugin/hooks/copilot-hooks.json
+++ b/plugin/hooks/copilot-hooks.json
@@ -18,7 +18,7 @@
{
"type": "command",
"command": "\"${PLUGIN_ROOT}/scripts/te-hook\" --host copilot",
- "timeout": 10
+ "timeout": 20
}
]
}
diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.json
index 2248ef8..48de93a 100644
--- a/plugin/hooks/hooks.json
+++ b/plugin/hooks/hooks.json
@@ -18,7 +18,7 @@
{
"type": "command",
"command": "\"${CLAUDE_PLUGIN_ROOT}/scripts/te-hook\"",
- "timeout": 10
+ "timeout": 20
}
]
}
@@ -34,6 +34,17 @@
]
}
],
+ "PostToolUseFailure": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "\"${CLAUDE_PLUGIN_ROOT}/scripts/te-hook\"",
+ "timeout": 60
+ }
+ ]
+ }
+ ],
"Stop": [
{
"hooks": [
diff --git a/plugin/lib/te_live b/plugin/lib/te_live
deleted file mode 100644
index 86d3486..0000000
--- a/plugin/lib/te_live
+++ /dev/null
@@ -1 +0,0 @@
-../../te_live
\ No newline at end of file
diff --git a/plugin/lib/tokeneconomizer b/plugin/lib/tokeneconomizer
deleted file mode 100644
index 4332233..0000000
--- a/plugin/lib/tokeneconomizer
+++ /dev/null
@@ -1 +0,0 @@
-../../tokeneconomizer
\ No newline at end of file
diff --git a/plugin/lib/tokeneconomizer b/plugin/lib/tokeneconomizer
new file mode 120000
index 0000000..4332233
--- /dev/null
+++ b/plugin/lib/tokeneconomizer
@@ -0,0 +1 @@
+../../tokeneconomizer
\ No newline at end of file
diff --git a/plugin/package.json b/plugin/package.json
index 7352c94..d51f261 100644
--- a/plugin/package.json
+++ b/plugin/package.json
@@ -2,12 +2,19 @@
"name": "tokeneconomizer",
"version": "0.1.0",
"private": true,
- "description": "TokenEconomizer for Pi: learned per-repo facts injected at session start, and a guard that redirects a turn stuck in a failing loop.",
- "keywords": ["pi-package", "cost", "tokens", "context"],
+ "description": "TokenEconomizer for Pi: micro-skills (short repository facts learned from earlier sessions) injected at session start, and a guard that redirects a turn stuck in a failing loop.",
+ "keywords": [
+ "pi-package",
+ "cost",
+ "tokens",
+ "context"
+ ],
"license": "MIT",
"repository": "https://github.com/microsoft/TokenEconomizer",
"pi": {
- "extensions": ["./pi/tokeneconomizer.ts"]
+ "extensions": [
+ "./pi/tokeneconomizer.ts"
+ ]
},
"peerDependencies": {
"@earendil-works/pi-coding-agent": "*"
diff --git a/plugin/pi/tokeneconomizer.ts b/plugin/pi/tokeneconomizer.ts
index 215e3e5..ba03cae 100644
--- a/plugin/pi/tokeneconomizer.ts
+++ b/plugin/pi/tokeneconomizer.ts
@@ -82,10 +82,12 @@ async function hook(payload: Record<string, unknown>, mode: string): Promise<any
}
}
+/** A notice in the UI; on stderr in print and JSON modes, which have no UI and keep stdout for
+ * the reply and the event stream -- so a headless stop, too, says why it happened. */
function notify(ctx: ExtensionContext, text: unknown) {
if (typeof text !== "string" || !text) return;
if (ctx.hasUI) ctx.ui.notify(text, "info");
- else if (truthy(process.env.TE_VERBOSE)) console.error(text);
+ else console.error(text);
}
const SOURCE: Record<string, string> = {
@@ -122,10 +124,17 @@ export default function tokeneconomizer(pi: ExtensionAPI) {
pi.on("before_agent_start", async (event, ctx) => {
prompts += 1;
turn = `${ctx.sessionManager.getSessionId()}:${prompts}`;
- await hook(
+ const out = await hook(
{ ...base(ctx), hook_event_name: "UserPromptSubmit", prompt_id: turn, prompt: event.prompt },
ctx.mode,
);
+ // The repository map arrives on a session's first prompt; it joins the manual for the rest
+ // of the session, since the section is set again on every prompt.
+ const extra = out?.hookSpecificOutput?.additionalContext;
+ if (extra) {
+ manual = manual ? `${manual}\n\n${extra}` : extra;
+ }
+ notify(ctx, out?.systemMessage);
if (manual) {
event.systemPromptOptions.sections = { ...(event.systemPromptOptions.sections ?? {}), [SECTION]: manual };
}
@@ -169,7 +178,7 @@ export default function tokeneconomizer(pi: ExtensionAPI) {
});
pi.registerCommand("te", {
- description: "TokenEconomizer: status | facts | replay | config (what it learned here, what it did)",
+ description: "TokenEconomizer: status | microskills | config (what it learned here, what it did)",
handler: async (args, ctx) => {
const argv = (args || "status").trim().split(/\s+/).filter(Boolean);
const out = await run("te", ["--host", "pi", "--cwd", ctx.cwd, ...argv], "", ctx.mode);
diff --git a/plugin/scripts/te b/plugin/scripts/te
old mode 100644
new mode 100755
index 833c3d5..0010305
--- a/plugin/scripts/te
+++ b/plugin/scripts/te
@@ -1,5 +1,5 @@
#!/bin/sh
-# TokenEconomizer command line (`te status`, `te untool show`, `te replay`, ...).
+# TokenEconomizer command line (`te status`, `te toolprune show`, `te config`, ...).
dir=$(CDPATH= cd -- "${0%/*}" && pwd)
for py in "${TE_PYTHON:-}" python3 python; do
if [ -n "$py" ] && command -v "$py" >/dev/null 2>&1; then
diff --git a/plugin/scripts/te-hook b/plugin/scripts/te-hook
old mode 100644
new mode 100755
diff --git a/plugin/scripts/te_bootstrap.py b/plugin/scripts/te_bootstrap.py
index 0114f6c..25b6986 100644
--- a/plugin/scripts/te_bootstrap.py
+++ b/plugin/scripts/te_bootstrap.py
@@ -1,37 +1,88 @@
-"""Locate TokenEconomizer (`tokeneconomizer` + `te_live`) and run the hook dispatcher (`hook`)
-or the command line (`cli`).
+"""Locate the `tokeneconomizer` package and run the hook dispatcher (`hook`) or the command line
+(`cli`), both in `tokeneconomizer.plugin`.
-The core package is found, in order:
+The package is found, in order:
1. `$TE_CORE_PATH` -- a checkout you point at explicitly;
- 2. `<plugin root>/lib` -- in the repository, symlinks to the two packages; Claude
+ 2. `<plugin root>/lib` -- in the repository, a symlink to the package; Claude
Code's install copies the plugin directory into its
- cache (even from a local marketplace) and follows them,
+ cache (even from a local marketplace) and follows it,
so the installed copy is self-contained. In the bundle
- `scripts/build_plugin.py` writes, real copies;
+ `scripts/build_plugin.py` writes, a real copy;
3. `<plugin root>/..` -- the repository this plugin directory lives in, for a
checkout whose symlinks were not created (`--plugin-dir`);
- 4. an installed package -- `pip install` of the repository.
+ 4. the marketplace it came from -- Codex's install copies the plugin directory but drops
+ the `lib` symlink; for a copy under
+ `<CODEX_HOME>/plugins/cache/<marketplace>/...`, the
+ checkout `config.toml` names as that marketplace's
+ `source` (the clone a local marketplace was added
+ from), or Codex's own checkout of a git marketplace,
+ `<CODEX_HOME>/.tmp/marketplaces/<marketplace>`;
+ 5. an installed package -- `pip install` of the repository.
+
+When none has it, a hook answers `{}` as always, and says why once in the plugin's errors.log.
This file must stay importable by any Python 3 so that an old interpreter can still answer a
hook with `{}` instead of a syntax error: no f-strings, no annotations, nothing newer than 3.0.
"""
import os
+import re
import sys
MIN_VERSION = (3, 10)
+def _marketplace_sources(plugin_root):
+ """For a Codex install copy (`<home>/plugins/cache/<marketplace>/<plugin>/<version>`), the
+ `source` its `config.toml` records for that marketplace (a local one), and the checkout Codex
+ keeps of a git one."""
+ parts = plugin_root.rstrip(os.sep).split(os.sep)
+ if len(parts) < 6 or parts[-4] != "cache" or parts[-5] != "plugins":
+ return []
+ home, market = os.sep.join(parts[:-5]), parts[-3]
+ out = [os.path.join(home, ".tmp", "marketplaces", market)]
+ try:
+ text = open(os.path.join(home, "config.toml")).read()
+ except (IOError, OSError):
+ return out
+ section = None
+ for line in text.splitlines():
+ line = line.strip()
+ if line.startswith("["):
+ section = line.strip("[]").strip().replace('"', "")
+ continue
+ m = re.match(r'source\s*=\s*"([^"]+)"', line)
+ if m and section == "marketplaces." + market:
+ out.append(m.group(1))
+ return out
+
+
def core_path():
plugin_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- for cand in (os.environ.get("TE_CORE_PATH"), os.path.join(plugin_root, "lib"),
- os.path.dirname(plugin_root)):
- if cand and os.path.isfile(os.path.join(cand, "te_live", "hook.py")) and \
- os.path.isfile(os.path.join(cand, "tokeneconomizer", "__init__.py")):
+ for cand in ([os.environ.get("TE_CORE_PATH"), os.path.join(plugin_root, "lib"),
+ os.path.dirname(plugin_root)] + _marketplace_sources(plugin_root)):
+ if cand and os.path.isfile(os.path.join(cand, "tokeneconomizer", "plugin", "hook.py")):
return cand
return None
+def _say_missing(plugin_root):
+ """One line in the plugin's errors.log (not repeated) when the core cannot be found."""
+ home = os.environ.get("TOKENECONOMIZER_HOME") or os.path.join(os.path.expanduser("~"),
+ ".tokeneconomizer")
+ line = ("bootstrap: the tokeneconomizer package was not found for the plugin at %s; "
+ "install from the bundle (scripts/build_plugin.py) or set TE_CORE_PATH\n" % plugin_root)
+ path = os.path.join(home, "errors.log")
+ try:
+ if os.path.exists(path) and line in open(path).read():
+ return
+ if not os.path.isdir(home):
+ os.makedirs(home)
+ open(path, "a").write(line)
+ except (IOError, OSError):
+ pass
+
+
def main():
mode = sys.argv[1] if len(sys.argv) > 1 else "hook"
rest = sys.argv[2:]
@@ -53,11 +104,18 @@ def main():
sys.path.insert(0, core)
try:
if mode == "hook":
- from te_live import hook
+ from tokeneconomizer.plugin import hook
return hook.main(rest)
- from te_live import cli
+ from tokeneconomizer.plugin import cli
return cli.main(rest)
except ImportError:
+ if core is None:
+ _say_missing(os.environ["TE_PLUGIN_ROOT"])
+ if mode != "hook":
+ sys.stderr.write("TokenEconomizer: its core package was not found next to the "
+ "plugin at %s (see ~/.tokeneconomizer/errors.log)\n"
+ % os.environ["TE_PLUGIN_ROOT"])
+ return 1
if mode == "hook":
sys.stdout.write("{}\n")
return 0
diff --git a/pyproject.toml b/pyproject.toml
index 9283263..7ac3b88 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -5,22 +5,22 @@ build-backend = "setuptools.build_meta"
[project]
name = "tokeneconomizer"
version = "0.1.0"
-description = "Runtime cost control for coding agents (Claude Code, Codex, Copilot CLI, Pi), delivered from outside the agent as a plugin."
+description = "Experience-driven black-box cost control for coding agents (Claude Code, Codex, Copilot CLI, Pi), as a plugin."
readme = "README.md"
requires-python = ">=3.10"
license = { text = "MIT" }
authors = [{ name = "TokenEconomizer authors" }]
keywords = ["llm-agents", "cost-optimization", "swe-bench", "token-economy"]
-# The core package is intentionally STDLIB-ONLY: the three mechanisms + the vendored
-# pricing/reflect/spiral building blocks import nothing outside the standard library, so
-# `import tokeneconomizer` works in any Python >=3.10 with zero install-time dependencies.
+# The package is STDLIB-ONLY: the three mechanisms, the trace reader, the ledger and the plugin
+# runtime import nothing outside the standard library, so it runs on any Python >=3.10 with zero
+# install-time dependencies.
dependencies = []
[project.scripts]
-# The live layer's command line (status, facts, untool, replay, ...). The plugin ships its own
-# launcher (plugin/scripts/te) and does not need the package installed.
-te = "te_live.cli:main"
+# The plugin's command line (status, microskills, toolprune, config, ...). The plugin ships its
+# own launcher (plugin/scripts/te) and does not need the package installed.
+te = "tokeneconomizer.plugin.cli:main"
[project.optional-dependencies]
# Test suite is offline (no Docker / no datasets).
@@ -33,25 +33,28 @@ test = ["pytest>=7.0"]
# actually 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.
harness = []
-# The repo-map external baseline (tokeneconomizer/baselines/repomap.py) generates aider's
+# The repo-map external baseline (experiments/te_bench/baselines/repomap.py) generates aider's
# token-budgeted map on the HOST -- the task container's Python is pinned to the issue's
# era and cannot run a modern tree-sitter stack. This is the ONLY baseline with a host
# dependency: rtk ships a static binary and Serena installs itself in-container.
#
-# It stays an EXTRA, and aider is imported inside `preflight()` rather than at module
-# scope, so `import tokeneconomizer` keeps its zero-dependency guarantee even though the
-# baselines now ship inside the core package. A machine that will never run the repomap
-# arms never needs aider installed.
+# It stays an EXTRA: aider is imported inside `preflight()`, and the generator both the
+# baseline and the plugin's opt-in map run (tokeneconomizer/plugin/repomap_gen.py) is a subprocess
+# that nothing imports, so `import tokeneconomizer` keeps its zero-dependency guarantee. A
+# machine that will never make a repo map never needs aider installed.
baselines = ["aider-chat>=0.60"]
[tool.setuptools.packages.find]
-# The core package and the plugin's live layer ONLY. The paper's reproduction code
-# (experiments/, including te_harness) is deliberately not distributed: `import
-# tokeneconomizer` must not be able to reach Docker or an agent CLI, and excluding it here is
-# what makes that structural rather than a convention.
-include = ["tokeneconomizer*", "te_live*"]
+# The package ONLY. The reproduction code (experiments/, including te_harness and te_bench) is
+# deliberately not distributed: `import tokeneconomizer` must not be able to reach Docker or a
+# benchmark harness, and excluding it here is what makes that structural.
+include = ["tokeneconomizer*"]
exclude = ["experiments*", "te_harness*", "tests*", "scripts*"]
[tool.pytest.ini_options]
testpaths = ["tests", "experiments/tests"]
addopts = "-q"
+
+[tool.setuptools.package-data]
+# The Claude Code tool-description snapshot the catalog reader joins against.
+tokeneconomizer = ["trace/*.json"]
diff --git a/scripts/build_plugin.py b/scripts/build_plugin.py
index c8fadf3..e4fcdaa 100644
--- a/scripts/build_plugin.py
+++ b/scripts/build_plugin.py
@@ -8,17 +8,17 @@ added as a local-directory marketplace -- the plugin finds the core package one
checkout itself. A marketplace INSTALL is different: Claude Code copies only the plugin directory
into its cache ("files outside the plugin directory aren't copied"), and Codex does the same, so
an installed copy of `plugin/` alone has no `tokeneconomizer` to import. The bundle fixes that by
-vendoring the core and the live harness (`tokeneconomizer/`, `te_live/`) into `<plugin>/lib/`,
-which `scripts/te_bootstrap.py` looks in first.
+copying the package (`tokeneconomizer/`, the mechanisms and the plugin runtime) into
+`<plugin>/lib/`, which `scripts/te_bootstrap.py` looks in first.
-Both are stdlib-only, so vendoring them is the whole dependency story: the bundle runs on any
-Python >= 3.10 with nothing installed. `te_harness/`, `scripts/` and the docs are not included.
+The package is stdlib-only, so copying it is the whole dependency story: the bundle runs on any
+Python >= 3.10 with nothing installed. `experiments/`, `scripts/` and the docs are not included.
Layout written to --out (a marketplace root you can `marketplace add`, publish as a branch or a
repository of its own, or zip for `claude --plugin-url`):
<out>/.claude-plugin/marketplace.json
- <out>/tokeneconomizer/ the plugin, with lib/{tokeneconomizer,te_live} vendored
+ <out>/tokeneconomizer/ the plugin, with lib/tokeneconomizer copied in
"""
import argparse
import json
@@ -35,13 +35,12 @@ def build(out):
plugin_out = os.path.join(out, "tokeneconomizer")
if os.path.exists(plugin_out):
shutil.rmtree(plugin_out)
- # plugin/lib holds symlinks to the core for an install from a checkout (see te_bootstrap);
- # the bundle replaces them with real copies.
+ # plugin/lib holds a symlink to the package for an install from a checkout (see
+ # te_bootstrap); the bundle replaces it with a real copy.
shutil.copytree(os.path.join(REPO, "plugin"), plugin_out,
ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".pytest_cache", "lib"))
- for pkg in ("tokeneconomizer", "te_live"):
- shutil.copytree(os.path.join(REPO, pkg), os.path.join(plugin_out, "lib", pkg),
- ignore=IGNORE)
+ shutil.copytree(os.path.join(REPO, "tokeneconomizer"),
+ os.path.join(plugin_out, "lib", "tokeneconomizer"), ignore=IGNORE)
with open(os.path.join(REPO, ".claude-plugin", "marketplace.json"), encoding="utf-8") as fh:
market = json.load(fh)
for entry in market.get("plugins", []):
diff --git a/te_live/__init__.py b/te_live/__init__.py
deleted file mode 100644
index 591bf5a..0000000
--- a/te_live/__init__.py
+++ /dev/null
@@ -1,39 +0,0 @@
-"""The live harness: the three mechanisms inside a real coding-agent session, through the hooks
-the agent already exposes.
-
-A sibling of `te_harness`, not a submodule of the core, for the same reason: it reaches an agent
-CLI (`claude -p`, `codex exec`) for its opt-in side calls and catalog probe, and
-`import tokeneconomizer` must not be able to. `te_harness` runs the controller over benchmark
-streams in Docker; `te_live` runs it inside the user's own sessions. The core never learns which.
-
-The research driver (`experiments/scripts/run_experiment.py`) holds one `Economizer` in one process for a
-whole stream of benchmark tasks, launches the sealed agent itself, and applies each decision at
-launch: a prompt prefix, `--disallowed-tools`, a kill-and-resume on the live JSON stream. A
-plugin has none of that. The user launches the agent, and the controller runs only when the agent
-calls one of its hooks -- each call a fresh, short-lived process. This package turns the
-stream-shaped core into that event-shaped one:
-
- * state -- per-repository, per-host state on disk (`paths`, `store`, `config`), so what
- is learned survives between hook processes, sessions and plugin updates;
- * hosts -- one adapter per agent (`hosts`, `transcripts`): hook payloads in, hook
- outputs out, and the agent's own session log turned into a trace the existing
- `trace` seam already reads;
- * mechanisms -- `fold` runs the SAME classes the experiments ran (`PrefixStage`,
- `ToolingStage`) over each finished session, and `guard` replays
- `vendor.spiral.NudgeGuard`'s control flow one tool call at a time;
- * entry points -- `hook.main` (what the plugin's hooks execute) and `cli.main` (`te`).
-
-What changes relative to the measured setting is written down where it changes, because it is
-the difference between a mechanism that ports and a number that does not:
-
- * there is no grader, so the spiral envelope learns from a "turn ended green" proxy;
- * a "task" is a session for injection and untooling, but a prompt-turn for the spiral guard --
- in interactive use the human already segments work into short turns;
- * tool removal is a deny list the user approves, applied from the next session, never a
- mid-session change (that would also invalidate the prompt cache);
- * a nudge is a mid-turn reminder attached to a tool result, not a resumed segment, so its
- effect has to be re-measured rather than inherited from the published rows.
-
-See docs/PLUGIN.md. Stdlib only, like the rest of the core: a hook must start in tens of
-milliseconds and must not depend on anything the user did not install.
-"""
diff --git a/te_live/cli.py b/te_live/cli.py
deleted file mode 100644
index 6eddbf1..0000000
--- a/te_live/cli.py
+++ /dev/null
@@ -1,665 +0,0 @@
-"""`te` -- inspect and steer what TokenEconomizer does in your sessions.
-
- te status what it has learned for this repository, and what it did
- te facts the manual it injects, and the facts still forming
- te untool show the proposed deny list, and the evidence behind it
- te untool apply [ITEM ...] write the proposal (or the named items) to the repository's
- settings: tools (Claude Code), capabilities (Codex) or
- MCP servers (Copilot)
- te untool restore [ITEM ...] remove entries this plugin added
- te untool refresh-catalog record the tool list a fresh session loads (Claude, Copilot)
- te untool measure measure the request with and without the proposal
- te replay [--limit N] [--commit] run the mechanisms over your existing session history
- te config show each mechanism on or off, its settings, the guard's thresholds
- te config set KEY=VALUE ... e.g. `spiral=off`, `inject=on`, `spiral.min_turns=12`
- (this repository; `--global` for every repository)
- te config unset KEY ... back to the next source down (the global file, then default)
- te doctor check the installation
- te --host copilot probe real Copilot sessions in a throwaway repository: does a
- learned fact change what the model does, and what does the
- deny list save (makes model calls; see te_live/probe.py)
-
-`--cwd` picks the repository (default: the current directory) and `--host` the agent
-(claude | codex | copilot | pi; default: `TE_HOST`, else the agent whose shell runs `te`, else
-claude). `replay` is the way to see what the mechanisms would do on
-your own sessions before turning any of them on: it folds your history into a scratch state and
-replays the spiral guard over every prompt-turn, with no LLM call. `--commit` keeps the result as
-the repository's starting state, so learning does not begin from zero.
-"""
-import argparse
-import glob
-import json
-import os
-import re
-import sys
-import tempfile
-import time
-
-from . import accounting, fold, guard, hosts, untool
-from .config import unset_config, write_config
-from .context import LiveContext
-from .paths import state_root
-from .store import Store
-
-
-def _ctx(args, env=None):
- host = hosts.HOSTS[args.host]()
- return LiveContext.build(host, args.cwd, env)
-
-
-def _fmt_tokens(n):
- if n is None:
- return "n/a"
- n = float(n)
- for unit, div in (("B", 1e9), ("M", 1e6), ("k", 1e3)):
- if abs(n) >= div:
- return f"{n / div:.1f}{unit}"
- return f"{n:.0f}"
-
-
-# ---- status / facts ------------------------------------------------------------------------
-def cmd_status(args):
- ctx = _ctx(args)
- cfg = ctx.config
- out = {"repo": ctx.repo.label, "repo_root": ctx.repo.root, "host": ctx.host.name,
- "state": ctx.store.base, "config": cfg.as_dict(), "warnings": cfg.warnings}
- inj = ctx.store.read("injection.json") or {}
- unt = ctx.store.read("untool.json") or {}
- env_tracker = guard.load_envelope(ctx.store, cfg.spiral_aggr, cfg.spiral_thresholds)
- ledger = accounting.summarize(ctx.store.read_lines("ledger.jsonl"))
- out.update({
- "injection": {"profile": cfg.inject_effective,
- "injected_lines": sum(1 for ln in (inj.get("rendered") or "").splitlines()
- if ln.startswith("- ")),
- "sessions_folded": inj.get("sessions", 0)},
- "untool": {"mode": cfg.untool, "sessions": unt.get("sessions", 0),
- "catalog_source": unt.get("catalog_source"),
- "proposal": unt.get("proposal", []),
- "applied": untool.applied(ctx.store)},
- "spiral": {"mode": cfg.spiral, "envelope": env_tracker.envelope,
- "ended_green_turns": len(env_tracker.resolved_turns)},
- "ledger": ledger})
- if args.json:
- print(json.dumps(out, indent=2, default=str))
- return 0
- print(f"TokenEconomizer -- {out['repo']} ({ctx.host.name})")
- print(f" state {out['state']}")
- print(f" config inject={cfg.inject_effective} untool={cfg.untool} spiral={cfg.spiral} "
- f"mode={cfg.mode} paid={cfg.paid} shadow={cfg.shadow}")
- for w in cfg.warnings:
- print(f" warning {w}")
- print(f" sessions {ledger['sessions']} folded, {_fmt_tokens(ledger['effective_tokens'])} "
- f"effective tokens, plugin overhead {_fmt_tokens(ledger['overhead_tokens'])} "
- f"({ledger['overhead_frac']:.1%})")
- i = out["injection"]
- print(f" injection {i['injected_lines']} fact(s) injected at session start "
- f"({i['sessions_folded']} sessions learned from)")
- u = out["untool"]
- if not untool.supports(ctx.host.name):
- print(" untooling not available on this host")
- else:
- src = u["catalog_source"] or "none yet"
- print(f" untooling {u['sessions']} sessions observed, catalog: {src}; "
- f"proposed {untool.unit(ctx.host.name, plural=True)}: "
- f"{', '.join(u['proposal']) or '-'}; applied: {', '.join(u['applied']) or '-'}")
- sp = out["spiral"]
- env_s = f"{sp['envelope']:.0f} tool calls" if sp["envelope"] else "not learned yet"
- print(f" spiral envelope {env_s} ({sp['ended_green_turns']} ended-green turns); "
- f"{ledger['nudges']} nudge(s), {ledger['aborts']} stop(s) over {ledger['turns']} turns")
- return 0
-
-
-def cmd_facts(args):
- ctx = _ctx(args)
- inj = ctx.store.read("injection.json") or {}
- text = inj.get("rendered") or ""
- print(text.rstrip() or "(nothing injected yet: no fact has cleared its firing gate)")
- facts = inj.get("facts") or {}
- rows = [(k, v) for k, v in facts.items() if isinstance(v, dict) and "state" in v]
- if rows:
- print("\nfacts tracked:")
- for k, v in sorted(rows):
- print(f" {v.get('state', '?'):9s} fire={v.get('fire', '?'):>5s} "
- f"{'INJECTED' if v.get('inject') else ' '} {k}")
- return 0
-
-
-# ---- untool --------------------------------------------------------------------------------
-def _untool_show(ctx, unt):
- host = ctx.host.name
- print(f"sessions observed: {unt.get('sessions', 0)} catalog: "
- f"{unt.get('catalog_source') or 'none yet'}")
- print(f"applied ({untool.unit(host, plural=True)} this plugin added to "
- f"{untool.settings_path(ctx.repo.root, host)}): "
- f"{', '.join(untool.applied(ctx.store)) or '-'}")
- print(f"proposed: {', '.join(unt.get('proposal', [])) or '-'}")
- if host == "codex":
- caps = unt.get("capabilities") or {}
- if caps:
- print("capabilities (removable from a project's .codex/config.toml):")
- for c, e in sorted(caps.items()):
- print(f" {c:14s} loaded in {e['loaded_sessions']:3d} sessions, unused in "
- f"{e['unused_sessions']:3d}{' USED (kept)' if e['used'] else ''}")
- trusted = untool.codex_project_trusted(ctx.repo.root)
- if trusted is False:
- print("note: Codex reads a project's .codex/config.toml only in a TRUSTED project; "
- "trust this one in Codex first, or an applied proposal does nothing.")
- return 0
- if host == "copilot":
- servers = unt.get("servers") or {}
- if servers:
- print("MCP servers (Copilot can only remove a whole server):")
- for name, e in sorted(servers.items()):
- state = "USED (kept)" if e["used"] else f"unused in {e['unused_sessions']} sessions"
- print(f" {name:24s} {e['tools']:3d} tools, {state}")
- streaks = unt.get("streaks") or {}
- if streaks and host == "claude":
- print("unused-session streaks (tools never used are candidates once over "
- f"{ctx.config.untool_evidence}):")
- for t, n in sorted(streaks.items(), key=lambda kv: -kv[1])[:30]:
- used = "used" if t in set(unt.get("used_tools", [])) else ""
- print(f" {n:4d} {t} {used}")
- if not unt.get("catalog_source") or unt.get("catalog_source") == "observed":
- print(f"note: without `te --host {host} untool refresh-catalog` only "
- + ("deferred and observed" if host == "claude" else "observed")
- + " tools are known, which leaves the always-loaded tools out of the evidence.")
- return 0
-
-
-def cmd_untool(args):
- ctx = _ctx(args)
- host = ctx.host.name
- if not untool.supports(host):
- print(f"untooling is not available on {host} (it declares only a handful of tools)")
- return 1
- unt = ctx.store.read("untool.json") or {}
- action = args.action
- if action == "show":
- return _untool_show(ctx, unt)
- if action == "apply":
- tools = args.tools or unt.get("proposal", [])
- if not tools:
- print("nothing to apply")
- return 0
- if host == "codex":
- bad = [t for t in tools if t not in untool.CODEX_TOGGLES]
- if bad:
- print(f"not a removable Codex capability: {', '.join(bad)} (choose from "
- f"{', '.join(untool.CODEX_LIVE_CAPABILITIES)})")
- return 2
- try:
- added = untool.apply(ctx.repo.root, tools, ctx.store, host=host)
- except RuntimeError as e:
- print(f"not applied: {e}")
- return 1
- print(f"added: {', '.join(added) or '(already present)'}\n"
- f"in {untool.settings_path(ctx.repo.root, host)} -- takes effect from the next "
- f"session.")
- if host == "copilot" and added:
- if untool.copilot_folder_trusted(ctx.repo.root) is False:
- print("warning: Copilot reads a repository's .github/copilot settings only in a "
- "trusted folder, and this one is not. Trust it (Copilot asks when you "
- "start it here), or the change does nothing.")
- left = untool.verify_copilot(ctx.repo.root, untool.applied(ctx.store))
- if left is not None:
- print("checked with a local capture: " + ", ".join(
- f"{k} {'removed' if not v else f'still loaded ({v} tools)'}"
- for k, v in sorted(left.items())))
- if host == "codex" and added:
- if untool.codex_project_trusted(ctx.repo.root) is False:
- print("warning: this project is not trusted in Codex, which ignores a "
- "project's .codex/config.toml until it is. Trust it (Codex asks when "
- "you start it here), or the change does nothing.")
- state = untool.verify_codex(ctx.repo.root, untool.applied(ctx.store))
- if state:
- print("codex features list: " + ", ".join(
- f"{k}={'on' if v else 'off'}" for k, v in sorted(state.items())))
- return 0
- if action == "restore":
- try:
- removed = untool.restore(ctx.repo.root, ctx.store, args.tools or None, host=host)
- except RuntimeError as e:
- print(f"not restored: {e}")
- return 1
- print(f"removed: {', '.join(removed) or '-'} (from the next session)")
- return 0
- if action == "refresh-catalog":
- if host == "codex":
- print("Codex needs no catalog: its removable capabilities are a fixed set "
- f"({', '.join(untool.CODEX_LIVE_CAPABILITIES)}), read from each session.")
- return 0
- path, tools = untool.refresh_catalog(state_root(), host=host)
- print(f"{len(tools)} tools recorded in {path}:\n " + ", ".join(tools))
- return 0
- if action == "measure":
- tools = args.tools or unt.get("proposal", []) or untool.applied(ctx.store)
- if not tools:
- print("no proposal to measure")
- return 1
- res = untool.measure(tools, host=host)
- print(json.dumps(res, indent=2))
- return 0
- return 2
-
-
-# ---- config / doctor / fold ----------------------------------------------------------------
-def _config_view(cfg):
- """The settings as a person reads them: each mechanism on or off, its knobs, and the guard's
- thresholds with the numbers a `spiral.<name>` setting would replace."""
- d = cfg.as_dict()
- pinned = d.pop("spiral_thresholds")
- return {
- "enabled": d.pop("enabled"),
- "facts (inject)": {"state": "off" if cfg.inject == "off" else "on",
- "inject": d.pop("inject"),
- "inject_max_facts": d.pop("inject_max_facts"),
- "inject_max_tokens": d.pop("inject_max_tokens"),
- "propose_every": d.pop("propose_every")},
- "unused tools (untool)": {"state": "off" if cfg.untool == "off" else "on",
- "untool": d.pop("untool"),
- "untool_evidence": d.pop("untool_evidence")},
- "stuck-turn guard (spiral)": {
- "state": "off" if cfg.spiral == "off" else "on",
- "spiral": d.pop("spiral"), "spiral_aggr": d.pop("spiral_aggr"),
- "spiral_nudges": d.pop("spiral_nudges"),
- "thresholds": guard.base_thresholds(cfg.spiral_aggr, pinned),
- "pinned": sorted(pinned)},
- "other": d,
- "warnings": cfg.warnings,
- }
-
-
-def cmd_config(args):
- ctx = _ctx(args)
- if args.action == "show":
- print(json.dumps(_config_view(ctx.config), indent=2))
- return 0
- path = (os.path.join(ctx.root, "config.json") if args.globally
- else os.path.join(os.path.dirname(ctx.store.base), "config.json"))
- if args.action == "unset":
- try:
- cur = unset_config(path, [k.strip() for k in args.pairs])
- except ValueError as e:
- print(f"rejected: {e}")
- return 2
- print(f"{path}: {json.dumps(cur, sort_keys=True)}")
- return 0
- updates = {}
- for kv in args.pairs:
- if "=" not in kv:
- print(f"expected KEY=VALUE, got {kv!r}")
- return 2
- k, v = kv.split("=", 1)
- updates[k.strip()] = v.strip()
- if not updates:
- print("nothing to set: give KEY=VALUE (see `te config show` for the keys)")
- return 2
- try:
- cur = write_config(path, updates)
- except ValueError as e:
- print(f"rejected: {e}")
- return 2
- print(f"{path}: {json.dumps(cur, sort_keys=True)}")
- print("applies from the next hook call; a new fact-size cap applies once the next session "
- "has been folded")
- return 0
-
-
-def cmd_fold(args):
- ctx = _ctx(args)
- sids = args.session or fold.pending_sessions(ctx)
- for sid in sids:
- rec = fold.fold_session(ctx, sid)
- if rec is not None and args.verbose:
- print(json.dumps(rec, default=str))
- return 0
-
-
-def cmd_judge(args):
- """The detached half of the paid stuck judge (see te_live/judge.py); not for people."""
- from . import judge
- judge.run_job(_ctx(args), args.session, args.job)
- return 0
-
-
-def cmd_probe(args):
- if args.host != "copilot":
- print("the probe runs on Copilot only so far: `te --host copilot probe`")
- return 2
- from . import probe
- return probe.run(sessions=args.sessions, model=args.model, keep=args.keep)
-
-
-def cmd_doctor(args):
- ok = sys.version_info >= (3, 10)
- print(f"python {sys.version.split()[0]} {'ok' if ok else '(needs >= 3.10)'}")
- root = state_root()
- try:
- os.makedirs(root, exist_ok=True)
- probe = os.path.join(root, ".write-test")
- open(probe, "w").close()
- os.remove(probe)
- print(f"state root {root} (writable)")
- except OSError as e:
- print(f"state root {root} NOT writable: {e}")
- ok = False
- for host in ("claude", "copilot"):
- cat = os.path.join(root, "hosts", host, "catalog.json")
- print(f"{host:11s} catalog {'present' if os.path.exists(cat) else 'not probed'}")
- from urllib.parse import urlparse
- from .sidecall import copilot_model
- base = os.environ.get("COPILOT_PROVIDER_BASE_URL")
- route = (f"BYOK {os.environ.get('COPILOT_PROVIDER_TYPE') or 'openai'} at "
- f"{urlparse(base).netloc or base}" if base else "Copilot subscription")
- print(f"copilot {route}; side calls and `probe` use model "
- f"{copilot_model() or '(Copilot default)'}")
- ctrust = untool.copilot_folder_trusted(args.cwd)
- if ctrust is not None:
- print(f"copilot this folder is {'trusted' if ctrust else 'NOT trusted'} (an untrusted "
- f"folder's .github/copilot settings are ignored)")
- trusted = untool.codex_project_trusted(args.cwd)
- if trusted is not None:
- print(f"codex this project is {'trusted' if trusted else 'NOT trusted'} "
- f"(an untrusted project's .codex/config.toml is ignored)")
- log = os.path.join(root, "errors.log")
- if os.path.exists(log):
- tail = open(log, encoding="utf-8", errors="replace").read().splitlines()[-6:]
- print("errors.log (tail):\n " + "\n ".join(tail))
- else:
- print("errors.log none")
- return 0 if ok else 1
-
-
-# ---- replay --------------------------------------------------------------------------------
-def _claude_projects_dir():
- base = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.join(os.path.expanduser("~"), ".claude")
- return os.path.join(base, "projects")
-
-
-def _within(path, root):
- path, root = os.path.realpath(path or ""), os.path.realpath(root)
- return path == root or path.startswith(root + os.sep)
-
-
-def _first_cwd(path, limit=200):
- for i, line in enumerate(open(path, encoding="utf-8", errors="replace")):
- if i > limit:
- break
- try:
- d = json.loads(line)
- except ValueError:
- continue
- if isinstance(d.get("cwd"), str):
- return d["cwd"]
- p = d.get("payload")
- if isinstance(p, dict) and isinstance(p.get("cwd"), str):
- return p["cwd"]
- return None
-
-
-def find_history(ctx, limit=0):
- """[(session_id, transcript)] of this repository's past sessions, oldest first."""
- found = []
- if ctx.host.name == "claude":
- slug = re.sub(r"[^A-Za-z0-9]", "-", os.path.realpath(ctx.repo.root))
- for d in glob.glob(os.path.join(_claude_projects_dir(), "*")):
- if not os.path.basename(d).startswith(slug):
- continue
- for f in glob.glob(os.path.join(d, "*.jsonl")):
- if _within(_first_cwd(f), ctx.repo.root):
- found.append((os.path.splitext(os.path.basename(f))[0], f))
- elif ctx.host.name == "pi":
- from .transcripts import pi_session_header
- agent = os.environ.get("PI_CODING_AGENT_DIR") or os.path.join(
- os.path.expanduser("~"), ".pi", "agent")
- for f in glob.glob(os.path.join(agent, "sessions", "*", "*.jsonl")):
- head = pi_session_header(f)
- if head.get("id") and _within(head.get("cwd"), ctx.repo.root):
- found.append((head["id"], f))
- elif ctx.host.name == "copilot":
- from .transcripts import copilot_session_meta
- for f in glob.glob(os.path.join(hosts.copilot_home(), "session-state", "*",
- "events.jsonl")):
- meta = copilot_session_meta(f)
- if meta.get("session_id") and _within(meta.get("cwd"), ctx.repo.root):
- found.append((meta["session_id"], f))
- else:
- home = os.environ.get("CODEX_HOME") or os.path.join(os.path.expanduser("~"), ".codex")
- for f in glob.glob(os.path.join(home, "sessions", "**", "rollout-*.jsonl"),
- recursive=True):
- if _within(_first_cwd(f), ctx.repo.root):
- found.append((os.path.basename(f)[len("rollout-"):-len(".jsonl")], f))
- found.sort(key=lambda sf: os.path.getmtime(sf[1]))
- return found[-limit:] if limit else found
-
-
-def _claude_turns(path):
- """Prompt-turns of a Claude Code transcript: [(calls, effective_tokens)], where calls are
- (name, args, result, exit). Usage is counted once per assistant message id, as the ledger
- counts it (the transcript repeats a message's usage on every content block)."""
- from tokeneconomizer.vendor import spiral
- turns, cur, pend, usage = [], None, {}, {}
-
- def close():
- if cur is not None and (cur or usage):
- eff = sum(accounting.effective(u)[0] or 0 for u in usage.values())
- turns.append((cur, eff))
-
- for line in open(path, encoding="utf-8", errors="replace"):
- try:
- d = json.loads(line)
- except ValueError:
- continue
- if d.get("type") == "user" and not d.get("isMeta") and not d.get("isSidechain"):
- c = (d.get("message") or {}).get("content")
- kinds = ({b.get("type") for b in c if isinstance(b, dict)}
- if isinstance(c, list) else set())
- if (isinstance(c, str) and c.strip() and not c.startswith("<")) or (
- "text" in kinds and "tool_result" not in kinds):
- close()
- cur, pend, usage = [], {}, {}
- continue
- if cur is None:
- continue
- msg = d.get("message") if isinstance(d.get("message"), dict) else {}
- if d.get("type") == "assistant" and isinstance(msg.get("usage"), dict):
- usage[msg.get("id") or len(usage)] = dict(msg["usage"], model=msg.get("model"))
- for name, args, result in spiral.completed_calls(line, pend):
- cur.append((name, args, result, None))
- close()
- return turns
-
-
-def _codex_turns(path):
- from .transcripts import _rollout_item_to_exec
- turns, order = {}, []
- for line in open(path, encoding="utf-8", errors="replace"):
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- p = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
- if ev.get("type") != "event_msg" or p.get("type") != "item_completed":
- continue
- item = _rollout_item_to_exec(p.get("item") or {}) or {}
- tid = p.get("turn_id") or "?"
- if tid not in turns:
- turns[tid] = []
- order.append(tid)
- if item.get("type") == "command_execution":
- turns[tid].append(("bash", {"command": item.get("command") or ""},
- item.get("aggregated_output") or "", item.get("exit_code")))
- elif item.get("type") == "file_change":
- paths = [c.get("path") for c in item.get("changes") or [] if isinstance(c, dict)]
- turns[tid].append(("apply_patch", {"path": paths[0] if paths else ""}, "", None))
- return [(turns[t], None) for t in order if turns[t]]
-
-
-def _session_turns(host, path):
- """Prompt-turns of one session log, whichever host wrote it."""
- if host.name == "claude":
- return _claude_turns(path)
- if host.name == "copilot":
- from .transcripts import copilot_turns
- return [(calls, None) for calls in copilot_turns(path)]
- if host.name == "pi":
- from .transcripts import pi_session_to_claude
- with tempfile.TemporaryDirectory(prefix="te-pi-") as d:
- out = os.path.join(d, "trace.jsonl")
- return _claude_turns(out) if pi_session_to_claude(path, out) is not None else []
- return _codex_turns(path)
-
-
-def cmd_replay(args):
- real = _ctx(args)
- history = find_history(real, args.limit)
- if not history:
- print(f"no {real.host.name} session history found for {real.repo.root}")
- return 1
- scratch = None
- ctx = real
- if not args.commit:
- scratch = tempfile.mkdtemp(prefix="te-replay-")
- ctx = LiveContext(host=real.host, repo=real.repo, root=real.root,
- store=Store(os.path.join(scratch, real.host.name)),
- config=real.config, env=dict(real.env, TE_FOLD_SYNC="1"))
- t0 = time.time()
- totals = {"turns": 0, "calls": 0, "nudge_turns": 0, "stop_turns": 0, "post_fire_calls": 0}
- turn_cost, turn_tokens = [], []
- for i, (sid, path) in enumerate(history):
- fold.fold_session(ctx, sid, transcript_path=path)
- turns = _session_turns(real.host, path)
- for calls, eff in turns:
- if eff is not None:
- turn_tokens.append(eff)
- if not calls:
- continue
- g = guard.TurnGuard(turn_key=f"{sid}:{totals['turns']}")
- ov = real.config.spiral_thresholds
- tracker = guard.load_envelope(ctx.store, real.config.spiral_aggr, ov)
- env_v, thr = tracker.envelope, guard.thresholds(tracker, ov)
- fired_at = None
- for j, (name, a, r, code) in enumerate(calls):
- d = g.fold(name, a, r, code, envelope=env_v, thr=thr,
- nudge_budget=real.config.spiral_nudges)
- if d and d[0] == "nudge":
- g.after_nudge()
- totals["nudge_turns"] += 1 if fired_at is None else 0
- fired_at = j if fired_at is None else fired_at
- elif d and d[0] == "abort":
- totals["stop_turns"] += 1
- fired_at = j if fired_at is None else fired_at
- if fired_at is not None:
- totals["post_fire_calls"] += len(calls) - fired_at - 1
- totals["turns"] += 1
- totals["calls"] += len(calls)
- turn_cost.append(len(calls))
- if g.cum_turns:
- guard.record_turn(ctx.store, g, level=real.config.spiral_aggr,
- overrides=real.config.spiral_thresholds)
- if args.verbose:
- print(f" [{i + 1}/{len(history)}] {sid} {len(turns)} turns")
- led = accounting.summarize(ctx.store.read_lines("ledger.jsonl"))
- inj = ctx.store.read("injection.json") or {}
- unt = ctx.store.read("untool.json") or {}
- tracker = guard.load_envelope(ctx.store, real.config.spiral_aggr,
- real.config.spiral_thresholds)
- facts = {k: v for k, v in (inj.get("facts") or {}).items() if isinstance(v, dict)}
- injected = [k for k, v in facts.items() if v.get("inject")]
- forming = [k for k, v in facts.items() if v.get("state") in ("CANDIDATE", "ACTIVE")
- and not v.get("inject")]
- span = (time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(history[0][1]))),
- time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(history[-1][1]))))
- print(f"TokenEconomizer replay -- {real.repo.label} ({real.host.name}), "
- f"{len(history)} sessions, {span[0]} -> {span[1]} ({time.time() - t0:.0f}s)")
- tail = ""
- if turn_tokens and sum(turn_tokens):
- top = sorted(turn_tokens, reverse=True)[:max(1, len(turn_tokens) // 10)]
- tail = (f"; the costliest 10% of prompt-turns carry "
- f"{sum(top) / sum(turn_tokens):.0%} of it")
- print(f" cost {_fmt_tokens(led['effective_tokens'])} effective tokens over "
- f"{led['priced_sessions']} priced sessions{tail}")
- print(f" injection {len(injected)} fact(s) would be injected now"
- + (f": {', '.join(injected)}" if injected else "")
- + (f"; {len(forming)} forming: {', '.join(forming[:5])}" if forming else ""))
- if untool.supports(real.host.name):
- print(f" untooling catalog {unt.get('catalog_source') or 'none'}; would propose "
- f"{untool.unit(real.host.name, plural=True)}: "
- f"{', '.join(unt.get('proposal') or []) or '-'}")
- turns = max(totals["turns"], 1)
- print(f" spiral {totals['turns']} prompt-turns (median "
- f"{sorted(turn_cost)[len(turn_cost) // 2] if turn_cost else 0} tool calls); guard "
- f"would nudge {totals['nudge_turns']} ({totals['nudge_turns'] / turns:.1%}) and stop "
- f"{totals['stop_turns']}; {totals['post_fire_calls']} tool calls came after a fire "
- f"({totals['post_fire_calls'] / max(totals['calls'], 1):.1%} of all calls)")
- env_s = f"{tracker.envelope:.0f}" if tracker.envelope else "n/a"
- print(f" learned envelope {env_s} tool calls from "
- f"{len(tracker.resolved_turns)} ended-green turns (heuristic gate; no judge)")
- if scratch:
- print(f" (scratch state in {scratch}; `te replay --commit` keeps it as the starting "
- f"state)")
- return 0
-
-
-def build_parser():
- ap = argparse.ArgumentParser(prog="te", description=__doc__,
- formatter_class=argparse.RawDescriptionHelpFormatter)
- ap.add_argument("--cwd", default=os.getcwd())
- ap.add_argument("--host", default=hosts.default_host(), choices=sorted(hosts.HOSTS))
- # The same two options are accepted after the subcommand too (`te fold --host codex ...`).
- # SUPPRESS keeps a subcommand that omits them from overwriting the top-level values.
- common = argparse.ArgumentParser(add_help=False)
- common.add_argument("--cwd", default=argparse.SUPPRESS)
- common.add_argument("--host", default=argparse.SUPPRESS, choices=sorted(hosts.HOSTS))
- sub = ap.add_subparsers(dest="cmd", required=True)
-
- def add(name):
- return sub.add_parser(name, parents=[common])
-
- p = add("status")
- p.add_argument("--json", action="store_true")
- p.set_defaults(fn=cmd_status)
- add("facts").set_defaults(fn=cmd_facts)
- p = add("untool")
- p.add_argument("action", nargs="?", default="show",
- choices=("show", "apply", "restore", "refresh-catalog", "measure"))
- p.add_argument("tools", nargs="*")
- p.set_defaults(fn=cmd_untool)
- p = add("replay")
- p.add_argument("--limit", type=int, default=0)
- p.add_argument("--commit", action="store_true")
- p.add_argument("--verbose", action="store_true")
- p.set_defaults(fn=cmd_replay)
- p = add("config")
- p.add_argument("action", nargs="?", default="show", choices=("show", "set", "unset"))
- p.add_argument("pairs", nargs="*")
- p.add_argument("--global", dest="globally", action="store_true")
- p.set_defaults(fn=cmd_config)
- p = add("fold")
- p.add_argument("--session", action="append")
- p.add_argument("--verbose", action="store_true")
- p.set_defaults(fn=cmd_fold)
- p = add("judge")
- p.add_argument("--session", required=True)
- p.add_argument("--job", required=True)
- p.set_defaults(fn=cmd_judge)
- add("doctor").set_defaults(fn=cmd_doctor)
- p = add("probe")
- p.add_argument("--sessions", type=int, default=6)
- p.add_argument("--model", default=None)
- p.add_argument("--keep", action="store_true")
- p.set_defaults(fn=cmd_probe)
- return ap
-
-
-def main(argv=None):
- args = build_parser().parse_args(argv)
- try:
- return args.fn(args) or 0
- finally:
- from .paths import secure_root
- secure_root()
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/te_live/config.py b/te_live/config.py
deleted file mode 100644
index 54be66f..0000000
--- a/te_live/config.py
+++ /dev/null
@@ -1,261 +0,0 @@
-"""Live configuration: which mechanisms act in real sessions, and how far each may go.
-
-The defaults are the conservative end of every switch, chosen from what the local replay of real
-sessions showed (docs/PLUGIN.md) rather than from the benchmark arms:
-
- * inject = "envfacts" -- the LLM-free layer only. The paid proposer (`envfacts+distiller`,
- `distiller`) is opt-in, and refused unless `paid` is also true;
- * untool = "propose" -- evidence is gathered and a deny list is proposed, but nothing is
- written to the user's settings until they approve it. "auto"
- applies proposals as they form;
- * spiral = "nudge" -- at most one mid-turn redirect per prompt-turn. "guard" also stops a
- turn that keeps spinning after the nudge, and only in headless mode;
- interactive sessions get a notice instead, because there a person is
- already the abort;
- * paid = False -- no mechanism makes an LLM call of its own. Every paid call that is
- allowed is charged to the session ledger, as the experiments charge
- optimizer_tokens to an arm;
- * shadow = False -- with True, every decision is computed and logged but none reaches
- the agent. The way to measure a mechanism before trusting it.
-
-Each of the three mechanisms also takes a plain `on` / `off` (`on` = the value above), and each
-has hyperparameters a person can set by hand:
-
- * inject_max_facts, inject_max_tokens -- size caps on the injected fact block;
- * propose_every -- sessions between paid proposer runs;
- * untool_evidence -- unused sessions before a tool is proposed;
- * spiral_aggr -- the guard's threshold preset;
- * spiral_nudges -- redirects per prompt-turn before it stops/notifies;
- * spiral.<name> -- one guard threshold, pinned over the preset and over
- what the repository's history learned (SPIRAL_KEYS).
-
-Sources, lowest precedence first: built-in defaults, `<root>/config.json`, the repository's
-`config.json`, then environment variables (`TE_INJECT`, `TE_UNTOOL`, `TE_SPIRAL`, `TE_MODE`,
-`TE_PAID`, `TE_SHADOW`, `TE_DISABLE`, and one per hyperparameter; `TE_SPIRAL_THRESHOLDS` takes
-JSON). An invalid value is ignored with a warning recorded in the result rather than raised: a
-typo in a config file must not break the agent's hooks.
-"""
-import json
-import os
-from dataclasses import asdict, dataclass, field, fields
-
-INJECT = ("off", "envfacts", "envfacts+distiller", "distiller")
-UNTOOL = ("off", "propose", "auto")
-SPIRAL = ("off", "nudge", "guard")
-MODES = ("auto", "interactive", "headless")
-AGGR = ("conservative", "default", "aggressive")
-
-# What `on` turns each mechanism to, and the words read as on / off.
-ON_VALUE = {"inject": "envfacts", "untool": "propose", "spiral": "nudge"}
-_ON = ("on", "true", "yes", "1", "enable", "enabled")
-_OFF = ("off", "false", "no", "0", "disable", "disabled")
-
-# The spiral guard's thresholds a person may pin (`spiral.<name>=<value>`), with their type and
-# range. They are the keys of `tokeneconomizer.vendor.spiral.DEFAULT_THRESHOLDS`; a turn's
-# "turns" are its tool calls here.
-SPIRAL_KEYS = {
- "min_turns": (int, 1, None, "tool calls in a turn before it can count as stuck"),
- "edit_churn": (int, 1, None, "edits to one file that count as churn"),
- "distinct_edit_files": (int, 1, None, "files edited that count as scattered"),
- "error_outputs": (int, 1, None, "failing tool results that count as sustained errors"),
- "stagnation": (float, 0.0, 1.0, "share of failures that repeat an earlier one"),
- "envelope_pct": (float, 1.0, 100.0, "percentile of this repository's ended-green turns"),
- "envelope_margin": (float, 0.1, None, "multiplier on that percentile: the envelope"),
- "envelope_min_samples": (int, 1, None, "ended-green turns needed before the envelope is used"),
- "backstop_mult": (float, 0.1, None, "stuck past this multiple of the envelope: redirect, "
- "then stop"),
- "judge_confidence": (float, 0.0, 1.0, "paid judge confidence needed to act (paid=true)"),
- "gate_min_turns": (int, 1, None, "tool calls before the paid judge is consulted"),
- "gate_error_outputs": (int, 1, None, "failing results that wake the paid judge early"),
-}
-
-
-@dataclass
-class LiveConfig:
- enabled: bool = True
- mode: str = "auto"
- inject: str = "envfacts"
- inject_max_facts: int = 4
- inject_max_tokens: int = 150
- propose_every: int = 5
- untool: str = "propose"
- untool_evidence: int = 5
- spiral: str = "nudge"
- spiral_aggr: str = "default"
- spiral_nudges: int = 1
- spiral_thresholds: dict = field(default_factory=dict)
- paid: bool = False
- paid_model: str = ""
- shadow: bool = False
- vocabulary: str = "auto"
- warnings: list = field(default_factory=list)
-
- _CHOICES = {"mode": MODES, "inject": INJECT, "untool": UNTOOL, "spiral": SPIRAL,
- "spiral_aggr": AGGR, "vocabulary": ("auto", "python-git", "node-web")}
-
- def as_dict(self):
- d = asdict(self)
- d.pop("warnings", None)
- return d
-
- def set(self, key, value, source="?"):
- """Apply one setting with type coercion and validation; False if rejected."""
- if key.startswith("spiral."):
- return self._set_threshold(key.split(".", 1)[1], value, source)
- names = {f.name: f for f in fields(self) if f.name != "warnings"}
- if key not in names:
- self.warnings.append(f"{source}: unknown key {key!r}")
- return False
- if key == "spiral_thresholds":
- if not isinstance(value, dict):
- self.warnings.append(f"{source}: spiral_thresholds must be an object")
- return False
- return all([self._set_threshold(k, v, source) for k, v in value.items()])
- if key in ON_VALUE and isinstance(value, (str, bool, int)):
- word = str(value).strip().lower()
- if word in _ON:
- value = ON_VALUE[key]
- elif word in _OFF:
- value = "off"
- cur = getattr(self, key)
- try:
- if isinstance(cur, bool):
- v = value if isinstance(value, bool) else str(value).strip().lower() in (
- "1", "true", "yes", "on")
- elif isinstance(cur, int):
- v = int(value)
- if v < 1:
- raise ValueError("must be >= 1")
- else:
- v = str(value).strip()
- except (TypeError, ValueError) as e:
- self.warnings.append(f"{source}: {key}={value!r} rejected ({e})")
- return False
- choices = self._CHOICES.get(key)
- if choices and v not in choices:
- self.warnings.append(f"{source}: {key}={v!r} not one of {choices}")
- return False
- setattr(self, key, v)
- return True
-
- def _set_threshold(self, name, value, source):
- spec = SPIRAL_KEYS.get(name)
- if spec is None:
- self.warnings.append(f"{source}: unknown spiral threshold {name!r} "
- f"(one of {', '.join(SPIRAL_KEYS)})")
- return False
- kind, lo, hi, _ = spec
- try:
- if isinstance(value, bool):
- raise ValueError("not a number")
- v = kind(float(value)) if kind is int and float(value).is_integer() else kind(value)
- except (TypeError, ValueError) as e:
- self.warnings.append(f"{source}: spiral.{name}={value!r} rejected ({e})")
- return False
- if (lo is not None and v < lo) or (hi is not None and v > hi):
- rng = f">= {lo}" if hi is None else f"between {lo} and {hi}"
- self.warnings.append(f"{source}: spiral.{name}={v!r} rejected (must be {rng})")
- return False
- self.spiral_thresholds[name] = v
- return True
-
- @property
- def inject_effective(self):
- """The injection profile that will actually run: a paid profile without `paid` falls
- back to the free layer, and says so in `warnings` when the config is loaded."""
- if self.inject in ("envfacts+distiller", "distiller") and not self.paid:
- return "envfacts"
- return self.inject
-
-
-_ENV = {"TE_MODE": "mode", "TE_INJECT": "inject", "TE_UNTOOL": "untool", "TE_SPIRAL": "spiral",
- "TE_PAID": "paid", "TE_SHADOW": "shadow", "TE_PROPOSE_EVERY": "propose_every",
- "TE_UNTOOL_EVIDENCE": "untool_evidence", "TE_SPIRAL_AGGR": "spiral_aggr",
- "TE_PAID_MODEL": "paid_model", "TE_VOCABULARY": "vocabulary",
- "TE_INJECT_MAX_FACTS": "inject_max_facts", "TE_INJECT_MAX_TOKENS": "inject_max_tokens",
- "TE_SPIRAL_NUDGES": "spiral_nudges"}
-
-
-def _read(path):
- try:
- with open(path, encoding="utf-8") as fh:
- obj = json.load(fh)
- return obj if isinstance(obj, dict) else {}
- except (OSError, ValueError):
- return {}
-
-
-def load_config(root, repo_dir=None, env=None):
- """Merge defaults, the global file, the repository file and the environment."""
- env = os.environ if env is None else env
- cfg = LiveConfig()
- for label, path in (("global", os.path.join(root, "config.json")),
- ("repo", os.path.join(repo_dir, "config.json") if repo_dir else None)):
- if path:
- for k, v in _read(path).items():
- cfg.set(k, v, source=f"{label} {path}")
- for var, key in _ENV.items():
- if env.get(var) not in (None, ""):
- cfg.set(key, env[var], source=var)
- if env.get("TE_SPIRAL_THRESHOLDS"):
- try:
- cfg.set("spiral_thresholds", json.loads(env["TE_SPIRAL_THRESHOLDS"]),
- source="TE_SPIRAL_THRESHOLDS")
- except ValueError:
- cfg.warnings.append("TE_SPIRAL_THRESHOLDS: not valid JSON")
- if str(env.get("TE_DISABLE", "")).strip().lower() in ("1", "true", "yes", "on"):
- cfg.enabled = False
- if cfg.inject != cfg.inject_effective:
- cfg.warnings.append(f"inject={cfg.inject!r} makes paid calls but paid=false; "
- f"running {cfg.inject_effective!r}")
- return cfg
-
-
-def write_config(path, updates):
- """Merge `updates` into the JSON config at `path` (validating each key first).
-
- A `spiral.<name>` key lands in the file's `spiral_thresholds` object."""
- probe = LiveConfig()
- bad = [k for k, v in updates.items() if not probe.set(k, v, source="te config")]
- if bad:
- raise ValueError("; ".join(probe.warnings))
- current = _read(path)
- for k in updates:
- if k.startswith("spiral."):
- name = k.split(".", 1)[1]
- current.setdefault("spiral_thresholds", {})[name] = probe.spiral_thresholds[name]
- elif k == "spiral_thresholds":
- current.setdefault("spiral_thresholds", {}).update(probe.spiral_thresholds)
- else:
- current[k] = getattr(probe, k)
- _write(path, current)
- return current
-
-
-def unset_config(path, keys):
- """Remove keys from the JSON config at `path`, so the next source down applies again.
-
- `spiral.<name>` removes one threshold; `spiral_thresholds` removes them all."""
- known = {f.name for f in fields(LiveConfig) if f.name != "warnings"}
- bad = [k for k in keys if k not in known and not (
- k.startswith("spiral.") and k.split(".", 1)[1] in SPIRAL_KEYS)]
- if bad:
- raise ValueError(f"unknown key(s): {', '.join(bad)}")
- current = _read(path)
- for k in keys:
- if k.startswith("spiral."):
- (current.get("spiral_thresholds") or {}).pop(k.split(".", 1)[1], None)
- if not current.get("spiral_thresholds"):
- current.pop("spiral_thresholds", None)
- else:
- current.pop(k, None)
- _write(path, current)
- return current
-
-
-def _write(path, obj):
- os.makedirs(os.path.dirname(path), exist_ok=True)
- tmp = path + ".tmp"
- with open(tmp, "w", encoding="utf-8") as fh:
- json.dump(obj, fh, indent=2, sort_keys=True)
- os.replace(tmp, path)
diff --git a/te_live/guard.py b/te_live/guard.py
deleted file mode 100644
index 3ffb69f..0000000
--- a/te_live/guard.py
+++ /dev/null
@@ -1,535 +0,0 @@
-"""The spiral guard, one tool call at a time.
-
-`vendor.spiral.NudgeGuard` is the live controller the experiments ran: it folds each completed
-tool call of a streamed rollout into a `SpiralState`, asks `assess_abort` (cheap gate -> sampled
-judge -> envelope fallback) whether the trajectory is stuck, and answers the first stuck
-detection with a nudge and a later one with an abort. It does that inside one process that owns
-the stream. Here every tool call arrives as a separate PostToolUse hook process, so `TurnGuard`
-is the same control flow with its state on disk between calls. The decisions are the vendored
-ones -- `SpiralState.update`, `is_stuck`, `assess_abort`, `nudge_text`, the cumulative backstop,
-`nudge_on_ambiguous` -- not a re-implementation of their thresholds.
-
-Three things differ, each because the setting does:
-
- * The unit is a PROMPT-TURN (one user prompt to the agent's stop), not a benchmark task. In
- interactive use the person already splits work into short turns (median 5 tool calls on the
- local replay), and a whole session folded as one trajectory looks stuck merely by being long.
- * The nudge is delivered mid-turn, attached to the tool result, instead of by killing the agent
- and resuming it with a continuation prompt. The per-segment reset that gives the agent a fair
- re-assessment after a nudge is kept: `after_nudge` starts a fresh `SpiralState`, exactly as
- `NudgeGuard.continuation` does.
- * There is no grader, so the per-repository envelope learns from turns that ENDED GREEN: the
- agent stopped on its own, the guard did not abort it, and no verification after its last
- edit failed (`resolved_proxy`). The envelope is the same `EnvelopeTracker`, fed that proxy.
-"""
-import re
-import shlex
-import time
-
-from tokeneconomizer.vendor import spiral
-
-_SLOTS = spiral.SpiralState.__slots__
-
-# What counts as running the project's own checks, across ecosystems. Broader than the vendored
-# `_TEST_RUN_RE` (which is the SWE-bench/Python vocabulary the guard's thresholds were tuned
-# on); used ONLY for the ended-green proxy, never to change what `SpiralState` counts.
-VERIFY_RE = re.compile(
- r"(?i)(?:^|[\s;&|(])(?:pytest|py\.test|tox|nox|python\d?(?:\.\d+)?\s+-m\s+(?:pytest|unittest)|"
- r"manage\.py\s+test|runtests(?:\.py)?|jest|vitest|mocha|ava|playwright\s+test|"
- r"(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test|go\s+test|cargo\s+(?:test|nextest)|"
- r"(?:mvn|mvnw|\./mvnw)\s+(?:\S+\s+)*test|(?:gradle|gradlew|\./gradlew)\s+(?:\S+\s+)*test|"
- r"make\s+(?:test|check)|ctest|rspec|phpunit|dotnet\s+test|swift\s+test|mix\s+test|"
- r"deno\s+test|bazel\s+test|(?:\./)?bin/test)\b")
-_EDIT = {"edit", "create"}
-
-
-# ---- edits made through the shell ----------------------------------------------------------
-# The vendored SpiralState counts an edit only when an edit TOOL makes it (Edit/Write/
-# str_replace). An agent that edits through Bash -- `sed -i`, `perl -pi`, a redirect or `tee`
-# into a source file, an inline Python script that writes the file back, `patch`/`git apply` --
-# looked like one that had edited nothing. Sonnet 5.5 edits that way; in the user-simulation
-# pilot the paid judge's digest read `edit_churn=0`, and its nudge told the agent "no files have
-# actually been edited" when four had. Such edits are folded in AFTER the vendored update, so its
-# counts and thresholds are untouched and the call still counts once.
-_HEREDOC_START = re.compile(r"<<-?\s*(['\"]?)([A-Za-z_]\w*)\1")
-_OPS = {"&&", "||", ";", ";;", "|", "|&", "&", "\n", "(", ")"}
-_OUT = {">", ">>", ">|", "&>", "&>>"} # redirects that write their operand
-_SKIP_OPERAND = {"<", "<<", "<<<", "<&", ">&", "<>"} # input, heredoc tags, fd duplication
-# Redirect and `tee` targets count only when they look like source, so `> out.log` or
-# `| tee /tmp/run.txt` -- capturing output -- is not mistaken for an edit.
-_SOURCE_FILE = re.compile(
- r"\.(?:py|pyi|pyx|pxd|js|jsx|mjs|cjs|ts|tsx|rs|go|java|kt|kts|scala|c|cc|cpp|cxx|h|hh|hpp|"
- r"rb|php|cs|swift|m|mm|sh|bash|zsh|lua|jl|ex|exs|erl|hs|ml|clj|sql|toml|ya?ml|json|cfg|ini|"
- r"conf|md|rst|html?|css|scss|vue|svelte|xml|gradle|properties|in)$", re.I)
-_PYTHON = re.compile(r"(?:^|[\s/;&|(])python\d?(?:\.\d+)?\b")
-_PY_OPEN_LIT = re.compile(r"open\(\s*(['\"])([^'\"\n]+)\1\s*,\s*(['\"])([^'\"]*)\3")
-_PY_OPEN_VAR = re.compile(r"open\(\s*([A-Za-z_]\w*)\s*,\s*(['\"])([^'\"]*)\2")
-_PY_WRITE_PATH_LIT = re.compile(
- r"(?:pathlib\.)?Path\(\s*(['\"])([^'\"\n]+)\1\s*\)\.write_(?:text|bytes)\(")
-_PY_WRITE_PATH_VAR = re.compile(r"\b([A-Za-z_]\w*)\.write_(?:text|bytes)\(")
-
-
-def _not_scratch(path):
- return bool(path) and not path.startswith(("/dev/", "/proc/", "/tmp/"))
-
-
-def _unquote(t):
- return t[1:-1] if len(t) >= 2 and t[0] == t[-1] and t[0] in "'\"" else t
-
-
-def _split_heredocs(cmd):
- """(the command's shell text without heredoc bodies, the bodies)."""
- shell, bodies, tag, body = [], [], None, []
- for line in cmd.split("\n"):
- if tag is not None:
- if line.strip() == tag:
- bodies.append("\n".join(body))
- tag, body = None, []
- else:
- body.append(line)
- continue
- shell.append(line)
- m = _HEREDOC_START.search(line)
- if m:
- tag = m.group(2)
- if tag is not None:
- bodies.append("\n".join(body))
- return "\n".join(shell), bodies
-
-
-def _tokens(text):
- """Shell words and operators. Quotes stay on quoted words, so a quoted `'>'` or `'|'` is
- never read as an operator; ValueError on unbalanced quotes."""
- lex = shlex.shlex(text, posix=False, punctuation_chars="();<>|&\n")
- lex.whitespace = " \t\r"
- lex.whitespace_split = True
- return list(lex)
-
-
-def _commands(shell):
- """(simple commands as unquoted word lists, the files their redirects write)."""
- try:
- streams = [_tokens(shell)]
- except ValueError: # one bad line must not hide the others
- streams = []
- for line in shell.split("\n"):
- try:
- streams.append(_tokens(line) + ["\n"])
- except ValueError:
- continue
- cmds, writes = [], []
- for toks in streams:
- cur, i = [], 0
- while i < len(toks):
- t = toks[i]
- if t in _OPS:
- if cur:
- cmds.append(cur)
- cur = []
- elif t in _OUT or t in _SKIP_OPERAND:
- if cur and cur[-1].isdigit(): # `2>`: the fd number is not an operand
- cur.pop()
- if t in _OUT and i + 1 < len(toks) and toks[i + 1] not in _OPS:
- writes.append(_unquote(toks[i + 1]))
- i += 1
- else:
- cur.append(_unquote(t))
- i += 1
- if cur:
- cmds.append(cur)
- return cmds, writes
-
-
-def _inplace_files(tokens, inplace_flag, script_flag):
- """File operands of an in-place editor (`sed -i`, `perl -pi`), or [] if not in place."""
- if not any(inplace_flag(t) for t in tokens[1:]):
- return []
- files, have_script, skip = [], False, False
- for t in tokens[1:]:
- if skip:
- skip, have_script = False, True
- continue
- if not t or t.startswith("-"):
- if t and script_flag(t):
- skip = True # the next token is the script
- continue
- if not have_script:
- have_script = True # the first operand is the script
- continue
- files.append(t)
- return files
-
-
-def _py_writes(text):
- """Paths an inline Python script writes; "(script)" for a write whose path this cannot
- resolve."""
- out = []
- for m in _PY_OPEN_LIT.finditer(text):
- if set(m.group(4)) & set("wax+"):
- out.append(m.group(2))
- variables = [m.group(1) for m in _PY_OPEN_VAR.finditer(text) if set(m.group(3)) & set("wax+")]
- out += [m.group(2) for m in _PY_WRITE_PATH_LIT.finditer(text)]
- variables += [m.group(1) for m in _PY_WRITE_PATH_VAR.finditer(text)]
- for var in dict.fromkeys(variables):
- found = re.findall(rf"\b{re.escape(var)}\s*=\s*(?:(?:pathlib\.)?Path\(\s*)?(['\"])"
- rf"([^'\"\n]+)\1", text)
- loop = re.search(rf"\bfor\s+{re.escape(var)}\s+in\s+[\[(]([^\])]*)[\])]", text)
- paths = [p for _, p in found]
- if loop:
- paths += re.findall(r"['\"]([^'\"\n]+)['\"]", loop.group(1))
- out += paths or ["(script)"]
- return out
-
-
-def shell_edit_targets(cmd):
- """Basenames of the files a shell command writes, in order, without repeats."""
- if not isinstance(cmd, str) or not cmd.strip():
- return []
- shell, bodies = _split_heredocs(cmd)
- cmds, writes = _commands(shell)
- found = [w for w in writes if _SOURCE_FILE.search(w)]
- for tokens in cmds:
- while tokens and (tokens[0] in ("sudo", "command", "env", "time", "nohup")
- or re.match(r"^\w+=", tokens[0])):
- tokens = tokens[1:]
- if not tokens:
- continue
- head = tokens[0].rsplit("/", 1)[-1]
- if head == "sed":
- found += _inplace_files(
- tokens, lambda t: bool(re.match(r"^(?:-[a-zA-Z]*i|--in-place)", t)),
- lambda t: t in ("-e", "-f", "--expression", "--file"))
- elif head == "perl":
- found += _inplace_files(tokens, lambda t: bool(re.match(r"^-[a-zA-Z]*i", t)),
- lambda t: bool(re.match(r"^-[a-zA-Z]*e$", t)))
- elif head == "tee":
- found += [t for t in tokens[1:] if not t.startswith("-") and _SOURCE_FILE.search(t)]
- elif head == "patch" or (head == "git" and len(tokens) > 1 and tokens[1] == "apply"):
- found.append("(patch)")
- elif head == "git" and len(tokens) > 2 and tokens[1] in ("checkout", "restore"):
- rest = (tokens[tokens.index("--") + 1:] if "--" in tokens
- else tokens[2:] if tokens[1] == "restore" else [])
- found += [t for t in rest if not t.startswith("-")]
- if _PYTHON.search(shell):
- found += _py_writes("\n".join([shell] + bodies))
- names = [p if p.startswith("(") else spiral._basename(p)
- for p in found if p.startswith("(") or _not_scratch(p)]
- return list(dict.fromkeys(n for n in names if n))
-
-
-def fold_shell_edits(st, names):
- """Count `names` as edits in a SpiralState, and say so in its action log."""
- for b in names:
- st.edit_order.append(b)
- st.edit_counts[b] = st.edit_counts.get(b, 0) + 1
- if names and st.recent:
- shown = ", ".join(names[:4]) + (", ..." if len(names) > 4 else "")
- st.recent[-1] = f"{st.recent[-1]} [edits {shown}]"
-
-
-def state_to_dict(st):
- return {k: getattr(st, k) for k in _SLOTS}
-
-
-def state_from_dict(d):
- st = spiral.SpiralState()
- for k in _SLOTS:
- if k in (d or {}):
- setattr(st, k, d[k])
- return st
-
-
-class TurnGuard:
- """`NudgeGuard` for one prompt-turn, persisted between hook calls via `to_dict`."""
-
- JUDGE_BASE_GAP = 5
- JUDGE_MAX_GAP = 20
- # A background verdict that never came back (its job died) stops blocking the next one
- # after this long; a side call is capped at 180 s.
- JUDGE_STALE_S = 300
-
- def __init__(self, turn_key="", data=None):
- d = data or {}
- self.turn_key = d.get("turn_key", turn_key)
- self.st = state_from_dict(d.get("st")) # this segment; reset after a nudge
- self.whole = state_from_dict(d.get("whole")) # the whole turn; never reset
- self.cum_turns = int(d.get("cum_turns", 0))
- self.segment = int(d.get("segment", 0))
- self.nudges_done = int(d.get("nudges_done", 0))
- self.aborted = bool(d.get("aborted", False))
- self.abort_delivered = bool(d.get("abort_delivered", False))
- self.events = list(d.get("events", []))
- self.judge_last = int(d.get("judge_last", -999))
- self.judge_gap = int(d.get("judge_gap", self.JUDGE_BASE_GAP))
- self.judge_calls = int(d.get("judge_calls", 0))
- self.judge_tokens = float(d.get("judge_tokens", 0) or 0)
- self.writer_tokens = float(d.get("writer_tokens", 0) or 0)
- self.last_edit = int(d.get("last_edit", 0))
- self.last_verify = int(d.get("last_verify", 0))
- self.last_verify_failed = bool(d.get("last_verify_failed", False))
- self.edits = int(d.get("edits", 0))
- self.verifications = int(d.get("verifications", 0))
- self.judge_pending = d.get("judge_pending") or None # {"id", "since", "segment"}
- self.nudge_ready = d.get("nudge_ready") or None # a redirect the judge wrote
-
- def to_dict(self):
- return {"turn_key": self.turn_key, "st": state_to_dict(self.st),
- "whole": state_to_dict(self.whole),
- "cum_turns": self.cum_turns, "segment": self.segment,
- "nudges_done": self.nudges_done, "aborted": self.aborted,
- "abort_delivered": self.abort_delivered, "events": self.events[-20:],
- "judge_last": self.judge_last, "judge_gap": self.judge_gap,
- "judge_calls": self.judge_calls, "judge_tokens": self.judge_tokens,
- "writer_tokens": self.writer_tokens, "last_edit": self.last_edit,
- "last_verify": self.last_verify, "last_verify_failed": self.last_verify_failed,
- "edits": self.edits, "verifications": self.verifications,
- "judge_pending": self.judge_pending, "nudge_ready": self.nudge_ready}
-
- # ---- outcome tracking for the ended-green proxy ----------------------------------
- def _track(self, name, args, result, exit_code, shell_edits=()):
- canon = spiral._canon_tool(name) # the vendored tool-name mapping
- if canon in _EDIT:
- self.last_edit = self.cum_turns
- self.edits += 1
- return
- cmd = (args or {}).get("command") if canon == "bash" else None
- verifies = isinstance(cmd, str) and bool(VERIFY_RE.search(cmd))
- if shell_edits:
- # `sed -i ... && pytest`: the edit comes first, so the run verifies it.
- self.last_edit = self.cum_turns - (1 if verifies else 0)
- self.edits += 1
- if verifies:
- self.last_verify = self.cum_turns
- self.verifications += 1
- if exit_code is not None:
- self.last_verify_failed = exit_code != 0
- else: # Claude Code reports no exit code
- self.last_verify_failed = bool(spiral._ERR_RE.search(result or ""))
-
- def resolved_proxy(self, stopped_normally=True):
- """Did this turn END GREEN? The stand-in for the grader the envelope cannot have."""
- if not stopped_normally or self.aborted or self.cum_turns == 0:
- return False
- return not (self.last_verify_failed and self.last_verify > self.last_edit)
-
- # ---- what the judge is told -------------------------------------------------------
- # The vendored digest says "Tests are still NOT green." whenever it has an envelope: on the
- # benchmark the guard only ever watched an unfinished task. Here the guard knows how the
- # turn's last verification went, so the judge -- and the redirect it writes -- is told that.
- _NOT_GREEN = "Tests are still NOT green."
-
- def verification_state(self):
- if not self.verifications:
- return "No test or verification run has been seen in this turn."
- state = "failed" if self.last_verify_failed else "passed"
- since = " There have been edits since." if self.last_edit > self.last_verify else ""
- return f"The last verification run {state}.{since}"
-
- def live_digest(self, digest):
- return (digest or "").replace(self._NOT_GREEN, self.verification_state())
-
- # ---- the judge, rate-limited with backoff exactly as NudgeGuard._sampled_judge ----
- def _backoff(self, v):
- if v and v.get("stuck") is False:
- self.judge_gap = min(self.JUDGE_MAX_GAP, self.judge_gap + self.JUDGE_BASE_GAP)
- else:
- self.judge_gap = self.JUDGE_BASE_GAP
-
- def _sampled(self, judge):
- def call(digest):
- if self.st.turns - self.judge_last < self.judge_gap:
- return None
- self.judge_last = self.st.turns
- self.judge_calls += 1
- try:
- v = judge(self.live_digest(digest))
- except Exception:
- v = None
- if v:
- self.judge_tokens += v.get("_tokens") or 0
- self._backoff(v)
- return v
- return call
-
- def _background(self, judge):
- """`_sampled` for a judge that runs in the background (`te_live.judge.AsyncJudge`):
- a verdict is taken whenever one has come back, a new job starts under the same rate
- limit, and while one is out the judge answers nothing -- which `assess_abort` reads as
- throttled, the same as a call the rate limit skipped."""
- def call(digest):
- found, v = judge.poll(self)
- if found:
- self.judge_pending = None
- if v:
- self.nudge_ready = (v.get("_nudge") or "").strip() or None
- self._backoff(v)
- return v or None
- if self.judge_pending:
- if time.time() - float(self.judge_pending.get("since") or 0) < self.JUDGE_STALE_S:
- return None
- self.judge_pending = None # its job never answered
- if self.st.turns - self.judge_last < self.judge_gap:
- return None
- self.judge_last = self.st.turns
- self.judge_calls += 1
- job = judge.start(self, self.live_digest(digest))
- if job:
- self.judge_pending = {"id": job, "since": time.time(), "segment": self.segment}
- return None
- return call
-
- # ---- one completed tool call ------------------------------------------------------
- def fold(self, name, args, result, exit_code=None, *, envelope=None, thr=None,
- judge=None, nudge_budget=1):
- """Fold one call; return None, ("nudge", reason) or ("abort", reason).
-
- The body is `NudgeGuard.monitor` for a single completed call."""
- thr = thr or spiral.DEFAULT_THRESHOLDS
- shell_edits = (shell_edit_targets((args or {}).get("command"))
- if spiral._canon_tool(name) == "bash" else [])
- self.st.update(name, args or {}, result or "")
- self.whole.update(name, args or {}, result or "")
- fold_shell_edits(self.st, shell_edits)
- fold_shell_edits(self.whole, shell_edits)
- self.cum_turns += 1
- self._track(name, args, result, exit_code, shell_edits)
- if self.aborted:
- return None
-
- backstop = thr.get("backstop_turns")
- if backstop is None and envelope is not None:
- backstop = envelope * thr["backstop_mult"]
- if (backstop is not None and self.cum_turns >= backstop
- and spiral.is_stuck(self.st, thr)):
- # The ladder is nudge, THEN stop. In the experiments the envelope was ~30 calls, so
- # its 2.5x backstop lay well past the stuck rule's 20-call floor and the nudge came
- # first. An interactive repository's envelope is ~4-10 calls: its backstop falls
- # INSIDE that floor, so the moment a turn first counts as stuck the backstop has
- # tripped too, and it pre-empted every nudge -- found by replaying a stuck trace
- # before a live test (2026-10-07). An unspent nudge goes first; after it, a fresh
- # segment must be stuck again before the backstop stops anything.
- reason = f"cum-backstop:{self.cum_turns}>={backstop:.0f}t"
- if self.nudges_done < nudge_budget:
- return self._stop("nudge", reason, envelope)
- return self._stop("abort", reason, envelope)
-
- wired = None
- if judge is not None:
- wired = self._background(judge) if hasattr(judge, "poll") else self._sampled(judge)
- abort, reason = spiral.assess_abort(self.st, envelope=envelope, judge=wired, thr=thr)
- if not abort:
- if (thr.get("nudge_on_ambiguous") and reason == "judge-ambiguous-spared"
- and self.nudges_done < nudge_budget):
- return self._stop("nudge", "ambiguous-past-envelope", envelope)
- return None
- if self.nudges_done < nudge_budget:
- return self._stop("nudge", reason, envelope)
- return self._stop("abort", reason, envelope)
-
- def _stop(self, action, reason, envelope):
- self.events.append({"segment": self.segment, "action": action,
- "turn_in_segment": self.st.turns, "cum_turns": self.cum_turns,
- "envelope": envelope, "reason": reason,
- "snapshot": self.st.snapshot()})
- if action == "abort":
- self.aborted = True
- return action, reason
-
- def nudge_body(self, envelope=None, writer=None):
- """The redirect text: the one a background judge already wrote with its verdict, else
- an LLM-written one when a writer is wired, else the vendored count template
- (`spiral.nudge_text`), which mirrors only the agent's own actions."""
- if self.nudge_ready:
- text, self.nudge_ready = self.nudge_ready, None
- return text
- if writer is not None:
- try:
- out = writer(self.live_digest(self.st.recent_digest(envelope=envelope)))
- except Exception:
- out = None
- if out:
- self.writer_tokens += out.get("_tokens") or 0
- text = (out.get("text") or "").strip()
- if text:
- return text
- return spiral.nudge_text(self.st)
-
- def after_nudge(self):
- """Start the post-nudge segment with a fresh state: `NudgeGuard.continuation`'s reset,
- which is the agent's fair re-assessment window."""
- self.nudges_done += 1
- self.segment += 1
- self.st = spiral.SpiralState()
- self.judge_last = -999
- self.judge_gap = self.JUDGE_BASE_GAP
- self.judge_pending = None # a verdict on the old segment is about the old one
- self.nudge_ready = None
-
- def summary(self, stopped_normally=True):
- return {"turn_key": self.turn_key, "tool_calls": self.cum_turns,
- "nudges": self.nudges_done, "aborted": self.aborted,
- "resolved_proxy": self.resolved_proxy(stopped_normally),
- "edits": self.edits, "verifications": self.verifications,
- "judge_tokens": self.judge_tokens, "writer_tokens": self.writer_tokens}
-
-
-# ---- the per-repository envelope ---------------------------------------------------------
-ENVELOPE_HISTORY = 500 # recent ended-green turns kept for the percentile
-
-
-# Overrides that shape the envelope itself, passed to the tracker; the rest are pinned over the
-# thresholds it returns.
-_ENVELOPE_KEYS = {"envelope_margin": "margin", "envelope_pct": "pct",
- "envelope_min_samples": "min_samples"}
-
-
-def load_envelope(store, level="default", overrides=None):
- d = store.read("envelope.json") or {}
- ov = overrides or {}
- tracker = spiral.EnvelopeTracker(level=level, **{
- arg: ov[key] for key, arg in _ENVELOPE_KEYS.items() if key in ov})
- tracker.resolved_turns = [int(x) for x in d.get("resolved_turns", []) if x]
- tracker.resolved_snaps = [s for s in d.get("resolved_snaps", []) if isinstance(s, dict)]
- return tracker
-
-
-def thresholds(tracker, overrides=None):
- """The thresholds a turn is checked against: the preset, what this repository's history
- learned on top of it, then a person's pinned values (`spiral.<name>`), which win."""
- thr = tracker.thresholds(max_turns=None)
- for key, value in (overrides or {}).items():
- if key not in _ENVELOPE_KEYS:
- thr[key] = value
- if "backstop_mult" in (overrides or {}) and tracker.envelope is not None:
- thr["backstop_turns"] = tracker.envelope * thr["backstop_mult"]
- return thr
-
-
-def base_thresholds(level="default", overrides=None):
- """The thresholds before any learning: the preset with a person's pinned values on top.
- What `te config show` reports, so the numbers a setting replaces are visible."""
- thr = spiral.scaled_thresholds(level)
- thr.update(overrides or {})
- thr.pop("restart_budget", None)
- return thr
-
-
-def save_envelope(store, tracker):
- store.write("envelope.json", {
- "level": tracker.level,
- "resolved_turns": tracker.resolved_turns[-ENVELOPE_HISTORY:],
- "resolved_snaps": tracker.resolved_snaps[-ENVELOPE_HISTORY:]})
-
-
-def record_turn(store, guard, level="default", stopped_normally=True, overrides=None):
- """Fold a finished turn into the envelope -- under the store lock, since two sessions in
- one repository share it. Only turns that ended green feed it, as only resolved tasks fed
- the experiments' envelope; a turn's own outcome gates only later turns."""
- # The snapshot is of the WHOLE turn (`guard.whole`), not the post-nudge segment: the
- # experiments snapshot a resolved task's full trajectory (`spiral_snapshot(transcript)`).
- with store.locked("envelope"):
- tracker = load_envelope(store, level, overrides)
- tracker.update(guard.cum_turns, guard.resolved_proxy(stopped_normally),
- snapshot=guard.whole.snapshot())
- save_envelope(store, tracker)
- return tracker
diff --git a/te_live/transcripts.py b/te_live/transcripts.py
deleted file mode 100644
index 14ebd70..0000000
--- a/te_live/transcripts.py
+++ /dev/null
@@ -1,541 +0,0 @@
-"""Read a host's own session log in the shapes the mechanisms already consume.
-
-The mechanisms read rollouts through one seam (`tokeneconomizer.trace`), which knows the three
-streams the harness captured: Claude Code `stream-json`, the Copilot CLI's events, and
-`codex exec --json`. A live session leaves a different file behind, and this module bridges it
-rather than teaching every mechanism a fourth schema:
-
- * Claude Code's interactive transcript uses the same `message.content[]` envelope as
- `stream-json`, so `trace.load_trajectory` reads it unchanged. What differs is usage: the
- transcript writes ONE ENTRY PER CONTENT BLOCK, each repeating its message's `usage`, so
- summing entries over-counts by the number of blocks (measured locally: two thirds of
- assistant message ids repeat, up to 12 times). `claude_session_usage` keys by message id.
- Subagents write their own files under `<session>/subagents/`, and their tool calls and
- tokens belong to the session that spawned them.
-
- * Codex's rollout (`~/.codex/sessions/.../rollout-*.jsonl`) wraps the same item fields the
- exec stream carries (`command`, `aggregated_output`, `exit_code`, `changes`) in
- `event_msg/item_completed` records with PascalCase item types, an argv list for the command
- and a path-keyed map for changes. `codex_rollout_to_exec` rewrites it into exec-stream lines,
- after which `trace.load_trajectory`, the injection layers and the spiral parsers read it as
- they read a harness transcript. Usage comes from its `token_count` events and is converted
- exactly as `te_harness.codex.row_usage` converts the exec stream's, because Codex's
- `input_tokens` is the GRAND input total including both cache fields.
-
- A compressed rollout (`.jsonl.zst`) cannot be read with the standard library; it is reported
- as unreadable rather than half-read.
-"""
-import glob
-import json
-import os
-import re
-import shlex
-
-_COPILOT_EXIT_RE = re.compile(r"<shellId: [^>]*?completed with exit code (-?\d+)>")
-_CLAUDE_KEYS = ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens",
- "output_tokens")
-
-
-def _lines(path):
- try:
- with open(path, encoding="utf-8", errors="replace") as fh:
- for line in fh:
- line = line.strip()
- if line:
- yield line
- except OSError:
- return
-
-
-def claude_subagent_files(transcript_path):
- """Subagent transcripts of a Claude Code session: `<dir>/<session-id>/subagents/*.jsonl`."""
- if not transcript_path:
- return []
- stem = os.path.splitext(transcript_path)[0]
- return sorted(glob.glob(os.path.join(stem, "subagents", "*.jsonl")))
-
-
-def claude_session_usage(transcript_path, include_subagents=True):
- """Token breakdown of a Claude Code session, de-duplicated by assistant message id.
-
- Returns the four breakdown fields `pricing.effective_tokens` reads, plus `model` (the most
- used one), `requests` (distinct assistant messages carrying usage) and `files` read."""
- files = [transcript_path] + (claude_subagent_files(transcript_path)
- if include_subagents else [])
- by_id, models, anon = {}, {}, 0
- for path in files:
- for line in _lines(path):
- if '"usage"' not in line:
- continue
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- if ev.get("type") != "assistant":
- continue
- msg = ev.get("message") or {}
- usage = msg.get("usage")
- if not isinstance(usage, dict):
- continue
- mid = msg.get("id")
- if not mid:
- anon += 1
- mid = f"anon-{path}-{anon}"
- # Later entries of the same message carry the final counts; keep the last.
- by_id[mid] = {k: int(usage.get(k) or 0) for k in _CLAUDE_KEYS}
- model = msg.get("model")
- if model:
- models[model] = models.get(model, 0) + 1
- out = {k: sum(u[k] for u in by_id.values()) for k in _CLAUDE_KEYS}
- out["requests"] = len(by_id)
- out["model"] = max(models, key=models.get) if models else None
- out["files"] = len([f for f in files if os.path.exists(f)])
- return out
-
-
-def claude_tool_usage(transcript_path, include_subagents=True):
- """{tool: calls} over a session and, by default, its subagents -- a tool a subagent used is
- in use, and denying it would take it from the subagent too."""
- from tokeneconomizer import trace
- counts = {}
- files = [transcript_path] + (claude_subagent_files(transcript_path)
- if include_subagents else [])
- for path in files:
- for name, n in trace.tool_usage(path).items():
- counts[name] = counts.get(name, 0) + n
- return counts
-
-
-def claude_deferred_tools(transcript_path):
- """Tool names the session listed as deferred (`deferred_tools_delta` attachments).
-
- Deferred tools cost one listing line each, not a schema, so they matter little to the bill;
- they are still part of what the session could call, so the untool catalog includes them."""
- names = set()
- for line in _lines(transcript_path):
- if '"deferred_tools_delta"' not in line:
- continue
- try:
- att = json.loads(line).get("attachment") or {}
- except ValueError:
- continue
- names.update(n for n in (att.get("addedNames") or []) if isinstance(n, str))
- names.difference_update(n for n in (att.get("removedNames") or []) if isinstance(n, str))
- return names
-
-
-# ---- Codex ---------------------------------------------------------------------------
-_ROLLOUT_ITEM_TYPES = {
- "CommandExecution": "command_execution",
- "FileChange": "file_change",
- "AgentMessage": "agent_message",
- "ImageView": "view_image",
- "Extension": "web_search",
- "McpToolCall": "mcp_tool_call",
- "CollabToolCall": "collab_tool_call",
-}
-
-
-def _command_text(command):
- if isinstance(command, list):
- return shlex.join(str(c) for c in command)
- return str(command or "")
-
-
-def _rollout_item_to_exec(item):
- """One rollout item -> the `codex exec --json` item shape, or None to skip it."""
- kind = _ROLLOUT_ITEM_TYPES.get(item.get("type"), None)
- if kind is None:
- return None
- out = {"type": kind, "id": item.get("id")}
- if kind == "command_execution":
- out.update(command=_command_text(item.get("command")),
- aggregated_output=item.get("aggregated_output")
- or ((item.get("stdout") or "") + (item.get("stderr") or "")),
- exit_code=item.get("exit_code"),
- status=str(item.get("status") or "").lower() or "completed")
- elif kind == "file_change":
- changes = item.get("changes")
- if isinstance(changes, dict):
- changes = [dict({"path": p}, **({"kind": (v or {}).get("type")}
- if isinstance(v, dict) else {}))
- for p, v in changes.items()]
- out.update(changes=changes or [],
- status=str(item.get("status") or "").lower() or "completed")
- elif kind == "agent_message":
- content = item.get("content")
- if isinstance(content, list):
- content = " ".join(c.get("text", "") for c in content if isinstance(c, dict))
- out.update(text=content or "")
- else:
- out.update({k: v for k, v in item.items() if k not in ("type", "id")})
- return out
-
-
-def codex_rollout_to_exec(rollout_path, out_path):
- """Rewrite a Codex rollout into `codex exec --json` lines at `out_path`.
-
- Returns the number of items written, or None when the rollout cannot be read (missing, or
- compressed). The thread id rides on a leading `thread.started` line, as in the exec stream."""
- if not rollout_path or rollout_path.endswith(".zst") or not os.path.exists(rollout_path):
- return None
- n = 0
- thread = None
- with open(out_path, "w", encoding="utf-8") as out:
- for line in _lines(rollout_path):
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
- if ev.get("type") == "session_meta" and thread is None:
- thread = payload.get("id") or payload.get("session_id")
- if thread:
- out.write(json.dumps({"type": "thread.started", "thread_id": thread}) + "\n")
- continue
- if ev.get("type") != "event_msg" or payload.get("type") != "item_completed":
- continue
- item = _rollout_item_to_exec(payload.get("item") or {})
- if item is None:
- continue
- out.write(json.dumps({"type": "item.completed", "item": item}) + "\n")
- n += 1
- return n
-
-
-def codex_capability_trace(rollout_path, out_path):
- """The exec-stream lines `mechanisms.codex_untool.inspect_usage` reads, for a rollout.
-
- `codex_rollout_to_exec` keeps the items the other mechanisms read; capability evidence
- also needs the model's own tool calls. In code mode every call is one `exec` custom tool
- whose input calls `tools.<name>(...)` -- `tools.view_image(`, `tools.spawn_agent(` -- and
- those ride in `response_item` records, which are added here as `custom_tool_call` /
- `function_call` items, the shape `codex_untool._item_capabilities` parses. Returns the number
- of items written, or None when the rollout cannot be read."""
- n = codex_rollout_to_exec(rollout_path, out_path)
- if n is None:
- return None
- with open(out_path, "a", encoding="utf-8") as out:
- for line in _lines(rollout_path):
- if '"response_item"' not in line:
- continue
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- p = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
- if ev.get("type") != "response_item" or p.get("type") not in (
- "custom_tool_call", "function_call"):
- continue
- item = {"type": p.get("type"), "name": p.get("name"),
- "id": p.get("call_id") or p.get("id"),
- "status": str(p.get("status") or "completed").lower()}
- item["input" if p.get("type") == "custom_tool_call" else "arguments"] = (
- p.get("input") if p.get("type") == "custom_tool_call" else p.get("arguments"))
- out.write(json.dumps({"type": "item.completed", "item": item}) + "\n")
- n += 1
- return n
-
-
-def codex_session_meta(rollout_path):
- """{cwd, model, cli_version} from a rollout's session_meta / turn_context records."""
- meta = {}
- for line in _lines(rollout_path):
- if '"session_meta"' not in line and '"turn_context"' not in line:
- continue
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- p = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
- if ev.get("type") == "session_meta":
- meta.setdefault("cwd", p.get("cwd"))
- meta.setdefault("cli_version", p.get("cli_version"))
- elif ev.get("type") == "turn_context" and p.get("model"):
- meta["model"] = p.get("model")
- return meta
-
-
-def codex_session_usage(rollout_path):
- """Token breakdown of a Codex session from its last cumulative `token_count`.
-
- Converted as `te_harness.codex.row_usage` converts the exec stream: fresh input is the grand
- input total less both cache fields, and reasoning tokens are added to output."""
- total = None
- requests = 0
- for line in _lines(rollout_path):
- if '"token_count"' not in line:
- continue
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- p = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
- if p.get("type") != "token_count":
- continue
- info = p.get("info") or {}
- if info.get("total_token_usage"):
- total = info["total_token_usage"]
- requests += 1
- meta = codex_session_meta(rollout_path)
- if not total:
- return {"input_tokens": None, "cache_read_input_tokens": None,
- "cache_creation_input_tokens": None, "output_tokens": None,
- "requests": 0, "model": meta.get("model")}
- inp = int(total.get("input_tokens") or 0)
- cached = int(total.get("cached_input_tokens") or 0)
- cw = int(total.get("cache_write_input_tokens") or 0)
- reasoning = int(total.get("reasoning_output_tokens") or 0)
- return {"input_tokens": max(0, inp - cached - cw),
- "cache_read_input_tokens": cached,
- "cache_creation_input_tokens": cw,
- "output_tokens": int(total.get("output_tokens") or 0) + reasoning,
- "reasoning_output_tokens": reasoning,
- "requests": requests, "model": meta.get("model")}
-
-
-# ---- Pi ------------------------------------------------------------------------------
-# Pi (earendil-works/pi) stores a session as a TREE of JSONL entries linked by `id` /
-# `parentId`; the conversation is the path from the current leaf back to the root, and an
-# abandoned branch stays in the file. Assistant messages carry `toolCall` blocks
-# ({id, name, arguments}) and their own usage; tool results are `toolResult` messages with
-# `isError`. `pi_session_to_claude` writes the ACTIVE branch as the Claude Code envelope the
-# trace seam already reads, so every mechanism reads a Pi session without a Pi branch.
-#
-# Usage, per pi-ai's own type: `input` excludes the cache fields, `output` already includes
-# reasoning, and `cacheWrite1h` is a subset of `cacheWrite` -- so the mapping to the ledger's
-# four fields is direct.
-
-def _pi_entries(path):
- out = []
- for line in _lines(path):
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- if isinstance(ev, dict):
- out.append(ev)
- return out
-
-
-def pi_session_header(path):
- """The `session` header line ({id, cwd, version, ...}), {} if absent."""
- for ev in _pi_entries(path)[:1]:
- if ev.get("type") == "session":
- return ev
- return {}
-
-
-def pi_active_branch(entries):
- """Entries on the path from the last entry (the leaf) back to the root, in order."""
- by_id = {e.get("id"): e for e in entries if e.get("id")}
- tree = [e for e in entries if e.get("id")]
- if not tree:
- return []
- path, cur, seen = [], tree[-1], set()
- while cur is not None and cur.get("id") not in seen:
- seen.add(cur.get("id"))
- path.append(cur)
- cur = by_id.get(cur.get("parentId"))
- return list(reversed(path))
-
-
-def _pi_usage(u):
- if not isinstance(u, dict):
- return None
- return {"input_tokens": int(u.get("input") or 0),
- "cache_read_input_tokens": int(u.get("cacheRead") or 0),
- "cache_creation_input_tokens": int(u.get("cacheWrite") or 0),
- "output_tokens": int(u.get("output") or 0),
- "cost_usd": float((u.get("cost") or {}).get("total") or 0)}
-
-
-def _pi_text(content):
- if isinstance(content, str):
- return content
- if isinstance(content, list):
- return "\n".join(c.get("text", "") for c in content
- if isinstance(c, dict) and c.get("type") == "text")
- return ""
-
-
-def pi_session_to_claude(path, out_path):
- """Write a Pi session's active branch as Claude Code transcript lines.
-
- Returns the number of tool calls written, or None when the file is missing."""
- if not path or not os.path.exists(path):
- return None
- n = 0
- with open(out_path, "w", encoding="utf-8") as out:
- for e in pi_active_branch(_pi_entries(path)):
- if e.get("type") != "message":
- continue
- m = e.get("message") or {}
- role = m.get("role")
- if role == "user":
- out.write(json.dumps({"type": "user", "message": {
- "role": "user", "content": _pi_text(m.get("content"))}}) + "\n")
- elif role == "assistant":
- blocks = []
- for b in m.get("content") or []:
- if isinstance(b, dict) and b.get("type") == "toolCall":
- blocks.append({"type": "tool_use", "id": b.get("id"),
- "name": b.get("name"), "input": b.get("arguments") or {}})
- n += 1
- elif isinstance(b, dict) and b.get("type") == "text":
- blocks.append({"type": "text", "text": b.get("text", "")})
- msg = {"id": e.get("id"), "role": "assistant", "content": blocks,
- "model": m.get("model")}
- usage = _pi_usage(m.get("usage"))
- if usage:
- msg["usage"] = {k: v for k, v in usage.items() if k != "cost_usd"}
- out.write(json.dumps({"type": "assistant", "message": msg}) + "\n")
- elif role == "toolResult":
- out.write(json.dumps({"type": "user", "message": {"role": "user", "content": [{
- "type": "tool_result", "tool_use_id": m.get("toolCallId"),
- "content": _pi_text(m.get("content")),
- "is_error": bool(m.get("isError"))}]}}) + "\n")
- return n
-
-
-def pi_session_usage(path):
- """Token breakdown of a Pi session's active branch, plus Pi's own cost estimate."""
- totals = {"input_tokens": 0, "cache_read_input_tokens": 0,
- "cache_creation_input_tokens": 0, "output_tokens": 0}
- cost, requests, models = 0.0, 0, {}
- for e in pi_active_branch(_pi_entries(path)):
- u = None
- if e.get("type") == "message" and (e.get("message") or {}).get("role") == "assistant":
- m = e["message"]
- u = _pi_usage(m.get("usage"))
- if m.get("model"):
- models[m["model"]] = models.get(m["model"], 0) + 1
- elif e.get("type") in ("usage", "compaction", "branch_summary"):
- u = _pi_usage(e.get("usage"))
- if u:
- requests += 1
- cost += u.pop("cost_usd")
- for k in totals:
- totals[k] += u[k]
- totals.update(requests=requests, cost_usd_vendor=round(cost, 6),
- model=max(models, key=models.get) if models else None)
- return totals
-
-
-# ---- GitHub Copilot CLI ---------------------------------------------------------------
-# Copilot writes each session to `<COPILOT_HOME>/session-state/<id>/events.jsonl`: the same
-# `tool.execution_start` / `tool.execution_complete` event stream `copilot --output-format json`
-# prints, which `trace.load_trajectory` already reads, so no rewrite is needed. Usage is in the
-# `session.shutdown` event, per model:
-# modelMetrics[model].usage = {inputTokens, outputTokens, cacheReadTokens,
-# cacheWriteTokens, reasoningTokens}
-# `inputTokens` is the GRAND input total: against a scripted endpoint that reported
-# prompt_tokens=1000 with cached_tokens=600 on each of 4 requests, it recorded inputTokens=4000
-# and cacheReadTokens=2400 (1.0.83). Fresh input is therefore input less both cache fields, as
-# `sum_openai_usage` and the Codex reader convert theirs. `outputTokens` is the provider's
-# completion count, which already includes reasoning, so reasoning is not added again.
-# A session killed before it shut down has no usage; it is reported as unpriced.
-
-def _copilot_events(path):
- for line in _lines(path):
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- if isinstance(ev, dict):
- yield ev
-
-
-def copilot_session_meta(path):
- """{cwd, model, cli_version, session_id} from a Copilot session's `session.start`."""
- for ev in _copilot_events(path):
- if ev.get("type") == "session.start":
- d = ev.get("data") or {}
- return {"cwd": (d.get("context") or {}).get("cwd"), "model": d.get("selectedModel"),
- "cli_version": d.get("copilotVersion"), "session_id": d.get("sessionId")}
- return {}
-
-
-def copilot_session_usage(path):
- """Token breakdown of a Copilot session from its `session.shutdown` events."""
- totals = {"input_tokens": 0, "cache_read_input_tokens": 0,
- "cache_creation_input_tokens": 0, "output_tokens": 0}
- requests, models, seen, tool_defs = 0, {}, False, None
- for ev in _copilot_events(path):
- if ev.get("type") != "session.shutdown":
- continue
- d = ev.get("data") or {}
- for model, m in (d.get("modelMetrics") or {}).items():
- u = (m or {}).get("usage") or {}
- inp = int(u.get("inputTokens") or 0)
- cr, cw = int(u.get("cacheReadTokens") or 0), int(u.get("cacheWriteTokens") or 0)
- totals["input_tokens"] += max(0, inp - cr - cw)
- totals["cache_read_input_tokens"] += cr
- totals["cache_creation_input_tokens"] += cw
- totals["output_tokens"] += int(u.get("outputTokens") or 0)
- n = int(((m or {}).get("requests") or {}).get("count") or 0)
- requests += n
- models[model] = models.get(model, 0) + n
- seen = True
- if d.get("toolDefinitionsTokens") is not None:
- tool_defs = int(d["toolDefinitionsTokens"])
- if not seen:
- out = {k: None for k in totals}
- out.update(requests=0, model=copilot_session_meta(path).get("model"))
- return out
- totals.update(requests=requests, model=max(models, key=models.get) if models else None,
- tool_definitions_tokens=tool_defs)
- return totals
-
-
-def copilot_turns(path):
- """Prompt-turns of a Copilot session: [[(name, args, result, exit_code)]], one list per
- user message, tool calls paired start-to-complete by call id."""
- turns, cur, pend = [], None, {}
- for ev in _copilot_events(path):
- t, d = ev.get("type"), ev.get("data") or {}
- if t == "user.message":
- if cur:
- turns.append(cur)
- cur, pend = [], {}
- elif t == "tool.execution_start" and cur is not None:
- pend[d.get("toolCallId")] = (str(d.get("toolName") or ""),
- d.get("arguments") if isinstance(d.get("arguments"),
- dict) else {})
- elif t == "tool.execution_complete" and cur is not None:
- name, args = pend.pop(d.get("toolCallId"), (None, None))
- if name is None:
- continue
- res = d.get("result") or {}
- text = res.get("content") if isinstance(res, dict) else str(res)
- text = text if isinstance(text, str) else json.dumps(text)
- if not d.get("success", True) and isinstance(d.get("error"), (str, dict)):
- text = (text or "") + "\n" + json.dumps(d.get("error"))
- m = _COPILOT_EXIT_RE.search((text or "")[-400:])
- cur.append((name, args, text or "", int(m.group(1)) if m else None))
- if cur:
- turns.append(cur)
- return turns
-
-
-def copilot_mcp_servers(env=None):
- """MCP server names a Copilot session can load: the built-in GitHub server plus every
- server in the user's `mcp-config.json`. Tool names are `<server>-<tool>`."""
- env = os.environ if env is None else env
- home = env.get("COPILOT_HOME") or os.path.join(os.path.expanduser("~"), ".copilot")
- names = {"github-mcp-server"}
- try:
- with open(os.path.join(home, "mcp-config.json"), encoding="utf-8") as fh:
- names.update((json.load(fh).get("mcpServers") or {}).keys())
- except (OSError, ValueError, AttributeError):
- pass
- return names
-
-
-def mcp_server_of(tool, servers):
- """The server a Copilot tool name belongs to (longest matching `<server>-` prefix)."""
- best = None
- for s in servers:
- if tool.startswith(s + "-") and (best is None or len(s) > len(best)):
- best = s
- return best
diff --git a/tests/fixtures/__init__.py b/tests/fixtures/__init__.py
index f2b6f5a..da0871f 100644
--- a/tests/fixtures/__init__.py
+++ b/tests/fixtures/__init__.py
@@ -5,12 +5,14 @@ import os
def write_claude_transcript(path, calls):
"""Write a minimal Claude-schema transcript.jsonl.
- `calls` is a list of (tool_name, input_dict, result_text)."""
+ `calls` is a list of (tool_name, input_dict, result_text[, cwd]); a cwd is recorded on the
+ call's entry, as Claude Code records the directory its shell is in."""
lines = []
- for i, (name, inp, res) in enumerate(calls):
+ for i, (name, inp, res, *cwd) in enumerate(calls):
tid = f"t{i}"
- lines.append({"message": {"content": [
- {"type": "tool_use", "id": tid, "name": name, "input": inp}]}})
+ lines.append(dict({"message": {"content": [
+ {"type": "tool_use", "id": tid, "name": name, "input": inp}]}},
+ **({"cwd": cwd[0]} if cwd else {})))
lines.append({"message": {"content": [
{"type": "tool_result", "tool_use_id": tid, "content": res}]}})
with open(path, "w", encoding="utf-8") as fh:
diff --git a/tests/test_codex_injection.py b/tests/test_envfacts.py
similarity index 61%
rename from tests/test_codex_injection.py
rename to tests/test_envfacts.py
index 1af685b..3346112 100644
--- a/tests/test_codex_injection.py
+++ b/tests/test_envfacts.py
@@ -1,4 +1,4 @@
-"""Codex-native injection: environment facts from generic detector families.
+"""Environment facts: micro-skills from generic detector families.
Every scenario is a synthetic stream of tasks (Codex transcript schema unless stated). The
assertions pin the four properties the mechanism exists for: facts FORM from recurring
@@ -8,10 +8,9 @@ cost nothing (`opt_tokens == 0`).
import json
import os
-from tokeneconomizer.mechanisms import codex_injection as ci
-from tokeneconomizer.mechanisms.codex_injection import EnvFactsDistiller
-from tokeneconomizer.mechanisms.injection import PrefixStage
-from tokeneconomizer.config import InjectionConfig, EconomizerConfig, needs_optimizer
+from tokeneconomizer.microskills import EnvFactsDistiller, PrefixStage
+from tokeneconomizer.microskills import envfacts as ef, observe
+from tokeneconomizer.config import InjectionConfig
from fixtures import write_codex_transcript, write_claude_transcript
BASE = "/opt/env/base/bin/python"
@@ -52,34 +51,34 @@ def _stream(tmp_path, n, maker, d=None):
# ---- observations ---------------------------------------------------------------------
def test_classify_forms_and_intents():
- obs = ci.classify_command(
+ obs = observe.classify_command(
'/bin/bash -lc "source /opt/env/bin/activate proj && python -m pytest tests -q"')
assert [(o.intent, o.form) for o in obs] == [
("run_tests", "source activate proj && python -m pytest")]
- obs = ci.classify_command("conda run -n proj python - <<'PY'\nimport x\nPY")
+ obs = observe.classify_command("conda run -n proj python - <<'PY'\nimport x\nPY")
assert [(o.intent, o.form) for o in obs] == [("run_interpreter", "conda run -n proj python")]
- obs = ci.classify_command("PYTHONPATH=/testbed ./tests/runtests.py auth_tests -v 1")
+ obs = observe.classify_command("PYTHONPATH=/testbed ./tests/runtests.py auth_tests -v 1")
assert [(o.intent, o.form) for o in obs] == [("run_tests", "python tests/runtests.py")]
- obs = ci.classify_command(f"{PROJ} bin/test sympy/core/tests/test_a.py")
+ obs = observe.classify_command(f"{PROJ} bin/test sympy/core/tests/test_a.py")
assert [(o.intent, o.form) for o in obs] == [("run_tests", f"{PROJ} bin/test")]
- obs = ci.classify_command("git remote -v; git tag --contains HEAD | head; git log --oneline -3")
+ obs = observe.classify_command("git remote -v; git tag --contains HEAD | head; git log --oneline -3")
assert [(o.intent, o.probe) for o in obs] == [("probe_vcs_refs", "remote"),
("probe_vcs_refs", "tag")]
- obs = ci.classify_command("curl -sS https://api.example.org/x | head -3")
+ obs = observe.classify_command("curl -sS https://api.example.org/x | head -3")
assert obs[0].intent == "fetch_remote" and obs[0].hosts == ("api.example.org",)
# a plain `git tag` lists ALL tags, past ones included: not a beyond-HEAD probe
- assert ci.classify_command("git tag | tail -5") == []
+ assert observe.classify_command("git tag | tail -5") == []
# heredoc bodies never become commands
- assert ci.classify_command("python - <<'PY'\npytest_is_a_word = 1\nPY")[0].intent == \
+ assert observe.classify_command("python - <<'PY'\npytest_is_a_word = 1\nPY")[0].intent == \
"run_interpreter"
def test_error_classes_are_environmental_only():
- assert ci.error_class("ModuleNotFoundError: No module named 'x'") == "module_missing"
- assert ci.error_class("bash: pytest: command not found") == "command_missing"
- assert ci.error_class("curl: (7) Failed to connect to h port 443: Connection refused") == \
+ assert observe.error_class("ModuleNotFoundError: No module named 'x'") == "module_missing"
+ assert observe.error_class("bash: pytest: command not found") == "command_missing"
+ assert observe.error_class("curl: (7) Failed to connect to h port 443: Connection refused") == \
"connection_refused"
- assert ci.error_class("AssertionError: 1 != 2\nFAILED tests/test_a.py::t") is None
+ assert observe.error_class("AssertionError: 1 != 2\nFAILED tests/test_a.py::t") is None
# ---- FormRepair -------------------------------------------------------------------------
@@ -88,12 +87,12 @@ def test_interpreter_fact_forms_fires_and_renders(tmp_path):
assert d.render() == "" # ACTIVE needs 3 drifted confirms AND 4 exercised
d.update(_broken_env_task(tmp_path, 3), iid="w-3", resolved=True)
text = d.render()
- assert text.startswith(ci.HEADER)
+ assert text.startswith(ef.HEADER)
assert PROJ in text and "python -m pytest …` fails here" in text
assert d.opt_tokens == 0
f = d.facts["form_repair:run_tests:python -m pytest"]
assert f.state == "ACTIVE" and f.life.fire_num == 4 and f.life.fire_den == 4
- assert ci.lint_ok(text)
+ assert ef.lint_ok(text)
def test_clean_environment_forms_nothing(tmp_path):
@@ -179,22 +178,22 @@ def test_refused_hosts_form_a_boundary_fact_and_a_reachable_host_does_not(tmp_pa
# ---- rendering discipline ---------------------------------------------------------------
def test_lint_refuses_completion_advice():
- assert not ci.lint_ok("You are done once the tests pass; skip the rest.")
- assert ci.lint_ok("`python …` fails here with command not found; `/x/bin/python …` works.")
+ assert not ef.lint_ok("You are done once the tests pass; skip the rest.")
+ assert ef.lint_ok("`python …` fails here with command not found; `/x/bin/python …` works.")
def test_block_is_capped_in_facts_and_tokens(tmp_path):
d = EnvFactsDistiller("acme/widget")
for i in range(7):
- f = ci.EnvFact(f"form_repair:run_tests:tool{i}", "form_repair", False,
+ f = ef.EnvFact(f"form_repair:run_tests:tool{i}", "form_repair", False,
{"intent": "run_tests", "a": f"tool{i}",
"b_counts": {f"/very/long/path/number/{i}/that/keeps/going/bin/tool{i}": 3},
"error_counts": {"command_missing": 3}})
f.life.state = "ACTIVE"; f.life.fire_num = f.life.fire_den = 10
d.facts[f.id] = f
text = d.render()
- assert text and len(text) <= ci.MAX_TOKENS * 4
- assert text.count("\n- ") <= ci.MAX_FACTS
+ assert text and len(text) <= ef.MAX_TOKENS * 4
+ assert text.count("\n- ") <= ef.MAX_FACTS
def test_form_repair_facts_sharing_the_working_form_merge_into_one_line(tmp_path):
@@ -209,13 +208,114 @@ def test_form_repair_facts_sharing_the_working_form_merge_into_one_line(tmp_path
assert text.count("\n- ") == 1 and "pytest …`" in text and "python -m pytest …`" in text
+def test_a_merged_line_with_one_working_form_says_works(tmp_path):
+ def two_forms(tmp_path, i):
+ return _task(tmp_path, i, [
+ _edit(f"pkg/m{i}.py"),
+ _cmd("pytest tests/test_a.py -q", "bash: pytest: command not found", 127),
+ _cmd("python -m pytest tests/test_a.py -q", f"{BASE}: No module named pytest", 1),
+ _cmd(f"{PROJ} -m pytest tests/test_a.py -q", "1 passed", 0)])
+ assert d_text(_stream(tmp_path, 4, two_forms)).endswith(f"`{PROJ} -m pytest …` works.")
+
+
+def d_text(d):
+ return d.render().strip().splitlines()[-1]
+
+
+def test_an_environment_fact_forms_in_a_repository_where_every_session_edits_one_file(tmp_path):
+ """Seen live on all four agents: in a small repository every session touched the same
+ module, so a fact needing confirmations on different files never formed. Whether `pytest`
+ is missing does not depend on which file a session edits."""
+ def same_file(tmp_path, i):
+ return _task(tmp_path, i, [
+ _edit("pkg/stock.py"),
+ _cmd("pytest -q", "bash: pytest: command not found", 127),
+ _cmd("python -m pytest -q", "4 passed in 0.01s", 0)])
+ d = _stream(tmp_path, 4, same_file)
+ assert d.facts["form_repair:run_tests:pytest"].state == "ACTIVE"
+ assert "`pytest …` fails here with command not found" in d.render()
+
+
+# ---- which working form a fact names --------------------------------------------------------
+LOCAL = "~/.local/bin/pytest"
+
+
+def _clean(tmp_path, i):
+ """The bare runner is missing; `python -m pytest` works at once."""
+ return _task(tmp_path, i, [
+ _edit(f"pkg/c{i}.py"),
+ _cmd("pytest -q", "bash: pytest: command not found", 127),
+ _cmd("python -m pytest -q", "4 passed in 0.01s", 0)])
+
+
+def _messy(tmp_path, i):
+ """Seen live on Claude Code: the bare runner fails twice, a user-site pytest stops at
+ collection, and only `PYTHONPATH=. ~/.local/bin/pytest` passes -- twice."""
+ return _task(tmp_path, i, [
+ _edit(f"pkg/m{i}.py"),
+ _cmd("pytest -q", "bash: pytest: command not found", 127),
+ _cmd("pytest -q", "bash: pytest: command not found", 127),
+ _cmd(f"{LOCAL} -q", "E ModuleNotFoundError: No module named 'stock'\n"
+ "Interrupted: 1 error during collection\n1 error in 0.08s", 2),
+ _cmd(f"PYTHONPATH=. {LOCAL} -q", "4 passed in 0.01s", 0),
+ _cmd(f"PYTHONPATH=. {LOCAL} -q", "4 passed in 0.01s", 0)])
+
+
+def test_a_form_that_only_worked_with_an_assignment_before_it_is_not_named(tmp_path):
+ d = _stream(tmp_path, 3, _clean)
+ for i in range(3, 6):
+ d.render()
+ d.update(_messy(tmp_path, i), iid=f"m-{i}", resolved=True)
+ f = d.facts["form_repair:run_tests:pytest"]
+ assert LOCAL not in f.params["b_counts"]
+ assert d_text(d).endswith("`python -m pytest …` works.")
+
+
+def test_one_session_is_one_piece_of_evidence_per_form(tmp_path):
+ def repeated(tmp_path, i): # three failures, then the same repair twice
+ return _task(tmp_path, i, [
+ _edit(f"pkg/r{i}.py")] + [
+ _cmd("pytest -q", "bash: pytest: command not found", 127)] * 3 + [
+ _cmd(f"{PROJ} -m pytest -q", "1 passed", 0)] * 2)
+ d = _stream(tmp_path, 2, _clean)
+ d.render(); d.update(repeated(tmp_path, 2), iid="r", resolved=True)
+ assert d.facts["form_repair:run_tests:pytest"].params["b_counts"] == {
+ "python -m pytest": 2, PROJ + " -m pytest": 1}
+ assert d.facts["form_repair:run_tests:pytest"].working_form() == "python -m pytest"
+
+
+def test_a_named_form_that_stops_working_is_named_no_more(tmp_path):
+ d = _stream(tmp_path, 4, _clean)
+ assert "`python -m pytest …` works" in d.render()
+
+ def gone(tmp_path, i): # the environment lost pytest altogether
+ return _task(tmp_path, i, [
+ _edit(f"pkg/g{i}.py"),
+ _cmd("pytest -q", "bash: pytest: command not found", 127),
+ _cmd("python -m pytest -q", f"{BASE}: No module named pytest", 1)])
+ for i in range(4, 9):
+ d.render(); d.update(gone(tmp_path, i), iid=f"g-{i}", resolved=True)
+ f = d.facts["form_repair:run_tests:pytest"]
+ assert f.params["b_fails"]["python -m pytest"] == 5 and f.working_form() is None
+ assert f.claim() == "" and "python -m pytest" not in d.render()
+
+
+def test_env_assignments_after_env_are_part_of_how_a_command_was_typed():
+ (o,) = observe.classify_command("env PYTHONPATH=. pytest -q")
+ assert (o.intent, o.form, o.env) == ("run_tests", "pytest", True)
+ (o,) = observe.classify_command("PYTHONPATH=. python -m pytest -q")
+ assert (o.form, o.env) == ("python -m pytest", True)
+ (o,) = observe.classify_command("python -m pytest -q")
+ assert o.env is False
+
+
# ---- persistence, other transcript schemas, stage wiring ---------------------------------
def test_save_load_roundtrip(tmp_path):
d = _stream(tmp_path, 4, _broken_env_task)
d.save(str(tmp_path))
d2 = EnvFactsDistiller.load("acme/widget", str(tmp_path))
assert d2.now == 4 and d2.render() == d.render()
- assert json.load(open(os.path.join(str(tmp_path), ci.STATE_SUBDIR, "acme__widget.json")))["opt_tokens"] == 0.0
+ assert json.load(open(os.path.join(str(tmp_path), ef.STATE_SUBDIR, "acme__widget.json")))["opt_tokens"] == 0.0
def test_claude_schema_yields_the_same_fact(tmp_path):
@@ -247,41 +347,19 @@ def test_prefix_stage_envfacts_profile_needs_no_runner_and_reports_zero(tmp_path
assert "form_repair:run_tests:python -m pytest" in srow["manual_facts"]
-def test_the_llm_free_arm_is_registered_and_makes_no_paid_call():
- """`codex-inject-envfacts` is the LLM-free ablation: the layer this module implements,
- with no proposer. (The DEFAULT Codex injection arm has carried the paid proposer on top
- since 2026-09-12 -- see tests/test_envfacts_profiles.py.)"""
- from tokeneconomizer.arms import ARMS
- cfg = ARMS["codex-inject-envfacts"].cfg()
- assert cfg.injection.enabled and cfg.injection.profile == "envfacts"
- assert cfg.injection.paid is False
- assert needs_optimizer(cfg) is False
- assert ARMS["codex-inject-envfacts"].mode == "manual4"
- assert ARMS["codex-inject-untool"].cfg().tooling.codex_untool is True
- assert needs_optimizer(EconomizerConfig(injection=InjectionConfig(enabled=True))) is True
-
-
# ---- rtk's Codex mode puts `rtk` in front of every command the agent types ----------------
-def test_the_classifiers_see_through_rtks_command_prefix():
- """`codex-trimech-rtk` stacks injection and the spiral on an agent that has been told to
- type `rtk pytest`, `rtk git status`, `rtk proxy <cmd>`. Before this, the environment-fact
- vocabulary (first token) and the spiral's test-run detector (anchored) both stopped
- recognising a test run under that prefix -- no fact ever formed and no green was ever
- trusted, on exactly the arm that co-activates them. Pinned as bare == prefixed, so a new
- wrapper spelling has to be added to trace.RTK_PREFIX_RE and nowhere else."""
- from tokeneconomizer.mechanisms import envfacts as ef, codex_spiral as cs
+def test_the_classifier_sees_through_rtks_command_prefix():
+ """An agent told to type `rtk pytest`, `rtk git status`, `rtk proxy <cmd>` must still be
+ read as running the tests, fetching, querying the repository. Pinned as bare == prefixed,
+ so a new wrapper spelling has to be added to trace.RTK_PREFIX_RE and nowhere else."""
from tokeneconomizer.trace import strip_rtk_prefix
cases = ("python -m pytest tests/ -q", "pytest -q", "bin/test sympy/x.py", "K=1 pytest -q",
"pip install foo", "curl https://x", "git status", "rg -n foo src")
for bare in cases:
for pre in ("rtk ", "rtk proxy ", "rtk K=2 "):
wrapped = pre + bare
- assert ([(o.intent, o.form) for o in ef.classify_command(wrapped)]
- == [(o.intent, o.form) for o in ef.classify_command(bare)]), wrapped
- assert cs.is_verification_command(wrapped) == cs.is_verification_command(bare), wrapped
- # a compound command keeps its second segment visible too
- assert cs.is_verification_command("cd x && rtk pytest -q")
- assert cs.is_verification_command("rtk pytest -q") and not cs.is_verification_command("rtk git status")
+ assert ([(o.intent, o.form) for o in observe.classify_command(wrapped)]
+ == [(o.intent, o.form) for o in observe.classify_command(bare)]), wrapped
# the stripper is exact: a bare `rtk`, or a command that merely starts with the letters,
# is not a wrapper
assert strip_rtk_prefix("rtk pytest -q") == "pytest -q"
diff --git a/tests/test_envfacts_args.py b/tests/test_envfacts_args.py
new file mode 100644
index 0000000..2423b35
--- /dev/null
+++ b/tests/test_envfacts_args.py
@@ -0,0 +1,292 @@
+"""Facts about HOW a command is called: the shape of the test labels the runner takes, and an
+environment variable the code asks for. Both are learned LLM-free from a failure followed, in
+the same task, by the run that worked."""
+import pytest
+
+from tokeneconomizer.microskills import envfacts as ef, observe
+from fixtures import write_claude_transcript
+
+OK = "Ran 4 tests in 0.1s\n\nOK"
+
+
+def _edit(i):
+ return ("Edit", {"file_path": f"/r/pkg/mod{i}.py", "old_string": "a", "new_string": "b"}, "ok")
+
+
+def _run(label):
+ return ("Bash", {"command": f"python tests/runtests.py {label} -v 2 2>&1 | tail -20"})
+
+
+def _stream(tmp_path, tasks):
+ """Run a distiller over tasks (lists of calls); return it and what it rendered per task."""
+ d = ef.EnvFactsDistiller("acme/widget")
+ rendered = []
+ for i, calls in enumerate(tasks):
+ rendered.append(d.render())
+ d.update(write_claude_transcript(str(tmp_path / f"t{i}.jsonl"), calls), iid=f"t{i}")
+ return d, rendered
+
+
[email protected]("a,b,rule", [
+ ("tests.model_inheritance", "model_inheritance", ("strip", "tests.")),
+ ("tests.admin_views.tests", "admin_views.tests", ("strip", "tests.")),
+ ("db.datetime.test_x::DateTests::test_a", "db.datetime.test_x.DateTests.test_a", ("sep", "::")),
+ ("db.datetime.test_x::DateTests", "db.datetime.test_x", ("sep", "::")),
+ ("model_fields.DurationFieldTests", "model_fields", None), # a class that is not there
+ ("admin_views.ChangeListTests", "admin_views", None),
+ ("app.tests", "other.tests", None),
+])
+def test_only_a_shape_rewrite_counts_as_a_repair(a, b, rule):
+ assert observe.label_rule(a, b) == rule
+
+
+def test_labels_are_the_structured_arguments_after_the_runner():
+ o = observe.classify_command("python tests/runtests.py tests.app -v 2 --settings=x 2>&1 | tail")[0]
+ assert observe._test_labels(o) == ("tests.app",)
+ o = observe.classify_command("python -m pytest pkg/test_a.py::T::test_b -q > /tmp/o.log")[0]
+ assert observe._test_labels(o) == ("pkg/test_a.py::T::test_b",)
+
+
+def test_a_label_prefix_the_runner_rejects_becomes_a_fact(tmp_path):
+ tasks = [[_edit(i), _run(f"tests.app{i}") + ("ModuleNotFoundError: No module named 'tests'",),
+ _run(f"app{i}") + (OK,)] for i in range(6)]
+ d, rendered = _stream(tmp_path, tasks)
+ assert "takes test labels without the `tests.` prefix" in rendered[-1]
+ claim = next(f.claim() for f in d.facts.values() if f.family == "arg_repair")
+ assert claim.startswith("`python tests/runtests.py` takes") and "(`app" in claim
+ assert ef.lint_ok(claim)
+
+
+def test_pytest_style_separators_the_runner_rejects_become_a_fact(tmp_path):
+ tasks = [[_edit(i),
+ _run(f"app{i}.tests::T::test_x") + (
+ f"ImportError: Failed to import test module: app{i}.tests::T::test_x",),
+ _run(f"app{i}.tests.T.test_x") + (OK,)] for i in range(6)]
+ _, rendered = _stream(tmp_path, tasks)
+ assert "takes dotted test labels" in rendered[-1]
+
+
+def test_a_plain_mistake_is_not_a_fact(tmp_path):
+ tasks = [[_edit(i),
+ _run(f"app{i}.tests.Missing") + (
+ f"AttributeError: module 'app{i}.tests' has no attribute 'Missing'",),
+ _run(f"app{i}") + (OK,)] for i in range(6)]
+ d, rendered = _stream(tmp_path, tasks)
+ assert not [f for f in d.facts.values() if f.family == "arg_repair"]
+ assert rendered[-1] == ""
+
+
+def test_a_prefixed_label_that_loads_contradicts_the_fact(tmp_path):
+ tasks = [[_edit(i), _run(f"tests.app{i}") + ("ModuleNotFoundError: No module named 'tests'",),
+ _run(f"app{i}") + (OK,)] for i in range(4)]
+ tasks.append([_edit(9), _run("tests.app9") + (OK,)])
+ d, _ = _stream(tmp_path, tasks)
+ fid = next(k for k in d.facts if k.startswith("arg_repair:"))
+ assert d.last_digest["verdicts"][fid][0] == "contradict"
+
+
+def _py(code, env=""):
+ return ("Bash", {"command": f"{env}python -c '{code}'"})
+
+
+NEED = ("Traceback (most recent call last):\n ...\nRuntimeError: settings are missing. Define "
+ "the environment variable APP_SETTINGS before importing app.")
+
+
+def test_an_environment_variable_the_code_asks_for_and_its_working_value_become_a_fact(tmp_path):
+ tasks = [[_edit(i), _py("import app; app.run()") + (NEED,),
+ _py("import app; app.run()", "APP_SETTINGS=conf.missing ") + (
+ "Traceback (most recent call last):\nModuleNotFoundError: No module named "
+ "'conf.missing'",),
+ _py("import app; app.run()", "APP_SETTINGS=conf.dev ") + ("ran",)]
+ for i in range(6)]
+ d, rendered = _stream(tmp_path, tasks)
+ assert ("Code that imports the project needs `APP_SETTINGS` set here: "
+ "`APP_SETTINGS=conf.dev` works, `conf.missing` does not.") in rendered[-1]
+ assert ef.lint_ok(d.facts["env_value:APP_SETTINGS"].claim())
+
+
+def test_a_value_set_in_the_code_counts_too(tmp_path):
+ code = 'import os; os.environ.setdefault("APP_SETTINGS", "conf.dev"); import app'
+ tasks = [[_edit(i), _py("import app") + (NEED,), ("Bash", {"command": f"python -c '{code}'"},
+ "ran")] for i in range(6)]
+ d, _ = _stream(tmp_path, tasks)
+ assert d.facts["env_value:APP_SETTINGS"].params["good"] == {"conf.dev": 6}
+
+
+def test_no_value_that_worked_means_no_fact(tmp_path):
+ tasks = [[_edit(i), _py("import app") + (NEED,),
+ _py("import app", "APP_SETTINGS=conf.missing ") + ("Traceback (most recent call "
+ "last):\nNameError: x",)]
+ for i in range(6)]
+ d, _ = _stream(tmp_path, tasks)
+ assert "env_value:APP_SETTINGS" not in d.facts
+
+
+def test_output_filtered_away_neither_teaches_nor_contradicts(tmp_path):
+ """`| grep FAILED` or a silent run shows no tests running: it proves nothing about the label
+ (both cases were in real sessions, and once retired a correct fact)."""
+ tasks = [[_edit(i), _run(f"app{i}.tests::T::test_x") + (
+ f"app{i}.tests::T::test_x (unittest.loader._FailedTest) ... ERROR",),
+ _run(f"app{i}.tests.T.test_x") + (OK,)] for i in range(4)]
+ tasks.append([_edit(8), _run("app8.tests::T::test_x") + ("FAILED (errors=1)",),
+ _run("app8.tests::T::test_y") + ("",)])
+ d, _ = _stream(tmp_path, tasks)
+ fid = "arg_repair:python tests/runtests.py:sep:::"
+ assert d.last_digest["verdicts"][fid][0] != "contradict"
+ assert d.facts[fid].state != "RETIRED"
+
+
+def test_a_repair_needs_the_rewritten_label_to_have_run_tests(tmp_path):
+ tasks = [[_edit(i), _run(f"tests.app{i}") + ("ModuleNotFoundError: No module named 'tests'",),
+ _run(f"app{i}") + ("",)] for i in range(6)] # no evidence the tests ran
+ d, _ = _stream(tmp_path, tasks)
+ assert not [f for f in d.facts.values() if f.family == "arg_repair"]
+
+
+def test_being_asked_for_the_variable_again_does_not_confirm_its_value(tmp_path):
+ tasks = [[_edit(0), _py("import app") + (NEED,),
+ _py("import app", "APP_SETTINGS=conf.dev ") + ("ran",)]]
+ tasks += [[_edit(i), _py("import app") + (NEED,)] for i in range(1, 6)]
+ d, rendered = _stream(tmp_path, tasks)
+ assert d.facts["env_value:APP_SETTINGS"].state == "CANDIDATE"
+ assert "APP_SETTINGS" not in rendered[-1]
+
+
+def test_mistyped_labels_do_not_teach_that_the_runner_fails(tmp_path):
+ """Seen in a live stream: bad labels report `ModuleNotFoundError` inside unittest's
+ `_FailedTest`, and a later `cd tests && python runtests.py` worked. That once became
+ "`python tests/runtests.py` fails here; `python runtests.py` works" -- wrong twice over."""
+ bad = ("tests (unittest.loader._FailedTest) ... ERROR\nImportError: Failed to import test "
+ "module: tests\nModuleNotFoundError: No module named 'tests.app'")
+ tasks = [[_edit(i), _run(f"tests.app{i}.tests.T") + (bad,),
+ ("Bash", {"command": f"cd tests && python runtests.py app{i}.tests.T -v 2"}, OK)]
+ for i in range(6)]
+ d, rendered = _stream(tmp_path, tasks)
+ assert not [f for f in d.facts.values() if f.family == "form_repair"]
+ assert "fails here" not in rendered[-1]
+
+
+def test_a_directory_change_is_part_of_the_form():
+ o = observe.classify_command("cd tests && python runtests.py forms -v 2")[0]
+ assert o.form == "cd tests && python runtests.py" and observe._test_labels(o) == ("forms",)
+
+
+def test_a_missing_runner_is_still_a_form_failure_not_a_label_one():
+ assert not observe._label_failed(("tests/test_a.py",), "/usr/bin/python3: No module named pytest")
+ assert observe._label_failed(("tests.app",), "ModuleNotFoundError: No module named 'tests'")
+ assert observe._label_failed(("app.tests.Missing",),
+ "AttributeError: module 'app.tests' has no attribute 'Missing'")
+ assert not observe._label_failed(("app.tests",), "AttributeError: 'NoneType' object has no "
+ "attribute 'pk'")
+
+
+ROOT = "/r"
+
+
+def _at(call, cwd):
+ return call + (cwd,)
+
+
+def _sh(cmd, out):
+ return ("Bash", {"command": cmd}, out)
+
+
+def test_a_bare_runner_in_a_directory_an_earlier_cd_left_is_learned_with_that_cd(tmp_path):
+ """Seen in a live session: Claude Code's shell keeps its directory, so after `cd tests &&
+ python runtests.py ...` the agent ran a bare `python runtests.py ...` -- in `tests/`. Read
+ without the directory, that taught "`python runtests.py` works", which fails from the
+ directory sessions start in."""
+ tasks = [[_at(_edit(i), ROOT),
+ _at(_sh("python -m pytest tests/app/tests.py -q",
+ "/venv/bin/python: No module named pytest"), ROOT),
+ _at(_sh(f"cd tests && python runtests.py app{i} -v 2", OK), ROOT),
+ _at(_sh(f"python runtests.py app{i}.tests -v 2", OK), ROOT + "/tests"),
+ _at(_sh("python runtests.py app.tests 2>&1 | tail -3",
+ "python: can't open file 'runtests.py': [Errno 2] No such file or "
+ "directory"), ROOT)]
+ for i in range(6)]
+ d, rendered = _stream(tmp_path, tasks)
+ assert "`(cd tests && python runtests.py …)` works" in rendered[-1]
+ assert "`python runtests.py …` works" not in rendered[-1]
+ assert not any(k.endswith(":python runtests.py") for k in d.facts), sorted(d.facts)
+
+
+def test_a_cd_into_the_start_directory_by_absolute_path_is_no_cd():
+ o = observe.classify_command("cd /r && python tests/runtests.py app", cwd="", root="/r")[0]
+ assert o.form == "python tests/runtests.py"
+ o = observe.classify_command("cd /r/tests && python runtests.py app", cwd="", root="/r")[0]
+ assert o.form == "cd tests && python runtests.py"
+ o = observe.classify_command("cd .. && python runtests.py app", cwd="tests", root="/r")[0]
+ assert o.form == "python runtests.py"
+ o = observe.classify_command("python runtests.py app", cwd="tests", root="/r")[0]
+ assert o.form == "cd tests && python runtests.py"
+ o = observe.classify_command("cd /elsewhere && python runtests.py app", cwd="", root="/r")[0]
+ assert o.form == "cd /elsewhere && python runtests.py" # left the start: as typed
+
+
+def test_a_command_stopped_by_its_own_cd_teaches_nothing(tmp_path):
+ p = write_claude_transcript(str(tmp_path / "t.jsonl"), [
+ _at(_sh("cd tests && python runtests.py app", "Exit code 1\n/bin/bash: line 1: cd: "
+ "tests: No such file or directory"), ROOT + "/tests")])
+ assert observe.observe_task(p)["obs"] == []
+
+
+def test_call_directories_line_up_with_the_calls(tmp_path):
+ from tokeneconomizer import trace
+ p = write_claude_transcript(str(tmp_path / "t.jsonl"), [
+ _at(_sh("ls", "a"), ROOT), ("Read", {"file_path": "/r/a"}, "x"),
+ _at(_sh("ls", "b"), ROOT + "/tests")])
+ assert trace.call_cwds(p) == [ROOT, None, ROOT + "/tests"]
+ assert len(trace.load_trajectory(p)) == 3
+
+
+CANT_OPEN = ("Exit code 2\npython: can't open file 'runtests.py': [Errno 2] No such file or "
+ "directory")
+
+
+def test_a_runner_script_run_where_it_is_not_becomes_a_fact(tmp_path):
+ tasks = [[_at(_edit(i), ROOT), _at(_sh(f"python runtests.py app{i}", CANT_OPEN), ROOT),
+ _at(_sh(f"cd tests && python runtests.py app{i}", OK), ROOT)] for i in range(6)]
+ _, rendered = _stream(tmp_path, tasks)
+ assert ("`python runtests.py …` fails here with a file-not-found error; "
+ "`(cd tests && python runtests.py …)` works.") in rendered[-1]
+
+
+def test_an_option_the_runner_rejects_is_not_a_failing_form(tmp_path):
+ """Seen live: `-k name` to Django's runner, from `tests/`, is "unrecognized arguments" --
+ the runner ran and refused an argument."""
+ bad = "Exit code 2\nusage: runtests.py [-h] [module [module ...]]\nruntests.py: error: " \
+ "unrecognized arguments: test_x"
+ tasks = [[_at(_edit(i), ROOT), _at(_sh(f"python runtests.py app{i} -k test_x", bad),
+ ROOT + "/tests"),
+ _at(_sh(f"python tests/runtests.py app{i}", OK), ROOT)] for i in range(6)]
+ d, rendered = _stream(tmp_path, tasks)
+ assert not [f for f in d.facts.values() if f.family == "form_repair"], sorted(d.facts)
+
+
+def test_a_run_whose_output_was_filtered_away_does_not_show_a_form_works(tmp_path):
+ """Seen live: `python runtests.py x 2>&1 | grep -E "^(OK|FAILED|Ran )"` at the root printed
+ nothing -- the "can't open file" was filtered out -- and counted as the form working."""
+ tasks = [[_at(_edit(i), ROOT), _at(_sh("python -m pytest tests/app", "Exit code 1\n"
+ "/venv/bin/python: No module named pytest"), ROOT),
+ _at(_sh(f"python runtests.py app{i} 2>&1 | grep -E '^(OK|FAILED|Ran )'",
+ "(Bash completed with no output)"), ROOT)] for i in range(6)]
+ d, _ = _stream(tmp_path, tasks)
+ assert not [f for f in d.facts.values() if f.family == "form_repair"], sorted(d.facts)
+
+
+def test_a_working_form_that_leaves_the_shell_where_it_is_is_the_one_named(tmp_path):
+ """Seen live: the fact named `cd tests && python runtests.py`, agents typed it, and their
+ shell stayed in `tests/` -- every later `cd tests && ...` failed. A form that does not move
+ the shell is named whenever one has worked, however rarely."""
+ tasks = [[_at(_edit(i), ROOT), _at(_sh(f"python runtests.py app{i}", CANT_OPEN), ROOT),
+ _at(_sh(f"cd tests && python runtests.py app{i}", OK), ROOT),
+ _at(_sh(f"cd tests && python runtests.py app{i}.tests", OK), ROOT)]
+ for i in range(6)]
+ tasks[3].append(_at(_sh("python tests/runtests.py app3", OK), ROOT))
+ d, rendered = _stream(tmp_path, tasks)
+ f = d.facts["form_repair:run_tests:python runtests.py"]
+ assert f.params["b_counts"]["cd tests && python runtests.py"] > \
+ f.params["b_counts"]["python tests/runtests.py"]
+ assert "`python tests/runtests.py …` works" in rendered[-1]
diff --git a/tests/test_injection.py b/tests/test_injection.py
index 989b875..490726c 100644
--- a/tests/test_injection.py
+++ b/tests/test_injection.py
@@ -1,7 +1,7 @@
"""Injection: the distiller lifecycle + the PrefixStage render/after_task cycle."""
import os
-from tokeneconomizer.mechanisms.injection import Distiller, PrefixStage
+from tokeneconomizer.microskills import Distiller, PrefixStage
from tokeneconomizer.config import InjectionConfig
from fixtures import write_claude_transcript
@@ -41,7 +41,7 @@ def test_distiller_grounds_and_fires_a_fact(tmp_path):
d = Distiller("acme/widget", runner=_facts_runner(payload))
d.last_propose = -1
# feed several tasks that each run pytest and pass, on disjoint edited files
- import tokeneconomizer.mechanisms.injection as inj
+ import tokeneconomizer.microskills.distiller as inj
inj.PROPOSE_EVERY = 1
for i in range(8):
tr = str(tmp_path / f"t{i}.jsonl")
diff --git a/tests/test_live_config.py b/tests/test_live_config.py
index c9f81ce..efbcdde 100644
--- a/tests/test_live_config.py
+++ b/tests/test_live_config.py
@@ -9,16 +9,16 @@ import os
import pytest
-from te_live import guard
-from te_live.config import LiveConfig, load_config, unset_config, write_config
-from te_live.paths import repo_identity, repo_state_dir
+from tokeneconomizer import loopguard as guard
+from tokeneconomizer.plugin.config import LiveConfig, load_config, unset_config, write_config
+from tokeneconomizer.plugin.paths import repo_identity, repo_state_dir
from tests.test_live_hooks import (GREEN, _first, _turn, env, repo, run_session, # noqa: F401
stuck_calls, trap_session)
# ---- parsing ------------------------------------------------------------------------------
[email protected]("key,on", [("inject", "envfacts"), ("untool", "propose"),
- ("spiral", "nudge")])
[email protected]("key,on", [("microskills", "envfacts"), ("toolprune", "propose"),
+ ("loopguard", "nudge")])
def test_each_mechanism_takes_a_plain_on_and_off(key, on):
cfg = LiveConfig()
assert cfg.set(key, "off") and getattr(cfg, key) == "off"
@@ -29,50 +29,90 @@ def test_each_mechanism_takes_a_plain_on_and_off(key, on):
def test_a_guard_threshold_is_typed_and_range_checked():
cfg = LiveConfig()
- assert cfg.set("spiral.min_turns", "12") and cfg.spiral_thresholds["min_turns"] == 12
- assert cfg.set("spiral.backstop_mult", "2") and cfg.spiral_thresholds["backstop_mult"] == 2.0
- assert not cfg.set("spiral.min_turns", "12.5") # a count is a whole number
- assert not cfg.set("spiral.stagnation", "1.5") # a share is between 0 and 1
- assert not cfg.set("spiral.min_turns", "0")
- assert not cfg.set("spiral.no_such_threshold", "3")
- assert cfg.spiral_thresholds == {"min_turns": 12, "backstop_mult": 2.0}
+ assert cfg.set("loopguard.min_turns", "12") and cfg.loopguard_thresholds["min_turns"] == 12
+ assert (cfg.set("loopguard.backstop_mult", "2")
+ and cfg.loopguard_thresholds["backstop_mult"] == 2.0)
+ assert not cfg.set("loopguard.min_turns", "12.5") # a count is a whole number
+ assert not cfg.set("loopguard.stagnation", "1.5") # a share is between 0 and 1
+ assert not cfg.set("loopguard.min_turns", "0")
+ assert not cfg.set("loopguard.no_such_threshold", "3")
+ assert cfg.loopguard_thresholds == {"min_turns": 12, "backstop_mult": 2.0}
assert len(cfg.warnings) == 4
def test_set_and_unset_keep_thresholds_in_their_own_object(tmp_path):
path = str(tmp_path / "config.json")
- write_config(path, {"spiral": "off", "spiral.min_turns": "12", "spiral.edit_churn": "6"})
- assert json.load(open(path)) == {"spiral": "off",
- "spiral_thresholds": {"edit_churn": 6, "min_turns": 12}}
+ write_config(path, {"loopguard": "off", "loopguard.min_turns": "12",
+ "loopguard.edit_churn": "6"})
+ assert json.load(open(path)) == {"loopguard": "off",
+ "loopguard_thresholds": {"edit_churn": 6, "min_turns": 12}}
with pytest.raises(ValueError):
- write_config(path, {"spiral.min_turns": "-1"}) # nothing written on a rejection
- unset_config(path, ["spiral.min_turns", "spiral"])
- assert json.load(open(path)) == {"spiral_thresholds": {"edit_churn": 6}}
- unset_config(path, ["spiral.edit_churn"])
+ write_config(path, {"loopguard.min_turns": "-1"}) # nothing written on a rejection
+ unset_config(path, ["loopguard.min_turns", "loopguard"])
+ assert json.load(open(path)) == {"loopguard_thresholds": {"edit_churn": 6}}
+ unset_config(path, ["loopguard.edit_churn"])
assert json.load(open(path)) == {}
with pytest.raises(ValueError):
- unset_config(path, ["spiral.nope"])
+ unset_config(path, ["loopguard.nope"])
def test_the_repository_file_beats_the_global_one_and_the_environment_beats_both(tmp_path):
root, repo_dir = tmp_path / "root", tmp_path / "repo"
- write_config(str(root / "config.json"), {"spiral_nudges": "3", "spiral.min_turns": "30"})
- write_config(str(repo_dir / "config.json"), {"spiral.min_turns": "10"})
+ write_config(str(root / "config.json"), {"loopguard_nudges": "3",
+ "loopguard.min_turns": "30"})
+ write_config(str(repo_dir / "config.json"), {"loopguard.min_turns": "10"})
cfg = load_config(str(root), str(repo_dir), env={})
- assert cfg.spiral_nudges == 3 and cfg.spiral_thresholds == {"min_turns": 10}
+ assert cfg.loopguard_nudges == 3 and cfg.loopguard_thresholds == {"min_turns": 10}
cfg = load_config(str(root), str(repo_dir), env={
- "TE_SPIRAL_NUDGES": "2", "TE_SPIRAL_THRESHOLDS": '{"min_turns": 8, "stagnation": 0.5}',
- "TE_INJECT_MAX_FACTS": "2", "TE_SPIRAL": "off"})
- assert cfg.spiral_nudges == 2 and cfg.inject_max_facts == 2 and cfg.spiral == "off"
- assert cfg.spiral_thresholds == {"min_turns": 8, "stagnation": 0.5}
+ "TE_LOOPGUARD_NUDGES": "2",
+ "TE_LOOPGUARD_THRESHOLDS": '{"min_turns": 8, "stagnation": 0.5}',
+ "TE_MICROSKILLS_MAX_FACTS": "2", "TE_LOOPGUARD": "off"})
+ assert cfg.loopguard_nudges == 2 and cfg.microskills_max_facts == 2
+ assert cfg.loopguard == "off"
+ assert cfg.loopguard_thresholds == {"min_turns": 8, "stagnation": 0.5}
assert not cfg.warnings
+def test_the_names_before_the_rename_still_work(tmp_path):
+ """`inject`, `untool`, `spiral` and their settings and variables are read as the new names;
+ a file holding both spellings takes the new one; writing a setting stores its new name and
+ drops the old spelling; unsetting by either name removes both."""
+ root, repo_dir = tmp_path / "root", tmp_path / "repo"
+ os.makedirs(root)
+ with open(root / "config.json", "w") as fh:
+ json.dump({"loopguard": "off", "spiral": "guard", "inject_max_facts": 3,
+ "untool": "auto", "propose_every": 7, "spiral_aggr": "aggressive",
+ "spiral_thresholds": {"min_turns": 9}}, fh)
+ cfg = load_config(str(root), str(repo_dir), env={
+ "TE_SPIRAL_NUDGES": "2", "TE_UNTOOL_EVIDENCE": "4", "TE_INJECT": "off"})
+ assert cfg.loopguard == "off" # the new name wins in one file
+ assert (cfg.microskills_max_facts, cfg.toolprune, cfg.microskills_propose_every,
+ cfg.loopguard_aggr) == (3, "auto", 7, "aggressive")
+ assert cfg.loopguard_thresholds == {"min_turns": 9}
+ assert (cfg.loopguard_nudges, cfg.toolprune_evidence, cfg.microskills) == (2, 4, "off")
+ assert not cfg.warnings
+ # a new variable beats its old spelling
+ assert load_config(str(root), env={"TE_SPIRAL": "nudge",
+ "TE_LOOPGUARD": "stop"}).loopguard == "stop"
+ assert LiveConfig().set("spiral", "guard") and LiveConfig().set("loopguard", "guard")
+ path = str(root / "config.json")
+ write_config(path, {"spiral": "nudge", "spiral.edit_churn": "5"})
+ written = json.load(open(path))
+ assert written["loopguard"] == "nudge" and "spiral" not in written
+ assert written["loopguard_thresholds"] == {"min_turns": 9, "edit_churn": 5}
+ assert "spiral_thresholds" not in written
+ unset_config(path, ["untool", "inject_max_facts", "spiral.min_turns"])
+ written = json.load(open(path))
+ assert "untool" not in written and "toolprune" not in written
+ assert "inject_max_facts" not in written
+ assert written["loopguard_thresholds"] == {"edit_churn": 5}
+
+
def test_the_fact_caps_default_to_the_cores_own():
- from tokeneconomizer.mechanisms import envfacts
+ from tokeneconomizer.microskills import envfacts
cfg = LiveConfig()
- assert (cfg.inject_max_facts, cfg.inject_max_tokens) == (envfacts.MAX_FACTS,
- envfacts.MAX_TOKENS)
+ assert (cfg.microskills_max_facts, cfg.microskills_max_tokens) == (envfacts.MAX_FACTS,
+ envfacts.MAX_TOKENS)
# ---- thresholds: preset, then learned, then pinned ----------------------------------------
diff --git a/tests/test_live_core.py b/tests/test_live_core.py
index 731623a..7ef4c54 100644
--- a/tests/test_live_core.py
+++ b/tests/test_live_core.py
@@ -11,9 +11,9 @@ import os
import pytest
from tokeneconomizer import trace
-from te_live import config as live_config
-from te_live import hosts, paths, transcripts
-from te_live.store import Store
+from tokeneconomizer.plugin import config as live_config
+from tokeneconomizer.plugin import hosts, paths
+from tokeneconomizer.plugin.store import Store
# ---- repository identity ---------------------------------------------------------------
@@ -90,13 +90,14 @@ def test_config_layers_and_never_raises_on_bad_values(tmp_path):
repo_dir = os.path.join(root, "repos", "r")
os.makedirs(repo_dir)
with open(os.path.join(root, "config.json"), "w") as fh:
+ # names from before the mechanisms were renamed: still read
json.dump({"spiral": "guard", "untool_evidence": 7, "bogus": 1}, fh)
with open(os.path.join(repo_dir, "config.json"), "w") as fh:
json.dump({"spiral": "nope", "inject": "envfacts+distiller"}, fh)
cfg = live_config.load_config(root, repo_dir=repo_dir, env={"TE_UNTOOL": "auto"})
- assert cfg.spiral == "guard" # the invalid repo value is ignored
- assert cfg.untool_evidence == 7 and cfg.untool == "auto"
- assert cfg.inject == "envfacts+distiller" and cfg.inject_effective == "envfacts"
+ assert cfg.loopguard == "stop" # the invalid repo value is ignored
+ assert cfg.toolprune_evidence == 7 and cfg.toolprune == "auto"
+ assert cfg.microskills == "envfacts+distiller" and cfg.microskills_effective == "envfacts"
joined = " ".join(cfg.warnings)
assert "bogus" in joined and "nope" in joined and "paid=false" in joined
assert live_config.load_config(root, env={"TE_DISABLE": "1"}).enabled is False
@@ -104,11 +105,11 @@ def test_config_layers_and_never_raises_on_bad_values(tmp_path):
def test_write_config_validates_before_writing(tmp_path):
path = str(tmp_path / "config.json")
- live_config.write_config(path, {"spiral": "off", "paid": "true"})
- assert json.load(open(path)) == {"spiral": "off", "paid": True}
+ live_config.write_config(path, {"loopguard": "off", "paid": "true"})
+ assert json.load(open(path)) == {"loopguard": "off", "paid": True}
with pytest.raises(ValueError):
- live_config.write_config(path, {"spiral": "sometimes"})
- assert json.load(open(path))["spiral"] == "off"
+ live_config.write_config(path, {"loopguard": "sometimes"})
+ assert json.load(open(path))["loopguard"] == "off"
# ---- Claude Code transcripts -----------------------------------------------------------------
@@ -132,11 +133,11 @@ def test_claude_usage_counts_each_message_once_and_includes_subagents(tmp_path):
sub_dir = tmp_path / "sess" / "subagents"
sub_dir.mkdir(parents=True)
_claude_lines(str(sub_dir / "agent-1.jsonl"), blocks_per_message=2, n_messages=1)
- u = transcripts.claude_session_usage(main)
+ u = trace.claude_session_usage(main)
assert u["requests"] == 3 # 2 main messages + 1 subagent message
assert u["cache_read_input_tokens"] == 3000 # not 3 x 2 x 1000 + 2 x 1000
assert u["model"] == "claude-opus-5-5" and u["files"] == 2
- assert transcripts.claude_session_usage(main, include_subagents=False)["requests"] == 2
+ assert trace.claude_session_usage(main, include_subagents=False)["requests"] == 2
def test_deferred_tools_are_read_from_attachments(tmp_path):
@@ -147,7 +148,7 @@ def test_deferred_tools_are_read_from_attachments(tmp_path):
"removedNames": []}}) + "\n")
fh.write(json.dumps({"type": "attachment", "attachment": {
"type": "deferred_tools_delta", "addedNames": [], "removedNames": ["WebSearch"]}}) + "\n")
- assert transcripts.claude_deferred_tools(p) == {"CronCreate"}
+ assert trace.claude_deferred_tools(p) == {"CronCreate"}
# ---- Codex rollouts ---------------------------------------------------------------------------
@@ -179,7 +180,7 @@ def _rollout(path):
def test_codex_rollout_reads_through_the_existing_trace_seam(tmp_path):
src = _rollout(str(tmp_path / "rollout-x.jsonl"))
out = str(tmp_path / "exec.jsonl")
- assert transcripts.codex_rollout_to_exec(src, out) == 2 # reasoning is not a tool call
+ assert trace.codex_rollout_to_exec(src, out) == 2 # reasoning is not a tool call
traj = trace.load_trajectory(out)
assert traj[0][0] == "shell" and traj[0][1]["command"] == "/bin/bash -lc 'pytest -q'"
assert traj[0][2] == "1 failed" and traj[0][3] is False
@@ -187,7 +188,7 @@ def test_codex_rollout_reads_through_the_existing_trace_seam(tmp_path):
def test_codex_usage_is_converted_as_the_harness_converts_it(tmp_path):
- u = transcripts.codex_session_usage(_rollout(str(tmp_path / "rollout-x.jsonl")))
+ u = trace.codex_session_usage(_rollout(str(tmp_path / "rollout-x.jsonl")))
# last cumulative total; fresh input excludes both cache fields; reasoning joins output
assert u["input_tokens"] == 3000 - 2000 - 200
assert u["cache_read_input_tokens"] == 2000 and u["cache_creation_input_tokens"] == 200
@@ -197,7 +198,7 @@ def test_codex_usage_is_converted_as_the_harness_converts_it(tmp_path):
def test_codex_capability_evidence_includes_the_models_own_exec_calls(tmp_path):
"""In code mode every tool call is one `exec` custom tool; `tools.view_image(` inside its
input is image use, and only the capability trace carries it."""
- from tokeneconomizer.mechanisms import codex_untool as cu
+ from tokeneconomizer.toolprune import codex as cu
src = _rollout(str(tmp_path / "rollout-x.jsonl"))
with open(src, "a") as fh:
fh.write(json.dumps({"type": "response_item", "payload": {
@@ -205,18 +206,18 @@ def test_codex_capability_evidence_includes_the_models_own_exec_calls(tmp_path):
"status": "completed",
"input": "const r = await tools.view_image({path: 'a.png'});"}}) + "\n")
out = str(tmp_path / "cap.jsonl")
- assert transcripts.codex_capability_trace(src, out) == 3
+ assert trace.codex_capability_trace(src, out) == 3
usage = cu.inspect_usage(out)
assert usage["completed"]["image_media"] == 1 and usage["completed"]["collaboration"] == 0
plain = str(tmp_path / "exec.jsonl")
- transcripts.codex_rollout_to_exec(src, plain)
+ trace.codex_rollout_to_exec(src, plain)
assert cu.inspect_usage(plain)["completed"]["image_media"] == 0
def test_a_compressed_rollout_is_reported_unreadable(tmp_path):
p = str(tmp_path / "rollout-x.jsonl.zst")
open(p, "wb").write(b"\x28\xb5\x2f\xfd")
- assert transcripts.codex_rollout_to_exec(p, str(tmp_path / "o.jsonl")) is None
+ assert trace.codex_rollout_to_exec(p, str(tmp_path / "o.jsonl")) is None
# ---- hosts ---------------------------------------------------------------------------------
@@ -242,6 +243,28 @@ def test_the_te_command_defaults_to_the_agent_whose_shell_runs_it():
assert hosts.default_host({"COPILOT_CLI": "1", "CLAUDECODE": "1"}) == "claude"
assert hosts.default_host({"TE_HOST": "codex", "CLAUDECODE": "1"}) == "codex"
assert hosts.default_host({"TE_HOST": "nonsense"}) == "claude"
+ assert hosts.default_host({}, recent="pi") == "pi"
+ assert hosts.default_host({"CLAUDECODE": "1"}, recent="pi") == "claude"
+
+
+def test_from_a_plain_terminal_te_is_about_the_agent_that_last_worked_here(tmp_path, monkeypatch,
+ capsys):
+ """Seen with every non-Claude tester: `te status` from a terminal showed the empty Claude
+ Code state of a repository only Codex (or Pi) had worked in."""
+ from tokeneconomizer.plugin import cli
+ from tokeneconomizer.plugin.paths import repo_identity, repo_state_dir
+ for k in ("TE_HOST", "CLAUDECODE", "COPILOT_CLI"):
+ monkeypatch.delenv(k, raising=False)
+ monkeypatch.setenv("TOKENECONOMIZER_HOME", str(tmp_path / "te"))
+ work = tmp_path / "work"
+ work.mkdir()
+ assert cli._recent_host(str(work)) is None
+ d = repo_state_dir(repo_identity(str(work)), "codex")
+ os.makedirs(d)
+ open(os.path.join(d, "ledger.jsonl"), "w").close()
+ assert cli._recent_host(str(work)) == "codex"
+ assert cli.main(["--cwd", str(work), "status"]) == 0
+ assert "(codex)" in capsys.readouterr().out.splitlines()[0]
# Payloads copilot 1.0.83 sent to a Claude-format plugin hook (PascalCase events), verbatim in
@@ -383,21 +406,41 @@ def _pi_session(path, cwd="/w/repo", sid="pi-1", abandoned=False):
def test_a_pi_session_reads_through_the_trace_seam_on_its_active_branch(tmp_path):
src = _pi_session(str(tmp_path / "s.jsonl"), abandoned=True)
out = str(tmp_path / "trace.jsonl")
- assert transcripts.pi_session_to_claude(src, out) == 3
+ assert trace.pi_session_to_claude(src, out) == 3
traj = trace.load_trajectory(out)
assert [(n, a.get("command") or a.get("path"), ok) for n, a, _, ok in traj] == [
("bash", "pytest -q", False), ("edit", "pkg/a.py", True), ("bash", "python -m pytest -q", True)]
assert "rm -rf build" not in open(out).read() # the abandoned branch is not read
+def test_a_pi_call_into_the_session_directory_is_the_plain_form(tmp_path):
+ """Pi starts every command afresh in the session's directory, so `cd <that dir> && tox`
+ is the same form as `tox`. Without a cwd per call it was learned as a second form, with the
+ absolute path in the claim, and the two split one fact's evidence."""
+ from tokeneconomizer.microskills.observe import PYTHON_GIT, observe_task
+ src = str(tmp_path / "s.jsonl")
+ _pi_session(src, cwd="/w/repo")
+ lines = [json.loads(l) for l in open(src)]
+ for e in lines:
+ for b in (e.get("message") or {}).get("content") or []:
+ if isinstance(b, dict) and b.get("arguments", {}).get("command") == "pytest -q":
+ b["arguments"]["command"] = "cd /w/repo && pytest -q"
+ open(src, "w").write("\n".join(json.dumps(e) for e in lines) + "\n")
+ out = str(tmp_path / "trace.jsonl")
+ trace.pi_session_to_claude(src, out)
+ assert trace.call_cwds(out) == ["/w/repo"] * 3
+ forms = [o.form for o in observe_task(out, PYTHON_GIT)["obs"] if o.intent == "run_tests"]
+ assert forms == ["pytest", "python -m pytest"]
+
+
def test_pi_usage_maps_directly_and_keeps_pis_own_cost(tmp_path):
- u = transcripts.pi_session_usage(_pi_session(str(tmp_path / "s.jsonl"), abandoned=True))
+ u = trace.pi_session_usage(_pi_session(str(tmp_path / "s.jsonl"), abandoned=True))
# three assistant messages on the active branch; output already includes reasoning
assert u["requests"] == 3
assert (u["input_tokens"], u["cache_read_input_tokens"], u["cache_creation_input_tokens"],
u["output_tokens"]) == (30, 3000, 300, 150)
assert u["cost_usd_vendor"] == pytest.approx(0.006) and u["model"] == "gpt-5.6-sol"
- assert transcripts.pi_session_header(str(tmp_path / "s.jsonl"))["cwd"] == "/w/repo"
+ assert trace.pi_session_header(str(tmp_path / "s.jsonl"))["cwd"] == "/w/repo"
def test_the_pi_host_reads_what_the_extension_sends():
@@ -412,7 +455,7 @@ def test_the_pi_host_reads_what_the_extension_sends():
# ---- the guard sees edits made through the shell ---------------------------------------------
-from te_live import guard # noqa: E402
+from tokeneconomizer import loopguard as guard # noqa: E402
@pytest.mark.parametrize("cmd,want", [
@@ -460,6 +503,26 @@ def test_shell_edits_reach_the_state_the_judge_reads_and_the_ended_green_proxy()
assert g.edits == 3 and g.last_verify > g.last_edit and not g.resolved_proxy()
+def test_reading_a_file_full_of_asserts_is_not_a_failure():
+ """Seen live on Pi: a passing 13-call turn that read its test file three times counted four
+ error outputs and two repeated identical failures, and opened the paid judge's gate."""
+ test_file = "def test_total():\n assert total([1, 2]) == 3\n raise ValueError('no')\n"
+ g = guard.TurnGuard(turn_key="t")
+ for _ in range(3):
+ g.fold("read", {"path": "tests/test_total.py"}, test_file)
+ g.fold("grep", {"pattern": "assert"}, "tests/test_total.py:2: assert total")
+ g.fold("bash", {"command": "cat tests/test_total.py"}, test_file, 0)
+ assert (g.whole.error_outputs, g.whole.repeated_fail_sigs) == (0, 0)
+ assert not guard.gate_for_judge(g.whole, dict(guard.DEFAULT_THRESHOLDS, gate_min_turns=1))
+ # what did fail still counts: a non-zero exit, or a read the tool itself reports as failed
+ g.fold("bash", {"command": "pytest -q"}, "FAILED tests/test_total.py - AssertionError", 1)
+ g.fold("bash", {"command": "pytest -q"}, "FAILED tests/test_total.py - AssertionError", None)
+ assert (g.whole.error_outputs, g.whole.repeated_fail_sigs) == (2, 1)
+ s = guard.SpiralState()
+ s.update("Read", {"file_path": "x.py"}, "Error: File does not exist.", failed=True)
+ assert s.error_outputs == 1
+
+
def test_the_judge_is_told_how_the_last_verification_went_not_that_tests_are_red():
g = guard.TurnGuard(turn_key="t")
vendored = "turns=3\nrepo_context: ... = 1.2x that typical length. Tests are still NOT green. A"
@@ -472,7 +535,7 @@ def test_the_judge_is_told_how_the_last_verification_went_not_that_tests_are_red
class _BackgroundJudge:
- """`te_live.judge.AsyncJudge`'s interface, with the verdict handed in by the test."""
+ """`plugin.judge.AsyncJudge`'s interface, with the verdict handed in by the test."""
def __init__(self):
self.started, self.verdict = [], None
@@ -562,41 +625,56 @@ def test_copilot_logs_read_through_the_existing_trace_seam(tmp_path):
traj = trace.load_trajectory(p)
assert [t[0] for t in traj] == ["bash", "view"] and traj[0][1]["command"] == "pytest -q"
assert trace.tool_usage(p) == {"bash": 1, "view": 1}
- (turn,) = transcripts.copilot_turns(p)
+ (turn,) = trace.copilot_turns(p)
assert turn[0][0] == "bash" and turn[0][3] == 1 and turn[1][3] is None
- assert transcripts.copilot_session_meta(p)["cwd"] == "/w/repo"
+ assert trace.copilot_session_meta(p)["cwd"] == "/w/repo"
+
+
+def test_a_copilot_call_into_the_session_directory_is_the_plain_form(tmp_path):
+ """Seen live: Copilot's models type `cd <repo> && ` before every command, so the repeated
+ `cd /w/repo && python -m unittest` and a one-off bare form were two forms, and the bare one
+ won as the form that leaves the shell where it is."""
+ from tokeneconomizer.microskills.observe import PYTHON_GIT, observe_task
+ p = copilot_events(str(tmp_path / "s" / "events.jsonl"), [
+ ("bash", {"command": "cd /w/repo && pytest -q"},
+ "bash: pytest: command not found\n<shellId: 0 completed with exit code 127>", False),
+ ("bash", {"command": "cd /w/repo && python -m unittest -q"},
+ "Ran 4 tests in 0.001s\nOK\n<shellId: 0 completed with exit code 0>", True)])
+ assert trace.call_cwds(p) == ["/w/repo", "/w/repo"]
+ assert [o.form for o in observe_task(p, PYTHON_GIT)["obs"] if o.intent == "run_tests"] == [
+ "pytest", "python -m unittest"]
def test_copilot_usage_is_converted_from_its_grand_input_total(tmp_path):
p = copilot_events(str(tmp_path / "s" / "events.jsonl"), [])
- u = transcripts.copilot_session_usage(p)
+ u = trace.copilot_session_usage(p)
# inputTokens counts cache reads and writes (verified against a scripted endpoint)
assert u["input_tokens"] == 4000 - 2400 - 100
assert u["cache_read_input_tokens"] == 2400 and u["cache_creation_input_tokens"] == 100
assert u["output_tokens"] == 80 and u["requests"] == 4 and u["model"] == "gpt-5.4"
assert u["tool_definitions_tokens"] == 13149
- killed = transcripts.copilot_session_usage(
+ killed = trace.copilot_session_usage(
copilot_events(str(tmp_path / "k" / "events.jsonl"), [], shutdown=False))
assert killed["input_tokens"] is None and killed["model"] == "gpt-5.4"
def test_copilot_tools_are_grouped_by_mcp_server(tmp_path):
servers = {"github-mcp-server", "github", "acme-db"}
- assert transcripts.mcp_server_of("github-mcp-server-list_issues", servers) == \
+ assert trace.mcp_server_of("github-mcp-server-list_issues", servers) == \
"github-mcp-server" # the longest prefix wins
- assert transcripts.mcp_server_of("acme-db-query", servers) == "acme-db"
- assert transcripts.mcp_server_of("bash", servers) is None
+ assert trace.mcp_server_of("acme-db-query", servers) == "acme-db"
+ assert trace.mcp_server_of("bash", servers) is None
home = tmp_path / "cp"
home.mkdir()
(home / "mcp-config.json").write_text(json.dumps({"mcpServers": {"acme-db": {}}}))
- assert transcripts.copilot_mcp_servers({"COPILOT_HOME": str(home)}) == {
+ assert trace.copilot_mcp_servers({"COPILOT_HOME": str(home)}) == {
"github-mcp-server", "acme-db"}
def test_a_copilot_side_call_is_a_bare_completion_priced_from_its_own_log(tmp_path,
monkeypatch):
import subprocess
- from te_live import sidecall
+ from tokeneconomizer.plugin import sidecall
monkeypatch.setenv("COPILOT_HOME", str(tmp_path / "cp"))
copilot_events(str(tmp_path / "cp" / "session-state" / "side1" / "events.jsonl"), [])
seen = {}
@@ -617,11 +695,108 @@ def test_a_copilot_side_call_is_a_bare_completion_priced_from_its_own_log(tmp_pa
assert seen["env"]["TE_SIDECALL"] == "1" # its own hooks must not recurse
cfg = live_config.LiveConfig(paid=True)
assert sidecall.runner_for("copilot", cfg).__code__.co_names.count("copilot_call") == 1
+ assert sidecall.runner_for("claude", cfg).__code__.co_names.count("claude_call") == 1
+ assert sidecall.runner_for("pi", cfg).__code__.co_names.count("pi_call") == 1
+
+
+def test_a_side_call_with_no_reply_is_noted_and_keeps_to_a_bare_completion(tmp_path,
+ monkeypatch):
+ """Seen live: under Copilot's BYOK the provider's variables do not reach the hooks, so the
+ side call ran signed out, answered nothing, and the plugin said nothing either."""
+ import subprocess
+ from tokeneconomizer.plugin import sidecall
+ monkeypatch.setenv("TOKENECONOMIZER_HOME", str(tmp_path / "te"))
+ home = tmp_path / "cp"
+ home.mkdir()
+ (home / "mcp-config.json").write_text(json.dumps({"mcpServers": {"acme-db": {}}}))
+ monkeypatch.setenv("COPILOT_HOME", str(home))
+ seen = {}
+
+ def fake_run(cmd, **kw):
+ seen["cmd"] = cmd
+ return subprocess.CompletedProcess(cmd, 1, stdout="",
+ stderr="Error: No authentication information found.")
+
+ monkeypatch.setattr(sidecall.subprocess, "run", fake_run)
+ assert sidecall.copilot_call("propose facts") == ("", None)
+ cmd = seen["cmd"]
+ assert cmd[cmd.index("--disable-mcp-server") + 1] == "acme-db"
+ log = (tmp_path / "te" / "errors.log").read_text()
+ assert "sidecall copilot: no reply (exit 1)" in log and "No authentication" in log
+
+
+def test_claude_side_calls_stay_out_of_the_persons_history_where_the_cli_allows(monkeypatch):
+ import subprocess
+ from tokeneconomizer.plugin import sidecall
+ helps = {"new": " --no-session-persistence Disable session persistence", "old": " -p"}
+ monkeypatch.setattr(sidecall.subprocess, "run", lambda cmd, **kw: subprocess.CompletedProcess(
+ cmd, 0, stdout=helps[cmd[0]], stderr=""))
+ monkeypatch.setattr(sidecall, "_FLAGS", {})
+ assert sidecall.claude_flags("new") == ["--no-session-persistence"]
+ assert sidecall.claude_flags("old") == []
+
+
+# `pi --print --mode json` on Pi 1.2.0 through OpenRouter, trimmed: the header, the system and
+# user messages, the reply (a thinking block, then the text), and the run's end.
+PI_JSON_RUN = [
+ {"type": "session", "version": 3, "id": "01a13c79", "cwd": "/tmp/te-side-x"},
+ {"type": "message_end", "message": {"role": "system", "content": "",
+ "sections": {"preamble": "You are an expert..."}}},
+ {"type": "message_end", "message": {"role": "user", "content": [
+ {"type": "text", "text": "propose facts"}]}},
+ {"type": "message_update", "usage": {"input": 745, "output": 3}},
+ {"type": "message_end", "message": {
+ "role": "assistant", "provider": "openrouter", "model": "anthropic/claude-haiku-4.5",
+ "content": [{"type": "thinking", "thinking": "Two lines."},
+ {"type": "text", "text": "- use python -m pytest"}],
+ "usage": {"input": 745, "output": 298, "cacheRead": 0, "cacheWrite": 0,
+ "totalTokens": 1043, "cacheWrite1h": 0, "reasoning": 281,
+ "cost": {"input": 0.000745, "output": 0.00149, "total": 0.002235}},
+ "stopReason": "stop"}},
+ {"type": "agent_settled", "aborted": False},
+]
+
+
+def test_a_pi_reply_is_read_from_its_json_run():
+ text, usage = trace.pi_json_reply("\n".join(json.dumps(e) for e in PI_JSON_RUN))
+ assert text == "- use python -m pytest"
+ assert usage == {"input_tokens": 745, "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 0, "output_tokens": 298,
+ "cost_usd": 0.002235, "model": "anthropic/claude-haiku-4.5"}
+ assert trace.pi_json_reply("") == ("", None)
+
+
+def test_a_pi_side_call_is_a_bare_run_on_the_persons_own_pi(monkeypatch):
+ import subprocess
+ from tokeneconomizer.plugin import sidecall
+ calls = []
+
+ def fake_run(cmd, **kw):
+ calls.append((cmd, kw))
+ if "--no-mcp" in cmd: # Pi before 1.0 has no such flag
+ return subprocess.CompletedProcess(cmd, 1, stdout="",
+ stderr="Error: Unknown option: --no-mcp\n")
+ out = "\n".join(json.dumps(e) for e in PI_JSON_RUN)
+ return subprocess.CompletedProcess(cmd, 0, stdout=out, stderr="")
+
+ monkeypatch.setattr(sidecall.subprocess, "run", fake_run)
+ text, eff = sidecall.pi_call("propose facts")
+ assert text == "- use python -m pytest" and eff and eff > 0
+ (first, kw), (second, _) = calls
+ assert first[:4] == ["pi", "--print", "--mode", "json"] and first[-2:] == ["--", "propose facts"]
+ for flag in ("--no-session", "--no-tools", "--no-extensions", "--no-context-files"):
+ assert flag in first
+ assert "--model" not in first # the person's own default model and login
+ assert "--no-mcp" in first and "--no-mcp" not in second
+ assert kw["env"]["TE_SIDECALL"] == "1" and kw["stdin"] is subprocess.DEVNULL
+ calls.clear()
+ sidecall.pi_call("propose facts", model="openrouter/anthropic/claude-haiku-4.5")
+ assert calls[-1][0][-4:-2] == ["--model", "openrouter/anthropic/claude-haiku-4.5"]
def test_a_copilot_notice_is_a_progress_line_before_the_hook_output():
import io
- from te_live import hook
+ from tokeneconomizer.plugin import hook
out = io.StringIO()
hook.main([], io.StringIO("{}"), out, {"TE_DISABLE": "1"})
assert out.getvalue() == "{}\n"
@@ -637,7 +812,7 @@ def test_a_copilot_notice_is_a_progress_line_before_the_hook_output():
def test_copilot_side_calls_name_a_model_a_byok_provider_can_serve():
- from te_live.sidecall import copilot_model
+ from tokeneconomizer.plugin.sidecall import copilot_model
byok = {"COPILOT_PROVIDER_BASE_URL": "https://api.anthropic.com",
"COPILOT_PROVIDER_TYPE": "anthropic"}
# `auto` is the subscription's router; a BYOK provider has none, and the call answered nothing
@@ -654,7 +829,7 @@ def test_copilot_side_calls_name_a_model_a_byok_provider_can_serve():
def test_the_probe_repository_carries_its_trap(tmp_path):
import subprocess
- from te_live import probe
+ from tokeneconomizer.plugin import probe
repo, trap = probe.make_repo(str(tmp_path))
bare = subprocess.run([os.path.join(trap, "pytest"), "-q"], cwd=repo, capture_output=True,
text=True)
@@ -672,7 +847,7 @@ def test_the_probe_repository_carries_its_trap(tmp_path):
def test_the_probe_counts_pytest_attempts_not_exit_codes():
- from te_live import probe
+ from tokeneconomizer.plugin import probe
# commands two real Haiku sessions ran: the piped one exited 0 although pytest is missing
runs, tried = probe.test_commands([
'find . -name "pytest.ini" -o -name "go.mod" | head -20',
@@ -689,9 +864,8 @@ def test_a_small_envelopes_backstop_never_preempts_the_nudge():
"""Interactive repositories learn envelopes of ~4-10 calls, so the hard backstop
(1.8-2.5x the envelope) lies inside the stuck rule's own floor: before this fix, the first
stuck call tripped the backstop and the turn was stopped without ever being redirected."""
- from te_live import guard
- from tokeneconomizer.vendor import spiral
- thr = spiral.scaled_thresholds("aggressive")
+ from tokeneconomizer import loopguard as guard
+ thr = guard.scaled_thresholds("aggressive")
fail = ("FAIL: test_floats (tests.test_calc.TestAdd)\nTraceback (most recent call last):\n"
"AssertionError: 0.30000000000000004 != 0.3\n\nFAILED (failures=1)\n")
g = guard.TurnGuard(turn_key="t")
@@ -710,3 +884,24 @@ def test_a_small_envelopes_backstop_never_preempts_the_nudge():
else:
break
assert fired == [(14, "nudge"), (28, "abort")]
+
+
[email protected]("cmd", ["python tests/runtests.py model_inheritance -v 2",
+ "./runtests.py basic", ".venv/bin/pytest -q tests/test_a.py",
+ "cd web && ./node_modules/.bin/jest src", "/usr/bin/python3 -m pytest",
+ "/w/venv/bin/pytest -q", "~/.local/bin/pytest -q",
+ "python3 /w/repo/tests/runtests.py basic"])
+def test_a_runner_named_by_path_counts_as_a_verification(cmd):
+ """A failing run after the last edit means the turn did not end green, whatever path the
+ runner was called by -- otherwise long failing turns feed the envelope and the guard
+ stops seeing them as long."""
+ g = guard.TurnGuard(turn_key="t")
+ g.fold("Edit", {"file_path": "/r/a.py", "old_string": "x", "new_string": "y"}, "ok")
+ g.fold("Bash", {"command": cmd}, "FAILED (failures=1)", 1)
+ assert g.verifications == 1 and not g.resolved_proxy()
+
+
[email protected]("cmd", ["cat /w/pytest.ini", "cat pytest.ini", "ls /w/tests",
+ "vim tests/runtests.py.bak"])
+def test_a_file_named_like_a_runner_is_not_a_verification(cmd):
+ assert not guard.VERIFY_RE.search(cmd)
diff --git a/tests/test_live_hooks.py b/tests/test_live_hooks.py
index 7f6badb..ff41b0b 100644
--- a/tests/test_live_hooks.py
+++ b/tests/test_live_hooks.py
@@ -9,16 +9,17 @@ here can break the agent's session.
Folds run inline (`TE_FOLD_SYNC=1`); in the plugin they are detached processes.
"""
+import glob
import io
import json
import os
import pytest
-from te_live import hook, untool
-from te_live.controller import LiveController
-from te_live.paths import repo_identity, repo_state_dir
-from te_live.store import Store
+from tokeneconomizer.plugin import denylist, hook, toolcheck
+from tokeneconomizer.plugin.controller import LiveController
+from tokeneconomizer.plugin.paths import repo_identity, repo_state_dir
+from tokeneconomizer.plugin.store import Store
@pytest.fixture
@@ -94,6 +95,34 @@ def run_session(env, repo, sid, transcript, host=None, source="startup"):
# ---- injection ---------------------------------------------------------------------------
+def prevented_session(path, repo, i):
+ """The agent was told: it runs the working form at once and never meets the trap."""
+ return write_session(path, [(f"fix bug {i}", [
+ ("Edit", {"file_path": f"{repo}/pkg/mod{i}.py", "old_string": "a", "new_string": "b"},
+ "ok", False),
+ ("Bash", {"command": "python -m pytest -q tests/test_a.py"}, "1 passed in 0.1s", False),
+ ])])
+
+
+def test_an_injected_fact_that_prevents_its_failure_stays_injected(env, repo, tmp_path):
+ """The session-start hook injects; a fold in another process learns afterwards. Without
+ telling the fold which facts the session was given, a fact that prevented its failure
+ counted as not having fired, and decayed out of the block -- seen live on Codex, where
+ three injected sessions left a fact at 5/8 and later under its gate."""
+ for i in range(5):
+ run_session(env, repo, f"s{i}", trap_session(str(tmp_path / f"s{i}.jsonl"), repo, i))
+ starts = [run_session(env, repo, f"p{i}", prevented_session(str(tmp_path / f"p{i}.jsonl"),
+ repo, i + 5))
+ for i in range(8)]
+ claim = "`pytest …` fails here with command not found; `python -m pytest …` works."
+ assert all(claim in s["hookSpecificOutput"]["additionalContext"] for s in starts)
+ (path,) = glob.glob(store_for(env, repo).path("mechanisms", "envfacts_state", "*.json"))
+ life = json.load(open(path))["facts"]["form_repair:run_tests:pytest"]["life"]
+ assert life["fire_num"] == life["fire_den"] # every session it was given counted
+ assert store_for(env, repo).read("sessions/p7.json")["injected_ids"] == [
+ "form_repair:run_tests:pytest"]
+
+
def test_a_learned_fact_reaches_the_next_session_and_is_announced_once(env, repo, tmp_path):
starts = [run_session(env, repo, f"s{i}", trap_session(str(tmp_path / f"s{i}.jsonl"), repo, i))
for i in range(6)]
@@ -190,7 +219,7 @@ def test_a_headless_guard_stops_the_turn_on_claude_but_not_on_codex(env, repo):
def _fake_judges(monkeypatch, seen):
- from tokeneconomizer.vendor import reflect
+ from tokeneconomizer.loopguard import judge as reflect
def judge(digest, runner, model="agent"):
seen.append(digest)
@@ -205,7 +234,7 @@ def _fake_judges(monkeypatch, seen):
def test_the_paid_judge_answers_from_a_job_and_its_spend_is_charged_as_it_happens(
env, repo, monkeypatch):
"""The job runs inline here (TE_JUDGE_SYNC=1); in the plugin it is a detached process."""
- from te_live import accounting
+ from tokeneconomizer.plugin import accounting
seen = []
_fake_judges(monkeypatch, seen)
paid = dict(env, TE_PAID="1", TE_JUDGE_SYNC="1")
@@ -229,7 +258,7 @@ def test_the_paid_judge_answers_from_a_job_and_its_spend_is_charged_as_it_happen
def test_a_hook_only_starts_the_paid_judge_and_never_waits_for_it(env, repo, monkeypatch):
- from te_live import judge as live_judge
+ from tokeneconomizer.plugin import judge as live_judge
seen, spawned = [], []
_fake_judges(monkeypatch, seen)
monkeypatch.setattr(live_judge, "spawn_job", lambda ctx, sid, job: spawned.append(job))
@@ -277,12 +306,12 @@ def test_unused_tools_are_proposed_but_nothing_changes_until_applied(env, repo,
prop = st.read("untool.json")["proposal"]
# protected tools (incl. a person's AskUserQuestion, and the web) are never proposed
assert sorted(prop) == ["CronCreate", "ShareOnboardingGuide", "Workflow"]
- assert not os.path.exists(untool.settings_path(repo)) # proposing writes nothing
+ assert not os.path.exists(denylist.settings_path(repo)) # proposing writes nothing
t = str(tmp_path / "next.jsonl")
open(t, "w").close()
notice = call(env, {"hook_event_name": "SessionStart", "session_id": "n", "source": "startup",
"transcript_path": t, "cwd": repo})["systemMessage"]
- assert "3 tool(s) went unused" in notice and "/tokeneconomizer:untool" in notice
+ assert "3 tool(s) went unused" in notice and "/tokeneconomizer:toolprune" in notice
def test_the_web_is_never_proposed_and_an_old_deny_rule_for_it_is_given_back(
@@ -290,29 +319,29 @@ def test_the_web_is_never_proposed_and_an_old_deny_rule_for_it_is_given_back(
_catalog(env, ["Bash", "Read", "CronCreate", "WebFetch", "WebSearch"])
st = store_for(env, repo)
# A deny list accepted under an earlier version, which still proposed the web.
- untool.apply(repo, ["CronCreate", "WebFetch", "WebSearch"], st)
+ denylist.apply(repo, ["CronCreate", "WebFetch", "WebSearch"], st)
for i in range(20): # far past the old 3x evidence bar
t = write_session(str(tmp_path / f"w{i}.jsonl"), [("look", [
("Bash", {"command": "ls"}, "a.py", False)])])
run_session(env, repo, f"w{i}", t)
- assert untool.applied(st) == ["CronCreate"]
- deny = json.load(open(untool.settings_path(repo)))["permissions"]["deny"]
+ assert denylist.applied(st) == ["CronCreate"]
+ deny = json.load(open(denylist.settings_path(repo)))["permissions"]["deny"]
assert deny == ["CronCreate"]
assert not {"WebFetch", "WebSearch"} & set(st.read("untool.json")["proposal"])
def test_apply_and_restore_touch_only_the_plugins_own_rules(repo, tmp_path):
st = Store(str(tmp_path / "st"))
- path = untool.settings_path(repo)
+ path = denylist.settings_path(repo)
os.makedirs(os.path.dirname(path))
json.dump({"permissions": {"deny": ["Bash(rm -rf:*)"], "allow": ["Read"]}, "model": "opus"},
open(path, "w"))
- assert untool.apply(repo, ["Workflow", "CronCreate"], st) == ["Workflow", "CronCreate"]
+ assert denylist.apply(repo, ["Workflow", "CronCreate"], st) == ["Workflow", "CronCreate"]
data = json.load(open(path))
assert data["permissions"]["deny"] == ["Bash(rm -rf:*)", "Workflow", "CronCreate"]
assert data["model"] == "opus" and data["permissions"]["allow"] == ["Read"]
- assert untool.restore(repo, st, ["CronCreate"]) == ["CronCreate"]
- assert untool.restore(repo, st) == ["Workflow"]
+ assert denylist.restore(repo, st, ["CronCreate"]) == ["CronCreate"]
+ assert denylist.restore(repo, st) == ["Workflow"]
assert json.load(open(path))["permissions"]["deny"] == ["Bash(rm -rf:*)"]
# the user wrote that file, so it was not added to the local git excludes
exclude = os.path.join(repo, ".git", "info", "exclude")
@@ -321,10 +350,10 @@ def test_apply_and_restore_touch_only_the_plugins_own_rules(repo, tmp_path):
def test_a_settings_file_the_plugin_creates_is_kept_out_of_git(repo, tmp_path):
st = Store(str(tmp_path / "st"))
- untool.apply(repo, ["Workflow"], st)
+ denylist.apply(repo, ["Workflow"], st)
assert "/.claude/settings.local.json" in open(
os.path.join(repo, ".git", "info", "exclude")).read().split()
- untool.apply(repo, ["CronCreate"], st) # idempotent exclude entry
+ denylist.apply(repo, ["CronCreate"], st) # idempotent exclude entry
assert open(os.path.join(repo, ".git", "info", "exclude")).read().count(
"/.claude/settings.local.json") == 1
@@ -349,8 +378,8 @@ def test_a_fold_that_cannot_take_the_lock_skips_and_the_session_is_still_folded_
"""The double fold seen live: a paid fold holds the lock through its side call, a second
fold of the same session gave up waiting after 10 s and folded it again, unlocked."""
import fcntl
- from te_live import fold, hosts
- from te_live.context import LiveContext
+ from tokeneconomizer.plugin import fold, hosts
+ from tokeneconomizer.plugin.context import LiveContext
t = trap_session(str(tmp_path / "s.jsonl"), repo, 0)
base = {"session_id": "s", "transcript_path": t, "cwd": repo}
call(env, dict(base, hook_event_name="SessionStart", source="startup"))
@@ -451,7 +480,7 @@ def test_pi_learns_from_its_own_session_files_and_injects_at_the_next_start(env,
assert all(s == {} for s in starts[:4])
ctx = starts[4]["hookSpecificOutput"]["additionalContext"]
assert "`python -m pytest …` works." in ctx
- assert "/te facts" in starts[4]["systemMessage"] # Pi's own command name
+ assert "/te microskills" in starts[4]["systemMessage"] # Pi's own command name
rec = store_for(env, repo, "pi").read_lines("ledger.jsonl")[0]
assert rec["requests"] == 3 and rec["priced_by"] == "model"
@@ -517,7 +546,7 @@ def test_copilot_learns_from_its_own_logs_and_injects_at_top_level(env, repo, tm
# Copilot never shows systemMessage; its TUI shows a progress line printed first
assert "systemMessage" not in starts[4]
(notice,) = starts[4]["progress"]
- assert "learned fact" in notice and "/tokeneconomizer:facts" in notice
+ assert "learned fact" in notice and "/tokeneconomizer:microskills" in notice
st = store_for(env, repo, "copilot")
rec = st.read_lines("ledger.jsonl")[0]
assert rec["host"] == "copilot" and rec["requests"] == 4 and rec["priced_by"] == "model"
@@ -553,9 +582,9 @@ def test_copilot_proposes_only_whole_unused_mcp_servers(env, repo, tmp_path, mon
assert unt["proposal"] == ["github-mcp-server"]
assert unt["servers"]["github-mcp-server"] == {"tools": 3, "used": False,
"unused_sessions": 5}
- assert not os.path.exists(untool.settings_path(repo, "copilot"))
+ assert not os.path.exists(denylist.settings_path(repo, "copilot"))
(notice,) = copilot_session(env, repo, tmp_path, "n", [], monkeypatch)["progress"]
- assert "1 MCP server(s) went unused" in notice and "/tokeneconomizer:untool" in notice
+ assert "1 MCP server(s) went unused" in notice and "/tokeneconomizer:toolprune" in notice
def test_a_server_whose_tool_was_used_once_is_never_proposed(env, repo, tmp_path, monkeypatch):
@@ -571,17 +600,17 @@ def test_a_server_whose_tool_was_used_once_is_never_proposed(env, repo, tmp_path
def test_copilot_apply_and_restore_touch_only_the_plugins_own_servers(repo, tmp_path):
st = Store(str(tmp_path / "st"))
- path = untool.settings_path(repo, "copilot")
+ path = denylist.settings_path(repo, "copilot")
assert path.endswith(os.path.join(".github", "copilot", "settings.local.json"))
os.makedirs(os.path.dirname(path))
json.dump({"disabledMcpServers": ["mine"], "model": "gpt-5.4"}, open(path, "w"))
- assert untool.apply(repo, ["github-mcp-server"], st, host="copilot") == ["github-mcp-server"]
+ assert denylist.apply(repo, ["github-mcp-server"], st, host="copilot") == ["github-mcp-server"]
assert json.load(open(path)) == {"disabledMcpServers": ["mine", "github-mcp-server"],
"model": "gpt-5.4"}
- assert untool.restore(repo, st, host="copilot") == ["github-mcp-server"]
+ assert denylist.restore(repo, st, host="copilot") == ["github-mcp-server"]
assert json.load(open(path)) == {"disabledMcpServers": ["mine"], "model": "gpt-5.4"}
os.remove(path)
- untool.apply(repo, ["github-mcp-server"], st, host="copilot") # created: kept out of git
+ denylist.apply(repo, ["github-mcp-server"], st, host="copilot") # created: kept out of git
assert "/.github/copilot/settings.local.json" in open(
os.path.join(repo, ".git", "info", "exclude")).read().split()
@@ -619,7 +648,7 @@ def test_codex_proposes_capabilities_it_never_saw_used(env, repo, tmp_path):
assert unt["capabilities"]["image_media"]["used"] is True
assert unt["capabilities"]["goals"] == {"loaded_sessions": 5, "unused_sessions": 5,
"used": False}
- assert not os.path.exists(untool.settings_path(repo, "codex")) # nothing written yet
+ assert not os.path.exists(denylist.settings_path(repo, "codex")) # nothing written yet
def test_codex_needs_the_full_evidence_before_proposing(env, repo, tmp_path):
@@ -636,7 +665,7 @@ def codex_accepts(monkeypatch):
"""Codex's own check of the edited config (`codex features list`), as a stub: the tests
must not depend on a local Codex install or its user config."""
verdicts = []
- monkeypatch.setattr(untool, "codex_config_error", lambda root, **kw: (
+ monkeypatch.setattr(denylist, "codex_config_error", lambda root, **kw: (
verdicts.pop(0) if verdicts else None))
return verdicts
@@ -644,12 +673,12 @@ def codex_accepts(monkeypatch):
def test_codex_apply_writes_marked_lines_and_restore_leaves_the_users_config(repo, tmp_path,
codex_accepts):
st = Store(str(tmp_path / "st"))
- path = untool.settings_path(repo, "codex")
+ path = denylist.settings_path(repo, "codex")
os.makedirs(os.path.dirname(path))
user = ('model_reasoning_effort = "high"\n\n[features]\nhooks = true\n\n'
'[[skills.config]]\npath = "/x/SKILL.md"\nenabled = false\n')
open(path, "w").write(user)
- assert untool.apply(repo, ["collaboration", "goals", "image_media"], st, host="codex") == [
+ assert denylist.apply(repo, ["collaboration", "goals", "image_media"], st, host="codex") == [
"collaboration", "goals", "image_media"]
text = open(path).read()
lines = text.splitlines()
@@ -662,25 +691,25 @@ def test_codex_apply_writes_marked_lines_and_restore_leaves_the_users_config(rep
assert "view_image = false # tokeneconomizer:image_media" in feats
assert lines[-2:] == ["[agents] # tokeneconomizer:collaboration",
"enabled = false # tokeneconomizer:collaboration"]
- assert untool.restore(repo, st, ["goals"], host="codex") == ["goals"]
+ assert denylist.restore(repo, st, ["goals"], host="codex") == ["goals"]
assert "goals = false" not in open(path).read()
- assert untool.restore(repo, st, host="codex") == ["collaboration", "image_media"]
+ assert denylist.restore(repo, st, host="codex") == ["collaboration", "image_media"]
assert open(path).read() == user.rstrip("\n") + "\n"
def test_a_config_codex_rejects_is_put_back(repo, tmp_path, codex_accepts):
st = Store(str(tmp_path / "st"))
- path = untool.settings_path(repo, "codex")
+ path = denylist.settings_path(repo, "codex")
os.makedirs(os.path.dirname(path))
open(path, "w").write('model = "gpt-5.6-sol"\n')
codex_accepts.append("Error loading config.toml: duplicate key")
with pytest.raises(RuntimeError, match="put back"):
- untool.apply(repo, ["goals"], st, host="codex")
- assert open(path).read() == 'model = "gpt-5.6-sol"\n' and untool.applied(st) == []
+ denylist.apply(repo, ["goals"], st, host="codex")
+ assert open(path).read() == 'model = "gpt-5.6-sol"\n' and denylist.applied(st) == []
os.remove(path)
codex_accepts.append("bad")
with pytest.raises(RuntimeError):
- untool.apply(repo, ["goals"], st, host="codex")
+ denylist.apply(repo, ["goals"], st, host="codex")
assert not os.path.exists(path) # a file it created is removed again
@@ -694,26 +723,26 @@ def test_a_committed_codex_config_is_never_edited(tmp_path, codex_accepts):
subprocess.run(git + ["-C", str(r), "add", ".codex/config.toml"], check=True)
subprocess.run(git + ["-C", str(r), "commit", "-qm", "team config"], check=True)
with pytest.raises(RuntimeError, match="committed"):
- untool.apply(str(r), ["goals"], Store(str(tmp_path / "st")), host="codex")
+ denylist.apply(str(r), ["goals"], Store(str(tmp_path / "st")), host="codex")
assert (r / ".codex" / "config.toml").read_text() == 'model = "gpt-5.6-sol"\n'
def test_codex_never_overrides_a_key_the_user_set(tmp_path):
- text, did = untool._toml_insert('[features]\ngoals = true\n', "features", "goals", "false",
+ text, did = denylist._toml_insert('[features]\ngoals = true\n', "features", "goals", "false",
"# t")
assert not did and text == '[features]\ngoals = true\n'
- text, did = untool._toml_insert('features.goals = true\n', "features", "goals", "false", "# t")
+ text, did = denylist._toml_insert('features.goals = true\n', "features", "goals", "false", "# t")
assert not did
# dotted top-level keys and no [features] table: stay dotted, never add a clashing table
- text, did = untool._toml_insert('features.hooks = true\n', "features", "view_image", "false",
+ text, did = denylist._toml_insert('features.hooks = true\n', "features", "view_image", "false",
"# t")
assert did and "[features]" not in text and "features.view_image = false # t" in text
# an inline table cannot be extended, and a [features] table beside it would be invalid
- text, did = untool._toml_insert('features = { hooks = true }\n', "features", "goals",
+ text, did = denylist._toml_insert('features = { hooks = true }\n', "features", "goals",
"false", "# t")
assert not did and text == 'features = { hooks = true }\n'
# a header the plugin added, under which the user has since put a key, is kept
- kept = untool._toml_remove('[agents] # t\nenabled = false # t\nmax_threads = 4\n', ["# t"])
+ kept = denylist._toml_remove('[agents] # t\nenabled = false # t\nmax_threads = 4\n', ["# t"])
assert kept == "[agents] # t\nmax_threads = 4\n"
@@ -721,23 +750,91 @@ def test_codex_trust_is_read_from_the_users_config(tmp_path, repo):
home = tmp_path / "codex-home"
home.mkdir()
env = {"CODEX_HOME": str(home)}
- assert untool.codex_project_trusted(repo, env) is None
+ assert denylist.codex_project_trusted(repo, env) is None
(home / "config.toml").write_text(f'[projects."{repo}"]\ntrust_level = "trusted"\n')
- assert untool.codex_project_trusted(repo, env) is True
+ assert denylist.codex_project_trusted(repo, env) is True
(home / "config.toml").write_text(f'[projects."{repo}/sub"]\ntrust_level = "trusted"\n'
f'[projects."{repo}"]\ntrust_level = "untrusted"\n')
- assert untool.codex_project_trusted(repo, env) is False
+ assert denylist.codex_project_trusted(repo, env) is False
def test_copilot_trust_is_read_from_its_config(tmp_path, repo):
home = tmp_path / "copilot-home"
home.mkdir()
env = {"COPILOT_HOME": str(home)}
- assert untool.copilot_folder_trusted(repo, env) is None
+ assert denylist.copilot_folder_trusted(repo, env) is None
# Copilot's config.json opens with `//` comment lines; trust covers subfolders
(home / "config.json").write_text(
"// User settings belong in settings.json.\n// This file is managed automatically.\n"
+ json.dumps({"trustedFolders": [os.path.dirname(repo)]}))
- assert untool.copilot_folder_trusted(repo, env) is True
+ assert denylist.copilot_folder_trusted(repo, env) is True
(home / "config.json").write_text(json.dumps({"trustedFolders": [repo + "-other"]}))
- assert untool.copilot_folder_trusted(repo, env) is False
+ assert denylist.copilot_folder_trusted(repo, env) is False
+
+
+# ---- a failed call reaches the guard on Claude Code -------------------------------------------
+# Claude Code 2.1.299 reports a failed call -- a non-zero exit, a refused command -- only as
+# PostToolUseFailure, with an `error` string and no `tool_response` (payload as captured). Before
+# the plugin's Claude hook file registered that event, the guard never saw a failing call: live
+# sessions counted 39 of 47 calls, and a failing test run after the last edit could not make a
+# turn end red.
+CLAUDE_FAILURE = {"hook_event_name": "PostToolUseFailure", "tool_name": "Bash",
+ "tool_input": {"command": "ls /nonexistent_dir_xyz"},
+ "tool_use_id": "toolu_01", "is_interrupt": False, "duration_ms": 25,
+ "error": "Exit code 2\nls: cannot access '/nonexistent_dir_xyz': No such file "
+ "or directory"}
+
+
+def test_claude_code_failure_payloads_parse_with_their_exit_code():
+ from tokeneconomizer.plugin.hosts import HOSTS
+ name, args, text, code = HOSTS["claude"]().tool_call(CLAUDE_FAILURE)
+ assert (name, args["command"], code) == ("Bash", "ls /nonexistent_dir_xyz", 2)
+ assert "cannot access" in text
+ _, _, _, code = HOSTS["claude"]().tool_call(dict(CLAUDE_FAILURE, tool_name="Read",
+ error="File does not exist."))
+ assert code is None
+
+
+def test_the_claude_hook_file_registers_failed_calls():
+ hooks = json.load(open(os.path.join(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__))), "plugin", "hooks", "hooks.json")))["hooks"]
+ assert hooks["PostToolUseFailure"] == hooks["PostToolUse"]
+
+
+def _claude_turn(env, repo, sid, key, calls):
+ """A Claude Code prompt-turn as it is delivered: a failed call arrives as PostToolUseFailure."""
+ base = {"session_id": sid, "transcript_path": "", "cwd": repo, "prompt_id": key}
+ call(env, dict(base, hook_event_name="UserPromptSubmit", prompt="go"))
+ outs = []
+ for name, args, result, failed in calls:
+ ev = (dict(base, hook_event_name="PostToolUseFailure", tool_name=name, tool_input=args,
+ error=result) if failed else
+ dict(base, hook_event_name="PostToolUse", tool_name=name, tool_input=args,
+ tool_response=result))
+ outs.append(call(env, ev))
+ call(env, dict(base, hook_event_name="Stop", stop_hook_active=False))
+ return outs
+
+
+def test_failed_calls_count_and_a_failing_check_after_the_last_edit_ends_the_turn_red(env, repo):
+ edit = ("Edit", {"file_path": "/r/pkg/a.py", "old_string": "x", "new_string": "y"}, "ok", False)
+ run = ("Bash", {"command": "python tests/runtests.py app"},
+ "Exit code 1\nFAILED (failures=1)", True)
+ _claude_turn(env, repo, "s", "p0", [edit, run, ("Read", {"file_path": "/r/b.py"},
+ "File does not exist.", True)])
+ (turn,) = [e for e in store_for(env, repo).read_lines("events.jsonl") if e["kind"] == "turn"]
+ assert turn["tool_calls"] == 3
+ assert turn["resolved_proxy"] is False
+
+
+def test_a_loop_the_agent_reports_only_as_failures_is_nudged(env, repo):
+ for k in range(5):
+ _turn(env, repo, "s", f"g{k}", GREEN)
+ calls = []
+ for k in range(40):
+ calls.append(("Edit", {"file_path": "/r/pkg/a.py", "old_string": "x", "new_string": "y"},
+ "ok", False) if k % 2 == 0 else
+ ("Bash", {"command": "pytest -q"}, "Exit code 1\nFAILED tests/test_a.py::"
+ "test_x - AssertionError: assert 1 == 2", True))
+ outs = _claude_turn(env, repo, "s", "stuck", calls)
+ assert any("hookSpecificOutput" in o for o in outs)
diff --git a/tests/test_live_repomap.py b/tests/test_live_repomap.py
new file mode 100644
index 0000000..62282d9
--- /dev/null
+++ b/tests/test_live_repomap.py
@@ -0,0 +1,130 @@
+"""The opt-in repository map: generated by whatever Python has aider, cached per commit outside
+the repository, and put in context once per session -- ranked toward the first prompt where the
+agent's prompt hook can carry context, at session start where it cannot."""
+import os
+import stat
+import subprocess
+import sys
+
+import pytest
+
+from tokeneconomizer.plugin import repomap
+from tokeneconomizer.plugin.config import LiveConfig
+from tests.test_live_hooks import call, env, repo # noqa: F401
+
+FAKE = """#!/bin/sh
+# A stand-in for a Python with aider: the import probe succeeds, and the generator prints a
+# map that names the identifiers it was ranked toward.
+if [ "$1" = "-c" ]; then exit {probe}; fi
+if [ -n "$4" ] && [ "{slow}" = "1" ]; then sleep 3; fi
+echo "pkg/core.py:"
+echo "| def run(): ranked toward [$4]"
+"""
+
+
+def _fake(tmp_path, probe=0, slow=0):
+ p = tmp_path / f"fakepy-{probe}-{slow}"
+ p.write_text(FAKE.format(probe=probe, slow=slow))
+ p.chmod(p.stat().st_mode | stat.S_IEXEC)
+ return str(p)
+
+
+def _env(env, tmp_path, mode="on", **kw):
+ e = dict(env, TE_REPOMAP=mode, TE_REPOMAP_PYTHON=_fake(tmp_path, **kw))
+ return e
+
+
+def _session(e, repo, sid, prompts, host=None):
+ base = {"session_id": sid, "transcript_path": "", "cwd": repo, "prompt_id": "p"}
+ start = call(e, dict(base, hook_event_name="SessionStart", source="startup"), host)
+ outs = [call(e, dict(base, hook_event_name="UserPromptSubmit", prompt=p,
+ prompt_id=f"p{i}"), host) for i, p in enumerate(prompts)]
+ return start, outs
+
+
+def _ctx_text(out):
+ return (out.get("hookSpecificOutput") or {}).get("additionalContext") or out.get(
+ "additionalContext") or ""
+
+
+def test_repomap_takes_on_off_and_start():
+ cfg = LiveConfig()
+ assert cfg.repomap == "off"
+ assert cfg.set("repomap", "on") and cfg.repomap == "on"
+ assert cfg.set("repomap", "start") and cfg.repomap == "start"
+ assert cfg.set("repomap", "false") and cfg.repomap == "off"
+ assert not cfg.set("repomap", "sometimes")
+
+
+def test_the_first_prompt_gets_a_map_ranked_toward_what_it_names(env, repo, tmp_path):
+ e = _env(env, tmp_path)
+ start, outs = _session(e, repo, "s1", ["Fix `parse_config` in ConfigLoader", "and then?"])
+ assert "Repository map" not in _ctx_text(start) # Claude Code: not at session start
+ first = _ctx_text(outs[0])
+ assert first.startswith("# Repository map") and "parse_config" in first
+ assert "ConfigLoader" in first
+ assert "added a map of acme/widget" in outs[0]["systemMessage"]
+ assert _ctx_text(outs[1]) == "" # once per session
+ _, again = _session(e, repo, "s2", ["Fix `other_thing`"])
+ assert "other_thing" in _ctx_text(again[0])
+ assert "systemMessage" not in again[0] # the notice is once per repository
+
+
+def test_a_slow_ranked_map_falls_back_to_the_cached_one(env, repo, tmp_path):
+ e = dict(_env(env, tmp_path, slow=1), TE_REPOMAP_TIMEOUT="1")
+ _, outs = _session(e, repo, "s1", ["Fix `parse_config`"])
+ text = _ctx_text(outs[0])
+ assert text.startswith("# Repository map") and "ranked toward []" in text
+
+
+def test_codex_and_start_mode_get_the_cached_map_at_session_start(env, repo, tmp_path):
+ start, outs = _session(_env(env, tmp_path), repo, "c1", ["Fix `x_y`"], host="codex")
+ assert _ctx_text(start).startswith("# Repository map")
+ assert all(_ctx_text(o) == "" for o in outs)
+ start, outs = _session(_env(env, tmp_path, mode="start"), repo, "s9", ["Fix `x_y`"])
+ assert _ctx_text(start).startswith("# Repository map") and _ctx_text(outs[0]) == ""
+
+
+def test_shadow_and_off_inject_nothing(env, repo, tmp_path):
+ _, outs = _session(dict(_env(env, tmp_path), TE_SHADOW="1"), repo, "s1", ["Fix `x_y`"])
+ assert _ctx_text(outs[0]) == ""
+ _, outs = _session(_env(env, tmp_path, mode="off"), repo, "s2", ["Fix `x_y`"])
+ assert outs[0] == {}
+
+
+def test_a_named_python_without_aider_is_reported_not_replaced(env, repo, tmp_path):
+ e = _env(env, tmp_path, probe=1)
+ start, outs = _session(e, repo, "s1", ["Fix `x_y`"])
+ assert _ctx_text(start) == "" and _ctx_text(outs[0]) == "" # nothing breaks
+ from tokeneconomizer.plugin.context import LiveContext
+ from tokeneconomizer.plugin.hosts import HOSTS
+ st = repomap.read_state(LiveContext.build(HOSTS["claude"](), repo, e))
+ assert "cannot import aider" in st["error"] and not st.get("map")
+
+
+def test_prompt_identifiers():
+ ids = repomap.prompt_idents("Fix `Model.save` so get_readonly_fields works on ModelAdmin")
+ assert {"save", "get_readonly_fields", "ModelAdmin"} <= set(ids)
+
+
[email protected](subprocess.run([sys.executable, "-c", "import aider.repomap"],
+ capture_output=True).returncode != 0,
+ reason="aider is not installed")
+def test_a_real_map_comes_from_tracked_files_and_leaves_the_repository_clean(tmp_path):
+ root = tmp_path / "proj"
+ (root / "pkg").mkdir(parents=True)
+ (root / "pkg" / "core.py").write_text("class Engine:\n def start(self):\n pass\n")
+ (root / "pkg" / "util.py").write_text("from pkg.core import Engine\n\ndef boot():\n"
+ " return Engine().start()\n")
+ (root / "static").mkdir()
+ (root / "static" / "big.min.js").write_text("function vendored(){}\n")
+ for c in (["git", "init", "-q"], ["git", "add", "-A"]):
+ subprocess.run(c, cwd=root, check=True)
+ cache = tmp_path / "tags"
+ out = subprocess.run([sys.executable, repomap.GEN, str(root), "512", "Engine", "--git",
+ "--cache", str(cache)], capture_output=True, text=True, timeout=300)
+ assert out.returncode == 0, out.stderr[-400:]
+ assert "pkg/core.py" in out.stdout and "Engine" in out.stdout
+ assert "big.min.js" not in out.stdout # vendored assets are not mapped
+ assert not any(n.startswith(".aider") for n in os.listdir(root))
+ assert cache.exists()
diff --git a/tests/test_live_safety.py b/tests/test_live_safety.py
index 770005c..e7cacd4 100644
--- a/tests/test_live_safety.py
+++ b/tests/test_live_safety.py
@@ -14,9 +14,9 @@ import sys
import pytest
-from te_live import untool
-from te_live.paths import ensure_launcher, secure_root
-from te_live.store import Store
+from tokeneconomizer.plugin import denylist, toolcheck
+from tokeneconomizer.plugin.paths import ensure_launcher, secure_root
+from tokeneconomizer.plugin.store import Store
from tests.test_live_hooks import repo # noqa: F401
PLUGIN = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "plugin")
@@ -34,7 +34,7 @@ def test_a_symlinked_settings_directory_is_refused(repo, tmp_path, host, rel):
os.symlink(outside, os.path.join(repo, rel))
item = {"claude": "Workflow", "copilot": "github-mcp-server", "codex": "goals"}[host]
with pytest.raises(RuntimeError, match="symlink"):
- untool.apply(repo, [item], Store(str(tmp_path / "st")), host=host)
+ denylist.apply(repo, [item], Store(str(tmp_path / "st")), host=host)
assert list(outside.rglob("*")) == []
@@ -45,8 +45,8 @@ def test_a_symlinked_settings_file_is_refused_and_its_target_untouched(repo, tmp
os.symlink(target, os.path.join(repo, ".claude", "settings.local.json"))
st = Store(str(tmp_path / "st"))
with pytest.raises(RuntimeError, match="symlink"):
- untool.apply(repo, ["Workflow"], st)
- assert untool.restore(repo, st, ["Workflow"]) == [] # nothing of its own to remove
+ denylist.apply(repo, ["Workflow"], st)
+ assert denylist.restore(repo, st, ["Workflow"]) == [] # nothing of its own to remove
assert target.read_text() == '{"keep": true}\n'
@@ -56,10 +56,10 @@ def test_a_settings_file_that_does_not_parse_is_refused_not_overwritten(repo, tm
broken = '{"permissions": {"allow": ["Bash(ls)"],}}\n' # a trailing comma
open(path, "w").write(broken)
with pytest.raises(RuntimeError, match="not valid JSON"):
- untool.apply(repo, ["Workflow"], Store(str(tmp_path / "st")))
+ denylist.apply(repo, ["Workflow"], Store(str(tmp_path / "st")))
assert open(path).read() == broken
open(path, "w").write("") # empty is the same as none
- assert untool.apply(repo, ["Workflow"], Store(str(tmp_path / "st2"))) == ["Workflow"]
+ assert denylist.apply(repo, ["Workflow"], Store(str(tmp_path / "st2"))) == ["Workflow"]
assert json.load(open(path)) == {"permissions": {"deny": ["Workflow"]}}
@@ -69,7 +69,7 @@ def test_a_git_file_pointing_out_of_the_repository_gets_no_exclude_line(repo, tm
elsewhere = tmp_path / "not-a-git-dir"
elsewhere.mkdir()
open(os.path.join(repo, ".git"), "w").write(f"gitdir: {elsewhere}\n")
- untool.apply(repo, ["Workflow"], Store(str(tmp_path / "st")))
+ denylist.apply(repo, ["Workflow"], Store(str(tmp_path / "st")))
assert list(elsewhere.rglob("*")) == []
@@ -77,7 +77,7 @@ def test_a_symlinked_exclude_file_is_not_written_through(repo, tmp_path):
victim = tmp_path / "victim"
victim.write_text("keep\n")
os.symlink(victim, os.path.join(repo, ".git", "info", "exclude"))
- untool.apply(repo, ["Workflow"], Store(str(tmp_path / "st")))
+ denylist.apply(repo, ["Workflow"], Store(str(tmp_path / "st")))
assert victim.read_text() == "keep\n"
diff --git a/tests/test_plugin_package.py b/tests/test_plugin_package.py
index 33b8776..4e6b10b 100644
--- a/tests/test_plugin_package.py
+++ b/tests/test_plugin_package.py
@@ -50,9 +50,9 @@ def test_manifests_agree_on_identity():
("copilot-hooks.json", "copilot")])
def test_hook_files_run_the_launcher_on_every_event(name, host):
doc = _json(PLUGIN, "hooks", name)
- # no PreToolUse: the plugin never blocks a call. Copilot reports a failed tool in an event
- # of its own, which the guard must see too.
- want = EVENTS | ({"PostToolUseFailure"} if host == "copilot" else set())
+ # no PreToolUse: the plugin never blocks a call. Claude Code and Copilot report a failed
+ # tool in an event of its own, which the guard must see too.
+ want = EVENTS | ({"PostToolUseFailure"} if host in (None, "copilot") else set())
assert set(doc["hooks"]) == want
launcher = os.path.join(PLUGIN, "scripts", "te-hook")
assert os.access(launcher, os.X_OK)
@@ -130,11 +130,13 @@ def test_the_bundle_runs_without_a_checkout(tmp_path):
subprocess.run([sys.executable, os.path.join(REPO, "scripts", "build_plugin.py"),
"--out", str(out)], check=True, capture_output=True)
bundle = out / "tokeneconomizer"
- assert (bundle / "lib" / "te_live" / "hook.py").exists()
+ assert (bundle / "lib" / "tokeneconomizer" / "plugin" / "hook.py").exists()
+ assert not (bundle / "lib" / "te_live").exists()
assert (bundle / ".github" / "plugin" / "plugin.json").exists()
assert (bundle / "hooks" / "copilot-hooks.json").exists()
assert (bundle / "lib" / "tokeneconomizer" / "__init__.py").exists()
assert not (bundle / "lib" / "te_harness").exists()
+ assert not (bundle / "lib" / "te_bench").exists()
assert not list(bundle.rglob("__pycache__"))
m = json.loads((out / ".claude-plugin" / "marketplace.json").read_text())
assert m["plugins"][0]["source"] == "./tokeneconomizer"
@@ -157,34 +159,95 @@ def test_the_bundle_runs_without_a_checkout(tmp_path):
# ---- the layering the README promises ------------------------------------------------------
-def test_import_tokeneconomizer_cannot_reach_the_live_harness():
- """`te_live` shells out to agent CLIs (opt-in side calls, the catalog probe); the core must
- not be able to, which is why it is a sibling package and not `tokeneconomizer.live`."""
- probe = ("import sys, tokeneconomizer, tokeneconomizer.arms, tokeneconomizer.mechanisms; "
- "print(any(m.split('.')[0] == 'te_live' for m in sys.modules))")
- out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, cwd=REPO)
- assert out.stdout.strip() == "False", out.stdout + out.stderr
- assert not os.path.exists(os.path.join(REPO, "tokeneconomizer", "live"))
+MECHANISMS = ("microskills", "toolprune", "loopguard", "trace")
+CORE_MODULES = ("config.py", "domain.py", "ledger.py", "pricing.py", "stage.py")
-def test_the_live_harness_is_stdlib_only_and_never_touches_the_benchmark_harness():
+def _imports(path):
+ """(module, level) of every import statement in a file."""
import ast
- live = os.path.join(REPO, "te_live")
- for name in sorted(os.listdir(live)):
- if not name.endswith(".py"):
- continue
- tree = ast.parse(open(os.path.join(live, name), encoding="utf-8").read())
- for node in ast.walk(tree):
- mods = ([a.name for a in node.names] if isinstance(node, ast.Import) else
- [node.module or ""] if isinstance(node, ast.ImportFrom) and node.level == 0
- else [])
- for mod in mods:
+ tree = ast.parse(open(path, encoding="utf-8").read())
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for a in node.names:
+ yield a.name, 0
+ elif isinstance(node, ast.ImportFrom):
+ yield node.module or "", node.level
+ if node.level and not node.module: # `from .. import plugin`
+ for a in node.names:
+ yield a.name, node.level
+
+
+def _core_files():
+ pkg = os.path.join(REPO, "tokeneconomizer")
+ for name in CORE_MODULES + ("__init__.py",):
+ yield os.path.join(pkg, name), 0
+ for sub in MECHANISMS:
+ for name in sorted(os.listdir(os.path.join(pkg, sub))):
+ if name.endswith(".py"):
+ yield os.path.join(pkg, sub, name), 1
+
+
+def test_the_mechanisms_never_import_the_plugin_runtime():
+ """The plugin runs the mechanisms; the mechanisms never know it exists. Checked on the source
+ (no import names `plugin`, absolutely or relatively) and on a live import."""
+ for path, depth in _core_files():
+ for mod, level in _imports(path):
+ if level == 0:
+ assert not mod.startswith("tokeneconomizer.plugin"), f"{path} imports {mod}"
+ else:
+ # `from ..plugin import x` inside a subpackage, `from .plugin` at the top level
+ parts = mod.split(".")
+ reaches_top = level == depth + 1
+ assert not (reaches_top and parts[0] == "plugin"), f"{path} imports .{mod}"
+ probe = ("import sys, tokeneconomizer, tokeneconomizer.domain, tokeneconomizer.stage\n"
+ + "".join(f"import tokeneconomizer.{m}\n" for m in MECHANISMS)
+ + "print(sorted(m for m in sys.modules if m.startswith('tokeneconomizer.plugin') "
+ "or m.split('.')[0] in ('te_bench', 'te_harness', 'te_live')))")
+ out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, cwd=REPO)
+ assert out.stdout.strip() == "[]", out.stdout + out.stderr
+
+
+def test_the_plugin_ships_and_loads_no_benchmark_code():
+ """The benchmark adapters, the facade, the workloads, the baselines and the benchmark-only
+ controllers live with the experiments (`experiments/te_bench/`). The plugin's library is the
+ package alone, and running every part of the plugin loads none of them."""
+ shipped = os.path.join(PLUGIN, "lib", "tokeneconomizer")
+ assert sorted(n for n in os.listdir(shipped)
+ if os.path.isdir(os.path.join(shipped, n)) and n != "__pycache__") == sorted(
+ MECHANISMS + ("plugin",))
+ for gone in ("adapters", "mechanisms", "vendor", "facade.py", "workloads.py", "runner.py",
+ "arms.py", "baselines"):
+ assert not os.path.exists(os.path.join(shipped, gone)), gone
+ for gone in ("codex_spiral.py", "spiral_stage.py", "nudge_guard.py"):
+ assert not any(gone in files for _, _, files in os.walk(shipped)), gone
+ mods = ("hook", "controller", "fold", "cli", "denylist", "toolcheck", "repomap",
+ "sidecall", "judge", "probe")
+ probe = ("import sys\n" + "".join(f"import tokeneconomizer.plugin.{m}\n" for m in mods)
+ + "print(sorted({m.split('.')[0] for m in sys.modules} "
+ "& {'te_bench', 'te_harness', 'te_live'}))")
+ out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, cwd=REPO)
+ assert out.stdout.strip() == "[]", out.stdout + out.stderr
+
+
+def test_the_package_is_stdlib_only_and_never_touches_the_benchmark_harness():
+ pkg = os.path.join(REPO, "tokeneconomizer")
+ for top, _, files in os.walk(pkg):
+ for name in sorted(files):
+ # the repository-map generator runs as a subprocess under a Python that has aider;
+ # nothing imports it
+ if not name.endswith(".py") or name == "repomap_gen.py":
+ continue
+ path = os.path.join(top, name)
+ for mod, level in _imports(path):
+ if level:
+ continue
root = mod.split(".")[0]
- assert root not in ("te_harness", "docker"), f"{name} imports {mod}"
+ assert root not in ("te_harness", "te_bench", "te_live", "docker"), \
+ f"{path} imports {mod}"
# tomllib: standard library from 3.11, imported behind an ImportError guard
assert root in sys.stdlib_module_names or root in (
- "tokeneconomizer", "te_live", "tomllib"), \
- f"{name} imports non-stdlib {mod}"
+ "tokeneconomizer", "tomllib"), f"{path} imports non-stdlib {mod}"
def test_the_plugin_directory_is_also_a_pi_package():
@@ -199,6 +262,14 @@ def test_the_plugin_directory_is_also_a_pi_package():
# call before it runs: the plugin guards nothing, on Pi as on the hook hosts.
assert set(re.findall(r'pi\.on\("(\w+)"', src)) == {
"session_start", "before_agent_start", "tool_result", "agent_end", "session_shutdown"}
+ # The repository root is the same package for `pi install git:github.com/...`, which clones
+ # the repository and reads the manifest at its root: same package, same extension file.
+ root = _json(os.path.dirname(PLUGIN), "package.json")
+ (root_ext,) = root["pi"]["extensions"]
+ assert os.path.realpath(os.path.join(os.path.dirname(PLUGIN), root_ext)) == \
+ os.path.realpath(os.path.join(PLUGIN, ext))
+ assert {k: v for k, v in root.items() if k != "pi"} == {k: v for k, v in pkg.items()
+ if k != "pi"}
# no lockfile: Claude Code installs a plugin's npm dependencies only when one exists,
# and this package has none to install (the Pi API is a peer dependency)
assert not any(os.path.exists(os.path.join(PLUGIN, f)) for f in
@@ -210,10 +281,10 @@ def test_the_plugin_carries_the_core_as_symlinks_an_install_copy_follows(tmp_pat
core must be reachable from inside plugin/. Seen live: without plugin/lib the installed copy's
hooks answered `{}` and every command crashed."""
import shutil
- for pkg in ("tokeneconomizer", "te_live"):
- link = os.path.join(PLUGIN, "lib", pkg)
- assert os.path.islink(link) and os.readlink(link) == f"../../{pkg}"
- assert os.path.isfile(os.path.join(link, "__init__.py"))
+ assert os.listdir(os.path.join(PLUGIN, "lib")) == ["tokeneconomizer"]
+ link = os.path.join(PLUGIN, "lib", "tokeneconomizer")
+ assert os.path.islink(link) and os.readlink(link) == "../../tokeneconomizer"
+ assert os.path.isfile(os.path.join(link, "plugin", "hook.py"))
# What an install does: copy the directory, following links. The copy runs on its own.
copy = str(tmp_path / "cache" / "tokeneconomizer" / "0.1.0")
shutil.copytree(PLUGIN, copy, symlinks=False,
@@ -222,3 +293,74 @@ def test_the_plugin_carries_the_core_as_symlinks_an_install_copy_follows(tmp_pat
text=True, env=dict(os.environ, TOKENECONOMIZER_HOME=str(tmp_path / "h")),
timeout=60)
assert out.returncode == 0 and "python" in out.stdout, out.stderr[-500:]
+
+
+def test_a_codex_install_copy_finds_the_core_in_the_marketplace_it_came_from(tmp_path):
+ """Codex installs a COPY of plugin/ that drops the `lib` symlink (seen live on 0.153.1), so
+ `codex plugin marketplace add <clone>` gave a plugin whose hooks answered `{}` and whose `te`
+ crashed. The copy now reads the marketplace's `source` from Codex's config.toml."""
+ import shutil
+ home = tmp_path / "codex"
+ copy = home / "plugins" / "cache" / "tokeneconomizer" / "tokeneconomizer" / "0.1.0"
+ shutil.copytree(PLUGIN, str(copy), symlinks=True,
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "lib"))
+ (copy / "lib").mkdir()
+
+ def te(source):
+ (home / "config.toml").write_text(
+ 'check_for_update_on_startup = false\n\n[marketplaces.tokeneconomizer]\n'
+ f'source_type = "local"\nsource = "{source}"\n')
+ return subprocess.run([str(copy / "scripts" / "te"), "doctor"], capture_output=True,
+ text=True, timeout=60, cwd=str(tmp_path),
+ env=dict(os.environ, TOKENECONOMIZER_HOME=str(tmp_path / "h"),
+ TE_CORE_PATH="", PYTHONPATH=""))
+ out = te(REPO)
+ assert out.returncode == 0 and "python" in out.stdout, out.stderr[-500:]
+ out = te(str(tmp_path / "nowhere"))
+ assert out.returncode == 1 and "core package was not found" in out.stderr
+ assert "was not found for the plugin at" in (tmp_path / "h" / "errors.log").read_text()
+ # A git marketplace (`codex plugin marketplace add owner/repo`): config.toml names the URL,
+ # and Codex keeps its checkout under .tmp/marketplaces (seen on 0.153.1).
+ (home / ".tmp" / "marketplaces").mkdir(parents=True)
+ os.symlink(REPO, str(home / ".tmp" / "marketplaces" / "tokeneconomizer"))
+ out = te("https://github.com/microsoft/TokenEconomizer.git")
+ assert out.returncode == 0 and "python" in out.stdout, out.stderr[-500:]
+
+
+def test_codex_gets_its_commands_as_plugin_skills_and_no_one_else_does():
+ """Codex has no plugin slash commands; its plugins carry skills. Ours live outside `skills/`,
+ which Claude Code and Copilot would load beside their slash commands."""
+ from tokeneconomizer.plugin import cli
+ manifest = _json(PLUGIN, ".codex-plugin", "plugin.json")
+ assert manifest["skills"] == "./codex-skills"
+ assert not os.path.exists(os.path.join(PLUGIN, "skills"))
+ root = os.path.join(PLUGIN, "codex-skills")
+ subcommands = set(cli.build_parser()._subparsers._group_actions[0].choices)
+ names = sorted(os.listdir(root))
+ assert names == ["tokeneconomizer-config", "tokeneconomizer-microskills",
+ "tokeneconomizer-status", "tokeneconomizer-toolprune"]
+ for name in names:
+ text = open(os.path.join(root, name, "SKILL.md"), encoding="utf-8").read()
+ assert text.startswith(f'---\nname: "{name}"\ndescription: >\n')
+ cmd = re.search(r'bin/te" --host codex --cwd "\$\(pwd\)" (\w+)', text)
+ assert cmd and cmd.group(1) in subcommands and cmd.group(1) == name.split("-", 1)[1]
+
+
+def test_the_commands_keep_their_earlier_names(tmp_path, monkeypatch, capsys):
+ """`te facts` / `te untool` and `/tokeneconomizer:facts` / `:untool` were the names before
+ the mechanisms were renamed; they run exactly what `microskills` / `toolprune` run."""
+ from tokeneconomizer.plugin import cli
+ monkeypatch.setenv("TOKENECONOMIZER_HOME", str(tmp_path / "home"))
+ work = tmp_path / "work"
+ work.mkdir()
+ for new, old in (("microskills", "facts"), ("toolprune", "untool")):
+ outs = []
+ for name in (new, old):
+ assert cli.main(["--cwd", str(work), "--host", "claude", name]) == 0
+ outs.append(capsys.readouterr().out)
+ assert outs[0] == outs[1] and outs[0]
+ body = {}
+ for name in (new, old):
+ text = open(os.path.join(PLUGIN, "commands", f"{name}.md"), encoding="utf-8").read()
+ body[name] = re.search(r'"\$te" --cwd "\$\(pwd\)" (\w+)', text).group(1)
+ assert body[new] == body[old] == new
diff --git a/tests/test_trace.py b/tests/test_trace.py
index f2539fc..a193016 100644
--- a/tests/test_trace.py
+++ b/tests/test_trace.py
@@ -15,6 +15,29 @@ def test_load_trajectory_claude(tmp_path):
assert "bash" in names and "edit" in names
+def test_a_claude_request_blob_repeating_the_conversation_adds_no_call(tmp_path):
+ """Claude Code 2.1.300 writes `api-request-blob` entries that repeat a request's messages,
+ earlier tool calls and results included. Read as calls, each one counted twice."""
+ import json
+ use = {"type": "tool_use", "id": "toolu_1", "name": "Bash", "input": {"command": "pytest -q"}}
+ res = {"type": "tool_result", "tool_use_id": "toolu_1",
+ "content": "/bin/bash: line 1: pytest: command not found", "is_error": True}
+ lines = [{"type": "assistant", "cwd": "/w/repo", "message": {"role": "assistant",
+ "content": [use]}},
+ {"type": "user", "message": {"role": "user", "content": [res]}},
+ {"type": "api-request-blob", "message": {"role": "assistant", "content": [use]}},
+ {"type": "api-request-blob", "message": {"role": "user", "content": [res]}},
+ {"type": "assistant", "message": {"role": "assistant", "content": [use]}}]
+ p = tmp_path / "s.jsonl"
+ p.write_text("\n".join(json.dumps(l) for l in lines))
+ calls = trace.load_trajectory(str(p))
+ assert [(c[0], c[1]["command"], c[3]) for c in calls] == [("Bash", "pytest -q", False)]
+ assert trace.call_cwds(str(p)) == ["/w/repo"]
+ assert trace.tool_usage(str(p)) == {"Bash": 1}
+ from tokeneconomizer.microskills import distiller
+ assert len(distiller.load_calls(str(p))) == 1
+
+
def test_tool_usage_counts(tmp_path):
p = str(tmp_path / "t.jsonl")
write_claude_transcript(p, [
@@ -45,7 +68,7 @@ def test_parse_catalog_missing_returns_empty(tmp_path):
import json as _json
from tokeneconomizer import trace as _trace
-from tokeneconomizer.vendor import reflect as _reflect
+from tokeneconomizer.trace import catalog as _catalog
_SCHEMA_LOG = (
'{"body":"{\\"tools\\":[{\\"name\\":\\"bash\\",\\"title\\":null,'
@@ -65,10 +88,10 @@ def _checkpoint_transcript(*names):
def test_flat_catalog_parses_name_fingerprint_form():
"""CLI >= 1.0.82 publishes `"tools": ["bash:66921ccc", ...]` and no schemas."""
- cat = _reflect.parse_tool_catalog_flat(_FLAT_LOG)
+ cat = _catalog.parse_tool_catalog_flat(_FLAT_LOG)
assert set(cat) == {"bash", "view", "edit"}
assert all(v == "" for v in cat.values()) # names only, no descriptions
- assert _reflect.parse_tool_catalog(_FLAT_LOG) == {} # schema reader stays schema-only
+ assert _catalog.parse_tool_catalog(_FLAT_LOG) == {} # schema reader stays schema-only
def test_schema_catalog_still_wins_and_keeps_descriptions(tmp_path):
diff --git a/tokeneconomizer/__init__.py b/tokeneconomizer/__init__.py
index 31452e9..eb858fb 100644
--- a/tokeneconomizer/__init__.py
+++ b/tokeneconomizer/__init__.py
@@ -1,28 +1,21 @@
-"""TokenEconomizer: externally-delivered, agent-agnostic middleware that aims to cut a sealed
-coding agent's amortized token cost without hurting task success.
+"""TokenEconomizer: experience-driven black-box cost control for coding agents.
-Hold the sealed agent fixed (Claude Code, Copilot CLI, Codex); make the environment learn
-a cheaper interface to itself. Three independently-switchable mechanisms read recent agent
-traces and make adaptive changes to cut effective token cost, each at a different point in
-a task's lifecycle:
+The agent stays as it is (Claude Code, Codex, Copilot CLI, Pi). Three mechanisms read its
+finished sessions and change what the next ones pay for:
- * injection -- inject a firing-gated, learned per-repo operating manual before the task.
- * tooling -- drop inapplicable tool schemas / capability packages at task construction
- (generic evidence untooling; Codex-native capability untooling).
- * spiral -- kill or nudge a stuck rollout in flight (generic guard; Codex-native
- post-green finalize).
+ * `microskills` -- micro-skill synthesis and injection: short repository facts learned from
+ recurring failures, stated at the start of the next session;
+ * `toolprune` -- tool pruning: tool definitions a repository never uses, proposed for the
+ agent's deny list;
+ * `loopguard` -- failure-loop intervention: a turn stuck repeating the same failure is
+ redirected once, then stopped or flagged.
-One normalized trace-reading seam (`trace`) and one honest cost ledger (`ledger`) are
-shared across all three. The mechanisms are harness-agnostic: task execution and the paid
-optimizer call enter through the `runner.AgentRunner` seam, and the task domain enters
-through a `DomainAdapter` (default SWE-bench). See `facade.Economizer` for the entry point.
-
-The exact task set the experiments ran -- which instances of which repos, per domain -- is
-data in `workloads`, so it is available on a bare clone with no results tree.
+They share one trace reader (`trace`), one cost ledger (`ledger`, `pricing`) and one domain
+interface (`domain.DomainAdapter`). `plugin` runs them inside real sessions through each agent's
+hooks; the mechanisms never import it. Stdlib only.
"""
-from .config import (EconomizerConfig, InjectionConfig, ToolingConfig, SpiralConfig)
-from .facade import Economizer
-from . import ledger, trace, runner, workloads
+from .config import EconomizerConfig, InjectionConfig, SpiralConfig, ToolingConfig
+from . import ledger, trace
-__all__ = ["Economizer", "EconomizerConfig", "InjectionConfig", "ToolingConfig",
- "SpiralConfig", "ledger", "trace", "runner", "workloads"]
+__all__ = ["EconomizerConfig", "InjectionConfig", "ToolingConfig", "SpiralConfig", "ledger",
+ "trace"]
diff --git a/tokeneconomizer/adapters/base.py b/tokeneconomizer/adapters/base.py
deleted file mode 100644
index 7b9ccc3..0000000
--- a/tokeneconomizer/adapters/base.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""DomainAdapter: the complete task-domain coupling surface of the economizer, named.
-
-The three mechanisms depend on their task domain ONLY through the methods below. This
-protocol is documentation-as-code: it enumerates exactly what a new domain (a different
-benchmark) must supply for the injection / tooling / spiral mechanisms to run unchanged.
-
-Where each is used:
-
- load_trajectory -> spiral state, injection distill, detect
- tool_usage -> tooling used-tool accrual
- parse_catalog -> tooling catalog snapshot (evidence untooling)
- detect -> LLM-free waste signals
- protected_tools -> untool never-drop work surface
- inapplicable_tools -> untool hardcoded drop set
- hardcoded_exclusions -> the concrete drop list given tools seen in use so far
- spiral_snapshot -> resolved-task turn snapshot for the per-stream envelope tracker
- problem_statements -> {task_id: redacted problem statement} for the per-task tool judge
- classify_domain -> (optional) a domain-specific brief for a tool classifier; None uses
- the default. Additive: not every mechanism path consults it.
- env_vocabulary -> (optional) the `envfacts.Vocabulary` naming this domain's
- interpreters, test runners, package tools, fetchers and probes, so
- the environment-fact families read a Node repository as they read a
- Python one. Absent -> the Python/git default.
-
-The task EXECUTOR + GRADER (run one instance, grade it) is deliberately NOT on this
-protocol: it lives at the orchestrator/runner layer, ABOVE the economizer (see
-`tokeneconomizer.runner.AgentRunner`), so a new benchmark's executor is swapped there.
-
-Introducing a new domain is a matter of supplying an adapter -- no mechanism edits.
-"""
-from typing import Protocol, runtime_checkable
-
-
-@runtime_checkable
-class DomainAdapter(Protocol):
- """Everything the economizer needs to know about a task domain."""
-
- name: str
-
- # ---- trajectory reading (normalized ordered call list) ----
- def load_trajectory(self, path):
- """-> [(tool_name, args_dict, result_text, success_bool)] over a saved transcript."""
- ...
-
- def tool_usage(self, path):
- """-> {tool_name: count} over a saved transcript."""
- ...
-
- def parse_catalog(self, run_dir_path, agent):
- """-> {tool_name: description} loaded by the agent for a task (or {} if unavailable)."""
- ...
-
- def parse_catalog_with_source(self, run_dir_path, agent):
- """-> ({tool: desc}, source_name) -- OPTIONAL. source_name is None when no catalog
- source produced anything, which untooling reports as a defect rather than treating
- as "no tools loaded". Adapters that do not implement it fall back to parse_catalog
- and report the source as 'unknown'."""
- return self.parse_catalog(run_dir_path, agent), "unknown"
-
- # ---- waste signals (LLM-free) ----
- def detect(self, path):
- """-> dict of task-agnostic inefficiency signals + evidence for this domain."""
- ...
-
- # ---- untooling tool-sets ----
- def protected_tools(self):
- """-> frozenset of tools that must never be dropped (the real work surface)."""
- ...
-
- def inapplicable_tools(self):
- """-> tuple of tools inapplicable-by-construction for a single sealed task."""
- ...
-
- def hardcoded_exclusions(self, used_tools):
- """-> list of tools to drop under the hardcoded untool path, given the set of
- tools observed in use across the stream so far."""
- ...
-
- # ---- spiral envelope ----
- def spiral_snapshot(self, path):
- """-> a resolved-task turn snapshot for the per-stream envelope tracker."""
- ...
-
- # ---- per-task judge inputs ----
- def problem_statements(self):
- """-> {task_id: redacted_problem_statement} used by the untool per-task judge."""
- ...
-
- # ---- environment-fact vocabulary (optional) ----
- def env_vocabulary(self):
- """-> an `envfacts.Vocabulary` for this domain (OPTIONAL; default Python/git)."""
- from ..mechanisms.envfacts import PYTHON_GIT
- return PYTHON_GIT
diff --git a/tokeneconomizer/baselines/_repomap_gen.py b/tokeneconomizer/baselines/_repomap_gen.py
deleted file mode 100644
index af1a0f3..0000000
--- a/tokeneconomizer/baselines/_repomap_gen.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python3
-"""Host-side aider repo-map generator. Prints the map to stdout.
-
-A separate process, not an import, for two reasons: aider pulls a large dependency tree
-that must never enter the runner's own address space (the runner is the thing whose token
-accounting has to stay trustworthy, and aider constructs models), and a generator that
-crashes or hangs on a pathological repo then costs one non-zero exit instead of the task.
-
-Usage: _repomap_gen.py <src_dir> <map_tokens> [mentioned_idents_csv]
-"""
-import os
-import sys
-
-from aider.io import InputOutput
-from aider.models import Model
-from aider.repomap import RepoMap
-
-# Directories that are not the library under test. Their contents rank well (many files,
-# many symbols) while never containing the fix, so leaving them in spends the token budget
-# on documentation and benchmarks instead of on the code the agent has to change.
-SKIP = ("/.git", "/__pycache__", "/.tox", "/build", "/dist", "/.eggs", ".egg-info",
- "/doc/", "/docs/", "/examples/", "/benchmarks/", "/tutorial/", "/asv_benchmarks/")
-
-
-def main():
- repo = os.path.abspath(sys.argv[1])
- budget = int(sys.argv[2]) if len(sys.argv) > 2 else 2048
- mentioned = set(sys.argv[3].split(",")) if len(sys.argv) > 3 and sys.argv[3] else set()
-
- files = []
- for dirpath, _dirnames, filenames in os.walk(repo):
- if any(s in dirpath for s in SKIP):
- continue
- files.extend(os.path.join(dirpath, f) for f in filenames if f.endswith(".py"))
-
- # stdout is the MAP and nothing else. aider's console writes its progress and warnings
- # to stdout ("Initial repo scan can be slow in larger repos, but only happens once.",
- # model-metadata warnings), and the scaffold takes this process's stdout verbatim as the
- # map body -- so every line aider prints would land in the agent's instructions. Point
- # sys.stdout at stderr while aider is constructed and runs, and write the map afterwards.
- real_stdout, sys.stdout = sys.stdout, sys.stderr
- try:
- io = InputOutput()
- # Used ONLY for its token counter -- no model is called and no key is needed. The
- # map is produced by static analysis; the counter just enforces the budget.
- model = Model("gpt-4o")
- rm = RepoMap(map_tokens=budget, root=repo, main_model=model, io=io, verbose=False)
- text = rm.get_repo_map([], files, mentioned_idents=mentioned) or ""
- finally:
- sys.stdout = real_stdout
- sys.stdout.write(text)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tokeneconomizer/config.py b/tokeneconomizer/config.py
index 40315a5..4740136 100644
--- a/tokeneconomizer/config.py
+++ b/tokeneconomizer/config.py
@@ -1,14 +1,15 @@
-"""EconomizerConfig: three independent on/off switches, one per mechanism.
-
-The three mechanisms act at three different lifecycle points and never contend for the
-same lever, so the config is just their union. `from_args` maps CLI-style flags onto the
-config; unknown attributes default off (via getattr), so a partial args object is fine.
-
- * injection -- inject a firing-gated per-repo operating manual before the task.
- * tooling -- drop inapplicable tool schemas (generic evidence untooling for
- Claude/Copilot; Codex-native capability untooling for Codex).
- * spiral -- kill/nudge a stuck rollout in flight (generic guard for Claude/Copilot;
- Codex-native post-green finalize for Codex).
+"""The mechanisms' own configuration, one dataclass each (the plugin's settings are
+`plugin.config`):
+
+ * `InjectionConfig` -- micro-skills: which distiller renders the block (`envfacts`, the paid
+ `distiller`, or both), its caps, and the proposer's cadence;
+ * `ToolingConfig` -- tool pruning: the evidence threshold, the optional per-task judge, and
+ Codex's capability controller;
+ * `SpiralConfig` -- the loop guard as a benchmark harness runs it (the plugin's guard takes
+ its settings from `plugin.config`).
+
+`EconomizerConfig` is their union, and `from_args` maps a harness's command-line flags onto it;
+unknown attributes default off, so a partial args object is fine.
"""
from dataclasses import dataclass, field
@@ -50,14 +51,14 @@ class InjectionConfig:
@dataclass
class ToolingConfig:
- """Untooling stage.
+ """Tool pruning.
- Generic evidence untooling (Claude / Copilot):
+ Evidence pruning (Claude Code / Copilot):
* evidence -- drop a tool loaded-but-unused for >= this many tasks (>0 on).
* evidence_reaudit -- periodically reload the full catalog every this many tasks.
* judge -- add a per-task instruction-aware LLM tool judge.
- Codex-native capability untooling:
+ Codex capability pruning:
* codex_untool -- enable the evidence-gated, resolve-safe capability controller.
"""
evidence: int = 0
@@ -72,8 +73,9 @@ class ToolingConfig:
@dataclass
class SpiralConfig:
- """Spiral guard stage (generic for Claude/Copilot; Codex-native for Codex)."""
- guard: bool = False # generic spiral guard (Claude / Copilot)
+ """The loop guard in a benchmark harness (generic for Claude/Copilot; Codex-native for
+ Codex)."""
+ guard: bool = False # generic loop guard (Claude / Copilot)
judge: bool = False # sampled LLM trace-judge for the abort decision
nudge: bool = False # rung-1 same-container nudge before abort
nudge_llm: bool = False # LLM-written nudge redirect (vs the count template)
@@ -101,17 +103,17 @@ class SpiralConfig:
def needs_optimizer(config):
"""Whether ANY enabled mechanism will make a paid between-task LLM call.
- The three clauses mirror `facade.Economizer.__init__` exactly -- it resolves an
+ The three clauses mirror `te_bench.facade.Economizer.__init__` exactly -- it resolves an
optimizer runner for injection when `injection.paid` (enabled AND a profile that
- carries the paid `distiller`; the LLM-free `envfacts` profile never calls), for untooling when
+ carries the paid `distiller`; the LLM-free `envfacts` profile never calls), for pruning when
`tooling.judge`, and for spiral when the guard is on AND it has a judge or an LLM
nudge writer. Kept as one predicate because callers OUTSIDE the facade need the
aggregate answer: a harness whose mechanism transport must be preflighted should not
pay for (or depend on) that probe when the arm will never call it. Arm `mode` is NOT
the test -- `spiral-only` and `untool-only` are `standalone` and do make paid calls.
- tests/test_optimizer_basis.py asserts this agrees with the facade for every arm in the
- registry, so the two cannot drift.
+ experiments/tests/test_optimizer_basis.py asserts this agrees with the facade for every
+ arm in the registry, so the two cannot drift.
"""
return bool(
config.injection.paid
diff --git a/tokeneconomizer/domain.py b/tokeneconomizer/domain.py
new file mode 100644
index 0000000..1b4f844
--- /dev/null
+++ b/tokeneconomizer/domain.py
@@ -0,0 +1,77 @@
+"""`DomainAdapter`: everything the mechanisms need to know about where they run.
+
+The mechanisms are domain-neutral; what is specific to a domain -- how its logs read, which
+tools are its work surface, which words name its interpreters and test runners -- enters only
+through these methods. The plugin's adapter is `plugin.adapter.LiveAdapter` (a real repository
+in a person's session); the benchmark adapters live in `experiments/te_bench/adapters/`.
+
+ load_trajectory -> every mechanism's view of a finished session
+ tool_usage -> the tools a session used (tool pruning's evidence)
+ parse_catalog -> the tools a session loaded (what pruning may propose)
+ protected_tools -> the work surface pruning never touches
+ inapplicable_tools -> tools no task in this domain can use, by construction
+ hardcoded_exclusions -> that set, less the tools seen in use so far
+ spiral_snapshot -> a finished trajectory's loop signals, for the guard's envelope
+ problem_statements -> {task_id: task text} for the optional per-task tool judge
+ env_vocabulary -> (optional) the `microskills.Vocabulary` naming this domain's
+ interpreters, runners, package tools, fetchers and probes
+
+Running a task and grading it is not on this protocol: that is the caller's job (the plugin's
+host hooks, or a benchmark harness).
+"""
+from typing import Protocol, runtime_checkable
+
+
+@runtime_checkable
+class DomainAdapter(Protocol):
+ """Everything the mechanisms need to know about a task domain."""
+
+ name: str
+
+ # ---- reading a finished session ----
+ def load_trajectory(self, path):
+ """-> [(tool_name, args_dict, result_text, success_bool)] over a saved session log."""
+ ...
+
+ def tool_usage(self, path):
+ """-> {tool_name: count} over a saved session log."""
+ ...
+
+ def parse_catalog(self, run_dir_path, agent):
+ """-> {tool_name: description} the agent loaded for a task ({} if unavailable)."""
+ ...
+
+ def parse_catalog_with_source(self, run_dir_path, agent):
+ """-> ({tool: desc}, source_name) -- OPTIONAL. source_name is None when no catalog
+ source produced anything, which pruning reports as a defect rather than reading as
+ "no tools loaded". The default falls back to parse_catalog with source 'unknown'."""
+ return self.parse_catalog(run_dir_path, agent), "unknown"
+
+ # ---- tool pruning ----
+ def protected_tools(self):
+ """-> frozenset of tools that must never be dropped (the work surface)."""
+ ...
+
+ def inapplicable_tools(self):
+ """-> tuple of tools inapplicable by construction for a single task."""
+ ...
+
+ def hardcoded_exclusions(self, used_tools):
+ """-> the tools to drop without evidence, given those seen in use so far."""
+ ...
+
+ # ---- loop guard ----
+ def spiral_snapshot(self, path):
+ """-> a finished trajectory's loop-signal snapshot, for the envelope tracker."""
+ ...
+
+ # ---- per-task judge inputs ----
+ def problem_statements(self):
+ """-> {task_id: problem statement}, for the optional per-task tool judge."""
+ ...
+
+ # ---- micro-skill vocabulary (optional) ----
+ def env_vocabulary(self):
+ """-> a `microskills.Vocabulary` for this domain (default: Python/git)."""
+ from .microskills import PYTHON_GIT
+ return PYTHON_GIT
diff --git a/tokeneconomizer/ledger.py b/tokeneconomizer/ledger.py
index 6e58416..282c08f 100644
--- a/tokeneconomizer/ledger.py
+++ b/tokeneconomizer/ledger.py
@@ -1,23 +1,18 @@
-"""One honest cost definition for the economizer.
+"""One cost definition for every mechanism.
-The amortized cost of a task is the agent's EXECUTION cost plus every mechanism's LLM
-OVERHEAD, on the same cache-aware effective basis (pricing.effective_tokens):
+The cost of a task (a session, in the plugin) is the agent's EXECUTION cost plus every
+mechanism's LLM OVERHEAD, both on the cache-aware effective basis of `pricing.effective_tokens`:
task_cost(t) = effective_exec(t) + overhead(t)
amortized(T) = (1/T) * sum_{t<=T} task_cost(t)
-`overhead()` sums the per-mechanism token fields each mechanism emits into the stream row.
-Every field here is real mechanism-internal LLM cost that must be amortized into the
-honest task cost -- so a method that mainly prunes cheap cached re-reads cannot look
-better than its real-dollar effect, and one that adds paid proposer/judge/nudge calls
-pays for them in the same ledger.
-
-This is the SINGLE definition of "cost" for the whole package: the mechanisms write these
-raw fields at emit time and the aggregation scripts (experiments/scripts/summarize_stream.py,
-experiments/scripts/aggregate.py) read the total back through this module, so the emitted ledger and
-the reported ledger can never drift.
+`overhead()` sums the per-mechanism token fields a mechanism records. Every field is real LLM
+spend made on the agent's behalf, so a mechanism that adds paid proposer, judge or redirect calls
+pays for them in the same account as the work they are meant to save. The plugin's session
+ledger (`plugin.accounting`) and the experiments' aggregation scripts both read this one
+definition, so the recorded and the reported cost cannot drift apart.
"""
-from .vendor import pricing
+from . import pricing
# Per-task mechanism-overhead token fields, by owning mechanism. All are real
# mechanism-internal LLM cost that must be amortized into the honest task cost.
diff --git a/tokeneconomizer/loopguard/README.md b/tokeneconomizer/loopguard/README.md
new file mode 100644
index 0000000..aa5cc66
--- /dev/null
+++ b/tokeneconomizer/loopguard/README.md
@@ -0,0 +1,33 @@
+# 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).
+
+Per tool call, `turn.TurnGuard`:
+
+1. folds the call into a `state.SpiralState` -- edits per file, files edited, error outputs,
+ verification runs, and how often a failure repeats one seen before (edits made through the
+ shell count too, `shell_edits.py`);
+2. checks a hard backstop: stuck *and* far past this repository's envelope;
+3. asks `rules.assess_abort`: a free gate decides whether the turn is worth a look; then either
+ the optional paid judge (`judge.py`) or the strict heuristic `is_stuck` with the envelope
+ decides;
+4. answers the first stuck verdict with a redirect (`rules.nudge_text`, or a judge-written one)
+ and starts a fresh segment, so the agent gets a fair window to recover; a later one with a
+ stop.
+
+The **envelope** (`envelope.py`) is a percentile of how long this repository's turns run when
+they end well -- the agent stopped on its own and no check after its last edit failed. Only such
+turns feed it, and a turn's own outcome only gates later turns. The guard's thresholds start
+from a preset (`SPIRAL_LEVELS`), learn on top of it, and can be pinned by hand
+(`loopguard.<name>` settings).
+
+| Module | |
+|---|---|
+| `turn.py` | `TurnGuard`: the guard for one prompt-turn, persisted between hook calls |
+| `rules.py` | thresholds and presets, the gate, `is_stuck`, `assess_abort`, the redirect text |
+| `envelope.py` | `EnvelopeTracker` and its per-repository storage |
+| `state.py` | `SpiralState`, `completed_calls` (one streamed line to finished calls) |
+| `shell_edits.py` | files a shell command writes (`sed -i`, redirects, inline Python, ...) |
+| `judge.py` | the optional paid stuck judge and redirect writer |
diff --git a/tokeneconomizer/loopguard/__init__.py b/tokeneconomizer/loopguard/__init__.py
new file mode 100644
index 0000000..0789328
--- /dev/null
+++ b/tokeneconomizer/loopguard/__init__.py
@@ -0,0 +1,27 @@
+"""Failure-loop intervention: notice a prompt-turn stuck in a failing loop, redirect it once,
+then stop it (headless) or tell the person (interactive).
+
+ * `state` -- `SpiralState`, the per-call fold of a trajectory's loop signals;
+ * `rules` -- thresholds, the free gate, the strict heuristic, `assess_abort`, the redirect;
+ * `envelope` -- the per-repository length of turns that ended well, and its storage;
+ * `shell_edits` -- edits made through the shell, counted like edit-tool edits;
+ * `turn` -- `TurnGuard`, the guard for one prompt-turn, one tool call at a time;
+ * `judge` -- the optional paid stuck judge and redirect writer.
+
+Stdlib only; never imports the plugin runtime.
+"""
+from .envelope import (EnvelopeTracker, base_thresholds, load_envelope, record_turn,
+ save_envelope, thresholds)
+from .judge import llm_nudge_writer, llm_stuck_judge
+from .rules import (DEFAULT_THRESHOLDS, SPIRAL_LEVELS, assess_abort, gate_for_judge, is_stuck,
+ nudge_text, scaled_thresholds)
+from .shell_edits import fold_shell_edits, shell_edit_targets
+from .state import SpiralState, canon_tool, completed_calls, state_from_trajectory
+from .turn import VERIFY_RE, TurnGuard
+
+__all__ = ["EnvelopeTracker", "base_thresholds", "load_envelope", "record_turn",
+ "save_envelope", "thresholds", "llm_nudge_writer", "llm_stuck_judge",
+ "DEFAULT_THRESHOLDS", "SPIRAL_LEVELS", "assess_abort", "gate_for_judge", "is_stuck",
+ "nudge_text", "scaled_thresholds", "fold_shell_edits", "shell_edit_targets",
+ "SpiralState", "canon_tool", "completed_calls", "state_from_trajectory",
+ "VERIFY_RE", "TurnGuard"]
diff --git a/tokeneconomizer/loopguard/envelope.py b/tokeneconomizer/loopguard/envelope.py
new file mode 100644
index 0000000..2683039
--- /dev/null
+++ b/tokeneconomizer/loopguard/envelope.py
@@ -0,0 +1,205 @@
+"""The per-repository envelope: how long a turn that ended well usually runs.
+
+`EnvelopeTracker` learns, from turns that ended well only, a percentile of their lengths (the
+envelope past which a stuck trajectory may be acted on) and the detector thresholds on top of
+the preset level. A turn's own outcome only ever gates LATER turns. The functions below keep a
+tracker in a repository's state store between sessions, under the store's lock, since two
+sessions in one repository share it.
+"""
+import math
+
+from .rules import scaled_thresholds
+
+
+def _percentile(xs, p):
+ """Linear-interpolated p-th percentile of xs (0<=p<=100). xs need not be sorted."""
+ if not xs:
+ return None
+ xs = sorted(xs)
+ n = len(xs)
+ if n == 1:
+ return float(xs[0])
+ i = (p / 100.0) * (n - 1)
+ lo = int(i)
+ frac = i - lo
+ if lo + 1 >= n:
+ return float(xs[-1])
+ return xs[lo] + frac * (xs[lo + 1] - xs[lo])
+
+
+class EnvelopeTracker:
+ """Per-repo resolved-turn envelope AND runtime-learned detection thresholds.
+
+ Envelope: margin * the p<pct> of turn-counts among RESOLVED tasks seen so far. Using a
+ PERCENTILE (default p90), not the max, makes the gate robust to a single very-long
+ resolve — empirically one 115-turn xarray resolve set a max-based envelope to ~144 and
+ disabled the guard for every 40-60-turn spiral below it; p90 ignores that lone outlier
+ (envelope ~32) while staying HIGH on repos like matplotlib where long resolves are
+ COMMON (so productive-long tasks stay protected). Stays None until >=min_samples
+ resolved tasks exist (don't trust a percentile of a handful of points), so we never
+ abort on a repo we know little about yet.
+
+ Thresholds: `thresholds()` derives the FULL detector threshold dict from the SAME
+ resolved-task history, so the guard adapts to the agent/repo's actual turn scale
+ instead of the hardcoded Copilot-scale DEFAULT_THRESHOLDS (which never fired on Claude
+ Code's <=80-turn runs — its backstop landed above the turn cap). Turn-scale gates
+ scale DOWN to the learned distribution; signal gates keep DEFAULT as a FLOOR so the
+ learned dict is never MORE trigger-happy than the hand-tuned one (resolve-safety). Fed
+ only by RESOLVED tasks (same causal rule as the envelope), so a task's own outcome can
+ only gate FUTURE tasks, never itself."""
+ def __init__(self, margin=None, pct=None, min_samples=None, level="default",
+ frozen_envelope=None):
+ # `level` selects the aggressiveness preset (SPIRAL_LEVELS). It sets the BASE
+ # thresholds this tracker starts from AND the envelope margin/percentile/min-samples;
+ # explicit margin/pct/min_samples args still win over the preset when given.
+ self.level = level
+ self.base_thr = scaled_thresholds(level)
+ self.margin = margin or self.base_thr["envelope_margin"]
+ self.pct = pct if pct is not None else self.base_thr["envelope_pct"]
+ self.min_samples = (min_samples if min_samples is not None
+ else self.base_thr["envelope_min_samples"])
+ # FROZEN envelope (pre-registered hyperparameter): when set, `envelope` returns this
+ # value from task 1, bypassing the >=min_samples warm-up. For SHORT streams (Web-Bench
+ # = 20 tasks, ~5 resolved at ~25% Pass@1) the percentile never reaches min_samples, so
+ # a within-stream-learned envelope would stay None the whole run and the guard would
+ # never engage. A frozen scalar (calibrated once from SWE-bench/held-out, IDENTICAL
+ # across all streams -- a fixed hyperparameter, NOT a prior pooled across the streams)
+ # lets the guard engage while preserving stream independence. None => today's behavior.
+ self.frozen_envelope = frozen_envelope
+ self.resolved_turns = [] # all RESOLVED tasks' turn counts (for the percentile)
+ self.resolved_snaps = [] # per-resolved-task SpiralState.snapshot() dicts (signals)
+
+ def update(self, turns, resolved, snapshot=None):
+ """Record a completed task. Only RESOLVED tasks feed the baseline. `snapshot` is an
+ optional SpiralState.snapshot() dict (edit_churn/distinct_edit_files/error_outputs/
+ stagnation/...) captured from that task's trajectory; when omitted only the
+ turn-envelope learns (back-compat with callers that don't reconstruct the state)."""
+ if resolved and turns:
+ self.resolved_turns.append(turns)
+ if snapshot:
+ self.resolved_snaps.append(snapshot)
+
+ @property
+ def envelope(self):
+ if len(self.resolved_turns) < self.min_samples:
+ # cold start: fall back to the frozen pre-registered envelope if one was set
+ # (short-stream case); else None == "don't trust a handful of points yet".
+ return self.frozen_envelope
+ return _percentile(self.resolved_turns, self.pct) * self.margin
+
+ def thresholds(self, max_turns=None):
+ """Return the detector threshold dict to hand to is_stuck/gate_for_judge/
+ assess_abort. Starts from the LEVEL-scaled base (scaled_thresholds(self.level); ==
+ DEFAULT_THRESHOLDS for level 'default') and, once >=min_samples RESOLVED tasks
+ exist, overrides the learned keys from this stream's resolved-task distribution.
+ Before warm-up (or with no data) it returns the base verbatim, so behavior is
+ unchanged until the stream has learned enough — exactly like the envelope gating
+ None today. Learned signal-gates floor against the SCALED base, so an 'aggressive'
+ level genuinely lowers those floors (and 'conservative' raises them). Pass
+ `max_turns` (the run's turn cap) to make the hard backstop REACHABLE under the cap."""
+ base = self.base_thr
+ thr = dict(base)
+ env = self.envelope
+ # cap-aware backstop: reachable even under a tight turn cap. The Copilot-scale
+ # `backstop_mult * envelope` landed ABOVE Claude's 80-turn cap (~110 turns) so it
+ # never fired; clamp it under 0.9*cap so an extreme outlier still aborts in-cap.
+ if env is not None:
+ bt = env * thr["backstop_mult"]
+ if max_turns:
+ bt = min(bt, 0.9 * max_turns)
+ thr["backstop_turns"] = bt
+ if len(self.resolved_turns) < self.min_samples:
+ return thr # cold start: level-scaled base (+ backstop_turns if env exists)
+
+ # --- turn-scale gates: relative to the learned resolved-turn distribution. On a
+ # short-turn agent (Claude p90~35) this drops the judge gate from 18 -> ~10 so the
+ # guard can engage before the cap; on a long-turn agent (Copilot p90~150+) the
+ # clamp keeps it at the base ceiling (no change). ---
+ p90t = _percentile(self.resolved_turns, 90) or 0
+
+ def _clamp(v, lo, hi):
+ return int(max(lo, min(hi, round(v))))
+ thr["gate_min_turns"] = _clamp(0.6 * p90t, 6, base["gate_min_turns"])
+ thr["min_turns"] = _clamp(0.6 * p90t, 8, base["min_turns"])
+
+ # --- signal gates: treat RESOLVED runs as the "normal" band and sit just ABOVE its
+ # p90, but never BELOW the (level-scaled) base floor (so the learned dict is never
+ # more trigger-happy than the level asks — protects resolve-safety on churny-but-
+ # productive repos, where this RAISES the bar). Needs the per-task snapshots. ---
+ if self.resolved_snaps:
+ def _sig(key):
+ return [s.get(key, 0) or 0 for s in self.resolved_snaps]
+ thr["edit_churn"] = max(base["edit_churn"],
+ math.ceil((_percentile(_sig("edit_churn"), 90) or 0) + 1))
+ thr["distinct_edit_files"] = max(
+ base["distinct_edit_files"],
+ math.ceil((_percentile(_sig("distinct_edit_files"), 90) or 0) + 1))
+ thr["error_outputs"] = max(
+ base["error_outputs"],
+ math.ceil((_percentile(_sig("error_outputs"), 90) or 0) + 1))
+ thr["gate_error_outputs"] = max(base["gate_error_outputs"],
+ thr["error_outputs"])
+ thr["stagnation"] = max(base["stagnation"],
+ round(_percentile(_sig("stagnation"), 90) or 0, 3))
+ return thr
+
+
+# ---- the per-repository envelope ---------------------------------------------------------
+ENVELOPE_HISTORY = 500 # recent ended-green turns kept for the percentile
+
+
+# Overrides that shape the envelope itself, passed to the tracker; the rest are pinned over the
+# thresholds it returns.
+_ENVELOPE_KEYS = {"envelope_margin": "margin", "envelope_pct": "pct",
+ "envelope_min_samples": "min_samples"}
+
+
+def load_envelope(store, level="default", overrides=None):
+ d = store.read("envelope.json") or {}
+ ov = overrides or {}
+ tracker = EnvelopeTracker(level=level, **{
+ arg: ov[key] for key, arg in _ENVELOPE_KEYS.items() if key in ov})
+ tracker.resolved_turns = [int(x) for x in d.get("resolved_turns", []) if x]
+ tracker.resolved_snaps = [s for s in d.get("resolved_snaps", []) if isinstance(s, dict)]
+ return tracker
+
+
+def thresholds(tracker, overrides=None):
+ """The thresholds a turn is checked against: the preset, what this repository's history
+ learned on top of it, then a person's pinned values (`<name>`), which win."""
+ thr = tracker.thresholds(max_turns=None)
+ for key, value in (overrides or {}).items():
+ if key not in _ENVELOPE_KEYS:
+ thr[key] = value
+ if "backstop_mult" in (overrides or {}) and tracker.envelope is not None:
+ thr["backstop_turns"] = tracker.envelope * thr["backstop_mult"]
+ return thr
+
+
+def base_thresholds(level="default", overrides=None):
+ """The thresholds before any learning: the preset with a person's pinned values on top.
+ What `te config show` reports, so the numbers a setting replaces are visible."""
+ thr = scaled_thresholds(level)
+ thr.update(overrides or {})
+ return thr
+
+
+def save_envelope(store, tracker):
+ store.write("envelope.json", {
+ "level": tracker.level,
+ "resolved_turns": tracker.resolved_turns[-ENVELOPE_HISTORY:],
+ "resolved_snaps": tracker.resolved_snaps[-ENVELOPE_HISTORY:]})
+
+
+def record_turn(store, guard, level="default", stopped_normally=True, overrides=None):
+ """Fold a finished turn into the envelope -- under the store lock, since two sessions in
+ one repository share it. Only turns that ended green feed it, as only resolved tasks fed
+ the experiments' envelope; a turn's own outcome gates only later turns."""
+ # The snapshot is of the WHOLE turn (`guard.whole`), not the post-nudge segment: the
+ # experiments snapshot a resolved task's full trajectory (`spiral_snapshot(transcript)`).
+ with store.locked("envelope"):
+ tracker = load_envelope(store, level, overrides)
+ tracker.update(guard.cum_turns, guard.resolved_proxy(stopped_normally),
+ snapshot=guard.whole.snapshot())
+ save_envelope(store, tracker)
+ return tracker
diff --git a/tokeneconomizer/loopguard/judge.py b/tokeneconomizer/loopguard/judge.py
new file mode 100644
index 0000000..0d4142f
--- /dev/null
+++ b/tokeneconomizer/loopguard/judge.py
@@ -0,0 +1,102 @@
+"""The loop guard's two optional paid calls: a stuck judge and a redirect writer.
+
+Both read the same leakage-safe digest of the agent's recent actions
+(`SpiralState.recent_digest`: commands, searches, edited file basenames, error signatures --
+never file contents or the task text). The judge decides stuck-versus-productive when the free
+gate is open; the writer turns the redirect from a count template into one that names the
+pattern it sees. Each returns its effective-token cost so the caller can charge it to the
+session's ledger, and falls back to the free path on any failure.
+"""
+import json
+import re
+
+from ..pricing import runner_effective_or_approx as _runner_effective_or_approx
+
+STUCK_JUDGE_SYSTEM = (
+ "You monitor an AI coding agent that is partway through ONE task in a software repo. "
+ "A cheap heuristic flagged its recent process as a possible UNPRODUCTIVE LOOP. Read "
+ "the leakage-safe digest of its RECENT actions and judge whether it is genuinely "
+ "STUCK — repeating the same kind of edit/test/failure with no progress toward green "
+ "tests, unlikely to recover if it keeps going the same way — versus still making "
+ "real progress (changing failures, narrowing the problem, exploring new hypotheses).\n\n"
+ "Judge ONLY the workflow from the digest; do NOT infer the task's solution or which "
+ "lines to change. Favor SPARING (stuck=false) when there is any sign of progress; "
+ "only return stuck=true with high confidence for a clear, repetitive dead-end.\n"
+ "Return ONLY a JSON object: {\"stuck\": bool, \"confidence\": <0.0-1.0>, "
+ "\"reason\": \"<short leakage-safe justification>\"}."
+)
+
+
+def llm_stuck_judge(digest, runner, model="agent"):
+ """The sampled stuck judge. `digest` is a leakage-safe recent-process string
+ (`SpiralState.recent_digest()`). Returns a verdict dict
+ {stuck: bool|None, confidence: float, reason: str, _tokens: number}; stuck=None on any
+ failure (the caller treats None/ambiguous by falling back to the envelope gate).
+ `_tokens` is the REAL token cost of this paid judge call (input+output+cache, from the
+ runner's usage block; a char-based approximation if the runner couldn't recover it) so
+ the caller can charge it to the ledger. 0 when no call was made."""
+ if runner is None or not digest:
+ return {"stuck": None, "confidence": 0.0, "reason": "no-runner", "_tokens": 0}
+ prompt = (STUCK_JUDGE_SYSTEM + "\n\nRecent process digest:\n" + digest
+ + "\n\nReturn the JSON verdict:")
+ try:
+ raw, _real = runner(prompt, model)
+ except Exception as e:
+ return {"stuck": None, "confidence": 0.0,
+ "reason": f"runner-error:{e}"[:60], "_tokens": 0}
+ raw = raw or ""
+ # EFFECTIVE (cache-aware) cost when the runner recovered usage; else approximate on the
+ # SAME basis: an uncached one-shot -> prompt is fresh input (weight 1), reply is output
+ # (weight 5). Keeps mechanism cost comparable to exec's cache-aware effective tokens.
+ _tokens = _runner_effective_or_approx(runner, prompt, raw, _real)
+ verdict = {"stuck": None, "confidence": 0.0, "reason": "", "_tokens": _tokens}
+ m = re.search(r"\{.*\}", raw, re.S)
+ if m:
+ try:
+ obj = json.loads(m.group(0))
+ verdict["stuck"] = (bool(obj["stuck"]) if "stuck" in obj
+ and obj["stuck"] is not None else None)
+ verdict["confidence"] = max(0.0, min(1.0, float(obj.get("confidence", 0) or 0)))
+ verdict["reason"] = str(obj.get("reason", ""))[:160]
+ except Exception:
+ pass
+ return verdict
+
+
+NUDGE_WRITER_SYSTEM = (
+ "An AI coding agent is stuck in a REPETITIVE, UNPRODUCTIVE loop partway through one "
+ "task in a software repo. You are given a leakage-safe digest of its RECENT ACTIONS "
+ "only (tool names, shell commands, searched patterns, edited file BASENAMES, and "
+ "error SIGNATURES — never file contents or the task description). Write a SHORT "
+ "redirect (2-4 sentences) addressed to the agent that: (1) names the specific "
+ "repetitive pattern you actually see in the digest (e.g. re-editing the same file, "
+ "re-running the same test to the same failure); (2) proposes a MATERIALLY DIFFERENT "
+ "next step (a different file/root-cause to consider, re-reading the failing test's "
+ "expectation, verifying a new hypothesis before editing again).\n"
+ "HARD CONSTRAINTS: Do NOT tell it to stop, give up, or reduce effort — only redirect. "
+ "Do NOT infer the task's solution, name specific line numbers to change, or reference "
+ "any code/identifier you cannot see in the digest. Output ONLY the redirect as plain "
+ "text — no preamble, no JSON, no headings."
+)
+
+
+def llm_nudge_writer(digest, runner, model="agent"):
+ """The sampled redirect writer. `digest` is the same leakage-safe recent-process
+ string the judge reads. Returns {"text": str, "_tokens": number}: a targeted redirect and
+ the effective token cost of the call, on the judge's basis. On any failure returns
+ {"text": "", "_tokens": 0} so the caller falls back to `rules.nudge_text`."""
+ if runner is None or not digest:
+ return {"text": "", "_tokens": 0}
+ prompt = (NUDGE_WRITER_SYSTEM + "\n\nRecent process digest:\n" + digest
+ + "\n\nWrite the redirect:")
+ try:
+ raw, _real = runner(prompt, model)
+ except Exception:
+ return {"text": "", "_tokens": 0}
+ raw = (raw or "").strip()
+ if not raw:
+ return {"text": "", "_tokens": 0}
+ # EFFECTIVE (cache-aware) cost when the runner recovered usage; else approximate on the
+ # SAME model-priced basis as llm_stuck_judge.
+ _tokens = _runner_effective_or_approx(runner, prompt, raw, _real)
+ return {"text": raw[:1200], "_tokens": _tokens}
diff --git a/tokeneconomizer/loopguard/rules.py b/tokeneconomizer/loopguard/rules.py
new file mode 100644
index 0000000..ff252d9
--- /dev/null
+++ b/tokeneconomizer/loopguard/rules.py
@@ -0,0 +1,198 @@
+"""When a trajectory counts as stuck, and what to do about it.
+
+Three tiers, cheapest first:
+
+ * `gate_for_judge` -- free, every call: is the recent trace worth a paid look at all?
+ * a paid judge -- optional (`judge.llm_stuck_judge`), only when the gate is open;
+ * `is_stuck` -- the strict heuristic decision used when no judge is wired: churn or
+ scatter, AND sustained errors, AND repeated identical failures.
+
+`assess_abort` runs the cascade against a per-repository envelope (how long a turn that ended
+well usually runs, `envelope.EnvelopeTracker`) with a hard backstop the judge cannot veto.
+`nudge_text` is the redirect the guard sends first: it mirrors only the agent's own actions
+back at it, carries no outside knowledge, and never tells it to stop.
+"""
+# ---- detector thresholds -----------------------------------------------------
+# The "stuck" signature (calibrated on the measured separation: spirals showed first-
+# 40-turn edit_churn ~6 vs ~1.5 normal, distinct_edit_files ~2.5 vs ~1, error_outputs
+# ~9 vs ~3). We require a CONJUNCTION (churn AND errors/scatter AND some repetition)
+# so productive-but-hard tasks (high activity, but CHANGING failures) are spared.
+DEFAULT_THRESHOLDS = {
+ "min_turns": 20, # don't judge stuck before the solve loop has run a while
+ "edit_churn": 4, # >=4 edits to one file
+ "distinct_edit_files": 3, # OR edits scattered across >=3 files
+ "error_outputs": 6, # sustained error density
+ "stagnation": 0.20, # >=20% of failures are repeats of an earlier one
+ "envelope_margin": 1.25, # restart/abort only beyond margin x the resolved-turn pctl
+ "envelope_pct": 90, # use the p90 of resolved turns (NOT max) — robust to a
+ # single very-long resolve poisoning the gate (see
+ # EnvelopeTracker). max-based envelope was disabled by one
+ # 115-turn xarray resolve; p90 ignores the lone outlier.
+ "envelope_min_samples": 5, # need >=5 resolved tasks before trusting the percentile
+ "judge_confidence": 0.7, # LLM trace-judge must be >=this confident to drive an abort
+ "backstop_mult": 2.5, # HARD backstop: beyond this multiple of the envelope, a
+ # stuck trajectory aborts REGARDLESS of the judge's verdict.
+ # Empirically the judge spared xarray-7019/7179 at 5.8x the
+ # envelope (177-204 turns vs envelope 35, stagnation 0.3-0.4)
+ # by misreading multi-file thrashing as "exploration"; the
+ # judge must not be able to veto a screaming outlier.
+ # ---- cheap GATE to the judge (Tier-0): permissive "worth a paid look?" trigger.
+ # Sensitive on purpose (catch candidates); the judge supplies precision. Far cheaper
+ # to evaluate than the judge, and far more permissive than is_stuck (which is the
+ # strict heuristic DECISION used only in the no-judge fallback).
+ "gate_min_turns": 18, # don't wake the judge before the loop has had time to form
+ "gate_error_outputs": 8, # OR: a lot of errors even without an exact repeat
+}
+
+
+# A single LEVEL scales the thresholds the guard starts from (the per-repository
+# EnvelopeTracker then learns on top, flooring learned signal gates against it). 'default' is
+# DEFAULT_THRESHOLDS exactly. 'aggressive' mainly wakes the nudge -- lower judge confidence, an
+# earlier gate, `nudge_on_ambiguous` -- and pulls the backstop in modestly (2.5x -> 1.8x);
+# 'conservative' spares harder, for churny-but-productive repositories.
+# nudge_on_ambiguous: a judge-AMBIGUOUS trajectory past the envelope gets the redirect
+# (never a stop) instead of being spared outright. Only 'aggressive' sets it.
+SPIRAL_LEVELS = {
+ "conservative": {
+ "judge_confidence": 0.85, "envelope_margin": 1.5, "backstop_mult": 3.5,
+ "stagnation": 0.30, "gate_min_turns": 24, "min_turns": 28,
+ "edit_churn": 5, "error_outputs": 8, "envelope_min_samples": 7,
+ },
+ "default": {}, # verbatim DEFAULT_THRESHOLDS — reproduces pre-knob behavior exactly
+ "aggressive": {
+ "judge_confidence": 0.55, "envelope_margin": 1.0, "backstop_mult": 1.8,
+ "stagnation": 0.12, "gate_min_turns": 12, "min_turns": 14,
+ "edit_churn": 3, "error_outputs": 4, "envelope_min_samples": 3,
+ "nudge_on_ambiguous": True,
+ },
+}
+
+
+def scaled_thresholds(level="default"):
+ """Return DEFAULT_THRESHOLDS overlaid with the named LEVEL's overrides (see
+ SPIRAL_LEVELS). Unknown level falls back to 'default' (verbatim defaults). This is the
+ BASE the EnvelopeTracker starts from; per-repo learning floors on top of it."""
+ thr = dict(DEFAULT_THRESHOLDS)
+ thr.update(SPIRAL_LEVELS.get(level, SPIRAL_LEVELS["default"]))
+ return thr
+
+
+def gate_for_judge(state, thr=None):
+ """TIER-0 (free, every turn): cheap rule-based trigger deciding whether the recent
+ trace is worth ELEVATING to the paid LLM judge. Permissive — it only needs a sign of
+ POSSIBLE trouble after the loop has had time to form: a repeated identical failure
+ (the cheapest 'no progress' signal) OR a high error density. Productive trajectories
+ (changing failures, few repeats) mostly keep this gate CLOSED, so the judge is rarely
+ consulted; the judge then makes the precise stuck-vs-productive call. This separation
+ is what keeps the judge from being a per-step tax."""
+ thr = thr or DEFAULT_THRESHOLDS
+ if state.turns < thr["gate_min_turns"]:
+ return False
+ return (state.repeated_fail_sigs >= 1
+ or state.error_outputs >= thr["gate_error_outputs"])
+
+
+def is_stuck(state, thr=None):
+ """Strict heuristic 'this looks like an unproductive loop' classifier — the DECISION
+ used only in the no-judge fallback. Must have run a while AND show churn/scatter AND
+ repeated identical failures (stagnation): the last term is what separates a doomed
+ spiral from a productive hard grind. (When the judge is wired, gate_for_judge is the
+ cheap trigger and the judge is the decision; is_stuck is not used.)"""
+ thr = thr or DEFAULT_THRESHOLDS
+ if state.turns < thr["min_turns"]:
+ return False
+ churny = (state.edit_churn >= thr["edit_churn"]
+ or state.distinct_edit_files >= thr["distinct_edit_files"])
+ noisy = state.error_outputs >= thr["error_outputs"]
+ repeating = state.stagnation >= thr["stagnation"]
+ return churny and noisy and repeating
+
+
+def assess_abort(state, envelope=None, judge=None, thr=None):
+ """Decide whether to abort, TRACE-FIRST, as an explicit TWO-TIER cascade. Returns
+ (abort: bool, reason: str).
+
+ TIER 0 — cheap rule-based GATE (free, every turn): gate_for_judge(). Decides only
+ whether the recent trace is WORTH a paid look. Permissive; productive trajectories
+ mostly keep it closed, so the judge is rarely consulted (this is what makes the
+ judge not a per-step tax).
+ TIER 1 — paid LLM JUDGE (only when the gate is open, and the caller additionally
+ rate-limits it): reads a leakage-safe digest of the RECENT actions and decides
+ stuck-vs-productive. The judge — not the step count — drives the outcome:
+ - STUCK, confidence>=judge_confidence -> ABORT, even within the envelope (a
+ clearly-doomed loop shouldn't burn tokens up to the envelope first);
+ - PRODUCTIVE -> SPARE, even past the envelope (progress shows in the trace);
+ - ambiguous -> defer to the envelope fallback.
+ FALLBACK — when NO judge is wired (judge=None): the strict is_stuck() heuristic plus
+ the per-repo resolved-turn envelope (the Phase-1.5 behavior), so the guard still
+ works cheaply without an LLM.
+ """
+ thr = thr or DEFAULT_THRESHOLDS
+
+ # HARD BACKSTOP (checked BEFORE the judge): an extreme outlier — far past the
+ # envelope AND stuck by the strict heuristic — aborts regardless of any judge
+ # verdict. The judge cannot veto this; it exists because the LLM judge empirically
+ # rationalized 5.8x-envelope thrashing (xarray-7019/7179) as "exploration".
+ # `backstop_turns` (learned, cap-aware) is preferred when the tracker supplied it, so
+ # the backstop stays REACHABLE under a tight turn cap; else fall back to the
+ # multiplier-on-envelope form (the Copilot-scale behavior).
+ backstop_turns = thr.get("backstop_turns")
+ if backstop_turns is None and envelope is not None:
+ backstop_turns = envelope * thr["backstop_mult"]
+ if (backstop_turns is not None
+ and state.turns >= backstop_turns
+ and is_stuck(state, thr)):
+ return True, (f"backstop:{state.turns}>={backstop_turns:.0f}"
+ f"turns stagnation={state.stagnation:.2f}")
+
+ if judge is not None:
+ # TWO-TIER: gate -> judge. The gate opens on the cheap rule-based trigger OR when
+ # the trajectory is already PAST this repo's typical resolved length (envelope) —
+ # an over-envelope run is worth a paid judge look even without an exact repeated
+ # failure yet, which is what lets the guard engage on a short-turn agent whose
+ # spirals hit the cap before accumulating a repeat signature.
+ over_envelope = envelope is not None and state.turns >= envelope
+ if not (gate_for_judge(state, thr) or over_envelope):
+ return False, "gate-closed"
+ try:
+ v = judge(state.recent_digest(envelope=envelope)) # caller rate-limits
+ except Exception:
+ v = None
+ if not v:
+ return False, "judge-throttled"
+ conf = float(v.get("confidence", 0) or 0)
+ if v.get("stuck") and conf >= thr["judge_confidence"]:
+ return True, f"judge-stuck@{conf:.2f}:{str(v.get('reason',''))[:60]}"
+ if v.get("stuck") is False:
+ return False, "judge-productive"
+ # judge AMBIGUOUS (stuck=None): do NOT abort on the (possibly under-calibrated,
+ # early-stream) envelope alone — that killed resolvable tasks like xarray-7120 at
+ # turn 28 when the p90 envelope was only 27. Ambiguity => SPARE; the hard backstop
+ # (2.5x envelope AND is_stuck, checked above) remains the only envelope-driven kill,
+ # and it sits well beyond any resolvable task's length.
+ return False, "judge-ambiguous-spared"
+
+ # FALLBACK (no judge): strict heuristic + envelope safety gate.
+ if not is_stuck(state, thr):
+ return False, "not-stuck"
+ if envelope is not None and state.turns >= envelope:
+ return True, f"envelope:{state.turns}>={envelope:.0f}"
+ return False, "stuck-but-within-envelope"
+
+
+def nudge_text(state):
+ """The redirect: mirror the agent's OWN repeated actions back at it. Contains
+ nothing but a summary of what it already did — leakage-safe by construction, and
+ framed to REDIRECT effort, never to stop it."""
+ busiest = max(state.edit_counts.items(), key=lambda kv: kv[1])[0] \
+ if state.edit_counts else "one file"
+ return (
+ "Process check (automated): so far you've made "
+ f"{sum(state.edit_counts.values())} edits across "
+ f"{state.distinct_edit_files} file(s) (most to `{busiest}`) and run "
+ f"{state.test_runs} verification(s), and the same failure has recurred "
+ f"{state.repeated_fail_sigs} time(s) without the tests going green. This "
+ "looks like a repetitive loop. Do NOT stop — instead step back and try a "
+ "MATERIALLY DIFFERENT hypothesis: re-read the failing test's expectation, "
+ "consider a different file or root cause than the ones you've been editing, "
+ "and verify the new hypothesis directly before editing again.")
diff --git a/tokeneconomizer/loopguard/shell_edits.py b/tokeneconomizer/loopguard/shell_edits.py
new file mode 100644
index 0000000..a6ed178
--- /dev/null
+++ b/tokeneconomizer/loopguard/shell_edits.py
@@ -0,0 +1,188 @@
+"""Edits made through the shell, which an edit-tool counter does not see.
+
+`SpiralState` counts an edit only when an edit TOOL makes it (Edit/Write/str_replace). An agent
+that edits through Bash -- `sed -i`, `perl -pi`, a redirect or `tee` into a source file, an
+inline Python script that writes the file back, `patch`/`git apply` -- looked like one that had
+edited nothing, and a judge reading the digest was told no file had been edited when four had.
+`shell_edit_targets` reads those writes off the command, and `fold_shell_edits` counts them
+after the regular update, so the call still counts once.
+"""
+import re
+import shlex
+
+from .state import basename
+
+_HEREDOC_START = re.compile(r"<<-?\s*(['\"]?)([A-Za-z_]\w*)\1")
+_OPS = {"&&", "||", ";", ";;", "|", "|&", "&", "\n", "(", ")"}
+_OUT = {">", ">>", ">|", "&>", "&>>"} # redirects that write their operand
+_SKIP_OPERAND = {"<", "<<", "<<<", "<&", ">&", "<>"} # input, heredoc tags, fd duplication
+# Redirect and `tee` targets count only when they look like source, so `> out.log` or
+# `| tee /tmp/run.txt` -- capturing output -- is not mistaken for an edit.
+_SOURCE_FILE = re.compile(
+ r"\.(?:py|pyi|pyx|pxd|js|jsx|mjs|cjs|ts|tsx|rs|go|java|kt|kts|scala|c|cc|cpp|cxx|h|hh|hpp|"
+ r"rb|php|cs|swift|m|mm|sh|bash|zsh|lua|jl|ex|exs|erl|hs|ml|clj|sql|toml|ya?ml|json|cfg|ini|"
+ r"conf|md|rst|html?|css|scss|vue|svelte|xml|gradle|properties|in)$", re.I)
+_PYTHON = re.compile(r"(?:^|[\s/;&|(])python\d?(?:\.\d+)?\b")
+_PY_OPEN_LIT = re.compile(r"open\(\s*(['\"])([^'\"\n]+)\1\s*,\s*(['\"])([^'\"]*)\3")
+_PY_OPEN_VAR = re.compile(r"open\(\s*([A-Za-z_]\w*)\s*,\s*(['\"])([^'\"]*)\2")
+_PY_WRITE_PATH_LIT = re.compile(
+ r"(?:pathlib\.)?Path\(\s*(['\"])([^'\"\n]+)\1\s*\)\.write_(?:text|bytes)\(")
+_PY_WRITE_PATH_VAR = re.compile(r"\b([A-Za-z_]\w*)\.write_(?:text|bytes)\(")
+
+
+def _not_scratch(path):
+ return bool(path) and not path.startswith(("/dev/", "/proc/", "/tmp/"))
+
+
+def _unquote(t):
+ return t[1:-1] if len(t) >= 2 and t[0] == t[-1] and t[0] in "'\"" else t
+
+
+def _split_heredocs(cmd):
+ """(the command's shell text without heredoc bodies, the bodies)."""
+ shell, bodies, tag, body = [], [], None, []
+ for line in cmd.split("\n"):
+ if tag is not None:
+ if line.strip() == tag:
+ bodies.append("\n".join(body))
+ tag, body = None, []
+ else:
+ body.append(line)
+ continue
+ shell.append(line)
+ m = _HEREDOC_START.search(line)
+ if m:
+ tag = m.group(2)
+ if tag is not None:
+ bodies.append("\n".join(body))
+ return "\n".join(shell), bodies
+
+
+def _tokens(text):
+ """Shell words and operators. Quotes stay on quoted words, so a quoted `'>'` or `'|'` is
+ never read as an operator; ValueError on unbalanced quotes."""
+ lex = shlex.shlex(text, posix=False, punctuation_chars="();<>|&\n")
+ lex.whitespace = " \t\r"
+ lex.whitespace_split = True
+ return list(lex)
+
+
+def _commands(shell):
+ """(simple commands as unquoted word lists, the files their redirects write)."""
+ try:
+ streams = [_tokens(shell)]
+ except ValueError: # one bad line must not hide the others
+ streams = []
+ for line in shell.split("\n"):
+ try:
+ streams.append(_tokens(line) + ["\n"])
+ except ValueError:
+ continue
+ cmds, writes = [], []
+ for toks in streams:
+ cur, i = [], 0
+ while i < len(toks):
+ t = toks[i]
+ if t in _OPS:
+ if cur:
+ cmds.append(cur)
+ cur = []
+ elif t in _OUT or t in _SKIP_OPERAND:
+ if cur and cur[-1].isdigit(): # `2>`: the fd number is not an operand
+ cur.pop()
+ if t in _OUT and i + 1 < len(toks) and toks[i + 1] not in _OPS:
+ writes.append(_unquote(toks[i + 1]))
+ i += 1
+ else:
+ cur.append(_unquote(t))
+ i += 1
+ if cur:
+ cmds.append(cur)
+ return cmds, writes
+
+
+def _inplace_files(tokens, inplace_flag, script_flag):
+ """File operands of an in-place editor (`sed -i`, `perl -pi`), or [] if not in place."""
+ if not any(inplace_flag(t) for t in tokens[1:]):
+ return []
+ files, have_script, skip = [], False, False
+ for t in tokens[1:]:
+ if skip:
+ skip, have_script = False, True
+ continue
+ if not t or t.startswith("-"):
+ if t and script_flag(t):
+ skip = True # the next token is the script
+ continue
+ if not have_script:
+ have_script = True # the first operand is the script
+ continue
+ files.append(t)
+ return files
+
+
+def _py_writes(text):
+ """Paths an inline Python script writes; "(script)" for a write whose path this cannot
+ resolve."""
+ out = []
+ for m in _PY_OPEN_LIT.finditer(text):
+ if set(m.group(4)) & set("wax+"):
+ out.append(m.group(2))
+ variables = [m.group(1) for m in _PY_OPEN_VAR.finditer(text) if set(m.group(3)) & set("wax+")]
+ out += [m.group(2) for m in _PY_WRITE_PATH_LIT.finditer(text)]
+ variables += [m.group(1) for m in _PY_WRITE_PATH_VAR.finditer(text)]
+ for var in dict.fromkeys(variables):
+ found = re.findall(rf"\b{re.escape(var)}\s*=\s*(?:(?:pathlib\.)?Path\(\s*)?(['\"])"
+ rf"([^'\"\n]+)\1", text)
+ loop = re.search(rf"\bfor\s+{re.escape(var)}\s+in\s+[\[(]([^\])]*)[\])]", text)
+ paths = [p for _, p in found]
+ if loop:
+ paths += re.findall(r"['\"]([^'\"\n]+)['\"]", loop.group(1))
+ out += paths or ["(script)"]
+ return out
+
+
+def shell_edit_targets(cmd):
+ """Basenames of the files a shell command writes, in order, without repeats."""
+ if not isinstance(cmd, str) or not cmd.strip():
+ return []
+ shell, bodies = _split_heredocs(cmd)
+ cmds, writes = _commands(shell)
+ found = [w for w in writes if _SOURCE_FILE.search(w)]
+ for tokens in cmds:
+ while tokens and (tokens[0] in ("sudo", "command", "env", "time", "nohup")
+ or re.match(r"^\w+=", tokens[0])):
+ tokens = tokens[1:]
+ if not tokens:
+ continue
+ head = tokens[0].rsplit("/", 1)[-1]
+ if head == "sed":
+ found += _inplace_files(
+ tokens, lambda t: bool(re.match(r"^(?:-[a-zA-Z]*i|--in-place)", t)),
+ lambda t: t in ("-e", "-f", "--expression", "--file"))
+ elif head == "perl":
+ found += _inplace_files(tokens, lambda t: bool(re.match(r"^-[a-zA-Z]*i", t)),
+ lambda t: bool(re.match(r"^-[a-zA-Z]*e$", t)))
+ elif head == "tee":
+ found += [t for t in tokens[1:] if not t.startswith("-") and _SOURCE_FILE.search(t)]
+ elif head == "patch" or (head == "git" and len(tokens) > 1 and tokens[1] == "apply"):
+ found.append("(patch)")
+ elif head == "git" and len(tokens) > 2 and tokens[1] in ("checkout", "restore"):
+ rest = (tokens[tokens.index("--") + 1:] if "--" in tokens
+ else tokens[2:] if tokens[1] == "restore" else [])
+ found += [t for t in rest if not t.startswith("-")]
+ if _PYTHON.search(shell):
+ found += _py_writes("\n".join([shell] + bodies))
+ names = [p if p.startswith("(") else basename(p)
+ for p in found if p.startswith("(") or _not_scratch(p)]
+ return list(dict.fromkeys(n for n in names if n))
+
+
+def fold_shell_edits(st, names):
+ """Count `names` as edits in a SpiralState, and say so in its action log."""
+ for b in names:
+ st.edit_order.append(b)
+ st.edit_counts[b] = st.edit_counts.get(b, 0) + 1
+ if names and st.recent:
+ shown = ", ".join(names[:4]) + (", ..." if len(names) > 4 else "")
+ st.recent[-1] = f"{st.recent[-1]} [edits {shown}]"
diff --git a/tokeneconomizer/loopguard/state.py b/tokeneconomizer/loopguard/state.py
new file mode 100644
index 0000000..127f10a
--- /dev/null
+++ b/tokeneconomizer/loopguard/state.py
@@ -0,0 +1,242 @@
+"""What the loop guard reads off a trajectory: a per-call fold of its failure-loop signals.
+
+`SpiralState` is updated once per completed tool call and keeps only counts and a short,
+leakage-safe action log: edits per file, files edited, error outputs, verification runs, and how
+often a failure repeats one seen before (`stagnation`, the signal that separates a loop from a
+hard but productive grind). `completed_calls` turns one streamed line of any agent's output into
+the calls it completes, so the same fold runs live and over a saved log.
+"""
+import hashlib
+import json
+import re
+
+from ..trace import load_trajectory as _load_trajectory
+
+# An output that RAN code to verify behavior (the test/repro step of the edit->test
+# loop).
+TEST_RUN_RE = re.compile(
+ r"(runtests(\.py)?|\bpytest\b|py\.test|manage\.py\s+test|python\s+-m\s+unittest|"
+ r"\btox\b|\bnox\b|\btrial\b|python\d?\s+-c\b)", re.IGNORECASE)
+ERR_RE = re.compile(
+ r"(Traceback \(most recent call last\)|\b\w*Error\b|\bFAILED\b|\bassert\b|"
+ r"Exception|errors during collection)", re.IGNORECASE)
+_EDIT_TOOLS = ("edit", "str_replace", "create")
+# Tools whose output is the content of files, not the outcome of running anything: a test file
+# full of `assert` read back is not a failure, nor is reading it twice a repeated one.
+_CONTENT_TOOLS = ("view", "grep", "glob")
+
+# Normalize agent-specific tool names to the copilot-style canonical names the folding
+# logic below keys on, so ONE code path handles both the Copilot stream schema and Claude
+# Code's stream-json (which names tools Bash/Read/Edit/Write/Grep/Glob/MultiEdit). Unknown
+# names pass through unchanged.
+_TOOL_CANON = {
+ "bash": "bash", "shell": "bash",
+ "read": "view", "view": "view",
+ "grep": "grep",
+ "glob": "glob",
+ "edit": "edit", "multiedit": "edit", "str_replace": "edit",
+ "apply_patch": "edit",
+ "write": "create", "create": "create",
+}
+
+
+def canon_tool(name):
+ return _TOOL_CANON.get((name or "").lower(), name or "?")
+
+
+def completed_calls(line, pend):
+ """Schema-agnostic fold of ONE streamed JSONL line into completed (name, args, result)
+ tool calls, so the live guards work for BOTH the Copilot stream
+ (tool.execution_start/complete) AND Claude Code's stream-json (assistant.tool_use /
+ user.tool_result). `pend` is a caller-owned dict {callId -> {name,args}} carried across
+ lines to pair a start/tool_use with its later complete/tool_result. Yields a list of
+ completed calls finished on THIS line (0, 1, or — for a Claude user msg batching
+ several tool_results — more). Tool names are canonicalized so downstream keying is
+ uniform; unpaired results fall back to name '?'."""
+ try:
+ ev = json.loads(line)
+ except Exception:
+ return []
+ t = ev.get("type")
+ out = []
+ # ---- Codex exec --json schema ----
+ if t == "item.completed":
+ item = ev.get("item") or {}
+ kind = item.get("type")
+ if kind == "command_execution":
+ out.append(("bash", {"command": item.get("command") or ""},
+ item.get("aggregated_output") or ""))
+ elif kind == "file_change":
+ changes = item.get("changes") or []
+ paths = [c.get("path") for c in changes
+ if isinstance(c, dict) and c.get("path")]
+ out.append(("edit", {"path": paths[0] if paths else "",
+ "paths": paths, "changes": changes}, ""))
+ return out
+ # ---- Copilot schema ----
+ if t == "tool.execution_start":
+ d = ev.get("data", {}) if isinstance(ev.get("data"), dict) else {}
+ pend[d.get("toolCallId")] = {"name": d.get("toolName"),
+ "args": d.get("arguments", {}) or {}}
+ return out
+ if t == "tool.execution_complete":
+ d = ev.get("data", {}) if isinstance(ev.get("data"), dict) else {}
+ info = pend.pop(d.get("toolCallId"), {"name": "?", "args": {}})
+ res = d.get("result") or {}
+ c = res.get("content") if isinstance(res, dict) else ""
+ out.append((canon_tool(info["name"]), info.get("args") or {},
+ c if isinstance(c, str) else ""))
+ return out
+ # ---- Claude Code stream-json schema ----
+ if t == "assistant":
+ for b in (ev.get("message", {}) or {}).get("content", []) or []:
+ if isinstance(b, dict) and b.get("type") == "tool_use":
+ pend[b.get("id")] = {"name": b.get("name"),
+ "args": b.get("input", {}) or {}}
+ return out
+ if t == "user":
+ for b in (ev.get("message", {}) or {}).get("content", []) or []:
+ if isinstance(b, dict) and b.get("type") == "tool_result":
+ info = pend.pop(b.get("tool_use_id"), {"name": "?", "args": {}})
+ c = b.get("content")
+ if isinstance(c, list): # content can be a list of text blocks
+ c = " ".join(x.get("text", "") for x in c if isinstance(x, dict))
+ out.append((canon_tool(info["name"]), info.get("args") or {},
+ c if isinstance(c, str) else ""))
+ return out
+ return out
+
+
+def basename(p):
+ return p.rstrip("/").split("/")[-1] if p else (p or "")
+
+
+def _failure_sig(text):
+ """A normalized signature of a failing output: drop numbers/addresses/paths so two
+ runs that fail the SAME way hash identically (used to detect 'no progress' — the
+ same failure recurring after edits). Leakage-safe: a hash, never the content."""
+ if not text:
+ return None
+ first = None
+ for ln in text.splitlines():
+ if ERR_RE.search(ln):
+ first = ln
+ break
+ if first is None:
+ return None
+ norm = re.sub(r"0x[0-9a-f]+|\d+|/\S+", "", first)
+ return hashlib.md5(norm.strip().encode("utf-8", "replace")).hexdigest()[:10]
+
+
+class SpiralState:
+ """Compact, incremental fold of one trajectory's spiral signals. Cheap to update
+ per event so it can run live."""
+ __slots__ = ("turns", "edit_counts", "edit_order", "error_outputs",
+ "test_runs", "fail_sigs", "repeated_fail_sigs", "recent")
+
+ def __init__(self):
+ self.turns = 0
+ self.edit_counts = {} # basename -> #edits
+ self.edit_order = [] # ordered basenames of edit targets
+ self.error_outputs = 0 # tool outputs carrying an error/failure marker
+ self.test_runs = 0 # code-execution verification steps
+ self.fail_sigs = {} # failure signature -> count
+ self.repeated_fail_sigs = 0 # # of failing outputs that REPEAT an earlier sig
+ self.recent = [] # leakage-safe rolling log of recent actions (for the
+ # LLM trace-judge); process-only, never fix content
+
+ # ---- derived signals ----
+ @property
+ def edit_churn(self):
+ return max(self.edit_counts.values()) if self.edit_counts else 0
+
+ @property
+ def distinct_edit_files(self):
+ return len(self.edit_counts)
+
+ @property
+ def stagnation(self):
+ """Fraction of failing outputs that repeat an earlier identical failure (the
+ agent edited but the SAME failure came back = no progress). 0 when no fails."""
+ total = sum(self.fail_sigs.values())
+ return (self.repeated_fail_sigs / total) if total else 0.0
+
+ def update(self, tool_name, args, result_text, failed=None):
+ """Fold one completed tool call into the state. `failed` is what the agent reported
+ about the call -- True for a non-zero exit or a tool error, False for success, None when
+ it did not say -- and decides whether its output can be a failing one: a call known to
+ have succeeded is not, a content tool only when the tool itself failed, and otherwise
+ the output's own markers decide."""
+ self.turns += 1
+ args = args if isinstance(args, dict) else {}
+ tool_name = canon_tool(tool_name) # accept Copilot- or Claude-named tools
+ action = tool_name or "?"
+ if tool_name in _EDIT_TOOLS:
+ b = basename(args.get("path") or args.get("filePath")
+ or args.get("file_path") or "")
+ if b:
+ self.edit_order.append(b)
+ self.edit_counts[b] = self.edit_counts.get(b, 0) + 1
+ action = f"edit {b}"
+ cmd = args.get("command", "") if tool_name == "bash" else ""
+ if cmd:
+ short = re.sub(r"\s+", " ", cmd.strip())[:90]
+ action = f"$ {short}"
+ if TEST_RUN_RE.search(cmd):
+ self.test_runs += 1
+ elif tool_name in ("grep", "glob"):
+ action = f"{tool_name} {str(args.get('pattern') or '')[:40]}"
+ elif tool_name == "view":
+ action = f"view {basename(args.get('path') or args.get('file_path') or '')}"
+ fail = None
+ can_fail = failed is True if tool_name in _CONTENT_TOOLS else failed is not False
+ if result_text and can_fail and ERR_RE.search(result_text):
+ self.error_outputs += 1
+ sig = _failure_sig(result_text)
+ if sig:
+ fail = sig
+ if sig in self.fail_sigs:
+ self.repeated_fail_sigs += 1
+ self.fail_sigs[sig] = self.fail_sigs.get(sig, 0) + 1
+ # rolling leakage-safe action log (tool name / command / search / error-SIGNATURE
+ # only — no file contents, edit bodies, or view output), capped to recent window.
+ tag = f" [err#{fail}]" if fail else ""
+ self.recent.append(f"{self.turns:>3}: {action}{tag}")
+ if len(self.recent) > 40:
+ self.recent = self.recent[-40:]
+
+ def recent_digest(self, n=24, envelope=None):
+ """A compact, LEAKAGE-SAFE digest of the agent's RECENT PROCESS (last n actions)
+ for the LLM trace-judge: commands/searches/edited-basenames and error-SIGNATURE
+ markers only — never fix content, edit bodies, view output, or the issue text.
+ `envelope` (this repo's typical resolved-task length) is passed as CONTEXT so the
+ judge can recognize an abnormally-long trajectory as a likely dead-end."""
+ head = (f"turns={self.turns} edit_churn={self.edit_churn} "
+ f"distinct_edit_files={self.distinct_edit_files} "
+ f"error_outputs={self.error_outputs} test_runs={self.test_runs} "
+ f"repeated_identical_failures={self.repeated_fail_sigs} "
+ f"stagnation={self.stagnation:.2f}")
+ if envelope:
+ ratio = self.turns / envelope if envelope else 0
+ head += (f"\nrepo_context: tasks here usually RESOLVE within ~{envelope:.0f} "
+ f"turns; this trajectory is at {self.turns} turns = {ratio:.1f}x that "
+ f"typical length. Tests are still NOT green. A trajectory far past "
+ f"the typical resolved length with recurring failures is likely a "
+ f"dead-end loop, even if it touches many files.")
+ return head + "\nRecent actions (oldest->newest):\n" + "\n".join(self.recent[-n:])
+
+ def snapshot(self):
+ return {"turns": self.turns, "edit_churn": self.edit_churn,
+ "distinct_edit_files": self.distinct_edit_files,
+ "error_outputs": self.error_outputs, "test_runs": self.test_runs,
+ "stagnation": round(self.stagnation, 3),
+ "repeated_fail_sigs": self.repeated_fail_sigs}
+
+
+def state_from_trajectory(path, load_trajectory=None):
+ """The final `SpiralState` of a saved session log (`trace.load_trajectory` by default)."""
+ load_trajectory = load_trajectory or _load_trajectory
+ st = SpiralState()
+ for name, args, res, ok in load_trajectory(path):
+ st.update(name, args, res, failed=None if ok is None else not ok)
+ return st
diff --git a/tokeneconomizer/loopguard/turn.py b/tokeneconomizer/loopguard/turn.py
new file mode 100644
index 0000000..67abbb9
--- /dev/null
+++ b/tokeneconomizer/loopguard/turn.py
@@ -0,0 +1,291 @@
+"""`TurnGuard`: the loop guard for one prompt-turn, one tool call at a time.
+
+Each tool call arrives as a separate hook process, so the guard's state is on disk between
+calls (`to_dict` / `TurnGuard(data=...)`). Per call it folds the result into a `SpiralState`,
+checks the cumulative backstop, and asks `rules.assess_abort` (gate -> optional paid judge ->
+envelope fallback) whether the turn is stuck; the first stuck verdict is answered with a
+redirect, a later one with a stop. After a redirect the per-segment state starts afresh, which is
+the agent's fair window to recover.
+
+ * The unit is a PROMPT-TURN (one user prompt to the agent's stop): in interactive use a person
+ already splits work into short turns, and a whole session folded as one trajectory looks
+ stuck merely by being long.
+ * The redirect is delivered mid-turn, attached to the tool result.
+ * There is no grader, so the per-repository envelope learns from turns that ENDED GREEN: the
+ agent stopped on its own, the guard did not stop it, and no verification after its last edit
+ failed (`resolved_proxy`).
+"""
+import re
+import time
+
+from .rules import DEFAULT_THRESHOLDS, assess_abort, is_stuck, nudge_text
+from .shell_edits import fold_shell_edits, shell_edit_targets
+from .state import ERR_RE, SpiralState, canon_tool
+
+_SLOTS = SpiralState.__slots__
+
+# What counts as running the project's own checks, across ecosystems. Broader than
+# `state.TEST_RUN_RE` (the Python vocabulary the guard's thresholds were tuned on); used ONLY
+# for the ended-green proxy, never to change what `SpiralState` counts. A runner
+# is often named by path (`python tests/runtests.py`, `.venv/bin/pytest`, `./node_modules/.bin/
+# jest`): without the optional directories those turns showed no verification at all, so a turn
+# whose last test run failed still counted as ended green and fed the envelope.
+VERIFY_RE = re.compile(
+ r"(?i)(?:^|[\s;&|(])(?:~?/)?(?:[\w.\-]+/)*(?:pytest|py\.test|tox|nox|python\d?(?:\.\d+)?\s+-m\s+(?:pytest|unittest)|"
+ r"manage\.py\s+test|runtests(?:\.py)?|jest|vitest|mocha|ava|playwright\s+test|"
+ r"(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test|go\s+test|cargo\s+(?:test|nextest)|"
+ r"(?:mvn|mvnw|\./mvnw)\s+(?:\S+\s+)*test|(?:gradle|gradlew|\./gradlew)\s+(?:\S+\s+)*test|"
+ r"make\s+(?:test|check)|ctest|rspec|phpunit|dotnet\s+test|swift\s+test|mix\s+test|"
+ r"deno\s+test|bazel\s+test|(?:\./)?bin/test)(?![\w.\-/])")
+_EDIT = {"edit", "create"}
+
+
+def state_to_dict(st):
+ return {k: getattr(st, k) for k in _SLOTS}
+
+
+def state_from_dict(d):
+ st = SpiralState()
+ for k in _SLOTS:
+ if k in (d or {}):
+ setattr(st, k, d[k])
+ return st
+
+
+class TurnGuard:
+ """The loop guard for one prompt-turn, persisted between hook calls via `to_dict`."""
+
+ JUDGE_BASE_GAP = 5
+ JUDGE_MAX_GAP = 20
+ # A background verdict that never came back (its job died) stops blocking the next one
+ # after this long; a side call is capped at 180 s.
+ JUDGE_STALE_S = 300
+
+ def __init__(self, turn_key="", data=None):
+ d = data or {}
+ self.turn_key = d.get("turn_key", turn_key)
+ self.st = state_from_dict(d.get("st")) # this segment; reset after a nudge
+ self.whole = state_from_dict(d.get("whole")) # the whole turn; never reset
+ self.cum_turns = int(d.get("cum_turns", 0))
+ self.segment = int(d.get("segment", 0))
+ self.nudges_done = int(d.get("nudges_done", 0))
+ self.aborted = bool(d.get("aborted", False))
+ self.abort_delivered = bool(d.get("abort_delivered", False))
+ self.events = list(d.get("events", []))
+ self.judge_last = int(d.get("judge_last", -999))
+ self.judge_gap = int(d.get("judge_gap", self.JUDGE_BASE_GAP))
+ self.judge_calls = int(d.get("judge_calls", 0))
+ self.judge_tokens = float(d.get("judge_tokens", 0) or 0)
+ self.writer_tokens = float(d.get("writer_tokens", 0) or 0)
+ self.last_edit = int(d.get("last_edit", 0))
+ self.last_verify = int(d.get("last_verify", 0))
+ self.last_verify_failed = bool(d.get("last_verify_failed", False))
+ self.edits = int(d.get("edits", 0))
+ self.verifications = int(d.get("verifications", 0))
+ self.judge_pending = d.get("judge_pending") or None # {"id", "since", "segment"}
+ self.nudge_ready = d.get("nudge_ready") or None # a redirect the judge wrote
+
+ def to_dict(self):
+ return {"turn_key": self.turn_key, "st": state_to_dict(self.st),
+ "whole": state_to_dict(self.whole),
+ "cum_turns": self.cum_turns, "segment": self.segment,
+ "nudges_done": self.nudges_done, "aborted": self.aborted,
+ "abort_delivered": self.abort_delivered, "events": self.events[-20:],
+ "judge_last": self.judge_last, "judge_gap": self.judge_gap,
+ "judge_calls": self.judge_calls, "judge_tokens": self.judge_tokens,
+ "writer_tokens": self.writer_tokens, "last_edit": self.last_edit,
+ "last_verify": self.last_verify, "last_verify_failed": self.last_verify_failed,
+ "edits": self.edits, "verifications": self.verifications,
+ "judge_pending": self.judge_pending, "nudge_ready": self.nudge_ready}
+
+ # ---- outcome tracking for the ended-green proxy ----------------------------------
+ def _track(self, name, args, result, exit_code, shell_edits=()):
+ canon = canon_tool(name)
+ if canon in _EDIT:
+ self.last_edit = self.cum_turns
+ self.edits += 1
+ return
+ cmd = (args or {}).get("command") if canon == "bash" else None
+ verifies = isinstance(cmd, str) and bool(VERIFY_RE.search(cmd))
+ if shell_edits:
+ # `sed -i ... && pytest`: the edit comes first, so the run verifies it.
+ self.last_edit = self.cum_turns - (1 if verifies else 0)
+ self.edits += 1
+ if verifies:
+ self.last_verify = self.cum_turns
+ self.verifications += 1
+ if exit_code is not None:
+ self.last_verify_failed = exit_code != 0
+ else: # Claude Code reports no exit code
+ self.last_verify_failed = bool(ERR_RE.search(result or ""))
+
+ def resolved_proxy(self, stopped_normally=True):
+ """Did this turn END GREEN? The stand-in for the grader the envelope cannot have.
+
+ Green unless a verification after the last edit failed. Requiring a PASSING check after
+ the last edit was tried on a continuous Django stream and made the envelope longer, not
+ shorter: it drops the short turns that edit without running anything, while the long
+ failing turns end with the agent's own checks passing either way."""
+ if not stopped_normally or self.aborted or self.cum_turns == 0:
+ return False
+ return not (self.last_verify_failed and self.last_verify > self.last_edit)
+
+ # ---- what the judge is told -------------------------------------------------------
+ # The digest says "Tests are still NOT green." whenever it has an envelope: on a benchmark
+ # the guard only ever watches an unfinished task. Here the guard knows how the
+ # turn's last verification went, so the judge -- and the redirect it writes -- is told that.
+ _NOT_GREEN = "Tests are still NOT green."
+
+ def verification_state(self):
+ if not self.verifications:
+ return "No test or verification run has been seen in this turn."
+ state = "failed" if self.last_verify_failed else "passed"
+ since = " There have been edits since." if self.last_edit > self.last_verify else ""
+ return f"The last verification run {state}.{since}"
+
+ def live_digest(self, digest):
+ return (digest or "").replace(self._NOT_GREEN, self.verification_state())
+
+ # ---- the judge, rate-limited with backoff exactly as NudgeGuard._sampled_judge ----
+ def _backoff(self, v):
+ if v and v.get("stuck") is False:
+ self.judge_gap = min(self.JUDGE_MAX_GAP, self.judge_gap + self.JUDGE_BASE_GAP)
+ else:
+ self.judge_gap = self.JUDGE_BASE_GAP
+
+ def _sampled(self, judge):
+ def call(digest):
+ if self.st.turns - self.judge_last < self.judge_gap:
+ return None
+ self.judge_last = self.st.turns
+ self.judge_calls += 1
+ try:
+ v = judge(self.live_digest(digest))
+ except Exception:
+ v = None
+ if v:
+ self.judge_tokens += v.get("_tokens") or 0
+ self._backoff(v)
+ return v
+ return call
+
+ def _background(self, judge):
+ """`_sampled` for a judge that runs in the background (`plugin.judge.AsyncJudge`):
+ a verdict is taken whenever one has come back, a new job starts under the same rate
+ limit, and while one is out the judge answers nothing -- which `assess_abort` reads as
+ throttled, the same as a call the rate limit skipped."""
+ def call(digest):
+ found, v = judge.poll(self)
+ if found:
+ self.judge_pending = None
+ if v:
+ self.nudge_ready = (v.get("_nudge") or "").strip() or None
+ self._backoff(v)
+ return v or None
+ if self.judge_pending:
+ if time.time() - float(self.judge_pending.get("since") or 0) < self.JUDGE_STALE_S:
+ return None
+ self.judge_pending = None # its job never answered
+ if self.st.turns - self.judge_last < self.judge_gap:
+ return None
+ self.judge_last = self.st.turns
+ self.judge_calls += 1
+ job = judge.start(self, self.live_digest(digest))
+ if job:
+ self.judge_pending = {"id": job, "since": time.time(), "segment": self.segment}
+ return None
+ return call
+
+ # ---- one completed tool call ------------------------------------------------------
+ def fold(self, name, args, result, exit_code=None, *, envelope=None, thr=None,
+ judge=None, nudge_budget=1):
+ """Fold one call; return None, ("nudge", reason) or ("abort", reason).
+
+ The body is `NudgeGuard.monitor` for a single completed call."""
+ thr = thr or DEFAULT_THRESHOLDS
+ shell_edits = (shell_edit_targets((args or {}).get("command"))
+ if canon_tool(name) == "bash" else [])
+ failed = None if exit_code is None else exit_code != 0
+ self.st.update(name, args or {}, result or "", failed)
+ self.whole.update(name, args or {}, result or "", failed)
+ fold_shell_edits(self.st, shell_edits)
+ fold_shell_edits(self.whole, shell_edits)
+ self.cum_turns += 1
+ self._track(name, args, result, exit_code, shell_edits)
+ if self.aborted:
+ return None
+
+ backstop = thr.get("backstop_turns")
+ if backstop is None and envelope is not None:
+ backstop = envelope * thr["backstop_mult"]
+ if (backstop is not None and self.cum_turns >= backstop
+ and is_stuck(self.st, thr)):
+ # The ladder is nudge, THEN stop. On a benchmark the envelope was ~30 calls, so
+ # its 2.5x backstop lay well past the stuck rule's 20-call floor and the nudge came
+ # first. An interactive repository's envelope is ~4-10 calls: its backstop falls
+ # INSIDE that floor, so the moment a turn first counts as stuck the backstop has
+ # tripped too, and it would pre-empt every nudge. An unspent nudge goes first;
+ # after it, a fresh segment must be stuck again before the backstop stops it.
+ reason = f"cum-backstop:{self.cum_turns}>={backstop:.0f}t"
+ if self.nudges_done < nudge_budget:
+ return self._stop("nudge", reason, envelope)
+ return self._stop("abort", reason, envelope)
+
+ wired = None
+ if judge is not None:
+ wired = self._background(judge) if hasattr(judge, "poll") else self._sampled(judge)
+ abort, reason = assess_abort(self.st, envelope=envelope, judge=wired, thr=thr)
+ if not abort:
+ if (thr.get("nudge_on_ambiguous") and reason == "judge-ambiguous-spared"
+ and self.nudges_done < nudge_budget):
+ return self._stop("nudge", "ambiguous-past-envelope", envelope)
+ return None
+ if self.nudges_done < nudge_budget:
+ return self._stop("nudge", reason, envelope)
+ return self._stop("abort", reason, envelope)
+
+ def _stop(self, action, reason, envelope):
+ self.events.append({"segment": self.segment, "action": action,
+ "turn_in_segment": self.st.turns, "cum_turns": self.cum_turns,
+ "envelope": envelope, "reason": reason,
+ "snapshot": self.st.snapshot()})
+ if action == "abort":
+ self.aborted = True
+ return action, reason
+
+ def nudge_body(self, envelope=None, writer=None):
+ """The redirect text: the one a background judge already wrote with its verdict, else
+ an LLM-written one when a writer is wired, else the count template
+ (`nudge_text`), which mirrors only the agent's own actions."""
+ if self.nudge_ready:
+ text, self.nudge_ready = self.nudge_ready, None
+ return text
+ if writer is not None:
+ try:
+ out = writer(self.live_digest(self.st.recent_digest(envelope=envelope)))
+ except Exception:
+ out = None
+ if out:
+ self.writer_tokens += out.get("_tokens") or 0
+ text = (out.get("text") or "").strip()
+ if text:
+ return text
+ return nudge_text(self.st)
+
+ def after_nudge(self):
+ """Start the post-nudge segment with a fresh state: `NudgeGuard.continuation`'s reset,
+ which is the agent's fair re-assessment window."""
+ self.nudges_done += 1
+ self.segment += 1
+ self.st = SpiralState()
+ self.judge_last = -999
+ self.judge_gap = self.JUDGE_BASE_GAP
+ self.judge_pending = None # a verdict on the old segment is about the old one
+ self.nudge_ready = None
+
+ def summary(self, stopped_normally=True):
+ return {"turn_key": self.turn_key, "tool_calls": self.cum_turns,
+ "nudges": self.nudges_done, "aborted": self.aborted,
+ "resolved_proxy": self.resolved_proxy(stopped_normally),
+ "edits": self.edits, "verifications": self.verifications,
+ "judge_tokens": self.judge_tokens, "writer_tokens": self.writer_tokens}
diff --git a/tokeneconomizer/mechanisms/__init__.py b/tokeneconomizer/mechanisms/__init__.py
deleted file mode 100644
index d909ab0..0000000
--- a/tokeneconomizer/mechanisms/__init__.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""The three lifecycle mechanisms of the economizer, each acting at a different point in
-a task's lifecycle and independently switchable:
-
- * injection (mechanisms.injection.PrefixStage) -- before the task: inject a
- firing-gated, learned per-repo operating manual.
- * tooling (mechanisms.tooling.ToolingStage) -- at task construction: drop
- inapplicable tool schemas (generic evidence untooling; Codex-native
- capability untooling).
- * spiral (mechanisms.spiral.SpiralStage + -- in flight / at finalize: kill or
- mechanisms.codex_spiral) nudge a stuck rollout; Codex-native
- post-green finalize.
-
-All three read a normalized trajectory through the one trace seam (tokeneconomizer.trace)
-and charge their LLM overhead through the one ledger (tokeneconomizer.ledger).
-"""
-from .base import Stage
-from .injection import PrefixStage, Distiller
-from .tooling import ToolingStage
-from .spiral import SpiralStage
-from .codex_spiral import CodexSpiralPolicy, DEFAULT_POLICY
-
-__all__ = ["Stage", "PrefixStage", "Distiller", "ToolingStage", "SpiralStage",
- "CodexSpiralPolicy", "DEFAULT_POLICY"]
diff --git a/tokeneconomizer/mechanisms/base.py b/tokeneconomizer/mechanisms/base.py
deleted file mode 100644
index 62da1cd..0000000
--- a/tokeneconomizer/mechanisms/base.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""Stage protocol: the lifecycle hooks the Economizer facade calls around one task.
-
-Each mechanism implements only the hooks it needs; unused hooks keep the no-op default.
-The hooks fire in this order per task (see facade.Economizer):
-
- before_task(task, injected) -> str # pre-rollout: may augment injected prefix
- build_tools(task) -> list|None # construction: tool-exclusion set
- run_kwargs(task) -> dict # construction: kwargs for the agent runner
- after_task(task, row, run_dir_path, srow) # post-rollout: update state + telemetry
- -> opt_tokens (int/float; 0 for stages with no overhead)
-
-Hooks receive the srow (stream row dict) so a mechanism can attach its own telemetry keys.
-"""
-
-
-class Stage:
- name = "base"
-
- def before_task(self, task, injected):
- return injected
-
- def build_tools(self, task):
- return None
-
- def run_kwargs(self, task):
- return {}
-
- def after_task(self, task, row, run_dir_path, srow):
- return 0
diff --git a/tokeneconomizer/mechanisms/codex_injection.py b/tokeneconomizer/mechanisms/codex_injection.py
deleted file mode 100644
index 3a457cf..0000000
--- a/tokeneconomizer/mechanisms/codex_injection.py
+++ /dev/null
@@ -1,28 +0,0 @@
-"""The Codex lane's injection defaults -- a thin layer over the shared `envfacts` module.
-
-The detector families, the environment-fact distiller and the vocabulary plug-in live in
-`mechanisms/envfacts.py` and are shared by every lane: replayed over the stored Claude Code
-and Copilot streams they form the same kinds of facts (and abstain on the one stream whose
-shell was activated), so nothing about them is Codex-specific. What IS specific to the Codex
-lane is recorded here rather than scattered:
-
- * the default profile is `envfacts+distiller` (2026-09-12): the LLM-free layer with the
- paid proposer on top at cadence 10. It was `envfacts` while the harness left the project
- environment inactive, when the free layer's interpreter fact formed. The harness now
- activates the environment, the interpreter fact no longer forms on a post-fix baseline, and the proposer
- is what remains to find repository facts. Its spend lands in `optimizer_tokens` like anywhere else; the
- LLM-free ablation is the arm `codex-inject-envfacts`;
- * Codex's `command_execution` items carry exact exit codes, which the shared observation
- layer reads directly through `trace.load_trajectory` (Claude and Copilot supply an error
- flag and the outcome is parsed from text);
- * Codex has a developer-role instruction channel (`developer_instructions` in the per-task
- `config.toml`, accepted by codex-cli 0.153.1) that could carry the block instead of the
- prompt prefix. Not wired: every lane injects through `build_prompt` today.
-
-Every public name of `envfacts` is re-exported so existing imports keep working.
-"""
-from .envfacts import * # noqa: F401,F403
-from .envfacts import _is_bare, _PASSTHROUGH, _root # noqa: F401 (offline analyses)
-
-CODEX_DEFAULT_PROFILE = "envfacts+distiller"
-CODEX_FREE_PROFILE = "envfacts" # the LLM-free ablation (arm codex-inject-envfacts)
diff --git a/tokeneconomizer/mechanisms/envfacts.py b/tokeneconomizer/mechanisms/envfacts.py
deleted file mode 100644
index 5b84a32..0000000
--- a/tokeneconomizer/mechanisms/envfacts.py
+++ /dev/null
@@ -1,809 +0,0 @@
-"""Environment facts: the LLM-free injection layer shared by every lane.
-
-WHAT IT DOES. As a repository's task stream runs, this controller reads each finished
-rollout through the one trace seam and looks for RECURRING SHAPES OF EVIDENCE that an
-agent re-discovers the same environment fact by failing at it, task after task. When a
-shape recurs across drifted tasks it becomes a one-line, declarative fact that is injected
-before the next task through the instruction channel (the prompt prefix on every lane). It
-runs alone (profile `envfacts`, the Codex lane's default) or underneath the paid proposer
-(profile `envfacts+distiller`), where its claims are handed to the proposer as
-already-stated so the paid budget is not spent rediscovering them.
-
-THE DESIGN RULE. The detectors describe shapes, never a harness: nothing here names a
-path, an environment manager, a repository or a benchmark. Every specific string in a
-rendered fact -- an interpreter path, a runner form, a refused host -- is a PARAMETER learned
-from the traces. The same code must form the interpreter fact on a harness whose shell is
-not activated, form nothing on one that is, and form the "history ends at HEAD" fact only
-where the probes really return nothing. The WORDS that name intents (which executables are
-interpreters, runners, package tools, fetchers, probes) are a `Vocabulary` the domain
-adapter supplies, so the same families read a Python/git repository and a Node/npm one.
-
-THE FAMILIES.
-
- FormRepair in one task, invocation form A of an intent (run the interpreter, run the
- tests, use the package tool) fails with an infrastructure error, and a later
- form B of the same intent succeeds. Fact: "`A ...` fails here with <error>;
- `B ...` works." Retires when a bare form runs the test runner successfully.
- Boundary every call of an operation class (fetching from a host) fails with one
- environmental error class and none ever succeeds. Fact: "Connections to
- <hosts> are refused here." Retires when a fetch to a listed host succeeds.
- EmptyProbe discovery probes of one kind (VCS refs beyond the checkout) return nothing in
- every task where they run. Fact: "no remote, no refs beyond HEAD". Retires --
- hard -- the moment a probe returns something, so it never forms on an image
- whose history continues past the base commit.
-
-LIFECYCLE. The validated `_Fact` state machine from `mechanisms/injection.py`, unchanged:
-CANDIDATE -> ACTIVE after K_PROMOTE confirmations on drifted tasks, recency-weighted score
-with asymmetric contradiction, and a FIRING GATE so a fact is injected only while the waste
-it prevents keeps occurring (or, once injected, keeps being prevented).
-
-COST HONESTY. No LLM is involved anywhere: `opt_tokens` is exactly 0. The rendered block is
-prompt bytes, priced by the ledger like the rest of the prompt (written once at cache-write,
-re-read every step); it is capped at MAX_TOKENS and MAX_FACTS, and a lint refuses any fact
-that reads as completion or verification advice -- the failure mode of the earlier Codex
-injection variants, which lost resolves with "you are done once the tests pass" hints.
-
-Stdlib only; agent-agnostic through `trace.load_trajectory` (Codex exit codes, Claude and
-Copilot error flags all reduce to the same (form, outcome) observations).
-"""
-import json
-import os
-import re
-
-from ..trace import strip_rtk_prefix
-from collections import Counter
-from dataclasses import dataclass
-
-from .injection import _Fact, edited_pyfiles
-from ..trace import load_trajectory
-
-STATE_SUBDIR = "envfacts_state"
-MAX_FACTS = 4
-MAX_TOKENS = 150 # ~4 chars per token; the whole block, header included
-HEADER = "# environment facts learned from earlier tasks in this checkout"
-
-# --------------------------------------------------------------------------------------
-# vocabulary -- the domain-supplied words that name intents (never harness constants)
-# --------------------------------------------------------------------------------------
-@dataclass(frozen=True)
-class Vocabulary:
- """What the families recognise as an interpreter, a test runner, a package tool, a
- fetcher, an environment probe. A domain adapter supplies one (`env_vocabulary()`); the
- families themselves are the same for every vocabulary."""
- name: str
- interpreters: frozenset # executables that run the language
- canonical_interpreter: str # how a shebang-run script is spelled as a form
- runner_heads: frozenset # bare test-runner executables
- runner_scripts: tuple # scripts that ARE the runner when an interpreter runs them
- runner_modules: frozenset # `<interpreter> -m <module>` runners
- package_tools: frozenset
- fetch_heads: frozenset = frozenset({"curl", "wget"})
- env_probe_heads: frozenset = frozenset({"which", "command", "type", "whereis"})
-
-
-PYTHON_GIT = Vocabulary(
- name="python-git",
- interpreters=frozenset({"python", "python2", "python3", "pypy", "pypy3"}),
- canonical_interpreter="python",
- runner_heads=frozenset({"pytest", "py.test", "tox", "nox", "nosetests", "trial"}),
- runner_scripts=("runtests.py", "bin/test", "bin/doctest", "manage.py"),
- runner_modules=frozenset({"pytest", "unittest", "nose", "django", "tox", "nox"}),
- package_tools=frozenset({"pip", "pip3", "conda", "mamba", "poetry", "pipenv", "uv",
- "apt", "apt-get"}),
-)
-
-NODE_WEB = Vocabulary(
- name="node-web",
- interpreters=frozenset({"node", "nodejs", "deno", "bun", "tsx", "ts-node"}),
- canonical_interpreter="node",
- runner_heads=frozenset({"jest", "vitest", "mocha", "playwright", "cypress", "ava",
- "karma"}),
- runner_scripts=(),
- runner_modules=frozenset(),
- package_tools=frozenset({"npm", "yarn", "pnpm", "corepack", "apt", "apt-get"}),
-)
-
-DEFAULT_VOCAB = PYTHON_GIT
-# Module-level aliases of the default vocabulary, kept for the offline analyses.
-INTERPRETERS = PYTHON_GIT.interpreters
-RUNNER_HEADS = PYTHON_GIT.runner_heads
-RUNNER_SCRIPTS = PYTHON_GIT.runner_scripts
-RUNNER_MODULES = PYTHON_GIT.runner_modules
-PACKAGE_TOOLS = PYTHON_GIT.package_tools
-FETCH_HEADS = PYTHON_GIT.fetch_heads
-GIT_FETCH_SUBS = frozenset({"fetch", "clone", "pull", "ls-remote"})
-GIT_PROBE_SUBS = frozenset({"remote", "branch", "tag", "fsck", "stash", "show-ref",
- "for-each-ref"})
-ENV_PROBE_HEADS = PYTHON_GIT.env_probe_heads
-PREFIX_HEADS = ("sudo", "env", "time", "exec", "nice", "nohup", "timeout")
-_PASSTHROUGH = frozenset({"cd", "echo", "head", "tail", "cat", "sort", "uniq", "tee", "true",
- "printf", "less", "more"})
-
-_ACTIVATE_RE = re.compile(r"^(?:source|\.)\s+\S*activate\s+([\w.-]+)\s*$")
-_CONDA_ACTIVATE_RE = re.compile(r"^(?:conda|mamba)\s+activate\s+([\w.-]+)\s*$")
-_CONDA_RUN_RE = re.compile(r"^(?:conda|mamba)\s+run\s+(?:--no-capture-output\s+|--live-stream\s+)*"
- r"(?:-n|--name)\s+([\w.-]+)\s+")
-_TOOL_RUN_RE = re.compile(r"^(poetry|pipenv|uv|npx|bundle|yarn|pnpm)\s+(?:run|exec)\s+")
-_NPX_RE = re.compile(r"^npx\s+(?:(?:--yes|-y|--no-install|--no)\s+)*")
-_INTERP_VERSIONED_RE = re.compile(r"^(?:python|node)\d(?:\.\d+)?$")
-_ENV_ASSIGN_RE = re.compile(r"^(?:[A-Za-z_][A-Za-z0-9_]*=(?:\"[^\"]*\"|'[^']*'|\S+)\s+)+")
-_WRAP_RE = re.compile(r"^/bin/(?:ba)?sh\s+-l?c\s+(.*)$", re.S)
-_HEREDOC_RE = re.compile(r"<<-?\s*['\"]?(\w+)['\"]?[^\n]*\n.*?\n\s*\1\b", re.S)
-_URL_HOST_RE = re.compile(r"https?://([^/\s'\"`]+)")
-
-# Error classes an ENVIRONMENT produces (as opposed to the code under test). Order matters:
-# the first match names the class.
-ERROR_CLASSES = (
- ("module_missing", re.compile(r"ModuleNotFoundError|No module named|Cannot find module|"
- r"ERR_MODULE_NOT_FOUND", re.I)),
- ("command_missing", re.compile(r"command not found|: not found\b|is not recognized", re.I)),
- ("permission_denied", re.compile(r"Permission denied|EACCES", re.I)),
- ("usage_error", re.compile(r"(?m)^usage:|unrecognized arguments|no such option|"
- r"error: argument|unknown option", re.I)),
- ("connection_refused", re.compile(r"Connection refused|Failed to connect to|"
- r"couldn't connect to|Could not connect|ECONNREFUSED", re.I)),
- ("name_resolution", re.compile(r"Could not resolve host|Temporary failure in name "
- r"resolution|Name or service not known|getaddrinfo|"
- r"nodename nor servname|ENOTFOUND", re.I)),
- ("unreachable", re.compile(r"Network is unreachable|No route to host|Connection timed out|"
- r"Operation timed out|timed out after|ETIMEDOUT", re.I)),
-)
-NETWORK_ERRORS = frozenset({"connection_refused", "name_resolution", "unreachable"})
-FORM_ERRORS = frozenset({"module_missing", "command_missing", "usage_error",
- "permission_denied"})
-
-# What "the probe returned something" looks like, per VCS probe kind. Deliberately narrow
-# patterns so the output of an unrelated segment in a compound command cannot masquerade
-# as a hit.
-_PROBE_HIT = {
- "remote": re.compile(r"(?m)^\S+\s+\S+\s+\((?:fetch|push)\)\s*$"),
- "branch": re.compile(r"(?m)^\s*remotes/\S+"),
- "tag": re.compile(r"(?m)^v?\d+(?:\.\d+)+(?:[a-z]+\d*|\.post\d+|-\S+)?\s*$"),
- "fsck": re.compile(r"(?m)^(?:unreachable|dangling)\s+(?:commit|tree|blob|tag)\s+[0-9a-f]{7,}"),
- "stash": re.compile(r"(?m)^stash@\{\d+\}"),
- "refs": re.compile(r"(?m)^[0-9a-f]{7,}\s+refs/"),
-}
-
-# Words that would turn a fact into completion or verification advice.
-_LINT_RE = re.compile(r"\b(skip|no need|don'?t|do not|stop|done|completed?|finish(?:ed)?|"
- r"verify|verification|instead of (?:running|testing))\b", re.I)
-
-_ERROR_PHRASE = {
- "module_missing": "ModuleNotFoundError",
- "command_missing": "command not found",
- "usage_error": "a usage error",
- "permission_denied": "permission denied",
-}
-
-
-# --------------------------------------------------------------------------------------
-# observations
-# --------------------------------------------------------------------------------------
-def unwrap(cmd):
- """Strip an agent's `/bin/bash -lc "<cmd>"` wrapper, if present."""
- cmd = cmd or ""
- m = _WRAP_RE.match(cmd.strip())
- if not m:
- return cmd
- inner = m.group(1).strip()
- if len(inner) >= 2 and inner[0] == inner[-1] and inner[0] in "\"'":
- q = inner[0]
- inner = inner[1:-1]
- if q == '"':
- inner = inner.replace('\\"', '"').replace("\\$", "$").replace("\\\\", "\\")
- return inner
-
-
-def segments(cmd):
- """Split a shell command into simple segments on && || ; | and newlines, outside quotes.
- Heredoc bodies are elided first so their contents are never mistaken for commands."""
- cmd = _HEREDOC_RE.sub(lambda m: m.group(0).split("\n", 1)[0] + " <heredoc>", cmd or "")
- out, buf, q, i = [], [], None, 0
- while i < len(cmd):
- c = cmd[i]
- if q:
- buf.append(c)
- if c == q:
- q = None
- elif c == "\\" and i + 1 < len(cmd):
- buf.append(cmd[i + 1]); i += 1
- elif c in "\"'":
- q = c; buf.append(c)
- elif c == "\n" or c == ";" or c == "|" or (c == "&" and cmd[i:i + 2] == "&&"):
- out.append("".join(buf)); buf = []
- if cmd[i:i + 2] in ("&&", "||"):
- i += 1
- else:
- buf.append(c)
- i += 1
- out.append("".join(buf))
- return [s.strip().strip("()").strip() for s in out if s.strip().strip("()").strip()]
-
-
-def _tokens(seg):
- return seg.split()
-
-
-class Observation:
- """One classified command segment."""
- __slots__ = ("call", "intent", "form", "head", "prefix", "hosts", "probe", "outcome",
- "segment")
-
- def __init__(self, call, intent, form, head, prefix, segment, hosts=(), probe=None):
- self.call, self.intent, self.form, self.head, self.prefix = call, intent, form, head, prefix
- self.segment, self.hosts, self.probe, self.outcome = segment, tuple(hosts), probe, None
-
- def __repr__(self):
- return f"Obs({self.intent},{self.form!r},{self.outcome})"
-
-
-def classify_command(cmd, call_index=0, vocab=None):
- """Observations for one shell command (possibly compound). Activation prefixes carry
- across the segments of one command, which is how `source activate X && python ...`
- becomes a single form. `vocab` names the domain's intents (default Python/git)."""
- vocab = vocab or DEFAULT_VOCAB
- obs = []
- carried = ""
- for seg in segments(unwrap(cmd)):
- # Transparent wrappers first: `K=V rtk pytest`, `rtk K=V pytest` and `rtk proxy pytest`
- # are all a pytest run. rtk's Codex mode puts that prefix on every command the agent
- # types (trace.strip_rtk_prefix), and a first-token vocabulary that did not remove it
- # would form no fact at all on the very arm that stacks injection on rtk.
- seg = _ENV_ASSIGN_RE.sub("", seg).strip()
- seg = _ENV_ASSIGN_RE.sub("", strip_rtk_prefix(seg)).strip()
- if not seg:
- continue
- m = _ACTIVATE_RE.match(seg) or _CONDA_ACTIVATE_RE.match(seg)
- if m:
- carried = f"{seg.split()[0] if seg.startswith(('conda', 'mamba')) else 'source'} activate {m.group(1)} &&"
- if carried.startswith("conda") or carried.startswith("mamba"):
- carried = f"conda activate {m.group(1)} &&"
- continue
- prefix = carried
- body = seg
- m = _CONDA_RUN_RE.match(body)
- if m:
- prefix = (prefix + " " if prefix else "") + f"conda run -n {m.group(1)}"
- body = body[m.end():]
- m = _TOOL_RUN_RE.match(body)
- if m:
- prefix = (prefix + " " if prefix else "") + f"{m.group(1)} run"
- body = body[m.end():]
- else:
- m = _NPX_RE.match(body)
- if m and m.end() > 0:
- prefix = (prefix + " " if prefix else "") + "npx"
- body = body[m.end():]
- toks = _tokens(body)
- while toks and toks[0] in PREFIX_HEADS:
- toks = toks[1:] if toks[0] != "timeout" else toks[2:]
- if not toks:
- continue
- head = toks[0]
- base = head.rsplit("/", 1)[-1]
- rest = toks[1:]
- o = _classify(head, base, rest, body, prefix, seg, call_index, vocab)
- if o is not None:
- obs.append(o)
- return obs
-
-
-def _runner_script(rest, vocab):
- for t in rest:
- if t.startswith("-"):
- continue
- for s in vocab.runner_scripts:
- if t == s or t.endswith("/" + s) or t.endswith(s):
- return t.lstrip("./") if t.startswith("./") else t
- return None
- return None
-
-
-def _classify(head, base, rest, body, prefix, seg, call, vocab):
- def form(expr):
- return (prefix + " " + expr).strip() if prefix else expr
-
- if base in vocab.interpreters or _INTERP_VERSIONED_RE.match(base):
- if rest and all(t in ("--version", "-V", "-VV", "-v") for t in rest):
- return Observation(call, "probe_env", form(head), head, prefix, seg)
- if "-m" in rest:
- mod = rest[rest.index("-m") + 1] if rest.index("-m") + 1 < len(rest) else ""
- if mod in vocab.runner_modules:
- return Observation(call, "run_tests", form(f"{head} -m {mod}"), head, prefix, seg)
- script = _runner_script(rest, vocab)
- if script and (script != "manage.py" or "test" in rest):
- return Observation(call, "run_tests", form(f"{head} {script}"), head, prefix, seg)
- return Observation(call, "run_interpreter", form(head), head, prefix, seg)
- if base in vocab.runner_heads:
- return Observation(call, "run_tests", form(head), head, prefix, seg)
- for s in vocab.runner_scripts:
- if head == s or head.endswith("/" + s) or head == "./" + s:
- if s == "manage.py" and "test" not in rest:
- break
- # A script run through its shebang is the interpreter running it; spell the
- # form that way so `./tests/runtests.py` and `python tests/runtests.py` pool.
- return Observation(call, "run_tests",
- form(f"{vocab.canonical_interpreter} " + head.lstrip("./")),
- head, prefix, seg)
- if base in ("make", "npm", "yarn", "pnpm", "cargo", "go") and rest and rest[0] == "test":
- return Observation(call, "run_tests", form(f"{base} test"), head, prefix, seg)
- if base in vocab.env_probe_heads:
- return Observation(call, "probe_env", form(base), head, prefix, seg)
- if base in vocab.fetch_heads:
- return Observation(call, "fetch_remote", form(base), head, prefix, seg,
- hosts=_URL_HOST_RE.findall(body))
- if base == "git" and rest:
- sub = rest[0]
- if sub in GIT_FETCH_SUBS:
- return Observation(call, "fetch_remote", form(f"git {sub}"), head, prefix, seg,
- hosts=_URL_HOST_RE.findall(body))
- if sub in GIT_PROBE_SUBS:
- kind = _probe_kind(sub, rest[1:])
- if kind:
- return Observation(call, "probe_vcs_refs", form(f"git {sub}"), head, prefix,
- seg, probe=kind)
- return None
- if base in vocab.package_tools:
- if base.startswith(("pip", "npm", "yarn", "pnpm")) and rest and rest[0] in (
- "install", "download", "add", "ci"):
- hosts = _URL_HOST_RE.findall(body)
- return Observation(call, "fetch_remote", form(f"{base} {rest[0]}"), head, prefix,
- seg, hosts=hosts)
- return Observation(call, "package_tool", form(base), head, prefix, seg)
- return None
-
-
-def _probe_kind(sub, args):
- a = set(args)
- if sub == "remote":
- return "remote"
- if sub == "branch" and a & {"-a", "-r", "--all", "--remotes", "-ar", "-ra"}:
- return "branch"
- if sub == "tag" and "--contains" in a: # plain `git tag` lists PAST tags too
- return "tag"
- if sub == "fsck":
- return "fsck"
- if sub == "stash" and args[:1] == ["list"]:
- return "stash"
- if sub in ("show-ref", "for-each-ref"):
- return "refs"
- return None
-
-
-def error_class(output):
- for name, rx in ERROR_CLASSES:
- if rx.search(output or ""):
- return name
- return None
-
-
-def _exit_code_hint(output):
- m = re.search(r"(?i)\bexit code[:=\s]+(\d+)", output or "")
- return int(m.group(1)) if m else None
-
-
-def observe_task(transcript_path, vocab=None):
- """Per-task digest: observations with outcomes, the edited files, the call count.
-
- Outcome attribution inside a compound command is heuristic and conservative: an
- infrastructure error is attributed to the segment whose executable the error names, else
- to the last relevant segment; a call that succeeded marks every relevant segment as
- having run; a failed call with no infrastructure error marks only the first relevant
- segment as having run and leaves the others unknown (an `&&` chain may not have reached
- them)."""
- calls = load_trajectory(transcript_path)
- obs_all = []
- triples = []
- for idx, (name, args, out, ok) in enumerate(calls):
- tool = (name or "").lower()
- triples.append((tool, args if isinstance(args, dict) else {}, out or ""))
- if tool not in ("shell", "bash", "stop_bash"):
- continue
- cmd = (args.get("command") or args.get("cmd") or "") if isinstance(args, dict) else ""
- out = out or ""
- obs = classify_command(cmd, idx, vocab)
- if not obs:
- continue
- # Pass-through segments (a leading `cd`, a trailing `| head`, an `echo ---`
- # separator) neither add evidence nor pollute the output, so they do not break a
- # call's homogeneity; filters that rewrite content (grep, sed, awk, wc) do.
- n_seg = sum(1 for sg in segments(unwrap(cmd))
- if (sg.split() or [""])[0].rsplit("/", 1)[-1] not in _PASSTHROUGH)
- homogeneous = n_seg == len(obs) and len({o.intent for o in obs}) == 1
- hint = _exit_code_hint(out)
- success = bool(ok) if hint is None else (hint == 0)
- err = error_class(out)
- if err in FORM_ERRORS or err in NETWORK_ERRORS:
- targets = [o for o in obs if o.intent in ("run_interpreter", "run_tests",
- "package_tool", "fetch_remote")]
- named = [o for o in targets
- if (o.head and o.head in out) or (o.head and o.head.rsplit("/", 1)[-1] in
- _error_line(out, err))]
- if err in NETWORK_ERRORS:
- named = [o for o in targets if o.intent == "fetch_remote"
- and (not o.hosts or any(h in out for h in o.hosts))] or \
- [o for o in targets if o.intent == "fetch_remote"]
- chosen = named or (targets[-1:] if not success else [])
- for o in chosen:
- o.outcome = err
- if success:
- for o in obs:
- if o.outcome is None:
- o.outcome = "ran"
- elif success:
- for o in obs:
- o.outcome = "ran"
- else:
- first = True
- for o in obs:
- if o.intent in ("run_interpreter", "run_tests", "package_tool", "fetch_remote"):
- o.outcome = "ran" if first else None
- first = False
- else:
- o.outcome = "ran" if o.intent != "probe_vcs_refs" else None
- for o in obs:
- if o.intent == "probe_vcs_refs":
- # Judged only when every segment of the call is a probe: another segment's
- # output (a `git describe`, a `sed`) would otherwise be read as the probe's.
- if not homogeneous:
- o.outcome = None
- else:
- o.outcome = "hit" if _PROBE_HIT[o.probe].search(out) else (
- "empty" if success else None)
- if o.intent == "fetch_remote" and o.outcome == "ran":
- # Reachability needs a homogeneous call that exited 0 with real output and no
- # network error; a compound command's exit code and output belong to its
- # last segment, not to the fetch.
- if not homogeneous or not success or not out.strip() or err in NETWORK_ERRORS:
- o.outcome = None
- obs_all.extend(obs)
- return {"obs": obs_all, "edited": sorted(edited_pyfiles(triples)), "n_calls": len(calls)}
-
-
-def _error_line(out, err):
- rx = dict(ERROR_CLASSES)[err]
- m = rx.search(out or "")
- if not m:
- return ""
- start = (out or "").rfind("\n", 0, m.start()) + 1
- end = (out or "").find("\n", m.end())
- return (out or "")[start:end if end >= 0 else None]
-
-
-def _is_bare(form):
- """A form with no activation prefix and no explicit path is 'bare'."""
- head = form.split()[0] if form else ""
- return "/" not in head and " activate " not in form and " run " not in form and \
- not form.startswith(("conda run", "poetry run", "pipenv run", "uv run", "npx "))
-
-
-# --------------------------------------------------------------------------------------
-# facts
-# --------------------------------------------------------------------------------------
-class EnvFact:
- def __init__(self, fid, family, high, params=None):
- self.id = fid
- self.family = family
- self.params = params or {}
- self.life = _Fact(fid, high)
-
- # ---- lifecycle passthrough ----
- @property
- def state(self):
- return self.life.state
-
- def injectable(self):
- return self.life.injectable()
-
- def firing_rate(self):
- return self.life.firing_rate()
-
- # ---- rendering ----
- def claim(self):
- p = self.params
- if self.family == "form_repair":
- b = self._best("b_counts")
- e = self._best("error_counts") or "module_missing"
- return f"`{p['a']} …` fails here with {_ERROR_PHRASE.get(e, e)}; `{b} …` works."
- if self.family == "boundary":
- hosts = [h for h, _ in Counter(p.get("hosts", {})).most_common(3)]
- return ("Outbound connections to " + _join(hosts) +
- " are refused here; nothing can be fetched from them.")
- if self.family == "empty_probe":
- return ("This checkout has no git remote and no branches, tags or unreachable "
- "objects beyond HEAD; its history ends at the checked-out commit.")
- return ""
-
- def _best(self, key):
- c = self.params.get(key) or {}
- return max(c.items(), key=lambda kv: kv[1])[0] if c else None
-
- def to_dict(self):
- return {"id": self.id, "family": self.family, "params": self.params,
- "life": self.life.to_dict()}
-
- @classmethod
- def from_dict(cls, d):
- f = cls(d["id"], d["family"], d["life"].get("high", False), d.get("params") or {})
- f.life = _Fact.from_dict(d["life"])
- return f
-
-
-CONTRADICT_STREAK = 2 # FormRepair: consecutive contradicted tasks before one counts
-
-
-def fold(fact, now, verdict, fired, exercised, files):
- """Fold one task's verdict into a fact's lifecycle.
-
- Two adjustments to the shared state machine. A high-stakes CANDIDATE that is contradicted
- retires at once (`_Fact` hard-kills only ACTIVE facts): an image whose history continues
- past HEAD does not become clean by being probed again. And a FormRepair contradiction --
- the bare form ran the test runner -- only counts after CONTRADICT_STREAK consecutive
- exercised tasks said so: a single task whose tests happened to need none of the missing
- packages is not a fixed environment, and the asymmetric contradiction weight would
- otherwise retire a fact confirmed thirty times over."""
- if fact.family == "form_repair" and exercised:
- streak = fact.params.get("contra_streak", 0)
- streak = streak + 1 if verdict == "contradict" else 0
- fact.params["contra_streak"] = streak
- if verdict == "contradict" and streak < CONTRADICT_STREAK:
- verdict = None
- fact.life.update(now, verdict, fired, exercised, files)
- if verdict == "contradict" and fact.life.high and fact.life.state == "CANDIDATE":
- fact.life.state, fact.life.retired_at = "RETIRED", now
-
-
-def _root(form):
- """The part of a working form that carries the environment: its activation prefix, or
- the directory of its explicit path."""
- if " && " in form:
- return form.split(" && ", 1)[0]
- if form.startswith(("conda run", "poetry run", "pipenv run", "uv run", "npx")):
- return " ".join(form.split()[:3])
- head = form.split()[0] if form else ""
- return head.rsplit("/", 1)[0] if "/" in head else head
-
-
-def _join(items):
- items = list(items)
- if not items:
- return "the hosts it tried"
- if len(items) == 1:
- return items[0]
- return ", ".join(items[:-1]) + " and " + items[-1]
-
-
-def lint_ok(text):
- return not _LINT_RE.search(text or "")
-
-
-# --------------------------------------------------------------------------------------
-# the distiller
-# --------------------------------------------------------------------------------------
-class EnvFactsDistiller:
- """Learns and injects environment facts over a repository's task stream.
-
- Interface parity with `injection.Distiller`, so `PrefixStage` drives both the same way:
- d = EnvFactsDistiller(repo, vocab=...) # fresh, or .load(repo, root, vocab=...)
- prefix = d.render() # block for the NEXT task ("" if none)
- d.update(transcript_path, iid=..., resolved=...)
- d.save(root)
- `runner`/`model` are accepted and ignored: nothing here is paid. `vocab` is the domain's
- `Vocabulary` (default Python/git); `injectable_claims()` is what a paid proposer stacked
- on top is told not to restate. `max_facts` / `max_tokens` cap the rendered block
- (default MAX_FACTS / MAX_TOKENS).
- """
- def __init__(self, repo, runner=None, model="agent", vocab=None, max_facts=None,
- max_tokens=None):
- self.max_facts = int(max_facts or MAX_FACTS)
- self.max_tokens = int(max_tokens or MAX_TOKENS)
- self.repo = repo
- self.vocab = vocab or DEFAULT_VOCAB
- self.now = 0
- self.facts = {} # id -> EnvFact
- self.opt_tokens = 0.0 # invariant: LLM-free
- self.last_injected = set() # fact ids rendered for the task now running
- self.last_digest = None # the most recent per-task verdicts (telemetry)
-
- # ---- render --------------------------------------------------------------------
- def render(self, task=None):
- chosen = self._select()
- self.last_injected = {f.id for f in chosen}
- if not chosen:
- return ""
- lines = [HEADER] + [f"- {t}" for t in self._merged_lines(chosen)]
- return "\n".join(lines) + "\n"
-
- def injectable_claims(self):
- """The claims that would be injected now, one string each (no header)."""
- return [f.claim() for f in self._select()]
-
- def _select(self):
- cands = [f for f in self.facts.values() if f.injectable() and lint_ok(f.claim())]
- prio = {"form_repair": 0, "empty_probe": 1, "boundary": 2}
- cands.sort(key=lambda f: (prio.get(f.family, 9),
- 0 if f.params.get("intent") == "run_interpreter" else 1,
- -f.firing_rate()))
- chosen = []
- for f in cands:
- trial = chosen + [f]
- if len(trial) > self.max_facts:
- break
- text = HEADER + "\n" + "\n".join(f"- {t}" for t in self._merged_lines(trial))
- if len(text) > self.max_tokens * 4:
- continue
- chosen = trial
- return chosen
-
- def _merged_lines(self, facts):
- """FormRepair facts whose working forms share a root (the same activation prefix
- or the same directory) collapse into one line: they are one environment fact."""
- lines, groups = [], {}
- for f in facts:
- if f.family == "form_repair":
- groups.setdefault(_root(f._best("b_counts") or ""), []).append(f)
- else:
- lines.append(f.claim())
- for _root_key, fs in groups.items():
- if len(fs) == 1:
- lines.insert(0, fs[0].claim())
- continue
- a_forms = _join([f"`{f.params['a']} …`" for f in fs])
- errs = sorted({_ERROR_PHRASE.get(f._best("error_counts") or "", "") for f in fs}
- - {""})
- b_forms = _join(sorted({f"`{f._best('b_counts')} …`" for f in fs}))
- lines.insert(0, f"{a_forms} fail here ({', '.join(errs) or 'environment error'}); "
- f"{b_forms} work.")
- return lines
-
- # ---- update --------------------------------------------------------------------
- def update(self, transcript_path, iid="", resolved=None, edited=None):
- try:
- digest = observe_task(transcript_path, self.vocab)
- except Exception:
- self.now += 1
- self.last_injected = set()
- return
- obs = digest["obs"]
- files = set(digest["edited"]) if edited is None else set(edited)
- injected = set(self.last_injected)
- verdicts = {}
-
- # ---- FormRepair: discover candidates, then fold every fact ----
- by_intent = {}
- for o in obs:
- by_intent.setdefault(o.intent, []).append(o)
- for intent in ("run_interpreter", "run_tests", "package_tool"):
- seq = by_intent.get(intent, [])
- fails = [o for o in seq if o.outcome in FORM_ERRORS]
- if intent != "run_tests":
- # An explicit path or activation that fails is a missing dependency, not a
- # resolution problem; only a bare form can be "repaired" by a fuller one.
- fails = [o for o in fails if _is_bare(o.form)]
- for a in fails:
- later_ok = [o for o in seq if o.outcome == "ran" and o.call > a.call
- and o.form != a.form
- and (intent == "run_tests" or not _is_bare(o.form))]
- if not later_ok:
- continue
- fid = f"form_repair:{intent}:{a.form}"
- f = self.facts.get(fid)
- if f is None:
- f = EnvFact(fid, "form_repair", high=False,
- params={"intent": intent, "a": a.form,
- "b_counts": {}, "error_counts": {}})
- self.facts[fid] = f
- for o in later_ok:
- f.params["b_counts"][o.form] = f.params["b_counts"].get(o.form, 0) + 1
- f.params["error_counts"][a.outcome] = f.params["error_counts"].get(a.outcome, 0) + 1
- for f in [x for x in self.facts.values() if x.family == "form_repair"]:
- intent, a_form = f.params["intent"], f.params["a"]
- seq = by_intent.get(intent, [])
- exercised = bool(seq)
- a_failed = any(o.form == a_form and o.outcome in FORM_ERRORS for o in seq)
- b_forms = set(f.params["b_counts"])
- b_ran = any(o.form in b_forms and o.outcome == "ran" for o in seq) or \
- any(o.outcome == "ran" and not _is_bare(o.form) for o in seq)
- # Contradiction: the bare form ran the TEST RUNNER without an environment error.
- # A bare interpreter one-liner succeeding is not evidence (pure-Python packages
- # import from the working tree under any interpreter).
- a_runner_ok = any(o.form == a_form and o.outcome == "ran"
- for o in by_intent.get("run_tests", []))
- fired = a_failed or (f.id in injected and b_ran and not a_failed)
- if a_failed or (b_ran and not a_runner_ok):
- verdict = "confirm"
- elif a_runner_ok:
- verdict = "contradict"
- else:
- verdict = None
- fold(f, self.now, verdict, fired, exercised, files)
- verdicts[f.id] = (verdict, fired, exercised)
-
- # ---- Boundary: hosts refused ----
- fetches = by_intent.get("fetch_remote", [])
- failed_hosts = Counter(h for o in fetches if o.outcome in NETWORK_ERRORS for h in o.hosts)
- ok_hosts = {h for o in fetches if o.outcome == "ran" for h in o.hosts}
- fid = "boundary:fetch_remote"
- f = self.facts.get(fid)
- if f is None and failed_hosts:
- f = EnvFact(fid, "boundary", high=True, params={"hosts": {}})
- self.facts[fid] = f
- if f is not None:
- for h, n in failed_hosts.items():
- f.params["hosts"][h] = f.params["hosts"].get(h, 0) + n
- known = set(f.params["hosts"])
- exercised = any(o.hosts for o in fetches)
- fired = bool(failed_hosts)
- if ok_hosts & known:
- verdict = "contradict"
- elif failed_hosts:
- verdict = "confirm"
- else:
- verdict = None
- fold(f, self.now, verdict, fired, exercised, files)
- verdicts[fid] = (verdict, fired, exercised)
-
- # ---- EmptyProbe: refs beyond the checkout ----
- probes = [o for o in by_intent.get("probe_vcs_refs", []) if o.outcome in ("hit", "empty")]
- fid = "empty_probe:vcs_refs"
- f = self.facts.get(fid)
- if f is None and probes:
- f = EnvFact(fid, "empty_probe", high=True, params={"kinds": {}})
- self.facts[fid] = f
- if f is not None:
- for o in probes:
- f.params["kinds"][o.probe] = f.params["kinds"].get(o.probe, 0) + 1
- exercised = bool(probes)
- fired = exercised
- if any(o.outcome == "hit" for o in probes):
- verdict = "contradict"
- elif probes:
- verdict = "confirm"
- else:
- verdict = None
- fold(f, self.now, verdict, fired, exercised, files)
- verdicts[fid] = (verdict, fired, exercised)
-
- self.last_digest = {"iid": iid, "resolved": resolved, "injected": sorted(injected),
- "verdicts": verdicts, "n_calls": digest["n_calls"]}
- self.last_injected = set()
- self.now += 1
-
- # ---- persistence -------------------------------------------------------------
- @staticmethod
- def _path(root, repo):
- d = os.path.join(root, STATE_SUBDIR)
- os.makedirs(d, exist_ok=True)
- return os.path.join(d, repo.replace("/", "__") + ".json")
-
- def save(self, root):
- with open(self._path(root, self.repo), "w", encoding="utf-8") as fh:
- json.dump({"repo": self.repo, "now": self.now, "opt_tokens": 0.0,
- "vocab": self.vocab.name,
- "facts": {k: f.to_dict() for k, f in self.facts.items()}}, fh, indent=2)
-
- @classmethod
- def load(cls, repo, root, runner=None, model="agent", vocab=None, max_facts=None,
- max_tokens=None):
- self = cls(repo, vocab=vocab, max_facts=max_facts, max_tokens=max_tokens)
- p = self._path(root, repo)
- if not os.path.exists(p):
- return self
- with open(p, encoding="utf-8") as fh:
- d = json.load(fh)
- self.now = d.get("now", 0)
- self.facts = {k: EnvFact.from_dict(v) for k, v in d.get("facts", {}).items()}
- return self
-
- # ---- telemetry ---------------------------------------------------------------
- def debug_row(self):
- row = {}
- for k, f in self.facts.items():
- row[k] = {"state": f.state, "fire": f"{f.life.fire_num}/{f.life.fire_den}",
- "rate": round(f.firing_rate(), 2), "inject": f.injectable(),
- "claim": f.claim()[:120], "family": f.family}
- row["_profile"] = "envfacts"
- row["_vocab"] = self.vocab.name
- if self.last_digest:
- row["_task"] = self.last_digest
- return row
diff --git a/tokeneconomizer/microskills/README.md b/tokeneconomizer/microskills/README.md
new file mode 100644
index 0000000..9e567e3
--- /dev/null
+++ b/tokeneconomizer/microskills/README.md
@@ -0,0 +1,36 @@
+# 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.
+
+Each finished session goes through three steps:
+
+1. **Observe** (`observe.py`). Every shell command is split into segments and classified by
+ *intent* (run the tests, run the interpreter, use the package tool, fetch, probe the VCS) and
+ *form* (how it was spelled), and its outcome is read off the output as an environmental error
+ class or a sign that tests ran. The words that name intents come from a `Vocabulary`
+ (`PYTHON_GIT`, `NODE_WEB`), so the same reader handles a Python or a Node repository.
+2. **Propose.** `envfacts.py` turns recurring shapes of evidence into candidate facts, with no
+ model call: a failing form followed by a working one (*form repair*), every fetch to a host
+ refused (*boundary*), VCS probes that always come back empty (*empty probe*), a test label
+ that loads once rewritten (*arg repair*), a missing environment variable that a later run
+ sets (*env value*). With `paid=true`, `distiller.py` adds an LLM proposer that authors facts
+ with host-checked detectors.
+3. **Keep or retire** (`lifecycle.py`). A candidate becomes active after confirmations on
+ three sessions (for a proposed fact about the code, sessions that edited different files),
+ retires on contradiction, and is injected only while
+ the failure it prevents keeps occurring (or keeps being prevented).
+
+`stage.PrefixStage` ties these together for a caller: render the block before a session, fold
+the session in after it. The block is capped (`MAX_FACTS`, `MAX_TOKENS`), and a lint refuses any
+fact that reads as completion or verification advice.
+
+| Module | |
+|---|---|
+| `observe.py` | command segmentation, intent and form, error classes, `observe_task` |
+| `envfacts.py` | `EnvFactsDistiller`: the five LLM-free fact families, rendering, caps |
+| `distiller.py` | `Distiller`: the optional paid proposer and its detector DSL |
+| `lifecycle.py` | `Lifecycle`: formation, retirement, the firing gate |
+| `stage.py` | `PrefixStage`, `ComposedDistiller` |
diff --git a/tokeneconomizer/microskills/__init__.py b/tokeneconomizer/microskills/__init__.py
new file mode 100644
index 0000000..1e76c03
--- /dev/null
+++ b/tokeneconomizer/microskills/__init__.py
@@ -0,0 +1,20 @@
+"""Micro-skill synthesis and injection: learn short repository facts from finished sessions,
+and state them at the start of the next one.
+
+ * `observe` -- what a finished session shows about its environment (classified commands);
+ * `envfacts` -- `EnvFactsDistiller`, the LLM-free environment-fact families;
+ * `distiller` -- `Distiller`, the optional paid proposer and its detector DSL;
+ * `lifecycle` -- the formation, retirement and firing gate every fact goes through;
+ * `stage` -- `PrefixStage`, which renders the block and folds each session back in.
+
+Stdlib only; never imports the plugin runtime.
+"""
+from .distiller import Distiller
+from .envfacts import EnvFactsDistiller
+from .lifecycle import Lifecycle
+from .observe import NODE_WEB, PYTHON_GIT, Vocabulary, classify_command, observe_task
+from .stage import ComposedDistiller, PrefixStage
+
+__all__ = ["Distiller", "EnvFactsDistiller", "Lifecycle", "NODE_WEB", "PYTHON_GIT",
+ "Vocabulary", "classify_command", "observe_task", "ComposedDistiller",
+ "PrefixStage"]
diff --git a/tokeneconomizer/mechanisms/injection.py b/tokeneconomizer/microskills/distiller.py
similarity index 69%
rename from tokeneconomizer/mechanisms/injection.py
rename to tokeneconomizer/microskills/distiller.py
index c05f91e..e647d56 100644
--- a/tokeneconomizer/mechanisms/injection.py
+++ b/tokeneconomizer/microskills/distiller.py
@@ -1,53 +1,27 @@
-"""Injection mechanism: a firing-gated, per-repo "operating manual" learned from the
-running task stream and injected into the next task's prefix.
-
-WHAT IT DOES. As a repo's chronological task stream runs, a paid LLM proposer (one call
-per `PROPOSE_EVERY` finished tasks, over a COMPACT digest -- never raw transcripts)
-authors two kinds of durable, repo-specific artifacts:
-
- * facts -- one-line declarative statements about the repo an agent would want
- stated up front (canonical test command, "a failing test already
- reproduces the bug", a required env var, a build step, ...).
- * extractors -- tiny host-executable predicates over the raw command/output stream
- that surface evidence the fixed digest doesn't already expose.
-
-Every fact carries a host-run DETECTOR (regex/predicate DSL), so the hot path stays
-LLM-free: the LLM invents the facts, the host runs the checks. Each fact then flows
-through a validated lifecycle -- FORMATION (promote CANDIDATE->ACTIVE after K_PROMOTE
-confirmations across DRIFTED tasks, proving commit-stable not task-stable), EXPIRY
-(recency-weighted score with asymmetric contradiction; a single clean contradiction
-hard-kills a high-stakes fact), and a FIRING GATE (inject a fact only once its measured
-firing rate on this repo clears FIRE_GATE) -- so dead prefix bytes never accrue.
-
-One revisable knob: an existing fact's CONTRADICTION condition (`detector.contradict`)
-may be corrected after the fact was first written; everything else about a fact, and all
-extractors, are append-only. Because the contradict regex only ever RETIRES a fact (never
-confirms/fires it), revising it cannot manufacture unearned credibility -- so the earned
-lifecycle counters are kept in place and the new condition applies going forward.
-
-COST HONESTY. The proposer's effective-token cost accrues on `Distiller.opt_tokens`; the
-per-task delta is charged to the amortized ledger as `optimizer_tokens`. As extractor
-coverage matures the proposer stops needing raw excerpts and the cost decays.
-
-It is the injection arm of the generic (Claude / Copilot) tri-mechanism stack.
-
-This is the single, un-versioned successor to the manual-distiller line (v5.1 frozen ->
-v5.2 open facts -> v5.3 open extractors -> v5.4 revisable contradiction).
+"""The paid proposer: an LLM that authors repository facts, each with a host-run detector.
+
+As a repository's sessions finish, one LLM call per `PROPOSE_EVERY` sessions reads a COMPACT
+digest of the recent ones (never raw transcripts) and authors two kinds of durable artifacts:
+
+ * facts -- one-line declarative statements an agent would want stated up front (the
+ canonical test command, a required environment variable, a build step);
+ * extractors -- small host-executable predicates over the raw command and output stream that
+ surface evidence the fixed digest does not already expose.
+
+Every fact carries a DETECTOR (a regex/predicate DSL), so the hot path stays LLM-free: the model
+invents the facts, the host checks them, and each goes through the shared `lifecycle`. Only a
+fact's contradiction condition may be revised after it is written; since that condition only
+ever retires a fact, revising it cannot manufacture credibility, and the earned counters stay.
+
+The proposer's effective-token cost accrues on `Distiller.opt_tokens`, which the caller charges
+to the ledger as overhead.
"""
import json
import os
import re
-from .base import Stage
-
-# ---- lifecycle knobs (the validated replay constants) ----------------------
-K_PROMOTE = 3 # drifted confirmations to promote CANDIDATE -> ACTIVE
-GAMMA = 0.8 # recency decay per task-ago
-LAMBDA = 5.0 # contradiction weight (asymmetry: fail toward retirement)
-SCORE_FLOOR = 0.0 # retire ACTIVE when recency score < floor
-HARD_KILL = True # high-stakes fact: single clean contradiction retires now
-FIRE_GATE = 0.40 # inject only if firing rate on this repo >= 40%
-FIRE_MIN_N = 4 # ...measured over at least this many exercised tasks
+from ..trace.claude import CONVERSATION
+from .lifecycle import Lifecycle, edited_pyfiles
# ---- proposer cadence / caps / gates ---------------------------------------
PROPOSE_EVERY = 8 # one LLM proposer call per this many tasks (PrefixStage rebinds
@@ -103,7 +77,7 @@ def load_calls(fp):
except Exception:
continue
m = d.get("message")
- if not isinstance(m, dict):
+ if not isinstance(m, dict) or d.get("type", "assistant") not in CONVERSATION:
continue
c = m.get("content")
if not isinstance(c, list):
@@ -111,7 +85,7 @@ def load_calls(fp):
for b in c:
if not isinstance(b, dict):
continue
- if b.get("type") == "tool_use":
+ if b.get("type") == "tool_use" and b.get("id") not in uses:
uses[b.get("id")] = (b.get("name", ""), b.get("input") or {})
order.append(b.get("id"))
elif b.get("type") == "tool_result":
@@ -129,85 +103,6 @@ def bash_cmds(calls):
return out
-def edited_pyfiles(calls):
- fs = set()
- for tool, args, _ in calls:
- if tool in ("edit", "multiedit", "write", "create", "str_replace_editor"):
- p = args.get("file_path") or args.get("path") or ""
- if p.endswith(".py"):
- fs.add(os.path.basename(p))
- elif tool == "apply_patch":
- for p in args.get("paths") or ():
- if p.endswith(".py"):
- fs.add(os.path.basename(p))
- return fs
-
-
-# ---- lifecycle state machine (per fact) ------------------------------------
-class _Fact:
- def __init__(self, key, high):
- self.key = key
- self.high = high
- self.state = "CANDIDATE" # CANDIDATE | ACTIVE | RETIRED
- self.confirms = [] # [(task_idx, [edited_files])]
- self.contradicts = [] # [task_idx]
- self.fire_num = 0 # tasks where the waste occurred (fired)
- self.fire_den = 0 # tasks where the fact was exercised
- self.promoted_at = None
- self.retired_at = None
-
- def to_dict(self):
- return {"key": self.key, "high": self.high, "state": self.state,
- "confirms": self.confirms, "contradicts": self.contradicts,
- "fire_num": self.fire_num, "fire_den": self.fire_den,
- "promoted_at": self.promoted_at, "retired_at": self.retired_at}
-
- @classmethod
- def from_dict(cls, d):
- f = cls(d["key"], d["high"])
- f.__dict__.update(d)
- return f
-
- def _drifted_confirms(self):
- kept = []
- for idx, fs in self.confirms:
- fs = set(fs)
- if not fs or all(len(fs & set(k)) == 0 for _, k in kept):
- kept.append((idx, fs))
- return len(kept)
-
- def score(self, now):
- s = sum(GAMMA ** (now - i) for i, _ in self.confirms)
- s -= LAMBDA * sum(GAMMA ** (now - i) for i in self.contradicts)
- return s
-
- def firing_rate(self):
- return (self.fire_num / self.fire_den) if self.fire_den else 0.0
-
- def injectable(self):
- """ACTIVE and clears the firing gate -> goes into the rendered manual."""
- return (self.state == "ACTIVE"
- and self.fire_den >= FIRE_MIN_N
- and self.firing_rate() >= FIRE_GATE)
-
- def update(self, now, verdict, fired, exercised, files):
- if exercised:
- self.fire_den += 1
- if fired:
- self.fire_num += 1
- if verdict == "confirm":
- self.confirms.append((now, sorted(files)))
- elif verdict == "contradict":
- self.contradicts.append(now)
- if self.state == "CANDIDATE":
- if self._drifted_confirms() >= K_PROMOTE:
- self.state, self.promoted_at = "ACTIVE", now
- elif self.state == "ACTIVE":
- hard = self.high and verdict == "contradict" and HARD_KILL
- if hard or self.score(now) < SCORE_FLOOR:
- self.state, self.retired_at = "RETIRED", now
-
-
# ---- compact digest: one dict per finished task (the proposer's only view) --
def build_digest(repo, transcript_path, iid, resolved=None):
try:
@@ -366,7 +261,7 @@ class Fact:
self.high = bool(spec.get("high_stakes", False))
self.detector = Detector(spec.get("detector", {}))
self.spec = spec
- self.life = _Fact(self.id, self.high) # the validated state machine
+ self.life = Lifecycle(self.id, self.high) # the validated state machine
@property
def state(self):
@@ -392,7 +287,7 @@ class Fact:
@classmethod
def from_dict(cls, d):
f = cls(d["spec"])
- f.life = _Fact.from_dict(d["life"])
+ f.life = Lifecycle.from_dict(d["life"])
return f
@@ -725,108 +620,3 @@ class Distiller:
if isinstance(row.get(fid), dict):
row[fid]["rev"] = f.spec.get("rev", 1)
return row
-
-
-# ---- composition: the free environment layer under the paid manual -------------------
-class ComposedDistiller:
- """`envfacts` first, the paid manual on top, driven as one distiller.
-
- The environment layer renders first (its block is what the proposer is told not to
- restate); both fold every finished task; each persists in its own state dir. Overhead is
- the proposer's alone -- the environment layer is LLM-free by construction."""
- def __init__(self, env, dist):
- self.env, self.dist = env, dist
-
- @property
- def opt_tokens(self):
- return self.dist.opt_tokens
-
- @property
- def now(self):
- return self.dist.now
-
- def render(self, task=None):
- a = self.env.render(task)
- b = self.dist.render(task)
- return (a + ("\n" if a and b else "") + b) if (a or b) else ""
-
- def update(self, transcript_path, iid="", resolved=None, edited=None):
- self.env.update(transcript_path, iid=iid, resolved=resolved, edited=edited)
- self.dist.update(transcript_path, iid=iid, resolved=resolved, edited=edited)
-
- def save(self, root):
- self.env.save(root)
- self.dist.save(root)
-
- def debug_row(self):
- row = dict(self.dist.debug_row())
- row.update(self.env.debug_row())
- row["_profile"] = "envfacts+distiller"
- return row
-
-
-# ---- lifecycle stage -------------------------------------------------------
-class PrefixStage(Stage):
- """Injection lifecycle hook: render the manual before a task, fold the finished
- task back into the distiller after it, and report the paid proposer's per-task
- token delta for the amortized ledger."""
- name = "prefix"
-
- def __init__(self, cfg, repo, results_root, fresh,
- runner=None, optimizer_model="agent", adapter=None, agent=None):
- self.results_root = results_root
- self.adapter = adapter
- self.agent = agent
- # The Distiller is the single source of truth for the proposer cadence: rebind
- # the module global that update()'s gate reads (process-local, idempotent).
- pe = int(getattr(cfg, "propose_every", 0) or 0)
- if pe > 0:
- global PROPOSE_EVERY
- PROPOSE_EVERY = pe
- profile = getattr(cfg, "profile", "distiller") or "distiller"
- # The environment-fact layer reads intents through a domain vocabulary; the adapter
- # supplies it when it has one (SWE-bench: Python/git; Web-Bench: Node/npm).
- vocab = adapter.env_vocabulary() if hasattr(adapter, "env_vocabulary") else None
- env = None
- if "envfacts" in profile:
- from .envfacts import EnvFactsDistiller
- caps = {"max_facts": getattr(cfg, "max_facts", 0) or None,
- "max_tokens": getattr(cfg, "max_tokens", 0) or None}
- env = (EnvFactsDistiller(repo, vocab=vocab, **caps) if fresh
- else EnvFactsDistiller.load(repo, results_root, vocab=vocab, **caps))
- if profile == "envfacts":
- # LLM-free environment facts alone. Same render/update/save interface, no
- # runner, opt_tokens stays 0 -- the ledger sees no overhead.
- self.reason = "envfacts"
- self.distiller = env
- else:
- # The paid proposer; with `envfacts+distiller` it is told which claims the free
- # layer already injects, so it authors only facts beyond them.
- external = env.injectable_claims if env is not None else None
- dist = (Distiller(repo, runner=runner, model=optimizer_model,
- external_facts=external) if fresh
- else Distiller.load(repo, results_root, runner=runner,
- model=optimizer_model, external_facts=external))
- if env is not None:
- self.reason = "envfacts+manual-distill"
- self.distiller = ComposedDistiller(env, dist)
- else:
- self.reason = "manual-distill"
- self.distiller = dist
-
- def render(self, task=None):
- """The firing-gated repo manual injected into the NEXT task's prefix."""
- return self.distiller.render(task=task) if self.distiller else ""
-
- def after_task(self, task, row, run_dir_path, srow):
- """Fold the finished task into the fact lifecycle; return (opt_tokens, reason).
- The paid proposer accrues cumulatively on distiller.opt_tokens; capture THIS
- task's delta for the per-task ledger (same effective-token basis)."""
- transcript = os.path.join(run_dir_path, "transcript.jsonl")
- before = self.distiller.opt_tokens
- self.distiller.update(transcript, iid=task["instance_id"],
- resolved=srow.get("resolved"))
- self.distiller.save(self.results_root)
- opt_tokens = self.distiller.opt_tokens - before
- srow["manual_facts"] = self.distiller.debug_row()
- return opt_tokens, self.reason
diff --git a/tokeneconomizer/microskills/envfacts.py b/tokeneconomizer/microskills/envfacts.py
new file mode 100644
index 0000000..7a0e857
--- /dev/null
+++ b/tokeneconomizer/microskills/envfacts.py
@@ -0,0 +1,555 @@
+"""Environment facts: micro-skills learned for free from recurring failures.
+
+As a repository's sessions finish, this distiller looks for RECURRING SHAPES OF EVIDENCE that an
+agent rediscovers the same environment fact by failing at it, session after session. When a
+shape recurs across sessions that edited different files, it becomes a one-line declarative
+fact, injected at the start of the next session. Every specific string in a rendered fact -- an
+interpreter path, a runner form, a refused host -- is a PARAMETER learned from the sessions;
+nothing here names a path, an environment manager, a repository or a benchmark.
+
+The families:
+
+ FormRepair in one session, form A of an intent (run the interpreter, run the tests, use the
+ package tool) fails with an infrastructure error and a later form B succeeds.
+ Fact: "`A ...` fails here with <error>; `B ...` works." Retires when a bare form
+ runs the test runner successfully.
+ Boundary every call of an operation class (fetching from a host) fails with one
+ environmental error class and none succeeds. Fact: "Connections to <hosts> are
+ refused here." Retires when a fetch to a listed host succeeds.
+ EmptyProbe discovery probes of one kind (VCS refs beyond the checkout) return nothing in
+ every session where they run. Fact: "no remote, no refs beyond HEAD". Retires --
+ hard -- the moment a probe returns something.
+ ArgRepair the test runner cannot load a label of one shape and, run the same way, loads it
+ rewritten into another (a leading package prefix dropped, `::` written as `.`).
+ A label naming something that does not exist matches neither rewrite, so a plain
+ mistake never becomes a fact. Retires when a label of the failing shape loads.
+ EnvValue code fails asking for an environment variable by name, and a later run that sets
+ it succeeds. Fact: "Code that imports the project needs `V` set here: `V=x`
+ works." Retires when that value fails the same way.
+
+Each fact goes through the shared `lifecycle`. No LLM is involved: `opt_tokens` is 0. The block
+is capped at MAX_FACTS and MAX_TOKENS, and a lint refuses any fact that reads as completion or
+verification advice.
+"""
+import json
+import os
+import re
+from collections import Counter
+
+from .lifecycle import Lifecycle
+from .observe import (DEFAULT_VOCAB, NETWORK_ERRORS, form_failed, form_worked, is_bare,
+ label_rule, observe_task)
+
+STATE_SUBDIR = "envfacts_state"
+MAX_FACTS = 4
+MAX_TOKENS = 150 # ~4 chars per token; the whole block, header included
+HEADER = "# environment facts learned from earlier tasks in this checkout"
+
+# Words that would turn a fact into completion or verification advice.
+_LINT_RE = re.compile(r"\b(skip|no need|don'?t|do not|stop|done|completed?|finish(?:ed)?|"
+ r"verify|verification|instead of (?:running|testing))\b", re.I)
+
+_ERROR_PHRASE = {
+ "module_missing": "ModuleNotFoundError",
+ "command_missing": "command not found",
+ "script_missing": "a file-not-found error",
+ "usage_error": "a usage error",
+ "permission_denied": "permission denied",
+}
+
+
+# --------------------------------------------------------------------------------------
+# facts
+# --------------------------------------------------------------------------------------
+class EnvFact:
+ def __init__(self, fid, family, high, params=None):
+ self.id = fid
+ self.family = family
+ self.params = params or {}
+ # An environment fact holds or not whatever files a session edits: in a small
+ # repository where every session touches the same module, three sessions missing
+ # `pytest` are three confirmations (seen live on all four agents).
+ self.life = Lifecycle(fid, high, drift=False)
+
+ # ---- lifecycle passthrough ----
+ @property
+ def state(self):
+ return self.life.state
+
+ def injectable(self):
+ return self.life.injectable()
+
+ def firing_rate(self):
+ return self.life.firing_rate()
+
+ # ---- rendering ----
+ def claim(self):
+ p = self.params
+ if self.family == "form_repair":
+ b = self.working_form()
+ if b is None:
+ return ""
+ e = self._best("error_counts") or "module_missing"
+ return (f"{_usage(p['a'])} fails here with {_ERROR_PHRASE.get(e, e)}; "
+ f"{_usage(b)} works.")
+ if self.family == "boundary":
+ hosts = [h for h, _ in Counter(p.get("hosts", {})).most_common(3)]
+ return ("Outbound connections to " + _join(hosts) +
+ " are refused here; nothing can be fetched from them.")
+ if self.family == "arg_repair":
+ if p.get("kind") == "sep":
+ return (f"{_usage(p['form'], '')} takes dotted test labels (`module.Class.test`, "
+ f"not `module::Class::test`).")
+ a, b = min((k.split(" ", 1) for k in p.get("examples") or {"x x": 1}),
+ key=lambda ab: len(ab[0]))
+ return (f"{_usage(p['form'], '')} takes test labels without the `{p['param']}` prefix "
+ f"(`{b}`, not `{a}`).")
+ if self.family == "env_value":
+ good = self._best("good") or ""
+ bad = [v for v in sorted(p.get("bad") or {}) if v != good][:1]
+ return (f"Code that imports the project needs `{p['var']}` set here: "
+ f"`{p['var']}={good}` works" + (f", `{bad[0]}` does not." if bad else "."))
+ if self.family == "empty_probe":
+ return ("This checkout has no git remote and no branches, tags or unreachable "
+ "objects beyond HEAD; its history ends at the checked-out commit.")
+ return ""
+
+ def _best(self, key):
+ c = self.params.get(key) or {}
+ return max(c.items(), key=lambda kv: kv[1])[0] if c else None
+
+ def working_form(self):
+ """The working form a FormRepair names: the one with the best record, sessions it worked
+ in as typed less sessions it failed in -- among those that leave the shell where it is
+ (`python tests/runtests.py`, not `cd tests && python runtests.py`) whenever one of them
+ has a good record at all. None when no form has: then the fact makes no claim."""
+ c = self.params.get("b_counts") or {}
+ bad = self.params.get("b_fails") or {}
+ net = {k: v - bad.get(k, 0) for k, v in c.items() if v > bad.get(k, 0)}
+ pool = {k: n for k, n in net.items() if not _moves_shell(k)} or net
+ return max(pool, key=lambda k: (pool[k], c[k])) if pool else None
+
+ def to_dict(self):
+ return {"id": self.id, "family": self.family, "params": self.params,
+ "life": self.life.to_dict()}
+
+ @classmethod
+ def from_dict(cls, d):
+ f = cls(d["id"], d["family"], d["life"].get("high", False), d.get("params") or {})
+ f.life = Lifecycle.from_dict(d["life"])
+ f.life.drift = False
+ return f
+
+
+CONTRADICT_STREAK = 2 # FormRepair: consecutive contradicted tasks before one counts
+
+
+def fold(fact, now, verdict, fired, exercised, files):
+ """Fold one task's verdict into a fact's lifecycle.
+
+ Two adjustments to the shared state machine. A high-stakes CANDIDATE that is contradicted
+ retires at once (`_Fact` hard-kills only ACTIVE facts): an image whose history continues
+ past HEAD does not become clean by being probed again. And a FormRepair contradiction --
+ the bare form ran the test runner -- only counts after CONTRADICT_STREAK consecutive
+ exercised tasks said so: a single task whose tests happened to need none of the missing
+ packages is not a fixed environment, and the asymmetric contradiction weight would
+ otherwise retire a fact confirmed thirty times over."""
+ if fact.family == "form_repair" and exercised:
+ streak = fact.params.get("contra_streak", 0)
+ streak = streak + 1 if verdict == "contradict" else 0
+ fact.params["contra_streak"] = streak
+ if verdict == "contradict" and streak < CONTRADICT_STREAK:
+ verdict = None
+ fact.life.update(now, verdict, fired, exercised, files)
+ if verdict == "contradict" and fact.life.high and fact.life.state == "CANDIDATE":
+ fact.life.state, fact.life.retired_at = "RETIRED", now
+
+
+def typed_ok(o):
+ """The form worked exactly as typed: no `VAR=value` before it, which its form leaves out,
+ had to help. `PYTHONPATH=. ~/.local/bin/pytest` passing says nothing for a bare
+ `~/.local/bin/pytest`, which here stopped at collection."""
+ return form_worked(o) and not o.env
+
+
+def _repairs(form, a_form, intent):
+ """Can `form` stand in for the failing `a_form`? Another form -- and, outside test runs,
+ not a bare one: only a fuller spelling repairs a bare interpreter or package tool."""
+ return form != a_form and (intent == "run_tests" or not is_bare(form))
+
+
+def _moves_shell(form):
+ return form.startswith("cd ") and " && " in form
+
+
+def _usage(form, args=" …"):
+ """A form as a claim shows it. One that starts with `cd DIR &&` is shown as a subshell: an
+ agent whose shell keeps its directory between calls (Claude Code) that typed the bare
+ `cd` would run every later command in DIR -- seen live, where "`cd tests && python
+ runtests.py …` works" was followed by `cd: tests: No such file or directory` and `can't
+ open file 'runtests.py'` over and over."""
+ return f"`({form}{args})`" if _moves_shell(form) else f"`{form}{args}`"
+
+
+def _root(form):
+ """The part of a working form that carries the environment: its activation prefix, or
+ the directory of its explicit path."""
+ if " && " in form:
+ return form.split(" && ", 1)[0]
+ if form.startswith(("conda run", "poetry run", "pipenv run", "uv run", "npx")):
+ return " ".join(form.split()[:3])
+ head = form.split()[0] if form else ""
+ return head.rsplit("/", 1)[0] if "/" in head else head
+
+
+def _join(items):
+ items = list(items)
+ if not items:
+ return "the hosts it tried"
+ if len(items) == 1:
+ return items[0]
+ return ", ".join(items[:-1]) + " and " + items[-1]
+
+
+def lint_ok(text):
+ return not _LINT_RE.search(text or "")
+
+
+# --------------------------------------------------------------------------------------
+# the distiller
+# --------------------------------------------------------------------------------------
+class EnvFactsDistiller:
+ """Learns and injects environment facts over a repository's task stream.
+
+ Interface parity with `injection.Distiller`, so `PrefixStage` drives both the same way:
+ d = EnvFactsDistiller(repo, vocab=...) # fresh, or .load(repo, root, vocab=...)
+ prefix = d.render() # block for the NEXT task ("" if none)
+ d.update(transcript_path, iid=..., resolved=...)
+ d.save(root)
+ `runner`/`model` are accepted and ignored: nothing here is paid. `vocab` is the domain's
+ `Vocabulary` (default Python/git); `injectable_claims()` is what a paid proposer stacked
+ on top is told not to restate. `max_facts` / `max_tokens` cap the rendered block
+ (default MAX_FACTS / MAX_TOKENS).
+ """
+ def __init__(self, repo, runner=None, model="agent", vocab=None, max_facts=None,
+ max_tokens=None):
+ self.max_facts = int(max_facts or MAX_FACTS)
+ self.max_tokens = int(max_tokens or MAX_TOKENS)
+ self.repo = repo
+ self.vocab = vocab or DEFAULT_VOCAB
+ self.now = 0
+ self.facts = {} # id -> EnvFact
+ self.opt_tokens = 0.0 # invariant: LLM-free
+ self.last_injected = set() # fact ids rendered for the task now running
+ self.last_digest = None # the most recent per-task verdicts (telemetry)
+
+ # ---- render --------------------------------------------------------------------
+ def render(self, task=None):
+ chosen = self._select()
+ self.last_injected = {f.id for f in chosen}
+ if not chosen:
+ return ""
+ lines = [HEADER] + [f"- {t}" for t in self._merged_lines(chosen)]
+ return "\n".join(lines) + "\n"
+
+ def injected_ids(self):
+ """The ids of the facts the last `render` chose: what the next session is given."""
+ return sorted(self.last_injected)
+
+ def seed_injected(self, ids):
+ """Say which facts the session about to be folded was actually given. A caller that
+ renders in one process and folds in another (the plugin: a session-start hook, then a
+ fold after the session) must, or an injected fact never counts as having fired and
+ decays out of the block while it works."""
+ self.last_injected = {i for i in ids or () if i in self.facts}
+
+ def injectable_claims(self):
+ """The claims that would be injected now, one string each (no header)."""
+ return [f.claim() for f in self._select()]
+
+ def _select(self):
+ cands = [f for f in self.facts.values()
+ if f.injectable() and f.claim() and lint_ok(f.claim())]
+ prio = {"form_repair": 0, "arg_repair": 1, "env_value": 2, "empty_probe": 3,
+ "boundary": 4}
+ cands.sort(key=lambda f: (prio.get(f.family, 9),
+ 0 if f.params.get("intent") == "run_interpreter" else 1,
+ -f.firing_rate()))
+ chosen = []
+ for f in cands:
+ trial = chosen + [f]
+ if len(trial) > self.max_facts:
+ break
+ text = HEADER + "\n" + "\n".join(f"- {t}" for t in self._merged_lines(trial))
+ if len(text) > self.max_tokens * 4:
+ continue
+ chosen = trial
+ return chosen
+
+ def _merged_lines(self, facts):
+ """FormRepair facts whose working forms share a root (the same activation prefix
+ or the same directory) collapse into one line: they are one environment fact."""
+ lines, groups = [], {}
+ for f in facts:
+ if f.family == "form_repair":
+ groups.setdefault(_root(f.working_form() or ""), []).append(f)
+ else:
+ lines.append(f.claim())
+ for _root_key, fs in groups.items():
+ if len(fs) == 1:
+ lines.insert(0, fs[0].claim())
+ continue
+ a_forms = _join([_usage(f.params["a"]) for f in fs])
+ errs = sorted({_ERROR_PHRASE.get(f._best("error_counts") or "", "") for f in fs}
+ - {""})
+ bs = sorted({_usage(f.working_form()) for f in fs})
+ lines.insert(0, f"{a_forms} fail here ({', '.join(errs) or 'environment error'}); "
+ f"{_join(bs)} {'works' if len(bs) == 1 else 'work'}.")
+ return lines
+
+ # ---- update --------------------------------------------------------------------
+ def update(self, transcript_path, iid="", resolved=None, edited=None):
+ try:
+ digest = observe_task(transcript_path, self.vocab)
+ except Exception:
+ self.now += 1
+ self.last_injected = set()
+ return
+ obs = digest["obs"]
+ files = set(digest["edited"]) if edited is None else set(edited)
+ injected = set(self.last_injected)
+ verdicts = {}
+
+ # ---- FormRepair: discover candidates, then fold every fact ----
+ by_intent = {}
+ for o in obs:
+ by_intent.setdefault(o.intent, []).append(o)
+ for intent in ("run_interpreter", "run_tests", "package_tool"):
+ seq = by_intent.get(intent, [])
+ # A test run that failed because its LABEL did not load says nothing about the way
+ # the runner was called (Django reports a bad label as a ModuleNotFoundError): those
+ # are ArgRepair's. Counting them here once taught "`python tests/runtests.py` fails;
+ # `python runtests.py` works" from a stream of mistyped labels.
+ fails = [o for o in seq if form_failed(o)]
+ if intent != "run_tests":
+ # An explicit path or activation that fails is a missing dependency, not a
+ # resolution problem; only a bare form can be "repaired" by a fuller one.
+ fails = [o for o in fails if is_bare(o.form)]
+ for a in fails:
+ if not any(typed_ok(o) and o.call > a.call and _repairs(o.form, a.form, intent)
+ for o in seq):
+ continue
+ fid = f"form_repair:{intent}:{a.form}"
+ f = self.facts.get(fid)
+ if f is None:
+ f = EnvFact(fid, "form_repair", high=False,
+ params={"intent": intent, "a": a.form,
+ "b_counts": {}, "error_counts": {}})
+ self.facts[fid] = f
+ f.params["error_counts"][a.outcome] = f.params["error_counts"].get(a.outcome, 0) + 1
+ # A session is one piece of evidence per form: every form that worked as typed adds
+ # one, and a known working form that failed as typed (and never worked) takes one
+ # back -- so one messy session cannot outvote several clean ones, and a form that
+ # stops working here stops being named.
+ ok = {o.form for o in seq if typed_ok(o)}
+ failed = {o.form for o in seq if form_failed(o) and not o.env} - ok
+ for f in self.facts.values():
+ if f.family != "form_repair" or f.params["intent"] != intent:
+ continue
+ for form in ok:
+ if _repairs(form, f.params["a"], intent):
+ f.params["b_counts"][form] = f.params["b_counts"].get(form, 0) + 1
+ fails_ = f.params.setdefault("b_fails", {})
+ for form in failed & set(f.params["b_counts"]):
+ fails_[form] = fails_.get(form, 0) + 1
+ for f in [x for x in self.facts.values() if x.family == "form_repair"]:
+ intent, a_form = f.params["intent"], f.params["a"]
+ seq = by_intent.get(intent, [])
+ exercised = bool(seq)
+ a_failed = any(o.form == a_form and form_failed(o) for o in seq)
+ b_forms = set(f.params["b_counts"])
+ b_ran = any(o.form in b_forms and form_worked(o) for o in seq) or \
+ any(form_worked(o) and not is_bare(o.form) for o in seq)
+ # Contradiction: the bare form ran the TEST RUNNER without an environment error.
+ # A bare interpreter one-liner succeeding is not evidence (pure-Python packages
+ # import from the working tree under any interpreter).
+ a_runner_ok = any(o.form == a_form and form_worked(o)
+ for o in by_intent.get("run_tests", []))
+ fired = a_failed or (f.id in injected and b_ran and not a_failed)
+ if a_failed or (b_ran and not a_runner_ok):
+ verdict = "confirm"
+ elif a_runner_ok:
+ verdict = "contradict"
+ else:
+ verdict = None
+ fold(f, self.now, verdict, fired, exercised, files)
+ verdicts[f.id] = (verdict, fired, exercised)
+
+ # ---- ArgRepair: labels the runner loads only in another shape ----
+ runs = [o for o in by_intent.get("run_tests", []) if o.labels]
+ for i, a_obs in enumerate(runs):
+ if not a_obs.label_err:
+ continue
+ for a in a_obs.labels:
+ for b_obs in runs[i + 1:]:
+ if b_obs.form != a_obs.form or not b_obs.loaded:
+ continue
+ rule = next((r for b in b_obs.labels for r in [label_rule(a, b)] if r), None)
+ if rule is None:
+ continue
+ b = next(b for b in b_obs.labels if label_rule(a, b) == rule)
+ fid = f"arg_repair:{a_obs.form}:{rule[0]}:{rule[1]}"
+ f = self.facts.get(fid)
+ if f is None:
+ f = EnvFact(fid, "arg_repair", high=False, params={
+ "form": a_obs.form, "kind": rule[0], "param": rule[1],
+ "examples": {}})
+ self.facts[fid] = f
+ key = f"{a} {b}"
+ f.params["examples"][key] = f.params["examples"].get(key, 0) + 1
+ break
+ for f in [x for x in self.facts.values() if x.family == "arg_repair"]:
+ mine = [o for o in runs if o.form == f.params["form"]]
+ if f.params["kind"] == "sep":
+ bad = lambda lab: "::" in lab
+ else:
+ bad = lambda lab, pre=f.params["param"]: lab.startswith(pre)
+ bad_failed = any(o.label_err and any(bad(x) for x in o.labels) for o in mine)
+ bad_loaded = any(o.loaded and any(bad(x) for x in o.labels) for o in mine)
+ good_loaded = any(o.loaded and any(not bad(x) for x in o.labels) for o in mine)
+ exercised = bool(mine)
+ fired = bad_failed or (f.id in injected and good_loaded and not bad_failed)
+ if bad_loaded:
+ verdict = "contradict"
+ elif bad_failed or good_loaded:
+ verdict = "confirm"
+ else:
+ verdict = None
+ fold(f, self.now, verdict, fired, exercised, files)
+ verdicts[f.id] = (verdict, fired, exercised)
+
+ # ---- EnvValue: a variable the code asks for, and the value that satisfied it ----
+ env = digest.get("env") or []
+ for i, c in enumerate(env):
+ for var in c["need"]:
+ later = [d for d in env[i + 1:] if var in d["sets"]]
+ good = [d["sets"][var] for d in later if d["ok"] and var not in d["need"]]
+ if not good:
+ continue
+ fid = f"env_value:{var}"
+ f = self.facts.get(fid)
+ if f is None:
+ f = EnvFact(fid, "env_value", high=False, params={
+ "var": var, "good": {}, "bad": {}})
+ self.facts[fid] = f
+ f.params["good"][good[0]] = f.params["good"].get(good[0], 0) + 1
+ for d in later:
+ if not d["ok"] and d["sets"][var] != good[0]:
+ val = d["sets"][var]
+ f.params["bad"][val] = f.params["bad"].get(val, 0) + 1
+ for f in [x for x in self.facts.values() if x.family == "env_value"]:
+ var, good = f.params["var"], f._best("good")
+ asked = any(var in c["need"] for c in env)
+ good_ok = any(c["sets"].get(var) == good and c["ok"] for c in env)
+ good_failed = any(c["sets"].get(var) == good and var in c["need"] for c in env)
+ exercised = asked or any(var in c["sets"] for c in env)
+ fired = asked or (f.id in injected and good_ok)
+ # Only the value working confirms the fact: code asking for the variable again
+ # shows the waste recurs (it fires), not that the learned value is right.
+ if good_failed:
+ verdict = "contradict"
+ elif good_ok:
+ verdict = "confirm"
+ else:
+ verdict = None
+ fold(f, self.now, verdict, fired, exercised, files)
+ verdicts[f.id] = (verdict, fired, exercised)
+
+ # ---- Boundary: hosts refused ----
+ fetches = by_intent.get("fetch_remote", [])
+ failed_hosts = Counter(h for o in fetches if o.outcome in NETWORK_ERRORS for h in o.hosts)
+ ok_hosts = {h for o in fetches if o.outcome == "ran" for h in o.hosts}
+ fid = "boundary:fetch_remote"
+ f = self.facts.get(fid)
+ if f is None and failed_hosts:
+ f = EnvFact(fid, "boundary", high=True, params={"hosts": {}})
+ self.facts[fid] = f
+ if f is not None:
+ for h, n in failed_hosts.items():
+ f.params["hosts"][h] = f.params["hosts"].get(h, 0) + n
+ known = set(f.params["hosts"])
+ exercised = any(o.hosts for o in fetches)
+ fired = bool(failed_hosts)
+ if ok_hosts & known:
+ verdict = "contradict"
+ elif failed_hosts:
+ verdict = "confirm"
+ else:
+ verdict = None
+ fold(f, self.now, verdict, fired, exercised, files)
+ verdicts[fid] = (verdict, fired, exercised)
+
+ # ---- EmptyProbe: refs beyond the checkout ----
+ probes = [o for o in by_intent.get("probe_vcs_refs", []) if o.outcome in ("hit", "empty")]
+ fid = "empty_probe:vcs_refs"
+ f = self.facts.get(fid)
+ if f is None and probes:
+ f = EnvFact(fid, "empty_probe", high=True, params={"kinds": {}})
+ self.facts[fid] = f
+ if f is not None:
+ for o in probes:
+ f.params["kinds"][o.probe] = f.params["kinds"].get(o.probe, 0) + 1
+ exercised = bool(probes)
+ fired = exercised
+ if any(o.outcome == "hit" for o in probes):
+ verdict = "contradict"
+ elif probes:
+ verdict = "confirm"
+ else:
+ verdict = None
+ fold(f, self.now, verdict, fired, exercised, files)
+ verdicts[fid] = (verdict, fired, exercised)
+
+ self.last_digest = {"iid": iid, "resolved": resolved, "injected": sorted(injected),
+ "verdicts": verdicts, "n_calls": digest["n_calls"]}
+ self.last_injected = set()
+ self.now += 1
+
+ # ---- persistence -------------------------------------------------------------
+ @staticmethod
+ def _path(root, repo):
+ d = os.path.join(root, STATE_SUBDIR)
+ os.makedirs(d, exist_ok=True)
+ return os.path.join(d, repo.replace("/", "__") + ".json")
+
+ def save(self, root):
+ with open(self._path(root, self.repo), "w", encoding="utf-8") as fh:
+ json.dump({"repo": self.repo, "now": self.now, "opt_tokens": 0.0,
+ "vocab": self.vocab.name,
+ "facts": {k: f.to_dict() for k, f in self.facts.items()}}, fh, indent=2)
+
+ @classmethod
+ def load(cls, repo, root, runner=None, model="agent", vocab=None, max_facts=None,
+ max_tokens=None):
+ self = cls(repo, vocab=vocab, max_facts=max_facts, max_tokens=max_tokens)
+ p = self._path(root, repo)
+ if not os.path.exists(p):
+ return self
+ with open(p, encoding="utf-8") as fh:
+ d = json.load(fh)
+ self.now = d.get("now", 0)
+ self.facts = {k: EnvFact.from_dict(v) for k, v in d.get("facts", {}).items()}
+ return self
+
+ # ---- telemetry ---------------------------------------------------------------
+ def debug_row(self):
+ row = {}
+ for k, f in self.facts.items():
+ row[k] = {"state": f.state, "fire": f"{f.life.fire_num}/{f.life.fire_den}",
+ "rate": round(f.firing_rate(), 2), "inject": f.injectable(),
+ "claim": f.claim()[:120], "family": f.family}
+ row["_profile"] = "envfacts"
+ row["_vocab"] = self.vocab.name
+ if self.last_digest:
+ row["_task"] = self.last_digest
+ return row
diff --git a/tokeneconomizer/microskills/lifecycle.py b/tokeneconomizer/microskills/lifecycle.py
new file mode 100644
index 0000000..e719d41
--- /dev/null
+++ b/tokeneconomizer/microskills/lifecycle.py
@@ -0,0 +1,102 @@
+"""The lifecycle every learned fact goes through, whoever proposed it.
+
+A fact is a CANDIDATE until it is confirmed on K_PROMOTE tasks -- tasks that edited different
+files, for a fact about the code (stable across the repository's history, not one task's
+coincidence); any K_PROMOTE tasks, for a fact about the environment, which does not change with
+the files a task edits (`drift=False`). It is then ACTIVE until a
+recency-weighted score, with contradictions weighted LAMBDA times a confirmation, falls below the
+floor -- or at once, for a high-stakes fact, on one clean contradiction. An ACTIVE fact is
+injected only while it clears the FIRING GATE: the waste it prevents occurred (or, once injected,
+kept being prevented) on at least FIRE_GATE of the tasks that exercised it.
+"""
+import os
+
+# ---- lifecycle knobs (the validated replay constants) ----------------------
+K_PROMOTE = 3 # confirmations (drifted, where drift applies) to promote -> ACTIVE
+GAMMA = 0.8 # recency decay per task-ago
+LAMBDA = 5.0 # contradiction weight (asymmetry: fail toward retirement)
+SCORE_FLOOR = 0.0 # retire ACTIVE when recency score < floor
+HARD_KILL = True # high-stakes fact: single clean contradiction retires now
+FIRE_GATE = 0.40 # inject only if firing rate on this repo >= 40%
+FIRE_MIN_N = 4 # ...measured over at least this many exercised tasks
+
+
+def edited_pyfiles(calls):
+ fs = set()
+ for tool, args, _ in calls:
+ if tool in ("edit", "multiedit", "write", "create", "str_replace_editor"):
+ p = args.get("file_path") or args.get("path") or ""
+ if p.endswith(".py"):
+ fs.add(os.path.basename(p))
+ elif tool == "apply_patch":
+ for p in args.get("paths") or ():
+ if p.endswith(".py"):
+ fs.add(os.path.basename(p))
+ return fs
+
+
+class Lifecycle:
+ def __init__(self, key, high, drift=True):
+ self.key = key
+ self.high = high
+ self.drift = drift # promotion needs confirmations on different files
+ self.state = "CANDIDATE" # CANDIDATE | ACTIVE | RETIRED
+ self.confirms = [] # [(task_idx, [edited_files])]
+ self.contradicts = [] # [task_idx]
+ self.fire_num = 0 # tasks where the waste occurred (fired)
+ self.fire_den = 0 # tasks where the fact was exercised
+ self.promoted_at = None
+ self.retired_at = None
+
+ def to_dict(self):
+ return {"key": self.key, "high": self.high, "drift": self.drift, "state": self.state,
+ "confirms": self.confirms, "contradicts": self.contradicts,
+ "fire_num": self.fire_num, "fire_den": self.fire_den,
+ "promoted_at": self.promoted_at, "retired_at": self.retired_at}
+
+ @classmethod
+ def from_dict(cls, d):
+ f = cls(d["key"], d["high"])
+ f.__dict__.update(d)
+ return f
+
+ def _drifted_confirms(self):
+ if not self.drift:
+ return len(self.confirms)
+ kept = []
+ for idx, fs in self.confirms:
+ fs = set(fs)
+ if not fs or all(len(fs & set(k)) == 0 for _, k in kept):
+ kept.append((idx, fs))
+ return len(kept)
+
+ def score(self, now):
+ s = sum(GAMMA ** (now - i) for i, _ in self.confirms)
+ s -= LAMBDA * sum(GAMMA ** (now - i) for i in self.contradicts)
+ return s
+
+ def firing_rate(self):
+ return (self.fire_num / self.fire_den) if self.fire_den else 0.0
+
+ def injectable(self):
+ """ACTIVE and clears the firing gate -> goes into the rendered manual."""
+ return (self.state == "ACTIVE"
+ and self.fire_den >= FIRE_MIN_N
+ and self.firing_rate() >= FIRE_GATE)
+
+ def update(self, now, verdict, fired, exercised, files):
+ if exercised:
+ self.fire_den += 1
+ if fired:
+ self.fire_num += 1
+ if verdict == "confirm":
+ self.confirms.append((now, sorted(files)))
+ elif verdict == "contradict":
+ self.contradicts.append(now)
+ if self.state == "CANDIDATE":
+ if self._drifted_confirms() >= K_PROMOTE:
+ self.state, self.promoted_at = "ACTIVE", now
+ elif self.state == "ACTIVE":
+ hard = self.high and verdict == "contradict" and HARD_KILL
+ if hard or self.score(now) < SCORE_FLOOR:
+ self.state, self.retired_at = "RETIRED", now
diff --git a/tokeneconomizer/microskills/observe.py b/tokeneconomizer/microskills/observe.py
new file mode 100644
index 0000000..e3c5380
--- /dev/null
+++ b/tokeneconomizer/microskills/observe.py
@@ -0,0 +1,602 @@
+"""What a finished session shows about its environment: classified commands and outcomes.
+
+Each shell command is split into segments, and each segment is classified by INTENT (run the
+interpreter, run the tests, use the package tool, fetch from a host, probe the VCS) and FORM
+(how it was spelled: `python -m pytest`, `/opt/env/bin/python -m pytest`, `cd tests && python
+runtests.py`). Its outcome is read off the output as an environmental error class
+(`module_missing`, `command_missing`, `connection_refused`, ...) or a sign that tests ran.
+Nothing here names a path, a repository or a harness: the words that name intents are a
+`Vocabulary` the domain supplies, so the same reader handles a Python/git and a Node/npm
+repository. `observe_task` returns everything the environment-fact families need from one
+session.
+"""
+import os
+import re
+from dataclasses import dataclass
+
+from ..trace import call_cwds, load_trajectory, strip_rtk_prefix
+from .lifecycle import edited_pyfiles
+
+
+# --------------------------------------------------------------------------------------
+# vocabulary -- the domain-supplied words that name intents (never harness constants)
+# --------------------------------------------------------------------------------------
+@dataclass(frozen=True)
+class Vocabulary:
+ """What the families recognise as an interpreter, a test runner, a package tool, a
+ fetcher, an environment probe. A domain adapter supplies one (`env_vocabulary()`); the
+ families themselves are the same for every vocabulary."""
+ name: str
+ interpreters: frozenset # executables that run the language
+ canonical_interpreter: str # how a shebang-run script is spelled as a form
+ runner_heads: frozenset # bare test-runner executables
+ runner_scripts: tuple # scripts that ARE the runner when an interpreter runs them
+ runner_modules: frozenset # `<interpreter> -m <module>` runners
+ package_tools: frozenset
+ fetch_heads: frozenset = frozenset({"curl", "wget"})
+ env_probe_heads: frozenset = frozenset({"which", "command", "type", "whereis"})
+
+
+PYTHON_GIT = Vocabulary(
+ name="python-git",
+ interpreters=frozenset({"python", "python2", "python3", "pypy", "pypy3"}),
+ canonical_interpreter="python",
+ runner_heads=frozenset({"pytest", "py.test", "tox", "nox", "nosetests", "trial"}),
+ runner_scripts=("runtests.py", "bin/test", "bin/doctest", "manage.py"),
+ runner_modules=frozenset({"pytest", "unittest", "nose", "django", "tox", "nox"}),
+ package_tools=frozenset({"pip", "pip3", "conda", "mamba", "poetry", "pipenv", "uv",
+ "apt", "apt-get"}),
+)
+
+NODE_WEB = Vocabulary(
+ name="node-web",
+ interpreters=frozenset({"node", "nodejs", "deno", "bun", "tsx", "ts-node"}),
+ canonical_interpreter="node",
+ runner_heads=frozenset({"jest", "vitest", "mocha", "playwright", "cypress", "ava",
+ "karma"}),
+ runner_scripts=(),
+ runner_modules=frozenset(),
+ package_tools=frozenset({"npm", "yarn", "pnpm", "corepack", "apt", "apt-get"}),
+)
+
+DEFAULT_VOCAB = PYTHON_GIT
+# Module-level aliases of the default vocabulary, kept for the offline analyses.
+INTERPRETERS = PYTHON_GIT.interpreters
+RUNNER_HEADS = PYTHON_GIT.runner_heads
+RUNNER_SCRIPTS = PYTHON_GIT.runner_scripts
+RUNNER_MODULES = PYTHON_GIT.runner_modules
+PACKAGE_TOOLS = PYTHON_GIT.package_tools
+FETCH_HEADS = PYTHON_GIT.fetch_heads
+GIT_FETCH_SUBS = frozenset({"fetch", "clone", "pull", "ls-remote"})
+GIT_PROBE_SUBS = frozenset({"remote", "branch", "tag", "fsck", "stash", "show-ref",
+ "for-each-ref"})
+ENV_PROBE_HEADS = PYTHON_GIT.env_probe_heads
+PREFIX_HEADS = ("sudo", "env", "time", "exec", "nice", "nohup", "timeout")
+_PASSTHROUGH = frozenset({"cd", "echo", "head", "tail", "cat", "sort", "uniq", "tee", "true",
+ "printf", "less", "more"})
+
+_ACTIVATE_RE = re.compile(r"^(?:source|\.)\s+\S*activate\s+([\w.-]+)\s*$")
+_CD_RE = re.compile(r"^cd\s+(['\"]?)([^\s;&|'\"]+)\1\s*$")
+_CD_FAILED_RE = re.compile(r"\bcd: [^\n]*: (?:No such file or directory|Not a directory)")
+_CONDA_ACTIVATE_RE = re.compile(r"^(?:conda|mamba)\s+activate\s+([\w.-]+)\s*$")
+_CONDA_RUN_RE = re.compile(r"^(?:conda|mamba)\s+run\s+(?:--no-capture-output\s+|--live-stream\s+)*"
+ r"(?:-n|--name)\s+([\w.-]+)\s+")
+_TOOL_RUN_RE = re.compile(r"^(poetry|pipenv|uv|npx|bundle|yarn|pnpm)\s+(?:run|exec)\s+")
+_NPX_RE = re.compile(r"^npx\s+(?:(?:--yes|-y|--no-install|--no)\s+)*")
+_INTERP_VERSIONED_RE = re.compile(r"^(?:python|node)\d(?:\.\d+)?$")
+_ENV_ASSIGN_RE = re.compile(r"^(?:[A-Za-z_][A-Za-z0-9_]*=(?:\"[^\"]*\"|'[^']*'|\S+)\s+)+")
+_ASSIGN_TOKEN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
+_WRAP_RE = re.compile(r"^/bin/(?:ba)?sh\s+-l?c\s+(.*)$", re.S)
+_HEREDOC_RE = re.compile(r"<<-?\s*['\"]?(\w+)['\"]?[^\n]*\n.*?\n\s*\1\b", re.S)
+_URL_HOST_RE = re.compile(r"https?://([^/\s'\"`]+)")
+
+# Error classes an ENVIRONMENT produces (as opposed to the code under test). Order matters:
+# the first match names the class.
+ERROR_CLASSES = (
+ ("module_missing", re.compile(r"ModuleNotFoundError|No module named|Cannot find module|"
+ r"ERR_MODULE_NOT_FOUND", re.I)),
+ ("command_missing", re.compile(r"command not found|: not found\b|is not recognized", re.I)),
+ # The interpreter started, but the script it was told to run is not where it looked:
+ # `python runtests.py` outside the directory that has it.
+ ("script_missing", re.compile(r"can't open file .*No such file or directory", re.I)),
+ ("permission_denied", re.compile(r"Permission denied|EACCES", re.I)),
+ ("usage_error", re.compile(r"(?m)^usage:|unrecognized arguments|no such option|"
+ r"error: argument|unknown option", re.I)),
+ ("connection_refused", re.compile(r"Connection refused|Failed to connect to|"
+ r"couldn't connect to|Could not connect|ECONNREFUSED", re.I)),
+ ("name_resolution", re.compile(r"Could not resolve host|Temporary failure in name "
+ r"resolution|Name or service not known|getaddrinfo|"
+ r"nodename nor servname|ENOTFOUND", re.I)),
+ ("unreachable", re.compile(r"Network is unreachable|No route to host|Connection timed out|"
+ r"Operation timed out|timed out after|ETIMEDOUT", re.I)),
+)
+NETWORK_ERRORS = frozenset({"connection_refused", "name_resolution", "unreachable"})
+FORM_ERRORS = frozenset({"module_missing", "command_missing", "script_missing",
+ "usage_error", "permission_denied"})
+
+# What "the probe returned something" looks like, per VCS probe kind. Deliberately narrow
+# patterns so the output of an unrelated segment in a compound command cannot masquerade
+# as a hit.
+_PROBE_HIT = {
+ "remote": re.compile(r"(?m)^\S+\s+\S+\s+\((?:fetch|push)\)\s*$"),
+ "branch": re.compile(r"(?m)^\s*remotes/\S+"),
+ "tag": re.compile(r"(?m)^v?\d+(?:\.\d+)+(?:[a-z]+\d*|\.post\d+|-\S+)?\s*$"),
+ "fsck": re.compile(r"(?m)^(?:unreachable|dangling)\s+(?:commit|tree|blob|tag)\s+[0-9a-f]{7,}"),
+ "stash": re.compile(r"(?m)^stash@\{\d+\}"),
+ "refs": re.compile(r"(?m)^[0-9a-f]{7,}\s+refs/"),
+}
+
+
+# --------------------------------------------------------------------------------------
+# observations
+# --------------------------------------------------------------------------------------
+def unwrap(cmd):
+ """Strip an agent's `/bin/bash -lc "<cmd>"` wrapper, if present."""
+ cmd = cmd or ""
+ m = _WRAP_RE.match(cmd.strip())
+ if not m:
+ return cmd
+ inner = m.group(1).strip()
+ if len(inner) >= 2 and inner[0] == inner[-1] and inner[0] in "\"'":
+ q = inner[0]
+ inner = inner[1:-1]
+ if q == '"':
+ inner = inner.replace('\\"', '"').replace("\\$", "$").replace("\\\\", "\\")
+ return inner
+
+
+def segments(cmd):
+ """Split a shell command into simple segments on && || ; | and newlines, outside quotes.
+ Heredoc bodies are elided first so their contents are never mistaken for commands."""
+ cmd = _HEREDOC_RE.sub(lambda m: m.group(0).split("\n", 1)[0] + " <heredoc>", cmd or "")
+ out, buf, q, i = [], [], None, 0
+ while i < len(cmd):
+ c = cmd[i]
+ if q:
+ buf.append(c)
+ if c == q:
+ q = None
+ elif c == "\\" and i + 1 < len(cmd):
+ buf.append(cmd[i + 1]); i += 1
+ elif c in "\"'":
+ q = c; buf.append(c)
+ elif c == "\n" or c == ";" or c == "|" or (c == "&" and cmd[i:i + 2] == "&&"):
+ out.append("".join(buf)); buf = []
+ if cmd[i:i + 2] in ("&&", "||"):
+ i += 1
+ else:
+ buf.append(c)
+ i += 1
+ out.append("".join(buf))
+ return [s.strip().strip("()").strip() for s in out if s.strip().strip("()").strip()]
+
+
+def _tokens(seg):
+ return seg.split()
+
+
+class Observation:
+ """One classified command segment."""
+ __slots__ = ("call", "intent", "form", "head", "prefix", "hosts", "probe", "outcome",
+ "segment", "labels", "label_err", "loaded", "tests_ran", "env")
+
+ def __init__(self, call, intent, form, head, prefix, segment, hosts=(), probe=None):
+ self.call, self.intent, self.form, self.head, self.prefix = call, intent, form, head, prefix
+ self.segment, self.hosts, self.probe, self.outcome = segment, tuple(hosts), probe, None
+ self.labels, self.label_err, self.loaded = (), False, False
+ self.tests_ran = False
+ self.env = False # typed with `VAR=value` before it, which its form leaves out
+
+ def __repr__(self):
+ return f"Obs({self.intent},{self.form!r},{self.outcome})"
+
+
+def _cd_target(cur, target, root=None):
+ """Where `cd target` from `cur` lands, relative to the directory the session started in
+ ("" for that directory itself); None when it leaves it or cannot be told (`~`, `$VAR`,
+ `-`, an absolute path with no known start)."""
+ if not target or target[0] in "~$-":
+ return None
+ if os.path.isabs(target):
+ if not root:
+ return None
+ rel = os.path.relpath(os.path.normpath(target), os.path.normpath(root))
+ else:
+ rel = os.path.normpath(os.path.join(cur or ".", target))
+ if rel == ".":
+ return ""
+ return None if rel == ".." or rel.startswith("../") else rel
+
+
+def classify_command(cmd, call_index=0, vocab=None, cwd="", root=None):
+ """Observations for one shell command (possibly compound). Activation prefixes carry
+ across the segments of one command, which is how `source activate X && python ...`
+ becomes a single form. `vocab` names the domain's intents (default Python/git).
+
+ `cwd` is the directory the command started in, relative to the one the session started
+ in (`root`, an absolute path when known): a shell that keeps its directory between calls
+ runs a bare `python runtests.py` in `tests/` after an earlier `cd tests`, and that is the
+ same form as `cd tests && python runtests.py` typed at the start."""
+ vocab = vocab or DEFAULT_VOCAB
+ obs = []
+ carried = ""
+ here = cwd or ""
+ cd = f"cd {here} &&" if here else ""
+ for seg in segments(unwrap(cmd)):
+ # Transparent wrappers first: `K=V rtk pytest`, `rtk K=V pytest` and `rtk proxy pytest`
+ # are all a pytest run. rtk's Codex mode puts that prefix on every command the agent
+ # types (trace.strip_rtk_prefix), and a first-token vocabulary that did not remove it
+ # would form no fact at all on the very arm that stacks injection on rtk.
+ typed = seg.strip()
+ seg = _ENV_ASSIGN_RE.sub("", typed).strip()
+ assigned = seg != typed
+ unwrapped = strip_rtk_prefix(seg).strip()
+ seg = _ENV_ASSIGN_RE.sub("", unwrapped).strip()
+ assigned = assigned or seg != unwrapped
+ if not seg:
+ continue
+ # A directory change is part of how the rest of the command runs: `cd tests && python
+ # runtests.py` works where a bare `python runtests.py` does not, so it is carried into
+ # the forms that follow, as an activation is.
+ m = _CD_RE.match(seg)
+ if m:
+ there = _cd_target(here, m.group(2), root) if here is not None else None
+ if there is None:
+ here, cd = None, f"cd {m.group(2)} &&"
+ else:
+ here, cd = there, (f"cd {there} &&" if there else "")
+ continue
+ m = _ACTIVATE_RE.match(seg) or _CONDA_ACTIVATE_RE.match(seg)
+ if m:
+ carried = f"{seg.split()[0] if seg.startswith(('conda', 'mamba')) else 'source'} activate {m.group(1)} &&"
+ if carried.startswith("conda") or carried.startswith("mamba"):
+ carried = f"conda activate {m.group(1)} &&"
+ continue
+ prefix = " ".join(x for x in (cd, carried) if x)
+ body = seg
+ m = _CONDA_RUN_RE.match(body)
+ if m:
+ prefix = (prefix + " " if prefix else "") + f"conda run -n {m.group(1)}"
+ body = body[m.end():]
+ m = _TOOL_RUN_RE.match(body)
+ if m:
+ prefix = (prefix + " " if prefix else "") + f"{m.group(1)} run"
+ body = body[m.end():]
+ else:
+ m = _NPX_RE.match(body)
+ if m and m.end() > 0:
+ prefix = (prefix + " " if prefix else "") + "npx"
+ body = body[m.end():]
+ toks = _tokens(body)
+ while toks and (toks[0] in PREFIX_HEADS or _ASSIGN_TOKEN_RE.match(toks[0])):
+ if _ASSIGN_TOKEN_RE.match(toks[0]): # `env VAR=value cmd`
+ assigned, toks = True, toks[1:]
+ else:
+ toks = toks[1:] if toks[0] != "timeout" else toks[2:]
+ if not toks:
+ continue
+ head = toks[0]
+ base = head.rsplit("/", 1)[-1]
+ rest = toks[1:]
+ o = _classify(head, base, rest, body, prefix, seg, call_index, vocab)
+ if o is not None:
+ o.env = assigned
+ obs.append(o)
+ return obs
+
+
+def _runner_script(rest, vocab):
+ for t in rest:
+ if t.startswith("-"):
+ continue
+ for s in vocab.runner_scripts:
+ if t == s or t.endswith("/" + s) or t.endswith(s):
+ return t.lstrip("./") if t.startswith("./") else t
+ return None
+ return None
+
+
+def _classify(head, base, rest, body, prefix, seg, call, vocab):
+ def form(expr):
+ return (prefix + " " + expr).strip() if prefix else expr
+
+ if base in vocab.interpreters or _INTERP_VERSIONED_RE.match(base):
+ if rest and all(t in ("--version", "-V", "-VV", "-v") for t in rest):
+ return Observation(call, "probe_env", form(head), head, prefix, seg)
+ if "-m" in rest:
+ mod = rest[rest.index("-m") + 1] if rest.index("-m") + 1 < len(rest) else ""
+ if mod in vocab.runner_modules:
+ return Observation(call, "run_tests", form(f"{head} -m {mod}"), head, prefix, seg)
+ script = _runner_script(rest, vocab)
+ if script and (script != "manage.py" or "test" in rest):
+ return Observation(call, "run_tests", form(f"{head} {script}"), head, prefix, seg)
+ return Observation(call, "run_interpreter", form(head), head, prefix, seg)
+ if base in vocab.runner_heads:
+ return Observation(call, "run_tests", form(head), head, prefix, seg)
+ for s in vocab.runner_scripts:
+ if head == s or head.endswith("/" + s) or head == "./" + s:
+ if s == "manage.py" and "test" not in rest:
+ break
+ # A script run through its shebang is the interpreter running it; spell the
+ # form that way so `./tests/runtests.py` and `python tests/runtests.py` pool.
+ return Observation(call, "run_tests",
+ form(f"{vocab.canonical_interpreter} " + head.lstrip("./")),
+ head, prefix, seg)
+ if base in ("make", "npm", "yarn", "pnpm", "cargo", "go") and rest and rest[0] == "test":
+ return Observation(call, "run_tests", form(f"{base} test"), head, prefix, seg)
+ if base in vocab.env_probe_heads:
+ return Observation(call, "probe_env", form(base), head, prefix, seg)
+ if base in vocab.fetch_heads:
+ return Observation(call, "fetch_remote", form(base), head, prefix, seg,
+ hosts=_URL_HOST_RE.findall(body))
+ if base == "git" and rest:
+ sub = rest[0]
+ if sub in GIT_FETCH_SUBS:
+ return Observation(call, "fetch_remote", form(f"git {sub}"), head, prefix, seg,
+ hosts=_URL_HOST_RE.findall(body))
+ if sub in GIT_PROBE_SUBS:
+ kind = _probe_kind(sub, rest[1:])
+ if kind:
+ return Observation(call, "probe_vcs_refs", form(f"git {sub}"), head, prefix,
+ seg, probe=kind)
+ return None
+ if base in vocab.package_tools:
+ if base.startswith(("pip", "npm", "yarn", "pnpm")) and rest and rest[0] in (
+ "install", "download", "add", "ci"):
+ hosts = _URL_HOST_RE.findall(body)
+ return Observation(call, "fetch_remote", form(f"{base} {rest[0]}"), head, prefix,
+ seg, hosts=hosts)
+ return Observation(call, "package_tool", form(base), head, prefix, seg)
+ return None
+
+
+def _probe_kind(sub, args):
+ a = set(args)
+ if sub == "remote":
+ return "remote"
+ if sub == "branch" and a & {"-a", "-r", "--all", "--remotes", "-ar", "-ra"}:
+ return "branch"
+ if sub == "tag" and "--contains" in a: # plain `git tag` lists PAST tags too
+ return "tag"
+ if sub == "fsck":
+ return "fsck"
+ if sub == "stash" and args[:1] == ["list"]:
+ return "stash"
+ if sub in ("show-ref", "for-each-ref"):
+ return "refs"
+ return None
+
+
+def error_class(output):
+ for name, rx in ERROR_CLASSES:
+ if rx.search(output or ""):
+ return name
+ return None
+
+
+def _exit_code_hint(output):
+ m = re.search(r"(?i)\bexit code[:=\s]+(\d+)", output or "")
+ return int(m.group(1)) if m else None
+
+
+# The runner could not load a test label: the module, file or name it names does not resolve.
+# Read off the output rather than the exit code -- agents pipe test runs through `| tail`.
+_LABEL_ERR_RE = re.compile(r"Failed to import test module|unittest\.loader\._FailedTest|"
+ r"ERROR: (?:file or directory )?not found|no tests ran|"
+ r"module '[\w.]+' has no attribute", re.I)
+_NO_MODULE_RE = re.compile(r"No module named ['\"]?([\w.]+)")
+
+
+def _label_failed(labels, out):
+ """Did the runner fail to load one of these labels? Either it says so, or the module it
+ cannot import is the label's own (`tests` for `tests.app`) -- a missing `pytest` is not."""
+ if _LABEL_ERR_RE.search(out or ""):
+ return True
+ heads = {re.split(r"[./:]", lab, 1)[0] for lab in labels}
+ return any(m.group(1).split(".")[0] in heads for m in _NO_MODULE_RE.finditer(out or ""))
+
+
+# ... and positive evidence that it loaded: tests actually ran. Output an agent filtered away
+# (`| grep FAILED`, a silent run) proves nothing either way.
+_LOADED_RE = re.compile(r"\bRan [1-9]\d* tests?\b|\b[1-9]\d* (?:passed|failed|passing|failing)\b|"
+ r"\bcollected [1-9]\d* items?\b")
+# Code asking for an environment variable by name, and the ways a command sets one.
+_ENV_NEED_RE = re.compile(r"environment variable\s+['\"`]?([A-Z][A-Z0-9_]{2,})")
+_ENV_PREFIX_RE = re.compile(r"(?:^|[\s;&(])(?:export\s+)?([A-Z][A-Z0-9_]{2,})=(['\"]?)([\w.\-/:]+)\2")
+_ENV_INCODE_RE = re.compile(r"os\.environ(?:\.setdefault\(\s*|\[\s*)['\"]([A-Z][A-Z0-9_]{2,})['\"]"
+ r"\s*(?:,|\]\s*=)\s*['\"]([\w.\-/:]+)['\"]")
+_FAILED_RE = re.compile(r"Traceback \(most recent call last\)|^\w*Error\b|"
+ r"\b[Ee]xit [Cc]ode[:=\s]+[1-9]", re.M)
+
+
+_LABEL_TOKEN_RE = re.compile(r"^[A-Za-z_][\w.\-/]*(?:::[\w.\-\[\]]+)*$")
+
+
+def _test_labels(o):
+ """The test labels a runner observation was given: positional arguments after the runner's
+ own token that look like a module, a path or a test id. A plain name right after an option
+ is taken to be that option's value (`-k name`), so it is not a label."""
+ toks = _tokens(o.segment)
+ last = (o.form.split() or [""])[-1]
+ start = next((i + 1 for i, t in enumerate(toks)
+ if t == last or t.lstrip("./") == last or t.endswith("/" + last)), len(toks))
+ out, skip, prev = [], False, ""
+ for t in toks[start:]:
+ if skip:
+ skip, prev = False, t
+ continue
+ if t in (">", ">>", "2>", "<", "|") or t.startswith(("2>", ">", "<", "|")):
+ skip = t in (">", ">>", "2>", "<")
+ prev = t
+ continue
+ structured = any(c in t for c in (".", "::", "/"))
+ after_option = prev.startswith("-") and "=" not in prev
+ if (not t.startswith("-") and _LABEL_TOKEN_RE.match(t)
+ and (structured or not after_option)):
+ out.append(t)
+ prev = t
+ return tuple(out)
+
+
+def label_rule(a, b):
+ """("sep", "::") or ("strip", prefix) when label `b` is label `a` rewritten into the shape the
+ runner loads, else None."""
+ if "::" in a and "::" not in b:
+ da = a.replace("::", ".")
+ if b == da or da.startswith(b + ".") or b.startswith(da + "."):
+ return ("sep", "::")
+ for sep in (".", "/"):
+ if sep not in a:
+ continue
+ p = a.split(sep, 1)[0] + sep
+ rest = a[len(p):]
+ if rest and not b.startswith(p) and (
+ b == rest or rest.startswith(b + sep) or b.startswith(rest + sep)):
+ return ("strip", p)
+ return None
+
+
+def _env_calls(cmd, out, success):
+ """What one call says about environment variables: those its output asks for, and those
+ its command sets (inline, exported or in the code it runs)."""
+ sets = {m.group(1): m.group(3) for m in _ENV_PREFIX_RE.finditer(cmd)}
+ sets.update({m.group(1): m.group(2) for m in _ENV_INCODE_RE.finditer(cmd)})
+ return {"need": sorted(set(_ENV_NEED_RE.findall(out or ""))), "sets": sets,
+ "ok": bool(success) and not _FAILED_RE.search(out or "")}
+
+
+def form_failed(o):
+ """Did this run show that the way the command was CALLED fails here? Not when the runner
+ started and rejected what it was given: a label it could not load (Django reports one as a
+ ModuleNotFoundError) or an option it does not take (`-k` to Django's runner) is a mistake
+ in the arguments, and once taught "`python tests/runtests.py` fails" from mistyped labels."""
+ if o.outcome not in FORM_ERRORS or o.label_err:
+ return False
+ return not (o.intent == "run_tests" and o.outcome == "usage_error")
+
+
+def form_worked(o):
+ """Did this run show the form works? A test run must show tests running: one whose
+ output was filtered away (`| grep -E "^(OK|FAILED)"` around a "can't open file") or that
+ stopped before any test proves nothing."""
+ return o.outcome == "ran" and (o.intent != "run_tests" or o.tests_ran)
+
+
+def observe_task(transcript_path, vocab=None):
+ """Per-task digest: observations with outcomes, the edited files, the call count.
+
+ Outcome attribution inside a compound command is heuristic and conservative: an
+ infrastructure error is attributed to the segment whose executable the error names, else
+ to the last relevant segment; a call that succeeded marks every relevant segment as
+ having run; a failed call with no infrastructure error marks only the first relevant
+ segment as having run and leaves the others unknown (an `&&` chain may not have reached
+ them)."""
+ calls = load_trajectory(transcript_path)
+ cwds = call_cwds(transcript_path)
+ root = next((c for c in cwds if c), None)
+ obs_all = []
+ triples = []
+ env_calls = []
+ for idx, (name, args, out, ok) in enumerate(calls):
+ tool = (name or "").lower()
+ triples.append((tool, args if isinstance(args, dict) else {}, out or ""))
+ if tool not in ("shell", "bash", "stop_bash"):
+ continue
+ cmd = (args.get("command") or args.get("cmd") or "") if isinstance(args, dict) else ""
+ out = out or ""
+ if _CD_FAILED_RE.search(out):
+ continue # stopped at its `cd`: nothing after it ran
+ here = ""
+ if root and idx < len(cwds) and cwds[idx]:
+ here = _cd_target("", cwds[idx], root)
+ here = here if here is not None else None
+ if here is None:
+ # Started outside the session's directory: its own `cd`s are taken as typed.
+ obs = classify_command(cmd, idx, vocab)
+ else:
+ obs = classify_command(cmd, idx, vocab, cwd=here, root=root)
+ if "python" in cmd or "=" in cmd:
+ ec = _env_calls(cmd, out, ok if _exit_code_hint(out) is None else
+ _exit_code_hint(out) == 0)
+ if ec["need"] or ec["sets"]:
+ env_calls.append(dict(ec, call=idx))
+ if not obs:
+ continue
+ for o in obs:
+ if o.intent == "run_tests":
+ o.labels = _test_labels(o)
+ o.label_err = bool(o.labels) and _label_failed(o.labels, out)
+ o.loaded = bool(o.labels) and not o.label_err and bool(_LOADED_RE.search(out))
+ o.tests_ran = bool(_LOADED_RE.search(out))
+ # Pass-through segments (a leading `cd`, a trailing `| head`, an `echo ---`
+ # separator) neither add evidence nor pollute the output, so they do not break a
+ # call's homogeneity; filters that rewrite content (grep, sed, awk, wc) do.
+ n_seg = sum(1 for sg in segments(unwrap(cmd))
+ if (sg.split() or [""])[0].rsplit("/", 1)[-1] not in _PASSTHROUGH)
+ homogeneous = n_seg == len(obs) and len({o.intent for o in obs}) == 1
+ hint = _exit_code_hint(out)
+ success = bool(ok) if hint is None else (hint == 0)
+ err = error_class(out)
+ if err in FORM_ERRORS or err in NETWORK_ERRORS:
+ targets = [o for o in obs if o.intent in ("run_interpreter", "run_tests",
+ "package_tool", "fetch_remote")]
+ named = [o for o in targets
+ if (o.head and o.head in out) or (o.head and o.head.rsplit("/", 1)[-1] in
+ _error_line(out, err))]
+ if err in NETWORK_ERRORS:
+ named = [o for o in targets if o.intent == "fetch_remote"
+ and (not o.hosts or any(h in out for h in o.hosts))] or \
+ [o for o in targets if o.intent == "fetch_remote"]
+ chosen = named or (targets[-1:] if not success else [])
+ for o in chosen:
+ o.outcome = err
+ if success:
+ for o in obs:
+ if o.outcome is None:
+ o.outcome = "ran"
+ elif success:
+ for o in obs:
+ o.outcome = "ran"
+ else:
+ first = True
+ for o in obs:
+ if o.intent in ("run_interpreter", "run_tests", "package_tool", "fetch_remote"):
+ o.outcome = "ran" if first else None
+ first = False
+ else:
+ o.outcome = "ran" if o.intent != "probe_vcs_refs" else None
+ for o in obs:
+ if o.intent == "probe_vcs_refs":
+ # Judged only when every segment of the call is a probe: another segment's
+ # output (a `git describe`, a `sed`) would otherwise be read as the probe's.
+ if not homogeneous:
+ o.outcome = None
+ else:
+ o.outcome = "hit" if _PROBE_HIT[o.probe].search(out) else (
+ "empty" if success else None)
+ if o.intent == "fetch_remote" and o.outcome == "ran":
+ # Reachability needs a homogeneous call that exited 0 with real output and no
+ # network error; a compound command's exit code and output belong to its
+ # last segment, not to the fetch.
+ if not homogeneous or not success or not out.strip() or err in NETWORK_ERRORS:
+ o.outcome = None
+ obs_all.extend(obs)
+ return {"obs": obs_all, "edited": sorted(edited_pyfiles(triples)), "n_calls": len(calls),
+ "env": env_calls}
+
+
+def _error_line(out, err):
+ rx = dict(ERROR_CLASSES)[err]
+ m = rx.search(out or "")
+ if not m:
+ return ""
+ start = (out or "").rfind("\n", 0, m.start()) + 1
+ end = (out or "").find("\n", m.end())
+ return (out or "")[start:end if end >= 0 else None]
+
+
+def is_bare(form):
+ """A form with no activation prefix and no explicit path is 'bare'."""
+ head = form.split()[0] if form else ""
+ return "/" not in head and " activate " not in form and " run " not in form and \
+ not form.startswith(("conda run", "poetry run", "pipenv run", "uv run", "npx "))
diff --git a/tokeneconomizer/microskills/stage.py b/tokeneconomizer/microskills/stage.py
new file mode 100644
index 0000000..3208688
--- /dev/null
+++ b/tokeneconomizer/microskills/stage.py
@@ -0,0 +1,131 @@
+"""`PrefixStage`: the micro-skill lifecycle hook -- render before a session, learn after it.
+
+It builds the distiller the profile names -- the LLM-free environment facts (`envfacts`), the
+paid proposer (`distiller`), or both (`envfacts+distiller`, the free layer first and its claims
+handed to the proposer as already stated) -- renders its block for the next session, and folds
+each finished session back in, reporting the paid proposer's cost for that session.
+"""
+import os
+
+from ..stage import Stage
+from . import distiller as _distiller
+from .distiller import Distiller
+
+
+# ---- composition: the free environment layer under the paid manual -------------------
+class ComposedDistiller:
+ """`envfacts` first, the paid manual on top, driven as one distiller.
+
+ The environment layer renders first (its block is what the proposer is told not to
+ restate); both fold every finished task; each persists in its own state dir. Overhead is
+ the proposer's alone -- the environment layer is LLM-free by construction."""
+ def __init__(self, env, dist):
+ self.env, self.dist = env, dist
+
+ @property
+ def opt_tokens(self):
+ return self.dist.opt_tokens
+
+ @property
+ def now(self):
+ return self.dist.now
+
+ def render(self, task=None):
+ a = self.env.render(task)
+ b = self.dist.render(task)
+ return (a + ("\n" if a and b else "") + b) if (a or b) else ""
+
+ def injected_ids(self):
+ return self.env.injected_ids()
+
+ def seed_injected(self, ids):
+ self.env.seed_injected(ids)
+
+ def update(self, transcript_path, iid="", resolved=None, edited=None):
+ self.env.update(transcript_path, iid=iid, resolved=resolved, edited=edited)
+ self.dist.update(transcript_path, iid=iid, resolved=resolved, edited=edited)
+
+ def save(self, root):
+ self.env.save(root)
+ self.dist.save(root)
+
+ def debug_row(self):
+ row = dict(self.dist.debug_row())
+ row.update(self.env.debug_row())
+ row["_profile"] = "envfacts+distiller"
+ return row
+
+
+# ---- lifecycle stage -------------------------------------------------------
+class PrefixStage(Stage):
+ """Injection lifecycle hook: render the manual before a task, fold the finished
+ task back into the distiller after it, and report the paid proposer's per-task
+ token delta for the amortized ledger."""
+ name = "prefix"
+
+ def __init__(self, cfg, repo, results_root, fresh,
+ runner=None, optimizer_model="agent", adapter=None, agent=None):
+ self.results_root = results_root
+ self.adapter = adapter
+ self.agent = agent
+ # The Distiller is the single source of truth for the proposer cadence: rebind
+ # the module global that update()'s gate reads (process-local, idempotent).
+ pe = int(getattr(cfg, "propose_every", 0) or 0)
+ if pe > 0:
+ _distiller.PROPOSE_EVERY = pe
+ profile = getattr(cfg, "profile", "distiller") or "distiller"
+ # The environment-fact layer reads intents through a domain vocabulary; the adapter
+ # supplies it when it has one (SWE-bench: Python/git; Web-Bench: Node/npm).
+ vocab = adapter.env_vocabulary() if hasattr(adapter, "env_vocabulary") else None
+ env = None
+ if "envfacts" in profile:
+ from .envfacts import EnvFactsDistiller
+ caps = {"max_facts": getattr(cfg, "max_facts", 0) or None,
+ "max_tokens": getattr(cfg, "max_tokens", 0) or None}
+ env = (EnvFactsDistiller(repo, vocab=vocab, **caps) if fresh
+ else EnvFactsDistiller.load(repo, results_root, vocab=vocab, **caps))
+ if profile == "envfacts":
+ # LLM-free environment facts alone. Same render/update/save interface, no
+ # runner, opt_tokens stays 0 -- the ledger sees no overhead.
+ self.reason = "envfacts"
+ self.distiller = env
+ else:
+ # The paid proposer; with `envfacts+distiller` it is told which claims the free
+ # layer already injects, so it authors only facts beyond them.
+ external = env.injectable_claims if env is not None else None
+ dist = (Distiller(repo, runner=runner, model=optimizer_model,
+ external_facts=external) if fresh
+ else Distiller.load(repo, results_root, runner=runner,
+ model=optimizer_model, external_facts=external))
+ if env is not None:
+ self.reason = "envfacts+manual-distill"
+ self.distiller = ComposedDistiller(env, dist)
+ else:
+ self.reason = "manual-distill"
+ self.distiller = dist
+
+ def render(self, task=None):
+ """The firing-gated repo manual injected into the NEXT task's prefix."""
+ return self.distiller.render(task=task) if self.distiller else ""
+
+ def injected_ids(self):
+ """The environment facts the last `render` chose, [] without that layer."""
+ get = getattr(self.distiller, "injected_ids", None)
+ return get() if get else []
+
+ def after_task(self, task, row, run_dir_path, srow):
+ """Fold the finished task into the fact lifecycle; return (opt_tokens, reason).
+ The paid proposer accrues cumulatively on distiller.opt_tokens; capture THIS
+ task's delta for the per-task ledger (same effective-token basis). A task that names
+ `injected_ids` says which environment facts it was given (see `seed_injected`)."""
+ transcript = os.path.join(run_dir_path, "transcript.jsonl")
+ seed = getattr(self.distiller, "seed_injected", None)
+ if seed and task.get("injected_ids") is not None:
+ seed(task["injected_ids"])
+ before = self.distiller.opt_tokens
+ self.distiller.update(transcript, iid=task["instance_id"],
+ resolved=srow.get("resolved"))
+ self.distiller.save(self.results_root)
+ opt_tokens = self.distiller.opt_tokens - before
+ srow["manual_facts"] = self.distiller.debug_row()
+ return opt_tokens, self.reason
diff --git a/tokeneconomizer/plugin/README.md b/tokeneconomizer/plugin/README.md
new file mode 100644
index 0000000..768dde4
--- /dev/null
+++ b/tokeneconomizer/plugin/README.md
@@ -0,0 +1,32 @@
+# Plugin runtime
+
+What the plugin's hooks and the `te` command run. The agent launches itself; this package runs
+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` |
+
+| Module | |
+|---|---|
+| `hook.py`, `cli.py` | entry points: the hook dispatcher and `te` |
+| `controller.py` | what happens at each hook |
+| `hosts.py` | per-agent hook payloads and outputs (Claude Code, Codex, Copilot CLI, Pi) |
+| `fold.py` | a finished session through `PrefixStage` and `ToolingStage` |
+| `denylist.py` | writing an approved proposal into each agent's settings, and taking it back |
+| `toolcheck.py` | asking the agent CLIs what a session loads, and what a deny list removed |
+| `config.py` | settings, their sources, and the earlier names they are still read under |
+| `context.py`, `paths.py`, `store.py` | where state lives, which repository a session is in, locked atomic JSON |
+| `adapter.py` | the `DomainAdapter` for a real repository |
+| `accounting.py` | the session ledger |
+| `sidecall.py`, `judge.py` | opt-in paid calls through the agent's own CLI, off the hook's critical path |
+| `repomap.py`, `repomap_gen.py` | the opt-in repository map |
+| `probe.py` | `te --host copilot probe`: the plugin end to end in real Copilot sessions |
+
+The installable plugin directory -- manifests, hook files and launchers -- is `plugin/` at the
+repository root; see `plugin/README.md` there and `docs/PLUGIN.md`.
diff --git a/tokeneconomizer/plugin/__init__.py b/tokeneconomizer/plugin/__init__.py
new file mode 100644
index 0000000..bfe5e1a
--- /dev/null
+++ b/tokeneconomizer/plugin/__init__.py
@@ -0,0 +1,29 @@
+"""The plugin runtime: the three mechanisms inside a person's own sessions, through the hooks
+each agent already exposes.
+
+The agent launches itself; this package runs only when the agent calls a hook, each call a
+fresh, short-lived process. So what is learned lives on disk, and every handler returns fast and
+fails open.
+
+ * state -- `paths`, `store`, `config`, `context`: per-repository, per-agent state that
+ survives hook processes, sessions and plugin updates;
+ * agents -- `hosts`: hook payloads in, hook outputs out, for Claude Code, Codex, Copilot
+ CLI and Pi; `adapter`: the `DomainAdapter` for a real repository;
+ * at each hook -- `controller`: inject the learned facts at session start, guard each
+ prompt-turn call by call, and hand a finished session to `fold`;
+ * after a session -- `fold`: run `PrefixStage` and `ToolingStage` over the finished session,
+ off the agent's critical path; `denylist` writes an approved proposal into
+ the agent's own settings file;
+ * paid, opt-in -- `sidecall`, `judge`: LLM calls through the agent's own CLI, charged to the
+ session's ledger (`accounting`);
+ * commands -- `hook.main` (what the hooks execute) and `cli.main` (`te`), with
+ `toolcheck`, `repomap` and `probe` behind it.
+
+What differs from a benchmark run is written down where it differs: there is no grader, so the
+loop guard's envelope learns from a "turn ended green" proxy; a "task" is a session for the
+facts and for pruning but a prompt-turn for the guard; a pruned tool leaves through a deny list
+the person approves, from the next session on; a redirect is attached to a tool result mid-turn.
+
+Stdlib only: a hook must start in tens of milliseconds and depend on nothing the person did not
+install. See docs/PLUGIN.md.
+"""
diff --git a/te_live/accounting.py b/tokeneconomizer/plugin/accounting.py
similarity index 89%
rename from te_live/accounting.py
rename to tokeneconomizer/plugin/accounting.py
index 46d4279..6d977b5 100644
--- a/te_live/accounting.py
+++ b/tokeneconomizer/plugin/accounting.py
@@ -9,8 +9,7 @@ corrupts a comparison). A user's session must still be recorded, so an unpriced
a labelled fallback curve and the record says `priced_by: "fallback"`; Claude ids never need it,
because every `claude-*` id already resolves to the Claude curve.
"""
-from tokeneconomizer import ledger
-from tokeneconomizer.vendor import pricing
+from .. import ledger, pricing
FALLBACK_WEIGHTS = dict(input=1.0, cache_read=0.10, cache_write=1.25, output=6.0)
@@ -52,3 +51,14 @@ def summarize(records):
"turns": sum(int(r.get("turns") or 0) for r in sessions),
"injected_sessions": sum(1 for r in sessions if r.get("injected_chars")),
}
+
+
+def fmt_tokens(n):
+ """A token count as a person reads it: 1.2M, 340k, 512."""
+ if n is None:
+ return "n/a"
+ n = float(n)
+ for unit, div in (("B", 1e9), ("M", 1e6), ("k", 1e3)):
+ if abs(n) >= div:
+ return f"{n / div:.1f}{unit}"
+ return f"{n:.0f}"
diff --git a/te_live/adapter.py b/tokeneconomizer/plugin/adapter.py
similarity index 80%
rename from te_live/adapter.py
rename to tokeneconomizer/plugin/adapter.py
index ecee7a2..9d79519 100644
--- a/te_live/adapter.py
+++ b/tokeneconomizer/plugin/adapter.py
@@ -1,18 +1,18 @@
"""`LiveAdapter`: the DomainAdapter for a real repository in a real session.
-The mechanisms read their domain only through a DomainAdapter (`adapters/base.py`), so running
+The mechanisms read their domain only through a DomainAdapter (`tokeneconomizer.domain`), so running
`PrefixStage` and `ToolingStage` on live sessions needs no mechanism edit -- only an adapter whose
answers fit an interactive session instead of a sealed benchmark task:
* `protected_tools` adds what a PERSON needs to the work surface. The benchmark protected set
- keeps Bash/Read/Edit/...; `reflect.INAPPLICABLE_TOOLS` then treats AskUserQuestion, plan
- mode, subagents and the web as inapplicable "by construction" for a headless sealed task. A
- person does use them interactively, so those are protected here -- the web tools always,
- however long they go unused -- and only evidence (loaded but unused for N sessions) can
- propose anything else.
+ keeps Bash/Read/Edit/...; `toolprune.tools.INAPPLICABLE_TOOLS` then treats AskUserQuestion, plan
+ mode and subagents as inapplicable "by construction" for a headless sealed task. A person
+ does use them interactively, so those are protected here, and so are the web tools, however
+ long they go unused; only evidence (loaded but unused for N sessions) can propose anything
+ else.
* `parse_catalog_with_source` reports what the session COULD call. An interactive transcript
does not record the tool list the way `stream-json`'s init event does, so the catalog is the
- union of a probed snapshot (`te untool refresh-catalog`, stored under the state root), the
+ union of a probed snapshot (`te toolprune refresh-catalog`, stored under the state root), the
deferred tools the transcript lists, and the tools it used. Without a snapshot only deferred
tools can be proposed -- they cost one listing line each, so that is honest but small.
* `env_vocabulary` picks the environment-fact vocabulary from the repository's own markers
@@ -22,9 +22,10 @@ answers fit an interactive session instead of a sealed benchmark task:
import json
import os
-from tokeneconomizer import trace
-from tokeneconomizer.vendor import reflect, spiral
-from . import transcripts
+from .. import trace
+from ..loopguard import state_from_trajectory
+from ..microskills import NODE_WEB, PYTHON_GIT
+from ..toolprune.tools import PROTECTED_TOOLS
# Tools a person relies on in an interactive session, beyond the benchmark work surface.
INTERACTIVE_PROTECTED = frozenset({
@@ -40,7 +41,7 @@ INTERACTIVE_PROTECTED = frozenset({
"WebFetch", "WebSearch",
})
# The Copilot CLI's own work surface and a person's tools there (1.0.83 names). Only MCP servers
-# can be removed persistently on Copilot (`untool.copilot_server_proposal`), so this matters
+# can be removed persistently on Copilot (`denylist.copilot_server_proposal`), so this matters
# for what the evidence reports, not for what can be written.
COPILOT_PROTECTED = frozenset({
"bash", "read_bash", "write_bash", "stop_bash", "list_bash", "view", "edit", "create",
@@ -59,7 +60,6 @@ _NODE_MARKERS = ("package.json",)
def detect_vocabulary(repo_root, preference="auto"):
- from tokeneconomizer.mechanisms.envfacts import NODE_WEB, PYTHON_GIT
if preference == "node-web":
return NODE_WEB
if preference == "python-git":
@@ -75,7 +75,7 @@ def catalog_path(state_root, host):
def load_catalog(state_root, host):
- """{tool: description} from the last `te untool refresh-catalog` probe, {} if none."""
+ """{tool: description} from the last `te toolprune refresh-catalog` probe, {} if none."""
try:
with open(catalog_path(state_root, host), encoding="utf-8") as fh:
data = json.load(fh)
@@ -108,7 +108,7 @@ class LiveAdapter:
cat = dict(self.catalog)
observed = set(self.tool_usage(transcript))
if self.host.name == "claude":
- observed |= transcripts.claude_deferred_tools(transcript)
+ observed |= trace.claude_deferred_tools(transcript)
elif self.host.name == "copilot":
# Some builds record the request's tool list in `session.usage_checkpoint`.
observed |= set(trace.parse_tool_names_copilot(
@@ -120,14 +120,10 @@ class LiveAdapter:
return {}, None
return cat, ("probe+observed" if self.catalog else "observed")
- # ---- waste signals ----
- def detect(self, path):
- return reflect.detect(path)
-
- # ---- untooling tool-sets ----
+ # ---- tool pruning ----
def protected_tools(self):
extra = COPILOT_PROTECTED if self.host.name == "copilot" else frozenset()
- return reflect.PROTECTED_TOOLS | INTERACTIVE_PROTECTED | extra
+ return PROTECTED_TOOLS | INTERACTIVE_PROTECTED | extra
def inapplicable_tools(self):
return () # nothing is inapplicable by construction here
@@ -135,9 +131,9 @@ class LiveAdapter:
def hardcoded_exclusions(self, used_tools):
return []
- # ---- spiral envelope ----
+ # ---- loop guard ----
def spiral_snapshot(self, path):
- return spiral.state_from_trajectory(path).snapshot()
+ return state_from_trajectory(path).snapshot()
# ---- per-task judge inputs ----
def problem_statements(self):
@@ -145,6 +141,3 @@ class LiveAdapter:
def env_vocabulary(self):
return detect_vocabulary(self.repo_root, self.vocabulary)
-
- def classify_domain(self):
- return None
diff --git a/tokeneconomizer/plugin/cli.py b/tokeneconomizer/plugin/cli.py
new file mode 100644
index 0000000..4e52409
--- /dev/null
+++ b/tokeneconomizer/plugin/cli.py
@@ -0,0 +1,516 @@
+"""`te` -- inspect and steer what TokenEconomizer does in your sessions.
+
+ te status what it has learned for this repository, and what it did
+ te microskills the facts it injects, and the ones still forming
+ te toolprune show the proposed deny list, and the evidence behind it
+ te toolprune apply [ITEM ...] write the proposal (or the named items) to the repository's
+ settings: tools (Claude Code), capabilities (Codex) or
+ MCP servers (Copilot)
+ te toolprune restore [ITEM ...] remove entries this plugin added
+ te toolprune refresh-catalog record the tool list a fresh session loads (Claude, Copilot)
+ te toolprune measure measure the request with and without the proposal
+ te config show each mechanism on or off, its settings, the guard's thresholds
+ te config set KEY=VALUE ... e.g. `loopguard=off`, `microskills=on`,
+ `loopguard.min_turns=12` (this repository; `--global` for
+ every repository)
+ te config unset KEY ... back to the next source down (the global file, then default)
+ te repomap [show | refresh] the repository map (`repomap=on`): what is cached, or
+ make it now
+ te doctor check the installation
+ te --host copilot probe real Copilot sessions in a throwaway repository: does a
+ learned fact change what the model does, and what does the
+ deny list save (makes model calls; see plugin/probe.py)
+
+`te facts` and `te untool` are the earlier names of `microskills` and `toolprune`, and still work.
+`--cwd` picks the repository (default: the current directory) and `--host` the agent
+(claude | codex | copilot | pi; default: `TE_HOST`, else the agent whose shell runs `te`, else
+claude).
+"""
+import argparse
+import glob
+import json
+import os
+import sys
+
+from .. import loopguard
+from . import accounting, denylist, fold, hosts, repomap, toolcheck
+from .config import unset_config, write_config
+from .context import LiveContext
+from .paths import state_root
+
+
+def _ctx(args, env=None):
+ host = hosts.HOSTS[args.host]()
+ return LiveContext.build(host, args.cwd, env)
+
+
+# ---- status / microskills ------------------------------------------------------------------
+def cmd_status(args):
+ ctx = _ctx(args)
+ cfg = ctx.config
+ out = {"repo": ctx.repo.label, "repo_root": ctx.repo.root, "host": ctx.host.name,
+ "state": ctx.store.base, "config": cfg.as_dict(), "warnings": cfg.warnings}
+ inj = ctx.store.read("injection.json") or {}
+ unt = ctx.store.read("untool.json") or {}
+ env_tracker = loopguard.load_envelope(ctx.store, cfg.loopguard_aggr,
+ cfg.loopguard_thresholds)
+ ledger = accounting.summarize(ctx.store.read_lines("ledger.jsonl"))
+ out.update({
+ "microskills": {"profile": cfg.microskills_effective,
+ "injected_lines": sum(1 for ln in (inj.get("rendered") or "").splitlines()
+ if ln.startswith("- ")),
+ "sessions_folded": inj.get("sessions", 0)},
+ "toolprune": {"mode": cfg.toolprune, "sessions": unt.get("sessions", 0),
+ "catalog_source": unt.get("catalog_source"),
+ "proposal": unt.get("proposal", []),
+ "applied": denylist.applied(ctx.store)},
+ "loopguard": {"mode": cfg.loopguard, "envelope": env_tracker.envelope,
+ "ended_green_turns": len(env_tracker.resolved_turns)},
+ "ledger": ledger})
+ if args.json:
+ print(json.dumps(out, indent=2, default=str))
+ return 0
+ print(f"TokenEconomizer -- {out['repo']} ({ctx.host.name})")
+ print(f" state {out['state']}")
+ print(f" config microskills={cfg.microskills_effective} toolprune={cfg.toolprune} "
+ f"loopguard={cfg.loopguard} repomap={cfg.repomap} mode={cfg.mode} paid={cfg.paid} "
+ f"shadow={cfg.shadow}")
+ if cfg.repomap != "off":
+ rm = repomap.read_state(ctx)
+ why = rm.get("error") or "made after the first session"
+ print(" repomap " + (f"{rm.get('chars', 0) // 4} tokens cached for "
+ f"{(rm.get('commit') or '?')[:10]}" if rm.get("map") else
+ f"none yet ({why})"))
+ for w in cfg.warnings:
+ print(f" warning {w}")
+ print(f" sessions {ledger['sessions']} folded, "
+ f"{accounting.fmt_tokens(ledger['effective_tokens'])} effective tokens, plugin "
+ f"overhead {accounting.fmt_tokens(ledger['overhead_tokens'])} "
+ f"({ledger['overhead_frac']:.1%})")
+ i = out["microskills"]
+ print(f" microskills {i['injected_lines']} fact(s) injected at session start "
+ f"({i['sessions_folded']} sessions learned from)")
+ u = out["toolprune"]
+ if not denylist.supports(ctx.host.name):
+ print(" toolprune not available on this host")
+ else:
+ src = u["catalog_source"] or "none yet"
+ print(f" toolprune {u['sessions']} sessions observed, catalog: {src}; "
+ f"proposed {denylist.unit(ctx.host.name, plural=True)}: "
+ f"{', '.join(u['proposal']) or '-'}; applied: {', '.join(u['applied']) or '-'}")
+ sp = out["loopguard"]
+ env_s = f"{sp['envelope']:.0f} tool calls" if sp["envelope"] else "not learned yet"
+ print(f" loopguard envelope {env_s} ({sp['ended_green_turns']} ended-green turns); "
+ f"{ledger['nudges']} nudge(s), {ledger['aborts']} stop(s) over {ledger['turns']} turns")
+ return 0
+
+
+def cmd_microskills(args):
+ ctx = _ctx(args)
+ inj = ctx.store.read("injection.json") or {}
+ text = inj.get("rendered") or ""
+ print(text.rstrip() or "(nothing injected yet: no fact has cleared its firing gate)")
+ facts = inj.get("facts") or {}
+ rows = [(k, v) for k, v in facts.items() if isinstance(v, dict) and "state" in v]
+ if rows:
+ print("\nfacts tracked:")
+ for k, v in sorted(rows):
+ print(f" {v.get('state', '?'):9s} fire={v.get('fire', '?'):>5s} "
+ f"{'INJECTED' if v.get('inject') else ' '} {k}")
+ return 0
+
+
+# ---- toolprune -----------------------------------------------------------------------------
+def _toolprune_show(ctx, unt):
+ host = ctx.host.name
+ print(f"sessions observed: {unt.get('sessions', 0)} catalog: "
+ f"{unt.get('catalog_source') or 'none yet'}")
+ print(f"applied ({denylist.unit(host, plural=True)} this plugin added to "
+ f"{denylist.settings_path(ctx.repo.root, host)}): "
+ f"{', '.join(denylist.applied(ctx.store)) or '-'}")
+ print(f"proposed: {', '.join(unt.get('proposal', [])) or '-'}")
+ if host == "codex":
+ caps = unt.get("capabilities") or {}
+ if caps:
+ print("capabilities (removable from a project's .codex/config.toml):")
+ for c, e in sorted(caps.items()):
+ print(f" {c:14s} loaded in {e['loaded_sessions']:3d} sessions, unused in "
+ f"{e['unused_sessions']:3d}{' USED (kept)' if e['used'] else ''}")
+ trusted = denylist.codex_project_trusted(ctx.repo.root)
+ if trusted is False:
+ print("note: Codex reads a project's .codex/config.toml only in a TRUSTED project; "
+ "trust this one in Codex first, or an applied proposal does nothing.")
+ return 0
+ if host == "copilot":
+ servers = unt.get("servers") or {}
+ if servers:
+ print("MCP servers (Copilot can only remove a whole server):")
+ for name, e in sorted(servers.items()):
+ state = "USED (kept)" if e["used"] else f"unused in {e['unused_sessions']} sessions"
+ print(f" {name:24s} {e['tools']:3d} tools, {state}")
+ streaks = unt.get("streaks") or {}
+ if streaks and host == "claude":
+ print("unused-session streaks (tools never used are candidates once over "
+ f"{ctx.config.toolprune_evidence}):")
+ for t, n in sorted(streaks.items(), key=lambda kv: -kv[1])[:30]:
+ used = "used" if t in set(unt.get("used_tools", [])) else ""
+ print(f" {n:4d} {t} {used}")
+ if not unt.get("catalog_source") or unt.get("catalog_source") == "observed":
+ print(f"note: without `te --host {host} toolprune refresh-catalog` only "
+ + ("deferred and observed" if host == "claude" else "observed")
+ + " tools are known, which leaves the always-loaded tools out of the evidence.")
+ return 0
+
+
+def cmd_toolprune(args):
+ ctx = _ctx(args)
+ host = ctx.host.name
+ if not denylist.supports(host):
+ print(f"tool pruning is not available on {host} (it declares only a handful of tools)")
+ return 1
+ unt = ctx.store.read("untool.json") or {}
+ action = args.action
+ if action == "show":
+ return _toolprune_show(ctx, unt)
+ if action == "apply":
+ tools = args.tools or unt.get("proposal", [])
+ if not tools:
+ print("nothing to apply")
+ return 0
+ if host == "codex":
+ bad = [t for t in tools if t not in denylist.CODEX_TOGGLES]
+ if bad:
+ print(f"not a removable Codex capability: {', '.join(bad)} (choose from "
+ f"{', '.join(denylist.CODEX_LIVE_CAPABILITIES)})")
+ return 2
+ try:
+ added = denylist.apply(ctx.repo.root, tools, ctx.store, host=host)
+ except RuntimeError as e:
+ print(f"not applied: {e}")
+ return 1
+ print(f"added: {', '.join(added) or '(already present)'}\n"
+ f"in {denylist.settings_path(ctx.repo.root, host)} -- takes effect from the next "
+ f"session.")
+ if host == "copilot" and added:
+ if denylist.copilot_folder_trusted(ctx.repo.root) is False:
+ print("warning: Copilot reads a repository's .github/copilot settings only in a "
+ "trusted folder, and this one is not. Trust it (Copilot asks when you "
+ "start it here), or the change does nothing.")
+ left = toolcheck.verify_copilot(ctx.repo.root, denylist.applied(ctx.store))
+ if left is not None:
+ print("checked with a local capture: " + ", ".join(
+ f"{k} {'removed' if not v else f'still loaded ({v} tools)'}"
+ for k, v in sorted(left.items())))
+ if host == "codex" and added:
+ if denylist.codex_project_trusted(ctx.repo.root) is False:
+ print("warning: this project is not trusted in Codex, which ignores a "
+ "project's .codex/config.toml until it is. Trust it (Codex asks when "
+ "you start it here), or the change does nothing.")
+ state = toolcheck.verify_codex(ctx.repo.root, denylist.applied(ctx.store))
+ if state:
+ print("codex features list: " + ", ".join(
+ f"{k}={'on' if v else 'off'}" for k, v in sorted(state.items())))
+ return 0
+ if action == "restore":
+ try:
+ removed = denylist.restore(ctx.repo.root, ctx.store, args.tools or None, host=host)
+ except RuntimeError as e:
+ print(f"not restored: {e}")
+ return 1
+ print(f"removed: {', '.join(removed) or '-'} (from the next session)")
+ return 0
+ if action == "refresh-catalog":
+ if host == "codex":
+ print("Codex needs no catalog: its removable capabilities are a fixed set "
+ f"({', '.join(denylist.CODEX_LIVE_CAPABILITIES)}), read from each session.")
+ return 0
+ path, tools = toolcheck.refresh_catalog(state_root(), host=host)
+ print(f"{len(tools)} tools recorded in {path}:\n " + ", ".join(tools))
+ return 0
+ if action == "measure":
+ tools = args.tools or unt.get("proposal", []) or denylist.applied(ctx.store)
+ if not tools:
+ print("no proposal to measure")
+ return 1
+ res = toolcheck.measure(tools, host=host)
+ print(json.dumps(res, indent=2))
+ return 0
+ return 2
+
+
+# ---- repomap ------------------------------------------------------------------------------
+def cmd_repomap(args):
+ ctx = _ctx(args)
+ if args.action == "refresh":
+ st = repomap.refresh(ctx)
+ else:
+ st = repomap.read_state(ctx)
+ if not st.get("map"):
+ print(f"no map cached for {ctx.repo.label}" + (f": {st['error']}" if st.get("error")
+ else ""))
+ if ctx.config.repomap == "off":
+ print("the map is off; turn it on with `te config set repomap=on`")
+ return 1 if args.action == "refresh" else 0
+ current = st.get("commit") == repomap.head_commit(ctx.repo.root)
+ print(f"{ctx.repo.label}: ~{st['chars'] // 4} tokens (budget {st.get('tokens_budget')}), "
+ f"commit {(st.get('commit') or '?')[:10]}{'' if current else ' (an older commit)'}, "
+ f"made in {st.get('secs')}s with {st.get('python')}")
+ if st.get("error"):
+ print(f"last refresh failed: {st['error']}")
+ print(repomap.HEADER + st["map"][:2000] + ("\n..." if len(st["map"]) > 2000 else ""))
+ return 0
+
+
+def _rtk_hook():
+ """Where rtk's PreToolUse hook is registered for Claude Code or Copilot, if anywhere."""
+ found = []
+ for path in (os.path.expanduser("~/.claude/settings.json"),
+ *glob.glob(os.path.expanduser("~/.copilot/hooks/*.json"))):
+ try:
+ if "rtk" in open(path, encoding="utf-8").read():
+ found.append(path)
+ except OSError:
+ pass
+ return found
+
+
+# ---- config / doctor / fold ----------------------------------------------------------------
+def _config_view(cfg):
+ """The settings as a person reads them: each mechanism on or off, its settings, and the
+ guard's thresholds with the numbers a `loopguard.<name>` setting would replace."""
+ d = cfg.as_dict()
+ pinned = d.pop("loopguard_thresholds")
+ return {
+ "enabled": d.pop("enabled"),
+ "microskills": {"state": "off" if cfg.microskills == "off" else "on",
+ "microskills": d.pop("microskills"),
+ "microskills_max_facts": d.pop("microskills_max_facts"),
+ "microskills_max_tokens": d.pop("microskills_max_tokens"),
+ "microskills_propose_every": d.pop("microskills_propose_every")},
+ "toolprune": {"state": "off" if cfg.toolprune == "off" else "on",
+ "toolprune": d.pop("toolprune"),
+ "toolprune_evidence": d.pop("toolprune_evidence")},
+ "loopguard": {
+ "state": "off" if cfg.loopguard == "off" else "on",
+ "loopguard": d.pop("loopguard"), "loopguard_aggr": d.pop("loopguard_aggr"),
+ "loopguard_nudges": d.pop("loopguard_nudges"),
+ "thresholds": loopguard.base_thresholds(cfg.loopguard_aggr, pinned),
+ "pinned": sorted(pinned)},
+ "other": d,
+ "warnings": cfg.warnings,
+ }
+
+
+def cmd_config(args):
+ ctx = _ctx(args)
+ if args.action == "show":
+ print(json.dumps(_config_view(ctx.config), indent=2))
+ return 0
+ path = (os.path.join(ctx.root, "config.json") if args.globally
+ else os.path.join(os.path.dirname(ctx.store.base), "config.json"))
+ if args.action == "unset":
+ try:
+ cur = unset_config(path, [k.strip() for k in args.pairs])
+ except ValueError as e:
+ print(f"rejected: {e}")
+ return 2
+ print(f"{path}: {json.dumps(cur, sort_keys=True)}")
+ return 0
+ updates = {}
+ for kv in args.pairs:
+ if "=" not in kv:
+ print(f"expected KEY=VALUE, got {kv!r}")
+ return 2
+ k, v = kv.split("=", 1)
+ updates[k.strip()] = v.strip()
+ if not updates:
+ print("nothing to set: give KEY=VALUE (see `te config show` for the keys)")
+ return 2
+ try:
+ cur = write_config(path, updates)
+ except ValueError as e:
+ print(f"rejected: {e}")
+ return 2
+ print(f"{path}: {json.dumps(cur, sort_keys=True)}")
+ print("applies from the next hook call; a new fact-size cap applies once the next session "
+ "has been folded")
+ host = hosts.HOSTS[args.host]
+ if cur.get("loopguard") == "stop" and not host.can_stop_mid_turn:
+ print(f"note: {host.name} cannot stop a turn from a hook, so `stop` gives the redirect "
+ f"and then a notice there, as `nudge` does")
+ return 0
+
+
+def cmd_fold(args):
+ ctx = _ctx(args)
+ sids = args.session or fold.pending_sessions(ctx)
+ for sid in sids:
+ rec = fold.fold_session(ctx, sid)
+ if rec is not None and args.verbose:
+ print(json.dumps(rec, default=str))
+ return 0
+
+
+def cmd_judge(args):
+ """The detached half of the paid stuck judge (see plugin/judge.py); not for people."""
+ from . import judge
+ judge.run_job(_ctx(args), args.session, args.job)
+ return 0
+
+
+def cmd_probe(args):
+ if args.host != "copilot":
+ print("the probe runs on Copilot only so far: `te --host copilot probe`")
+ return 2
+ from . import probe
+ return probe.run(sessions=args.sessions, model=args.model, keep=args.keep)
+
+
+def cmd_doctor(args):
+ ok = sys.version_info >= (3, 10)
+ print(f"python {sys.version.split()[0]} {'ok' if ok else '(needs >= 3.10)'}")
+ root = state_root()
+ try:
+ os.makedirs(root, exist_ok=True)
+ probe = os.path.join(root, ".write-test")
+ open(probe, "w").close()
+ os.remove(probe)
+ print(f"state root {root} (writable)")
+ except OSError as e:
+ print(f"state root {root} NOT writable: {e}")
+ ok = False
+ import shutil as _sh
+ # Only the agents installed here: a Codex-only machine has no Claude Code catalog to probe.
+ agents = [h for h in ("claude", "codex", "copilot", "pi") if _sh.which(h)]
+ print(f"agents {', '.join(agents) or 'none of claude, codex, copilot, pi on PATH'}")
+ if "claude" in agents:
+ cat = os.path.join(root, "hosts", "claude", "catalog.json")
+ print(f"claude catalog {'present' if os.path.exists(cat) else 'not probed'}")
+ if "codex" in agents:
+ trusted = denylist.codex_project_trusted(args.cwd)
+ if trusted is not None:
+ print(f"codex this project is {'trusted' if trusted else 'NOT trusted'} "
+ f"(an untrusted project's .codex/config.toml is ignored)")
+ if "copilot" in agents:
+ from urllib.parse import urlparse
+ from .sidecall import copilot_model
+ cat = os.path.join(root, "hosts", "copilot", "catalog.json")
+ print(f"copilot catalog {'present' if os.path.exists(cat) else 'not probed'}")
+ base = os.environ.get("COPILOT_PROVIDER_BASE_URL")
+ route = (f"BYOK {os.environ.get('COPILOT_PROVIDER_TYPE') or 'openai'} at "
+ f"{urlparse(base).netloc or base}" if base else "Copilot subscription")
+ print(f"copilot {route}; side calls and `probe` use model "
+ f"{copilot_model() or '(Copilot default)'}")
+ if base:
+ print("copilot note: Copilot does not pass COPILOT_PROVIDER_* to the plugin's "
+ "hooks, so with paid=true its side calls cannot use this provider")
+ ctrust = denylist.copilot_folder_trusted(args.cwd)
+ if ctrust is not None:
+ print(f"copilot this folder is {'trusted' if ctrust else 'NOT trusted'} (an "
+ f"untrusted folder's .github/copilot settings are ignored)")
+ if "pi" in agents:
+ settings = os.path.join(os.environ.get("PI_CODING_AGENT_DIR") or os.path.join(
+ os.path.expanduser("~"), ".pi", "agent"), "settings.json")
+ try:
+ pkgs = json.load(open(settings, encoding="utf-8")).get("packages") or []
+ except (OSError, ValueError, AttributeError):
+ pkgs = []
+ mine = [p for p in pkgs if "tokeneconomizer" in json.dumps(p).lower()]
+ print(f"pi package {'installed: ' + str(mine[0]) if mine else 'not in ' + settings}")
+ ctx = _ctx(args)
+ py = repomap.find_python(ctx)
+ print(f"repomap {ctx.config.repomap}; " + (f"aider found ({py})" if py else
+ "no Python with aider found (pip install aider-chat, or set repomap_python)"))
+ rtk, hooks = _sh.which("rtk"), _rtk_hook()
+ if rtk or hooks:
+ print(f"rtk {rtk or 'not on PATH'}; hook in "
+ f"{', '.join(hooks) or 'no settings file'}. Compatible. Note: `rtk pytest` prints "
+ f"nothing when pytest is missing, so the plugin cannot learn that fact from it")
+ log = os.path.join(root, "errors.log")
+ if os.path.exists(log):
+ tail = open(log, encoding="utf-8", errors="replace").read().splitlines()[-6:]
+ print("errors.log (tail):\n " + "\n ".join(tail))
+ else:
+ print("errors.log none")
+ return 0 if ok else 1
+
+
+def build_parser():
+ ap = argparse.ArgumentParser(prog="te", description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--cwd", default=os.getcwd())
+ ap.add_argument("--host", default=None, choices=sorted(hosts.HOSTS))
+ # The same two options are accepted after the subcommand too (`te fold --host codex ...`).
+ # SUPPRESS keeps a subcommand that omits them from overwriting the top-level values.
+ common = argparse.ArgumentParser(add_help=False)
+ common.add_argument("--cwd", default=argparse.SUPPRESS)
+ common.add_argument("--host", default=argparse.SUPPRESS, choices=sorted(hosts.HOSTS))
+ sub = ap.add_subparsers(dest="cmd", required=True)
+
+ def add(name, *aliases):
+ return sub.add_parser(name, aliases=list(aliases), parents=[common])
+
+ p = add("status")
+ p.add_argument("--json", action="store_true")
+ p.set_defaults(fn=cmd_status)
+ add("microskills", "facts").set_defaults(fn=cmd_microskills)
+ p = add("toolprune", "untool")
+ p.add_argument("action", nargs="?", default="show",
+ choices=("show", "apply", "restore", "refresh-catalog", "measure"))
+ p.add_argument("tools", nargs="*")
+ p.set_defaults(fn=cmd_toolprune)
+ p = add("config")
+ p.add_argument("action", nargs="?", default="show", choices=("show", "set", "unset"))
+ p.add_argument("pairs", nargs="*")
+ p.add_argument("--global", dest="globally", action="store_true")
+ p.set_defaults(fn=cmd_config)
+ p = add("fold")
+ p.add_argument("--session", action="append")
+ p.add_argument("--verbose", action="store_true")
+ p.set_defaults(fn=cmd_fold)
+ p = add("judge")
+ p.add_argument("--session", required=True)
+ p.add_argument("--job", required=True)
+ p.set_defaults(fn=cmd_judge)
+ add("doctor").set_defaults(fn=cmd_doctor)
+ p = add("repomap")
+ p.add_argument("action", nargs="?", default="show", choices=("show", "refresh"))
+ p.set_defaults(fn=cmd_repomap)
+ p = add("probe")
+ p.add_argument("--sessions", type=int, default=6)
+ p.add_argument("--model", default=None)
+ p.add_argument("--keep", action="store_true")
+ p.set_defaults(fn=cmd_probe)
+ return ap
+
+
+def _recent_host(cwd):
+ """The agent whose state for this repository changed last, or None: from a plain terminal,
+ a Codex or Pi user means their own agent's state without typing `--host`."""
+ from .paths import repo_identity, repo_state_dir
+ try:
+ repo = repo_identity(cwd)
+ except OSError:
+ return None
+ seen = {}
+ for name in hosts.HOSTS:
+ d = repo_state_dir(repo, name)
+ if os.path.isdir(d):
+ seen[name] = max([os.path.getmtime(d)] + [os.path.getmtime(os.path.join(d, f))
+ for f in os.listdir(d)])
+ return max(seen, key=seen.get) if seen else None
+
+
+def main(argv=None):
+ args = build_parser().parse_args(argv)
+ if args.host is None:
+ args.host = hosts.default_host(recent=_recent_host(args.cwd))
+ try:
+ return args.fn(args) or 0
+ finally:
+ from .paths import secure_root
+ secure_root()
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tokeneconomizer/plugin/config.py b/tokeneconomizer/plugin/config.py
new file mode 100644
index 0000000..d3423a7
--- /dev/null
+++ b/tokeneconomizer/plugin/config.py
@@ -0,0 +1,346 @@
+"""The plugin's settings: which mechanisms act in real sessions, and how far each may go.
+
+The defaults are the conservative end of every switch:
+
+ * microskills = "envfacts" -- the LLM-free facts only. The paid proposer (`envfacts+distiller`,
+ `distiller`) is opt-in, and refused unless `paid` is also true;
+ * toolprune = "propose" -- evidence is gathered and a deny list is proposed, but nothing is
+ written to the agent's settings until the person approves it;
+ "auto" applies proposals as they form;
+ * loopguard = "nudge" -- at most one mid-turn redirect per prompt-turn. "stop" also stops
+ a turn that keeps failing after the redirect, in headless mode
+ only; an interactive session gets a notice instead, because there
+ a person is already watching;
+ * paid = False -- no mechanism makes an LLM call of its own. Every paid call that is
+ allowed is charged to the session's ledger;
+ * shadow = False -- with True, every decision is computed and logged but none
+ reaches the agent: the way to measure a mechanism before
+ trusting it.
+
+Each mechanism also takes a plain `on` / `off` (`on` = the value above), and has settings a
+person can tune by hand:
+
+ * microskills_max_facts, microskills_max_tokens -- caps on the injected block;
+ * microskills_propose_every -- sessions between paid proposer runs;
+ * toolprune_evidence -- unused sessions before a tool is proposed;
+ * loopguard_aggr -- the guard's threshold preset;
+ * loopguard_nudges -- redirects per prompt-turn before it stops or notifies;
+ * loopguard.<name> -- one guard threshold, pinned over the preset and over what the
+ repository's history learned (LOOPGUARD_KEYS);
+ * repomap, repomap_tokens, repomap_python, repomap_timeout -- the opt-in repository map.
+
+The names before the mechanisms were renamed are read too, so an existing config file keeps
+working: `inject` (microskills), `untool` (toolprune), `spiral` (loopguard), with their
+settings (`inject_max_facts`, `untool_evidence`, `spiral.<name>`, ...) and environment variables
+(`TE_INJECT`, ...), and the value `guard` for `stop`. Writing a setting stores its new name.
+
+Sources, lowest precedence first: built-in defaults, `<root>/config.json`, the repository's
+`config.json`, then environment variables (`TE_MICROSKILLS`, `TE_TOOLPRUNE`, `TE_LOOPGUARD`,
+`TE_MODE`, `TE_PAID`, `TE_SHADOW`, `TE_DISABLE`, and one per setting; `TE_LOOPGUARD_THRESHOLDS`
+takes JSON). Within one source a new name wins over its old one. An invalid value is ignored with
+a warning recorded in the result rather than raised: a typo in a config file must not break the
+agent's hooks.
+"""
+import json
+import os
+from dataclasses import asdict, dataclass, field, fields
+
+MICROSKILLS = ("off", "envfacts", "envfacts+distiller", "distiller")
+TOOLPRUNE = ("off", "propose", "auto")
+LOOPGUARD = ("off", "nudge", "stop")
+REPOMAP = ("off", "on", "start")
+MODES = ("auto", "interactive", "headless")
+AGGR = ("conservative", "default", "aggressive")
+
+# What `on` turns each mechanism to, and the words read as on / off.
+ON_VALUE = {"microskills": "envfacts", "toolprune": "propose", "loopguard": "nudge",
+ "repomap": "on"}
+_ON = ("on", "true", "yes", "1", "enable", "enabled")
+_OFF = ("off", "false", "no", "0", "disable", "disabled")
+# Values renamed with their mechanism.
+_VALUE_ALIASES = {"loopguard": {"guard": "stop"}}
+
+# Setting names from before the mechanisms were renamed: old -> new.
+ALIASES = {
+ "inject": "microskills",
+ "inject_max_facts": "microskills_max_facts",
+ "inject_max_tokens": "microskills_max_tokens",
+ "propose_every": "microskills_propose_every",
+ "untool": "toolprune",
+ "untool_evidence": "toolprune_evidence",
+ "spiral": "loopguard",
+ "spiral_aggr": "loopguard_aggr",
+ "spiral_nudges": "loopguard_nudges",
+ "spiral_thresholds": "loopguard_thresholds",
+}
+_THRESHOLD_PREFIXES = ("loopguard.", "spiral.")
+
+# The loop guard's thresholds a person may pin (`loopguard.<name>=<value>`), with their type
+# and range. They are the keys of `loopguard.DEFAULT_THRESHOLDS`; a turn's "turns" are its tool
+# calls here.
+LOOPGUARD_KEYS = {
+ "min_turns": (int, 1, None, "tool calls in a turn before it can count as stuck"),
+ "edit_churn": (int, 1, None, "edits to one file that count as churn"),
+ "distinct_edit_files": (int, 1, None, "files edited that count as scattered"),
+ "error_outputs": (int, 1, None, "failing tool results that count as sustained errors"),
+ "stagnation": (float, 0.0, 1.0, "share of failures that repeat an earlier one"),
+ "envelope_pct": (float, 1.0, 100.0, "percentile of this repository's ended-green turns"),
+ "envelope_margin": (float, 0.1, None, "multiplier on that percentile: the envelope"),
+ "envelope_min_samples": (int, 1, None, "ended-green turns needed before the envelope is used"),
+ "backstop_mult": (float, 0.1, None, "stuck past this multiple of the envelope: redirect, "
+ "then stop"),
+ "judge_confidence": (float, 0.0, 1.0, "paid judge confidence needed to act (paid=true)"),
+ "gate_min_turns": (int, 1, None, "tool calls before the paid judge is consulted"),
+ "gate_error_outputs": (int, 1, None, "failing results that wake the paid judge early"),
+}
+
+
+def canonical(key):
+ """A setting's current name: `inject` -> `microskills`, `spiral.x` -> `loopguard.x`."""
+ for prefix in _THRESHOLD_PREFIXES:
+ if key.startswith(prefix):
+ return "loopguard." + key[len(prefix):]
+ return ALIASES.get(key, key)
+
+
+def _threshold_name(key):
+ """`min_turns` for `loopguard.min_turns` (or the old `spiral.min_turns`), else None."""
+ for prefix in _THRESHOLD_PREFIXES:
+ if key.startswith(prefix):
+ return key[len(prefix):]
+ return None
+
+
+@dataclass
+class LiveConfig:
+ enabled: bool = True
+ mode: str = "auto"
+ microskills: str = "envfacts"
+ microskills_max_facts: int = 4
+ microskills_max_tokens: int = 150
+ microskills_propose_every: int = 5
+ toolprune: str = "propose"
+ toolprune_evidence: int = 5
+ loopguard: str = "nudge"
+ loopguard_aggr: str = "default"
+ loopguard_nudges: int = 1
+ loopguard_thresholds: dict = field(default_factory=dict)
+ repomap: str = "off"
+ repomap_tokens: int = 2048
+ repomap_python: str = ""
+ repomap_timeout: int = 8
+ paid: bool = False
+ paid_model: str = ""
+ shadow: bool = False
+ vocabulary: str = "auto"
+ warnings: list = field(default_factory=list)
+
+ _CHOICES = {"mode": MODES, "microskills": MICROSKILLS, "toolprune": TOOLPRUNE,
+ "loopguard": LOOPGUARD, "repomap": REPOMAP, "loopguard_aggr": AGGR,
+ "vocabulary": ("auto", "python-git", "node-web")}
+
+ def as_dict(self):
+ d = asdict(self)
+ d.pop("warnings", None)
+ return d
+
+ def set(self, key, value, source="?"):
+ """Apply one setting with type coercion and validation; False if rejected."""
+ name = _threshold_name(key)
+ if name is not None:
+ return self._set_threshold(name, value, source)
+ key = canonical(key)
+ names = {f.name: f for f in fields(self) if f.name != "warnings"}
+ if key not in names:
+ self.warnings.append(f"{source}: unknown key {key!r}")
+ return False
+ if key == "loopguard_thresholds":
+ if not isinstance(value, dict):
+ self.warnings.append(f"{source}: loopguard_thresholds must be an object")
+ return False
+ return all([self._set_threshold(k, v, source) for k, v in value.items()])
+ if key in ON_VALUE and isinstance(value, (str, bool, int)):
+ word = str(value).strip().lower()
+ if word in _ON:
+ value = ON_VALUE[key]
+ elif word in _OFF:
+ value = "off"
+ else:
+ value = _VALUE_ALIASES.get(key, {}).get(word, value)
+ cur = getattr(self, key)
+ try:
+ if isinstance(cur, bool):
+ v = value if isinstance(value, bool) else str(value).strip().lower() in (
+ "1", "true", "yes", "on")
+ elif isinstance(cur, int):
+ v = int(value)
+ if v < 1:
+ raise ValueError("must be >= 1")
+ else:
+ v = str(value).strip()
+ except (TypeError, ValueError) as e:
+ self.warnings.append(f"{source}: {key}={value!r} rejected ({e})")
+ return False
+ choices = self._CHOICES.get(key)
+ if choices and v not in choices:
+ self.warnings.append(f"{source}: {key}={v!r} not one of {choices}")
+ return False
+ setattr(self, key, v)
+ return True
+
+ def _set_threshold(self, name, value, source):
+ spec = LOOPGUARD_KEYS.get(name)
+ if spec is None:
+ self.warnings.append(f"{source}: unknown loopguard threshold {name!r} "
+ f"(one of {', '.join(LOOPGUARD_KEYS)})")
+ return False
+ kind, lo, hi, _ = spec
+ try:
+ if isinstance(value, bool):
+ raise ValueError("not a number")
+ v = kind(float(value)) if kind is int and float(value).is_integer() else kind(value)
+ except (TypeError, ValueError) as e:
+ self.warnings.append(f"{source}: loopguard.{name}={value!r} rejected ({e})")
+ return False
+ if (lo is not None and v < lo) or (hi is not None and v > hi):
+ rng = f">= {lo}" if hi is None else f"between {lo} and {hi}"
+ self.warnings.append(f"{source}: loopguard.{name}={v!r} rejected (must be {rng})")
+ return False
+ self.loopguard_thresholds[name] = v
+ return True
+
+ @property
+ def microskills_effective(self):
+ """The micro-skill profile that will actually run: a paid profile without `paid` falls
+ back to the free layer, and says so in `warnings` when the config is loaded."""
+ if self.microskills in ("envfacts+distiller", "distiller") and not self.paid:
+ return "envfacts"
+ return self.microskills
+
+
+# Environment variables, old names first so that a new name set alongside its old one wins.
+_ENV = {"TE_MODE": "mode", "TE_PAID": "paid", "TE_SHADOW": "shadow",
+ "TE_PAID_MODEL": "paid_model", "TE_VOCABULARY": "vocabulary",
+ "TE_INJECT": "microskills", "TE_INJECT_MAX_FACTS": "microskills_max_facts",
+ "TE_INJECT_MAX_TOKENS": "microskills_max_tokens",
+ "TE_PROPOSE_EVERY": "microskills_propose_every",
+ "TE_UNTOOL": "toolprune", "TE_UNTOOL_EVIDENCE": "toolprune_evidence",
+ "TE_SPIRAL": "loopguard", "TE_SPIRAL_AGGR": "loopguard_aggr",
+ "TE_SPIRAL_NUDGES": "loopguard_nudges",
+ "TE_MICROSKILLS": "microskills", "TE_MICROSKILLS_MAX_FACTS": "microskills_max_facts",
+ "TE_MICROSKILLS_MAX_TOKENS": "microskills_max_tokens",
+ "TE_MICROSKILLS_PROPOSE_EVERY": "microskills_propose_every",
+ "TE_TOOLPRUNE": "toolprune", "TE_TOOLPRUNE_EVIDENCE": "toolprune_evidence",
+ "TE_LOOPGUARD": "loopguard", "TE_LOOPGUARD_AGGR": "loopguard_aggr",
+ "TE_LOOPGUARD_NUDGES": "loopguard_nudges",
+ "TE_REPOMAP": "repomap", "TE_REPOMAP_TOKENS": "repomap_tokens",
+ "TE_REPOMAP_PYTHON": "repomap_python", "TE_REPOMAP_TIMEOUT": "repomap_timeout"}
+_ENV_THRESHOLDS = ("TE_SPIRAL_THRESHOLDS", "TE_LOOPGUARD_THRESHOLDS")
+
+
+def _read(path):
+ try:
+ with open(path, encoding="utf-8") as fh:
+ obj = json.load(fh)
+ return obj if isinstance(obj, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def _old_names_first(items):
+ """A file's settings with every old name before every new one, so the new one wins."""
+ return sorted(items, key=lambda kv: canonical(kv[0]) == kv[0])
+
+
+def load_config(root, repo_dir=None, env=None):
+ """Merge defaults, the global file, the repository file and the environment."""
+ env = os.environ if env is None else env
+ cfg = LiveConfig()
+ for label, path in (("global", os.path.join(root, "config.json")),
+ ("repo", os.path.join(repo_dir, "config.json") if repo_dir else None)):
+ if path:
+ for k, v in _old_names_first(_read(path).items()):
+ cfg.set(k, v, source=f"{label} {path}")
+ for var, key in _ENV.items():
+ if env.get(var) not in (None, ""):
+ cfg.set(key, env[var], source=var)
+ for var in _ENV_THRESHOLDS:
+ if env.get(var):
+ try:
+ cfg.set("loopguard_thresholds", json.loads(env[var]), source=var)
+ except ValueError:
+ cfg.warnings.append(f"{var}: not valid JSON")
+ if str(env.get("TE_DISABLE", "")).strip().lower() in ("1", "true", "yes", "on"):
+ cfg.enabled = False
+ if cfg.microskills != cfg.microskills_effective:
+ cfg.warnings.append(f"microskills={cfg.microskills!r} makes paid calls but paid=false; "
+ f"running {cfg.microskills_effective!r}")
+ return cfg
+
+
+def _drop_old_names(current, key):
+ """Remove every old spelling of `key` from a config file's contents."""
+ for old, new in ALIASES.items():
+ if new == key:
+ current.pop(old, None)
+
+
+def write_config(path, updates):
+ """Merge `updates` into the JSON config at `path` (validating each key first), under the
+ settings' current names. A `loopguard.<name>` key lands in `loopguard_thresholds`."""
+ probe = LiveConfig()
+ bad = [k for k, v in updates.items() if not probe.set(k, v, source="te config")]
+ if bad:
+ raise ValueError("; ".join(probe.warnings))
+ current = _read(path)
+ # an old file's thresholds move to the new name, so nothing pinned is lost
+ if "spiral_thresholds" in current:
+ old = current.pop("spiral_thresholds")
+ if isinstance(old, dict):
+ current["loopguard_thresholds"] = dict(old, **current.get("loopguard_thresholds")
+ or {})
+ for k in updates:
+ name = _threshold_name(k)
+ key = canonical(k)
+ if name is not None:
+ current.setdefault("loopguard_thresholds", {})[name] = \
+ probe.loopguard_thresholds[name]
+ elif key == "loopguard_thresholds":
+ current.setdefault("loopguard_thresholds", {}).update(probe.loopguard_thresholds)
+ else:
+ _drop_old_names(current, key)
+ current[key] = getattr(probe, key)
+ _write(path, current)
+ return current
+
+
+def unset_config(path, keys):
+ """Remove keys (by either name) from the JSON config at `path`, so the next source down
+ applies again. `loopguard.<name>` removes one threshold; `loopguard_thresholds` all."""
+ known = {f.name for f in fields(LiveConfig) if f.name != "warnings"}
+ bad = [k for k in keys if canonical(k) not in known and _threshold_name(k) not in
+ LOOPGUARD_KEYS]
+ if bad:
+ raise ValueError(f"unknown key(s): {', '.join(bad)}")
+ current = _read(path)
+ for k in keys:
+ name = _threshold_name(k)
+ if name is not None:
+ for table in ("loopguard_thresholds", "spiral_thresholds"):
+ (current.get(table) or {}).pop(name, None)
+ if not current.get(table):
+ current.pop(table, None)
+ else:
+ key = canonical(k)
+ current.pop(key, None)
+ _drop_old_names(current, key)
+ _write(path, current)
+ return current
+
+
+def _write(path, obj):
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(obj, fh, indent=2, sort_keys=True)
+ os.replace(tmp, path)
diff --git a/te_live/context.py b/tokeneconomizer/plugin/context.py
similarity index 54%
rename from te_live/context.py
rename to tokeneconomizer/plugin/context.py
index 0bb68fb..7bb96ad 100644
--- a/te_live/context.py
+++ b/tokeneconomizer/plugin/context.py
@@ -1,5 +1,7 @@
"""`LiveContext`: everything one hook call or CLI command needs about where it is running."""
import os
+import subprocess
+import sys
from dataclasses import dataclass
from .config import LiveConfig, load_config
@@ -38,3 +40,23 @@ class LiveContext:
store = Store(base)
config = load_config(root, repo_dir=os.path.dirname(base), env=env)
return cls(host=host, repo=repo, root=root, store=store, config=config, env=env)
+
+ def spawn(self, argv, log_name):
+ """Run `te <argv>` for this host and repository in a detached process, its output
+ appended to `<store>/<log_name>`. A hook uses it for anything slower than a hook may
+ take (folding a session, the paid judge, the repository map)."""
+ # The directory holding the package: the checkout, or the bundle's lib/.
+ core = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+ env = dict(self.env)
+ env["PYTHONPATH"] = core + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH")
+ else "")
+ cmd = [sys.executable, "-m", "tokeneconomizer.plugin.cli", *argv,
+ "--host", self.host.name, "--cwd", self.repo.root]
+ self.store.ensure()
+ log = open(self.store.path(log_name), "a")
+ try:
+ subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log,
+ cwd=self.repo.root, env=env, start_new_session=True)
+ finally:
+ log.close()
+ return True
diff --git a/te_live/controller.py b/tokeneconomizer/plugin/controller.py
similarity index 67%
rename from te_live/controller.py
rename to tokeneconomizer/plugin/controller.py
index d04b57c..405307a 100644
--- a/te_live/controller.py
+++ b/tokeneconomizer/plugin/controller.py
@@ -1,8 +1,10 @@
"""`LiveController`: what the plugin does at each hook.
- SessionStart inject the repository's learned manual (cached by the last fold), and
- fold any earlier session that ended without its SessionEnd being seen
- UserPromptSubmit open a prompt-turn for the spiral guard
+ SessionStart inject the repository's micro-skills (cached by the last fold), and
+ fold any earlier session that ended without its SessionEnd being seen;
+ with `repomap` on, refresh a stale map in the background
+ UserPromptSubmit open a prompt-turn for the loop guard; on a session's first prompt, add
+ the repository map (`repomap=on`)
PostToolUse fold the call into the turn's guard; nudge, or stop, when it says so
Stop close the turn; an ended-green turn feeds the repository's envelope
SessionEnd hand the session to a detached `te fold`
@@ -11,7 +13,7 @@ Every handler returns quickly and fails open. A hook that raises would break the
for a cost optimization, so `hook.main` turns any exception into an empty output, and nothing
here waits on the network: injection reads a cached render, and the only paid call a hook can
cause -- the sampled stuck judge -- runs only when `paid` is on and the free gate is open, and
-then in a detached job (`te_live.judge`), never in the hook itself.
+then in a detached job (`judge`), never in the hook itself.
Every visible action is announced in one `systemMessage` line, so a person can see why the agent
changed course; `shadow` computes and logs every decision without acting on any of them.
@@ -20,7 +22,8 @@ import hashlib
import os
import time
-from . import fold, guard, untool
+from .. import loopguard
+from . import denylist, fold, repomap
from .hosts import merge_outputs
from .paths import ensure_launcher
@@ -92,8 +95,9 @@ class LiveController:
outputs = []
seen = self.store.read("notices.json") or {}
- if self.cfg.inject != "off":
- text = (self.store.read("injection.json") or {}).get("rendered") or ""
+ if self.cfg.microskills != "off":
+ inj = self.store.read("injection.json") or {}
+ text = inj.get("rendered") or ""
# A resumed or forked conversation already carries what the first start injected;
# a cleared or compacted one has lost it. ("new" is Copilot's word for "startup".)
if text and source in ("startup", "new", "clear", "compact"):
@@ -102,42 +106,67 @@ class LiveController:
if not self.cfg.shadow:
outputs.append(self.host.context("SessionStart", text))
s["injected_chars"] = len(text)
+ if "rendered_ids" in inj: # which facts, for this session's fold
+ s["injected_ids"] = list(inj["rendered_ids"])
digest = hashlib.sha1(text.encode("utf-8")).hexdigest()
if seen.get("injection") != digest:
outputs.append(self.host.notice(
f"TokenEconomizer: added {n_facts} learned fact(s) about "
f"{self.ctx.repo.label} to this session's context "
- f"(review with `{self._cmd('facts')}`)."))
+ f"(review with `{self._cmd('microskills')}`)."))
seen["injection"] = digest
- if (self.cfg.untool == "propose" and untool.supports(self.host.name)
+ if (self.cfg.toolprune == "propose" and denylist.supports(self.host.name)
and not self.cfg.shadow):
prop = (self.store.read("untool.json") or {}).get("proposal") or []
key = ",".join(prop)
if prop and seen.get("untool") != key:
outputs.append(self.host.notice(
- f"TokenEconomizer: {len(prop)} {untool.unit(self.host.name)}(s) went unused "
+ f"TokenEconomizer: {len(prop)} {denylist.unit(self.host.name)}(s) went unused "
f"in this repository's recent sessions ({', '.join(prop[:4])}"
f"{'...' if len(prop) > 4 else ''}). Review with "
- f"`{self._cmd('untool')}`; nothing changes until you apply it."))
+ f"`{self._cmd('toolprune')}`; nothing changes until you apply it."))
seen["untool"] = key
+ if self.cfg.repomap != "off":
+ if repomap.stale(self.ctx):
+ repomap.spawn_refresh(self.ctx)
+ at_start = self.cfg.repomap == "start" or not self.host.prompt_context
+ if at_start and source in ("startup", "new", "clear", "compact"):
+ outputs.extend(self._inject_map(s, seen, repomap.cached_block(self.ctx),
+ "SessionStart", "cached"))
+ s["repomap_done"] = True
+
if outputs:
self.store.write("notices.json", seen)
self._save(s)
fold.spawn_fold(self.ctx, fold.pending_sessions(self.ctx, exclude=(self.sid,)))
return merge_outputs(*outputs)
+ def _inject_map(self, s, seen, block, event, how):
+ """The outputs that put the repository map in context (and say so, once per repository)."""
+ self._log("repomap", chars=len(block), how=how)
+ if not block or self.cfg.shadow:
+ return []
+ s["repomap_chars"] = len(block)
+ out = [self.host.context(event, block)]
+ if not seen.get("repomap"):
+ out.append(self.host.notice(
+ f"TokenEconomizer: added a map of {self.ctx.repo.label}'s key files and symbols "
+ f"to this session's context (~{len(block) // 4} tokens; `repomap=off` to stop)."))
+ seen["repomap"] = True
+ return out
+
# ---- prompt-turns -------------------------------------------------------------------
def _close_turn(self, s, stopped_normally):
data = s.get("turn")
if not data:
return None
- g = guard.TurnGuard(data=data)
+ g = loopguard.TurnGuard(data=data)
summary = g.summary(stopped_normally)
if g.cum_turns and stopped_normally:
- guard.record_turn(self.store, g, level=self.cfg.spiral_aggr,
- overrides=self.cfg.spiral_thresholds)
+ loopguard.record_turn(self.store, g, level=self.cfg.loopguard_aggr,
+ overrides=self.cfg.loopguard_thresholds)
s["turns"] = (s.get("turns") or [])[-(TURN_HISTORY - 1):] + [summary]
s["judge_tokens"] = float(s.get("judge_tokens", 0) or 0) + g.judge_tokens
s["writer_tokens"] = float(s.get("writer_tokens", 0) or 0) + g.writer_tokens
@@ -145,18 +174,29 @@ class LiveController:
return summary
def user_prompt(self):
- if self.cfg.spiral == "off":
+ if self.cfg.loopguard == "off" and not (self.cfg.repomap == "on"
+ and self.host.prompt_context):
return {}
s = self._session()
- # A turn still open here never reached Stop -- the person interrupted it. Its outcome
- # is unknown, so it is recorded but does not feed the envelope.
- self._close_turn(s, stopped_normally=False)
- s["turn"] = guard.TurnGuard(turn_key=self.host.turn_key(self.p)).to_dict()
+ outputs = []
+ if self.cfg.repomap == "on" and self.host.prompt_context and not s.get("repomap_done"):
+ # Once per session, on its first prompt: a map ranked toward what the prompt names.
+ s["repomap_done"] = True
+ seen = self.store.read("notices.json") or {}
+ block, how = repomap.for_prompt(self.ctx, self.p.get("prompt") or "")
+ outputs = self._inject_map(s, seen, block, "UserPromptSubmit", how)
+ if outputs:
+ self.store.write("notices.json", seen)
+ if self.cfg.loopguard != "off":
+ # A turn still open here never reached Stop -- the person interrupted it. Its
+ # outcome is unknown, so it is recorded but does not feed the envelope.
+ self._close_turn(s, stopped_normally=False)
+ s["turn"] = loopguard.TurnGuard(turn_key=self.host.turn_key(self.p)).to_dict()
self._save(s)
- return {}
+ return merge_outputs(*outputs) if outputs else {}
def stop(self):
- if self.cfg.spiral == "off" or self.p.get("stop_hook_active"):
+ if self.cfg.loopguard == "off" or self.p.get("stop_hook_active"):
return {}
s = self._session()
summary = self._close_turn(s, stopped_normally=True)
@@ -167,18 +207,16 @@ class LiveController:
# ---- PostToolUse ---------------------------------------------------------------------
def _judge(self, thr):
- """The paid stuck judge, run in the background (`te_live.judge`), or None.
-
- It used to run here, inside the hook, with the nudge writer after it: ~22 s with the
- agent waiting, per nudge, in the user-simulation pilot. Now the hook only starts a job
- and a later call picks up its verdict, with the redirect already written."""
+ """The paid stuck judge, run in the background (`judge.AsyncJudge`), or None: the
+ hook only starts a job, and a later call picks up its verdict with the redirect already
+ written, so the agent never waits on it."""
if not self.cfg.paid:
return None
from .judge import AsyncJudge
return AsyncJudge(self.ctx, self.sid, thr.get("judge_confidence"))
def post_tool(self):
- if self.cfg.spiral == "off" or self.host.is_subagent(self.p):
+ if self.cfg.loopguard == "off" or self.host.is_subagent(self.p):
return {}
s = self._session()
key = self.host.turn_key(self.p)
@@ -186,14 +224,14 @@ class LiveController:
if data and key and data.get("turn_key") and data["turn_key"] != key:
self._close_turn(s, stopped_normally=False) # a turn we never saw end
data = None
- g = guard.TurnGuard(data=data) if data else guard.TurnGuard(turn_key=key)
+ g = loopguard.TurnGuard(data=data) if data else loopguard.TurnGuard(turn_key=key)
name, args, text, code = self.host.tool_call(self.p)
- tracker = guard.load_envelope(self.store, level=self.cfg.spiral_aggr,
- overrides=self.cfg.spiral_thresholds)
+ tracker = loopguard.load_envelope(self.store, level=self.cfg.loopguard_aggr,
+ overrides=self.cfg.loopguard_thresholds)
envelope = tracker.envelope
- thr = guard.thresholds(tracker, self.cfg.spiral_thresholds)
+ thr = loopguard.thresholds(tracker, self.cfg.loopguard_thresholds)
decision = g.fold(name, args, text, code, envelope=envelope, thr=thr,
- judge=self._judge(thr), nudge_budget=self.cfg.spiral_nudges)
+ judge=self._judge(thr), nudge_budget=self.cfg.loopguard_nudges)
out = {}
if decision:
action, reason = decision
@@ -211,7 +249,7 @@ class LiveController:
elif action == "abort" and not g.abort_delivered:
g.abort_delivered = True
s["aborts"] = int(s.get("aborts", 0)) + 1
- can_stop = (self.cfg.spiral == "guard" and self.ctx.headless
+ can_stop = (self.cfg.loopguard == "stop" and self.ctx.headless
and self.host.can_stop_mid_turn)
self._log("abort", reason=reason, tool_calls=g.cum_turns, envelope=envelope,
delivered="stop" if can_stop else "notice")
diff --git a/te_live/untool.py b/tokeneconomizer/plugin/denylist.py
similarity index 57%
rename from te_live/untool.py
rename to tokeneconomizer/plugin/denylist.py
index 0137b1a..4dd1c41 100644
--- a/te_live/untool.py
+++ b/tokeneconomizer/plugin/denylist.py
@@ -1,57 +1,48 @@
-"""Applying an untool proposal on each host, and measuring the request with and without it.
+"""Writing an approved tool-pruning proposal into each agent's own settings, and taking it back.
-Evidence untooling decides WHICH tools to drop (`mechanisms.tooling.ToolingStage`, driven by
-`live.fold`). On the benchmark the harness applied the decision at launch. A plugin launches
-nothing, so on each host the lever is a per-repository settings file the agent reads at session
-start, and the unit of removal is whatever that file can express:
+Tool pruning decides WHICH tools to drop (`toolprune.ToolingStage`, run by `fold`). A plugin
+launches nothing, so on each host the lever is a per-repository settings file the agent reads at
+session start, and the unit of removal is whatever that file can express:
* Claude Code -- a TOOL. A bare-name `permissions.deny` rule removes the tool from the
session's tool list, not merely refusing the call. Verified on 2.1.286: three deny rules
took a session from 30 tools to 27, the same list `--disallowed-tools` produced, and the
same rules in a project's `.claude/settings.local.json` took it to 23.
- * Codex -- a CAPABILITY package (`mechanisms.codex_untool`), written as config toggles into
- the project's `.codex/config.toml`. Verified on 0.153.1 with `codex debug prompt-input`:
- the collaboration, goals and image toggles take effect from a project-local file -- but
- ONLY in a trusted project; an untrusted project's `.codex/` is ignored, so `apply` checks
- trust and says so. The `skills` package is not
- offered: its toggle (`[[skills.config]] enabled = false` per bundled skill) takes effect in
- the user-level config only, and a per-repository decision does not belong there.
+ * Codex -- a CAPABILITY package (`toolprune.codex`), written as config toggles into the
+ project's `.codex/config.toml`. Verified on 0.153.1 with `codex debug prompt-input`: the
+ collaboration, goals and image toggles take effect from a project-local file -- but ONLY in
+ a trusted project; an untrusted project's `.codex/` is ignored, so `apply` checks trust and
+ says so. The `skills` package is not offered: its toggle takes effect in the user-level
+ config only, and a per-repository decision does not belong there.
* Copilot CLI -- an MCP SERVER, through `disabledMcpServers` in the repository's
`.github/copilot/settings.local.json`. Verified on 1.0.83: listing the built-in
`github-mcp-server` removes its tools from the request -- but, as on Codex, ONLY in a
- trusted folder (Copilot's `trustedFolders`, which its first-run prompt fills): the same
- file in an untrusted directory changes nothing.
- `apply` checks trust and confirms the effect with a local capture. Copilot has no persistent per-tool filter (`--excluded-tools` is a launch
- flag; `permissions.deny` refuses calls but leaves the schema in the request), so a server
- is proposed only when every one of its tools has gone unused.
+ trusted folder (Copilot's `trustedFolders`). Copilot has no persistent per-tool filter
+ (`--excluded-tools` is a launch flag; `permissions.deny` refuses calls but leaves the schema
+ in the request), so a server is proposed only when every one of its tools has gone unused.
Rules common to all three:
- * Only the user's approval (`te untool apply`), or `untool: auto`, writes the file, and only
- from the NEXT session: tools are fixed at session start, and changing them mid-session would
- re-write the cached prompt prefix.
+ * Only the person's approval (`te toolprune apply`), or `toolprune: auto`, writes the file,
+ and only from the NEXT session: tools are fixed at session start, and changing them
+ mid-session would rewrite the cached prompt prefix.
* The writer adds and removes exactly the entries it recorded adding (`untool_applied.json`);
- an entry the user wrote is never touched.
+ an entry the person wrote is never touched.
* When the plugin creates the file, it adds the path to `.git/info/exclude`, so a file meant
to be per-user can never be committed by accident.
-Measuring: `measure` compares one request with and without the proposal. On Claude Code that is
-two small `claude -p` requests on the cheapest model. On Codex and Copilot it costs nothing: Codex renders its prompt
-input locally (`codex debug prompt-input`), and Copilot's request is captured by a scripted
-endpoint on localhost (`copilot_capture`), so no model is ever called.
+Checking what an applied list did, and measuring a request with and without it, is
+`toolcheck`'s job.
"""
import json
import os
import re
import shutil
import subprocess
-import tempfile
-import threading
import time
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from .. import trace
from . import adapter as live_adapter
-from . import transcripts
SETTINGS_REL = os.path.join(".claude", "settings.local.json")
CODEX_CONFIG_REL = os.path.join(".codex", "config.toml")
@@ -125,7 +116,7 @@ def _guard_target(repo_root, path):
"leads out of the repository")
-def _write_json(path, obj):
+def write_json(path, obj):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".te.tmp"
with open(tmp, "w", encoding="utf-8") as fh:
@@ -197,7 +188,7 @@ def _apply_json_list(repo_root, items, store, host):
if not added:
return []
lst.extend(added)
- _write_json(path, data)
+ write_json(path, data)
if created:
_exclude_from_git(repo_root, _SETTINGS[host])
_record(store, set(applied(store)) | set(added), path)
@@ -223,7 +214,7 @@ def _restore_json_list(repo_root, store, items, host):
holder.pop(key)
if outer and not holder:
data.pop(outer, None)
- _write_json(path, data)
+ write_json(path, data)
_record(store, mine - target, path)
return removed
@@ -433,16 +424,6 @@ def copilot_folder_trusted(path, env=None):
return False
-def verify_copilot(repo_root, servers, cli="copilot"):
- """{server: tools still in the request} for a session started in `repo_root`, by the local
- capture (no model call); None if no request could be captured."""
- body = copilot_capture(cwd=repo_root, cli=cli)
- if not body:
- return None
- names = _request_tools(body)
- return {s: sum(1 for n in names if n and n.startswith(s + "-")) for s in servers}
-
-
def codex_home(env=None):
env = os.environ if env is None else env
return env.get("CODEX_HOME") or os.path.join(os.path.expanduser("~"), ".codex")
@@ -471,28 +452,6 @@ def codex_project_trusted(repo_root, env=None):
return False
-def verify_codex(repo_root, capabilities, cli="codex", timeout=30):
- """What `codex features list`, run in the repository, says about the applied toggles:
- {feature: enabled} for the features those capabilities switch off, or None when the CLI
- is unavailable. Free: it reads configuration and calls no model."""
- feats = [k for c in capabilities for t, k, v in CODEX_TOGGLES.get(c, ())
- if t == "features"]
- if not feats or not shutil.which(cli):
- return None
- try:
- out = subprocess.run([cli, "features", "list"], capture_output=True, text=True,
- cwd=repo_root, timeout=timeout,
- env=dict(os.environ, TE_SIDECALL="1"))
- except (OSError, subprocess.SubprocessError):
- return None
- state = {}
- for line in (out.stdout or "").splitlines():
- parts = line.split()
- if len(parts) >= 2 and parts[0] in feats:
- state[parts[0]] = parts[-1] == "true"
- return state or None
-
-
# ---- dispatch ------------------------------------------------------------------------------
def apply(repo_root, tools, store, host="claude"):
"""Write `tools` (tools, capabilities or MCP servers, by host). Returns those newly added."""
@@ -522,7 +481,7 @@ def copilot_server_proposal(raw, catalog, used, servers):
"""MCP servers every one of whose catalog tools is in the evidence proposal `raw`."""
by_server = {}
for t in catalog:
- s = transcripts.mcp_server_of(t, servers)
+ s = trace.mcp_server_of(t, servers)
if s:
by_server.setdefault(s, set()).add(t)
raw = set(raw)
@@ -531,205 +490,3 @@ def copilot_server_proposal(raw, catalog, used, servers):
# ---- the catalog probe and the measurement ------------------------------------------------
-def _init_tools(extra_args, cli="claude", timeout=60):
- """Tool list from a `claude -p` session's init event; the process is killed right after it,
- before the model is asked anything."""
- env = dict(os.environ, TE_SIDECALL="1")
- cmd = [cli, "-p", "Reply with OK", "--output-format", "stream-json", "--verbose",
- "--model", "haiku", "--max-turns", "1"] + list(extra_args)
- with tempfile.TemporaryDirectory(prefix="te-probe-") as cwd:
- p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
- stderr=subprocess.DEVNULL, text=True, env=env, cwd=cwd)
- tools, version = None, None
- deadline = time.time() + timeout
- try:
- for line in p.stdout:
- try:
- ev = json.loads(line)
- except ValueError:
- continue
- if ev.get("type") == "system" and ev.get("subtype") == "init":
- tools, version = ev.get("tools"), ev.get("claude_code_version")
- break
- if time.time() > deadline:
- break
- finally:
- p.kill()
- p.wait()
- return tools, version
-
-
-class _Capture(BaseHTTPRequestHandler):
- """A chat-completions endpoint that records the request and answers "OK"."""
- def log_message(self, *a):
- pass
-
- def _send(self, body, ctype="application/json"):
- data = body.encode() if isinstance(body, str) else body
- self.send_response(200)
- self.send_header("Content-Type", ctype)
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
-
- def do_GET(self):
- self._send(json.dumps({"object": "list", "data": [{"id": "gpt-5.4", "object": "model"}]}))
-
- def do_POST(self):
- n = int(self.headers.get("Content-Length") or 0)
- try:
- body = json.loads(self.rfile.read(n) or b"{}")
- except ValueError:
- body = {}
- self.server.captured.append(body)
- msg = {"role": "assistant", "content": "OK"}
- usage = {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
- if body.get("stream"):
- chunks = [{"choices": [{"index": 0, "delta": msg, "finish_reason": None}]},
- {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
- {"choices": [], "usage": usage}]
- self._send("".join(f"data: {json.dumps(dict(c, object='chat.completion.chunk'))}"
- "\n\n" for c in chunks) + "data: [DONE]\n\n",
- "text/event-stream")
- else:
- self._send(json.dumps({"object": "chat.completion", "usage": usage, "choices": [
- {"index": 0, "message": msg, "finish_reason": "stop"}]}))
-
-
-def copilot_capture(extra_args=(), cwd=None, cli="copilot", timeout=90):
- """The first request a fresh `copilot -p` session sends, captured on localhost.
-
- Copilot's BYOK mode is pointed at a scripted endpoint in this process, so the request --
- system prompt, tool schemas -- is recorded exactly as Copilot builds it, and no model,
- credential or quota is touched. Returns the request body, or None."""
- srv = ThreadingHTTPServer(("127.0.0.1", 0), _Capture)
- srv.captured = []
- th = threading.Thread(target=srv.serve_forever, daemon=True)
- th.start()
- # The person's own model, when the environment names one: Copilot shapes its built-in tools
- # by model family (`edit`/`create` for Claude models, `apply_patch` for GPT ones).
- from .sidecall import copilot_model
- # A router's `provider/` prefix (OpenRouter: `anthropic/claude-haiku-4.5`) is not part of
- # the id Copilot recognises.
- model = (copilot_model() or "gpt-5.4").split("/", 1)[-1]
- env = {k: v for k, v in os.environ.items()
- if not k.startswith("COPILOT_PROVIDER_") and k != "COPILOT_MODEL"}
- env.update(TE_SIDECALL="1", COPILOT_PROVIDER_TYPE="openai",
- COPILOT_PROVIDER_BASE_URL=f"http://127.0.0.1:{srv.server_address[1]}/v1",
- COPILOT_PROVIDER_API_KEY="te-local-probe", COPILOT_MODEL=model,
- COPILOT_PROVIDER_WIRE_API="completions", NO_PROXY="127.0.0.1,localhost",
- no_proxy="127.0.0.1,localhost")
- tmp = None
- if cwd is None:
- tmp = tempfile.mkdtemp(prefix="te-probe-")
- cwd = tmp
- try:
- subprocess.run([cli, "-p", "Reply with OK", "--no-auto-update", "--no-color"]
- + list(extra_args), cwd=cwd, env=env, capture_output=True, text=True,
- timeout=timeout, stdin=subprocess.DEVNULL)
- except (OSError, subprocess.SubprocessError):
- pass
- finally:
- srv.shutdown()
- srv.server_close()
- if tmp:
- shutil.rmtree(tmp, ignore_errors=True)
- return srv.captured[0] if srv.captured else None
-
-
-def _request_tools(body):
- return [(t.get("function") or {}).get("name") or t.get("name") or t.get("type")
- for t in (body or {}).get("tools") or []]
-
-
-def _copilot_version(cli="copilot"):
- try:
- out = subprocess.run([cli, "--version"], capture_output=True, text=True, timeout=30)
- return (out.stdout or "").strip().splitlines()[0]
- except (OSError, subprocess.SubprocessError, IndexError):
- return None
-
-
-def refresh_catalog(state_root, cli=None, host="claude"):
- """Record the tool list a fresh session loads on this machine."""
- if host == "copilot":
- body = copilot_capture(cli=cli or "copilot")
- tools = [t for t in _request_tools(body) if t]
- if not tools:
- raise RuntimeError("could not capture the tool list of a `copilot -p` request")
- path = live_adapter.catalog_path(state_root, "copilot")
- _write_json(path, {"tools": sorted(tools), "copilot_version": _copilot_version(),
- "probed_at": time.time()})
- return path, sorted(tools)
- if host != "claude":
- raise RuntimeError(f"no catalog probe for {host}")
- tools, version = _init_tools([], cli=cli or "claude")
- if not tools:
- raise RuntimeError("could not read the tool list from a `claude -p` init event")
- path = live_adapter.catalog_path(state_root, "claude")
- _write_json(path, {"tools": sorted(tools), "claude_code_version": version,
- "probed_at": time.time()})
- return path, sorted(tools)
-
-
-def _prompt_tokens(extra_args, cli="claude", timeout=180):
- env = dict(os.environ, TE_SIDECALL="1")
- cmd = [cli, "-p", "Reply with exactly: OK", "--output-format", "json", "--model", "haiku",
- "--max-turns", "1"] + list(extra_args)
- with tempfile.TemporaryDirectory(prefix="te-measure-") as cwd:
- out = subprocess.run(cmd, capture_output=True, text=True, env=env, cwd=cwd,
- timeout=timeout)
- data = json.loads(out.stdout or "{}")
- u = data.get("usage") or {}
- return (sum(int(u.get(k) or 0) for k in ("input_tokens", "cache_read_input_tokens",
- "cache_creation_input_tokens")),
- data.get("total_cost_usd"))
-
-
-def _codex_prompt_chars(overrides, cli="codex", timeout=60):
- cmd = [cli, "debug", "prompt-input"]
- for table, key, value in overrides:
- cmd += ["-c", f"{table}.{key}={value}" if table else f"{key}={value}"]
- with tempfile.TemporaryDirectory(prefix="te-measure-") as cwd:
- out = subprocess.run(cmd + ["OK"], capture_output=True, text=True, cwd=cwd,
- timeout=timeout, env=dict(os.environ, TE_SIDECALL="1"))
- return len(out.stdout or "") if out.returncode == 0 else None
-
-
-def measure(tools, cli=None, host="claude"):
- """Request size with and without `tools` removed.
-
- Claude Code: prompt tokens of two small requests. Codex and Copilot: characters of the
- rendered request, and a ~4-characters-per-token estimate, at no cost."""
- if not tools:
- return None
- if host == "codex":
- toggles = [t for c in tools for t in CODEX_TOGGLES.get(c, ())]
- full = _codex_prompt_chars([], cli=cli or "codex")
- lean = _codex_prompt_chars(toggles, cli=cli or "codex")
- if full is None or lean is None:
- raise RuntimeError("`codex debug prompt-input` failed")
- return {"capabilities": list(tools), "prompt_input_chars_full": full,
- "prompt_input_chars_lean": lean, "saved_chars_per_request": full - lean,
- "saved_tokens_per_request_est": (full - lean) // 4,
- "note": "prompt input only (developer/user items); tool schemas not included",
- "probe_cost_usd": 0.0}
- if host == "copilot":
- args = [a for s in tools for a in ("--disable-mcp-server", s)]
- full = copilot_capture(cli=cli or "copilot")
- lean = copilot_capture(args, cli=cli or "copilot")
- if not full or not lean:
- raise RuntimeError("could not capture a `copilot -p` request")
- size = lambda b: len(json.dumps(b.get("tools"))) + len(json.dumps(b.get("messages")))
- return {"mcp_servers": list(tools),
- "tools_full": len(_request_tools(full)), "tools_lean": len(_request_tools(lean)),
- "request_chars_full": size(full), "request_chars_lean": size(lean),
- "saved_chars_per_request": size(full) - size(lean),
- "saved_tokens_per_request_est": (size(full) - size(lean)) // 4,
- "probe_cost_usd": 0.0}
- cli = cli or "claude"
- full, c1 = _prompt_tokens([], cli=cli)
- lean, c2 = _prompt_tokens(["--disallowed-tools", ",".join(tools)], cli=cli)
- return {"tools": list(tools), "prompt_tokens_full": full, "prompt_tokens_lean": lean,
- "saved_per_request": full - lean,
- "probe_cost_usd": round((c1 or 0) + (c2 or 0), 4)}
diff --git a/te_live/fold.py b/tokeneconomizer/plugin/fold.py
similarity index 79%
rename from te_live/fold.py
rename to tokeneconomizer/plugin/fold.py
index 511ff78..e5be66a 100644
--- a/te_live/fold.py
+++ b/tokeneconomizer/plugin/fold.py
@@ -1,8 +1,8 @@
"""Folding a finished session into what the plugin knows about its repository.
-This is the live counterpart of the experiments' `Economizer.after_task`, and it runs the same
-classes: `PrefixStage` learns and renders the injected manual (envfacts, plus the paid proposer
-when allowed), and `ToolingStage` accrues evidence untooling's used-tool and unused-streak state.
+It runs the mechanisms' own classes over the finished session: `PrefixStage` learns and renders
+the micro-skills (the LLM-free facts, plus the paid proposer when allowed), and `ToolingStage`
+accrues tool pruning's used-tool and unused-streak evidence.
A session is one "task" of the repository's stream for both, the unit they were built around.
Two adaptations, both forced by the setting:
@@ -21,12 +21,11 @@ it did not earn.
"""
import os
import shutil
-import subprocess
-import sys
import tempfile
import time
-from . import accounting, sidecall, transcripts, untool
+from .. import trace
+from . import accounting, denylist, sidecall
from . import adapter as live_adapter
from .adapter import LiveAdapter, load_catalog
@@ -52,46 +51,51 @@ def _run_dir(workdir, trace_path):
return run
-def _fold_injection(ctx, adapter, run_dir, session_id):
- profile = ctx.config.inject_effective
+def _fold_microskills(ctx, adapter, run_dir, session_id, injected=None):
+ profile = ctx.config.microskills_effective
if profile == "off":
return None
from tokeneconomizer.config import InjectionConfig
- from tokeneconomizer.mechanisms.injection import PrefixStage
- icfg = InjectionConfig(enabled=True, propose_every=ctx.config.propose_every, profile=profile,
- max_facts=ctx.config.inject_max_facts,
- max_tokens=ctx.config.inject_max_tokens)
+ from tokeneconomizer.microskills import PrefixStage
+ icfg = InjectionConfig(enabled=True, profile=profile,
+ propose_every=ctx.config.microskills_propose_every,
+ max_facts=ctx.config.microskills_max_facts,
+ max_tokens=ctx.config.microskills_max_tokens)
runner = sidecall.runner_for(ctx.host.name, ctx.config) if icfg.paid else None
stage = PrefixStage(icfg, ctx.repo.label, ctx.mech_dir, False, runner=runner,
optimizer_model="agent", adapter=adapter, agent=ctx.host.name)
srow = {"resolved": None}
- opt_tokens, reason = stage.after_task({"instance_id": session_id}, {}, run_dir, srow)
+ task = {"instance_id": session_id}
+ if injected is not None:
+ task["injected_ids"] = injected
+ opt_tokens, reason = stage.after_task(task, {}, run_dir, srow)
rendered = stage.render() or ""
prior = ctx.store.read("injection.json") or {}
ctx.store.write("injection.json", {
"profile": profile, "reason": reason, "rendered": rendered,
+ "rendered_ids": stage.injected_ids(),
"facts": srow.get("manual_facts"), "updated": time.time(),
"sessions": int(prior.get("sessions", 0)) + 1})
return {"optimizer_tokens": float(opt_tokens or 0), "rendered_chars": len(rendered)}
-def _fold_untool(ctx, adapter, run_dir, session_id, transcript=None, workdir=None):
- if not untool.supports(ctx.host.name) or ctx.config.untool == "off":
+def _fold_toolprune(ctx, adapter, run_dir, session_id, transcript=None, workdir=None):
+ if not denylist.supports(ctx.host.name) or ctx.config.toolprune == "off":
return None
if ctx.host.name == "codex":
- return _fold_untool_codex(ctx, adapter, session_id, transcript, workdir)
+ return _fold_toolprune_codex(ctx, adapter, session_id, transcript, workdir)
host = ctx.host.name
from tokeneconomizer.config import ToolingConfig
- from tokeneconomizer.mechanisms.tooling import ToolingStage
+ from tokeneconomizer.toolprune import ToolingStage
st = ctx.store.read("untool.json") or {}
- stage = ToolingStage(ToolingConfig(evidence=ctx.config.untool_evidence), host, "agent",
+ stage = ToolingStage(ToolingConfig(evidence=ctx.config.toolprune_evidence), host, "agent",
adapter=adapter, repo=ctx.repo.label, results_root=ctx.mech_dir,
fresh=True)
stage.used_tools = set(st.get("used_tools", []))
stage.tool_unused_streaks = {k: int(v) for k, v in (st.get("streaks") or {}).items()}
stage.catalog_tools = set(st.get("catalog_tools", []))
stage.catalog_desc = dict(st.get("catalog_desc") or {})
- applied = untool.applied(ctx.store)
+ applied = denylist.applied(ctx.store)
stage._exclude_tools = list(applied) # the mask this session actually ran under
# A tool that has since become protected (the web tools, from this version on) comes back:
# remove the plugin's OWN deny rule for it. Only rules it recorded adding, never one the
@@ -100,12 +104,12 @@ def _fold_untool(ctx, adapter, run_dir, session_id, transcript=None, workdir=Non
restored = []
if any(t in protected for t in applied) and not ctx.config.shadow:
try:
- restored = untool.restore(ctx.repo.root, ctx.store,
+ restored = denylist.restore(ctx.repo.root, ctx.store,
[t for t in applied if t in protected], host=host)
except RuntimeError: # an unreadable or redirected settings file: leave it
restored = []
if restored:
- applied = untool.applied(ctx.store)
+ applied = denylist.applied(ctx.store)
# The stage warns once per STREAM when no catalog parses -- a harness defect signal there.
# Here a stage lives for one fold, and a session that called no tool legitimately has no
# observed catalog; the source (or its absence) is recorded in untool.json instead.
@@ -121,21 +125,21 @@ def _fold_untool(ctx, adapter, run_dir, session_id, transcript=None, workdir=Non
"catalog_source": srow.get("untool_catalog_source") or st.get("catalog_source"),
"sessions": sessions, "updated": time.time()}
if host == "copilot":
- # Copilot's only persistent lever is a whole MCP server (`untool` module docstring).
- servers = transcripts.copilot_mcp_servers(ctx.env)
- proposal = [s for s in untool.copilot_server_proposal(
+ # Copilot's only persistent lever is a whole MCP server (see `denylist`).
+ servers = trace.copilot_mcp_servers(ctx.env)
+ proposal = [s for s in denylist.copilot_server_proposal(
raw, stage.catalog_tools, stage.used_tools, servers) if s not in applied]
doc["servers"] = _server_summary(stage, servers)
else:
- proposal = [t for t in untool.filter_proposal(raw, stage.tool_unused_streaks,
- ctx.config.untool_evidence)
+ proposal = [t for t in denylist.filter_proposal(raw, stage.tool_unused_streaks,
+ ctx.config.toolprune_evidence)
if t not in applied]
doc["proposal"] = proposal
doc["new_in_proposal"] = sorted(set(proposal) - set(st.get("proposal", [])))
added = []
- if ctx.config.untool == "auto" and proposal and not ctx.config.shadow:
+ if ctx.config.toolprune == "auto" and proposal and not ctx.config.shadow:
try:
- added = untool.apply(ctx.repo.root, proposal, ctx.store, host=host)
+ added = denylist.apply(ctx.repo.root, proposal, ctx.store, host=host)
doc["proposal"], doc["auto_applied"] = [], added
except RuntimeError as e: # an unreadable or redirected file: keep proposing
doc["auto_apply_refused"] = str(e)
@@ -149,7 +153,7 @@ def _server_summary(stage, servers):
"""{server: {tools, used, unused_sessions}} -- the Copilot evidence at the unit it acts on."""
out = {}
for t in stage.catalog_tools:
- s = transcripts.mcp_server_of(t, servers)
+ s = trace.mcp_server_of(t, servers)
if not s:
continue
e = out.setdefault(s, {"tools": 0, "used": False, "unused_sessions": None})
@@ -160,42 +164,42 @@ def _server_summary(stage, servers):
return out
-def _fold_untool_codex(ctx, adapter, session_id, transcript, workdir):
+def _fold_toolprune_codex(ctx, adapter, session_id, transcript, workdir):
"""Codex: the experiments' capability controller (`codex_untool.CodexUntoolProfile`, driven
through `ToolingStage`) decides which packages went unused, over a trace that carries the
- model's own `exec` calls (`transcripts.codex_capability_trace`). Two live adaptations:
+ model's own `exec` calls (`trace.codex_capability_trace`). Two live adaptations:
* the session ran under the capabilities the PERSON applied, not the profile's own mask
(a plugin launches nothing), so the observation is recorded against the applied set;
* a package is proposed only once the profile has demoted it AND it went unused in
- `untool_evidence` sessions (x3 for image/media, the high-risk package), with no use
+ `toolprune_evidence` sessions (x3 for image/media, the high-risk package), with no use
ever -- the profile alone demotes collaboration after one unused task, which was right
for a sealed benchmark stream and is too quick for a person's sessions."""
from tokeneconomizer.config import ToolingConfig
- from tokeneconomizer.mechanisms.tooling import ToolingStage
+ from tokeneconomizer.toolprune import ToolingStage
if not transcript or not workdir:
return None
cap_dir = os.path.join(workdir, "capabilities")
os.makedirs(cap_dir, exist_ok=True)
cap_trace = os.path.join(cap_dir, "trace.jsonl")
- if transcripts.codex_capability_trace(transcript, cap_trace) is None:
+ if trace.codex_capability_trace(transcript, cap_trace) is None:
return None
run_dir = _run_dir(cap_dir, cap_trace)
stage = ToolingStage(ToolingConfig(codex_untool=True), "codex", "agent", adapter=adapter,
repo=ctx.repo.label, results_root=ctx.mech_dir, fresh=False)
stage._warned_no_catalog = True
stage.build_tools({"instance_id": session_id}, 0)
- applied = untool.applied(ctx.store)
+ applied = denylist.applied(ctx.store)
stage.codex_profile._pending["logical_capabilities"] = sorted(applied)
srow = {}
stage.after_task({"instance_id": session_id}, {}, run_dir, srow)
state = stage.codex_profile.state
ever_used = set(state.get("ever_completed") or ())
loaded = state.get("loaded_exposures") or {}
- proposal = [c for c in untool.CODEX_LIVE_CAPABILITIES
+ proposal = [c for c in denylist.CODEX_LIVE_CAPABILITIES
if c in (state.get("current_pruned") or ()) and c not in ever_used
and c not in applied
- and int(loaded.get(c, 0)) >= ctx.config.untool_evidence * (
+ and int(loaded.get(c, 0)) >= ctx.config.toolprune_evidence * (
live_adapter.HIGH_RISK_FACTOR if c in CODEX_HIGH_RISK else 1)]
prior = ctx.store.read("untool.json") or {}
doc = {"sessions": int(state.get("tasks_completed") or 0), "catalog_source": "capabilities",
@@ -203,13 +207,13 @@ def _fold_untool_codex(ctx, adapter, session_id, transcript, workdir):
"unused_sessions": int((state.get("zero_attempt_exposures")
or {}).get(c, 0)),
"used": c in ever_used}
- for c in untool.CODEX_LIVE_CAPABILITIES},
+ for c in denylist.CODEX_LIVE_CAPABILITIES},
"proposal": proposal, "updated": time.time(),
"new_in_proposal": sorted(set(proposal) - set(prior.get("proposal", [])))}
added = []
- if ctx.config.untool == "auto" and proposal and not ctx.config.shadow:
+ if ctx.config.toolprune == "auto" and proposal and not ctx.config.shadow:
try:
- added = untool.apply(ctx.repo.root, proposal, ctx.store, host="codex")
+ added = denylist.apply(ctx.repo.root, proposal, ctx.store, host="codex")
doc["proposal"], doc["auto_applied"] = [], added
except RuntimeError as e: # a committed or unparseable file: keep proposing
doc["auto_apply_refused"] = str(e)
@@ -247,8 +251,9 @@ def fold_session(ctx, session_id, transcript_path=None):
adapter = LiveAdapter(ctx.host, ctx.repo.root, vocabulary=ctx.config.vocabulary,
catalog=load_catalog(ctx.root, ctx.host.name))
with ctx.store.locked("mechanisms"):
- inj = _fold_injection(ctx, adapter, run_dir, session_id)
- unt = _fold_untool(ctx, adapter, run_dir, session_id,
+ inj = _fold_microskills(ctx, adapter, run_dir, session_id,
+ injected=sess.get("injected_ids"))
+ unt = _fold_toolprune(ctx, adapter, run_dir, session_id,
transcript=transcript, workdir=workdir)
record["injection"] = inj
record["untool"] = unt
@@ -264,7 +269,7 @@ def fold_session(ctx, session_id, transcript_path=None):
"turns": len(turns),
"nudges": int(sess.get("nudges", 0)), "aborts": int(sess.get("aborts", 0)),
"injected_chars": int(sess.get("injected_chars", 0)),
- "untool_applied": untool.applied(ctx.store),
+ "untool_applied": denylist.applied(ctx.store),
"overhead": {
"optimizer_tokens": ((record.get("injection") or {}).get("optimizer_tokens")
or 0),
@@ -312,18 +317,5 @@ def spawn_fold(ctx, session_ids):
return None
if ctx.env.get("TE_FOLD_SYNC") == "1":
return [fold_session(ctx, sid) for sid in session_ids]
- # The directory holding both packages: the checkout, or the bundle's lib/.
- core = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- env = dict(ctx.env)
- env["PYTHONPATH"] = core + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
- cmd = [sys.executable, "-m", "te_live.cli", "fold",
- "--host", ctx.host.name, "--cwd", ctx.repo.root] + [
- a for sid in session_ids for a in ("--session", sid)]
- ctx.store.ensure()
- log = open(ctx.store.path("fold.log"), "a")
- try:
- subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log,
- cwd=ctx.repo.root, env=env, start_new_session=True)
- finally:
- log.close()
- return True
+ return ctx.spawn(["fold"] + [a for sid in session_ids for a in ("--session", sid)],
+ "fold.log")
diff --git a/te_live/hook.py b/tokeneconomizer/plugin/hook.py
similarity index 94%
rename from te_live/hook.py
rename to tokeneconomizer/plugin/hook.py
index 2e89917..ed35d13 100644
--- a/te_live/hook.py
+++ b/tokeneconomizer/plugin/hook.py
@@ -1,11 +1,11 @@
"""The entry point every plugin hook executes: hook JSON on stdin, hook JSON on stdout.
- python -m te_live.hook [--host claude|codex]
+ python -m tokeneconomizer.plugin.hook [--host claude|codex|copilot|pi]
It never fails the agent. Whatever goes wrong -- unreadable input, a full disk, a bug -- the hook
prints `{}` (which changes nothing) and records the traceback in `<state root>/errors.log`. It
also does nothing at all in two cases: `TE_DISABLE=1`, and `TE_SIDECALL=1`, which marks the
-nested agent process of the plugin's own paid side calls (`live.sidecall`) so it cannot recurse
+nested agent process of the plugin's own paid side calls (`sidecall`) so it cannot recurse
into these hooks.
"""
import contextlib
diff --git a/te_live/hosts.py b/tokeneconomizer/plugin/hosts.py
similarity index 88%
rename from te_live/hosts.py
rename to tokeneconomizer/plugin/hosts.py
index aea83e3..30373cf 100644
--- a/te_live/hosts.py
+++ b/tokeneconomizer/plugin/hosts.py
@@ -16,7 +16,7 @@ an adapter rather than a branch in a mechanism:
* Tool results. Claude Code's Bash `tool_response` is `{stdout, stderr, interrupted, ...}` with
no exit code (verified); Codex's command items carry one, and it is used when present.
* The session log. Claude Code's transcript is read as-is; Codex's rollout is rewritten into
- exec-stream lines first (`transcripts.codex_rollout_to_exec`).
+ exec-stream lines first (`trace.codex_rollout_to_exec`).
The GitHub Copilot CLI runs the same Claude-format hook file (PascalCase events, Claude-shaped
snake_case payloads), with differences each verified on 1.0.83 against a local scripted model
@@ -44,10 +44,9 @@ import json
import os
import re
import shlex
-import tempfile
import time
-from . import transcripts
+from .. import trace
_RESPONSE_KEYS = ("stdout", "stderr", "output", "aggregated_output", "formatted_output",
"content", "result", "error", "message", "text_result_for_llm")
@@ -111,6 +110,8 @@ def merge_outputs(*outputs):
class Host:
name = "?"
can_stop_mid_turn = False
+ # Whether context returned from UserPromptSubmit reaches the model (verified per host).
+ prompt_context = False
def session_id(self, p):
return str(p.get("session_id") or "")
@@ -140,9 +141,12 @@ class Host:
return False
def tool_call(self, p):
- """(tool_name, args, result_text, exit_code_or_None) for a PostToolUse payload."""
+ """(tool_name, args, result_text, exit_code_or_None) for a PostToolUse payload, or for
+ a PostToolUseFailure one: Claude Code reports a call that failed -- a non-zero exit, a
+ refused command, a file that is not there -- only there, with an `error` string
+ ("Exit code 2\nls: cannot access ...") and no `tool_response` (2.1.299)."""
args = p.get("tool_input") if isinstance(p.get("tool_input"), dict) else {}
- resp = p.get("tool_response")
+ resp = _failure_response(p) or p.get("tool_response")
return str(p.get("tool_name") or ""), args, response_text(resp), _exit_code(resp)
# -- the finished session, in the shapes the mechanisms read --------------------------
@@ -157,10 +161,21 @@ class Host:
"""Wait, if this host needs to, until the finished session's log is complete."""
def tool_usage(self, trace_path):
- from tokeneconomizer import trace
return trace.tool_usage(trace_path)
+def _failure_response(p):
+ """A PostToolUseFailure payload's `error` as a response; None for any other payload. A
+ shell failure names its exit code ("Exit code 2"); other failures carry none."""
+ if p.get("tool_response") is not None or p.get("tool_result") is not None or \
+ p.get("error") is None:
+ return None
+ text = str(p.get("error"))
+ m = _EXIT_RE.search(text[:400])
+ return dict({"error": text, "result_type": "failure"},
+ **({"exit_code": int(m.group(1))} if m else {}))
+
+
def _exit_code(resp):
if isinstance(resp, dict):
for k in ("exit_code", "exitCode", "returncode", "status_code"):
@@ -186,6 +201,7 @@ def _exit_code(resp):
class ClaudeCode(Host):
name = "claude"
can_stop_mid_turn = True
+ prompt_context = True
def turn_key(self, p):
return str(p.get("prompt_id") or "")
@@ -203,10 +219,10 @@ class ClaudeCode(Host):
return str(env.get("CLAUDE_CODE_ENTRYPOINT", "")).startswith("sdk")
def session_usage(self, transcript_path):
- return transcripts.claude_session_usage(transcript_path)
+ return trace.claude_session_usage(transcript_path)
def tool_usage(self, trace_path):
- return transcripts.claude_tool_usage(os.path.realpath(trace_path))
+ return trace.claude_tool_usage(os.path.realpath(trace_path))
_CODEX_SHELL = {"bash", "shell", "exec_command", "local_shell", "unified_exec",
@@ -237,11 +253,11 @@ class Codex(Host):
def mechanism_trace(self, transcript_path, workdir):
out = os.path.join(workdir, "codex_exec_trace.jsonl")
- n = transcripts.codex_rollout_to_exec(transcript_path, out)
+ n = trace.codex_rollout_to_exec(transcript_path, out)
return out if n is not None else None
def session_usage(self, transcript_path):
- return transcripts.codex_session_usage(transcript_path)
+ return trace.codex_session_usage(transcript_path)
class Pi(Host):
@@ -259,6 +275,7 @@ class Pi(Host):
"""
name = "pi"
can_stop_mid_turn = True
+ prompt_context = True # the extension appends it to the session's section
def turn_key(self, p):
return str(p.get("prompt_id") or "")
@@ -271,11 +288,11 @@ class Pi(Host):
def mechanism_trace(self, transcript_path, workdir):
out = os.path.join(workdir, "pi_trace.jsonl")
- n = transcripts.pi_session_to_claude(transcript_path, out)
+ n = trace.pi_session_to_claude(transcript_path, out)
return out if n is not None else None
def session_usage(self, transcript_path):
- return transcripts.pi_session_usage(transcript_path)
+ return trace.pi_session_usage(transcript_path)
def copilot_home(env=None):
@@ -287,6 +304,7 @@ class Copilot(Host):
"""The GitHub Copilot CLI, through `plugin/.github/plugin/plugin.json` and its hook file."""
name = "copilot"
can_stop_mid_turn = False
+ prompt_context = True # verified: top-level additionalContext
def transcript(self, p):
# Only Stop carries `transcript_path`; the log's location is fixed by the session id.
@@ -305,13 +323,11 @@ class Copilot(Host):
def tool_call(self, p):
args = p.get("tool_input") if isinstance(p.get("tool_input"), dict) else {}
- resp = p.get("tool_result")
- if resp is None and p.get("error") is not None: # PostToolUseFailure
- resp = {"error": str(p.get("error")), "result_type": "failure"}
+ resp = _failure_response(p) or p.get("tool_result")
return str(p.get("tool_name") or ""), args, response_text(resp), _exit_code(resp)
def session_usage(self, transcript_path):
- return transcripts.copilot_session_usage(transcript_path)
+ return trace.copilot_session_usage(transcript_path)
def settle(self, transcript_path, wait_s=15.0, fresh_s=60.0):
# Copilot writes `session.shutdown` -- the event that carries usage -- just AFTER the
@@ -335,10 +351,11 @@ class Copilot(Host):
HOSTS = {"claude": ClaudeCode, "codex": Codex, "copilot": Copilot, "pi": Pi}
-def default_host(env=None):
+def default_host(env=None, recent=None):
"""The host a `te` command run without `--host` is about: `TE_HOST`, else the agent whose
shell it runs in (Claude Code marks its shell `CLAUDECODE=1`, Copilot `COPILOT_CLI=1`),
- else Claude Code."""
+ else -- a plain terminal -- `recent`, the agent that last worked in this repository (see
+ `cli`), else Claude Code."""
env = os.environ if env is None else env
if env.get("TE_HOST") in HOSTS:
return env["TE_HOST"]
@@ -346,7 +363,7 @@ def default_host(env=None):
return "claude"
if env.get("COPILOT_CLI") == "1":
return "copilot"
- return "claude"
+ return recent if recent in HOSTS else "claude"
def detect(payload, env=None, hint=None):
@@ -366,7 +383,3 @@ def detect(payload, env=None, hint=None):
if not tp and (env or {}).get("COPILOT_PLUGIN_ROOT"):
return Copilot()
return ClaudeCode()
-
-
-def scratch_dir(prefix="te-"):
- return tempfile.mkdtemp(prefix=prefix)
diff --git a/te_live/judge.py b/tokeneconomizer/plugin/judge.py
similarity index 71%
rename from te_live/judge.py
rename to tokeneconomizer/plugin/judge.py
index 93a3fe9..25c0fe8 100644
--- a/te_live/judge.py
+++ b/tokeneconomizer/plugin/judge.py
@@ -1,22 +1,19 @@
-"""The paid spiral judge, off the hook's critical path.
+"""The loop guard's paid judge, off the hook's critical path.
With `paid` on, the guard's gate can ask an LLM whether a turn is stuck and, when it is, have a
second call write the redirect. Both are side calls through the agent's own CLI (`sidecall`),
-and run inside a PostToolUse hook they held the agent for ~22 s per nudge in the user-simulation
-pilot. So the hook only STARTS a job here and returns: `AsyncJudge.start` writes the request and
+and run inside a PostToolUse hook they would hold the agent for tens of seconds. So the hook
+only STARTS a job here and returns: `AsyncJudge.start` writes the request and
spawns `te judge` detached; the job runs the judge, and the nudge writer only when the verdict is
stuck, then leaves the verdict -- with the redirect already written -- for the next PostToolUse,
-whose `AsyncJudge.poll` hands it to the guard. The cascade the guard runs (`assess_abort`) is the
-vendored one: while a verdict is pending the judge answers nothing, which it already reads as
-"throttled", so the decision rules are unchanged; only their latency moved off the agent.
+whose `AsyncJudge.poll` hands it to the guard. The cascade the guard runs (`assess_abort`) is
+unchanged: while a verdict is pending the judge answers nothing, which it already reads as
+"throttled"; only the latency moved off the agent.
What a job spends is charged to the ledger the moment it is spent, as its own `overhead` record
for the session: a verdict that lands after its turn -- or its session -- has ended was still paid
for, and must not drop out of the account.
"""
-import os
-import subprocess
-import sys
import time
from . import sidecall
@@ -55,7 +52,7 @@ class AsyncJudge:
def run_job(ctx, session_id, job_id):
"""The detached half: judge the digest, write the redirect if stuck, charge the ledger."""
- from tokeneconomizer.vendor import reflect
+ from ..loopguard import judge as loop_judge
req = ctx.store.read(REQUEST.format(sid=session_id)) or {}
if req.get("id") != job_id: # superseded by a newer request
return None
@@ -63,14 +60,14 @@ def run_job(ctx, session_id, job_id):
verdict, written = None, None
if runner is not None:
try:
- verdict = reflect.llm_stuck_judge(req.get("digest") or "", runner, model="agent")
+ verdict = loop_judge.llm_stuck_judge(req.get("digest") or "", runner, model="agent")
except Exception:
verdict = None
conf = float((verdict or {}).get("confidence") or 0)
if verdict and verdict.get("stuck") and conf >= float(req.get("threshold") or 0):
try:
- written = reflect.llm_nudge_writer(req.get("digest") or "", runner,
- model="agent")
+ written = loop_judge.llm_nudge_writer(req.get("digest") or "", runner,
+ model="agent")
except Exception:
written = None
if written and (written.get("text") or "").strip():
@@ -92,16 +89,4 @@ def spawn_job(ctx, session_id, job_id):
"""Run a judge job detached (inline when TE_JUDGE_SYNC=1, for tests)."""
if ctx.env.get("TE_JUDGE_SYNC") == "1":
return run_job(ctx, session_id, job_id)
- core = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- env = dict(ctx.env)
- env["PYTHONPATH"] = core + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
- cmd = [sys.executable, "-m", "te_live.cli", "judge", "--host", ctx.host.name,
- "--cwd", ctx.repo.root, "--session", session_id, "--job", job_id]
- ctx.store.ensure()
- log = open(ctx.store.path("judge.log"), "a")
- try:
- subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log,
- cwd=ctx.repo.root, env=env, start_new_session=True)
- finally:
- log.close()
- return True
+ return ctx.spawn(["judge", "--session", session_id, "--job", job_id], "judge.log")
diff --git a/te_live/paths.py b/tokeneconomizer/plugin/paths.py
similarity index 98%
rename from te_live/paths.py
rename to tokeneconomizer/plugin/paths.py
index e85740c..8bb7d49 100644
--- a/te_live/paths.py
+++ b/tokeneconomizer/plugin/paths.py
@@ -178,7 +178,8 @@ class RepoId:
def repo_identity(cwd, env=None):
"""Identify the repository a session in `cwd` belongs to."""
root = find_repo_root(cwd, env) or os.path.abspath(cwd or os.getcwd())
- remote = normalize_remote(origin_url(root)) if os.path.exists(os.path.join(root, ".git")) else ""
+ has_git = os.path.exists(os.path.join(root, ".git"))
+ remote = normalize_remote(origin_url(root)) if has_git else ""
canon = remote or os.path.realpath(root)
label = "/".join(remote.split("/")[-2:]) if remote else os.path.basename(root.rstrip("/"))
digest = hashlib.sha1(canon.encode("utf-8")).hexdigest()[:10]
diff --git a/te_live/probe.py b/tokeneconomizer/plugin/probe.py
similarity index 93%
rename from te_live/probe.py
rename to tokeneconomizer/plugin/probe.py
index d37395c..b7e0566 100644
--- a/te_live/probe.py
+++ b/tokeneconomizer/plugin/probe.py
@@ -8,10 +8,9 @@ real sessions with the plugin loaded, under a state root of its own -- your lear
never touched. The trap is the commonest one in Python repositories: the project is set up for
pytest (`[tool.pytest.ini_options]`), but pytest is not installed, so bare `pytest` and
`python -m pytest` both fail while the tests, written with `unittest`, pass under
-`python -m unittest`. (A first version made only bare `pytest` fail; Haiku never typed it, so
-nothing was learned.) The repository is created inside a folder Copilot trusts when there is
-one, because Copilot ignores an untrusted folder's settings, the deny list's file included. Then it applies the deny list it proposed, runs one more session, restores it,
-and reports:
+`python -m unittest`. The repository is created inside a folder Copilot trusts when there is
+one, because Copilot ignores an untrusted folder's settings, the deny list's file included.
+Then it applies the deny list it proposed, runs one more session, restores it, and reports:
* per session: whether the learned fact was in the context, the first test command the
model ran, how many test commands failed, the request's tool-definition tokens;
@@ -31,7 +30,8 @@ import sys
import tempfile
import time
-from . import hosts, sidecall, transcripts, untool
+from .. import trace
+from . import denylist, hosts, sidecall, toolcheck
from .context import LiveContext
PROMPT = ("Run this repository's test suite and report how many tests pass. Do not install "
@@ -136,14 +136,14 @@ def inspect_session(sid):
hosts.Copilot().settle(log)
injected = False
cmds = [(args or {}).get("command") or ""
- for (name, args, _, _) in [c for t in transcripts.copilot_turns(log) for c in t]
+ for (name, args, _, _) in [c for t in trace.copilot_turns(log) for c in t]
if name == "bash"]
tests, tried_pytest = test_commands(cmds)
for line in open(log, encoding="utf-8", errors="replace"):
if '"hook.end"' in line and '"sessionStart"' in line:
out = (json.loads(line).get("data") or {}).get("output") or {}
injected = injected or "fails here" in (out.get("additionalContext") or "")
- usage = transcripts.copilot_session_usage(log)
+ usage = trace.copilot_session_usage(log)
first = tests[0] if tests else None
if first:
first = re.sub(r"^cd \S+ && ", "", first)[:60]
@@ -175,7 +175,7 @@ def run(sessions=6, model=None, keep=False, cli="copilot", out=print):
raise RuntimeError(f"`{cli}` is not on PATH")
model = sidecall.copilot_model(model or "")
plugin = _plugin_root()
- base = next((f for f in (untool.copilot_trusted_folders() or [])
+ base = next((f for f in (denylist.copilot_trusted_folders() or [])
if os.path.isdir(f) and os.access(f, os.W_OK)), None)
root = tempfile.mkdtemp(prefix=".te-probe-copilot-", dir=base)
state = os.path.join(root, "state")
@@ -189,7 +189,7 @@ def run(sessions=6, model=None, keep=False, cli="copilot", out=print):
if not base:
out(" note: Copilot trusts no folder here, so the deny list cannot take effect "
"in the probe's repository (Copilot ignores an untrusted folder's settings)")
- _, tools = untool.refresh_catalog(state, host="copilot")
+ _, tools = toolcheck.refresh_catalog(state, host="copilot")
out(f" catalog: {len(tools)} tools recorded (local capture, no model call)")
ctx = LiveContext.build(hosts.Copilot(), repo, env)
results = []
@@ -206,7 +206,7 @@ def run(sessions=6, model=None, keep=False, cli="copilot", out=print):
proposal = unt.get("proposal") or []
lean = None
if proposal:
- untool.apply(repo, proposal, ctx.store, host="copilot")
+ denylist.apply(repo, proposal, ctx.store, host="copilot")
try:
sid, answer, err = run_session(repo, env, plugin, model, cli=cli)
if sid:
@@ -214,7 +214,7 @@ def run(sessions=6, model=None, keep=False, cli="copilot", out=print):
lean = dict(inspect_session(sid), label="deny list", answer=answer)
out(_line(lean) + f" answer: {answer[:40]}")
finally:
- untool.restore(repo, ctx.store, host="copilot")
+ denylist.restore(repo, ctx.store, host="copilot")
# the verdict
everything = results + ([lean] if lean else [])
without = [r for r in everything if not r["injected"] and r["tests"]]
@@ -231,7 +231,7 @@ def run(sessions=6, model=None, keep=False, cli="copilot", out=print):
f"{lean['tool_definition_tokens']} tokens per request")
elif not proposal:
out(" deny list: nothing proposed (a server is proposed once none of its tools "
- "was used in `untool_evidence` sessions)")
+ "was used in `toolprune_evidence` sessions)")
return 0
finally:
if keep:
diff --git a/tokeneconomizer/plugin/repomap.py b/tokeneconomizer/plugin/repomap.py
new file mode 100644
index 0000000..7a4ecef
--- /dev/null
+++ b/tokeneconomizer/plugin/repomap.py
@@ -0,0 +1,219 @@
+"""The repository map: aider's ranked map of a repository's key files and symbols, in context.
+
+Opt-in (`repomap=on`). A map of the files and signatures that matter most gives the agent its
+bearings up front, instead of reading files to learn where things are. It is the experiments'
+repo-map baseline, delivered through the plugin's own channel instead of a project instructions
+file, so nothing is written into the repository.
+
+ * The map is aider's (`aider.repomap.RepoMap`): tree-sitter tags ranked by PageRank,
+ trimmed to a token budget (`repomap_tokens`). aider is NOT a dependency of the plugin: it
+ runs in whichever Python has it (`repomap_python`, else the interpreter of an installed
+ `aider` command, else the plugin's own Python, else `python3`), as a separate process,
+ so its dependency tree never loads into a hook.
+ * aider caches the tags it parses. That cache lives in the plugin's state, next to the map
+ -- not in the repository, where aider would put it.
+ * A map is made for a commit and cached. At session start, a map for another commit (or
+ none) is regenerated in the background; the session uses the cached one meanwhile.
+ * `repomap=on`: on the first prompt of a session, a map ranked toward the identifiers in
+ that prompt is generated within `repomap_timeout` seconds and added to the context; if
+ that does not finish in time, the cached map goes in instead. Agents whose prompt hook
+ cannot add context (Codex) get the cached map at session start.
+ * `repomap=start`: the cached map at session start, on every agent. No per-prompt work.
+
+The map is a fixed prefix on every request of the session: a cost on sessions that already
+knew where to look, a saving on those that would have searched.
+"""
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+
+
+# The generator ships with the core; the experiments' repo-map baseline runs the same one.
+GEN = os.path.join(os.path.dirname(os.path.abspath(__file__)), "repomap_gen.py")
+
+HEADER = ("# Repository map\n"
+ "Ranked key files and symbols (signatures only) of this repository. Consult it to "
+ "find where things are before searching.\n\n")
+PROBE = "import aider.repomap"
+REFRESH_TIMEOUT_S = 900
+
+
+def _repo_dir(ctx):
+ """Per repository, shared by every agent: a map does not depend on which one reads it."""
+ return os.path.dirname(ctx.store.base)
+
+
+def _state_path(ctx):
+ return os.path.join(_repo_dir(ctx), "repomap.json")
+
+
+def _cache_dir(ctx):
+ return os.path.join(_repo_dir(ctx), "repomap-tags")
+
+
+def read_state(ctx):
+ try:
+ with open(_state_path(ctx), encoding="utf-8") as fh:
+ d = json.load(fh)
+ return d if isinstance(d, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def _write_state(ctx, d):
+ path = _state_path(ctx)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(d, fh, indent=2)
+ os.replace(tmp, path)
+
+
+def head_commit(root):
+ try:
+ out = subprocess.run(["git", "rev-parse", "HEAD"], cwd=root, capture_output=True,
+ text=True, timeout=10)
+ return out.stdout.strip() if out.returncode == 0 else ""
+ except (OSError, subprocess.SubprocessError):
+ return ""
+
+
+def _has_aider(python, env):
+ try:
+ return subprocess.run([python, "-c", PROBE], capture_output=True, timeout=60,
+ env=env).returncode == 0
+ except (OSError, subprocess.SubprocessError):
+ return False
+
+
+def _aider_command_python():
+ """The interpreter behind an installed `aider` command (pipx and uv tool installs give it a
+ venv of its own), read off the script's shebang."""
+ exe = shutil.which("aider")
+ if not exe:
+ return None
+ try:
+ with open(exe, "rb") as fh:
+ first = fh.readline().decode("utf-8", "replace").strip()
+ except OSError:
+ return None
+ if first.startswith("#!"):
+ parts = first[2:].split()
+ if parts and os.path.basename(parts[0]) != "env" and os.path.exists(parts[0]):
+ return parts[0]
+ return None
+
+
+def find_python(ctx):
+ """A Python that can import aider, or None. The answer is remembered in the map's state.
+
+ A Python the person named (`repomap_python`) is the only one tried: quietly using another
+ would hide that the one they chose cannot make the map."""
+ env = _gen_env(ctx)
+ if ctx.config.repomap_python:
+ return ctx.config.repomap_python if _has_aider(ctx.config.repomap_python, env) else None
+ cands = [read_state(ctx).get("python"), _aider_command_python(), sys.executable,
+ shutil.which("python3")]
+ seen = set()
+ for c in cands:
+ if not c or c in seen:
+ continue
+ seen.add(c)
+ if _has_aider(c, env):
+ return c
+ return None
+
+
+def _gen_env(ctx):
+ env = dict(ctx.env)
+ env.pop("PYTHONPATH", None)
+ env["TE_SIDECALL"] = "1"
+ return env
+
+
+def generate(ctx, python, idents=(), timeout=REFRESH_TIMEOUT_S):
+ """(map text, error) for the repository as it is now."""
+ cmd = [python, GEN, ctx.repo.root, str(ctx.config.repomap_tokens), ",".join(idents),
+ "--git", "--cache", _cache_dir(ctx)]
+ try:
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
+ env=_gen_env(ctx), cwd=ctx.repo.root)
+ except subprocess.TimeoutExpired:
+ return "", f"timed out after {timeout}s"
+ except OSError as e:
+ return "", str(e)
+ if out.returncode != 0:
+ return "", (out.stderr or "").strip()[-300:] or f"exit {out.returncode}"
+ return out.stdout, ""
+
+
+def refresh(ctx):
+ """Make the cached map for the current commit. Returns the new state."""
+ t0 = time.time()
+ commit = head_commit(ctx.repo.root)
+ python = find_python(ctx)
+ if not python:
+ named = ctx.config.repomap_python
+ state = dict(read_state(ctx), commit=commit, updated=time.time(), error=(
+ f"repomap_python {named} cannot import aider" if named else
+ "no Python with aider found (install aider-chat, or set repomap_python)"))
+ _write_state(ctx, state)
+ return state
+ text, err = generate(ctx, python)
+ state = {"commit": commit, "python": python, "map": text, "chars": len(text),
+ "tokens_budget": ctx.config.repomap_tokens, "secs": round(time.time() - t0, 1),
+ "error": err or None, "updated": time.time()}
+ if not text and read_state(ctx).get("map"):
+ prior = read_state(ctx)
+ state.update(map=prior["map"], chars=len(prior["map"]), commit=prior.get("commit"))
+ _write_state(ctx, state)
+ return state
+
+
+def stale(ctx):
+ s = read_state(ctx)
+ return (not s.get("map") or s.get("commit") != head_commit(ctx.repo.root)
+ or s.get("tokens_budget") != ctx.config.repomap_tokens)
+
+
+def spawn_refresh(ctx):
+ """Refresh in a detached process (inline when TE_FOLD_SYNC=1, for tests)."""
+ if ctx.env.get("TE_FOLD_SYNC") == "1":
+ return refresh(ctx)
+ return ctx.spawn(["repomap", "refresh"], "repomap.log")
+
+
+def cached_block(ctx):
+ m = read_state(ctx).get("map") or ""
+ return HEADER + m if m.strip() else ""
+
+
+_IDENT_RES = (re.compile(r"`([A-Za-z_][A-Za-z0-9_.]*)`"),
+ re.compile(r"\b([a-z_][a-z0-9_]*_[a-z0-9_]+)\b"),
+ re.compile(r"\b([A-Z][a-zA-Z0-9]+[A-Z][a-zA-Z0-9]*)\b"))
+
+
+def prompt_idents(text):
+ """Identifiers a prompt names (backticked names, snake_case, CamelCase): the map is ranked
+ toward them, as the experiments ranked it toward the issue's."""
+ ids = set()
+ for rx in _IDENT_RES:
+ ids |= set(rx.findall(text or ""))
+ return sorted({i.split(".")[-1] for i in ids if len(i) > 2})[:60]
+
+
+def for_prompt(ctx, prompt):
+ """(block, how) for the first prompt of a session: a map ranked toward the prompt if it can
+ be made in time, else the cached one."""
+ idents = prompt_idents(prompt)
+ python = read_state(ctx).get("python")
+ if idents and python:
+ text, err = generate(ctx, python, idents, timeout=ctx.config.repomap_timeout)
+ if text.strip():
+ return HEADER + text, "prompt"
+ block = cached_block(ctx)
+ return block, ("cached" if block else "none")
diff --git a/tokeneconomizer/plugin/repomap_gen.py b/tokeneconomizer/plugin/repomap_gen.py
new file mode 100644
index 0000000..8b8a5e7
--- /dev/null
+++ b/tokeneconomizer/plugin/repomap_gen.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+"""Host-side aider repo-map generator. Prints the map to stdout.
+
+A separate process, not an import, for two reasons: aider pulls a large dependency tree that
+must never enter a hook's (or a harness's) own process, and a generator that crashes or hangs
+on a pathological repository then costs one non-zero exit instead of the session.
+
+Usage: repomap_gen.py <src_dir> <map_tokens> [mentioned_idents_csv] [--git] [--cache DIR]
+
+ --git map the files `git ls-files` lists, in every language aider reads (the plugin's
+ live repository), instead of walking the `.py` files of an extracted tree
+ --cache DIR keep aider's tags cache in DIR instead of inside the repository
+"""
+import os
+import sys
+
+from aider.io import InputOutput
+from aider.models import Model
+from aider.repomap import RepoMap
+
+# Directories that are not the library under test. Their contents rank well (many files,
+# many symbols) while never containing the fix, so leaving them in spends the token budget
+# on documentation and benchmarks instead of on the code the agent has to change.
+SKIP = ("/.git", "/__pycache__", "/.tox", "/build", "/dist", "/.eggs", ".egg-info",
+ "/doc/", "/docs/", "/examples/", "/benchmarks/", "/tutorial/", "/asv_benchmarks/")
+
+
+# Across every language a repository also carries code it did not write: vendored libraries
+# and minified assets rank high (big, symbol-dense) and are never what a session works on.
+VENDORED = ("/vendor/", "/vendors/", "/third_party/", "/third-party/", "/node_modules/",
+ "/bower_components/", "/static/", "/assets/")
+MINIFIED = (".min.js", ".min.css", ".bundle.js", "-min.js")
+MAX_BYTES = 256 * 1024
+
+
+def _git_files(repo):
+ import subprocess
+ out = subprocess.run(["git", "ls-files", "-z"], cwd=repo, capture_output=True, text=True)
+ files = []
+ for f in out.stdout.split("\0"):
+ path = "/" + f
+ if (not f or any(s in path for s in SKIP + VENDORED) or f.endswith(MINIFIED)):
+ continue
+ full = os.path.join(repo, f)
+ try:
+ if os.path.getsize(full) > MAX_BYTES:
+ continue
+ except OSError:
+ continue
+ files.append(full)
+ return files
+
+
+def main():
+ args = sys.argv[1:]
+ use_git = "--git" in args
+ cache = args[args.index("--cache") + 1] if "--cache" in args else None
+ pos = [a for i, a in enumerate(args)
+ if not a.startswith("--") and (i == 0 or args[i - 1] != "--cache")]
+ repo = os.path.abspath(pos[0])
+ budget = int(pos[1]) if len(pos) > 1 else 2048
+ mentioned = set(pos[2].split(",")) if len(pos) > 2 and pos[2] else set()
+
+ if use_git:
+ files = _git_files(repo)
+ else:
+ files = []
+ for dirpath, _dirnames, filenames in os.walk(repo):
+ if any(s in dirpath for s in SKIP):
+ continue
+ files.extend(os.path.join(dirpath, f) for f in filenames if f.endswith(".py"))
+ if cache:
+ # An absolute path: aider joins it onto the repository root, which leaves it as is.
+ RepoMap.TAGS_CACHE_DIR = os.path.abspath(cache)
+
+ # stdout is the MAP and nothing else. aider's console writes its progress and warnings
+ # to stdout ("Initial repo scan can be slow in larger repos, but only happens once.",
+ # model-metadata warnings), and the scaffold takes this process's stdout verbatim as the
+ # map body -- so every line aider prints would land in the agent's instructions. Point
+ # sys.stdout at stderr while aider is constructed and runs, and write the map afterwards.
+ real_stdout, sys.stdout = sys.stdout, sys.stderr
+ try:
+ io = InputOutput()
+ # Used ONLY for its token counter -- no model is called and no key is needed. The
+ # map is produced by static analysis; the counter just enforces the budget.
+ model = Model("gpt-4o")
+ rm = RepoMap(map_tokens=budget, root=repo, main_model=model, io=io, verbose=False)
+ text = rm.get_repo_map([], files, mentioned_idents=mentioned) or ""
+ finally:
+ sys.stdout = real_stdout
+ sys.stdout.write(text)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/te_live/sidecall.py b/tokeneconomizer/plugin/sidecall.py
similarity index 63%
rename from te_live/sidecall.py
rename to tokeneconomizer/plugin/sidecall.py
index d837ff0..a38efb2 100644
--- a/te_live/sidecall.py
+++ b/tokeneconomizer/plugin/sidecall.py
@@ -20,16 +20,22 @@ so no extra API key is needed and the call is billed where the session is:
from. The model is `copilot_model`'s choice: under BYOK, Copilot has no router to fall back
on, and `COPILOT_MODEL=auto` -- a common setting, the subscription's router -- made the call
answer nothing (1.0.83, an Anthropic provider).
+ * Pi: `pi --print --mode json` with nothing loaded but the model -- no tools, extensions,
+ skills, prompt templates, context files, MCP servers or saved session. With no `paid_model`
+ it runs on the person's own default provider and model, under whatever login Pi holds for
+ it (a subscription signed in with `/login`, or an API key).
Every side call runs with `TE_SIDECALL=1`, which the plugin's hook entry point treats as "do
-nothing": without it the nested agent would run this plugin's hooks and recurse. Nothing here runs
-unless `paid` is enabled.
+nothing": without it the nested agent would run this plugin's hooks and recurse. A call that
+returns no reply -- a CLI that is not signed in, say -- leaves one line in the plugin's
+errors.log, which `te doctor` shows. Nothing here runs unless `paid` is enabled.
"""
import json
import os
import subprocess
import tempfile
+from .. import trace
from . import accounting
TIMEOUT_S = 180
@@ -39,13 +45,50 @@ def _env():
return dict(os.environ, TE_SIDECALL="1")
+def _no_reply(host, out):
+ """Note a side call that came back empty: the paid helpers otherwise fail silently -- seen
+ with Copilot, which does not pass a BYOK provider's variables to the hooks that start it."""
+ import time
+ from .paths import state_root
+ tail = " ".join((getattr(out, "stderr", "") or "").split())[-300:]
+ try:
+ root = state_root()
+ os.makedirs(root, exist_ok=True)
+ with open(os.path.join(root, "errors.log"), "a", encoding="utf-8") as fh:
+ fh.write(f"--- {time.strftime('%Y-%m-%dT%H:%M:%S')} sidecall {host}: no reply "
+ f"(exit {getattr(out, 'returncode', '?')}) {tail}\n")
+ except OSError:
+ pass
+
+
+_FLAGS = {}
+
+
+def claude_flags(cli="claude"):
+ """`--no-session-persistence` when this Claude Code has it: a side call or a measurement is
+ not a session of the person's, and should not appear in their history (`claude --resume`)."""
+ if cli not in _FLAGS:
+ try:
+ help_text = subprocess.run([cli, "--help"], capture_output=True, text=True,
+ timeout=30, stdin=subprocess.DEVNULL).stdout
+ except (OSError, subprocess.SubprocessError):
+ help_text = ""
+ _FLAGS[cli] = ["--no-session-persistence"] if "--no-session-persistence" in help_text else []
+ return list(_FLAGS[cli])
+
+
def claude_call(prompt, model="haiku", cli="claude", timeout=TIMEOUT_S):
cmd = [cli, "-p", "--output-format", "json", "--max-turns", "1", "--tools", "",
- "--model", model or "haiku"]
+ "--model", model or "haiku"] + claude_flags(cli)
with tempfile.TemporaryDirectory(prefix="te-side-") as cwd:
out = subprocess.run(cmd, input=prompt, capture_output=True, text=True,
timeout=timeout, env=_env(), cwd=cwd)
- data = json.loads(out.stdout or "{}")
+ try:
+ data = json.loads(out.stdout or "{}")
+ except ValueError:
+ data = {}
+ if not data.get("result"):
+ _no_reply("claude", out)
usage = dict(data.get("usage") or {})
usage["model"] = next(iter(data.get("modelUsage") or {}), None) or (model or "claude")
eff, _ = accounting.effective(usage)
@@ -67,13 +110,17 @@ def codex_call(prompt, model="", cli="codex", timeout=TIMEOUT_S):
ev = json.loads(line)
except ValueError:
continue
- if ev.get("type") == "item.completed" and (ev.get("item") or {}).get("type") == "agent_message":
+ item = ev.get("item") or {}
+ if ev.get("type") == "item.completed" and item.get("type") == "agent_message":
text = ev["item"].get("text") or text
elif ev.get("type") == "turn.completed":
usage = ev.get("usage") or usage
+ if not text:
+ _no_reply("codex", out)
eff = None
if usage:
- inp, cached = int(usage.get("input_tokens") or 0), int(usage.get("cached_input_tokens") or 0)
+ inp = int(usage.get("input_tokens") or 0)
+ cached = int(usage.get("cached_input_tokens") or 0)
cw = int(usage.get("cache_write_input_tokens") or 0)
eff, _ = accounting.effective({
"input_tokens": max(0, inp - cached - cw), "cache_read_input_tokens": cached,
@@ -84,6 +131,31 @@ def codex_call(prompt, model="", cli="codex", timeout=TIMEOUT_S):
return text, eff
+# Pi before 1.0 has no `--no-mcp` (and no built-in MCP to switch off); it rejects the flag.
+PI_FLAGS = ("--print", "--mode", "json", "--no-session", "--no-tools", "--no-extensions",
+ "--no-skills", "--no-prompt-templates", "--no-context-files", "--offline")
+
+
+def pi_call(prompt, model="", cli="pi", timeout=TIMEOUT_S):
+ model_args = ["--model", model] if model else []
+ with tempfile.TemporaryDirectory(prefix="te-side-") as cwd:
+ for extra in (["--no-mcp"], []):
+ cmd = [cli, *PI_FLAGS, *extra, *model_args, "--", prompt]
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
+ env=_env(), cwd=cwd, stdin=subprocess.DEVNULL)
+ if "Unknown option: --no-mcp" not in (out.stderr or ""):
+ break
+ text, usage = trace.pi_json_reply(out.stdout)
+ if not text:
+ _no_reply("pi", out)
+ eff = None
+ if usage:
+ usage.pop("cost_usd", None)
+ usage["model"] = usage.get("model") or model or "pi"
+ eff, _ = accounting.effective(usage)
+ return text, eff
+
+
# Everything the Copilot CLI offers (1.0.83 names), so the completion is offered nothing; a name
# the installed CLI does not know is ignored.
COPILOT_TOOLS = ("bash", "read_bash", "write_bash", "stop_bash", "list_bash", "view", "grep",
@@ -116,10 +188,14 @@ def copilot_model(paid_model="", env=None):
def copilot_call(prompt, model="", cli="copilot", timeout=TIMEOUT_S):
- from . import hosts, transcripts
+ from .. import trace
+ from . import hosts
model = copilot_model(model)
cmd = [cli, "-p", prompt, "--output-format", "json", "--no-color", "--no-auto-update",
"--no-custom-instructions", "--disable-builtin-mcps"]
+ # The person's own MCP servers too: a completion needs none of them to connect.
+ for server in sorted(trace.copilot_mcp_servers() - {"github-mcp-server"}):
+ cmd += ["--disable-mcp-server", server]
for t in COPILOT_TOOLS:
cmd += ["--deny-tool", t, "--excluded-tools", t]
if model:
@@ -137,21 +213,26 @@ def copilot_call(prompt, model="", cli="copilot", timeout=TIMEOUT_S):
text = (ev.get("data") or {}).get("content") or text
elif ev.get("type") == "result":
sid = ev.get("sessionId") or sid
+ if not text:
+ _no_reply("copilot", out)
eff = None
if sid:
log = os.path.join(hosts.copilot_home(), "session-state", sid, "events.jsonl")
hosts.Copilot().settle(log, wait_s=5.0)
- usage = transcripts.copilot_session_usage(log)
+ usage = trace.copilot_session_usage(log)
usage["model"] = usage.get("model") or model or "copilot"
eff, _ = accounting.effective(usage)
return text, eff
def runner_for(host_name, config):
- """The optimizer callable for this host, or None when paid calls are not allowed."""
+ """The optimizer callable for this host, or None when paid calls are not allowed. Each host's
+ calls go through that host's own CLI, never another agent's."""
if not config.paid:
return None
model = config.paid_model
+ if host_name == "pi":
+ return lambda prompt, _m="agent": pi_call(prompt, model=model)
if host_name == "codex":
return lambda prompt, _m="agent": codex_call(prompt, model=model)
if host_name == "copilot":
diff --git a/te_live/store.py b/tokeneconomizer/plugin/store.py
similarity index 100%
rename from te_live/store.py
rename to tokeneconomizer/plugin/store.py
diff --git a/tokeneconomizer/plugin/toolcheck.py b/tokeneconomizer/plugin/toolcheck.py
new file mode 100644
index 0000000..319d9e3
--- /dev/null
+++ b/tokeneconomizer/plugin/toolcheck.py
@@ -0,0 +1,258 @@
+"""Asking the host CLIs what tools a session really loads.
+
+ * `refresh_catalog` -- the tool list a fresh session loads (Claude Code, Copilot), recorded so
+ pruning sees the always-loaded tools, not only the ones a session used;
+ * `verify_copilot`, `verify_codex` -- what an applied deny list actually removed;
+ * `measure` -- one request with and without a proposal. On Claude Code that is two
+ small `claude -p` requests on the cheapest model; Codex renders its
+ prompt input locally (`codex debug prompt-input`) and Copilot's request
+ is captured by a scripted endpoint on localhost, so neither calls a model.
+"""
+import json
+import os
+import shutil
+import subprocess
+import tempfile
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+from . import adapter as live_adapter
+from .denylist import CODEX_TOGGLES, write_json as _write_json
+from .sidecall import claude_flags
+
+
+def verify_copilot(repo_root, servers, cli="copilot"):
+ """{server: tools still in the request} for a session started in `repo_root`, by the local
+ capture (no model call); None if no request could be captured."""
+ body = copilot_capture(cwd=repo_root, cli=cli)
+ if not body:
+ return None
+ names = _request_tools(body)
+ return {s: sum(1 for n in names if n and n.startswith(s + "-")) for s in servers}
+
+
+def verify_codex(repo_root, capabilities, cli="codex", timeout=30):
+ """What `codex features list`, run in the repository, says about the applied toggles:
+ {feature: enabled} for the features those capabilities switch off, or None when the CLI
+ is unavailable. Free: it reads configuration and calls no model."""
+ feats = [k for c in capabilities for t, k, v in CODEX_TOGGLES.get(c, ())
+ if t == "features"]
+ if not feats or not shutil.which(cli):
+ return None
+ try:
+ out = subprocess.run([cli, "features", "list"], capture_output=True, text=True,
+ cwd=repo_root, timeout=timeout,
+ env=dict(os.environ, TE_SIDECALL="1"))
+ except (OSError, subprocess.SubprocessError):
+ return None
+ state = {}
+ for line in (out.stdout or "").splitlines():
+ parts = line.split()
+ if len(parts) >= 2 and parts[0] in feats:
+ state[parts[0]] = parts[-1] == "true"
+ return state or None
+
+
+def _init_tools(extra_args, cli="claude", timeout=60):
+ """Tool list from a `claude -p` session's init event; the process is killed right after it,
+ before the model is asked anything."""
+ env = dict(os.environ, TE_SIDECALL="1")
+ cmd = [cli, "-p", "Reply with OK", "--output-format", "stream-json", "--verbose",
+ "--model", "haiku", "--max-turns", "1"] + claude_flags(cli) + list(extra_args)
+ with tempfile.TemporaryDirectory(prefix="te-probe-") as cwd:
+ p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, text=True, env=env, cwd=cwd)
+ tools, version = None, None
+ deadline = time.time() + timeout
+ try:
+ for line in p.stdout:
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ if ev.get("type") == "system" and ev.get("subtype") == "init":
+ tools, version = ev.get("tools"), ev.get("claude_code_version")
+ break
+ if time.time() > deadline:
+ break
+ finally:
+ p.kill()
+ p.wait()
+ return tools, version
+
+
+class _Capture(BaseHTTPRequestHandler):
+ """A chat-completions endpoint that records the request and answers "OK"."""
+ def log_message(self, *a):
+ pass
+
+ def _send(self, body, ctype="application/json"):
+ data = body.encode() if isinstance(body, str) else body
+ self.send_response(200)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def do_GET(self):
+ self._send(json.dumps({"object": "list", "data": [{"id": "gpt-5.4", "object": "model"}]}))
+
+ def do_POST(self):
+ n = int(self.headers.get("Content-Length") or 0)
+ try:
+ body = json.loads(self.rfile.read(n) or b"{}")
+ except ValueError:
+ body = {}
+ self.server.captured.append(body)
+ msg = {"role": "assistant", "content": "OK"}
+ usage = {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
+ if body.get("stream"):
+ chunks = [{"choices": [{"index": 0, "delta": msg, "finish_reason": None}]},
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ {"choices": [], "usage": usage}]
+ self._send("".join(f"data: {json.dumps(dict(c, object='chat.completion.chunk'))}"
+ "\n\n" for c in chunks) + "data: [DONE]\n\n",
+ "text/event-stream")
+ else:
+ self._send(json.dumps({"object": "chat.completion", "usage": usage, "choices": [
+ {"index": 0, "message": msg, "finish_reason": "stop"}]}))
+
+
+def copilot_capture(extra_args=(), cwd=None, cli="copilot", timeout=90):
+ """The first request a fresh `copilot -p` session sends, captured on localhost.
+
+ Copilot's BYOK mode is pointed at a scripted endpoint in this process, so the request --
+ system prompt, tool schemas -- is recorded exactly as Copilot builds it, and no model,
+ credential or quota is touched. Returns the request body, or None."""
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), _Capture)
+ srv.captured = []
+ th = threading.Thread(target=srv.serve_forever, daemon=True)
+ th.start()
+ # The person's own model, when the environment names one: Copilot shapes its built-in tools
+ # by model family (`edit`/`create` for Claude models, `apply_patch` for GPT ones).
+ from .sidecall import copilot_model
+ # A router's `provider/` prefix (OpenRouter: `anthropic/claude-haiku-4.5`) is not part of
+ # the id Copilot recognises.
+ model = (copilot_model() or "gpt-5.4").split("/", 1)[-1]
+ env = {k: v for k, v in os.environ.items()
+ if not k.startswith("COPILOT_PROVIDER_") and k != "COPILOT_MODEL"}
+ env.update(TE_SIDECALL="1", COPILOT_PROVIDER_TYPE="openai",
+ COPILOT_PROVIDER_BASE_URL=f"http://127.0.0.1:{srv.server_address[1]}/v1",
+ COPILOT_PROVIDER_API_KEY="te-local-probe", COPILOT_MODEL=model,
+ COPILOT_PROVIDER_WIRE_API="completions", NO_PROXY="127.0.0.1,localhost",
+ no_proxy="127.0.0.1,localhost")
+ tmp = None
+ if cwd is None:
+ tmp = tempfile.mkdtemp(prefix="te-probe-")
+ cwd = tmp
+ try:
+ subprocess.run([cli, "-p", "Reply with OK", "--no-auto-update", "--no-color"]
+ + list(extra_args), cwd=cwd, env=env, capture_output=True, text=True,
+ timeout=timeout, stdin=subprocess.DEVNULL)
+ except (OSError, subprocess.SubprocessError):
+ pass
+ finally:
+ srv.shutdown()
+ srv.server_close()
+ if tmp:
+ shutil.rmtree(tmp, ignore_errors=True)
+ return srv.captured[0] if srv.captured else None
+
+
+def _request_tools(body):
+ return [(t.get("function") or {}).get("name") or t.get("name") or t.get("type")
+ for t in (body or {}).get("tools") or []]
+
+
+def _copilot_version(cli="copilot"):
+ try:
+ out = subprocess.run([cli, "--version"], capture_output=True, text=True, timeout=30)
+ return (out.stdout or "").strip().splitlines()[0]
+ except (OSError, subprocess.SubprocessError, IndexError):
+ return None
+
+
+def refresh_catalog(state_root, cli=None, host="claude"):
+ """Record the tool list a fresh session loads on this machine."""
+ if host == "copilot":
+ body = copilot_capture(cli=cli or "copilot")
+ tools = [t for t in _request_tools(body) if t]
+ if not tools:
+ raise RuntimeError("could not capture the tool list of a `copilot -p` request")
+ path = live_adapter.catalog_path(state_root, "copilot")
+ _write_json(path, {"tools": sorted(tools), "copilot_version": _copilot_version(),
+ "probed_at": time.time()})
+ return path, sorted(tools)
+ if host != "claude":
+ raise RuntimeError(f"no catalog probe for {host}")
+ tools, version = _init_tools([], cli=cli or "claude")
+ if not tools:
+ raise RuntimeError("could not read the tool list from a `claude -p` init event")
+ path = live_adapter.catalog_path(state_root, "claude")
+ _write_json(path, {"tools": sorted(tools), "claude_code_version": version,
+ "probed_at": time.time()})
+ return path, sorted(tools)
+
+
+def _prompt_tokens(extra_args, cli="claude", timeout=180):
+ env = dict(os.environ, TE_SIDECALL="1")
+ cmd = [cli, "-p", "Reply with exactly: OK", "--output-format", "json", "--model", "haiku",
+ "--max-turns", "1"] + claude_flags(cli) + list(extra_args)
+ with tempfile.TemporaryDirectory(prefix="te-measure-") as cwd:
+ out = subprocess.run(cmd, capture_output=True, text=True, env=env, cwd=cwd,
+ timeout=timeout)
+ data = json.loads(out.stdout or "{}")
+ u = data.get("usage") or {}
+ return (sum(int(u.get(k) or 0) for k in ("input_tokens", "cache_read_input_tokens",
+ "cache_creation_input_tokens")),
+ data.get("total_cost_usd"))
+
+
+def _codex_prompt_chars(overrides, cli="codex", timeout=60):
+ cmd = [cli, "debug", "prompt-input"]
+ for table, key, value in overrides:
+ cmd += ["-c", f"{table}.{key}={value}" if table else f"{key}={value}"]
+ with tempfile.TemporaryDirectory(prefix="te-measure-") as cwd:
+ out = subprocess.run(cmd + ["OK"], capture_output=True, text=True, cwd=cwd,
+ timeout=timeout, env=dict(os.environ, TE_SIDECALL="1"))
+ return len(out.stdout or "") if out.returncode == 0 else None
+
+
+def measure(tools, cli=None, host="claude"):
+ """Request size with and without `tools` removed.
+
+ Claude Code: prompt tokens of two small requests. Codex and Copilot: characters of the
+ rendered request, and a ~4-characters-per-token estimate, at no cost."""
+ if not tools:
+ return None
+ if host == "codex":
+ toggles = [t for c in tools for t in CODEX_TOGGLES.get(c, ())]
+ full = _codex_prompt_chars([], cli=cli or "codex")
+ lean = _codex_prompt_chars(toggles, cli=cli or "codex")
+ if full is None or lean is None:
+ raise RuntimeError("`codex debug prompt-input` failed")
+ return {"capabilities": list(tools), "prompt_input_chars_full": full,
+ "prompt_input_chars_lean": lean, "saved_chars_per_request": full - lean,
+ "saved_tokens_per_request_est": (full - lean) // 4,
+ "note": "prompt input only (developer/user items); tool schemas not included",
+ "probe_cost_usd": 0.0}
+ if host == "copilot":
+ args = [a for s in tools for a in ("--disable-mcp-server", s)]
+ full = copilot_capture(cli=cli or "copilot")
+ lean = copilot_capture(args, cli=cli or "copilot")
+ if not full or not lean:
+ raise RuntimeError("could not capture a `copilot -p` request")
+ size = lambda b: len(json.dumps(b.get("tools"))) + len(json.dumps(b.get("messages")))
+ return {"mcp_servers": list(tools),
+ "tools_full": len(_request_tools(full)), "tools_lean": len(_request_tools(lean)),
+ "request_chars_full": size(full), "request_chars_lean": size(lean),
+ "saved_chars_per_request": size(full) - size(lean),
+ "saved_tokens_per_request_est": (size(full) - size(lean)) // 4,
+ "probe_cost_usd": 0.0}
+ cli = cli or "claude"
+ full, c1 = _prompt_tokens([], cli=cli)
+ lean, c2 = _prompt_tokens(["--disallowed-tools", ",".join(tools)], cli=cli)
+ return {"tools": list(tools), "prompt_tokens_full": full, "prompt_tokens_lean": lean,
+ "saved_per_request": full - lean,
+ "probe_cost_usd": round((c1 or 0) + (c2 or 0), 4)}
diff --git a/tokeneconomizer/vendor/pricing.py b/tokeneconomizer/pricing.py
similarity index 94%
rename from tokeneconomizer/vendor/pricing.py
rename to tokeneconomizer/pricing.py
index 4a5ebf9..5bb7f73 100644
--- a/tokeneconomizer/vendor/pricing.py
+++ b/tokeneconomizer/pricing.py
@@ -186,10 +186,20 @@ def effective_tokens(rec, weights=None):
return tt if isinstance(tt, (int, float)) else 0
-def cache_read_fraction(rec):
- """Share of tokens_total that is cached re-read (diagnostic; None if unknown)."""
- if not has_breakdown(rec):
- return None
- tt = rec.get("tokens_total") or 0
- cr = rec.get("cache_read_input_tokens") or 0
- return (cr / tt) if tt else None
+def approx_tokens(text):
+ """A character-count estimate of a text's tokens (~4 characters each)."""
+ return max(1, len(text) // 4)
+
+
+def runner_effective_or_approx(runner, prompt, raw, real):
+ """The effective tokens of one side call: the usage its runner recovered, else the runner's
+ own model-priced estimate, else an uncached estimate (prompt at x1, reply at x5)."""
+ if real is not None:
+ return real
+ estimator = getattr(runner, "estimate_effective", None)
+ if callable(estimator):
+ try:
+ return estimator(prompt, raw)
+ except Exception:
+ pass
+ return approx_tokens(prompt) + 5 * approx_tokens(raw)
diff --git a/tokeneconomizer/stage.py b/tokeneconomizer/stage.py
new file mode 100644
index 0000000..1b0e80a
--- /dev/null
+++ b/tokeneconomizer/stage.py
@@ -0,0 +1,29 @@
+"""`Stage`: the lifecycle hooks a mechanism offers around one task (a session, in the plugin).
+
+Each mechanism implements only the hooks it needs; the rest keep the no-op default. A caller
+-- the plugin's `fold`, or a benchmark harness -- runs them in this order:
+
+ before_task(task, injected) -> str # before: may extend the injected prefix
+ build_tools(task) -> list|None # at launch: the tools to exclude
+ run_kwargs(task) -> dict # at launch: settings for the agent runner
+ after_task(task, row, run_dir_path, srow) # after: update state, record telemetry
+ -> opt_tokens (LLM overhead; 0 for a free mechanism)
+
+`srow` is the caller's record of the task, where a mechanism may attach its own telemetry.
+"""
+
+
+class Stage:
+ name = "base"
+
+ def before_task(self, task, injected):
+ return injected
+
+ def build_tools(self, task):
+ return None
+
+ def run_kwargs(self, task):
+ return {}
+
+ def after_task(self, task, row, run_dir_path, srow):
+ return 0
diff --git a/tokeneconomizer/toolprune/README.md b/tokeneconomizer/toolprune/README.md
new file mode 100644
index 0000000..bce9f86
--- /dev/null
+++ b/tokeneconomizer/toolprune/README.md
@@ -0,0 +1,25 @@
+# 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.
+
+- **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
+ `evidence` sessions; a protected work-surface tool (`tools.PROTECTED_TOOLS`) or one ever seen
+ in use is never proposed. An optional per-task judge (`tools.judge_tools_for_task`) can also
+ drop tools the task text makes irrelevant, its cost charged to the ledger.
+- **Capability pruning** (Codex; `codex.CodexUntoolProfile`). Codex's unit is a capability
+ package (collaboration, goals, image/media, ...) switched off in its config. A package is
+ demoted only after enough loaded-but-unused sessions, at most two per session, and a single
+ use protects it for good.
+
+This package decides *what* to drop. Writing the decision into an agent's own settings file, only
+after the person approves it and only from the next session, is the plugin's job
+(`tokeneconomizer/plugin/denylist.py`).
+
+| Module | |
+|---|---|
+| `stage.py` | `ToolingStage`: evidence across sessions, the proposal, the Codex mask |
+| `codex.py` | `CodexUntoolProfile`: Codex's evidence-gated capability controller |
+| `tools.py` | the protected and inapplicable tool sets; the optional per-task tool judge |
diff --git a/tokeneconomizer/toolprune/__init__.py b/tokeneconomizer/toolprune/__init__.py
new file mode 100644
index 0000000..99803b7
--- /dev/null
+++ b/tokeneconomizer/toolprune/__init__.py
@@ -0,0 +1,18 @@
+"""Tool pruning: stop paying, on every request, for tool definitions a repository never uses.
+
+ * `stage` -- `ToolingStage`: tracks which loaded tools go unused, session after session, and
+ proposes dropping a tool once it has gone unused for `evidence` sessions (never a
+ protected tool, never one ever used);
+ * `codex` -- `CodexUntoolProfile`: the same idea for Codex, whose unit is a capability
+ package switched off in its config rather than a single tool;
+ * `tools` -- the protected work surface, the inapplicable-by-construction set, and the
+ optional per-task tool judge.
+
+Stdlib only; never imports the plugin runtime.
+"""
+from .codex import CodexUntoolProfile
+from .stage import ToolingStage
+from .tools import INAPPLICABLE_TOOLS, PROTECTED_TOOLS, judge_tools_for_task
+
+__all__ = ["CodexUntoolProfile", "ToolingStage", "INAPPLICABLE_TOOLS", "PROTECTED_TOOLS",
+ "judge_tools_for_task"]
diff --git a/tokeneconomizer/mechanisms/codex_untool.py b/tokeneconomizer/toolprune/codex.py
similarity index 89%
rename from tokeneconomizer/mechanisms/codex_untool.py
rename to tokeneconomizer/toolprune/codex.py
index 6ad45d8..55b32dd 100644
--- a/tokeneconomizer/mechanisms/codex_untool.py
+++ b/tokeneconomizer/toolprune/codex.py
@@ -1,42 +1,27 @@
-"""Codex-native capability untooling.
-
-Codex ships a broad default tool/instruction surface (collaboration sub-agents, web,
-skills, image/media, request-user-input, deferred wait, planning, ...). On a sealed,
-detached, network-isolated, single-agent SWE-bench task most of that surface is
-inapplicable, yet its schemas + guidance are re-sent on every model turn and billed each
-time. This controller removes the inapplicable packages from the request contract.
-
-DESIGN (causal, evidence-gated, resolve-safe):
-
- * A fresh repository stream starts on the COMPLETE contract (task 1 observes everything).
- * After each completed task, at most two independently-observed packages are demoted,
- using ONLY prior completed-task evidence (never the current task, never the grade at
- selection time). A single completed use PERMANENTLY protects a package.
- * Higher-risk packages (image/media, skills) require more loaded-but-unused exposures
- before demotion than collaboration/web.
- * Narrow issue-text hints and sparse single-package probes restore one package before a
- task without restoring the rest of the contract (fail-open recovery).
- * Deferred `wait` is treated as CORE, not demotable: live traces established its
- indirect utility (pruning it triggered dozens of shell-polling commands), so recent
- experience keeps it loaded -- the key correction the shipped controller makes over its
- predecessor. The mask is frozen within a task; grades/classifiers/reasoning-effort/
- prefix-injection/output-compaction/spiral do not participate.
-
-This is the single, un-versioned successor to
-the codex-untool line (v1 classifier -> ... -> v5 sealed atomic packages -> v6
-recent-experience gradual -> v7 indirect-use core).
-
-WHAT THE MASK CAN REACH ON THE CURRENT HARNESS (te_harness, codex-cli 0.153.1, config
-toggles only -- no relay; recorded from the CLI's own request against a local endpoint). The
-packages a supported toggle removes are `collaboration` (the agent tools plus two
-collaboration messages), `goals` (inside the code-mode `exec` description), `image_media`
-and `skills` (the bundled system skills' listing, removed by disabling each bundled skill in
-config). `web` is already blocked on every arm; `request_user_input` has no toggle in
-0.153.1 and its demotion changes nothing there; `planning` is not in this contract at all.
-
-The ToolingStage computes the logical capability MASK here; the concrete mapping from a
-capability id to Codex config/relay prune-items is the runner's job (it owns the Codex
-request contract), so this module stays free of any Docker/CLI harness dependency.
+"""`CodexUntoolProfile`: tool pruning on Codex, where the unit is a capability package.
+
+Codex ships a broad default surface (collaboration sub-agents, web, skills, image/media,
+request-user-input, deferred wait, planning, ...) whose schemas and guidance are re-sent on
+every request. This controller removes the packages a repository's sessions do not use:
+
+ * A fresh repository starts on the COMPLETE contract (its first session sees everything).
+ * After each completed session, at most two independently-observed packages are demoted,
+ using ONLY earlier sessions' evidence. A single completed use PERMANENTLY protects a
+ package.
+ * Higher-risk packages (image/media, skills) need more loaded-but-unused exposures before
+ demotion than collaboration or web.
+ * Narrow task-text hints and sparse single-package probes restore one package before a
+ session without restoring the rest of the contract (fail-open recovery).
+ * Deferred `wait` is CORE, never demoted: in recorded traces, pruning it made agents poll
+ through the shell instead (dozens of polling commands). The mask is frozen within a session.
+
+What a mask can reach depends on the Codex build: on codex-cli 0.153.1, config toggles remove
+`collaboration` (the agent tools and two collaboration messages), `goals` (inside the code-mode
+`exec` description), `image_media` and `skills` (the bundled skills' listing). `web` has a
+toggle as well; `request_user_input` has none; `planning` is not in that contract at all.
+
+The controller computes the logical capability MASK; mapping a capability to Codex config or
+request rewrites is the caller's job (`plugin.denylist` writes a project's `.codex/config.toml`).
"""
import copy
import hashlib
@@ -67,8 +52,7 @@ CAPABILITY_DESCRIPTIONS = {
"Maintain a structured todo/update_plan list. This can help some long repairs but "
"is optional because the agent can reason and report progress without the tool."),
"web": (
- "Search/open the public web and query online services. The task container is "
- "network-isolated; empty or uncompleted attempts are not useful evidence."),
+ "Search/open the public web and query online services."),
"request_user_input": (
"Pause for interactive human input. Runs are detached, autonomous, and have no "
"human available inside a task."),
@@ -155,7 +139,7 @@ _SKILL_USE = re.compile(
_FAILED_STATUSES = frozenset(("failed", "error", "cancelled"))
_HINT_BASE_RELAY = (
- "deferred_wait", "image_media", "request_user_input", "skills", "sealed_web")
+ "deferred_wait", "image_media", "request_user_input", "skills", "web")
def task_hints(problem_statement):
@@ -293,7 +277,7 @@ RECENT_WINDOW = 3
# Native config carries a supported toggle for these; web/image are also relay-pruned
# because current Codex builds serialize their real declarations inside the unified exec
# package (their native toggles are harmless defense in depth).
-# `skills` (2026-09-11): the CLI bundles system skills into $CODEX_HOME at startup and lists
+# `skills`: the CLI bundles system skills into $CODEX_HOME at startup and lists
# them in a <skills_instructions> developer message (~0.64k tokens); disabling each bundled
# skill through `[[skills.config]] enabled = false` removes the whole block. Its relay id is
# kept for harnesses that prune by request rewrite.
@@ -301,7 +285,7 @@ CONFIG_CAPABILITIES = frozenset(("collaboration", "web", "goals", "skills", "ima
"interactive_guidance"))
_RELAY_CAPABILITIES = {
"collaboration": (),
- "web": ("sealed_web",),
+ "web": ("web",),
"goals": (),
"interactive_guidance": (),
"skills": ("skills",),
diff --git a/tokeneconomizer/mechanisms/tooling.py b/tokeneconomizer/toolprune/stage.py
similarity index 81%
rename from tokeneconomizer/mechanisms/tooling.py
rename to tokeneconomizer/toolprune/stage.py
index 439ee1c..3797a5b 100644
--- a/tokeneconomizer/mechanisms/tooling.py
+++ b/tokeneconomizer/toolprune/stage.py
@@ -1,29 +1,25 @@
-"""Tooling mechanism (untooling): drop inapplicable tool schemas from the per-turn prefix.
-
-A sealed agent's tool catalog is re-sent every turn and billed every turn, but on any one
-task most tools are inapplicable. Untooling removes them. Two paths, chosen by agent:
-
- * GENERIC evidence untooling (Claude / Copilot) -- `ToolingConfig.evidence`:
- A tool is dropped once it has been LOADED-BUT-UNUSED for `evidence` consecutive
- tasks (never dropping a protected work-surface tool or one ever seen in use). With
- `judge=True`, a per-task instruction-aware LLM judge additionally drops tools its
- (redacted) issue text makes irrelevant. Periodic re-audit reloads the full catalog.
- All judge/classify tokens fold into the honest ledger.
-
- * CODEX-NATIVE capability untooling (Codex) -- `ToolingConfig.codex_untool`:
- Removes whole inapplicable capability PACKAGES from Codex's request contract via the
- evidence-gated, resolve-safe controller in `codex_untool.CodexUntoolProfile`. The
- Stage computes the frozen capability mask; the runner maps it onto Codex config/relay
- prune-items (that mapping is the runner's job, keeping this module harness-free).
-
-Untool state (`used_tools`, `tool_unused_streaks`, catalog snapshot) accrues every task
-even when untooling is off, so a run that toggles the switch is never wrong.
+"""`ToolingStage`: tool pruning's lifecycle hook -- learn which loaded tools go unused, and propose
+dropping them.
+
+An agent's tool definitions are re-sent, and billed, on every request, whether or not a
+repository's work ever calls them. Two paths, chosen by agent:
+
+ * Evidence pruning (Claude Code, Copilot) -- `ToolingConfig.evidence`: a tool is proposed once
+ it has been LOADED BUT UNUSED for `evidence` consecutive sessions; a protected work-surface
+ tool, or one ever seen in use, never is. With `judge=True` a per-task LLM judge may also
+ drop tools the task text makes irrelevant, its cost charged to the ledger.
+ * Capability pruning (Codex) -- `ToolingConfig.codex_untool`: whole capability PACKAGES leave
+ Codex's request through the evidence-gated controller in `codex.CodexUntoolProfile`. The
+ stage computes the mask; mapping it onto Codex's configuration is the caller's job.
+
+The evidence (`used_tools`, `tool_unused_streaks`, the catalog) accrues every session even when
+pruning is off, so switching it on later starts from what was already seen.
"""
import os
-from .base import Stage
-from ..vendor import reflect
-from . import codex_untool as cu
+from ..stage import Stage
+from . import codex as cu
+from .tools import judge_tools_for_task
_CODEX_AGENTS = ("codex",)
@@ -40,7 +36,7 @@ class ToolingStage(Stage):
self.judge_tool_runner = judge_tool_runner
self.adapter = adapter
- # ---- shared untool state (owned here, mutated across tasks) ----
+ # ---- shared pruning state (owned here, mutated across tasks) ----
self.used_tools = set() # tools observed in use across the stream so far
self.tool_unused_streaks = {} # {tool: consecutive tasks unused while loaded}
self.catalog_tools = set() # every tool ever seen in the full catalog
@@ -52,7 +48,7 @@ class ToolingStage(Stage):
self._codex_selection = None
if cfg.codex_untool and agent in _CODEX_AGENTS:
if not repo or not results_root:
- raise ValueError("codex untooling requires repo and results_root")
+ raise ValueError("Codex capability pruning requires repo and results_root")
self.codex_profile = cu.CodexUntoolProfile(repo, results_root, fresh=fresh)
# ---- generic per-task instruction-aware judge: redacted-issue lookup ----
@@ -105,7 +101,7 @@ class ToolingStage(Stage):
if t not in protected and t not in self.used_tools
and t not in trace_excluded}
if cand:
- loadmap, self._task_judge_tokens = reflect.judge_tools_for_task(
+ loadmap, self._task_judge_tokens = judge_tools_for_task(
self.problem_by_iid[iid], cand, self.judge_tool_runner,
model=self.optimizer_model)
self._task_judge_dropped = [t for t, load in loadmap.items()
@@ -118,7 +114,7 @@ class ToolingStage(Stage):
return None
def run_kwargs(self, task):
- """Hand the runner the frozen mask's CONFIG half (generic untooling needs none).
+ """Hand the runner the frozen mask's CONFIG half (evidence pruning needs none).
The relay half already crosses the seam as `build_tools`' return value, but the two
are not interchangeable and the config half cannot be recovered from it: the
@@ -143,7 +139,7 @@ class ToolingStage(Stage):
if self.adapter else set())
self.used_tools.update(task_used)
- # ---- Codex-native capability untooling ----
+ # ---- Codex capability pruning ----
if self.codex_profile is not None:
selection = self._codex_selection or {}
usage = cu.inspect_usage(transcript)
@@ -164,7 +160,7 @@ class ToolingStage(Stage):
srow["codex_untool_adapt_tokens"] = 0
return 0
- # ---- generic evidence untooling bookkeeping ----
+ # ---- evidence pruning bookkeeping ----
if cfg.evidence:
srow["untooled_excluded"] = row.get("untooled_excluded", [])
srow["untool_evidence_excluded"] = list(self._exclude_tools or [])
@@ -172,7 +168,7 @@ class ToolingStage(Stage):
if not self._exclude_tools and self.adapter is not None:
# Source-aware where the adapter supports it: an empty catalog is
# indistinguishable from "this agent loaded no tools", and that ambiguity
- # is exactly how a Copilot CLI upgrade silently turned untooling into a
+ # is exactly how a Copilot CLI upgrade silently turned pruning into a
# no-op for a whole sweep (trace.catalog_sources). Record which source won
# so the next migration shows up in the rows, and say so out loud the first
# time nothing parses.
@@ -188,7 +184,7 @@ class ToolingStage(Stage):
elif not self.catalog_tools and not self._warned_no_catalog:
self._warned_no_catalog = True
print(f"[tooling] !! no tool catalog parsed for agent={self.agent} "
- f"from {run_dir_path} -- evidence untooling can drop NOTHING and "
+ f"from {run_dir_path} -- evidence pruning can drop NOTHING and "
f"this arm will behave as its baseline. Likely an agent-CLI "
f"upgrade that moved the catalog; see trace.catalog_sources.",
flush=True)
diff --git a/tokeneconomizer/toolprune/tools.py b/tokeneconomizer/toolprune/tools.py
new file mode 100644
index 0000000..a90b706
--- /dev/null
+++ b/tokeneconomizer/toolprune/tools.py
@@ -0,0 +1,104 @@
+"""The tool sets tool pruning never touches, and the optional per-task tool judge.
+
+`PROTECTED_TOOLS` is the work surface (shell, read, edit, search) on every agent; nothing prunes
+it. `INAPPLICABLE_TOOLS` are tools that cannot help a single headless task by construction
+(orchestration, scheduling, session memory, interactive questions). `judge_tools_for_task` is
+the paid, instruction-aware judge: it reads the task text and the catalog and says which tools
+to load for THIS task, never dropping a protected one.
+"""
+import json
+import re
+
+from ..pricing import approx_tokens as _approx_tokens
+
+INAPPLICABLE_TOOLS = (
+ # sub-agent orchestration (a single sealed task has nothing to delegate to)
+ "task", "list_agents", "read_agent", "write_agent",
+ # session DB / scheduling / skills / CLI self-docs — irrelevant to solving code
+ "sql", "session_store_sql", "manage_schedule", "skill",
+ "fetch_copilot_cli_documentation",
+ # persistent memory (also off by default headless) and its vote tool
+ "store_memory", "vote_memory",
+ # interactive Q&A: headless can never get an answer
+ "ask_user",
+ # ---- Claude Code tool names (PascalCase; disjoint from the Copilot names
+ # above, so listing both is safe regardless of --agent). These are
+ # inapplicable-by-construction for one sealed headless SWE-bench task.
+ # Work surface (Bash/Edit/Read/Write/Grep/Glob) is kept.
+ # sub-agent orchestration + workflow engine (nothing to delegate to):
+ "Agent", "Workflow",
+ # task list / scheduling / cron (no session persistence in a single task):
+ "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "TaskOutput", "TaskStop",
+ "ScheduleWakeup", "CronCreate", "CronDelete", "CronList",
+ # plan-mode + git-worktree session controls (irrelevant to a sealed rollout):
+ "EnterPlanMode", "ExitPlanMode", "EnterWorktree", "ExitWorktree",
+ # skills and notebooks:
+ "Skill", "NotebookEdit",
+ # interactive Q&A: headless can never get an answer:
+ "AskUserQuestion",
+)
+# Tools that must always stay available regardless of usage (the real work surface).
+PROTECTED_TOOLS = frozenset({
+ "bash", "view", "grep", "glob", "edit", "create", "str_replace",
+ "read_bash", "stop_bash", "list_bash", "read_file",
+ # Codex's complete native work surface (fixed; neither schema is removable).
+ "shell", "apply_patch",
+ # Claude Code work-surface names:
+ "Bash", "Edit", "Write", "Read", "Grep", "Glob", "MultiEdit",
+})
+
+
+TOOL_JUDGE_DOMAIN = (
+ "You configure the toolset for an autonomous coding agent that is about to solve ONE "
+ "specific GitHub issue by READING, EDITING, and TESTING source code in a single "
+ "repository, HEADLESS and SINGLE-SHOT (no human, one sealed container, no sub-agents / "
+ "scheduling / external memory). Every LOADED tool's JSON schema is re-sent on EVERY turn "
+ "and costs tokens. Below are the ISSUE text and the currently-available tools. For THIS "
+ "specific issue, mark each tool:\n"
+ " LOAD = plausibly useful to read/navigate/edit/run/test code to solve THIS issue\n"
+ " DROP = this specific issue will not need it\n"
+ "Be conservative: DROP only when you are confident the tool is irrelevant to THIS issue. "
+ "Do NOT assume a tool is needed merely because it exists. Return ONLY a JSON object "
+ "{tool_name: {\"load\": true|false, \"reason\": \"<short>\"}}.\n"
+)
+
+
+def judge_tools_for_task(problem_statement, catalog, runner, model="agent",
+ domain=None, max_issue_chars=4000):
+ """Per-task, INSTRUCTION-AWARE tool judge. Reads the (redacted) task text plus
+ the candidate tool catalog ({name: desc}) and returns ({tool: load_bool}, tokens): which
+ tools to LOAD for THIS task. Complements the trace-based rule — the caller unions the
+ DROP set with the evidence exclusions (and never drops PROTECTED or ever-used tools).
+
+ Leakage-safe: the caller MUST pass the SAME problem statement the agent receives, never
+ a solution or its tests. On any failure returns
+ ({}, tokens) so the caller keeps everything loaded (safe). `tokens` is the cache-aware
+ EFFECTIVE cost of this one-shot call (fresh input x1 + output x5 when approximated), on
+ the same basis as the session's own cost, so it is charged to the same ledger."""
+ if runner is None or not catalog or not problem_statement:
+ return {}, 0
+ brief = domain or TOOL_JUDGE_DOMAIN
+ prompt = (brief + "\nISSUE:\n" + problem_statement[:max_issue_chars]
+ + "\n\nTOOLS:\n" + "\n".join(f"- {n}: {d}" for n, d in catalog.items())
+ + "\n\nReturn the JSON classification:")
+ try:
+ raw, real = runner(prompt, model)
+ except Exception:
+ return {}, 0
+ raw = raw or ""
+ tokens = real if real is not None else (_approx_tokens(prompt) + 5 * _approx_tokens(raw))
+ out = {}
+ m = re.search(r"\{.*\}", raw, re.S)
+ if m:
+ try:
+ obj = json.loads(m.group(0))
+ for t, v in obj.items():
+ load = v.get("load") if isinstance(v, dict) else v
+ out[t] = bool(load)
+ except Exception:
+ return {}, tokens
+ # safety: never DROP a protected work tool, whatever the judge said.
+ for t in PROTECTED_TOOLS:
+ if t in out:
+ out[t] = True
+ return out, tokens
diff --git a/tokeneconomizer/trace.py b/tokeneconomizer/trace.py
deleted file mode 100644
index d396845..0000000
--- a/tokeneconomizer/trace.py
+++ /dev/null
@@ -1,161 +0,0 @@
-"""Single import point for trace reading -- the one normalized seam every mechanism
-reads agent trajectories through.
-
-All three mechanisms (injection / tooling / spiral) consume a saved rollout transcript
-through the four functions below, so the transcript-schema knowledge lives in exactly one
-place. The heavy lifting is delegated to the vendored `reflect` reader, which auto-detects
-the supported transcript schemas (Claude Code / Copilot CLI).
-
-`parse_catalog` is the only agent-specific branch: it returns the tool catalog the agent
-loaded for a task. For Codex there is no per-task JSON tool dump, so we return the known
-default surface (inlined below, so this package needs no runner/`agents` dependency).
-"""
-import json
-import os
-import re
-
-from .vendor import reflect
-
-# Codex ships a fixed default tool surface (it does not dump JSON tool schemas into a
-# debug log). Inlined here -- verbatim from the original CodexDriver.DEFAULT_TOOL_CATALOG
-# -- so catalog-size telemetry reflects what is actually loaded (and prunable) without a
-# dependency on the Docker/CLI runner layer.
-CODEX_DEFAULT_TOOL_CATALOG = {
- "shell": "Run shell commands to inspect, edit, and test the repository.",
- "apply_patch": "Apply source-code file changes.",
- "web_search": "Search the web (inapplicable on air-gapped SWE-bench).",
- "view_image": "Attach a local image to context (unused on text tasks).",
- "update_plan": "Maintain a step plan (scaffolding, unused here).",
- "spawn_agent": "Spawn a collaborating subagent.",
- "send_input": "Send input to a collaborating subagent.",
- "resume_agent": "Resume a collaborating subagent.",
- "wait_agent": "Wait for a collaborating subagent.",
- "close_agent": "Close a collaborating subagent.",
-}
-
-
-# rtk in its Codex mode is the one scaffold that changes the COMMAND LINE rather than hooking
-# it: the agent is told to type `rtk pytest`, `rtk git status`, `rtk proxy <cmd>`. Every
-# classifier that reads a command's first token -- the environment-fact vocabulary, the
-# spiral's test-run detector -- would otherwise stop seeing a test run, a fetch or a repo
-# query on exactly the arm that co-activates them (`codex-trimech-rtk`). One definition, so
-# the classifiers cannot disagree about what counts as the wrapper. `rtk proxy` is rtk's own
-# passthrough (run unfiltered, still tracked); a bare `rtk` with no command is left alone.
-RTK_PREFIX_RE = re.compile(r"^rtk\s+(?:proxy\s+)?(?=\S)")
-
-
-def strip_rtk_prefix(command):
- """`rtk pytest -q` -> `pytest -q`; anything else unchanged."""
- return RTK_PREFIX_RE.sub("", (command or "").lstrip(), count=1)
-
-
-def load_trajectory(path):
- """Ordered [(tool_name, args, result_text, success)] over a saved transcript.jsonl.
- Auto-detects the supported agent transcript schemas (delegates to reflect)."""
- return reflect.load_trajectory(path)
-
-
-def tool_usage(path):
- """{tool_name: count} over a saved transcript (delegates to reflect.tool_usage)."""
- return reflect.tool_usage(path)
-
-
-def detect(path):
- """LLM-free signal dict over a saved transcript (delegates to reflect.detect)."""
- return reflect.detect(path)
-
-
-# Ordered catalog sources for the Copilot CLI. The CLI has changed where it publishes the
-# loaded tool catalog at least twice, and each time the OLD reader started returning {} --
-# which untooling cannot distinguish from "this agent loaded no tools", so it degraded to a
-# silent no-op (see reflect.parse_tool_catalog). So instead of one reader with a fallback,
-# every known source is tried and the RICHEST result wins: descriptions beat names, more
-# tools beat fewer. That way one pipeline serves every CLI build we have seen, chooses per
-# run dir at runtime, and a build that publishes two sources is not at the mercy of which
-# one we happened to try first.
-#
-# schema_debug_log {name: desc} CLI <= ~1.0.81 the only source carrying descriptions
-# usage_checkpoint {name: ""} CLI ~1.0.82 transcript session.usage_checkpoint
-# flat_debug_log {name: ""} CLI >= 1.0.82 "tools": ["bash:66921ccc", ...]
-#
-# `catalog_sources` returns every source that produced anything, so a caller can record
-# which one won and notice the next migration from the rows instead of from a null result.
-def _read(path):
- try:
- return open(path, encoding="utf-8", errors="replace").read()
- except OSError:
- return ""
-
-
-def catalog_sources(run_dir_path, agent):
- """[(source_name, {tool: desc}), ...] for every catalog source that yielded tools."""
- if agent == "codex":
- return [("codex_default", dict(CODEX_DEFAULT_TOOL_CATALOG))]
- if agent == "claude":
- cat = reflect.parse_tool_catalog_claude(
- _read(os.path.join(run_dir_path, "transcript.jsonl")))
- return [("claude_transcript", cat)] if cat else []
- dbg = _read(os.path.join(run_dir_path, "copilot_debug.log"))
- tr = _read(os.path.join(run_dir_path, "transcript.jsonl"))
- out = []
- for name, cat in (("schema_debug_log", reflect.parse_tool_catalog(dbg)),
- ("usage_checkpoint", parse_tool_names_copilot(tr)),
- ("flat_debug_log", reflect.parse_tool_catalog_flat(dbg))):
- if cat:
- out.append((name, cat))
- return out
-
-
-def _catalog_rank(item):
- """Richest-first: prefer a source with descriptions, then one with more tools."""
- _, cat = item
- return (sum(1 for v in cat.values() if v), len(cat))
-
-
-def parse_catalog_with_source(run_dir_path, agent):
- """({tool: desc}, source_name) -- the richest catalog available for this run dir.
-
- source_name is None when NO source produced anything, which is the condition that used
- to pass silently and turn evidence untooling into a no-op. Callers should treat it as a
- defect signal, not as an empty catalog.
- """
- srcs = catalog_sources(run_dir_path, agent)
- if not srcs:
- return {}, None
- name, cat = max(srcs, key=_catalog_rank)
- return cat, name
-
-
-def parse_catalog(run_dir_path, agent):
- """Agent-agnostic parse of the loaded tool catalog ({name: desc}) from a task's run
- dir -- Copilot debug log or Claude transcript. Returns {} if unavailable.
-
- Codex has no per-task JSON tool dump, so its known default surface is returned instead
- (CODEX_DEFAULT_TOOL_CATALOG) so catalog-size telemetry is honest.
- """
- return parse_catalog_with_source(run_dir_path, agent)[0]
-
-
-def parse_tool_names_copilot(transcript_text):
- """{tool_name: ""} for the tools a Copilot run actually loaded.
-
- The names ride in `session.usage_checkpoint` events under
- data.promptCacheBreakState[].models[].tools[] -- the same list the model was sent, so
- this reflects what the agent really had, not a static default surface.
- """
- names = set()
- for line in (transcript_text or "").splitlines():
- line = line.strip()
- if not line:
- continue
- try:
- ev = json.loads(line)
- except Exception:
- continue
- for pcb in ((ev.get("data") or {}).get("promptCacheBreakState") or []):
- for model in (pcb.get("models") or {}).values():
- for tool in (model.get("tools") or []):
- name = tool.get("name")
- if name:
- names.add(name)
- return {n: "" for n in sorted(names)}
diff --git a/tokeneconomizer/trace/README.md b/tokeneconomizer/trace/README.md
new file mode 100644
index 0000000..43a9278
--- /dev/null
+++ b/tokeneconomizer/trace/README.md
@@ -0,0 +1,18 @@
+# Trace
+
+The one place that knows each agent's session-log format. Every mechanism reads a finished
+session as an ordered list of `(tool_name, args, result_text, success)` calls through
+`load_trajectory`, whichever agent wrote it.
+
+| Module | |
+|---|---|
+| `calls.py` | `load_trajectory` (format sniffed per file), `call_cwds`, `tool_usage`, `strip_rtk_prefix` |
+| `catalog.py` | the tool list a session loaded, from whichever source the agent publishes |
+| `claude.py` | Claude Code transcripts: calls with the shell's directory, usage by message id, subagents, deferred tools |
+| `codex.py` | `codex exec --json` streams; a session's rollout file, converted to that stream; usage |
+| `copilot.py` | Copilot CLI event logs: calls, usage, prompt-turns, MCP servers |
+| `pi.py` | Pi's session tree: the active branch, written as a Claude transcript; usage |
+| `jsonl.py` | line and record readers shared by the above |
+
+A new agent needs a reader here and nothing else: once its log reads as `(name, args, result,
+ok)` calls, every mechanism handles it.
diff --git a/tokeneconomizer/trace/__init__.py b/tokeneconomizer/trace/__init__.py
new file mode 100644
index 0000000..e686d19
--- /dev/null
+++ b/tokeneconomizer/trace/__init__.py
@@ -0,0 +1,40 @@
+"""Reading agent session logs: the one place that knows each agent's file format.
+
+Every mechanism reads a finished session through this package, so the format knowledge lives
+here and nowhere else:
+
+ * `calls` -- `load_trajectory`: any agent's log as ordered `(name, args, result, ok)` calls;
+ `call_cwds`, `tool_usage`, `strip_rtk_prefix`;
+ * `catalog` -- the tool list a session loaded, from whichever source the agent publishes;
+ * `claude`, `codex`, `copilot`, `pi` -- each agent's own session file: usage, metadata,
+ prompt-turns, and the conversions that let the readers above handle it.
+
+Stdlib only.
+"""
+from .calls import RTK_PREFIX_RE, call_cwds, load_trajectory, strip_rtk_prefix, tool_usage
+from .catalog import (CODEX_DEFAULT_TOOL_CATALOG, catalog_sources, parse_catalog,
+ parse_catalog_with_source, parse_tool_catalog, parse_tool_catalog_claude,
+ parse_tool_catalog_flat, parse_tool_names_copilot)
+from .claude import (claude_calls, claude_deferred_tools, claude_session_usage,
+ claude_subagent_files, claude_tool_usage)
+from .codex import (codex_capability_trace, codex_exec_calls, codex_rollout_to_exec,
+ codex_session_meta, codex_session_usage, rollout_item_to_exec)
+from .copilot import (copilot_event_calls, copilot_mcp_servers, copilot_session_meta,
+ copilot_session_usage, copilot_turns, mcp_server_of)
+from .pi import (pi_active_branch, pi_json_reply, pi_session_header, pi_session_to_claude,
+ pi_session_usage)
+
+__all__ = [
+ "RTK_PREFIX_RE", "call_cwds", "load_trajectory", "strip_rtk_prefix", "tool_usage",
+ "CODEX_DEFAULT_TOOL_CATALOG", "catalog_sources", "parse_catalog", "parse_catalog_with_source",
+ "parse_tool_catalog", "parse_tool_catalog_claude", "parse_tool_catalog_flat",
+ "parse_tool_names_copilot",
+ "claude_calls", "claude_deferred_tools", "claude_session_usage", "claude_subagent_files",
+ "claude_tool_usage",
+ "codex_capability_trace", "codex_exec_calls", "codex_rollout_to_exec", "codex_session_meta",
+ "codex_session_usage", "rollout_item_to_exec",
+ "copilot_event_calls", "copilot_mcp_servers", "copilot_session_meta",
+ "copilot_session_usage", "copilot_turns", "mcp_server_of",
+ "pi_active_branch", "pi_json_reply", "pi_session_header", "pi_session_to_claude",
+ "pi_session_usage",
+]
diff --git a/tokeneconomizer/trace/calls.py b/tokeneconomizer/trace/calls.py
new file mode 100644
index 0000000..8130c8d
--- /dev/null
+++ b/tokeneconomizer/trace/calls.py
@@ -0,0 +1,75 @@
+"""Every agent's tool calls as one ordered list of `(name, args, result_text, success)`.
+
+`load_trajectory` reads a saved session log of any supported agent -- a Claude Code transcript
+or `stream-json`, a Copilot CLI event log, a Codex `exec --json` stream -- and returns the same
+tuples, so a mechanism never needs to know which agent wrote the file. A Codex rollout and a Pi
+session are converted into one of these first (`codex.codex_rollout_to_exec`,
+`pi.pi_session_to_claude`).
+"""
+import os
+import re
+
+from .claude import claude_calls
+from .codex import codex_exec_calls
+from .copilot import copilot_event_calls, copilot_session_cwd
+
+# rtk in its Codex mode changes the COMMAND LINE rather than hooking it: the agent is told to
+# type `rtk pytest`, `rtk git status`, `rtk proxy <cmd>`. Every classifier that reads a
+# command's first token -- the micro-skill vocabulary, a test-run detector -- would otherwise
+# stop seeing a test run, a fetch or a repository query. One definition, so the classifiers
+# cannot disagree about what counts as the wrapper. `rtk proxy` is rtk's own passthrough (run
+# unfiltered, still tracked); a bare `rtk` with no command is left alone.
+RTK_PREFIX_RE = re.compile(r"^rtk\s+(?:proxy\s+)?(?=\S)")
+
+
+def strip_rtk_prefix(command):
+ """`rtk pytest -q` -> `pytest -q`; anything else unchanged."""
+ return RTK_PREFIX_RE.sub("", (command or "").lstrip(), count=1)
+
+
+def _is_codex_exec(lines):
+ return any('"type":"item.completed"' in line.replace(" ", "") for line in lines)
+
+
+def load_trajectory(path):
+ """Ordered [(tool_name, args, result_text, success)] over a saved session log.
+
+ The schema is sniffed from the lines: Codex emits completed items, Claude Code emits message
+ envelopes carrying `tool_use` blocks, and anything else is read as Copilot events."""
+ if not os.path.exists(path):
+ return []
+ lines = [l.strip() for l in open(path) if l.strip()]
+ if _is_codex_exec(lines):
+ return codex_exec_calls(lines)
+ if any('"tool_use"' in line or '"type": "assistant"' in line or '"type":"assistant"' in line
+ for line in lines):
+ return [c[:4] for c in claude_calls(lines)]
+ return copilot_event_calls(lines)
+
+
+def call_cwds(path):
+ """The directory each call of `load_trajectory(path)` ran in, aligned with it; None where
+ the log does not say. Claude Code's shell keeps its directory between calls, and its
+ transcript records it on every entry: after `cd tests && ...`, a bare `python runtests.py`
+ runs in `tests/`. Codex runs each command afresh. Copilot's log records only where the
+ session started, and that is where its calls are read as starting: models there type
+ `cd <that directory> && ...` before every command, which is then the plain form."""
+ calls = load_trajectory(path)
+ if not calls or not os.path.exists(path):
+ return [None] * len(calls)
+ lines = [l.strip() for l in open(path) if l.strip()]
+ if _is_codex_exec(lines):
+ return [None] * len(calls)
+ cwds = [c[4] for c in claude_calls(lines)]
+ if len(cwds) == len(calls):
+ return cwds
+ return [copilot_session_cwd(lines)] * len(calls)
+
+
+def tool_usage(path):
+ """{tool_name: calls} over a saved session log."""
+ counts = {}
+ for name, _args, _res, _ok in load_trajectory(path):
+ if name:
+ counts[name] = counts.get(name, 0) + 1
+ return counts
diff --git a/tokeneconomizer/trace/catalog.py b/tokeneconomizer/trace/catalog.py
new file mode 100644
index 0000000..aa14d7e
--- /dev/null
+++ b/tokeneconomizer/trace/catalog.py
@@ -0,0 +1,213 @@
+"""The tool catalog an agent loaded for a session: `{tool_name: description}`.
+
+Tool pruning needs the full list a session was offered, not only the tools it called. Each
+agent publishes it differently:
+
+ * Claude Code -- the `system` init event of `stream-json` names the loaded tools; their
+ descriptions are a static property of the CLI build, joined from a snapshot
+ (`claude_tool_catalog.json`);
+ * Copilot CLI -- its debug log, in one of three shapes depending on the build (below);
+ * Codex -- a fixed default surface (it writes no tool dump).
+
+`catalog_sources` returns every source that produced anything, and `parse_catalog_with_source`
+the richest of them with its name, so a caller can record which source won and notice the next
+format change from its records instead of from an empty catalog.
+"""
+import json
+import os
+import re
+
+# Codex ships a fixed default tool surface (it does not dump JSON tool schemas into a
+# debug log). Inlined here -- verbatim from the original CodexDriver.DEFAULT_TOOL_CATALOG
+# -- so catalog-size telemetry reflects what is actually loaded (and prunable) without a
+# dependency on the Docker/CLI runner layer.
+CODEX_DEFAULT_TOOL_CATALOG = {
+ "shell": "Run shell commands to inspect, edit, and test the repository.",
+ "apply_patch": "Apply source-code file changes.",
+ "web_search": "Search the web.",
+ "view_image": "Attach a local image to context (unused on text tasks).",
+ "update_plan": "Maintain a step plan (scaffolding, unused here).",
+ "spawn_agent": "Spawn a collaborating subagent.",
+ "send_input": "Send input to a collaborating subagent.",
+ "resume_agent": "Resume a collaborating subagent.",
+ "wait_agent": "Wait for a collaborating subagent.",
+ "close_agent": "Close a collaborating subagent.",
+}
+
+# Matches `"name": "<tool>", ... "description": "<text>"` in the (JSON-in-JSON) debug
+# log. Allows optional intervening scalar fields (e.g. `"title": null,`) between name and
+# description — newer Copilot CLI schemas insert `"title"`, which previously caused every
+# tool except the few lacking a title to be missed.
+_CATALOG_RE = re.compile(
+ r'"name":\s*"([a-z_]+)"\s*,\s*(?:"[a-z_]+":\s*(?:"[^"]*"|null|true|false|[0-9.]+)\s*,\s*)*'
+ r'"description":\s*"')
+
+# Recovering the Copilot CLI's catalog. Three sources, in the order the CLI dropped them:
+# 1. `_CATALOG_RE` over debug-log tool SCHEMAS ("name" + "description" objects). Gone by
+# 1.0.82 -- newer builds write no schemas at all.
+# 2. `parse_tool_names_copilot` over the transcript's `session.usage_checkpoint` ->
+# `data.promptCacheBreakState[].models[].tools[]`. Carried 1.0.82; 1.0.83 stopped emitting
+# the event.
+# 3. The flat catalog the debug log still writes on both versions --
+#
+# "tools": [ "bash:66921ccc", "read_bash:71c40652", ... ]
+#
+# With (1) and (2) both gone on 1.0.83 the catalog parsed EMPTY, and an empty catalog is
+# indistinguishable from "no tools loaded": pruning silently did nothing. So every source is
+# tried and the richest wins (descriptions beat names, more tools beat fewer). The flat form
+# carries names only, which is enough for evidence pruning; a tool judge reasoning over
+# descriptions gets nothing from it.
+_CATALOG_FLAT_BLOCK_RE = re.compile(r'"tools"\s*:\s*\[(.*?)\]', re.DOTALL)
+_CATALOG_FLAT_ITEM_RE = re.compile(r'"([a-z][a-z0-9_]*):[0-9a-f]{6,}"')
+
+
+def parse_tool_catalog_flat(debug_log_text):
+ """{tool_name: ""} from the CLI >= 1.0.83 flat `"tools": ["name:fingerprint", ...]`."""
+ out = {}
+ for block in _CATALOG_FLAT_BLOCK_RE.findall(debug_log_text or ""):
+ for name in _CATALOG_FLAT_ITEM_RE.findall(block):
+ out.setdefault(name, "")
+ return out
+
+
+def parse_tool_catalog(debug_log_text, max_desc=200):
+ """Extract {tool_name: short_description} from a saved copilot debug log. Works on
+ the JSON-in-JSON escaped payload (the tool schemas the model is sent). Agent-agnostic
+ in spirit: any agent whose log carries name/description tool defs parses the same.
+
+ Schema-only by design: the flat name:fingerprint catalog is a SEPARATE source
+ (`parse_tool_catalog_flat`), and `trace.catalog_sources` tries both and picks the
+ richest. Folding the fallback in here would make the winning source unreportable --
+ a run using the flat catalog would still claim it had parsed schemas."""
+ if not debug_log_text:
+ return {}
+ s = (debug_log_text.replace('\\"', '"').replace('\\n', '\n').replace('\\\\', '\\'))
+ out = {}
+ for m in _CATALOG_RE.finditer(s):
+ name = m.group(1)
+ if name in out:
+ continue
+ desc = s[m.end():m.end() + max_desc + 40].split('\n')[0][:max_desc]
+ out[name] = desc
+ return out
+
+
+# Claude Code writes no debug log of tool schemas. Its `stream-json` init event carries the
+# loaded tool NAMES; the descriptions are a static property of the CLI build, snapshotted once
+# into claude_tool_catalog.json and joined against the live names.
+_CLAUDE_CATALOG_SNAPSHOT = os.path.join(os.path.dirname(__file__),
+ "claude_tool_catalog.json")
+
+
+def _load_claude_catalog_snapshot(path=None):
+ p = path or _CLAUDE_CATALOG_SNAPSHOT
+ try:
+ with open(p, encoding="utf-8") as f:
+ return json.load(f)
+ except Exception:
+ return {}
+
+
+def parse_tool_catalog_claude(transcript_text, max_desc=200, snapshot=None):
+ """Extract {tool_name: short_description} for a Claude Code run. Reads the loaded
+ tool NAMES from the transcript's `system` init event and joins them to the
+ description snapshot (claude_tool_catalog.json). Names present in the transcript
+ but missing from the snapshot get an empty description (the classifier still sees
+ the name); snapshot entries whose tool was NOT loaded this run are skipped, so the
+ catalog reflects what the agent was actually sent. Returns {} if no system event."""
+ if not transcript_text:
+ return {}
+ snap = snapshot if snapshot is not None else _load_claude_catalog_snapshot()
+ names = []
+ for line in transcript_text.splitlines():
+ line = line.strip()
+ if not line or '"type"' not in line or '"system"' not in line:
+ continue
+ try:
+ ev = json.loads(line)
+ except Exception:
+ continue
+ if ev.get("type") == "system" and isinstance(ev.get("tools"), list):
+ names = ev["tools"]
+ break
+ return {n: (snap.get(n, "") or "")[:max_desc] for n in names}
+
+
+def _read(path):
+ try:
+ return open(path, encoding="utf-8", errors="replace").read()
+ except OSError:
+ return ""
+
+
+def catalog_sources(run_dir_path, agent):
+ """[(source_name, {tool: desc}), ...] for every catalog source that yielded tools."""
+ if agent == "codex":
+ return [("codex_default", dict(CODEX_DEFAULT_TOOL_CATALOG))]
+ if agent == "claude":
+ cat = parse_tool_catalog_claude(
+ _read(os.path.join(run_dir_path, "transcript.jsonl")))
+ return [("claude_transcript", cat)] if cat else []
+ dbg = _read(os.path.join(run_dir_path, "copilot_debug.log"))
+ tr = _read(os.path.join(run_dir_path, "transcript.jsonl"))
+ out = []
+ for name, cat in (("schema_debug_log", parse_tool_catalog(dbg)),
+ ("usage_checkpoint", parse_tool_names_copilot(tr)),
+ ("flat_debug_log", parse_tool_catalog_flat(dbg))):
+ if cat:
+ out.append((name, cat))
+ return out
+
+
+def _catalog_rank(item):
+ """Richest-first: prefer a source with descriptions, then one with more tools."""
+ _, cat = item
+ return (sum(1 for v in cat.values() if v), len(cat))
+
+
+def parse_catalog_with_source(run_dir_path, agent):
+ """({tool: desc}, source_name) -- the richest catalog available for this run dir.
+
+ source_name is None when NO source produced anything. Callers should treat that as a
+ defect signal, not as an empty catalog: an empty catalog makes tool pruning a no-op.
+ """
+ srcs = catalog_sources(run_dir_path, agent)
+ if not srcs:
+ return {}, None
+ name, cat = max(srcs, key=_catalog_rank)
+ return cat, name
+
+
+def parse_catalog(run_dir_path, agent):
+ """Agent-agnostic parse of the loaded tool catalog ({name: desc}) from a task's run
+ dir -- Copilot debug log or Claude transcript. Returns {} if unavailable.
+
+ Codex has no per-task JSON tool dump, so its known default surface is returned instead
+ (CODEX_DEFAULT_TOOL_CATALOG) so catalog-size telemetry is honest.
+ """
+ return parse_catalog_with_source(run_dir_path, agent)[0]
+
+
+def parse_tool_names_copilot(transcript_text):
+ """{tool_name: ""} for the tools a Copilot run actually loaded.
+
+ The names ride in `session.usage_checkpoint` events under
+ data.promptCacheBreakState[].models[].tools[] -- the same list the model was sent, so
+ this reflects what the agent really had, not a static default surface.
+ """
+ names = set()
+ for line in (transcript_text or "").splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ ev = json.loads(line)
+ except Exception:
+ continue
+ for pcb in ((ev.get("data") or {}).get("promptCacheBreakState") or []):
+ for model in (pcb.get("models") or {}).values():
+ for tool in (model.get("tools") or []):
+ name = tool.get("name")
+ if name:
+ names.add(name)
+ return {n: "" for n in sorted(names)}
diff --git a/tokeneconomizer/trace/claude.py b/tokeneconomizer/trace/claude.py
new file mode 100644
index 0000000..3ea1026
--- /dev/null
+++ b/tokeneconomizer/trace/claude.py
@@ -0,0 +1,139 @@
+"""Claude Code's session transcript: tool calls, token usage, subagents, deferred tools.
+
+The interactive transcript uses the same `message.content[]` envelope as `stream-json`, so one
+reader serves both. Usage is the difference: the transcript writes ONE ENTRY PER CONTENT BLOCK,
+each repeating its message's `usage`, so summing entries over-counts by the number of blocks;
+`claude_session_usage` keys by message id. Subagents write their own files under
+`<session>/subagents/`, and their tool calls and tokens belong to the session that spawned them.
+
+Only the conversation's own entries (`assistant`, `user`) carry its calls. Claude Code 2.1.300
+also writes `api-request-blob` entries that repeat each request's messages, earlier tool calls
+and results included; read as calls, every call counted twice.
+"""
+import glob
+import json
+import os
+
+from .jsonl import lines as _lines
+
+_CLAUDE_KEYS = ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens",
+ "output_tokens")
+CONVERSATION = ("assistant", "user")
+
+
+def claude_calls(lines):
+ """[(name, args, result_text, success, cwd)] for the lines of a Claude transcript: each
+ `tool_use` block paired with its `tool_result` by id, with the directory the shell was in."""
+ out, order, seen = [], [], {}
+ results = {}
+ for line in lines:
+ try:
+ ev = json.loads(line)
+ except Exception:
+ continue
+ if ev.get("type", "assistant") not in CONVERSATION:
+ continue
+ msg = ev.get("message") or {}
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+ for b in content:
+ if not isinstance(b, dict):
+ continue
+ if b.get("type") == "tool_use":
+ tid = b.get("id")
+ if tid in seen:
+ continue
+ seen[tid] = {"name": b.get("name"), "args": b.get("input", {}),
+ "cwd": ev.get("cwd") if isinstance(ev.get("cwd"), str) else None}
+ order.append(tid)
+ elif b.get("type") == "tool_result":
+ tid = b.get("tool_use_id")
+ c = b.get("content")
+ if isinstance(c, list):
+ c = " ".join(x.get("text", "") for x in c
+ if isinstance(x, dict))
+ results[tid] = (c if isinstance(c, str) else "",
+ not b.get("is_error", False))
+ for tid in order:
+ info = seen[tid]
+ res_text, ok = results.get(tid, ("", True))
+ out.append((info["name"], info["args"], res_text, ok, info["cwd"]))
+ return out
+
+
+def claude_subagent_files(transcript_path):
+ """Subagent transcripts of a Claude Code session: `<dir>/<session-id>/subagents/*.jsonl`."""
+ if not transcript_path:
+ return []
+ stem = os.path.splitext(transcript_path)[0]
+ return sorted(glob.glob(os.path.join(stem, "subagents", "*.jsonl")))
+
+
+def claude_session_usage(transcript_path, include_subagents=True):
+ """Token breakdown of a Claude Code session, de-duplicated by assistant message id.
+
+ Returns the four breakdown fields `pricing.effective_tokens` reads, plus `model` (the most
+ used one), `requests` (distinct assistant messages carrying usage) and `files` read."""
+ files = [transcript_path] + (claude_subagent_files(transcript_path)
+ if include_subagents else [])
+ by_id, models, anon = {}, {}, 0
+ for path in files:
+ for line in _lines(path):
+ if '"usage"' not in line:
+ continue
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ if ev.get("type") != "assistant":
+ continue
+ msg = ev.get("message") or {}
+ usage = msg.get("usage")
+ if not isinstance(usage, dict):
+ continue
+ mid = msg.get("id")
+ if not mid:
+ anon += 1
+ mid = f"anon-{path}-{anon}"
+ # Later entries of the same message carry the final counts; keep the last.
+ by_id[mid] = {k: int(usage.get(k) or 0) for k in _CLAUDE_KEYS}
+ model = msg.get("model")
+ if model:
+ models[model] = models.get(model, 0) + 1
+ out = {k: sum(u[k] for u in by_id.values()) for k in _CLAUDE_KEYS}
+ out["requests"] = len(by_id)
+ out["model"] = max(models, key=models.get) if models else None
+ out["files"] = len([f for f in files if os.path.exists(f)])
+ return out
+
+
+def claude_tool_usage(transcript_path, include_subagents=True):
+ """{tool: calls} over a session and, by default, its subagents -- a tool a subagent used is
+ in use, and denying it would take it from the subagent too."""
+ from .calls import tool_usage
+ counts = {}
+ files = [transcript_path] + (claude_subagent_files(transcript_path)
+ if include_subagents else [])
+ for path in files:
+ for name, n in tool_usage(path).items():
+ counts[name] = counts.get(name, 0) + n
+ return counts
+
+
+def claude_deferred_tools(transcript_path):
+ """Tool names the session listed as deferred (`deferred_tools_delta` attachments).
+
+ Deferred tools cost one listing line each, not a schema, so they matter little to the bill;
+ they are still part of what the session could call, so the pruning catalog includes them."""
+ names = set()
+ for line in _lines(transcript_path):
+ if '"deferred_tools_delta"' not in line:
+ continue
+ try:
+ att = json.loads(line).get("attachment") or {}
+ except ValueError:
+ continue
+ names.update(n for n in (att.get("addedNames") or []) if isinstance(n, str))
+ names.difference_update(n for n in (att.get("removedNames") or []) if isinstance(n, str))
+ return names
diff --git a/tokeneconomizer/vendor/claude_tool_catalog.json b/tokeneconomizer/trace/claude_tool_catalog.json
similarity index 100%
rename from tokeneconomizer/vendor/claude_tool_catalog.json
rename to tokeneconomizer/trace/claude_tool_catalog.json
diff --git a/tokeneconomizer/trace/codex.py b/tokeneconomizer/trace/codex.py
new file mode 100644
index 0000000..3afd549
--- /dev/null
+++ b/tokeneconomizer/trace/codex.py
@@ -0,0 +1,254 @@
+"""Codex: the `exec --json` stream, and the rollout file an interactive session leaves.
+
+`codex exec --json` emits one `item.completed` record per command or file change; those become
+`shell` and `apply_patch` calls. The rollout (`~/.codex/sessions/.../rollout-*.jsonl`) wraps the
+same item fields in `event_msg/item_completed` records with PascalCase item types, an argv list
+for the command and a path-keyed map for changes; `codex_rollout_to_exec` rewrites it into exec
+lines, after which every reader handles it as a harness stream. Usage comes from the rollout's
+`token_count` events, converted as `te_harness.codex.row_usage` converts the exec stream's,
+because Codex's `input_tokens` is the GRAND input total including both cache fields.
+
+A compressed rollout (`.jsonl.zst`) cannot be read with the standard library; it is reported as
+unreadable rather than half-read.
+"""
+import json
+import os
+import re
+import shlex
+
+from .jsonl import lines as _lines
+
+_SHELL_PATCH_FILE_RE = re.compile(r"^\*\*\* (?:Update|Add|Delete) File:\s*(.+?)\s*$", re.M)
+_SHELL_GIT_APPLY_PATH_RE = re.compile(r"^\+\+\+ b/(.+?)\s*$", re.M)
+
+
+def _shell_patch_paths(command):
+ """Paths touched by a patch applied through the shell, () when it is not one."""
+ command = command or ""
+ if "*** Begin Patch" in command:
+ found = _SHELL_PATCH_FILE_RE.findall(command)
+ elif re.search(r"\bgit\s+apply\b", command):
+ found = _SHELL_GIT_APPLY_PATH_RE.findall(command)
+ else:
+ return ()
+ return tuple(dict.fromkeys(p.strip() for p in found if p.strip()))
+
+
+def codex_exec_calls(lines):
+ """Normalize Codex `exec --json` item events.
+
+ Commands become `shell` calls with a `command` argument; file-change items become
+ `apply_patch` calls carrying the changed paths. Agent messages are not tool calls."""
+ out = []
+ for line in lines:
+ try:
+ ev = json.loads(line)
+ except Exception:
+ continue
+ if ev.get("type") != "item.completed":
+ continue
+ item = ev.get("item") or {}
+ kind = item.get("type")
+ if kind == "command_execution":
+ command = item.get("command") or ""
+ output = item.get("aggregated_output") or ""
+ try:
+ ok = int(item.get("exit_code")) == 0
+ except (TypeError, ValueError):
+ ok = False
+ # A patch applied THROUGH THE SHELL (`apply_patch <<'PATCH' ... *** Begin
+ # Patch`) is an edit as much as a native file_change item is; with some model
+ # providers it is the only form the CLI emits. It is surfaced as the same
+ # `apply_patch` call every reader already handles, so a provider change cannot
+ # hide edits from them.
+ paths = _shell_patch_paths(command)
+ if paths and (ok or "Success." in output):
+ out.append((
+ "apply_patch",
+ {"path": paths[0], "paths": list(paths), "changes": [],
+ "via": "shell"},
+ "",
+ True,
+ ))
+ out.append(("shell", {"command": command}, output, ok))
+ elif kind == "file_change":
+ changes = item.get("changes") or []
+ paths = [c.get("path") for c in changes
+ if isinstance(c, dict) and c.get("path")]
+ out.append((
+ "apply_patch",
+ {"path": paths[0] if paths else "", "paths": paths,
+ "changes": changes},
+ "",
+ item.get("status") == "completed",
+ ))
+ return out
+
+
+_ROLLOUT_ITEM_TYPES = {
+ "CommandExecution": "command_execution",
+ "FileChange": "file_change",
+ "AgentMessage": "agent_message",
+ "ImageView": "view_image",
+ "Extension": "web_search",
+ "McpToolCall": "mcp_tool_call",
+ "CollabToolCall": "collab_tool_call",
+}
+
+
+def _command_text(command):
+ if isinstance(command, list):
+ return shlex.join(str(c) for c in command)
+ return str(command or "")
+
+
+def rollout_item_to_exec(item):
+ """One rollout item -> the `codex exec --json` item shape, or None to skip it."""
+ kind = _ROLLOUT_ITEM_TYPES.get(item.get("type"), None)
+ if kind is None:
+ return None
+ out = {"type": kind, "id": item.get("id")}
+ if kind == "command_execution":
+ out.update(command=_command_text(item.get("command")),
+ aggregated_output=item.get("aggregated_output")
+ or ((item.get("stdout") or "") + (item.get("stderr") or "")),
+ exit_code=item.get("exit_code"),
+ status=str(item.get("status") or "").lower() or "completed")
+ elif kind == "file_change":
+ changes = item.get("changes")
+ if isinstance(changes, dict):
+ changes = [dict({"path": p}, **({"kind": (v or {}).get("type")}
+ if isinstance(v, dict) else {}))
+ for p, v in changes.items()]
+ out.update(changes=changes or [],
+ status=str(item.get("status") or "").lower() or "completed")
+ elif kind == "agent_message":
+ content = item.get("content")
+ if isinstance(content, list):
+ content = " ".join(c.get("text", "") for c in content if isinstance(c, dict))
+ out.update(text=content or "")
+ else:
+ out.update({k: v for k, v in item.items() if k not in ("type", "id")})
+ return out
+
+
+def codex_rollout_to_exec(rollout_path, out_path):
+ """Rewrite a Codex rollout into `codex exec --json` lines at `out_path`.
+
+ Returns the number of items written, or None when the rollout cannot be read (missing, or
+ compressed). The thread id rides on a leading `thread.started` line, as in the exec stream."""
+ if not rollout_path or rollout_path.endswith(".zst") or not os.path.exists(rollout_path):
+ return None
+ n = 0
+ thread = None
+ with open(out_path, "w", encoding="utf-8") as out:
+ for line in _lines(rollout_path):
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
+ if ev.get("type") == "session_meta" and thread is None:
+ thread = payload.get("id") or payload.get("session_id")
+ if thread:
+ out.write(json.dumps({"type": "thread.started", "thread_id": thread}) + "\n")
+ continue
+ if ev.get("type") != "event_msg" or payload.get("type") != "item_completed":
+ continue
+ item = rollout_item_to_exec(payload.get("item") or {})
+ if item is None:
+ continue
+ out.write(json.dumps({"type": "item.completed", "item": item}) + "\n")
+ n += 1
+ return n
+
+
+def codex_capability_trace(rollout_path, out_path):
+ """The exec-stream lines `toolprune.codex.inspect_usage` reads, for a rollout.
+
+ `codex_rollout_to_exec` keeps the items the other mechanisms read; capability evidence
+ also needs the model's own tool calls. In code mode every call is one `exec` custom tool
+ whose input calls `tools.<name>(...)` -- `tools.view_image(`, `tools.spawn_agent(` -- and
+ those ride in `response_item` records, which are added here as `custom_tool_call` /
+ `function_call` items, the shape `toolprune.codex._item_capabilities` parses. Returns the number
+ of items written, or None when the rollout cannot be read."""
+ n = codex_rollout_to_exec(rollout_path, out_path)
+ if n is None:
+ return None
+ with open(out_path, "a", encoding="utf-8") as out:
+ for line in _lines(rollout_path):
+ if '"response_item"' not in line:
+ continue
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ p = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
+ if ev.get("type") != "response_item" or p.get("type") not in (
+ "custom_tool_call", "function_call"):
+ continue
+ item = {"type": p.get("type"), "name": p.get("name"),
+ "id": p.get("call_id") or p.get("id"),
+ "status": str(p.get("status") or "completed").lower()}
+ item["input" if p.get("type") == "custom_tool_call" else "arguments"] = (
+ p.get("input") if p.get("type") == "custom_tool_call" else p.get("arguments"))
+ out.write(json.dumps({"type": "item.completed", "item": item}) + "\n")
+ n += 1
+ return n
+
+
+def codex_session_meta(rollout_path):
+ """{cwd, model, cli_version} from a rollout's session_meta / turn_context records."""
+ meta = {}
+ for line in _lines(rollout_path):
+ if '"session_meta"' not in line and '"turn_context"' not in line:
+ continue
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ p = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
+ if ev.get("type") == "session_meta":
+ meta.setdefault("cwd", p.get("cwd"))
+ meta.setdefault("cli_version", p.get("cli_version"))
+ elif ev.get("type") == "turn_context" and p.get("model"):
+ meta["model"] = p.get("model")
+ return meta
+
+
+def codex_session_usage(rollout_path):
+ """Token breakdown of a Codex session from its last cumulative `token_count`.
+
+ Converted as `te_harness.codex.row_usage` converts the exec stream: fresh input is the grand
+ input total less both cache fields, and reasoning tokens are added to output."""
+ total = None
+ requests = 0
+ for line in _lines(rollout_path):
+ if '"token_count"' not in line:
+ continue
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ p = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
+ if p.get("type") != "token_count":
+ continue
+ info = p.get("info") or {}
+ if info.get("total_token_usage"):
+ total = info["total_token_usage"]
+ requests += 1
+ meta = codex_session_meta(rollout_path)
+ if not total:
+ return {"input_tokens": None, "cache_read_input_tokens": None,
+ "cache_creation_input_tokens": None, "output_tokens": None,
+ "requests": 0, "model": meta.get("model")}
+ inp = int(total.get("input_tokens") or 0)
+ cached = int(total.get("cached_input_tokens") or 0)
+ cw = int(total.get("cache_write_input_tokens") or 0)
+ reasoning = int(total.get("reasoning_output_tokens") or 0)
+ return {"input_tokens": max(0, inp - cached - cw),
+ "cache_read_input_tokens": cached,
+ "cache_creation_input_tokens": cw,
+ "output_tokens": int(total.get("output_tokens") or 0) + reasoning,
+ "reasoning_output_tokens": reasoning,
+ "requests": requests, "model": meta.get("model")}
diff --git a/tokeneconomizer/trace/copilot.py b/tokeneconomizer/trace/copilot.py
new file mode 100644
index 0000000..e21d5ed
--- /dev/null
+++ b/tokeneconomizer/trace/copilot.py
@@ -0,0 +1,156 @@
+"""The GitHub Copilot CLI's session log: tool calls, usage, prompt-turns, MCP servers.
+
+Copilot writes each session to `<COPILOT_HOME>/session-state/<id>/events.jsonl`: the same
+`tool.execution_start` / `tool.execution_complete` event stream `copilot --output-format json`
+prints, so a session log and a harness stream read alike. Usage is in the `session.shutdown`
+event, per model:
+
+ modelMetrics[model].usage = {inputTokens, outputTokens, cacheReadTokens,
+ cacheWriteTokens, reasoningTokens}
+
+`inputTokens` is the GRAND input total: against a scripted endpoint reporting prompt_tokens=1000
+with cached_tokens=600 on each of 4 requests, it recorded inputTokens=4000 and
+cacheReadTokens=2400 (1.0.83). Fresh input is therefore input less both cache fields.
+`outputTokens` is the provider's completion count, which already includes reasoning. A session
+killed before it shut down has no usage; it is reported as unpriced.
+"""
+import json
+import os
+import re
+
+from .jsonl import records as _copilot_events
+
+_COPILOT_EXIT_RE = re.compile(r"<shellId: [^>]*?completed with exit code (-?\d+)>")
+
+
+def copilot_event_calls(lines):
+ """[(name, args, result_text, success)] from Copilot `tool.execution_*` events, a start
+ paired with its completion by call id."""
+ out, pend = [], {}
+ for line in lines:
+ try:
+ ev = json.loads(line)
+ except Exception:
+ continue
+ t = ev.get("type")
+ d = ev.get("data", {}) if isinstance(ev.get("data"), dict) else {}
+ if t == "tool.execution_start":
+ pend[d.get("toolCallId")] = {"name": d.get("toolName"),
+ "args": d.get("arguments", {})}
+ elif t == "tool.execution_complete":
+ info = pend.get(d.get("toolCallId"), {"name": "?", "args": {}})
+ res = d.get("result") or {}
+ content = res.get("content") if isinstance(res, dict) else ""
+ out.append((info["name"], info["args"],
+ content if isinstance(content, str) else "",
+ d.get("success")))
+ return out
+
+
+def copilot_session_cwd(lines):
+ """The directory a Copilot session started in (`session.start` -> `context.cwd`), or None."""
+ for line in lines:
+ if '"session.start"' not in line:
+ continue
+ try:
+ d = json.loads(line).get("data") or {}
+ except ValueError:
+ continue
+ cwd = (d.get("context") or {}).get("cwd")
+ return cwd if isinstance(cwd, str) else None
+ return None
+
+
+def copilot_session_meta(path):
+ """{cwd, model, cli_version, session_id} from a Copilot session's `session.start`."""
+ for ev in _copilot_events(path):
+ if ev.get("type") == "session.start":
+ d = ev.get("data") or {}
+ return {"cwd": (d.get("context") or {}).get("cwd"), "model": d.get("selectedModel"),
+ "cli_version": d.get("copilotVersion"), "session_id": d.get("sessionId")}
+ return {}
+
+
+def copilot_session_usage(path):
+ """Token breakdown of a Copilot session from its `session.shutdown` events."""
+ totals = {"input_tokens": 0, "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 0, "output_tokens": 0}
+ requests, models, seen, tool_defs = 0, {}, False, None
+ for ev in _copilot_events(path):
+ if ev.get("type") != "session.shutdown":
+ continue
+ d = ev.get("data") or {}
+ for model, m in (d.get("modelMetrics") or {}).items():
+ u = (m or {}).get("usage") or {}
+ inp = int(u.get("inputTokens") or 0)
+ cr, cw = int(u.get("cacheReadTokens") or 0), int(u.get("cacheWriteTokens") or 0)
+ totals["input_tokens"] += max(0, inp - cr - cw)
+ totals["cache_read_input_tokens"] += cr
+ totals["cache_creation_input_tokens"] += cw
+ totals["output_tokens"] += int(u.get("outputTokens") or 0)
+ n = int(((m or {}).get("requests") or {}).get("count") or 0)
+ requests += n
+ models[model] = models.get(model, 0) + n
+ seen = True
+ if d.get("toolDefinitionsTokens") is not None:
+ tool_defs = int(d["toolDefinitionsTokens"])
+ if not seen:
+ out = {k: None for k in totals}
+ out.update(requests=0, model=copilot_session_meta(path).get("model"))
+ return out
+ totals.update(requests=requests, model=max(models, key=models.get) if models else None,
+ tool_definitions_tokens=tool_defs)
+ return totals
+
+
+def copilot_turns(path):
+ """Prompt-turns of a Copilot session: [[(name, args, result, exit_code)]], one list per
+ user message, tool calls paired start-to-complete by call id."""
+ turns, cur, pend = [], None, {}
+ for ev in _copilot_events(path):
+ t, d = ev.get("type"), ev.get("data") or {}
+ if t == "user.message":
+ if cur:
+ turns.append(cur)
+ cur, pend = [], {}
+ elif t == "tool.execution_start" and cur is not None:
+ pend[d.get("toolCallId")] = (str(d.get("toolName") or ""),
+ d.get("arguments") if isinstance(d.get("arguments"),
+ dict) else {})
+ elif t == "tool.execution_complete" and cur is not None:
+ name, args = pend.pop(d.get("toolCallId"), (None, None))
+ if name is None:
+ continue
+ res = d.get("result") or {}
+ text = res.get("content") if isinstance(res, dict) else str(res)
+ text = text if isinstance(text, str) else json.dumps(text)
+ if not d.get("success", True) and isinstance(d.get("error"), (str, dict)):
+ text = (text or "") + "\n" + json.dumps(d.get("error"))
+ m = _COPILOT_EXIT_RE.search((text or "")[-400:])
+ cur.append((name, args, text or "", int(m.group(1)) if m else None))
+ if cur:
+ turns.append(cur)
+ return turns
+
+
+def copilot_mcp_servers(env=None):
+ """MCP server names a Copilot session can load: the built-in GitHub server plus every
+ server in the user's `mcp-config.json`. Tool names are `<server>-<tool>`."""
+ env = os.environ if env is None else env
+ home = env.get("COPILOT_HOME") or os.path.join(os.path.expanduser("~"), ".copilot")
+ names = {"github-mcp-server"}
+ try:
+ with open(os.path.join(home, "mcp-config.json"), encoding="utf-8") as fh:
+ names.update((json.load(fh).get("mcpServers") or {}).keys())
+ except (OSError, ValueError, AttributeError):
+ pass
+ return names
+
+
+def mcp_server_of(tool, servers):
+ """The server a Copilot tool name belongs to (longest matching `<server>-` prefix)."""
+ best = None
+ for s in servers:
+ if tool.startswith(s + "-") and (best is None or len(s) > len(best)):
+ best = s
+ return best
diff --git a/tokeneconomizer/trace/jsonl.py b/tokeneconomizer/trace/jsonl.py
new file mode 100644
index 0000000..b0faf94
--- /dev/null
+++ b/tokeneconomizer/trace/jsonl.py
@@ -0,0 +1,25 @@
+"""Reading a JSONL log line by line, skipping what does not parse."""
+import json
+
+
+def lines(path):
+ """Non-empty, stripped lines of a text file; nothing when it cannot be read."""
+ try:
+ with open(path, encoding="utf-8", errors="replace") as fh:
+ for line in fh:
+ line = line.strip()
+ if line:
+ yield line
+ except OSError:
+ return
+
+
+def records(path):
+ """Each line of a JSONL file that parses to a JSON object."""
+ for line in lines(path):
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(ev, dict):
+ yield ev
diff --git a/tokeneconomizer/trace/pi.py b/tokeneconomizer/trace/pi.py
new file mode 100644
index 0000000..8f96fb3
--- /dev/null
+++ b/tokeneconomizer/trace/pi.py
@@ -0,0 +1,154 @@
+"""Pi (earendil-works/pi): a session stored as a TREE of JSONL entries.
+
+Entries link by `id` / `parentId`; the conversation is the path from the current leaf back to
+the root, and an abandoned branch stays in the file. Assistant messages carry `toolCall` blocks
+({id, name, arguments}) and their own usage; tool results are `toolResult` messages with
+`isError`. `pi_session_to_claude` writes the ACTIVE branch as the Claude Code envelope the other
+readers already handle, so no mechanism needs a Pi branch.
+
+Usage, per pi-ai's own type: `input` excludes the cache fields, `output` already includes
+reasoning, and `cacheWrite1h` is a subset of `cacheWrite` -- so the mapping to the ledger's four
+fields is direct.
+"""
+import json
+import os
+
+from .jsonl import records
+
+
+def _pi_entries(path):
+ return list(records(path))
+
+
+def pi_session_header(path):
+ """The `session` header line ({id, cwd, version, ...}), {} if absent."""
+ for ev in _pi_entries(path)[:1]:
+ if ev.get("type") == "session":
+ return ev
+ return {}
+
+
+def pi_active_branch(entries):
+ """Entries on the path from the last entry (the leaf) back to the root, in order."""
+ by_id = {e.get("id"): e for e in entries if e.get("id")}
+ tree = [e for e in entries if e.get("id")]
+ if not tree:
+ return []
+ path, cur, seen = [], tree[-1], set()
+ while cur is not None and cur.get("id") not in seen:
+ seen.add(cur.get("id"))
+ path.append(cur)
+ cur = by_id.get(cur.get("parentId"))
+ return list(reversed(path))
+
+
+def _pi_usage(u):
+ if not isinstance(u, dict):
+ return None
+ return {"input_tokens": int(u.get("input") or 0),
+ "cache_read_input_tokens": int(u.get("cacheRead") or 0),
+ "cache_creation_input_tokens": int(u.get("cacheWrite") or 0),
+ "output_tokens": int(u.get("output") or 0),
+ "cost_usd": float((u.get("cost") or {}).get("total") or 0)}
+
+
+def _pi_text(content):
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return "\n".join(c.get("text", "") for c in content
+ if isinstance(c, dict) and c.get("type") == "text")
+ return ""
+
+
+def pi_session_to_claude(path, out_path):
+ """Write a Pi session's active branch as Claude Code transcript lines.
+
+ Pi starts every shell command afresh in the session's directory, so each call is written
+ with the header's `cwd`: an agent that types `cd /abs/repo && tox` into that directory ran
+ plain `tox`, and is read that way. Returns the number of tool calls written, or None when
+ the file is missing."""
+ if not path or not os.path.exists(path):
+ return None
+ n = 0
+ entries = _pi_entries(path)
+ head = entries[0] if entries and entries[0].get("type") == "session" else {}
+ cwd = head.get("cwd") if isinstance(head.get("cwd"), str) else None
+ with open(out_path, "w", encoding="utf-8") as out:
+ for e in pi_active_branch(entries):
+ if e.get("type") != "message":
+ continue
+ m = e.get("message") or {}
+ role = m.get("role")
+ if role == "user":
+ out.write(json.dumps({"type": "user", "message": {
+ "role": "user", "content": _pi_text(m.get("content"))}}) + "\n")
+ elif role == "assistant":
+ blocks = []
+ for b in m.get("content") or []:
+ if isinstance(b, dict) and b.get("type") == "toolCall":
+ blocks.append({"type": "tool_use", "id": b.get("id"),
+ "name": b.get("name"), "input": b.get("arguments") or {}})
+ n += 1
+ elif isinstance(b, dict) and b.get("type") == "text":
+ blocks.append({"type": "text", "text": b.get("text", "")})
+ msg = {"id": e.get("id"), "role": "assistant", "content": blocks,
+ "model": m.get("model")}
+ usage = _pi_usage(m.get("usage"))
+ if usage:
+ msg["usage"] = {k: v for k, v in usage.items() if k != "cost_usd"}
+ out.write(json.dumps(dict({"type": "assistant", "message": msg},
+ **({"cwd": cwd} if cwd else {}))) + "\n")
+ elif role == "toolResult":
+ out.write(json.dumps({"type": "user", "message": {"role": "user", "content": [{
+ "type": "tool_result", "tool_use_id": m.get("toolCallId"),
+ "content": _pi_text(m.get("content")),
+ "is_error": bool(m.get("isError"))}]}}) + "\n")
+ return n
+
+
+def pi_json_reply(stdout):
+ """(text, usage) of a `pi --print --mode json` run: the last assistant message's text, and
+ the usage of every assistant message in ledger fields, with Pi's model id and its own cost
+ estimate (`cost_usd`). `usage` is None when the run produced no assistant message."""
+ text, usage = "", None
+ for line in (stdout or "").splitlines():
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ m = ev.get("message") if isinstance(ev, dict) and ev.get("type") == "message_end" else None
+ if not isinstance(m, dict) or m.get("role") != "assistant":
+ continue
+ text = _pi_text(m.get("content")) or text
+ u = _pi_usage(m.get("usage"))
+ if u:
+ usage = usage or dict.fromkeys(u, 0)
+ for k, v in u.items():
+ usage[k] += v
+ usage["model"] = m.get("model") or usage.get("model")
+ return text, usage
+
+
+def pi_session_usage(path):
+ """Token breakdown of a Pi session's active branch, plus Pi's own cost estimate."""
+ totals = {"input_tokens": 0, "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 0, "output_tokens": 0}
+ cost, requests, models = 0.0, 0, {}
+ for e in pi_active_branch(_pi_entries(path)):
+ u = None
+ if e.get("type") == "message" and (e.get("message") or {}).get("role") == "assistant":
+ m = e["message"]
+ u = _pi_usage(m.get("usage"))
+ if m.get("model"):
+ models[m["model"]] = models.get(m["model"], 0) + 1
+ elif e.get("type") in ("usage", "compaction", "branch_summary"):
+ u = _pi_usage(e.get("usage"))
+ if u:
+ requests += 1
+ cost += u.pop("cost_usd")
+ for k in totals:
+ totals[k] += u[k]
+ totals.update(requests=requests, cost_usd_vendor=round(cost, 6),
+ model=max(models, key=models.get) if models else None)
+ return totals
diff --git a/tokeneconomizer/vendor/__init__.py b/tokeneconomizer/vendor/__init__.py
deleted file mode 100644
index 884e3d8..0000000
--- a/tokeneconomizer/vendor/__init__.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""Vendored, dependency-free building blocks shared by the economizer mechanisms.
-
-These three modules were lifted verbatim from the original research harness and carry
-NO third-party or cross-package dependencies (Python stdlib only). They are vendored
-here so `tokeneconomizer` is fully self-contained -- no `sys.path` injection into a
-sibling benchmark tree, no external install:
-
- * pricing -- cache-aware effective-token cost weighting (MODEL_WEIGHTS price table)
- * reflect -- LLM-free waste detector + gated reflection + evidence-untool tool judge
- * spiral -- runtime spiral-state folder + cheapest-sufficient escalation ladder
-
-The only edit applied on vendoring was rewiring spiral's lazy `import reflect` to the
-relative `from . import reflect` so the two stay a matched pair inside this package.
-"""
-from . import pricing, reflect, spiral
-
-__all__ = ["pricing", "reflect", "spiral"]
diff --git a/tokeneconomizer/vendor/reflect.py b/tokeneconomizer/vendor/reflect.py
deleted file mode 100644
index 0116c86..0000000
--- a/tokeneconomizer/vendor/reflect.py
+++ /dev/null
@@ -1,1377 +0,0 @@
-#!/usr/bin/env python3
-"""
-Gated reflection for the amortized self-optimization loop.
-
-A single unified engine: the detector surfaces BOTH environment-discovery waste
-(re-probing the interpreter/conda env) AND navigation waste (re-searching for the
-same code, re-reading the same files), and the optimizer turns either into durable,
-task-agnostic notes (env facts + "where things live" facts) for one compounding
-manifest. (Env-discovery is largely solved by the realistic baseline; navigation is
-the remaining lever — both flow through the same machinery.)
-
-Two stages, so the paid optimizer runs only when a free check finds something:
-
- STAGE A detect(trajectory) free, every task — arithmetic on the
- trajectory we already capture.
- GATE trigger(signals, window) fire the paid optimizer ONLY on an
- obvious / recurring inefficiency; default
- is no-op (the interface stays unchanged).
- STAGE B optimize(signals, state, ...) paid, rare — an LLM call (model
- configurable, default = the agent being
- optimized) that emits durable, TASK-AGNOSTIC
- repo notes addressing the detected waste.
-
-Because triggers fire often early in a stream and rarely once the interface
-matures, optimizer overhead is front-loaded and self-extinguishing.
-
-The detector understands the Copilot CLI transcript schema
-(tool.execution_start / tool.execution_complete). Stdlib only.
-"""
-import json
-import os
-import re
-import subprocess
-
-# ---- inefficiency signal patterns (kept in sync with trace analysis) ---------
-ENV_PROBE_RE = re.compile(
- r"(which\s+python|ls\s+/opt/miniconda3|conda\s+env\s+list|conda\s+activate|"
- r"source\s+activate|compgen\s+-c|/envs/|command\s+-v\s+python|"
- r"ls\s+/usr/bin.*python|find\s+/.*python|\bpython\d?\s+--version)",
- re.IGNORECASE)
-
-# Generic command-INTENT buckets (NOT repo-specific): agents routinely burn a
-# round-trip discovering the right *form* of a common operation. We watch the
-# test-running family because switching forms within a task ("tried pytest, then
-# fell back to the repo's runner") is a high-precision, leakage-safe, recurring
-# discovery that a durable "use <tool> to run tests" note eliminates.
-TEST_FORM_RES = {
- "pytest": re.compile(r"\b(pytest|py\.test|python\s+-m\s+pytest)\b", re.I),
- "runtests.py": re.compile(r"runtests(\.py)?", re.I),
- "manage.py test": re.compile(r"manage\.py\s+test", re.I),
- "tox": re.compile(r"\btox\b", re.I),
- "nox": re.compile(r"\bnox\b", re.I),
- "unittest": re.compile(r"python\s+-m\s+unittest", re.I),
- "trial": re.compile(r"\btrial\b", re.I),
-}
-# Infrastructure-error markers (NOT test failures like "FAIL:"): these signal the
-# command itself was wrong/misconfigured. They matter because agents pipe through
-# `2>&1 | tail`, so the shell exit code is 0 and a success-based detector is blind.
-ERROR_MARKER_RE = re.compile(
- r"(Traceback \(most recent call last\)|ModuleNotFoundError|ImportError|"
- r"cannot import|command not found|No such file or directory|"
- r"unrecognized arguments|no tests ran|errors during collection|"
- r"is not a registered|ERROR: .*not found|usage: )", re.IGNORECASE)
-# External fetches: web/github tools or bash curl/wget to a non-local URL. Attempts
-# remain potential discovery waste; successful fetches are the integrity flag because
-# blocked attempts cannot import solution evidence into the sealed repository.
-EXTERNAL_URL_RE = re.compile(r"\b(curl|wget)\b[^\n]*https?://", re.IGNORECASE)
-# Backstop integrity flag: ANY mention of a GitHub gold-source host in a command,
-# regardless of the client used (curl, python urllib/requests, etc.). github.com
-# matches api.github.com too; api.githubcopilot.com (the model endpoint) is NOT
-# matched, so legitimate model traffic never trips this.
-GOLD_HOST_RE = re.compile(
- r"(?:github\.com|githubusercontent\.com|codeload\.github)", re.IGNORECASE)
-# A network attempt is still useful diagnostic evidence, but an isolation shim or a
-# refused connection means no external bytes entered the task. Keep those attempts
-# distinct from successful fetches so integrity validation does not reject a sealed run.
-BLOCKED_FETCH_RE = re.compile(
- r"(?:(?:gold|network)-isolation:.*blocked|failed to connect|connection refused|"
- r"could not resolve host|network is unreachable|name or service not known|"
- r"operation timed out)", re.IGNORECASE)
-# A command that RUNS code to verify behavior — the test/reproduction step of the
-# edit->test->fail iteration loop. Broader than TEST_FORM_RES (it also matches the
-# ad-hoc `python -c` reproductions agents use). Used to detect EXECUTION-iteration
-# waste (re-running an unchanged command), which drives the costly multi-turn spirals.
-TEST_RUN_RE = re.compile(
- r"(runtests(\.py)?|\bpytest\b|py\.test|manage\.py\s+test|python\s+-m\s+unittest|"
- r"\btox\b|\bnox\b|\btrial\b|python\d?\s+-c\b)", re.IGNORECASE)
-
-
-def _norm_cmd(c):
- return re.sub(r"\s+", " ", c.strip()).lower()
-
-
-def load_trajectory(path):
- """Return an ordered list of (toolName, command_or_args, result_text, success)
- from a saved agent transcript.jsonl. Auto-detects the format: Copilot CLI emits
- tool.execution_start/complete events; Claude Code emits `assistant` messages whose
- content[] carries `tool_use` blocks (and `user` messages with `tool_result`)."""
- out, pend = [], {}
- if not os.path.exists(path):
- return out
- lines = [l.strip() for l in open(path) if l.strip()]
- # Format sniff: Codex emits completed command/file items directly (there is no
- # start/result pairing). Handle it before the Claude/Copilot paths so every
- # downstream economizer stage sees the same normalized tuple stream.
- if any('"type":"item.completed"' in line.replace(" ", "") for line in lines):
- return _load_trajectory_codex(lines)
- # format sniff: Claude if any line is an assistant/user message-envelope event.
- is_claude = False
- for line in lines:
- if '"tool_use"' in line or ('"type": "assistant"' in line
- or '"type":"assistant"' in line):
- is_claude = True
- break
- if is_claude:
- return _load_trajectory_claude(lines)
- for line in lines:
- try:
- ev = json.loads(line)
- except Exception:
- continue
- t = ev.get("type")
- d = ev.get("data", {}) if isinstance(ev.get("data"), dict) else {}
- if t == "tool.execution_start":
- pend[d.get("toolCallId")] = {"name": d.get("toolName"),
- "args": d.get("arguments", {})}
- elif t == "tool.execution_complete":
- info = pend.get(d.get("toolCallId"), {"name": "?", "args": {}})
- res = d.get("result") or {}
- content = res.get("content") if isinstance(res, dict) else ""
- out.append((info["name"], info["args"],
- content if isinstance(content, str) else "",
- d.get("success")))
- return out
-
-
-_SHELL_PATCH_FILE_RE = re.compile(r"^\*\*\* (?:Update|Add|Delete) File:\s*(.+?)\s*$", re.M)
-_SHELL_GIT_APPLY_PATH_RE = re.compile(r"^\+\+\+ b/(.+?)\s*$", re.M)
-
-
-def _shell_patch_paths(command):
- """Paths touched by a patch applied through the shell, () when it is not one."""
- command = command or ""
- if "*** Begin Patch" in command:
- found = _SHELL_PATCH_FILE_RE.findall(command)
- elif re.search(r"\bgit\s+apply\b", command):
- found = _SHELL_GIT_APPLY_PATH_RE.findall(command)
- else:
- return ()
- return tuple(dict.fromkeys(p.strip() for p in found if p.strip()))
-
-
-def _load_trajectory_codex(lines):
- """Normalize Codex ``exec --json`` item events.
-
- Commands become ``shell`` calls with a conventional ``command`` argument;
- file-change items become ``apply_patch`` calls carrying the changed paths.
- Agent-message items are deliberately omitted because they are not tool calls.
- """
- out = []
- for line in lines:
- try:
- ev = json.loads(line)
- except Exception:
- continue
- if ev.get("type") != "item.completed":
- continue
- item = ev.get("item") or {}
- kind = item.get("type")
- if kind == "command_execution":
- command = item.get("command") or ""
- output = item.get("aggregated_output") or ""
- try:
- ok = int(item.get("exit_code")) == 0
- except (TypeError, ValueError):
- ok = False
- # A patch applied THROUGH THE SHELL (`apply_patch <<'PATCH' ... *** Begin
- # Patch`) is an edit as much as a native file_change item is; on some model
- # providers it is the only form the CLI emits (2026-09-12). Surface
- # it as the same `apply_patch` call every consumer already reads -- injection
- # drift, the untool audit, the waste signals -- so a provider change cannot
- # blind them.
- paths = _shell_patch_paths(command)
- if paths and (ok or "Success." in output):
- out.append((
- "apply_patch",
- {"path": paths[0], "paths": list(paths), "changes": [],
- "via": "shell"},
- "",
- True,
- ))
- out.append(("shell", {"command": command}, output, ok))
- elif kind == "file_change":
- changes = item.get("changes") or []
- paths = [c.get("path") for c in changes
- if isinstance(c, dict) and c.get("path")]
- out.append((
- "apply_patch",
- {"path": paths[0] if paths else "", "paths": paths,
- "changes": changes},
- "",
- item.get("status") == "completed",
- ))
- return out
-
-
-def _load_trajectory_claude(lines):
- """Claude Code stream-json variant of load_trajectory. Pairs each `tool_use` block
- (in an `assistant` message) with its matching `tool_result` (in a later `user`
- message) by tool_use id, yielding the same (name, args, result_text, success)
- tuples the Copilot path returns so all downstream analysis is format-agnostic."""
- out, order, seen = [], [], {}
- results = {}
- for line in lines:
- try:
- ev = json.loads(line)
- except Exception:
- continue
- msg = ev.get("message") or {}
- content = msg.get("content")
- if not isinstance(content, list):
- continue
- for b in content:
- if not isinstance(b, dict):
- continue
- if b.get("type") == "tool_use":
- tid = b.get("id")
- seen[tid] = {"name": b.get("name"), "args": b.get("input", {})}
- order.append(tid)
- elif b.get("type") == "tool_result":
- tid = b.get("tool_use_id")
- c = b.get("content")
- if isinstance(c, list):
- c = " ".join(x.get("text", "") for x in c
- if isinstance(x, dict))
- results[tid] = (c if isinstance(c, str) else "",
- not b.get("is_error", False))
- for tid in order:
- info = seen[tid]
- res_text, ok = results.get(tid, ("", True))
- out.append((info["name"], info["args"], res_text, ok))
- return out
-
-
-def _basename(p):
- return p.rstrip("/").split("/")[-1] if p else p
-
-
-# ---- v4.1 mechanism A: untooling (per-turn-prefix minimization) ---------------
-# The sealed agent re-feeds every loaded tool's JSON schema in its context EVERY
-# turn (cache_read), so unused tool schemas are a fixed per-turn tax. Because the rollout is
-# single-shot we cannot re-enable a tool mid-task, so we exclude ONLY tools that are
-# inapplicable BY CONSTRUCTION for one sealed SWE-bench task — the agentic-
-# orchestration / session / memory / scheduling / docs meta-tools that cannot help
-# edit-and-test a repo and that the agent would only invoke by mistake. File/shell/
-# search/edit tools (bash, view, grep, glob, edit, create, read_bash) are NEVER
-# excluded. The set is intentionally conservative; widen only with stream evidence.
-INAPPLICABLE_TOOLS = (
- # sub-agent orchestration (a single sealed task has nothing to delegate to)
- "task", "list_agents", "read_agent", "write_agent",
- # session DB / scheduling / skills / CLI self-docs — irrelevant to solving code
- "sql", "session_store_sql", "manage_schedule", "skill",
- "fetch_copilot_cli_documentation",
- # persistent memory (also off by default headless) and its vote tool
- "store_memory", "vote_memory",
- # interactive Q&A: headless can never get an answer
- "ask_user",
- # ---- Claude Code tool names (PascalCase; disjoint from the Copilot names
- # above, so listing both is safe regardless of --agent). These are
- # inapplicable-by-construction for one sealed headless SWE-bench task.
- # Work surface (Bash/Edit/Read/Write/Grep/Glob) is kept.
- # sub-agent orchestration + workflow engine (nothing to delegate to):
- "Agent", "Workflow",
- # task list / scheduling / cron (no session persistence in a single task):
- "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "TaskOutput", "TaskStop",
- "ScheduleWakeup", "CronCreate", "CronDelete", "CronList",
- # plan-mode + git-worktree session controls (irrelevant to a sealed rollout):
- "EnterPlanMode", "ExitPlanMode", "EnterWorktree", "ExitWorktree",
- # skills, notebooks, and network tools (network is scrubbed in-container):
- "Skill", "NotebookEdit", "WebSearch", "WebFetch",
- # interactive Q&A: headless can never get an answer:
- "AskUserQuestion",
-)
-# Tools that must always stay available regardless of usage (the real work surface).
-PROTECTED_TOOLS = frozenset({
- "bash", "view", "grep", "glob", "edit", "create", "str_replace",
- "read_bash", "stop_bash", "list_bash", "read_file",
- # Codex's complete native work surface (fixed; neither schema is removable).
- "shell", "apply_patch",
- # Claude Code work-surface names:
- "Bash", "Edit", "Write", "Read", "Grep", "Glob", "MultiEdit",
-})
-
-
-def tool_usage(trajectory_path):
- """Map toolName -> call count for one trajectory (free; for untooling evidence
- and stream-wide zero-usage learning)."""
- counts = {}
- for name, _args, _res, _ok in load_trajectory(trajectory_path):
- if name:
- counts[name] = counts.get(name, 0) + 1
- return counts
-
-
-def untool_exclusions(used_tools=None, extra_inapplicable=()):
- """Return the list of tool names to exclude from the agent's schema this task.
-
- Conservative by default: the static INAPPLICABLE_TOOLS set (inapplicable by
- construction for a sealed single task). `used_tools` is the set of tools observed
- in use across the stream so far; any inapplicable tool that HAS been used is kept
- (so a repo that genuinely uses one is never starved). PROTECTED_TOOLS are never
- excluded even if listed. `extra_inapplicable` lets a caller widen the set with
- stream evidence (e.g. tools with zero uses across a long window)."""
- used = set(used_tools or ())
- cand = list(INAPPLICABLE_TOOLS) + [t for t in extra_inapplicable
- if t not in INAPPLICABLE_TOOLS]
- return [t for t in cand if t not in PROTECTED_TOOLS and t not in used]
-
-
-# ---- v4.2: self-contained untooling (optimizer-reasoned, not hardcoded) -------
-# The v4.1 exclusion set above is a HAND-AUTHORED prior. v4.2 makes untooling
-# self-contained: introspect the agent's ACTUAL loaded tool catalog (from its debug
-# log — agent-agnostic), then let the optimizer LLM classify each tool KEEP/EXCLUDE/
-# UNSURE from its description + a fixed domain brief. EXCLUDE drops immediately; UNSURE
-# stays LOADED (safe) until observed-unused over a window, then demotes to EXCLUDE; a
-# periodic re-audit reloads the full catalog to recover from drift. Prototype validated:
-# deterministic, reproduces the high-value hand exclusions (incl. the ~9.6k-token `task`
-# schema), zero unsafe over-exclusions. The hardcoded list remains the offline fallback.
-
-# Matches `"name": "<tool>", ... "description": "<text>"` in the (JSON-in-JSON) debug
-# log. Allows optional intervening scalar fields (e.g. `"title": null,`) between name and
-# description — newer Copilot CLI schemas insert `"title"`, which previously caused every
-# tool except the few lacking a title to be missed.
-_CATALOG_RE = re.compile(
- r'"name":\s*"([a-z_]+)"\s*,\s*(?:"[a-z_]+":\s*(?:"[^"]*"|null|true|false|[0-9.]+)\s*,\s*)*'
- r'"description":\s*"')
-
-
-# Recovering the loaded tool catalog on the Copilot CLI, and why this fallback exists.
-#
-# Three sources have been tried, in the order the CLI killed them:
-# 1. `_CATALOG_RE` over debug-log tool SCHEMAS ("name"+"description" objects). Dead by
-# 1.0.82 -- newer builds write no schemas at all.
-# 2. `trace.parse_tool_names_copilot` over the transcript's `session.usage_checkpoint`
-# -> `data.promptCacheBreakState[].models[].tools[]`. This is what actually carried
-# 1.0.82, and 1.0.83 stopped emitting the event entirely (measured: 1 occurrence per
-# 1.0.82 transcript, 0 per 1.0.83 transcript).
-# 3. This parser: the flat catalog the debug log still writes on BOTH versions --
-#
-# "tools": [ "bash:66921ccc", "read_bash:71c40652", ... ]
-#
-# With (1) and (2) both dead on 1.0.83 the catalog parsed EMPTY, so `catalog_tools` stayed
-# empty, the drop-candidate loop had nothing to iterate, and evidence untooling silently
-# became a no-op -- every `untool-*` / `trimech*` arm ran as its own baseline while still
-# being named an untooling arm. Measured 2026-09-05 on one sklearn seed: CLI 1.0.82 gave
-# `untool_catalog_size=17` and dropped 8 tools on 30 of 31 tasks; CLI 1.0.83, same harness
-# and same repo, gave `untool_catalog_size=0` and dropped nothing on 31 of 31.
-#
-# Source (3) is preferred over (2) because it survived both upgrades. Names only -- the
-# fingerprint form carries no descriptions, the same consequence (2) had: evidence
-# untooling works (it needs names), the instruction-aware tool JUDGE has nothing to reason
-# over and will drop nothing while still billing for the call.
-_CATALOG_FLAT_BLOCK_RE = re.compile(r'"tools"\s*:\s*\[(.*?)\]', re.DOTALL)
-_CATALOG_FLAT_ITEM_RE = re.compile(r'"([a-z][a-z0-9_]*):[0-9a-f]{6,}"')
-
-
-def parse_tool_catalog_flat(debug_log_text):
- """{tool_name: ""} from the CLI >= 1.0.83 flat `"tools": ["name:fingerprint", ...]`."""
- out = {}
- for block in _CATALOG_FLAT_BLOCK_RE.findall(debug_log_text or ""):
- for name in _CATALOG_FLAT_ITEM_RE.findall(block):
- out.setdefault(name, "")
- return out
-
-
-def parse_tool_catalog(debug_log_text, max_desc=200):
- """Extract {tool_name: short_description} from a saved copilot debug log. Works on
- the JSON-in-JSON escaped payload (the tool schemas the model is sent). Agent-agnostic
- in spirit: any agent whose log carries name/description tool defs parses the same.
-
- Schema-only by design: the flat name:fingerprint catalog is a SEPARATE source
- (`parse_tool_catalog_flat`), and `trace.catalog_sources` tries both and picks the
- richest. Folding the fallback in here would make the winning source unreportable --
- a run using the flat catalog would still claim it had parsed schemas."""
- if not debug_log_text:
- return {}
- s = (debug_log_text.replace('\\"', '"').replace('\\n', '\n').replace('\\\\', '\\'))
- out = {}
- for m in _CATALOG_RE.finditer(s):
- name = m.group(1)
- if name in out:
- continue
- desc = s[m.end():m.end() + max_desc + 40].split('\n')[0][:max_desc]
- out[name] = desc
- return out
-
-
-# Claude Code emits no debug log of raw schemas the way the Copilot CLI does. Its
-# stream-json transcript carries the loaded tool NAMES (the `system` init event's
-# `tools` list) but not their descriptions. The descriptions are a static property
-# of the CLI build, so we snapshot them ONCE (host-side, from a recorded request) into
-# claude_tool_catalog.json and JOIN the transcript's live tool names against it.
-# This is the agent-agnostic analog of parse_tool_catalog: same {name: desc} output,
-# same downstream classify_tools/learned_exclusions path — only the source differs.
-_CLAUDE_CATALOG_SNAPSHOT = os.path.join(os.path.dirname(__file__),
- "claude_tool_catalog.json")
-
-
-def _load_claude_catalog_snapshot(path=None):
- p = path or _CLAUDE_CATALOG_SNAPSHOT
- try:
- with open(p, encoding="utf-8") as f:
- return json.load(f)
- except Exception:
- return {}
-
-
-def parse_tool_catalog_claude(transcript_text, max_desc=200, snapshot=None):
- """Extract {tool_name: short_description} for a Claude Code run. Reads the loaded
- tool NAMES from the transcript's `system` init event and joins them to the
- description snapshot (claude_tool_catalog.json). Names present in the transcript
- but missing from the snapshot get an empty description (the classifier still sees
- the name); snapshot entries whose tool was NOT loaded this run are skipped, so the
- catalog reflects what the agent was actually sent. Returns {} if no system event."""
- if not transcript_text:
- return {}
- snap = snapshot if snapshot is not None else _load_claude_catalog_snapshot()
- names = []
- for line in transcript_text.splitlines():
- line = line.strip()
- if not line or '"type"' not in line or '"system"' not in line:
- continue
- try:
- ev = json.loads(line)
- except Exception:
- continue
- if ev.get("type") == "system" and isinstance(ev.get("tools"), list):
- names = ev["tools"]
- break
- return {n: (snap.get(n, "") or "")[:max_desc] for n in names}
-
-
-TOOL_CLASSIFY_DOMAIN = (
- "You configure the toolset for an autonomous coding agent that will solve GitHub "
- "issues by READING, EDITING, and TESTING source code in a single repository. "
- "Execution constraints: the agent runs HEADLESS and SINGLE-SHOT (no human is "
- "available to answer questions), in one sealed container per task (no sub-agents, no "
- "persistent cross-session state, no scheduling, no external memory). Each loaded "
- "tool's full JSON schema is re-sent to the model on EVERY turn, costing tokens, so "
- "tools that cannot possibly help edit-and-test code in this setting should be "
- "removed.\n\nFor EACH tool below, classify it:\n"
- " KEEP = could plausibly help read/navigate/edit/run/test code in a repo\n"
- " EXCLUDE = structurally cannot help in this headless single-shot code-fixing "
- "setting\n"
- " UNSURE = ambiguous\n"
- "Be conservative: only EXCLUDE when you are confident the tool is inapplicable BY "
- "CONSTRUCTION. Return ONLY a JSON object {tool_name: {\"class\": "
- "\"KEEP|EXCLUDE|UNSURE\", \"reason\": \"<short>\"}}.\n\nTOOLS:\n"
-)
-
-
-def classify_tools(catalog, runner, model="agent", domain=None):
- """Optimizer step (v4.2): classify each tool in `catalog` ({name: desc}) as
- KEEP/EXCLUDE/UNSURE via one LLM call. Returns ({tool: {class, reason}}, tokens).
- Leakage-safe (reads only tool metadata + a fixed domain brief, never task content).
- On any failure returns ({}, tokens) so the caller can fall back to the hardcoded
- list. PROTECTED_TOOLS are force-KEEP regardless of the model (never let the LLM drop
- the core work surface).
-
- `domain` overrides the classification brief (defaults to the SWE-bench code-fixing
- brief TOOL_CLASSIFY_DOMAIN). A different benchmark (e.g. a read-only secret-finding
- scan) passes its own brief so applicability is judged against ITS task, not SWE-bench's
- — this is what makes the mechanism self-contained across benchmarks rather than
- tied to a hardcoded SWE-bench assumption. The brief must instruct the model to return
- the same {tool: {class, reason}} JSON."""
- if runner is None or not catalog:
- return {}, 0
- prompt = ((domain or TOOL_CLASSIFY_DOMAIN)
- + "\n".join(f"- {n}: {d}" for n, d in catalog.items())
- + "\n\nReturn the JSON classification:")
- raw, real = runner(prompt, model)
- raw = raw or ""
- tokens = real if real is not None else _approx_tokens(prompt) + _approx_tokens(raw)
- out = {}
- m = re.search(r"\{.*\}", raw, re.S)
- if m:
- try:
- obj = json.loads(m.group(0))
- for t, v in obj.items():
- cls = (v.get("class") if isinstance(v, dict) else v) or "UNSURE"
- cls = str(cls).upper()
- if cls not in ("KEEP", "EXCLUDE", "UNSURE"):
- cls = "UNSURE"
- reason = (v.get("reason") if isinstance(v, dict) else "") or ""
- out[t] = {"class": cls, "reason": str(reason)[:160]}
- except Exception:
- return {}, tokens
- # safety: never EXCLUDE a protected work tool, whatever the model said.
- for t in list(out):
- if t in PROTECTED_TOOLS and out[t]["class"] == "EXCLUDE":
- out[t] = {"class": "KEEP", "reason": "protected work tool (forced)"}
- return out, tokens
-
-
-TOOL_JUDGE_DOMAIN = (
- "You configure the toolset for an autonomous coding agent that is about to solve ONE "
- "specific GitHub issue by READING, EDITING, and TESTING source code in a single "
- "repository, HEADLESS and SINGLE-SHOT (no human, one sealed container, no sub-agents / "
- "scheduling / external memory). Every LOADED tool's JSON schema is re-sent on EVERY turn "
- "and costs tokens. Below are the ISSUE text and the currently-available tools. For THIS "
- "specific issue, mark each tool:\n"
- " LOAD = plausibly useful to read/navigate/edit/run/test code to solve THIS issue\n"
- " DROP = this specific issue will not need it\n"
- "Be conservative: DROP only when you are confident the tool is irrelevant to THIS issue. "
- "Do NOT assume a tool is needed merely because it exists. Return ONLY a JSON object "
- "{tool_name: {\"load\": true|false, \"reason\": \"<short>\"}}.\n"
-)
-
-
-def judge_tools_for_task(problem_statement, catalog, runner, model="agent",
- domain=None, max_issue_chars=4000):
- """Per-task, INSTRUCTION-AWARE tool judge (v4.4). Reads the (redacted) issue text plus
- the candidate tool catalog ({name: desc}) and returns ({tool: load_bool}, tokens): which
- tools to LOAD for THIS task. Complements the trace-based rule — the caller unions the
- DROP set with the evidence exclusions (and never drops PROTECTED or ever-used tools).
-
- Leakage-safe: the caller MUST pass the SAME redacted problem statement the agent receives
- (run_agent._redact_gold_pointers), never the gold patch or tests. On any failure returns
- ({}, tokens) so the caller keeps everything loaded (safe). `tokens` is the cache-aware
- EFFECTIVE cost of this one-shot call (fresh input x1 + output x5 when approximated), on
- the same basis as exec, so judge overhead folds into the honest amortized task cost."""
- if runner is None or not catalog or not problem_statement:
- return {}, 0
- brief = domain or TOOL_JUDGE_DOMAIN
- prompt = (brief + "\nISSUE:\n" + problem_statement[:max_issue_chars]
- + "\n\nTOOLS:\n" + "\n".join(f"- {n}: {d}" for n, d in catalog.items())
- + "\n\nReturn the JSON classification:")
- try:
- raw, real = runner(prompt, model)
- except Exception:
- return {}, 0
- raw = raw or ""
- tokens = real if real is not None else (_approx_tokens(prompt) + 5 * _approx_tokens(raw))
- out = {}
- m = re.search(r"\{.*\}", raw, re.S)
- if m:
- try:
- obj = json.loads(m.group(0))
- for t, v in obj.items():
- load = v.get("load") if isinstance(v, dict) else v
- out[t] = bool(load)
- except Exception:
- return {}, tokens
- # safety: never DROP a protected work tool, whatever the judge said.
- for t in PROTECTED_TOOLS:
- if t in out:
- out[t] = True
- return out, tokens
-
-
-def learned_exclusions(classification, used_tools=None, unused_streaks=None,
- unsure_demote_after=4):
- """Turn a v4.2 classification into the exclusion list for the NEXT task.
-
- EXCLUDE-classified tools are excluded (unless protected or since-observed-in-use).
- UNSURE tools stay LOADED until they have gone `unused_streaks[tool]` >=
- `unsure_demote_after` consecutive tasks without use, then they are excluded too
- (evidence-based demotion — safe because they were loaded and observed). KEEP never
- excluded. Falls back to [] when there is no classification yet (caller then loads the
- full catalog for that task = a re-audit/warm-up turn)."""
- if not classification:
- return []
- used = set(used_tools or ())
- streaks = unused_streaks or {}
- excl = []
- for t, v in classification.items():
- if t in PROTECTED_TOOLS or t in used:
- continue
- cls = v.get("class")
- if cls == "EXCLUDE":
- excl.append(t)
- elif cls == "UNSURE" and streaks.get(t, 0) >= unsure_demote_after:
- excl.append(t)
- return excl
-
-
-def detect(trajectory_path):
- """STAGE A — free. Compute inefficiency signals from a saved trajectory, plus
- TASK-AGNOSTIC evidence the optimizer can turn into durable notes. Two families:
-
- ENV-DISCOVERY re-probing for the interpreter / conda env (empty bash probes).
- NAVIGATION re-finding code: repeated search queries (grep/glob) and files
- read multiple times — i.e. the agent re-locating the same things.
-
- Evidence is restricted to *where things are* signals (search queries, file
- paths) — never the contents of a fix — so it cannot encode a task's solution.
- Notes derived from it are location/architecture facts, validated leakage-safe by
- the optimizer's task-agnostic constraint and future-only credit."""
- calls = load_trajectory(trajectory_path)
- bash = [c for c in calls if c[0] in ("bash", "shell")]
- cmds = [(_norm_cmd(a.get("command", "")), res, ok) for _, a, res, ok in bash]
-
- def is_empty(res):
- return re.sub(r"<shellId.*", "", res or "").strip() in ("", "(empty)")
-
- # --- env-discovery family ---
- probe_cmds = [c for c, _, _ in cmds if ENV_PROBE_RE.search(c)]
- empty_probe_cmds = [c for c, r, _ in cmds if is_empty(r) and ENV_PROBE_RE.search(c)]
- failed = sum(1 for _, _, ok in cmds if ok is False)
- seen = {}
- for c, _, _ in cmds:
- seen[c] = seen.get(c, 0) + 1
- repeats = sum(v - 1 for v in seen.values() if v > 1)
- env_evidence = []
- for c in (empty_probe_cmds or probe_cmds):
- if c not in env_evidence:
- env_evidence.append(c)
- if len(env_evidence) >= 5:
- break
-
- # --- navigation family (structured tools + grep-in-bash) ---
- searches, reads = [], []
- for name, args, _, _ in calls:
- if name in ("grep",):
- q = (args.get("pattern") or "").strip()
- if q:
- searches.append(q.lower())
- elif name in ("glob",):
- q = (args.get("pattern") or "").strip()
- if q:
- searches.append(q.lower())
- elif name in ("view",) or "read_file" in (name or ""):
- # built-in view OR the read_file MCP tool (navcache/shadowread arms rename
- # reads to read_file; count them so nav signals + anchoring still work)
- p = args.get("path") or ""
- if p:
- reads.append(p)
- # grep run through bash, too
- for c, _, _ in cmds:
- m = re.search(r"\b(?:grep|rg)\b[^|]*?['\"]([^'\"]{2,40})['\"]", c)
- if m:
- searches.append(m.group(1).lower())
-
- def _dups(seq):
- s = {}
- for x in seq:
- s[x] = s.get(x, 0) + 1
- return s
-
- sdup, rdup = _dups(searches), _dups(reads)
- repeated_searches = sum(v - 1 for v in sdup.values() if v > 1)
- redundant_reads = sum(v - 1 for v in rdup.values() if v > 1)
- # evidence: the repeated queries / files (what the agent kept re-locating)
- nav_evidence = ([f"searched repeatedly: {q!r}" for q, n in sdup.items() if n > 1][:4]
- + [f"re-read file: {_basename(p)}" for p, n in rdup.items() if n > 1][:4])
-
- # --- tooling-discovery family (generic, type-agnostic friction) ---
- # (a) superseded test-runner form: the agent used >1 distinct test-runner form
- # in one task -> it discovered the right one the hard way. Ordered, so we can
- # report "tried X then settled on Y".
- test_forms_seq = []
- for c, _, _ in cmds:
- for form, rx in TEST_FORM_RES.items():
- if rx.search(c):
- if not test_forms_seq or test_forms_seq[-1] != form:
- test_forms_seq.append(form)
- break
- distinct_forms = list(dict.fromkeys(test_forms_seq))
- superseded_tools = max(0, len(distinct_forms) - 1)
- tooling_evidence = []
- if superseded_tools:
- tooling_evidence.append(
- "tried test runners in order " + " -> ".join(test_forms_seq)
- + f"; '{distinct_forms[-1]}' is the form that stuck")
-
- # (b) infrastructure errors in command output (masked by pipes; success=True)
- error_cmds = [(c, r) for c, r, _ in cmds if ERROR_MARKER_RE.search(r or "")]
- error_outputs = len(error_cmds)
- for c, r in error_cmds[:3]:
- m = ERROR_MARKER_RE.search(r or "")
- snippet = (m.group(0) if m else "")[:60]
- tooling_evidence.append(f"command errored ({snippet}): {c[:70]}")
-
- # (c) external fetches: web/github tools or bash curl/wget to a URL. Recorded for
- # filtering (integrity) and as possible discovery waste; NOT used to trigger
- # the optimizer (no leakage-safe note can come from "it searched the web").
- external_fetches = 0
- external_fetch_successes = 0
- for name, args, result, success in calls:
- if name in ("web_fetch", "web_search") or (name or "").startswith("github"):
- external_fetches += 1
- external_fetch_successes += int(
- success is not False and not BLOCKED_FETCH_RE.search(result or ""))
- for c, result, success in cmds:
- # curl/wget to any URL, OR any reference to a GitHub gold-source host via any
- # client (python urllib/requests, etc.) — the latter is the backstop that
- # catches non-curl exfiltration the URL regex would miss.
- if EXTERNAL_URL_RE.search(c) or GOLD_HOST_RE.search(c):
- external_fetches += 1
- external_fetch_successes += int(
- success is not False and not BLOCKED_FETCH_RE.search(result or ""))
-
- # --- execution-iteration family (targets the edit->test->fail loop that drives
- # the costly multi-turn spirals; cost is ~linear in turns, and these patterns
- # are turns the agent could have avoided). Evidence is COUNTS ONLY — no
- # filenames, commands, or test labels — so it stays strictly leakage-safe
- # (a process-discipline note, never a hint at the fix location). ---
- exec_evidence = []
- # (d) re-running an UNCHANGED test/repro command (the suite is deterministic, so
- # a repeat of the exact same command yields the exact same result = wasted turn)
- test_cmd_counts = {}
- for c, _, _ in cmds:
- if TEST_RUN_RE.search(c):
- test_cmd_counts[c] = test_cmd_counts.get(c, 0) + 1
- repeated_test_runs = sum(v - 1 for v in test_cmd_counts.values() if v > 1)
- if repeated_test_runs:
- exec_evidence.append(
- f"re-ran an identical test/repro command {repeated_test_runs} extra "
- "time(s) (the suite is deterministic — one run gives the same result)")
- # (e) edit churn: many edits to a SINGLE file, with re-reads interleaved — the
- # trial-and-error edit storm. Count per file basename (count only, no names).
- edit_seq = [] # ordered basenames of edit targets
- file_edits = {}
- for name, args, _, _ in calls:
- if name in ("edit", "str_replace", "create", "apply_patch"):
- paths = args.get("paths") or [
- args.get("path") or args.get("filePath") or ""]
- for path in paths:
- p = _basename(path)
- if p:
- edit_seq.append(p)
- file_edits[p] = file_edits.get(p, 0) + 1
- edit_churn = max(file_edits.values()) if file_edits else 0
- if edit_churn >= 3:
- exec_evidence.append(
- f"made {edit_churn} edits to a single file (trial-and-error iteration); "
- "forming a hypothesis from one focused read before editing, and "
- "verifying with the cheapest reproduction, avoids edit-test churn")
-
- return {
- "n_bash": len(bash),
- "n_tool_calls": len(calls),
- "env_probes": len(probe_cmds),
- "empty_outputs": sum(1 for _, r, _ in cmds if is_empty(r)),
- "failed_cmds": failed,
- "repeated_cmds": repeats,
- "n_searches": len(searches),
- "repeated_searches": repeated_searches,
- "redundant_reads": redundant_reads,
- "superseded_tools": superseded_tools,
- "error_outputs": error_outputs,
- "external_fetches": external_fetches,
- "external_fetch_successes": external_fetch_successes,
- "repeated_test_runs": repeated_test_runs,
- "edit_churn": edit_churn,
- "evidence_env_cmds": env_evidence,
- "evidence_nav": nav_evidence,
- "evidence_tooling": tooling_evidence,
- "evidence_exec": exec_evidence,
- }
-
-
-# ---- the gate ----------------------------------------------------------------
-DEFAULT_THRESHOLDS = {
- # "obvious in this task": any single signal at/above these fires
- "env_probes": 5,
- "empty_outputs": 6,
- "repeated_cmds": 3,
- "repeated_searches": 3,
- "redundant_reads": 5,
- "superseded_tools": 1, # one wrong-then-right tool switch is a clean discovery
- "error_outputs": 2, # repeated infra errors -> a durable "how to" note
- "repeated_test_runs": 1, # re-running an unchanged test/repro = a wasted turn
- "edit_churn": 5, # >=5 edits to one file = a trial-and-error edit storm
- # "recurring across window": a signal averaging >= this over the last W tasks
- "window": 3,
- "recurring_env_probes_avg": 2.0,
- "recurring_empty_avg": 3.0,
- "recurring_repeated_searches_avg": 2.0,
- "recurring_superseded_avg": 0.5,
- "recurring_edit_churn_avg": 3.0,
-}
-
-
-def trigger(signals, recent_signals, thr=None):
- """GATE — decide whether to invoke the paid optimizer. Returns (bool, reason).
- Fires on an obvious single-task spike (env-discovery / navigation / tooling-
- discovery / execution-iteration) OR a pattern recurring across the window;
- otherwise no-op (interface unchanged). external_fetches is deliberately NOT a
- trigger (no leakage-safe note can be distilled from web/github access)."""
- thr = thr or DEFAULT_THRESHOLDS
- # (1) obvious single-task inefficiency.
- # NB (v1.4): edit_churn and redundant_reads are deliberately NOT triggers. They
- # measure trial-and-error iteration / re-reading, which is solve-loop work bound to
- # task difficulty, not interface friction. Firing on them produced generic process-
- # habit notes ("read the function first", "batch reads") that added upfront reading
- # WITHOUT shrinking the edit->test loop, inflating cost on matplotlib. They are still
- # computed in detect() and logged as diagnostics, just not acted upon.
- for k in ("superseded_tools", "error_outputs",
- "repeated_test_runs",
- "env_probes", "empty_outputs", "repeated_cmds", "repeated_searches"):
- if signals.get(k, 0) >= thr[k]:
- return True, f"obvious:{k}={signals[k]}>={thr[k]}"
- if METHOD == "v1.3":
- # v1.3 also triggers on edit_churn / redundant_reads (P1, removed in v1.4).
- for k in ("edit_churn", "redundant_reads"):
- if signals.get(k, 0) >= thr[k]:
- return True, f"obvious:{k}={signals[k]}>={thr[k]}"
- # (2) recurring across the window (more general, less leakage-prone)
- win = recent_signals[-thr["window"]:]
- if len(win) >= thr["window"]:
- for sig_key, thr_key in (("env_probes", "recurring_env_probes_avg"),
- ("empty_outputs", "recurring_empty_avg"),
- ("repeated_searches", "recurring_repeated_searches_avg"),
- ("superseded_tools", "recurring_superseded_avg")):
- avg = sum(s.get(sig_key, 0) for s in win) / len(win)
- if avg >= thr[thr_key]:
- return True, f"recurring:{sig_key}_avg={avg:.1f}"
- return False, "below-threshold"
-
-
-# ---- coverage suppression ----------------------------------------------------
-# Signals where a SINGLE durable note addresses ALL future occurrences (e.g. "use
-# runtests.py, not pytest" covers every later pytest detour; an env-setup note covers
-# every later env re-probe). Once the manifest covers such a signal, re-firing the paid
-# optimizer on it just re-derives a duplicate and returns empty — pure waste.
-# error_outputs stays uncovered (each infra error can need a genuinely different
-# 'use X to do Y' fix). NB (v1.4): edit_churn / redundant_reads are no longer triggers
-# (see trigger()), so they are not listed here.
-GLOBALLY_COVERABLE = {"superseded_tools", "env_probes",
- "repeated_test_runs", "repeated_searches"}
-
-
-def primary_signal(reason):
- """Extract the signal key from a trigger() reason string, e.g.
- 'obvious:superseded_tools=1>=1' or 'recurring:env_probes_avg=2.0' -> the key."""
- if not reason or ":" not in reason:
- return None
- body = reason.split(":", 1)[1]
- key = re.split(r"[=]", body, 1)[0]
- key = re.sub(r"_avg$", "", key)
- return key
-
-
-def is_covered(reason, state):
- """True if the gate fired on a GLOBALLY_COVERABLE signal that the manifest already
- covers — so the paid optimizer would only re-derive a duplicate. Suppress it."""
- k = primary_signal(reason)
- return k in GLOBALLY_COVERABLE and k in set(state.get("covered_signals", []))
-
-
-def mark_covered(reason, state):
- """Record that a GLOBALLY_COVERABLE signal is now addressed by the manifest. Call
- only after the optimizer actually ADDED a note in response to this firing."""
- k = primary_signal(reason)
- if k in GLOBALLY_COVERABLE:
- cov = state.setdefault("covered_signals", [])
- if k not in cov:
- cov.append(k)
-
-
-# ---- the paid optimizer ------------------------------------------------------
-# METHOD selects the optimizer generation (set via AGENTEO_METHOD env, default v1.4):
-# v1.4 (default): bans process-habit notes (P2) and does NOT trigger on edit_churn/
-# redundant_reads (P1) — the committed milestone.
-# v1.3 : the prior hardened global manifest — ALLOWS process-discipline
-# notes (category d) and triggers on edit_churn/redundant_reads.
-# (v1.2 location notes are not exposed here; both v1.3/v1.4 forbid location facts.)
-METHOD = os.environ.get("AGENTEO_METHOD", "v1.4")
-
-OPTIMIZER_SYSTEM = (
- "You maintain a SHORT list of durable, GENERAL operating notes for working "
- "efficiently in a software repository. You are shown signals of wasted effort "
- "from a recent task trajectory and the current notes. Propose at most {k} NEW "
- "notes that would help FUTURE tasks avoid the same waste.\n\n"
- "GOAL: capture concrete, checkable facts about THIS repo's tooling and "
- "environment so future tasks use the right command/form the first time. NEVER "
- "reduce the number of attempts the agent is willing to make to reach a correct, "
- "test-passing solution, and NEVER tell it to stop early.\n\n"
- "STRICT RULES:\n"
- "- ALLOWED note categories ONLY: (a) the correct command/tool to "
- "build/test/run/lint here, and which forms DON'T work; (b) environment/config "
- "facts and gotchas (interpreter, import-path conventions, how to reproduce); "
- "(c) infrastructure-error fixes (the durable 'use X to do Y' fact behind a "
- "recurring traceback). EVERY note must name a concrete command, flag, path, "
- "tool, or environment fact that an unrelated future task could act on verbatim.\n"
- "- FORBIDDEN: (1) Do NOT write notes about WHERE specific components, symbols, "
- "subsystems, classes, or tests LIVE (no 'X lives in file Y', no per-file or "
- "per-symbol location facts) — these are task-specific, leak localization, and "
- "mislead unrelated tasks. (2) Do NOT write any note that caps iteration, "
- "discourages re-running tests, tells the agent to 'trust' a result, 'make one "
- "consolidated change', stop early, or otherwise reduce its willingness to keep "
- "iterating until the tests actually pass. (3) NEVER describe or hint at the "
- "solution to any specific task, which file to change, or which lines. (4) Do NOT "
- "write generic process/workflow-discipline advice (e.g. 'read the full function "
- "before editing', 'batch related reads in one pass', 'trace callers/data flow "
- "first', 'form a hypothesis before editing', 'reproduce with the cheapest check', "
- "'reuse earlier search results instead of re-searching') — these are not repo-"
- "specific, have no checkable command/path footprint, and slow the edit->test "
- "solve loop without preventing real interface friction.\n"
- "- Each note one line, concise, durable across code changes, and applicable to "
- "ANY task in this repo (not just tasks touching one file).\n"
- "- If nothing general, durable, and repo-wide can be added, return an empty list.\n"
- "Return ONLY a JSON list of strings."
-)
-
-# v1.3 optimizer: the pre-v1.4 prompt — ALLOWS process-discipline notes (category d)
-# and omits FORBIDDEN(4). Location facts (FORBIDDEN 1) and effort-capping (FORBIDDEN 2)
-# stay banned (those distinguish v1.3 from the discarded v1.2).
-OPTIMIZER_SYSTEM_V13 = (
- "You maintain a SHORT list of durable, GENERAL operating notes for working "
- "efficiently in a software repository. You are shown signals of wasted effort "
- "from a recent task trajectory and the current notes. Propose at most {k} NEW "
- "notes that would help FUTURE tasks avoid the same waste.\n\n"
- "GOAL: make each step the agent takes cheaper / more informed. NEVER reduce the "
- "number of attempts the agent is willing to make to reach a correct, test-passing "
- "solution.\n\n"
- "STRICT RULES:\n"
- "- ALLOWED note categories ONLY: (a) the correct command/tool to build/test/run/"
- "lint here, and which forms DON'T work; (b) environment/config facts and gotchas; "
- "(c) infrastructure-error fixes (the durable 'use X to do Y' fact behind a "
- "recurring traceback); (d) step-cheapening workflow habits that do NOT cap effort "
- "(e.g. read a section once before editing it, batch related reads in one pass, "
- "confirm an import path before running a probe).\n"
- "- FORBIDDEN: (1) Do NOT write notes about WHERE specific components, symbols, "
- "subsystems, classes, or tests LIVE (no per-file/per-symbol location facts). "
- "(2) Do NOT write any note that caps iteration, discourages re-running tests, "
- "tells the agent to 'trust' a result, stop early, or otherwise reduce its "
- "willingness to keep iterating. (3) NEVER hint at the solution to any task.\n"
- "- Each note one line, concise, durable, applicable to ANY task in this repo.\n"
- "- If nothing general and durable can be added, return an empty list.\n"
- "Return ONLY a JSON list of strings."
-)
-
-
-def _optimizer_system():
- return OPTIMIZER_SYSTEM_V13 if METHOD == "v1.3" else OPTIMIZER_SYSTEM
-
-
-def build_optimizer_prompt(signals, state, k=3):
- cur = [n["text"] for n in state["notes"] if not n.get("pruned")]
- env_ev = signals.get("evidence_env_cmds", [])
- tool_ev = signals.get("evidence_tooling", [])
- counts = {k2: v for k2, v in signals.items()
- if not k2.startswith("evidence_")}
- # v1.4: only the Class-A evidence blocks (tooling-discovery and wasted env-
- # discovery commands) are surfaced. The execution-iteration (edit-churn) and
- # repeated-navigation blocks were removed — they solicited generic process-habit
- # notes ("read the section once", "batch reads") that inflated the solve loop
- # without preventing real interface friction.
- blocks = ""
- if tool_ev:
- blocks += ("\n\nTooling-discovery waste (the agent used the wrong command/tool "
- "form first, then corrected, or hit an infrastructure error — infer "
- "the durable 'use <tool/command> to do <task>' fact, NOT any fix):\n"
- + "\n".join(f" - {c}" for c in tool_ev))
- if env_ev:
- blocks += ("\n\nWasted environment-discovery commands (returned nothing — "
- "infer the durable env fact that makes them unnecessary):\n"
- + "\n".join(f" $ {c}" for c in env_ev))
- if METHOD == "v1.3":
- # v1.3 also surfaces execution-iteration + repeated-navigation evidence, which
- # solicit the process-discipline notes v1.3 allows (and v1.4 banned).
- exec_ev = signals.get("evidence_exec", [])
- nav_ev = signals.get("evidence_nav", [])
- if exec_ev:
- blocks += ("\n\nExecution-iteration waste (edit churn / re-running):\n"
- + "\n".join(f" - {c}" for c in exec_ev))
- if nav_ev:
- blocks += ("\n\nRepeated-navigation waste (re-searching / re-reading):\n"
- + "\n".join(f" - {c}" for c in nav_ev))
- return (_optimizer_system().format(k=k)
- + "\n\nCurrent notes:\n" + ("\n".join(f"- {c}" for c in cur) or "(none)")
- + "\n\nWaste signal counts from the latest task:\n" + json.dumps(counts)
- + blocks
- + "\n\nReturn the JSON list of new notes:")
-
-
-def optimize(signals, state, model="agent", k=3, runner=None):
- """STAGE B — paid. Ask the configured optimizer model for new durable notes.
- `runner(prompt, model) -> (str, real_tokens)` performs the LLM call (so the model
- is fully configurable and the call is injectable/testable). Returns
- (notes, tokens) where tokens is the call's REAL token usage when the runner can
- recover it, else a char-based approximation. Parses a JSON list of strings;
- tolerant of extra prose around it."""
- prompt = build_optimizer_prompt(signals, state, k=k)
- if runner is None:
- # no runner wired (offline/dry): propose nothing, cost nothing.
- return [], 0
- raw, real = runner(prompt, model)
- raw = raw or ""
- notes = _parse_notes(raw)
- tokens = real if real is not None else _approx_tokens(prompt) + _approx_tokens(raw)
- return notes[:k], tokens
-
-
-def _parse_notes(raw):
- m = re.search(r"\[.*\]", raw, re.S)
- if not m:
- return []
- try:
- arr = json.loads(m.group(0))
- return [str(x).strip() for x in arr if str(x).strip()]
- except Exception:
- return []
-
-
-# ---- v2.1 anchored-knowledge optimizer ---------------------------------------
-# A SEPARATE, parallel optimizer that produces FILE-ANCHORED structural facts about
-# the files the agent navigated heavily this task. Kept separate from the global
-# optimize() so the global tier is byte-identical to the v1.3 hardened optimizer
-# (clean A/B: v2.1 = v1.3 global manifest + anchored). These facts are the location/
-# structure knowledge the v1.3 global optimizer had to BAN from the global manifest —
-# safe here because they are surfaced ONLY when the agent
-# opens that file (no global pollution, no pre-leak of localization).
-ANCHORED_OPTIMIZER_SYSTEM = (
- "You record durable, FILE-SPECIFIC structural knowledge about a code repository, "
- "to help FUTURE tasks that edit the SAME files work with less re-exploration. You "
- "are shown files the agent navigated/re-read heavily in a recent task. For each "
- "file worth a note, state ONE concise, durable fact about THAT FILE that a future "
- "editor of it would want to know up front: what it contains, key classes/base "
- "classes and their contract, conventions, extension points, or gotchas.\n\n"
- "STRICT RULES:\n"
- "- The fact must be about the FILE'S STABLE STRUCTURE, true regardless of any "
- "specific task — NOT the solution to the current task, NOT which lines to change, "
- "NOT a fix. If the only thing you can say about a file is task-specific, skip it.\n"
- "- One short line per file. Durable across code changes when possible.\n"
- "- Only include files where a genuine, reusable structural fact exists.\n"
- "Return ONLY a JSON list of objects: [{\"path\": \"<repo-relative path>\", "
- "\"text\": \"<one-line structural fact>\"}].")
-
-
-def _heavy_files(trajectory_path, min_reads=2, top=4):
- """Repo-relative paths the agent read >= min_reads times (navigation hotspots),
- most-read first. These are where anchored knowledge has the most future payoff."""
- counts = {}
- for name, args, _, _ in load_trajectory(trajectory_path):
- a = args if isinstance(args, dict) else {}
- if name == "view" or "read_file" in (name or ""):
- p = (a.get("path") or "").strip()
- if p:
- counts[p] = counts.get(p, 0) + 1
- heavy = sorted((p for p, c in counts.items() if c >= min_reads),
- key=lambda p: -counts[p])[:top]
- return heavy
-
-
-def optimize_anchored(trajectory_path, state, model="agent", k=4, runner=None):
- """STAGE B (anchored) — paid, parallel to optimize(). Ask the model for durable
- file-structural facts about the navigation-hotspot files. Returns (items, tokens)
- where items = [{path, text, tag}]. No-op (0 cost) when no heavy files or no runner."""
- if runner is None:
- return [], 0
- heavy = _heavy_files(trajectory_path)
- if not heavy:
- return [], 0
- existing = {p: [n["text"] for n in b] for p, b in (state.get("anchored") or {}).items()}
- prompt = (ANCHORED_OPTIMIZER_SYSTEM
- + "\n\nFiles the agent navigated/re-read heavily this task:\n"
- + "\n".join(f"- {p}" for p in heavy)
- + "\n\nExisting anchored facts (do not duplicate):\n"
- + (json.dumps(existing) if existing else "(none)")
- + "\n\nReturn the JSON list of {path, text}:")
- raw, real = runner(prompt, model)
- items = _parse_anchored(raw or "")
- # keep only facts whose path is one we actually navigated (no hallucinated paths)
- heavy_set = set(heavy)
- items = [{"path": it["path"], "text": it["text"], "tag": "uncertain"}
- for it in items if it.get("path") in heavy_set and it.get("text")][:k]
- tokens = real if real is not None else _approx_tokens(prompt) + _approx_tokens(raw)
- return items, tokens
-
-
-def _parse_anchored(raw):
- m = re.search(r"\[.*\]", raw, re.S)
- if not m:
- return []
- try:
- arr = json.loads(m.group(0))
- out = []
- for x in arr:
- if isinstance(x, dict) and x.get("path") and x.get("text"):
- out.append({"path": str(x["path"]).strip(),
- "text": str(x["text"]).strip()})
- return out
- except Exception:
- return []
-
-
-def _approx_tokens(text):
- return max(1, len(text) // 4)
-
-
-def _runner_effective_or_approx(runner, prompt, raw, real):
- """Use recovered usage, then a runner's model-priced estimate, then legacy ×5."""
- if real is not None:
- return real
- estimator = getattr(runner, "estimate_effective", None)
- if callable(estimator):
- try:
- return estimator(prompt, raw)
- except Exception:
- pass
- return _approx_tokens(prompt) + 5 * _approx_tokens(raw)
-
-
-# ---- v2.2 subsystem fix-map optimizer ----------------------------------------
-# v2.1's anchored tier failed on realistic streams: it anchored at FILE granularity
-# (cross-task file-revisit ~12-33%) and learned from within-task re-reads, so its
-# delivery surface was near-zero. v2.2 fixes BOTH: it captures from the RESOLVED
-# patch's EDITED files (the proven solve sites), anchors at SUBSYSTEM (dir) level —
-# where revisit is 79% on xarray — and records only SYMBOL-level structure (no line
-# numbers, no defect), so it survives the median ~69-line churn between visits
-# (measured symbol-survival = 100% median). Delivery is verify-on-inject (the reader
-# drops any mapped symbol that no longer exists), so drift can't mislead.
-FIXMAP_OPTIMIZER_SYSTEM = (
- "You record a durable SUBSYSTEM MAP for a code repository, to help FUTURE tasks "
- "that edit the SAME directory navigate to the fix site faster. You are shown the "
- "directory of a just-RESOLVED task and the functions/classes that were edited. For "
- "each, state ONE concise, durable line: the symbol name and its responsibility, "
- "and the test file that validates it.\n\n"
- "STRICT RULES:\n"
- "- Anchor on the SYMBOL (function/class name) and its STABLE ROLE — NEVER line "
- "numbers, NEVER the specific bug or fix, NEVER what to change. A future reader "
- "must not be able to reconstruct this task's solution from your map.\n"
- "- One short line per symbol: `symbol — role (validated by tests/<file>)`.\n"
- "- Skip anything that is only true for this one defect.\n"
- "Return ONLY a JSON list of {\"path\": \"<dir>\", \"text\": \"<line>\"}.")
-
-
-def _edited_symbols(patch_path):
- """From a unified diff, map each edited .py file to the def/class symbols whose
- bodies were touched. Returns {dir: set(symbols)}; line numbers are NOT retained."""
- dirs = {}
- cur, hunk_syms = None, set()
- if not os.path.isfile(patch_path):
- return dirs
- sym_re = re.compile(r"(?:def|class)\s+(\w+)")
- for ln in open(patch_path, errors="replace"):
- if ln.startswith("+++ b/"):
- cur = ln[6:].strip()
- elif ln.startswith("@@") and cur and cur.endswith(".py") and "test" not in cur:
- m = sym_re.search(ln) # hunk header often carries the enclosing def/class
- if m:
- dirs.setdefault(os.path.dirname(cur), set()).add(m.group(1))
- elif (ln.startswith("+") or ln.startswith("-")) and cur and cur.endswith(".py") \
- and "test" not in cur:
- m = sym_re.search(ln)
- if m:
- dirs.setdefault(os.path.dirname(cur), set()).add(m.group(1))
- return dirs
-
-
-def optimize_fixmap(patch_path, state, model="agent", k=4, runner=None):
- """v2.2 — paid, fires only on RESOLVED tasks. Build symbol-level subsystem facts
- from the edited dirs. Returns (items, tokens); items=[{path=dir, text, tag}]."""
- if runner is None:
- return [], 0
- dirs = _edited_symbols(patch_path)
- if not dirs:
- return [], 0
- existing = {d: [n["text"] for n in b] for d, b in (state.get("anchored") or {}).items()}
- desc = "\n".join(f"- {d}: {', '.join(sorted(s))}" for d, s in dirs.items() if s)
- if not desc.strip():
- return [], 0
- prompt = (FIXMAP_OPTIMIZER_SYSTEM
- + "\n\nResolved task edited these subsystems (dir: symbols):\n" + desc
- + "\n\nExisting subsystem maps (do not duplicate):\n"
- + (json.dumps(existing) if existing else "(none)")
- + "\n\nReturn the JSON list of {path, text}:")
- raw, real = runner(prompt, model)
- items = _parse_anchored(raw or "")
- valid_dirs = set(dirs)
- items = [{"path": it["path"], "text": it["text"], "tag": "uncertain"}
- for it in items if it.get("path") in valid_dirs and it.get("text")][:k]
- tokens = real if real is not None else _approx_tokens(prompt) + _approx_tokens(raw)
- return items, tokens
-
-
-# ---- optional LLM-detector tier ----------------------------------------------
-# Answers the design question "must the detector use a fixed vocabulary?". The free
-# heuristic detect()/trigger() runs every task (cheap, and it also flags integrity /
-# external-fetch regardless). This tier is an LLM that reads a LEAKAGE-SAFE PROCESS
-# digest of one trajectory and decides, open-endedly, whether there is a recurring,
-# task-agnostic inefficiency worth a durable note — without being told the signal
-# types in advance. Because an LLM call per task would reintroduce the very overhead
-# the gate exists to remove, it is meant to be SAMPLED (every Nth task, or only when
-# the free detector is ambiguous), never run unconditionally.
-
-def trajectory_summary(trajectory_path, max_cmds=25):
- """A compact, LEAKAGE-SAFE digest of an agent's PROCESS (not its solution): the
- bash commands it ran, what it searched for, which files it opened (basenames),
- and infrastructure-error snippets — deliberately EXCLUDING the patch/diff, edit
- contents, view contents, and the issue text, so it cannot encode the fix."""
- calls = load_trajectory(trajectory_path)
- lines, n_view, n_edit = [], 0, 0
- for name, args, res, ok in calls:
- if name == "bash":
- c = _norm_cmd(args.get("command", ""))
- err = ERROR_MARKER_RE.search(res or "")
- tag = f" [err: {err.group(0)[:40]}]" if err else ""
- if c:
- lines.append(f"$ {c[:120]}{tag}")
- elif name in ("grep", "glob"):
- q = (args.get("pattern") or "").strip()
- if q:
- lines.append(f"search {name}: {q[:60]}")
- elif name == "view":
- n_view += 1
- p = _basename(args.get("path") or "")
- if p:
- lines.append(f"view {p}")
- elif name in ("edit", "str_replace", "create"):
- n_edit += 1
- elif name in ("web_fetch", "web_search") or (name or "").startswith("github"):
- lines.append(f"EXTERNAL {name}")
- # cap to keep the digest cheap and process-focused
- if len(lines) > max_cmds:
- lines = lines[:max_cmds] + [f"... (+{len(lines)-max_cmds} more actions)"]
- head = f"({len(calls)} tool calls; {n_view} views, {n_edit} edits)"
- return head + "\n" + "\n".join(lines)
-
-
-LLM_DETECTOR_SYSTEM = (
- "You audit an AI coding agent's PROCESS trace for one task in a repository it "
- "will face MORE tasks in. Decide whether the trace shows a RECURRING, "
- "TASK-AGNOSTIC inefficiency that a short durable repo note would prevent next "
- "time — e.g. discovering the right build/test/run command the hard way, "
- "re-finding where code lives, or re-probing the environment.\n\n"
- "Do NOT infer or describe the task's solution or which lines to change. Judge "
- "only the agent's workflow efficiency.\n"
- "Return ONLY a JSON object: {\"worth_optimizing\": bool, \"kind\": \"<short "
- "label e.g. tooling-discovery|navigation|env|none>\", \"evidence\": [\"<short "
- "leakage-safe observations the optimizer can turn into a durable note>\"]}. "
- "If the workflow was already efficient, return worth_optimizing=false, kind="
- "\"none\", evidence=[]."
-)
-
-
-def llm_detect(trajectory_path, runner, model="agent"):
- """SAMPLED LLM detector. Returns (verdict_dict, tokens). verdict_dict has keys
- worth_optimizing(bool), kind(str), evidence(list[str]). On any failure returns a
- safe negative verdict. The evidence can be fed straight into the optimizer via
- signals['evidence_tooling']."""
- if runner is None:
- return {"worth_optimizing": False, "kind": "none", "evidence": []}, 0
- summary = trajectory_summary(trajectory_path)
- prompt = (LLM_DETECTOR_SYSTEM + "\n\nProcess trace:\n" + summary
- + "\n\nReturn the JSON verdict:")
- raw, real = runner(prompt, model)
- raw = raw or ""
- tokens = real if real is not None else _approx_tokens(prompt) + _approx_tokens(raw)
- verdict = {"worth_optimizing": False, "kind": "none", "evidence": []}
- m = re.search(r"\{.*\}", raw, re.S)
- if m:
- try:
- obj = json.loads(m.group(0))
- verdict["worth_optimizing"] = bool(obj.get("worth_optimizing"))
- verdict["kind"] = str(obj.get("kind", "none"))[:40]
- ev = obj.get("evidence", [])
- verdict["evidence"] = [str(x)[:160] for x in ev][:5] if isinstance(ev, list) else []
- except Exception:
- pass
- return verdict, tokens
-
-
-# ---- v4.1 spiral trace-judge (live abort decision; same LLM-detector machinery) ----
-# The Phase-1.5 abort decision was step-count-gated (resolved-turn envelope). This is the
-# TRACE-CONTENT tier: an LLM reads a leakage-safe digest of the agent's RECENT actions
-# (built by spiral.SpiralState.recent_digest — commands / searches / edited basenames /
-# error SIGNATURES only, never fix content) and judges whether the trajectory is an
-# unrecoverable loop or still making progress. It is the same sampled-LLM pattern as
-# llm_detect (leakage-safe process digest -> open-ended verdict), here wired to the live
-# spiral guard rather than the between-task optimizer. Meant to be called RARELY — only
-# when the free heuristic (spiral.is_stuck) already flagged a candidate stuck state.
-STUCK_JUDGE_SYSTEM = (
- "You monitor an AI coding agent that is partway through ONE task in a software repo. "
- "A cheap heuristic flagged its recent process as a possible UNPRODUCTIVE LOOP. Read "
- "the leakage-safe digest of its RECENT actions and judge whether it is genuinely "
- "STUCK — repeating the same kind of edit/test/failure with no progress toward green "
- "tests, unlikely to recover if it keeps going the same way — versus still making "
- "real progress (changing failures, narrowing the problem, exploring new hypotheses).\n\n"
- "Judge ONLY the workflow from the digest; do NOT infer the task's solution or which "
- "lines to change. Favor SPARING (stuck=false) when there is any sign of progress; "
- "only return stuck=true with high confidence for a clear, repetitive dead-end.\n"
- "Return ONLY a JSON object: {\"stuck\": bool, \"confidence\": <0.0-1.0>, "
- "\"reason\": \"<short leakage-safe justification>\"}."
-)
-
-
-def llm_stuck_judge(digest, runner, model="agent"):
- """SAMPLED LLM trace-judge for the live spiral guard. `digest` is a leakage-safe
- recent-process string (spiral.SpiralState.recent_digest()). Returns a verdict dict
- {stuck: bool|None, confidence: float, reason: str, _tokens: number}; stuck=None on any
- failure (the caller treats None/ambiguous by falling back to the envelope gate).
- `_tokens` is the REAL token cost of this paid judge call (input+output+cache, from the
- runner's usage block; a char-based approximation if the runner couldn't recover it) so
- the harness can fold mechanism-internal LLM cost into the amortized task cost. 0 when no
- call was made."""
- if runner is None or not digest:
- return {"stuck": None, "confidence": 0.0, "reason": "no-runner", "_tokens": 0}
- prompt = (STUCK_JUDGE_SYSTEM + "\n\nRecent process digest:\n" + digest
- + "\n\nReturn the JSON verdict:")
- try:
- raw, _real = runner(prompt, model)
- except Exception as e:
- return {"stuck": None, "confidence": 0.0,
- "reason": f"runner-error:{e}"[:60], "_tokens": 0}
- raw = raw or ""
- # EFFECTIVE (cache-aware) cost when the runner recovered usage; else approximate on the
- # SAME basis: an uncached one-shot -> prompt is fresh input (weight 1), reply is output
- # (weight 5). Keeps mechanism cost comparable to exec's cache-aware effective tokens.
- _tokens = _runner_effective_or_approx(runner, prompt, raw, _real)
- verdict = {"stuck": None, "confidence": 0.0, "reason": "", "_tokens": _tokens}
- m = re.search(r"\{.*\}", raw, re.S)
- if m:
- try:
- obj = json.loads(m.group(0))
- verdict["stuck"] = (bool(obj["stuck"]) if "stuck" in obj
- and obj["stuck"] is not None else None)
- verdict["confidence"] = max(0.0, min(1.0, float(obj.get("confidence", 0) or 0)))
- verdict["reason"] = str(obj.get("reason", ""))[:160]
- except Exception:
- pass
- return verdict
-
-
-# ---- v6.1 LLM-targeted rung-1 NUDGE writer -----------------------------------
-# The v4.3 rung-1 nudge (spiral.nudge_text) is leakage-safe but GENERIC: it only
-# splices counts into a fixed template ("N edits across M files, same failure recurred
-# K times -> try something different"). This writer makes the redirect TARGETED: a
-# sampled LLM reads the SAME leakage-safe recent-process digest the stuck-judge sees
-# (spiral.SpiralState.recent_digest — commands / searches / edited basenames / error
-# SIGNATURES only) and names the specific repetitive pattern + a materially different
-# next step. It carries NO external knowledge (no issue text, no fix content, no gold
-# pointer), so it stays inside the effort-capping ban exactly like nudge_text: it may
-# only REDIRECT effort, never stop it. Falls back to the template on any failure.
-NUDGE_WRITER_SYSTEM = (
- "An AI coding agent is stuck in a REPETITIVE, UNPRODUCTIVE loop partway through one "
- "task in a software repo. You are given a leakage-safe digest of its RECENT ACTIONS "
- "only (tool names, shell commands, searched patterns, edited file BASENAMES, and "
- "error SIGNATURES — never file contents or the task description). Write a SHORT "
- "redirect (2-4 sentences) addressed to the agent that: (1) names the specific "
- "repetitive pattern you actually see in the digest (e.g. re-editing the same file, "
- "re-running the same test to the same failure); (2) proposes a MATERIALLY DIFFERENT "
- "next step (a different file/root-cause to consider, re-reading the failing test's "
- "expectation, verifying a new hypothesis before editing again).\n"
- "HARD CONSTRAINTS: Do NOT tell it to stop, give up, or reduce effort — only redirect. "
- "Do NOT infer the task's solution, name specific line numbers to change, or reference "
- "any code/identifier you cannot see in the digest. Output ONLY the redirect as plain "
- "text — no preamble, no JSON, no headings."
-)
-
-
-def llm_nudge_writer(digest, runner, model="agent"):
- """SAMPLED LLM writer for the v6.1 targeted rung-1 nudge. `digest` is the same
- leakage-safe recent-process string fed to llm_stuck_judge
- (spiral.SpiralState.recent_digest()). Returns {"text": str, "_tokens": number}: a
- targeted, leakage-safe redirect and the REAL cache-aware effective token cost of the
- call (folded into amortized task cost by the harness, same basis as the judge). On any
- failure returns {"text": "", "_tokens": 0} so the caller falls back to the generic
- spiral.nudge_text template (resolve-safe zero-LLM path)."""
- if runner is None or not digest:
- return {"text": "", "_tokens": 0}
- prompt = (NUDGE_WRITER_SYSTEM + "\n\nRecent process digest:\n" + digest
- + "\n\nWrite the redirect:")
- try:
- raw, _real = runner(prompt, model)
- except Exception:
- return {"text": "", "_tokens": 0}
- raw = (raw or "").strip()
- if not raw:
- return {"text": "", "_tokens": 0}
- # EFFECTIVE (cache-aware) cost when the runner recovered usage; else approximate on the
- # SAME model-priced basis as llm_stuck_judge.
- _tokens = _runner_effective_or_approx(runner, prompt, raw, _real)
- return {"text": raw[:1200], "_tokens": _tokens}
diff --git a/tokeneconomizer/vendor/spiral.py b/tokeneconomizer/vendor/spiral.py
deleted file mode 100644
index 32a914e..0000000
--- a/tokeneconomizer/vendor/spiral.py
+++ /dev/null
@@ -1,833 +0,0 @@
-#!/usr/bin/env python3
-"""
-v4.1 mechanism B + C: runtime spiral detector and escalation-ladder decision.
-
-The cost of a SWE-bench stream is brutally heavy-tailed: the top ~10% of tasks carry
-~50% of cache-aware effective cost, and that tail is dominated by long, UNRESOLVED
-spirals (the agent thrashing in an edit->test->fail loop while its re-fed context
-grows ~quadratically). This module:
-
- detect_incremental(events) STAGE B (free) — fold the trajectory so far into a
- compact SpiralState (edit churn, distinct edited files,
- error density, repeated near-identical edit->test->fail
- cycles, turn count).
- decide(state, envelope) STAGE C — given the per-repo RESOLVED-turn envelope,
- return the cheapest sufficient ladder action:
- none -> nudge -> compact -> restart -> abort.
-
-Design constraints (learned this milestone):
- * High turn-count is REPO-DEPENDENT: matplotlib's long tasks mostly resolve, only
- xarray's are doomed. So the heavy interventions (restart/abort) are gated on the
- per-repo `envelope` = a margin beyond the longest RESOLVED task seen so far; on a
- repo where long==hard-but-solvable the envelope is high and they rarely fire.
- * The lightest rung (nudge) is leakage-safe BY CONSTRUCTION: it only mirrors the
- agent's OWN repeated actions back at it ("you tried N similar things, same
- result"); it carries no external knowledge and never says "stop", only "try
- something different" — so it dodges the effort-capping ban.
- * abort is the terminal cap (autonomous/CI only); interactive callers should map it
- to a hand-off instead.
-
-Stdlib only. The event schema mirrors reflect.load_trajectory (Copilot CLI
-tool.execution_start / tool.execution_complete), so this runs offline on saved
-transcripts AND live on a streamed JSONL.
-"""
-import hashlib
-import json
-import re
-
-# An output that RAN code to verify behavior (the test/repro step of the edit->test
-# loop). Mirrors reflect.TEST_RUN_RE intent but local to keep this module standalone.
-_TEST_RUN_RE = re.compile(
- r"(runtests(\.py)?|\bpytest\b|py\.test|manage\.py\s+test|python\s+-m\s+unittest|"
- r"\btox\b|\bnox\b|\btrial\b|python\d?\s+-c\b)", re.IGNORECASE)
-_ERR_RE = re.compile(
- r"(Traceback \(most recent call last\)|\b\w*Error\b|\bFAILED\b|\bassert\b|"
- r"Exception|errors during collection)", re.IGNORECASE)
-_EDIT_TOOLS = ("edit", "str_replace", "create")
-
-# Normalize agent-specific tool names to the copilot-style canonical names the folding
-# logic below keys on, so ONE code path handles both the Copilot stream schema and Claude
-# Code's stream-json (which names tools Bash/Read/Edit/Write/Grep/Glob/MultiEdit). Unknown
-# names pass through unchanged.
-_TOOL_CANON = {
- "bash": "bash", "shell": "bash",
- "read": "view", "view": "view",
- "grep": "grep",
- "glob": "glob",
- "edit": "edit", "multiedit": "edit", "str_replace": "edit",
- "apply_patch": "edit",
- "write": "create", "create": "create",
-}
-
-
-def _canon_tool(name):
- return _TOOL_CANON.get((name or "").lower(), name or "?")
-
-
-def completed_calls(line, pend):
- """Schema-agnostic fold of ONE streamed JSONL line into completed (name, args, result)
- tool calls, so the live guards work for BOTH the Copilot stream
- (tool.execution_start/complete) AND Claude Code's stream-json (assistant.tool_use /
- user.tool_result). `pend` is a caller-owned dict {callId -> {name,args}} carried across
- lines to pair a start/tool_use with its later complete/tool_result. Yields a list of
- completed calls finished on THIS line (0, 1, or — for a Claude user msg batching
- several tool_results — more). Tool names are canonicalized so downstream keying is
- uniform; unpaired results fall back to name '?'."""
- try:
- ev = json.loads(line)
- except Exception:
- return []
- t = ev.get("type")
- out = []
- # ---- Codex exec --json schema ----
- if t == "item.completed":
- item = ev.get("item") or {}
- kind = item.get("type")
- if kind == "command_execution":
- out.append(("bash", {"command": item.get("command") or ""},
- item.get("aggregated_output") or ""))
- elif kind == "file_change":
- changes = item.get("changes") or []
- paths = [c.get("path") for c in changes
- if isinstance(c, dict) and c.get("path")]
- out.append(("edit", {"path": paths[0] if paths else "",
- "paths": paths, "changes": changes}, ""))
- return out
- # ---- Copilot schema ----
- if t == "tool.execution_start":
- d = ev.get("data", {}) if isinstance(ev.get("data"), dict) else {}
- pend[d.get("toolCallId")] = {"name": d.get("toolName"),
- "args": d.get("arguments", {}) or {}}
- return out
- if t == "tool.execution_complete":
- d = ev.get("data", {}) if isinstance(ev.get("data"), dict) else {}
- info = pend.pop(d.get("toolCallId"), {"name": "?", "args": {}})
- res = d.get("result") or {}
- c = res.get("content") if isinstance(res, dict) else ""
- out.append((_canon_tool(info["name"]), info.get("args") or {},
- c if isinstance(c, str) else ""))
- return out
- # ---- Claude Code stream-json schema ----
- if t == "assistant":
- for b in (ev.get("message", {}) or {}).get("content", []) or []:
- if isinstance(b, dict) and b.get("type") == "tool_use":
- pend[b.get("id")] = {"name": b.get("name"),
- "args": b.get("input", {}) or {}}
- return out
- if t == "user":
- for b in (ev.get("message", {}) or {}).get("content", []) or []:
- if isinstance(b, dict) and b.get("type") == "tool_result":
- info = pend.pop(b.get("tool_use_id"), {"name": "?", "args": {}})
- c = b.get("content")
- if isinstance(c, list): # content can be a list of text blocks
- c = " ".join(x.get("text", "") for x in c if isinstance(x, dict))
- out.append((_canon_tool(info["name"]), info.get("args") or {},
- c if isinstance(c, str) else ""))
- return out
- return out
-
-
-def _basename(p):
- return p.rstrip("/").split("/")[-1] if p else (p or "")
-
-
-def _failure_sig(text):
- """A normalized signature of a failing output: drop numbers/addresses/paths so two
- runs that fail the SAME way hash identically (used to detect 'no progress' — the
- same failure recurring after edits). Leakage-safe: a hash, never the content."""
- if not text:
- return None
- first = None
- for ln in text.splitlines():
- if _ERR_RE.search(ln):
- first = ln
- break
- if first is None:
- return None
- norm = re.sub(r"0x[0-9a-f]+|\d+|/\S+", "", first)
- return hashlib.md5(norm.strip().encode("utf-8", "replace")).hexdigest()[:10]
-
-
-class SpiralState:
- """Compact, incremental fold of one trajectory's spiral signals. Cheap to update
- per event so it can run live."""
- __slots__ = ("turns", "edit_counts", "edit_order", "error_outputs",
- "test_runs", "fail_sigs", "repeated_fail_sigs", "recent")
-
- def __init__(self):
- self.turns = 0
- self.edit_counts = {} # basename -> #edits
- self.edit_order = [] # ordered basenames of edit targets
- self.error_outputs = 0 # tool outputs carrying an error/failure marker
- self.test_runs = 0 # code-execution verification steps
- self.fail_sigs = {} # failure signature -> count
- self.repeated_fail_sigs = 0 # # of failing outputs that REPEAT an earlier sig
- self.recent = [] # leakage-safe rolling log of recent actions (for the
- # LLM trace-judge); process-only, never fix content
-
- # ---- derived signals ----
- @property
- def edit_churn(self):
- return max(self.edit_counts.values()) if self.edit_counts else 0
-
- @property
- def distinct_edit_files(self):
- return len(self.edit_counts)
-
- @property
- def stagnation(self):
- """Fraction of failing outputs that repeat an earlier identical failure (the
- agent edited but the SAME failure came back = no progress). 0 when no fails."""
- total = sum(self.fail_sigs.values())
- return (self.repeated_fail_sigs / total) if total else 0.0
-
- def update(self, tool_name, args, result_text):
- """Fold one completed tool call into the state."""
- self.turns += 1
- args = args if isinstance(args, dict) else {}
- tool_name = _canon_tool(tool_name) # accept Copilot- or Claude-named tools
- action = tool_name or "?"
- if tool_name in _EDIT_TOOLS:
- b = _basename(args.get("path") or args.get("filePath")
- or args.get("file_path") or "")
- if b:
- self.edit_order.append(b)
- self.edit_counts[b] = self.edit_counts.get(b, 0) + 1
- action = f"edit {b}"
- cmd = args.get("command", "") if tool_name == "bash" else ""
- if cmd:
- short = re.sub(r"\s+", " ", cmd.strip())[:90]
- action = f"$ {short}"
- if _TEST_RUN_RE.search(cmd):
- self.test_runs += 1
- elif tool_name in ("grep", "glob"):
- action = f"{tool_name} {str(args.get('pattern') or '')[:40]}"
- elif tool_name == "view":
- action = f"view {_basename(args.get('path') or args.get('file_path') or '')}"
- fail = None
- if result_text and _ERR_RE.search(result_text):
- self.error_outputs += 1
- sig = _failure_sig(result_text)
- if sig:
- fail = sig
- if sig in self.fail_sigs:
- self.repeated_fail_sigs += 1
- self.fail_sigs[sig] = self.fail_sigs.get(sig, 0) + 1
- # rolling leakage-safe action log (tool name / command / search / error-SIGNATURE
- # only — no file contents, edit bodies, or view output), capped to recent window.
- tag = f" [err#{fail}]" if fail else ""
- self.recent.append(f"{self.turns:>3}: {action}{tag}")
- if len(self.recent) > 40:
- self.recent = self.recent[-40:]
-
- def recent_digest(self, n=24, envelope=None):
- """A compact, LEAKAGE-SAFE digest of the agent's RECENT PROCESS (last n actions)
- for the LLM trace-judge: commands/searches/edited-basenames and error-SIGNATURE
- markers only — never fix content, edit bodies, view output, or the issue text.
- Mirrors reflect.trajectory_summary's leakage stance, windowed to 'now'.
- `envelope` (this repo's typical resolved-task length) is passed as CONTEXT so the
- judge can recognize an abnormally-long trajectory as a likely dead-end."""
- head = (f"turns={self.turns} edit_churn={self.edit_churn} "
- f"distinct_edit_files={self.distinct_edit_files} "
- f"error_outputs={self.error_outputs} test_runs={self.test_runs} "
- f"repeated_identical_failures={self.repeated_fail_sigs} "
- f"stagnation={self.stagnation:.2f}")
- if envelope:
- ratio = self.turns / envelope if envelope else 0
- head += (f"\nrepo_context: tasks here usually RESOLVE within ~{envelope:.0f} "
- f"turns; this trajectory is at {self.turns} turns = {ratio:.1f}x that "
- f"typical length. Tests are still NOT green. A trajectory far past "
- f"the typical resolved length with recurring failures is likely a "
- f"dead-end loop, even if it touches many files.")
- return head + "\nRecent actions (oldest->newest):\n" + "\n".join(self.recent[-n:])
-
-
- def snapshot(self):
- return {"turns": self.turns, "edit_churn": self.edit_churn,
- "distinct_edit_files": self.distinct_edit_files,
- "error_outputs": self.error_outputs, "test_runs": self.test_runs,
- "stagnation": round(self.stagnation, 3),
- "repeated_fail_sigs": self.repeated_fail_sigs}
-
-
-# ---- detector thresholds -----------------------------------------------------
-# The "stuck" signature (calibrated on the measured separation: spirals showed first-
-# 40-turn edit_churn ~6 vs ~1.5 normal, distinct_edit_files ~2.5 vs ~1, error_outputs
-# ~9 vs ~3). We require a CONJUNCTION (churn AND errors/scatter AND some repetition)
-# so productive-but-hard tasks (high activity, but CHANGING failures) are spared.
-DEFAULT_THRESHOLDS = {
- "min_turns": 20, # don't judge stuck before the solve loop has run a while
- "edit_churn": 4, # >=4 edits to one file
- "distinct_edit_files": 3, # OR edits scattered across >=3 files
- "error_outputs": 6, # sustained error density
- "stagnation": 0.20, # >=20% of failures are repeats of an earlier one
- "envelope_margin": 1.25, # restart/abort only beyond margin x the resolved-turn pctl
- "envelope_pct": 90, # use the p90 of resolved turns (NOT max) — robust to a
- # single very-long resolve poisoning the gate (see
- # EnvelopeTracker). max-based envelope was disabled by one
- # 115-turn xarray resolve; p90 ignores the lone outlier.
- "envelope_min_samples": 5, # need >=5 resolved tasks before trusting the percentile
- "restart_budget": 2, # max restarts before the terminal abort cap
- "judge_confidence": 0.7, # LLM trace-judge must be >=this confident to drive an abort
- "backstop_mult": 2.5, # HARD backstop: beyond this multiple of the envelope, a
- # stuck trajectory aborts REGARDLESS of the judge's verdict.
- # Empirically the judge spared xarray-7019/7179 at 5.8x the
- # envelope (177-204 turns vs envelope 35, stagnation 0.3-0.4)
- # by misreading multi-file thrashing as "exploration"; the
- # judge must not be able to veto a screaming outlier.
- # ---- cheap GATE to the judge (Tier-0): permissive "worth a paid look?" trigger.
- # Sensitive on purpose (catch candidates); the judge supplies precision. Far cheaper
- # to evaluate than the judge, and far more permissive than is_stuck (which is the
- # strict heuristic DECISION used only in the no-judge fallback).
- "gate_min_turns": 18, # don't wake the judge before the loop has had time to form
- "gate_error_outputs": 8, # OR: a lot of errors even without an exact repeat
-}
-
-
-# ---- v6.1 aggressiveness knob ------------------------------------------------
-# A single user-facing LEVEL scales the base thresholds the guard starts from (the per-repo
-# EnvelopeTracker then learns ON TOP of this base, flooring learned signal-gates against it).
-# Calibrated on the guard-active arms (v41fix/v43-xarray, n=239): the ABORT/backstop path is
-# already near-right (only 1 task slipped past 2.5x envelope), but (a) the rung-1 NUDGE was
-# effectively DORMANT (1/239) because it shares the abort's bias-to-spare judge gate, and
-# (b) a middle band of 28 unresolved tasks ran past typical-resolved length yet under the
-# backstop with no intervention. So 'aggressive' mainly WAKES THE NUDGE (lower judge
-# confidence, earlier gate, and nudge_on_ambiguous) and tightens that middle band, while
-# only MODESTLY pulling the backstop in (2.5x -> 1.8x). 'default' == today's behavior
-# EXACTLY (empty override). 'conservative' spares harder (for churny-but-productive repos).
-# nudge_on_ambiguous: when True, a judge-AMBIGUOUS trajectory PAST the envelope fires the
-# resolve-safe NUDGE (never an abort) instead of being spared outright — safe because a
-# nudge only redirects. Only 'aggressive' sets it.
-SPIRAL_LEVELS = {
- "conservative": {
- "judge_confidence": 0.85, "envelope_margin": 1.5, "backstop_mult": 3.5,
- "stagnation": 0.30, "gate_min_turns": 24, "min_turns": 28,
- "edit_churn": 5, "error_outputs": 8, "envelope_min_samples": 7,
- },
- "default": {}, # verbatim DEFAULT_THRESHOLDS — reproduces pre-knob behavior exactly
- "aggressive": {
- "judge_confidence": 0.55, "envelope_margin": 1.0, "backstop_mult": 1.8,
- "stagnation": 0.12, "gate_min_turns": 12, "min_turns": 14,
- "edit_churn": 3, "error_outputs": 4, "envelope_min_samples": 3,
- "nudge_on_ambiguous": True,
- },
-}
-
-
-def scaled_thresholds(level="default"):
- """Return DEFAULT_THRESHOLDS overlaid with the named LEVEL's overrides (see
- SPIRAL_LEVELS). Unknown level falls back to 'default' (verbatim defaults). This is the
- BASE the EnvelopeTracker starts from; per-repo learning floors on top of it."""
- thr = dict(DEFAULT_THRESHOLDS)
- thr.update(SPIRAL_LEVELS.get(level, SPIRAL_LEVELS["default"]))
- return thr
-
-
-def gate_for_judge(state, thr=None):
- """TIER-0 (free, every turn): cheap rule-based trigger deciding whether the recent
- trace is worth ELEVATING to the paid LLM judge. Permissive — it only needs a sign of
- POSSIBLE trouble after the loop has had time to form: a repeated identical failure
- (the cheapest 'no progress' signal) OR a high error density. Productive trajectories
- (changing failures, few repeats) mostly keep this gate CLOSED, so the judge is rarely
- consulted; the judge then makes the precise stuck-vs-productive call. This separation
- is what keeps the judge from being a per-step tax."""
- thr = thr or DEFAULT_THRESHOLDS
- if state.turns < thr["gate_min_turns"]:
- return False
- return (state.repeated_fail_sigs >= 1
- or state.error_outputs >= thr["gate_error_outputs"])
-
-
-def is_stuck(state, thr=None):
- """Strict heuristic 'this looks like an unproductive loop' classifier — the DECISION
- used only in the no-judge fallback. Must have run a while AND show churn/scatter AND
- repeated identical failures (stagnation): the last term is what separates a doomed
- spiral from a productive hard grind. (When the judge is wired, gate_for_judge is the
- cheap trigger and the judge is the decision; is_stuck is not used.)"""
- thr = thr or DEFAULT_THRESHOLDS
- if state.turns < thr["min_turns"]:
- return False
- churny = (state.edit_churn >= thr["edit_churn"]
- or state.distinct_edit_files >= thr["distinct_edit_files"])
- noisy = state.error_outputs >= thr["error_outputs"]
- repeating = state.stagnation >= thr["stagnation"]
- return churny and noisy and repeating
-
-
-# ladder rungs, cheapest first
-NONE, NUDGE, COMPACT, RESTART, ABORT = "none", "nudge", "compact", "restart", "abort"
-
-
-def assess_abort(state, envelope=None, judge=None, thr=None):
- """Decide whether to abort, TRACE-FIRST, as an explicit TWO-TIER cascade. Returns
- (abort: bool, reason: str).
-
- TIER 0 — cheap rule-based GATE (free, every turn): gate_for_judge(). Decides only
- whether the recent trace is WORTH a paid look. Permissive; productive trajectories
- mostly keep it closed, so the judge is rarely consulted (this is what makes the
- judge not a per-step tax).
- TIER 1 — paid LLM JUDGE (only when the gate is open, and the caller additionally
- rate-limits it): reads a leakage-safe digest of the RECENT actions and decides
- stuck-vs-productive. The judge — not the step count — drives the outcome:
- - STUCK, confidence>=judge_confidence -> ABORT, even within the envelope (a
- clearly-doomed loop shouldn't burn tokens up to the envelope first);
- - PRODUCTIVE -> SPARE, even past the envelope (progress shows in the trace);
- - ambiguous -> defer to the envelope fallback.
- FALLBACK — when NO judge is wired (judge=None): the strict is_stuck() heuristic plus
- the per-repo resolved-turn envelope (the Phase-1.5 behavior), so the guard still
- works cheaply without an LLM.
- """
- thr = thr or DEFAULT_THRESHOLDS
-
- # HARD BACKSTOP (checked BEFORE the judge): an extreme outlier — far past the
- # envelope AND stuck by the strict heuristic — aborts regardless of any judge
- # verdict. The judge cannot veto this; it exists because the LLM judge empirically
- # rationalized 5.8x-envelope thrashing (xarray-7019/7179) as "exploration".
- # `backstop_turns` (learned, cap-aware) is preferred when the tracker supplied it, so
- # the backstop stays REACHABLE under a tight turn cap; else fall back to the
- # multiplier-on-envelope form (the Copilot-scale behavior).
- backstop_turns = thr.get("backstop_turns")
- if backstop_turns is None and envelope is not None:
- backstop_turns = envelope * thr["backstop_mult"]
- if (backstop_turns is not None
- and state.turns >= backstop_turns
- and is_stuck(state, thr)):
- return True, (f"backstop:{state.turns}>={backstop_turns:.0f}"
- f"turns stagnation={state.stagnation:.2f}")
-
- if judge is not None:
- # TWO-TIER: gate -> judge. The gate opens on the cheap rule-based trigger OR when
- # the trajectory is already PAST this repo's typical resolved length (envelope) —
- # an over-envelope run is worth a paid judge look even without an exact repeated
- # failure yet, which is what lets the guard engage on a short-turn agent whose
- # spirals hit the cap before accumulating a repeat signature.
- over_envelope = envelope is not None and state.turns >= envelope
- if not (gate_for_judge(state, thr) or over_envelope):
- return False, "gate-closed"
- try:
- v = judge(state.recent_digest(envelope=envelope)) # caller rate-limits
- except Exception:
- v = None
- if not v:
- return False, "judge-throttled"
- conf = float(v.get("confidence", 0) or 0)
- if v.get("stuck") and conf >= thr["judge_confidence"]:
- return True, f"judge-stuck@{conf:.2f}:{str(v.get('reason',''))[:60]}"
- if v.get("stuck") is False:
- return False, "judge-productive"
- # judge AMBIGUOUS (stuck=None): do NOT abort on the (possibly under-calibrated,
- # early-stream) envelope alone — that killed resolvable tasks like xarray-7120 at
- # turn 28 when the p90 envelope was only 27. Ambiguity => SPARE; the hard backstop
- # (2.5x envelope AND is_stuck, checked above) remains the only envelope-driven kill,
- # and it sits well beyond any resolvable task's length.
- return False, "judge-ambiguous-spared"
-
- # FALLBACK (no judge): strict heuristic + envelope safety gate.
- if not is_stuck(state, thr):
- return False, "not-stuck"
- if envelope is not None and state.turns >= envelope:
- return True, f"envelope:{state.turns}>={envelope:.0f}"
- return False, "stuck-but-within-envelope"
-
-
-def should_abort(state, envelope, judge=None, thr=None):
- """Backward-compatible boolean wrapper over assess_abort()."""
- ok, _reason = assess_abort(state, envelope=envelope, judge=judge, thr=thr)
- return ok
-
-
-def decide(state, envelope=None, restarts_done=0, nudged=False,
- autonomous=False, thr=None):
- """STAGE C — choose the cheapest sufficient ladder action.
-
- `envelope` = margin * (longest RESOLVED task's turn count seen so far) for this
- repo, or None to disable the heavy rungs (then we only ever nudge). `restarts_done`
- and `nudged` track what's already been tried this task so the ladder escalates.
-
- Returns one of NONE / NUDGE / COMPACT / RESTART / ABORT.
- """
- thr = thr or DEFAULT_THRESHOLDS
- if not is_stuck(state, thr):
- return NONE
- # rung 1: always try the free, resolve-safe nudge first.
- if not nudged:
- return NUDGE
- # beyond the nudge we need the per-repo envelope to authorize heavier action — this
- # is what keeps us off matplotlib's productive long tasks.
- over_envelope = envelope is not None and state.turns >= envelope
- if not over_envelope:
- # still within the band where long==plausibly-productive: only compact (safe).
- return COMPACT
- if restarts_done < thr["restart_budget"]:
- return RESTART
- return ABORT if autonomous else COMPACT
-
-
-def nudge_text(state):
- """The rung-1 message: mirror the agent's OWN repeated actions back at it. Contains
- nothing but a summary of what it already did — leakage-safe by construction, and
- framed to REDIRECT effort, never to stop it."""
- busiest = max(state.edit_counts.items(), key=lambda kv: kv[1])[0] \
- if state.edit_counts else "one file"
- return (
- "Process check (automated): so far you've made "
- f"{sum(state.edit_counts.values())} edits across "
- f"{state.distinct_edit_files} file(s) (most to `{busiest}`) and run "
- f"{state.test_runs} verification(s), and the same failure has recurred "
- f"{state.repeated_fail_sigs} time(s) without the tests going green. This "
- "looks like a repetitive loop. Do NOT stop — instead step back and try a "
- "MATERIALLY DIFFERENT hypothesis: re-read the failing test's expectation, "
- "consider a different file or root cause than the ones you've been editing, "
- "and verify the new hypothesis directly before editing again.")
-
-
-def restart_digest(state):
- """Leakage-safe brief carried across a context RESTART: what was already tried
- (counts + the files touched, which are the agent's own actions) and that tests are
- still red. Never includes a fix, a gold pointer, or which lines to change."""
- files = ", ".join(f"{b} ({n} edits)" for b, n in
- sorted(state.edit_counts.items(), key=lambda kv: -kv[1]))
- return (
- "Resuming this task with a fresh, compact context after a repetitive loop. "
- "What was already attempted (do NOT simply repeat it): edited " + (files or "—")
- + f"; ran {state.test_runs} verifications; the tests are still failing and the "
- f"same failure recurred {state.repeated_fail_sigs} time(s). Form a different "
- "hypothesis about the root cause, confirm it by reading the relevant code and "
- "the failing test's expectation, then make a focused change and verify.")
-
-
-# ---- rung-1 NUDGE live controller --------------------------------------------
-RESUME_HEADER = (
- "\n\n---\nNOTE: you are RESUMING this same task. The repository at /testbed already "
- "contains your OWN in-progress edits from your previous attempt (inspect them with "
- "`git diff`); do not discard that work, build on it. The tests are still not passing.\n")
-
-
-class NudgeGuard:
- """Live rung-1 controller: run the sealed agent as a sequence of streamed SEGMENTS in
- ONE container, delivering the leakage-safe NUDGE between segments.
-
- Why segments: the rollout is single-shot `copilot -p`, so a nudge cannot be injected
- into the running context. Instead the guard STOPS the current stream the moment the
- trajectory looks stuck (freezing the container's working tree with the agent's edits
- intact) and the harness RE-INVOKES the agent with a continuation prompt = original task
- + RESUME_HEADER + nudge_text(). The agent resumes on top of its own on-disk edits.
-
- Ladder realized here (compact/restart remain P2): the FIRST stuck detection NUDGES; a
- subsequent stuck detection (or the cumulative backstop) ABORTS. Each new segment starts
- with a FRESH per-segment SpiralState, so the post-nudge behavior must independently
- re-accumulate churn/errors/stagnation past the gate before it can be judged stuck again
- — that reset IS the nudge's fair grace window (assess_abort's gate needs >=18 turns).
- A cumulative backstop (turns summed across segments) bounds total cost regardless.
-
- Usage (harness side):
- guard = NudgeGuard(envelope=env, judge=spiral_judge, verbose=True)
- rec, wall = run_agent(..., monitor=guard.monitor,
- continuation=lambda: guard.continuation(prompt))
- # then read guard.nudges_done / guard.aborted / guard.events for telemetry.
- """
-
- def __init__(self, envelope=None, judge=None, thr=None, nudge_budget=1,
- verbose=False, nudge_writer=None, resume_header=None):
- self.envelope = envelope
- self.judge = judge # raw digest->verdict callable (rate-limited HERE)
- self.thr = thr or DEFAULT_THRESHOLDS
- self.nudge_budget = nudge_budget
- self.verbose = verbose
- # v6.1: optional LLM-targeted nudge writer (digest -> {"text","_tokens"}). When
- # set, continuation() uses it to build a TARGETED redirect from the same leakage-
- # safe digest the judge sees, falling back to the generic nudge_text template on
- # any empty/failed result. None => the fixed count-template (v4.3 behavior).
- self.nudge_writer = nudge_writer
- self.resume_header = resume_header if resume_header is not None else RESUME_HEADER
- self.nudge_writer_tokens = 0 # REAL token cost of paid nudge-writer calls
- # per-segment stuck-detection state (reset by continuation() after each nudge)
- self.st = SpiralState()
- self.pend = {} # toolCallId -> {name,args} within the segment
- # cross-segment accounting
- self.cum_turns = 0 # turns summed over ALL segments (cumulative backstop)
- self.segment = 0
- self.nudges_done = 0
- self.aborted = False # terminal abort fired
- self.pending_action = None # 'nudge' | 'abort' set when a segment should stop
- self.events = [] # telemetry: nudge/abort decisions
- # sampled-judge cadence (mirror run_agent's _sampled_judge: backoff on productive)
- self._judge_last = -999
- self._judge_gap = 5
- self._judge_calls = 0
- self.judge_tokens = 0 # REAL token cost of all paid judge calls (mechanism
- # overhead folded into amortized task cost by callers)
- self._JUDGE_BASE_GAP = 5
- self._JUDGE_MAX_GAP = 20
-
- # ---- the paid judge, rate-limited with backoff (keyed on per-segment turns) -------
- def _sampled_judge(self, digest):
- if self.judge is None:
- return None
- if self.st.turns - self._judge_last < self._judge_gap:
- return None
- self._judge_last = self.st.turns
- self._judge_calls += 1
- try:
- v = self.judge(digest)
- except Exception:
- v = None
- if v:
- self.judge_tokens += v.get("_tokens") or 0
- if v and v.get("stuck") is False:
- self._judge_gap = min(self._JUDGE_MAX_GAP, self._judge_gap + self._JUDGE_BASE_GAP)
- else:
- self._judge_gap = self._JUDGE_BASE_GAP
- if self.verbose and v:
- print(f" [nudge-judge] seg{self.segment} turn {self.st.turns} "
- f"(call #{self._judge_calls}, next>={self._judge_gap}): "
- f"stuck={v.get('stuck')} conf={v.get('confidence')} "
- f"{str(v.get('reason', ''))[:50]}")
- return v
-
- # ---- STREAM monitor: fold one JSONL event, return True to STOP this segment -------
- def monitor(self, line):
- # completed_calls handles BOTH the Copilot schema (tool.execution_start/complete)
- # and Claude Code's stream-json (assistant.tool_use / user.tool_result). A single
- # Claude user message can batch several tool_results, so fold+assess EACH in order
- # and stop on the first that trips the gate.
- for name, args, result in completed_calls(line, self.pend):
- self.st.update(name, args, result)
- self.cum_turns += 1
-
- # cumulative hard backstop across segments (per-segment st resets, so
- # assess_abort's own backstop only sees within-segment turns; this catches a
- # task that keeps spiraling across a nudge without any single segment exceeding
- # the envelope). Prefer the learned cap-aware `backstop_turns` (so it stays
- # reachable under a tight turn cap); else fall back to backstop_mult*envelope.
- backstop_turns = self.thr.get("backstop_turns")
- if backstop_turns is None and self.envelope is not None:
- backstop_turns = self.envelope * self.thr["backstop_mult"]
- if (backstop_turns is not None
- and self.cum_turns >= backstop_turns
- and is_stuck(self.st, self.thr)):
- return self._stop("abort",
- f"cum-backstop:{self.cum_turns}>={backstop_turns:.0f}t")
-
- abort, reason = assess_abort(self.st, envelope=self.envelope,
- judge=(self._sampled_judge if self.judge else None),
- thr=self.thr)
- if not abort:
- # v6.1 aggressive knob: a judge-AMBIGUOUS trajectory PAST the envelope is
- # spared from ABORT by assess_abort (resolve-safety), but under this level we
- # still fire the RESOLVE-SAFE nudge on it (redirect only, never a kill) — this
- # is what wakes the otherwise-dormant nudge on the middle band of long-running
- # unresolved tasks. Never escalates to abort here.
- if (self.thr.get("nudge_on_ambiguous")
- and reason == "judge-ambiguous-spared"
- and self.nudges_done < self.nudge_budget):
- return self._stop("nudge", "ambiguous-past-envelope")
- continue
- # stuck: nudge first (while budget remains), else abort.
- if self.nudges_done < self.nudge_budget:
- return self._stop("nudge", reason)
- return self._stop("abort", reason)
- return False
-
- def _stop(self, action, reason):
- self.pending_action = action
- rec = {"segment": self.segment, "action": action,
- "turn_in_segment": self.st.turns, "cum_turns": self.cum_turns,
- "envelope": self.envelope, "reason": reason,
- "snapshot": self.st.snapshot()}
- self.events.append(rec)
- if action == "abort":
- self.aborted = True
- if self.verbose:
- print(f" [nudge-guard] seg{self.segment} {action.upper()} at "
- f"turn {self.st.turns} (cum {self.cum_turns}) ({reason}) "
- f"{self.st.snapshot()}")
- return True
-
- # ---- nudge body: v6.1 LLM-targeted redirect, else the generic template ------------
- def _nudge_body(self):
- """Build the rung-1 nudge text. If an LLM nudge_writer is wired, feed it the SAME
- leakage-safe recent digest the judge sees and use its targeted redirect; fold the
- paid cost into nudge_writer_tokens. Fall back to the generic nudge_text template on
- an absent writer or any empty/failed result (resolve-safe zero-LLM path)."""
- if self.nudge_writer is not None:
- try:
- out = self.nudge_writer(self.st.recent_digest(envelope=self.envelope))
- except Exception:
- out = None
- if out:
- self.nudge_writer_tokens += out.get("_tokens") or 0
- txt = (out.get("text") or "").strip()
- if txt:
- if self.verbose:
- print(f" [nudge-writer] seg{self.segment} targeted redirect "
- f"({len(txt)} chars, +{out.get('_tokens')} tok)")
- return txt
- return nudge_text(self.st)
-
- # ---- CONTINUATION: called after a segment aborts; return next prompt or None ------
- def continuation(self, base_prompt):
- """Return the continuation prompt for the next segment, or None to stop for good.
- Only a 'nudge' stop continues; an 'abort' stop (or a natural end) is terminal."""
- if self.pending_action != "nudge":
- return None
- text = self._nudge_body()
- self.nudges_done += 1
- # fresh per-segment state -> the agent gets a fair, independent re-assessment.
- self.st = SpiralState()
- self.pend = {}
- self.pending_action = None
- self.segment += 1
- self._judge_last = -999
- self._judge_gap = self._JUDGE_BASE_GAP
- return base_prompt + self.resume_header + text
-
-
-# ---- envelope tracking -------------------------------------------------------
-def _percentile(xs, p):
- """Linear-interpolated p-th percentile of xs (0<=p<=100). xs need not be sorted."""
- if not xs:
- return None
- xs = sorted(xs)
- n = len(xs)
- if n == 1:
- return float(xs[0])
- i = (p / 100.0) * (n - 1)
- lo = int(i)
- frac = i - lo
- if lo + 1 >= n:
- return float(xs[-1])
- return xs[lo] + frac * (xs[lo + 1] - xs[lo])
-
-
-class EnvelopeTracker:
- """Per-repo resolved-turn envelope AND runtime-learned detection thresholds.
-
- Envelope: margin * the p<pct> of turn-counts among RESOLVED tasks seen so far. Using a
- PERCENTILE (default p90), not the max, makes the gate robust to a single very-long
- resolve — empirically one 115-turn xarray resolve set a max-based envelope to ~144 and
- disabled the guard for every 40-60-turn spiral below it; p90 ignores that lone outlier
- (envelope ~32) while staying HIGH on repos like matplotlib where long resolves are
- COMMON (so productive-long tasks stay protected). Stays None until >=min_samples
- resolved tasks exist (don't trust a percentile of a handful of points), so we never
- abort on a repo we know little about yet.
-
- Thresholds: `thresholds()` derives the FULL detector threshold dict from the SAME
- resolved-task history, so the guard adapts to the agent/repo's actual turn scale
- instead of the hardcoded Copilot-scale DEFAULT_THRESHOLDS (which never fired on Claude
- Code's <=80-turn runs — its backstop landed above the turn cap). Turn-scale gates
- scale DOWN to the learned distribution; signal gates keep DEFAULT as a FLOOR so the
- learned dict is never MORE trigger-happy than the hand-tuned one (resolve-safety). Fed
- only by RESOLVED tasks (same causal rule as the envelope), so a task's own outcome can
- only gate FUTURE tasks, never itself."""
- def __init__(self, margin=None, pct=None, min_samples=None, level="default",
- frozen_envelope=None):
- # v6.1: `level` selects the aggressiveness preset (SPIRAL_LEVELS). It sets the BASE
- # thresholds this tracker starts from AND the envelope margin/percentile/min-samples;
- # explicit margin/pct/min_samples args still win over the preset when given.
- self.level = level
- self.base_thr = scaled_thresholds(level)
- self.margin = margin or self.base_thr["envelope_margin"]
- self.pct = pct if pct is not None else self.base_thr["envelope_pct"]
- self.min_samples = (min_samples if min_samples is not None
- else self.base_thr["envelope_min_samples"])
- # FROZEN envelope (pre-registered hyperparameter): when set, `envelope` returns this
- # value from task 1, bypassing the >=min_samples warm-up. For SHORT streams (Web-Bench
- # = 20 tasks, ~5 resolved at ~25% Pass@1) the percentile never reaches min_samples, so
- # a within-stream-learned envelope would stay None the whole run and the guard would
- # never engage. A frozen scalar (calibrated once from SWE-bench/held-out, IDENTICAL
- # across all streams -- a fixed hyperparameter, NOT a prior pooled across the streams)
- # lets the guard engage while preserving stream independence. None => today's behavior.
- self.frozen_envelope = frozen_envelope
- self.resolved_turns = [] # all RESOLVED tasks' turn counts (for the percentile)
- self.resolved_snaps = [] # per-resolved-task SpiralState.snapshot() dicts (signals)
-
- def update(self, turns, resolved, snapshot=None):
- """Record a completed task. Only RESOLVED tasks feed the baseline. `snapshot` is an
- optional SpiralState.snapshot() dict (edit_churn/distinct_edit_files/error_outputs/
- stagnation/...) captured from that task's trajectory; when omitted only the
- turn-envelope learns (back-compat with callers that don't reconstruct the state)."""
- if resolved and turns:
- self.resolved_turns.append(turns)
- if snapshot:
- self.resolved_snaps.append(snapshot)
-
- @property
- def envelope(self):
- if len(self.resolved_turns) < self.min_samples:
- # cold start: fall back to the frozen pre-registered envelope if one was set
- # (short-stream case); else None == "don't trust a handful of points yet".
- return self.frozen_envelope
- return _percentile(self.resolved_turns, self.pct) * self.margin
-
- def thresholds(self, max_turns=None):
- """Return the detector threshold dict to hand to is_stuck/gate_for_judge/
- assess_abort. Starts from the LEVEL-scaled base (scaled_thresholds(self.level); ==
- DEFAULT_THRESHOLDS for level 'default') and, once >=min_samples RESOLVED tasks
- exist, overrides the learned keys from this stream's resolved-task distribution.
- Before warm-up (or with no data) it returns the base verbatim, so behavior is
- unchanged until the stream has learned enough — exactly like the envelope gating
- None today. Learned signal-gates floor against the SCALED base, so an 'aggressive'
- level genuinely lowers those floors (and 'conservative' raises them). Pass
- `max_turns` (the run's turn cap) to make the hard backstop REACHABLE under the cap."""
- base = self.base_thr
- thr = dict(base)
- env = self.envelope
- # cap-aware backstop: reachable even under a tight turn cap. The Copilot-scale
- # `backstop_mult * envelope` landed ABOVE Claude's 80-turn cap (~110 turns) so it
- # never fired; clamp it under 0.9*cap so an extreme outlier still aborts in-cap.
- if env is not None:
- bt = env * thr["backstop_mult"]
- if max_turns:
- bt = min(bt, 0.9 * max_turns)
- thr["backstop_turns"] = bt
- if len(self.resolved_turns) < self.min_samples:
- return thr # cold start: level-scaled base (+ backstop_turns if env exists)
-
- # --- turn-scale gates: relative to the learned resolved-turn distribution. On a
- # short-turn agent (Claude p90~35) this drops the judge gate from 18 -> ~10 so the
- # guard can engage before the cap; on a long-turn agent (Copilot p90~150+) the
- # clamp keeps it at the base ceiling (no change). ---
- p90t = _percentile(self.resolved_turns, 90) or 0
-
- def _clamp(v, lo, hi):
- return int(max(lo, min(hi, round(v))))
- thr["gate_min_turns"] = _clamp(0.6 * p90t, 6, base["gate_min_turns"])
- thr["min_turns"] = _clamp(0.6 * p90t, 8, base["min_turns"])
-
- # --- signal gates: treat RESOLVED runs as the "normal" band and sit just ABOVE its
- # p90, but never BELOW the (level-scaled) base floor (so the learned dict is never
- # more trigger-happy than the level asks — protects resolve-safety on churny-but-
- # productive repos, where this RAISES the bar). Needs the per-task snapshots. ---
- if self.resolved_snaps:
- def _sig(key):
- return [s.get(key, 0) or 0 for s in self.resolved_snaps]
- import math
- thr["edit_churn"] = max(base["edit_churn"],
- math.ceil((_percentile(_sig("edit_churn"), 90) or 0) + 1))
- thr["distinct_edit_files"] = max(
- base["distinct_edit_files"],
- math.ceil((_percentile(_sig("distinct_edit_files"), 90) or 0) + 1))
- thr["error_outputs"] = max(
- base["error_outputs"],
- math.ceil((_percentile(_sig("error_outputs"), 90) or 0) + 1))
- thr["gate_error_outputs"] = max(base["gate_error_outputs"],
- thr["error_outputs"])
- thr["stagnation"] = max(base["stagnation"],
- round(_percentile(_sig("stagnation"), 90) or 0, 3))
- return thr
-
-
-# ---- offline / shadow-mode helper --------------------------------------------
-def state_from_trajectory(path, load_trajectory=None):
- """Build a final SpiralState by replaying a saved transcript.jsonl. Reuses
- reflect.load_trajectory by default (import lazily to avoid a hard dependency when
- spiral.py is used standalone). Returns a SpiralState (use .snapshot() / decide()).
- """
- if load_trajectory is None:
- from . import reflect
- load_trajectory = reflect.load_trajectory
- st = SpiralState()
- for name, args, res, _ok in load_trajectory(path):
- st.update(name, args, res)
- return st