Experience-Driven Black-Box Cost Control for Coding Agents
Python agentic-aiagentic-codingai-codingai-coding-assistantanthropicartificial-intelligenceclaude-codecodexcoding-agentcoding-agentscost-optimizationcost-reductiondeveloper-toolsgithub-copilotllmopen-sourceopenaiproductivitytoken-optimization
readme updated
Aarone8da43b015c2
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex fb76a9a..fd3c9c5 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -8,7 +8,7 @@{"name": "tokeneconomizer","source": "./plugin",- "description": "Micro-skills learned per repository, tool pruning through a deny list you approve, and a failure-loop guard."+ "description": "Micro-skills learned per repository, tool pruning of tools a repository never uses (one command gives them back), and a failure-loop guard."}]}diff --git a/README.md b/README.mdindex 742b3c7..8ed847f 100644--- a/README.md+++ b/README.md@@ -35,11 +35,13 @@ what the next sessions in that repository pay for:that `pytest` is missing here and `python -m pytest` works, that the test runner wants labelswithout a `tests.` prefix -- are learned from recurring evidence and stated at the start ofthe 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.+- **Tool pruning.** Tools that stay loaded but go unused, session after session (five in a row+ by default), are left out of the next sessions through the agent's own settings. By default+ this happens without asking you: the next session start says which tools were left out, and+ one command gives them back. Set `toolprune=propose` to approve each deny list yourself instead.- **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.+ cycle, well past how long this repository's turns usually take, gets one redirect. If it is+ still stuck after that, the plugin tells you how to stop it; it never stops a turn itself.Each mechanism can be switched off or tuned on its own. The plugin's actions are announced inone line, every hook fails open, and by default it makes no model calls of its own. What it learns@@ -64,7 +66,7 @@ Four principles shape the mechanisms:- **Keep task success.** Facts form only from recurring evidence, tools are pruned only aftergoing unused, and the loop guard spares a turn that is still making progress.- **Recover from mistakes.** A fact a later session contradicts is retired, an applied deny list- can be restored, and the guard redirects before it ever stops a turn.+ can be restored, and the guard only redirects and tells you: stopping a turn is your call.The paper evaluates these mechanisms with Claude Code, Codex and the Copilot CLI on SWE-Bench,Web-Bench and two security benchmarks; [`experiments/`](experiments/README.md) reruns the@@ -119,9 +121,9 @@ Work as usual; the plugin needs nothing from you. To see what it does, or to cha|---|---|---|---|---|| see what it learned and did, and what sessions cost | `/tokeneconomizer:status` | `$tokeneconomizer:status` | `/tokeneconomizer:status` | `/te status` || see the facts it injects, and those forming | `/tokeneconomizer:microskills` | `$tokeneconomizer:microskills` | `/tokeneconomizer:microskills` | `/te microskills` |-| review the proposed deny list | `/tokeneconomizer:toolprune` | `$tokeneconomizer:toolprune` | `/tokeneconomizer:toolprune` | not used: Pi loads four tools |-| accept it, from the next session | `/tokeneconomizer:toolprune apply` | `$tokeneconomizer:toolprune apply` | `/tokeneconomizer:toolprune apply` | — |-| undo it | `/tokeneconomizer:toolprune restore` | `$tokeneconomizer:toolprune restore` | `/tokeneconomizer:toolprune restore` | — |+| see the tools it left out, and the evidence | `/tokeneconomizer:toolprune` | `$tokeneconomizer:toolprune` | `/tokeneconomizer:toolprune` | not used: Pi loads four tools |+| give them back (it will not remove them again) | `/tokeneconomizer:toolprune restore` | `$tokeneconomizer:toolprune restore` | `/tokeneconomizer:toolprune restore` | — |+| approve each deny list yourself instead | `/tokeneconomizer:config set toolprune=propose`, then `/tokeneconomizer:toolprune apply` | `$tokeneconomizer:config set toolprune=propose`, then `$tokeneconomizer:toolprune apply` | `/tokeneconomizer:config set toolprune=propose`, then `/tokeneconomizer:toolprune apply` | — || show every setting in effect | `/tokeneconomizer:config` | `$tokeneconomizer:config` | `/tokeneconomizer:config` | `/te config` || turn a mechanism off in this repository | `/tokeneconomizer:config set loopguard=off` | `$tokeneconomizer:config set loopguard=off` | `/tokeneconomizer:config set loopguard=off` | `/te config set loopguard=off` || ... or in every repository | `/tokeneconomizer:config set loopguard=off --global` | `$tokeneconomizer:config set loopguard=off --global` | `/tokeneconomizer:config set loopguard=off --global` | `/te config set loopguard=off --global` |@@ -133,11 +135,11 @@ Work as usual; the plugin needs nothing from you. To see what it does, or to chaInside an agent, each command is one model turn. Codex has no plugin slash commands, so there theyare skills, named like the slash commands: type `$tokeneconomizer` and pick one. (A question inplain words may be answered from the plugin's files without running the command; naming the skill-runs it.) A Codex command that changes something (`config set`, `toolprune apply`, ...) writes+runs it.) A Codex command that changes something (`config set`, `toolprune restore`, ...) writesoutside Codex's sandbox, so Codex asks first: choose **Yes, proceed**. The Copilot CLI runs slashcommands in its interactive mode only, and asks before each: choose **Yes**. From a terminal everycommand is free: put any of the ones above after `te --host <agent>` (`te --host codex toolprune-apply`, `te --host pi repos`; settings are shared by every agent, so `te config set loopguard=off+restore`, `te --host pi repos`; settings are shared by every agent, so `te config set loopguard=off--global` needs none). From a plain terminal, `te` without `--host` means the agent that last workedin the repository. The launcher in `~/.tokeneconomizer/bin` is written by the first session.@@ -145,12 +147,15 @@ in the repository. The launcher in `~/.tokeneconomizer/bin` is written by the fiThe three mechanisms are `microskills`, `toolprune` and `loopguard`; each takes `on` or `off`,and each has numbers you can tune with the same `config set` command (in Claude Code's form here;-each agent's is in the table above):+each agent's is in the table above). Tool pruning is `auto` by default: once a tool has gone+unused for `toolprune_evidence` sessions in a row (five), the plugin adds it to the deny list+without asking, and it is left out from the next session on. With `toolprune=propose` the plugin+only proposes the list, and nothing changes until you run `toolprune apply`.```text/tokeneconomizer:config set microskills_max_facts=2 # inject at most two facts-/tokeneconomizer:config set toolprune_evidence=10 # propose after ten unused sessions-/tokeneconomizer:config set loopguard=stop # stop stuck headless turns (Claude, Pi)+/tokeneconomizer:config set toolprune_evidence=10 # wait for ten unused sessions+/tokeneconomizer:config set loopguard_nudges=2 # redirect twice before telling you```For one session only, set an environment variable when you start the agent:@@ -164,15 +169,48 @@ variable: [Settings](plugin/README.md#settings).| | 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 `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)**, and how the package fits together in-**[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)**.+| Claude Code | at session start | tools, in `.claude/settings.local.json` | a redirect, then a notice to you |+| Codex | at session start | capability packages, in the project's `.codex/config.toml` | a redirect, then a notice to you |+| Copilot CLI | at session start | whole MCP servers, in `.github/copilot/settings.local.json` | a redirect, then a notice to you |+| Pi | at session start | — (Pi loads four tools) | a redirect, then a notice to you |++Tool pruning writes only the entries it adds and never touches deny rules you wrote; a settings+file it creates is kept out of git (`.git/info/exclude`). The next session start says what it+left out. On Claude Code that line shows only in the detailed transcript (**Ctrl+O**), so+`/tokeneconomizer:toolprune` is the place to check. `toolprune restore` removes the plugin's+entries and no others, and what you give back stays back. With `toolprune=propose`, nothing is+written until you approve it. If the plugin cannot edit a file safely (a `.codex/config.toml`+your repository commits, a settings file that is not valid JSON, a path through a symlink), the+list stays a proposal and the session start says why. How each agent's hooks and settings+were verified to behave is in **[`docs/PLUGIN.md`](docs/PLUGIN.md)**, and how the package fits+together in **[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)**.++### When a turn gets stuck++The loop guard does the same on every agent, in its interactive UI and in a headless run+(`claude -p`, `codex exec`, `copilot -p`, `pi -p`). The first time a turn looks stuck, it adds a+redirect to the model's context, and the model sees it on every agent. If the turn is still+stuck after that, it shows you one line, which ends with how to stop the turn on that agent:++> TokenEconomizer: this turn still looks stuck after a redirect (envelope, 12 tool calls). Press+> Esc to interrupt it.++It never stops a turn itself; whether to stop is up to you. Where that line appears, and how you+stop, differ by agent and mode:++| | Claude Code | Codex | Copilot CLI | Pi |+|---|---|---|---|---|+| **Interactive: the line appears** | in Claude's reply: the plugin asks Claude to repeat it word for word; the detailed transcript (**Ctrl+O**) always has it | in the conversation ("↳ Hook · TokenEconomizer: …") | in the conversation ("● TokenEconomizer: …") | as a notification |+| **Interactive: to stop** | **Esc** | **Esc**, then `/stop` to end a command it left running | **Esc** twice | **Esc** |+| **Headless: the line appears** | in Claude's final reply, so in the text output; also as a `hook_response` event with `--output-format stream-json --verbose` | nowhere: `codex exec` prints no hook messages | on stdout | on stderr |+| **Headless: to stop** | **Ctrl+C** (ends the run and its command) | **Ctrl+C** (ends the run and its command) | **Ctrl+C** (ends the run and its command) | **Ctrl+C** ends the run; a command it started runs on until it finishes |++Claude Code can keep a plugin's own lines to its detailed transcript, which is why the line+reaches you there through Claude: it is a request to the model, so a model may word it+differently or leave it out. In a headless run nobody may be watching, so a turn the guard+flagged keeps running until it ends by itself or reaches the agent's own limits. `te status` counts the redirects and the+"still stuck" notices afterwards. `loopguard=stop`, with which earlier versions stopped a+headless turn on Claude Code and Pi, is still accepted and works as `nudge`, with a warning.## Repositorydiff --git a/docs/PLUGIN.md b/docs/PLUGIN.mdindex c234543..902cb52 100644--- a/docs/PLUGIN.md+++ b/docs/PLUGIN.md@@ -13,10 +13,10 @@ the hooks run) and `plugin/` (the packaging for each agent). To install and use| Hook | What the plugin does | Mechanism it drives ||---|---|---|-| `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 |+| `SessionStart` | Injects the repository's micro-skills (a cached render) as `additionalContext`; announces changed facts, tools the deny list newly left out, or a proposal still waiting, each 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 |+| `PostToolUse` | Folds the call into the turn's guard; delivers a redirect as `additionalContext`, then, if the turn is still stuck, a one-line notice to the person (on Claude Code, also as context asking the model to repeat it); never stops the turn | loopguard |+| `PostToolUseFailure` | The same, for a call that failed (Claude Code and Copilot report a failed call only here); the answer names this event, as Claude Code requires | 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 |@@ -27,7 +27,8 @@ flow — `SpiralState.update`, `assess_abort`, `is_stuck`, `nudge_text`, the cumone 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 loop+ source file, an inline Python script that writes a file back, `patch`/`git apply`, Codex's+ `apply_patch <<'PATCH'`. The loopstate counts only edit tools, and agents that edit through Bash then looked as if they hadedited nothing.* **The nudge always comes before the stop.** The benchmark ladder checks a hard backstop (a@@ -52,11 +53,11 @@ Every hook fails open: any error becomes an empty output (no change) and a trace| 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) |+| Tool removal | `--disallowed-tools` / Codex config at launch | a **deny list**, applied by default once the evidence forms it and announced at the next session start (`toolprune=propose` waits for approval instead), 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) || 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 `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" |+| Still stuck after the redirect | terminal abort, in autonomous runs | a one-line **notice** to the person, ending with how to stop the turn on that agent and in that mode (§3); the plugin never stops a turn, and `loopguard: stop` is read as `nudge` | Not every agent's hooks can stop a turn (Codex and Copilot ignore `continue: false`), and the person decides: the benchmark guard's own design note says "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@@ -72,7 +73,8 @@ and date it was verified on; §5 says what has not been exercised.not found in this environment", and the detached fold priced that session from its transcript.* `PostToolUse` `additionalContext` is followed **in the same turn** — no restart needed.* `PostToolUse` `{"continue": false}` halts the loop after the current tool (one of three- requested commands ran) and the session ends cleanly.+ requested commands ran) and the session ends cleanly. (The plugin no longer uses it: it stops+ no turn on any agent.)* A bare-name `permissions.deny` rule **removes the tool from the session's tool list**, the samelist `--disallowed-tools` produces, whether the rule comes from `--settings` or from aproject's `.claude/settings.local.json`. A plugin's own `settings.json` cannot carry deny rules@@ -140,10 +142,10 @@ Hooks are **trust-gated**: skipped until approved in `/hooks` (stored asThat gate, kebab-case event names and an argv-list handler are why `te_harness` once recordedthat 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 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.+`continue: false` does **not** stop a Codex turn mid-flight, one reason the guard's last rung is+a notice on every agent, 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 pruning — verified on 0.153.1, 2026-10-07** (`codex debug prompt-input` renders asession's prompt input locally, with no model call; `codex features list` prints the effective@@ -255,7 +257,7 @@ isolated `PI_CODING_AGENT_DIR`):* Pi has no hook protocol; `plugin/pi/tokeneconomizer.ts` speaks the dispatcher's on Pi'sbehalf — `session_start`, `before_agent_start`, `tool_result`, `agent_end` and`session_shutdown` each become one `te-hook --host pi` call — and applies the answers with- Pi's own levers: a system-prompt section, a steering message, `ctx.abort()`, a UI notice.+ Pi's own levers: a system-prompt section, a steering message, a UI notice.* End to end: four synthetic Pi session files taught it that bare `pytest` is missing; in a realsession the `<tokeneconomizer>` section appeared in the session's recorded system prompt, themodel answered "Tests should be run with `python -m pytest …` because the `pytest` command is@@ -301,7 +303,7 @@ this plugin's guide step by step (Claude Code 2.1.300, Codex 0.153.1, Copilot CL* The loop guard's redirect reached the model mid-turn on all four; on Pi a `steer` message, andwith `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.+ a notice. (Since 2026-10-21 the second fire is a notice on every agent; see below.)* Paid side calls ran through each agent's own CLI (Copilot's only off BYOK, above) and werecharged 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,@@ -342,6 +344,38 @@ ended and was folded and priced. What the run showed:* Pi announced `pi update --extensions` itself when the repository moved on, and `/te` answeredin its terminal UI with no model call.+**The loop guard on every agent and mode, 2026-10-21** (Claude Code 2.1.306, Codex 0.163.0,+Copilot CLI 1.0.101, Pi 1.3.0; every model through OpenRouter): each agent ran a provoked loop+(an exercise of twelve failing edit-and-test cycles, with a small seeded envelope and pinned+thresholds), in its terminal UI and headless.++* All four got the redirect and then, once, the still-stuck notice; none was stopped.+* Where the notice appears: Claude Code, only in the detailed transcript (Ctrl+O), as+ "PostToolUse:Bash says: …", and in `claude -p` only as a `hook_response` event of+ `--output-format stream-json --verbose`; Codex, in the conversation ("↳ Hook · …"), and nowhere+ under `codex exec`; Copilot, in the conversation and on stdout under `-p`; Pi, as a notification+ and on stderr under `-p`. The redirect's own announcement showed only in Claude Code's detailed+ transcript, on `copilot -p`'s stdout and on `pi -p`'s stderr.+* How a person stops a turn, each checked on a running `sleep`: Claude Code, **Esc** (the command+ is killed too); Codex, **Esc** interrupts the turn but its command runs on as a background+ terminal until `/stop`; Copilot, **Esc** twice; Pi, **Esc**. Headless, Ctrl+C ends `claude -p`,+ `codex exec` and `copilot -p` with their commands, and `pi -p` while its command, started+ detached, runs on until it finishes. The notice ends with the agent's way (`hosts.stop_hint`).+* Then, since Claude Code hid its own line, the plugin there also asks the model to repeat the+ notice word for word (`hosts.relay`). Claude Haiku 5.5 opened its next message and its final+ reply with it, in the terminal UI and under `claude -p`, whose text output then began with it.+ On the way, found and fixed: Claude Code rejects an answer to a failed call that names+ `PostToolUse` ("Hook returned incorrect event name: expected 'PostToolUseFailure' but got+ 'PostToolUse'") and drops it, so a redirect or notice that fell on a failed call, as in a+ failing test run, was lost there; an answer now names the event it answers. Answering a failed+ call, the hook's own line also showed under the call without Ctrl+O.+* Telling headless from interactive: Claude Code's environment says so, and Pi's extension; Codex+ only in its rollout's first record (`source: "exec"`); Copilot only in its own command line+ (`copilot -p`), its payloads, environment and session log being the same in both modes.+* Found and fixed: Codex 0.163.0 edits with `apply_patch <<'PATCH'` and runs the tests in the+ same command, and the guard counted none of its twelve edits, so it never fired; and+ `copilot -p` was told the interactive way to stop.+## 4. State and privacyAll state is local, under `$TOKENECONOMIZER_HOME` (default `~/.tokeneconomizer`), one directory@@ -364,7 +398,9 @@ Which repository a session belongs to (`plugin/paths.py`, `plugin/repos.py`):every later hook, and the fold it hands off, uses the repository it started in -- where theagent files its own session log. `te status` run inside a session says so when the two differ.* **Deny lists stay per checkout.** The clones of a repository share its evidence and proposal,- but each has its own settings file, so `untool_applied.json` records what was added per file.+ but each has its own settings file, so `untool_applied.json` records per file what was added,+ and what the person gave back with `restore`: `toolprune: auto`, the default, never applies that+ again (an explicit `toolprune apply NAME` does), as the evidence would keep proposing it.* **State from earlier keys is carried over.** Up to 0.1.0 a checkout's folder name was part ofthe key, any `.git` entry made a checkout, and a session was recorded wherever the agent was.The first time a checkout is seen (`index.json`) the state under its earlier keys is sent@@ -401,13 +437,20 @@ not trust.* **Copilot CLI** — the real-model checks used one model (Claude Haiku 4.5, over BYOK). Aper-tool deny list waits on Copilot gaining a persistent per-tool filter.-* **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+* **The loop guard, live** — both rungs have run on a provoked loop on every agent (2026-10-21),+ not on a real spiral, and whether a nudge changes a looping model's course is not established+ (on Pi one run stopped after it, another went on). The guard counts edits andrepeated failures, not understanding, so with a small learned envelope it can fire on a turnthat has already found its cause and is working around it.-* **Pi** — a live nudge and stop (steer message, `ctx.abort()`); tool pruning is not planned there,- since Pi declares only four tools by default.+* **Pi** — tool pruning is not planned there, since Pi declares only four tools by default.* **Known gaps:**+ * A test run whose exit code the model masks (`python3 -m unittest; echo "exit=$?"`, seen on+ Copilot) reads as passing where the agent reports exit codes (Copilot, Codex, Pi), so a turn+ of such runs counts as ended green and is never flagged.+ * `codex exec` prints no hook messages, so a headless Codex run shows no notice; `te status`+ counts it afterwards. On Claude Code the notice reaches the conversation and `claude -p`'s+ output only because the model repeats it, which a model may word differently or leave out;+ the detailed transcript (Ctrl+O) always has it.* A turn that ran no recognised verification counts as ended green, so a failed turn withoutone can enter the envelope and loosen the guard for every later turn.* The free fact layer has no family for "this tool is absent here, with no workingdiff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.jsonindex 9fcb1c6..2f0db27 100644--- a/plugin/.claude-plugin/plugin.json+++ b/plugin/.claude-plugin/plugin.json@@ -2,7 +2,7 @@"name": "tokeneconomizer","displayName": "TokenEconomizer","version": "0.1.0",- "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.",+ "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 that leaves out tools a repository's sessions never use (one command gives them back), and a guard that redirects a turn stuck in a failing loop.","author": {"name": "TokenEconomizer authors"},diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.jsonindex eb0461d..408879e 100644--- a/plugin/.codex-plugin/plugin.json+++ b/plugin/.codex-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "tokeneconomizer","version": "0.1.0",- "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.",+ "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 that turns off capabilities a repository's sessions never use (in the project's .codex/config.toml; one command gives them back), and a guard that redirects a turn stuck in a failing loop.","author": {"name": "TokenEconomizer authors"},diff --git a/plugin/.github/plugin/plugin.json b/plugin/.github/plugin/plugin.jsonindex ee8ceae..15647da 100644--- a/plugin/.github/plugin/plugin.json+++ b/plugin/.github/plugin/plugin.json@@ -1,7 +1,7 @@{"name": "tokeneconomizer","version": "0.1.0",- "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.",+ "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 that turns off MCP servers a repository's sessions never use (one command gives them back), and a guard that redirects a turn stuck in a failing loop.","author": {"name": "TokenEconomizer authors"},diff --git a/plugin/README.md b/plugin/README.mdindex 856139e..9dfa1a6 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -59,16 +59,27 @@ This records which tools a Claude Code session loads, with no model call. Do itmachine, and again after Claude Code updates. **Don't skip it:** without it the deny list seesonly the few tools Claude Code defers, not the ones every session loads.-**4. Work normally.** See [What to expect](#what-to-expect). When the deny list is ready, a-session start says so; then:+**4. Work normally.** See [What to expect](#what-to-expect). Once tools have gone unused for+about five sessions, the plugin leaves them out of the next sessions without asking you, and the+session start says so once:```text-/tokeneconomizer:toolprune # the proposed tools and the evidence-/tokeneconomizer:toolprune apply # accept them, from your next session+/tokeneconomizer:toolprune # the tools it left out, and the evidence+/tokeneconomizer:toolprune restore # give them back, from your next session; they stay back```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.+git, and it never touches deny rules you wrote. To approve each deny list yourself instead:+`/tokeneconomizer:config set toolprune=propose`, then `/tokeneconomizer:toolprune apply`.++**Where its messages appear.** Claude Code 2.1.306 shows the plugin's one-line messages (facts+added, tools left out) only in its detailed transcript: press **Ctrl+O**, where they read+`<event> says: TokenEconomizer: …`. A turn that still looks stuck is the exception:+the plugin also asks Claude to repeat that line word for word, so it shows in Claude's reply,+and under `claude -p` in its final reply. That is a request to the model, which may word it+differently or leave it out; the detailed transcript always has it. To stop a turn, press+**Esc**; under `claude -p`, Ctrl+C ends the run. With `--output-format stream-json --verbose`+every message also arrives as a `hook_response` event.Each slash command is one model turn. The same commands are free from a terminal, as`~/.tokeneconomizer/bin/te --host claude <command>` run inside the repository@@ -81,7 +92,7 @@ shows the old behaviour, run `claude plugin update tokeneconomizer@tokeneconomiz**Uninstall.**-1. In each repository where you accepted a deny list: `/tokeneconomizer:toolprune restore`.+1. In each repository where the plugin left tools out: `/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@@ -113,17 +124,21 @@ read-only, so Codex asks first: choose **Yes, proceed**. From a terminal, inside`~/.tokeneconomizer/bin/te --host codex <command>` (the launcher appears after the firstsession).-**4. Work normally.** See [What to expect](#what-to-expect). Codex's deny list removes the+**4. Work normally.** See [What to expect](#what-to-expect). Codex's deny list turns off thesub-agent (`collaboration`), `goals` and image (`image_media`) packages, each only after it wentunused in every session where it was loaded; a package you used even once is kept. It iswritten 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.+(the session start that announces it says so otherwise), and never into one your repository+commits: that stays a proposal, and the session start says why. The web, asking you questions+and the bundled skills are never turned off. `$tokeneconomizer:toolprune restore` gives the+packages back, and `toolprune measure` shows the difference with no model call.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. Quitting Codex's interactive mode (`/exit`) keeps the+there; a loop guard redirect still reaches the model. In the terminal UI a turn that is still+stuck after the redirect shows "↳ Hook · TokenEconomizer: … Press Esc to interrupt it, then /stop+to end a command it left running": Esc interrupts the turn, but a command it started keeps+running in the background until `/stop`. Under `codex exec`, Ctrl+C ends the run and its command.+Quitting Codex's interactive mode (`/exit`) keeps thesession open to `codex resume` and sends no session end, so the plugin learns from it at a latersession start, once it has been quiet for ten minutes; `codex exec` sessions are learned fromas they end.@@ -133,7 +148,7 @@ again to refresh Codex's installed copy (your hook approval is kept).**Uninstall.**-1. In each repository where you accepted a deny list:+1. In each repository where the plugin turned packages off:`~/.tokeneconomizer/bin/te --host codex toolprune restore` (it leaves an empty `.codex/`).2. `codex plugin remove tokeneconomizer@tokeneconomizer`, then`codex plugin marketplace remove tokeneconomizer`.@@ -175,21 +190,23 @@ commands work only in interactive mode; the plugin's notices also appear under `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+single built-in tool, only one that turns off a whole MCP server, so the deny list turns off aserver 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.+signed in to GitHub. It is written to `.github/copilot/settings.local.json`, and the next session+start says so; `/tokeneconomizer:toolprune restore` turns the server back on. `toolprune+measure` shows the difference with no model call.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.+launcher appears after the first session). A turn that is still stuck after the loop guard's+redirect shows "● TokenEconomizer: …" in the conversation (and on stdout under `copilot -p`); press+**Esc** twice to interrupt it, or Ctrl+C to end a `copilot -p` run.**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`.+1. In each repository where the plugin turned a server off: `/tokeneconomizer:toolprune restore`.2. `copilot plugin uninstall tokeneconomizer@tokeneconomizer`, then`copilot plugin marketplace remove tokeneconomizer`.3. Optional: `rm -rf ~/.tokeneconomizer`.@@ -250,7 +267,9 @@ pi install git:github.com/microsoft/TokenEconomizer**2. Check it.** Start a new Pi session and type `/te status`. The commands are `/te status`,`/te microskills`, `/te config …` and `/te repos`; 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.+tools. In print and JSON modes the plugin's notices go to stderr. A turn that is still stuck+after the loop guard's redirect gets a notice: press **Esc** to abort it, or Ctrl+C to end a+`pi -p` run (a command Pi started then runs on until it finishes).**3. Work normally.** See [What to expect](#what-to-expect).@@ -265,13 +284,17 @@ from); `pi config` turns it off without removing it. Optional: `rm -rf ~/.tokeneconfirming ones, among at least four where it applied), and is injected at every session startafter that while the failure keeps occurring or keeps being prevented. A session start thatadds 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`.+- **Deny list.** Applied without asking you, after about five sessions in which a tool, package+ or server went unused, from the next session on; that session's start says so once. `toolprune restore` gives+ back what the plugin removed, and only that, and what you give back is never removed again+ (`toolprune apply NAME` removes one again). With `toolprune=propose`, it is only proposed, the+ session start says so, and nothing changes until you run `toolprune apply`. 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).+ repository's usual length, one redirect is attached to a tool result; if the turn is still stuck+ after it, a one-line notice tells you how to stop it. The plugin never stops a turn itself.+ Where the notice appears, and how to stop, on each agent and in each mode:+ [When a turn gets stuck](../README.md#when-a-turn-gets-stuck).- **Cost.** `status` shows each session's tokens, priced after it ends, and the plugin's ownoverhead, which is zero unless you turn on the paid helpers.@@ -281,9 +304,9 @@ from); `pi config` turns it off without removing it. Optional: `rm -rf ~/.tokene|---|---|| `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` | the deny list: what it left out, what it would leave out next, and the evidence |+| `toolprune apply [ITEM …]` | apply a waiting proposal (with `toolprune=propose`), or the named items; from the next session |+| `toolprune restore [ITEM …]` | give back the plugin's entries (all, or the named ones); they are not removed again || `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 |@@ -335,14 +358,14 @@ and are shared by every agent working in it. The examples use Claude Code's form| 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) |+| Tool pruning | `toolprune` | `auto`: applied as soon as it forms, from the next session, and announced | `off`; `propose`: only proposed, applied when you run `toolprune apply` |+| Loop guard | `loopguard` | `nudge`: one mid-turn redirect, then a notice to you if the turn is still stuck | `off`; `stop` (which once stopped a headless turn on Claude Code and Pi) is read as `nudge`, with a warning |**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 toolprune_evidence=10 # wait for ten unused sessions/tokeneconomizer:config set loopguard_nudges=2 loopguard.min_turns=30/tokeneconomizer:config unset loopguard.min_turns # back to the default```@@ -352,9 +375,9 @@ and are shared by every agent working in it. The examples use Claude Code's form| `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) |+| `toolprune_evidence` | `5` | sessions a tool must go unused before it is left out (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_nudges` | `1` | redirects per prompt-turn before the guard only notifies you || `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@@ -373,7 +396,7 @@ wins over both. Defaults at each preset:| `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 |+| `backstop_mult` | 3.5 | 2.5 | 1.8 | past this multiple of the envelope, a stuck turn is redirected, then flagged to you || `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 |@@ -406,10 +429,10 @@ deny list at the next session start. A new fact-size cap shows once the next ses**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.+variables `TE_INJECT`, `TE_UNTOOL`, `TE_SPIRAL`, ...; all of them are still read (`spiral=guard` as+`loopguard=stop`, which now works as `nudge`), 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@@ -474,7 +497,7 @@ way, and only when you run it.| 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 `toolprune refresh-catalog` (Claude Code, Copilot) |+| the deny list leaves nothing out 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/toolprune/SKILL.md b/plugin/codex-skills/toolprune/SKILL.mdindex 703ed39..9abe8eb 100644--- a/plugin/codex-skills/toolprune/SKILL.md+++ b/plugin/codex-skills/toolprune/SKILL.md@@ -1,7 +1,7 @@---name: "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.+ Review, undo or apply TokenEconomizer's deny 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 restore or apply it.---# TokenEconomizer: toolprunediff --git a/plugin/pi/tokeneconomizer.ts b/plugin/pi/tokeneconomizer.tsindex dfc3aa7..a30dec0 100644--- a/plugin/pi/tokeneconomizer.ts+++ b/plugin/pi/tokeneconomizer.ts@@ -12,8 +12,8 @@* `tokeneconomizer` system-prompt section, on every* prompt, because Pi diffs sections between runs and* an omitted one would be recorded as removed- * tool_result -> PostToolUse the guard; a nudge is delivered as a steering- * message, a stop as ctx.abort()+ * tool_result -> PostToolUse the guard; a redirect is delivered as a steering+ * message, a still-stuck notice as a UI notice* agent_end -> Stop closes the turn* session_shutdown -> SessionEnd hands the session to a detached fold*@@ -169,10 +169,6 @@ export default function tokeneconomizer(pi: ExtensionAPI) {pi.sendMessage({ customType: SECTION, content: nudge, display: true }, { deliverAs: "steer" });}notify(ctx, out?.systemMessage);- if (out?.continue === false) {- notify(ctx, out?.stopReason);- ctx.abort();- }});pi.on("agent_end", async (_event, ctx) => {diff --git a/plugin/slash-commands/toolprune.md b/plugin/slash-commands/toolprune.mdindex 436bcd9..deba614 100644--- a/plugin/slash-commands/toolprune.md+++ b/plugin/slash-commands/toolprune.md@@ -1,5 +1,5 @@----description: Review or apply TokenEconomizer's proposed deny list of tools this repository never uses+description: Review the tools TokenEconomizer left out of this repository's sessions, give them back, or apply a waiting proposalargument-hint: "[show | apply [TOOL ...] | restore [TOOL ...] | refresh-catalog | measure]"---The arguments I typed after the command are: "$ARGUMENTS" (it shows the proposal when there are none).diff --git a/plugin/slash-commands/untool.md b/plugin/slash-commands/untool.mdindex c1c73cd..289ef14 100644--- a/plugin/slash-commands/untool.md+++ b/plugin/slash-commands/untool.md@@ -1,5 +1,5 @@----description: Earlier name of /tokeneconomizer:toolprune - review or apply the proposed deny list+description: Earlier name of /tokeneconomizer:toolprune - review the deny list, give tools back, or apply a proposalargument-hint: "[show | apply [TOOL ...] | restore [TOOL ...] | refresh-catalog | measure]"---The arguments I typed after the command are: "$ARGUMENTS" (it shows the proposal when there are none).diff --git a/tests/test_live_config.py b/tests/test_live_config.pyindex efbcdde..fc37425 100644--- a/tests/test_live_config.py+++ b/tests/test_live_config.py@@ -17,7 +17,7 @@ from tests.test_live_hooks import (GREEN, _first, _turn, env, repo, run_session,# ---- parsing ------------------------------------------------------------------------------[email protected]("key,on", [("microskills", "envfacts"), ("toolprune", "propose"),[email protected]("key,on", [("microskills", "envfacts"), ("toolprune", "auto"),("loopguard", "nudge")])def test_each_mechanism_takes_a_plain_on_and_off(key, on):cfg = LiveConfig()@@ -192,3 +192,14 @@ def test_injection_off_and_a_tight_fact_cap_keep_the_context_clean(env, repo, tmrun_session(tight, repo, "s5", trap_session(str(tmp_path / "s5.jsonl"), repo, 5))after = run_session(tight, repo, "s6", trap_session(str(tmp_path / "s6.jsonl"), repo, 6))assert "hookSpecificOutput" not in after+++def test_loopguard_stop_is_still_read_and_acts_as_nudge_with_a_warning(tmp_path):+ """`stop` once stopped a headless turn on Claude Code and Pi; the plugin no longer stops a+ turn on any agent, so an existing `stop` (or the old `spiral=guard`) keeps working as the+ redirect-then-notice ladder, and says so."""+ for env in ({"TE_LOOPGUARD": "stop"}, {"TE_SPIRAL": "guard"}):+ cfg = load_config(str(tmp_path), env=env)+ assert cfg.loopguard == "stop"+ assert any("loopguard=stop acts as nudge" in w for w in cfg.warnings)+ assert not load_config(str(tmp_path), env={"TE_LOOPGUARD": "nudge"}).warningsdiff --git a/tests/test_live_core.py b/tests/test_live_core.pyindex c1d2160..3472d67 100644--- a/tests/test_live_core.py+++ b/tests/test_live_core.py@@ -284,7 +284,7 @@ COPILOT_FAILURE = {"hook_event_name": "PostToolUseFailure", "session_id": "10bbcdef test_the_copilot_payloads_observed_live_are_read():c = hosts.detect(COPILOT_POST, {"COPILOT_PLUGIN_ROOT": "/p"})- assert c.name == "copilot" and not c.can_stop_mid_turn and c.stop("why") is None+ assert c.name == "copilot"name, args, text, code = c.tool_call(COPILOT_POST)assert (name, args["description"], code) == ("Bash", "run it", 3) # exit code from the textassert text.startswith("boom")@@ -318,7 +318,6 @@ def test_claude_tool_results_and_outputs():assert "1 failed" in text and "Traceback" in textassert h.context("PostToolUse", "x") == {"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": "x"}}- assert h.stop("why") == {"continue": False, "stopReason": "why"}# the hook environment of a `claude -p` session, as observed on 2.1.285assert h.headless({"CLAUDE_CODE_SESSION_ATTENDED": "0", "CLAUDE_CODE_ENTRYPOINT": "sdk-cli"})assert not h.headless({"CLAUDE_CODE_SESSION_ATTENDED": "1", "CLAUDE_CODE_ENTRYPOINT": "sdk-cli"})@@ -338,9 +337,8 @@ def test_the_codex_posttooluse_payload_observed_live_is_read():assert host.tool_call(payload) == ("bash", {"command": "echo one"}, "one\n", None)-def test_codex_tool_calls_normalize_and_never_stop():+def test_codex_tool_calls_normalize():c = hosts.Codex()- assert c.stop("why") is None and not c.can_stop_mid_turnname, args, text, code = c.tool_call({"tool_name": "exec_command", "tool_input": {"command": ["bash", "-lc", "go test ./..."]},"tool_response": {"output": "FAIL", "exit_code": 1}})@@ -447,7 +445,6 @@ def test_pi_usage_maps_directly_and_keeps_pis_own_cost(tmp_path):def test_the_pi_host_reads_what_the_extension_sends():h = hosts.HOSTS["pi"]()- assert h.can_stop_mid_turn and h.stop("why") == {"continue": False, "stopReason": "why"}name, args, text, code = h.tool_call({"tool_name": "bash", "tool_input": {"command": "go test"},"tool_response": {"content": "FAIL\nCommand exited with code 1","isError": True, "exit_code": 1}})@@ -474,6 +471,11 @@ from tokeneconomizer import loopguard as guard # noqa: E402["a.py", "b.py"]),("python - <<'E'\nfrom pathlib import Path\nPath('m/n.py').write_text('x')\nE", ["n.py"]),("git apply /tmp/fix.diff", ["(patch)"]),+ # Codex 0.163.0 edits like this, then tests, in ONE command (seen live)+ ("apply_patch <<'PATCH'\n*** Begin Patch\n*** Update File: pkg/__init__.py\n@@\n- x\n"+ "+ y\n*** End Patch\nPATCH\npython3 -m unittest", ["__init__.py"]),+ ("apply_patch <<'P'\n*** Begin Patch\n*** Add File: a/new.py\n+x\n*** Update File: b/old.py\n"+ "*** End Patch\nP", ["new.py", "old.py"]),("git checkout -- a.py b/c.py", ["a.py", "c.py"]),# not edits: output captures, scratch, reads, and operators inside quotes("python -m pytest -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt", []),@@ -907,3 +909,28 @@ def test_a_runner_named_by_path_counts_as_a_verification(cmd):"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)+++def test_codex_exec_and_copilot_p_are_told_from_their_terminal_uis(tmp_path, monkeypatch):+ """The still-stuck notice names the headless way to stop in `codex exec` and `copilot -p`.+ Codex says how a session was started only in its rollout's first record; Copilot only in its+ own command line (0.163.0, 1.0.101: the hook payloads and environments are the same)."""+ exec_log, tui_log = tmp_path / "rollout-exec.jsonl", tmp_path / "rollout-tui.jsonl"+ exec_log.write_text(json.dumps({"type": "session_meta", "payload": {+ "originator": "codex_exec", "source": "exec"}}) + "\n")+ tui_log.write_text(json.dumps({"type": "session_meta", "payload": {+ "originator": "codex-tui", "source": "vscode"}}) + "\n")+ c = hosts.Codex()+ assert c.headless({}, str(exec_log)) and not c.headless({}, str(tui_log))+ assert not c.headless({}, None) and not c.headless({}, str(tmp_path / "missing"))+ cp = hosts.Copilot()+ monkeypatch.setattr(hosts, "_ancestor_args", lambda: [+ "/bin/sh /p/scripts/te-hook --host copilot",+ "copilot -p Reply with the word ready. --model claude-haiku-4.5"])+ assert cp.headless({})+ monkeypatch.setattr(hosts, "_ancestor_args", lambda: ["copilot", "sh -c cd ~/proj && copilot"])+ assert not cp.headless({})+ monkeypatch.setattr(hosts, "_ancestor_args", lambda: ["copilot --prompt=fix it"])+ assert cp.headless({})+ assert cp.stop_hint(True) == "Press Ctrl+C to end the run."+ assert cp.stop_hint(False) == "Press Esc twice to interrupt it."diff --git a/tests/test_live_hooks.py b/tests/test_live_hooks.pyindex 874c159..a584ade 100644--- a/tests/test_live_hooks.py+++ b/tests/test_live_hooks.py@@ -16,7 +16,7 @@ import osimport pytest-from tokeneconomizer.plugin import denylist, hook, toolcheck+from tokeneconomizer.plugin import denylist, hook, hosts, toolcheckfrom tokeneconomizer.plugin.controller import LiveControllerfrom tokeneconomizer.plugin.paths import repo_identity, repo_state_dirfrom tokeneconomizer.plugin.store import Store@@ -204,19 +204,67 @@ def test_warm_guard_nudges_then_only_notifies_in_an_interactive_session(env, repassert all(o == {} for o in outs[nudge + 2 + later:]) # the notice is delivered once-def test_a_headless_guard_stops_the_turn_on_claude_but_not_on_codex(env, repo):- headless = dict(env, TE_MODE="headless", TE_SPIRAL="guard")- for k in range(5):- _turn(headless, repo, "s", f"g{k}", GREEN)- outs = _turn(headless, repo, "s", "stuck", stuck_calls(40))- assert any(o.get("continue") is False and "stopped this turn" in o["stopReason"]- for o in outs)+def _guard_turn(env, repo, sid, key, calls, host):+ """One prompt-turn on `host`, each call in that agent's own payload shape."""+ idk = "turn_id" if host == "codex" else "prompt_id"+ base = {"session_id": sid, "transcript_path": "", "cwd": repo}+ if host != "copilot":+ base[idk] = key+ rkey = "tool_result" if host == "copilot" else "tool_response"+ call(env, dict(base, hook_event_name="UserPromptSubmit", prompt="go"), host)+ outs = [call(env, dict(base, hook_event_name="PostToolUse", tool_name=n, tool_input=i,+ **{rkey: r}), host) for n, i, r in calls]+ call(env, dict(base, hook_event_name="Stop", stop_hook_active=False), host)+ return outs+++def _stuck(host, n=40):+ if host in ("claude", "codex"):+ return stuck_calls(n, host if host == "codex" else None)+ fail = "FAILED tests/test_a.py::test_x - AssertionError: assert 1 == 2"+ if host == "pi":+ return [("edit", {"path": "/r/pkg/a.py", "oldText": "x", "newText": "y"}, {"content": "ok"})+ if k % 2 == 0 else ("bash", {"command": "pytest -q"},+ {"content": fail, "isError": True, "exit_code": 1})+ for k in range(n)]+ return [("Edit", {"path": "/r/pkg/a.py"}, {"result_type": "success",+ "text_result_for_llm": "ok"})+ if k % 2 == 0 else ("Bash", {"command": "pytest -q"}, {+ "result_type": "success",+ "text_result_for_llm": fail + "\n<shellId: 0 completed with exit code 1>"})+ for k in range(n)]++[email protected]("host", ["claude", "codex", "copilot", "pi"])[email protected]("mode", ["interactive", "headless"])[email protected]("setting", ["nudge", "stop"])+def test_the_guard_redirects_then_tells_the_person_how_to_stop_on_every_agent(+ env, repo, host, mode, setting):+ """One ladder everywhere: a redirect to the model, then one notice to the person with the+ agent's way to stop the turn. The plugin never stops it -- `stop` is read as `nudge`."""+ env = dict(env, TE_MODE=mode, TE_LOOPGUARD=setting)+ green = [("Read", {"file_path": "/r/a.py"}, "ok")] * 8for k in range(5):- _turn(headless, repo, "c", f"g{k}", GREEN, host="codex")- outs = _turn(headless, repo, "c", "stuck", stuck_calls(40, "codex"), host="codex")- assert any("hookSpecificOutput" in o for o in outs) # nudged- assert not any("continue" in o for o in outs) # Codex cannot stop mid-turn- assert any("still looks stuck" in (o.get("systemMessage") or "") for o in outs)+ _guard_turn(env, repo, "s", f"g{k}", green, host)+ outs = _guard_turn(env, repo, "s", "stuck", _stuck(host), host)+ ctx_key = (lambda o: o.get("additionalContext")) if host == "copilot" else (+ lambda o: (o.get("hookSpecificOutput") or {}).get("additionalContext"))+ shown = (lambda o: " ".join(o.get("progress") or [])) if host == "copilot" else (+ lambda o: o.get("systemMessage") or "")+ to_model = [ctx_key(o) for o in outs if ctx_key(o)]+ stuck = [shown(o) for o in outs if "still looks stuck" in shown(o)]+ assert len(stuck) == 1 # one notice+ hint = hosts.HOSTS[host]().stop_hint(mode == "headless")+ assert stuck[0].endswith(hint)+ assert not any("continue" in o or "stopReason" in o for o in outs) # never a stop+ if host == "claude":+ # Claude Code keeps hook messages out of the main view, so the notice also goes to the+ # model, word for word, to pass on in its reply; the redirect comes first.+ redirect, relay = to_model+ assert "Process check (automated)" in redirect+ assert stuck[0] in relay and "it does not change your task" in relay+ else:+ assert len(to_model) == 1 # the redirect alonedef _fake_judges(monkeypatch, seen):@@ -295,7 +343,9 @@ def _catalog(env, tools):json.dump({"tools": tools}, open(os.path.join(d, "catalog.json"), "w"))-def test_unused_tools_are_proposed_but_nothing_changes_until_applied(env, repo, tmp_path):+def test_with_propose_unused_tools_are_proposed_but_nothing_changes_until_applied(+ env, repo, tmp_path):+ env = dict(env, TE_TOOLPRUNE="propose")_catalog(env, ["Bash", "Read", "Edit", "Write", "AskUserQuestion", "Workflow","CronCreate", "ShareOnboardingGuide", "WebFetch"])for i in range(5):@@ -313,6 +363,63 @@ def test_unused_tools_are_proposed_but_nothing_changes_until_applied(env, repo,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:toolprune" in notice+ assert "nothing changes until you run `/tokeneconomizer:toolprune apply`" in notice+++def test_by_default_unused_tools_are_removed_from_the_next_session_and_it_says_so(+ env, repo, tmp_path):+ """`toolprune=auto` is the default: the fold that forms the proposal writes it, the next+ session start says so once, and `restore` gives the tools back."""+ _catalog(env, ["Bash", "Read", "Edit", "Write", "AskUserQuestion", "Workflow",+ "CronCreate", "ShareOnboardingGuide", "WebFetch"])+ for i in range(5):+ t = write_session(str(tmp_path / f"u{i}.jsonl"), [("look", [+ ("Read", {"file_path": f"{repo}/a.py"}, "x", False),+ ("Bash", {"command": "ls"}, "a.py", False)])])+ run_session(env, repo, f"u{i}", t)+ st = store_for(env, repo)+ deny = json.load(open(denylist.settings_path(repo)))["permissions"]["deny"]+ assert sorted(deny) == ["CronCreate", "ShareOnboardingGuide", "Workflow"]+ assert st.read("untool.json")["proposal"] == []+ t = str(tmp_path / "next.jsonl")+ open(t, "w").close()++ def start(sid):+ return call(env, {"hook_event_name": "SessionStart", "session_id": sid,+ "source": "startup", "transcript_path": t, "cwd": repo})+ notice = start("n1")["systemMessage"]+ assert "removed 3 tool(s) this repository's sessions never used" in notice+ assert "`/tokeneconomizer:toolprune restore` gives them back" in notice+ assert "systemMessage" not in start("n2") # said once+++def test_tools_given_back_stay_back_until_named_again(env, repo, tmp_path, monkeypatch, capsys):+ """Under the default `auto`, `restore` must stick: the evidence still says the tools go+ unused, and the next fold would otherwise take them away again."""+ from tokeneconomizer.plugin import cli+ for k, v in env.items():+ monkeypatch.setenv(k, v)+ _catalog(env, ["Bash", "Read", "Workflow", "CronCreate"])++ def sessions(prefix, n):+ for i in range(n):+ t = write_session(str(tmp_path / f"{prefix}{i}.jsonl"), [("look", [+ ("Bash", {"command": "ls"}, "a.py", False)])])+ run_session(env, repo, f"{prefix}{i}", t)+ sessions("a", 5)+ def deny():+ return json.load(open(denylist.settings_path(repo))).get("permissions", {}).get("deny", [])+ assert sorted(deny()) == ["CronCreate", "Workflow"]+ assert cli.main(["--host", "claude", "--cwd", repo, "toolprune", "restore"]) == 0+ assert "kept from now on" in capsys.readouterr().out and deny() == []+ sessions("b", 6) # still unused, still kept+ assert deny() == []+ assert cli.main(["--host", "claude", "--cwd", repo, "toolprune", "show"]) == 0+ out = capsys.readouterr().out+ assert "proposed: -" in out and "kept, as you gave them back" in out+ assert cli.main(["--host", "claude", "--cwd", repo, "toolprune", "apply", "Workflow"]) == 0+ assert deny() == ["Workflow"]+ assert denylist.kept_for(store_for(env, repo), repo) == ["CronCreate"]def test_the_web_is_never_proposed_and_an_old_deny_rule_for_it_is_given_back(@@ -486,18 +593,17 @@ def test_pi_learns_from_its_own_session_files_and_injects_at_the_next_start(env,assert rec["requests"] == 3 and rec["priced_by"] == "model"-def test_a_headless_pi_turn_that_keeps_spinning_is_stopped(env, repo):- headless = dict(env, TE_PI_MODE="print", TE_SPIRAL="guard")+def test_pi_print_mode_counts_as_headless_for_the_stop_hint(env, repo):+ """Pi says its mode through the extension (`TE_PI_MODE`); a print-mode notice names the+ headless way to stop."""+ penv = dict(env, TE_PI_MODE="print")for k in range(5):- _turn(headless, repo, "p", f"g{k}", [("read", {"path": "/r/a.py"}, {"content": "ok"})] * 8,- host="pi")- fail = {"content": "FAILED tests/test_a.py::test_x - AssertionError\nCommand exited with code 1",- "isError": True, "exit_code": 1}- calls = [("edit", {"path": "/r/pkg/a.py", "oldText": "x", "newText": "y"}, {"content": "ok"})- if k % 2 == 0 else ("bash", {"command": "pytest -q"}, fail) for k in range(40)]- outs = _turn(headless, repo, "p", "stuck", calls, host="pi")- assert any("hookSpecificOutput" in o for o in outs)- assert any(o.get("continue") is False for o in outs)+ _guard_turn(penv, repo, "p", f"g{k}",+ [("read", {"path": "/r/a.py"}, {"content": "ok"})] * 8, "pi")+ outs = _guard_turn(penv, repo, "p", "stuck", _stuck("pi"), "pi")+ notice = next(o["systemMessage"] for o in outs+ if "still looks stuck" in o.get("systemMessage", ""))+ assert notice.endswith(hosts.HOSTS["pi"]().stop_hint(True))# ---- GitHub Copilot CLI, through the payloads it sends -------------------------------------@@ -571,6 +677,7 @@ def _copilot_catalog(env, tools):def test_copilot_proposes_only_whole_unused_mcp_servers(env, repo, tmp_path, monkeypatch):+ env = dict(env, TE_TOOLPRUNE="propose")_copilot_catalog(env, ["bash", "view", "sql", "fetch_copilot_cli_documentation"]+ GITHUB_TOOLS)for i in range(5):@@ -588,6 +695,19 @@ def test_copilot_proposes_only_whole_unused_mcp_servers(env, repo, tmp_path, monassert "1 MCP server(s) went unused" in notice and "/tokeneconomizer:toolprune" in notice+def test_by_default_copilot_turns_off_the_unused_server_and_says_so(env, repo, tmp_path,+ monkeypatch):+ _copilot_catalog(env, ["bash", "view"] + GITHUB_TOOLS)+ for i in range(5):+ copilot_session(env, repo, tmp_path, f"u{i}", [+ ("bash", {"command": "ls"}, "a.py\n<shellId: 0 completed with exit code 0>", True)],+ monkeypatch)+ settings = json.load(open(denylist.settings_path(repo, "copilot")))+ assert settings["disabledMcpServers"] == ["github-mcp-server"]+ (notice,) = copilot_session(env, repo, tmp_path, "n", [], monkeypatch)["progress"]+ assert "removed 1 MCP server(s)" in notice and "toolprune restore" in notice++def test_a_server_whose_tool_was_used_once_is_never_proposed(env, repo, tmp_path, monkeypatch):_copilot_catalog(env, ["bash"] + GITHUB_TOOLS)copilot_session(env, repo, tmp_path, "used", [@@ -639,6 +759,7 @@ def codex_rollout(path, repo, i, exec_inputs=()):def test_codex_proposes_capabilities_it_never_saw_used(env, repo, tmp_path):+ env = dict(env, TE_TOOLPRUNE="propose")for i in range(5):uses = ["await tools.view_image({path: 'a.png'})"] if i == 2 else []t = codex_rollout(str(tmp_path / f"rollout-{i}.jsonl"), repo, i, uses)@@ -728,6 +849,44 @@ def test_a_committed_codex_config_is_never_edited(tmp_path, codex_accepts):assert (r / ".codex" / "config.toml").read_text() == 'model = "gpt-5.6-sol"\n'+def _codex_sessions(env, repo, tmp_path, n=5):+ for i in range(n):+ t = codex_rollout(str(tmp_path / f"rollout-{i}.jsonl"), repo, i)+ run_session(env, repo, f"cx{i}", t, host="codex")+++def _codex_start(env, repo, tmp_path, sid):+ t = codex_rollout(str(tmp_path / f"rollout-{sid}.jsonl"), repo, 99)+ return call(env, {"hook_event_name": "SessionStart", "session_id": sid, "source": "startup",+ "transcript_path": t, "cwd": repo}, "codex")+++def test_by_default_codex_writes_the_unused_capabilities_off_and_says_so(env, repo, tmp_path,+ codex_accepts):+ _codex_sessions(env, repo, tmp_path)+ text = open(denylist.settings_path(repo, "codex")).read()+ assert "include_collaboration_mode_instructions = false" in text and "goals = false" in text+ notice = _codex_start(env, repo, tmp_path, "next")["systemMessage"]+ assert "removed 2 capability(s)" in notice and "toolprune restore" in notice+++def test_a_committed_codex_config_keeps_the_default_a_proposal_and_says_why(tmp_path, env,+ codex_accepts):+ import subprocess+ r = tmp_path / "shared"+ (r / ".codex").mkdir(parents=True)+ (r / ".codex" / "config.toml").write_text('model = "gpt-5.6-sol"\n')+ git = ["git", "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"]+ subprocess.run(["git", "init", "-q", str(r)], check=True)+ subprocess.run(git + ["-C", str(r), "add", ".codex/config.toml"], check=True)+ subprocess.run(git + ["-C", str(r), "commit", "-qm", "team config"], check=True)+ _codex_sessions(env, str(r), tmp_path)+ assert (r / ".codex" / "config.toml").read_text() == 'model = "gpt-5.6-sol"\n'+ notice = _codex_start(env, str(r), tmp_path, "next")["systemMessage"]+ assert "2 capability(s) went unused" in notice and "could not be applied" in notice+ assert "is committed in this repository" in notice++def test_codex_never_overrides_a_key_the_user_set(tmp_path):text, did = denylist._toml_insert('[features]\ngoals = true\n', "features", "goals", "false","# t")@@ -839,3 +998,28 @@ def test_a_loop_the_agent_reports_only_as_failures_is_nudged(env, repo):"test_x - AssertionError: assert 1 == 2", True))outs = _claude_turn(env, repo, "s", "stuck", calls)assert any("hookSpecificOutput" in o for o in outs)+++def test_an_answer_to_a_failed_call_names_the_failure_event(env, repo):+ """Claude Code reports a failing command as PostToolUseFailure and rejects an answer whose+ `hookEventName` says PostToolUse ("Hook returned incorrect event name", 2.1.306), dropping+ the redirect and the notice with it -- and a stuck turn's calls are mostly failures."""+ green = [("Read", {"file_path": "/r/a.py"}, "ok")] * 8+ for k in range(5):+ _turn(env, repo, "s", f"g{k}", green)+ base = {"session_id": "s", "transcript_path": "", "cwd": repo, "prompt_id": "stuck"}+ call(env, dict(base, hook_event_name="UserPromptSubmit", prompt="go"))+ answered = []+ for k in range(40):+ if k % 2 == 0:+ p = dict(base, hook_event_name="PostToolUse", tool_name="Edit", tool_response="ok",+ tool_input={"file_path": "/r/pkg/a.py", "old_string": "x", "new_string": "y"})+ else:+ p = dict(base, hook_event_name="PostToolUseFailure", tool_name="Bash",+ tool_input={"command": "pytest -q"},+ error="Exit code 1\nFAILED tests/test_a.py::test_x - AssertionError")+ o = call(env, p)+ if "hookSpecificOutput" in o:+ answered.append((p["hook_event_name"], o["hookSpecificOutput"]["hookEventName"]))+ assert answered and all(sent == named for sent, named in answered)+ assert any(sent == "PostToolUseFailure" for sent, _ in answered)diff --git a/tokeneconomizer/loopguard/shell_edits.py b/tokeneconomizer/loopguard/shell_edits.pyindex a6ed178..491117e 100644--- a/tokeneconomizer/loopguard/shell_edits.py+++ b/tokeneconomizer/loopguard/shell_edits.py@@ -2,8 +2,9 @@`SpiralState` counts an edit only when an edit TOOL makes it (Edit/Write/str_replace). An agentthat 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.+inline Python script that writes the file back, `patch`/`git apply`, Codex's `apply_patch` fed a+patch on stdin -- 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 themafter the regular update, so the call still counts once."""@@ -28,6 +29,9 @@ _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)\(")+# Codex's patch format, as `apply_patch <<'PATCH'` takes it on stdin (seen live on 0.163.0, the+# edit and the test run in one command); `trace.codex` reads the same lines from a session log.+_PATCH_FILE = re.compile(r"^\*\*\* (?:Update|Add|Delete) File:\s*(.+?)\s*$", re.M)def _not_scratch(path):@@ -165,6 +169,8 @@ def shell_edit_targets(cmd):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 == "apply_patch":+ found += _PATCH_FILE.findall("\n".join(bodies + [" ".join(tokens[1:])])) or ["(patch)"]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"):diff --git a/tokeneconomizer/loopguard/turn.py b/tokeneconomizer/loopguard/turn.pyindex 67abbb9..21185bd 100644--- a/tokeneconomizer/loopguard/turn.py+++ b/tokeneconomizer/loopguard/turn.py@@ -4,8 +4,9 @@ Each tool call arrives as a separate hook process, so the guard's state is on dicalls (`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.+redirect, a later one with a stop verdict (which the plugin delivers as a notice to the person,+never as 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 personalready splits work into short turns, and a whole session folded as one trajectory looksdiff --git a/tokeneconomizer/plugin/cli.py b/tokeneconomizer/plugin/cli.pyindex c699aaf..c7d76c7 100644--- a/tokeneconomizer/plugin/cli.py+++ b/tokeneconomizer/plugin/cli.py@@ -165,7 +165,8 @@ def cmd_status(args):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")+ f"{ledger['nudges']} redirect(s), {ledger['aborts']} still-stuck notice(s) over "+ f"{ledger['turns']} turns")return 0@@ -193,6 +194,10 @@ def _toolprune_show(ctx, unt):f"{denylist.settings_path(ctx.repo.root, host)}): "f"{', '.join(denylist.applied_for(ctx.store, ctx.repo.root, host)) or '-'}")print(f"proposed: {', '.join(_proposal(ctx, unt)) or '-'}")+ kept = denylist.kept_for(ctx.store, ctx.repo.root, host)+ if kept:+ print(f"kept, as you gave them back (`toolprune apply NAME` removes one again): "+ f"{', '.join(kept)}")if host == "codex":caps = unt.get("capabilities") or {}if caps:@@ -232,9 +237,10 @@ def _toolprune_show(ctx, unt):def _proposal(ctx, unt):- """The proposal, less what this checkout already applied: the clones of one repository share- its evidence, and one of them may have applied the list before another."""+ """The proposal, less what this checkout already applied or gave back: the clones of one+ repository share its evidence, and one of them may have applied the list before another."""mine = set(denylist.applied_for(ctx.store, ctx.repo.root, ctx.host.name))+ mine |= set(denylist.kept_for(ctx.store, ctx.repo.root, ctx.host.name))return [t for t in unt.get("proposal", []) if t not in mine]@@ -266,6 +272,8 @@ def cmd_toolprune(args):except RuntimeError as e:print(f"not applied: {e}")return 1+ # Named by the person: no longer one they gave back, whatever `restore` said before.+ denylist.set_kept(ctx.store, ctx.repo.root, host, remove=tools)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.")@@ -297,7 +305,12 @@ def cmd_toolprune(args):except RuntimeError as e:print(f"not restored: {e}")return 1- print(f"removed: {', '.join(removed) or '-'} (from the next session)")+ # Given back by the person: `toolprune: auto` must not take them away again at the next+ # fold, and a proposal does not ask for them again.+ denylist.set_kept(ctx.store, ctx.repo.root, host, add=removed)+ print(f"removed: {', '.join(removed) or '-'} (from the next session)"+ + (f"; kept from now on (`toolprune apply {removed[0]}` removes one again)"+ if removed else ""))return 0if action == "refresh-catalog":if host == "codex":@@ -417,10 +430,9 @@ def cmd_config(args):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")+ if cur.get("loopguard") == "stop":+ print("note: `stop` acts as `nudge`: the plugin never stops a turn; a turn still stuck "+ "after the redirect gets a notice saying how to stop it")return 0diff --git a/tokeneconomizer/plugin/config.py b/tokeneconomizer/plugin/config.pyindex d3423a7..5a7f7f2 100644--- a/tokeneconomizer/plugin/config.py+++ b/tokeneconomizer/plugin/config.py@@ -1,16 +1,19 @@"""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:+The defaults:* 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;+ * toolprune = "auto" -- a deny list is applied as soon as the evidence forms it, from+ the next session, and announced once at that session's start;+ `toolprune restore` gives it back. "propose" only proposes it,+ and writes nothing to the agent's settings until the person+ runs `toolprune apply`;+ * loopguard = "nudge" -- at most one mid-turn redirect per prompt-turn; a turn still+ stuck after it gets a notice to the person, saying how to stop+ it. The plugin never stops a turn itself. "stop", which used to+ stop a headless turn on Claude Code and Pi, is still read, and+ acts as "nudge" with a warning;* paid = False -- no mechanism makes an LLM call of its own. Every paid call that isallowed is charged to the session's ledger;* shadow = False -- with True, every decision is computed and logged but none@@ -24,7 +27,7 @@ person can tune by hand:* 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_nudges -- redirects per prompt-turn before the guard only notifies;* loopguard.<name> -- one guard threshold, pinned over the preset and over what therepository's history learned (LOOPGUARD_KEYS);* repomap, repomap_tokens, repomap_python, repomap_timeout -- the opt-in repository map.@@ -53,7 +56,7 @@ 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",+ON_VALUE = {"microskills": "envfacts", "toolprune": "auto", "loopguard": "nudge","repomap": "on"}_ON = ("on", "true", "yes", "1", "enable", "enabled")_OFF = ("off", "false", "no", "0", "disable", "disabled")@@ -119,7 +122,7 @@ class LiveConfig:microskills_max_facts: int = 4microskills_max_tokens: int = 150microskills_propose_every: int = 5- toolprune: str = "propose"+ toolprune: str = "auto"toolprune_evidence: int = 5loopguard: str = "nudge"loopguard_aggr: str = "default"@@ -272,6 +275,10 @@ def load_config(root, repo_dir=None, env=None):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.loopguard == "stop":+ cfg.warnings.append("loopguard=stop acts as nudge: the plugin no longer stops a turn; a "+ "turn still stuck after the redirect gets a notice saying how to stop "+ "it (set loopguard=nudge to silence this)")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}")diff --git a/tokeneconomizer/plugin/context.py b/tokeneconomizer/plugin/context.pyindex a75c2d7..ec64057 100644--- a/tokeneconomizer/plugin/context.py+++ b/tokeneconomizer/plugin/context.py@@ -27,11 +27,16 @@ class LiveContext:@propertydef headless(self):+ return self.is_headless()++ def is_headless(self, transcript=None):+ """Whether nobody is at the agent's own UI: `mode` when set, else what the agent shows+ (its environment, its session log at `transcript`, its process)."""if self.config.mode == "headless":return Trueif self.config.mode == "interactive":return False- return self.host.headless(self.env)+ return self.host.headless(self.env, transcript)@classmethoddef build(cls, host, cwd, env=None, session_id=None, settle=True):diff --git a/tokeneconomizer/plugin/controller.py b/tokeneconomizer/plugin/controller.pyindex e9447e3..acf716c 100644--- a/tokeneconomizer/plugin/controller.py+++ b/tokeneconomizer/plugin/controller.py@@ -5,7 +5,8 @@with `repomap` on, refresh a stale map in the backgroundUserPromptSubmit open a prompt-turn for the loop guard; on a session's first prompt, addthe repository map (`repomap=on`)- PostToolUse fold the call into the turn's guard; nudge, or stop, when it says so+ PostToolUse fold the call into the turn's guard; a redirect when it first says the+ turn is stuck, then a notice to the person saying how to stop itStop close the turn; an ended-green turn feeds the repository's envelopeSessionEnd hand the session to a detached `te fold`@@ -98,6 +99,7 @@ class LiveController:s.setdefault("cwd", self.host.cwd(self.p, self.ctx.env))outputs = []seen = self.store.read("notices.json") or {}+ seen_before = dict(seen)if self.cfg.microskills != "off":inj = self.store.read("injection.json") or {}@@ -120,20 +122,9 @@ class LiveController:f"(review with `{self._cmd('microskills')}`)."))seen["injection"] = digest- if (self.cfg.toolprune == "propose" and denylist.supports(self.host.name)+ if (self.cfg.toolprune != "off" and denylist.supports(self.host.name)and not self.cfg.shadow):- # What this checkout already applied is no news here (another clone may not have).- mine = set(denylist.applied_for(self.store, self.ctx.repo.root, self.host.name))- prop = [t for t in (self.store.read("untool.json") or {}).get("proposal") or []- if t not in mine]- key = ",".join(prop)- if prop and seen.get("untool") != key:- outputs.append(self.host.notice(- 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('toolprune')}`; nothing changes until you apply it."))- seen["untool"] = key+ outputs.extend(self._toolprune_notices(seen))note = repos.migration_notice(self.ctx.root, self._cmd("repos"))if note and not self.cfg.shadow:@@ -148,7 +139,7 @@ class LiveController:"SessionStart", "cached"))s["repomap_done"] = True- if outputs:+ if seen != seen_before:self.store.write("notices.json", seen)self._save(s)repos.note_repo(self.ctx.root, self.ctx.repo)@@ -157,6 +148,44 @@ class LiveController:fold.spawn_fold(self.ctx, fold.pending_sessions(self.ctx, exclude=(self.sid,)))return merge_outputs(*outputs)+ def _toolprune_notices(self, seen):+ """The deny list's lines at session start, each said once: what `auto` removed from this+ checkout's sessions (from this one on), and a proposal still waiting -- under `propose`,+ or when `auto` could not write the settings file."""+ out = []+ cmd, unit = self._cmd("toolprune"), denylist.unit(self.host.name)+ unt = self.store.read("untool.json") or {}+ root = self.ctx.repo.root+ mine = sorted(denylist.applied_for(self.store, root, self.host.name))++ def few(items):+ return ", ".join(items[:4]) + ("..." if len(items) > 4 else "")+ if self.cfg.toolprune == "auto" and seen.get("untool_applied", "") != ",".join(mine):+ if mine:+ trusted = (denylist.codex_project_trusted(root) if self.host.name == "codex" else+ denylist.copilot_folder_trusted(root) if self.host.name == "copilot"+ else None)+ out.append(self.host.notice(+ f"TokenEconomizer removed {len(mine)} {unit}(s) this repository's sessions "+ f"never used ({few(mine)}), from this session on. Review with `{cmd}`; "+ f"`{cmd} restore` gives them back."+ + (" (The agent reads that setting only in a trusted folder: trust this "+ "one.)" if trusted is False else "")))+ seen["untool_applied"] = ",".join(mine)+ # What this checkout already applied, or gave back, is no news here (another clone may+ # not have).+ kept = set(denylist.kept_for(self.store, root, self.host.name))+ prop = [t for t in unt.get("proposal") or [] if t not in mine and t not in kept]+ if prop and seen.get("untool") != ",".join(prop):+ refused = unt.get("auto_apply_refused") if self.cfg.toolprune == "auto" else None+ out.append(self.host.notice(+ f"TokenEconomizer: {len(prop)} {unit}(s) went unused in this repository's recent "+ f"sessions ({few(prop)}). Review with `{cmd}`; "+ + (f"they could not be applied ({refused}), and `{cmd} apply` tries again."+ if refused else f"nothing changes until you run `{cmd} apply`.")))+ seen["untool"] = ",".join(prop)+ return out+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)@@ -232,6 +261,10 @@ class LiveController:def post_tool(self):if self.cfg.loopguard == "off" or self.host.is_subagent(self.p):return {}+ # The answer names the event it answers: Claude Code rejects a PostToolUseFailure answer+ # labelled PostToolUse ("Hook returned incorrect event name", 2.1.306) and drops it whole,+ # redirect and notice -- and a stuck turn's calls are mostly failures.+ event = self.p.get("hook_event_name") or "PostToolUse"s = self._session()key = self.host.turn_key(self.p)data = s.get("turn")@@ -257,25 +290,26 @@ class LiveController:self._log("nudge", reason=reason, tool_calls=g.cum_turns, envelope=envelope)if not self.cfg.shadow:out = merge_outputs(- self.host.context("PostToolUse", body),+ self.host.context(event, body),self.host.notice(f"TokenEconomizer nudged this turn ({short}): the "f"same failure kept recurring."))elif action == "abort" and not g.abort_delivered:+ # Still stuck after the redirect. The plugin never stops a turn itself -- the+ # agents' hooks cannot all do it, and the person decides -- so the last rung is+ # a notice that says how to stop it, the same on every agent and in every mode.g.abort_delivered = Trues["aborts"] = int(s.get("aborts", 0)) + 1- 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")+ delivered="notice")if not self.cfg.shadow:- if can_stop:- out = self.host.stop(- f"TokenEconomizer stopped this turn: it kept repeating the same "- f"failing steps after a redirect ({short}).")- else:- out = self.host.notice(- f"TokenEconomizer: this turn still looks stuck after a redirect "- f"({short}, {g.cum_turns} tool calls). Consider stepping in.")+ headless = self.ctx.is_headless(self.host.transcript(self.p))+ text = (f"TokenEconomizer: this turn still looks stuck after a redirect "+ f"({short}, {g.cum_turns} tool calls). {self.host.stop_hint(headless)}")+ out = self.host.notice(text)+ if self.host.relays_notices:+ # Where the agent keeps hook messages out of the person's view, the+ # model passes the notice on in its reply, which they do see.+ out = merge_outputs(out, self.host.context(event, self.host.relay(text)))s["turn"] = g.to_dict()self._save(s)return outdiff --git a/tokeneconomizer/plugin/denylist.py b/tokeneconomizer/plugin/denylist.pyindex 9a8781a..ad2ffa5 100644--- a/tokeneconomizer/plugin/denylist.py+++ b/tokeneconomizer/plugin/denylist.py@@ -23,9 +23,10 @@ session start, and the unit of removal is whatever that file can express:Rules common to all three:- * 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.+ * `toolprune: auto` (the default) writes the file as soon as a proposal forms, and the next+ session start says so; with `toolprune: propose` only the person's approval (`te toolprune+ apply`) does. Either way it applies 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`,per settings file, since the clones of one repository share its state but not theirsettings); an entry the person wrote is never touched.@@ -182,11 +183,36 @@ def applied_by_path(doc):return {}-def write_applied(store, by_path):+def kept_by_path(doc):+ """{settings file: [entries the person gave back with `restore`]}: never applied again by+ `toolprune: auto`, which would otherwise remove them at the next fold."""+ kept = doc.get("kept")+ return {_canon(p): list(t or []) for p, t in kept.items()} if isinstance(kept, dict) else {}+++def write_applied(store, by_path, kept=None):+ doc = store.read(APPLIED) or {}+ kept = kept_by_path(doc) if kept is None else keptstore.write(APPLIED, {"by_path": {p: sorted(t) for p, t in by_path.items() if t},+ "kept": {p: sorted(t) for p, t in kept.items() if t},"updated": time.time()})+def kept_for(store, repo_root, host="claude"):+ """What the person gave back in this checkout, which `auto` must leave alone."""+ return list(kept_by_path(store.read(APPLIED) or {}).get(+ _canon(settings_path(repo_root, host))) or [])+++def set_kept(store, repo_root, host, add=(), remove=()):+ """Mark entries as given back by the person (`restore`), or no longer (`apply` by name)."""+ doc = store.read(APPLIED) or {}+ kept = kept_by_path(doc)+ path = _canon(settings_path(repo_root, host))+ kept[path] = sorted((set(kept.get(path) or []) | set(add)) - set(remove))+ write_applied(store, applied_by_path(doc), kept)++def applied(store, path=None):"""What the plugin added to the settings file at `path`; without one, to any checkout's."""by = applied_by_path(store.read(APPLIED) or {})diff --git a/tokeneconomizer/plugin/fold.py b/tokeneconomizer/plugin/fold.pyindex e8b0181..9ab88d1 100644--- a/tokeneconomizer/plugin/fold.py+++ b/tokeneconomizer/plugin/fold.py@@ -96,6 +96,7 @@ def _fold_toolprune(ctx, adapter, run_dir, session_id, transcript=None, workdir=stage.catalog_tools = set(st.get("catalog_tools", []))stage.catalog_desc = dict(st.get("catalog_desc") or {})applied = denylist.applied_for(ctx.store, ctx.repo.root, ctx.host.name)+ kept = set(denylist.kept_for(ctx.store, ctx.repo.root, ctx.host.name)) # given backstage._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@@ -128,12 +129,13 @@ def _fold_toolprune(ctx, adapter, run_dir, session_id, transcript=None, workdir=# 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]+ raw, stage.catalog_tools, stage.used_tools, servers)+ if s not in applied and s not in kept]doc["servers"] = _server_summary(stage, servers)else:proposal = [t for t in denylist.filter_proposal(raw, stage.tool_unused_streaks,ctx.config.toolprune_evidence)- if t not in applied]+ if t not in applied and t not in kept]doc["proposal"] = proposaldoc["new_in_proposal"] = sorted(set(proposal) - set(st.get("proposal", [])))added = []@@ -190,6 +192,7 @@ def _fold_toolprune_codex(ctx, adapter, session_id, transcript, workdir):stage._warned_no_catalog = Truestage.build_tools({"instance_id": session_id}, 0)applied = denylist.applied_for(ctx.store, ctx.repo.root, ctx.host.name)+ kept = set(denylist.kept_for(ctx.store, ctx.repo.root, ctx.host.name)) # given backstage.codex_profile._pending["logical_capabilities"] = sorted(applied)srow = {}stage.after_task({"instance_id": session_id}, {}, run_dir, srow)@@ -198,7 +201,7 @@ def _fold_toolprune_codex(ctx, adapter, session_id, transcript, workdir):loaded = state.get("loaded_exposures") or {}proposal = [c for c in denylist.CODEX_LIVE_CAPABILITIESif c in (state.get("current_pruned") or ()) and c not in ever_used- and c not in applied+ and c not in applied and c not in keptand 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 {}diff --git a/tokeneconomizer/plugin/hosts.py b/tokeneconomizer/plugin/hosts.pyindex 439b213..2073c4f 100644--- a/tokeneconomizer/plugin/hosts.py+++ b/tokeneconomizer/plugin/hosts.py@@ -8,11 +8,10 @@ an adapter rather than a branch in a mechanism:* Turn identity. Claude Code stamps every event of a prompt-turn with `prompt_id`; Codexstamps `turn_id`.- * Stopping. Claude Code's `{"continue": false}` from PostToolUse halts the agent loop after the- current tool (verified on 2.1.286; the session stays usable). Codex's does NOT stop a turn- mid-flight -- it replaces the tool result and the model carries on -- so on Codex the guard's- last rung is a notice to the user, matching the Codex-native spiral policies, which never- abort by design.+ * Stopping. The plugin never stops a turn: the guard's last rung, on every agent and in every+ mode, is a notice telling the person how to (`stop_hint`). Claude Code's `{"continue":+ false}` from PostToolUse would halt its loop (verified on 2.1.286), but Codex's replaces the+ tool result and the model carries on, and Copilot's runs every call; the person decides.* Tool results. Claude Code's Bash `tool_response` is `{stdout, stderr, interrupted, ...}` withno 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@@ -28,8 +27,7 @@ endpoint (docs/PLUGIN.md §3):* Tool names are Claude's (`Bash`, `Read`); a shell result is `tool_result.text_result_for_llm` ending in `<shellId: N completed with exit code X>`, and a failed toolfires `PostToolUseFailure` with an `error` string.- * `continue: false` does not stop a turn (three of three calls ran), so, as on Codex, the- guard's last rung is a notice.+ * `continue: false` does not stop a turn (three of three calls ran).* `systemMessage` is never shown. What the TUI does show is a stdout line`{"type": "progress", "message": ...}` printed BEFORE the hook's final JSON object, whichstill applies (verified on SessionStart, UserPromptSubmit and PostToolUse). So a Copilot@@ -109,7 +107,11 @@ def merge_outputs(*outputs):class Host:name = "?"- can_stop_mid_turn = False+ # How a person stops a turn, for the loop guard's notice: in the agent's own UI, and in a+ # headless run (one prompt, so stopping the turn ends the run). Each agent's are verified+ # in its own terminal UI and headless mode (2026-10-21).+ interrupt = "Interrupt the agent to stop it."+ end_run = "Press Ctrl+C to end the run."# Whether context returned from UserPromptSubmit reaches the model (verified per host).prompt_context = False@@ -139,10 +141,22 @@ class Host:def notice(self, text):return {"systemMessage": text}- def stop(self, reason):- return None+ def stop_hint(self, headless):+ return self.end_run if headless else self.interrupt++ # Whether the loop guard's still-stuck notice must also go through the model, because the+ # agent does not put hook messages where the person looks.+ relays_notices = False++ def relay(self, text):+ """What the model is asked, so that it passes `text` on to the person, word for word.+ The notice is the person's to act on: it does not change the model's task."""+ return ("TokenEconomizer, a plugin the user runs, has a notice for them, and their main "+ "view does not show plugin messages. Put this line, word for word, in your next "+ f"message to the user, and again in your final reply:\n\n{text}\n\nIt is for "+ "the user to act on; it does not change your task.")- def headless(self, env):+ def headless(self, env, transcript=None):return Falsedef tool_call(self, p):@@ -205,7 +219,10 @@ def _exit_code(resp):class ClaudeCode(Host):name = "claude"- can_stop_mid_turn = True+ interrupt = "Press Esc to interrupt it." # 2.1.306: the running command is killed too+ # 2.1.306 shows a hook's `systemMessage` only in the detailed transcript (Ctrl+O), and+ # `claude -p` prints it not at all; Claude's own reply is in the main view and in the output.+ relays_notices = Trueprompt_context = Truedef turn_key(self, p):@@ -215,10 +232,7 @@ class ClaudeCode(Host):# Claude Code exports its session id to the Bash tool's shell (seen on 2.1.304).return str(env.get("TE_SESSION_ID") or env.get("CLAUDE_CODE_SESSION_ID") or "")- def stop(self, reason):- return {"continue": False, "stopReason": reason}-- def headless(self, env):+ def headless(self, env, transcript=None):# Observed in a `claude -p` session's hook environment (2.1.285):# CLAUDE_CODE_SESSION_ATTENDED=0 and CLAUDE_CODE_ENTRYPOINT=sdk-cli. The attended flag# says what matters directly -- is a person watching -- so it wins when present.@@ -240,7 +254,9 @@ _CODEX_SHELL = {"bash", "shell", "exec_command", "local_shell", "unified_exec",class Codex(Host):name = "codex"- can_stop_mid_turn = False+ # 0.163.0: Esc interrupts the turn, but a command it started keeps running as a "background+ # terminal" until `/stop`. (`codex exec` prints no hook messages, so its notice goes unseen.)+ interrupt = "Press Esc to interrupt it, then /stop to end a command it left running."def turn_key(self, p):return str(p.get("turn_id") or "")@@ -260,6 +276,17 @@ class Codex(Host):return "apply_patch", {"path": paths[0] if paths else "", "paths": paths}, text, codereturn name, args, text, code+ def headless(self, env, transcript=None):+ # The rollout's first record names its front end: `source: "exec"`, originator+ # `codex_exec` under `codex exec`; `codex-tui` in the terminal UI (0.163.0). The hook's+ # payload and environment are the same in both.+ try:+ with open(transcript or "", encoding="utf-8") as fh:+ meta = (json.loads(fh.readline()) or {}).get("payload") or {}+ except (OSError, ValueError, AttributeError):+ return False+ return meta.get("source") == "exec" or str(meta.get("originator", "")) == "codex_exec"+def mechanism_trace(self, transcript_path, workdir):out = os.path.join(workdir, "codex_exec_trace.jsonl")n = trace.codex_rollout_to_exec(transcript_path, out)@@ -275,7 +302,7 @@ class Pi(Host):Pi has no hook protocol of its own -- extensions are TypeScript functions on its eventbus -- so the extension speaks THIS one on Pi's behalf: it calls the same dispatcher witha Claude-shaped payload per event and applies the answer with Pi's own levers (a system- prompt section, a steering message, `ctx.abort()`, a UI notice). What it sends:+ prompt section, a steering message, a UI notice). What it sends:* `prompt_id`, which it numbers itself, for the turn identity Pi does not stamp;* `tool_response = {content, isError, exit_code}` -- Pi's bash result carries a real@@ -283,16 +310,16 @@ class Pi(Host):* Pi's mode in `TE_PI_MODE` on the hook's environment: print / json / rpc are headless."""name = "pi"- can_stop_mid_turn = Trueprompt_context = True # the extension appends it to the session's section+ # 1.3.0: Esc aborts the turn and its command; Ctrl+C ends `pi -p`, but a command it started+ # runs on (detached) until it finishes.+ interrupt = "Press Esc to abort it."+ end_run = "Press Ctrl+C to end the run; a command it started runs on until it finishes."def turn_key(self, p):return str(p.get("prompt_id") or "")- def stop(self, reason):- return {"continue": False, "stopReason": reason}-- def headless(self, env):+ def headless(self, env, transcript=None):return str(env.get("TE_PI_MODE", "")).strip() in ("print", "json", "rpc")def mechanism_trace(self, transcript_path, workdir):@@ -312,7 +339,7 @@ def copilot_home(env=None):class Copilot(Host):"""The GitHub Copilot CLI, through `plugin/.github/plugin/plugin.json` and its hook file."""name = "copilot"- can_stop_mid_turn = False+ interrupt = "Press Esc twice to interrupt it." # 1.0.101: "esc esc interrupt"prompt_context = True # verified: top-level additionalContextdef transcript(self, p):@@ -330,6 +357,13 @@ class Copilot(Host):def notice(self, text):return {PROGRESS: [text]}+ def headless(self, env, transcript=None):+ # `copilot -p` hands its hooks the same payload, environment and session log as the+ # terminal UI (1.0.101); only its command line differs, and the hook is its child. Asked+ # only when a notice is written, so the `ps` calls cost nothing on an ordinary call.+ return any(_PROMPT_FLAG.search(a) for a in _ancestor_args()+ if "copilot" in a.split(" ", 1)[0])+def tool_call(self, p):args = p.get("tool_input") if isinstance(p.get("tool_input"), dict) else {}resp = _failure_response(p) or p.get("tool_result")@@ -357,6 +391,29 @@ class Copilot(Host):time.sleep(0.25)+_PROMPT_FLAG = re.compile(r"\s(?:-p|--prompt)(?:[\s=]|$)")+++def _ancestor_args(limit=4):+ """The command lines of this process's nearest ancestors, nearest first."""+ import subprocess+ out, pid = [], os.getppid()+ for _ in range(limit):+ if pid <= 1:+ break+ try:+ line = subprocess.run(["ps", "-o", "ppid=,args=", "-p", str(pid)], capture_output=True,+ text=True, timeout=2).stdout.strip()+ except (OSError, subprocess.SubprocessError):+ break+ ppid, _, args = line.partition(" ")+ if not args:+ break+ out.append(args.strip())+ pid = int(ppid) if ppid.strip().isdigit() else 0+ return out++HOSTS = {"claude": ClaudeCode, "codex": Codex, "copilot": Copilot, "pi": Pi}diff --git a/tokeneconomizer/plugin/probe.py b/tokeneconomizer/plugin/probe.pyindex b7e0566..c817b75 100644--- a/tokeneconomizer/plugin/probe.py+++ b/tokeneconomizer/plugin/probe.py@@ -106,7 +106,10 @@ def _session_env(state, trap):"TE_SIDECALL", "TE_DISABLE", "TERM_PROGRAM")}# An installed copy of the plugin does not run beside the --plugin-dir one: Copilot loads# one plugin per name (verified: one SessionStart hook with both present).- env.update(TOKENECONOMIZER_HOME=state, PATH=trap + os.pathsep + env.get("PATH", ""))+ # The probe applies the deny list itself, for one measured session, and restores it: its+ # sessions must only propose one, as `toolprune=auto` would apply it for all the rest.+ env.update(TOKENECONOMIZER_HOME=state, PATH=trap + os.pathsep + env.get("PATH", ""),+ TE_TOOLPRUNE="propose")return envdiff --git a/tokeneconomizer/plugin/repos.py b/tokeneconomizer/plugin/repos.pyindex 8f1c489..bb9e6f4 100644--- a/tokeneconomizer/plugin/repos.py+++ b/tokeneconomizer/plugin/repos.py@@ -309,12 +309,15 @@ def _take_learned(src, dst, label):def _merge_applied(src, dst):- from .denylist import APPLIED, applied_by_path, write_applied- by = applied_by_path(dst.read(APPLIED) or {})- for path, tools in applied_by_path(src.read(APPLIED) or {}).items():+ from .denylist import APPLIED, applied_by_path, kept_by_path, write_applied+ d_doc, s_doc = dst.read(APPLIED) or {}, src.read(APPLIED) or {}+ by, kept = applied_by_path(d_doc), kept_by_path(d_doc)+ for path, tools in applied_by_path(s_doc).items():by[path] = sorted(set(by.get(path) or []) | set(tools))- if by:- write_applied(dst, by)+ for path, tools in kept_by_path(s_doc).items():+ kept[path] = sorted(set(kept.get(path) or []) | set(tools))+ if by or kept:+ write_applied(dst, by, kept)def _merge_envelope(src, dst):