From 4f65f20dd1aebdd276ee63dcc2a023eeedf6ee7f Mon Sep 17 00:00:00 2001 From: Adarsh B A <93112340+adarshba@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:29:42 +0530 Subject: [PATCH 1/9] feat(zeph): borrow review ideas, vendor TokenEconomizer and simplify the front door - add a minimal-code ladder, cold read, UI clean-up mode and "not run" reviewer status - vendor TokenEconomizer hooks; tool pruning proposes by default - rename setup-zeph to setup and let failure-map load on its own - lead the READMEs with pilot, help and setup - credit ponytail and unslop in THIRD_PARTY --- .github/README | 10 +- README.md | 37 +- THIRD_PARTY.md | 4 + plugins/zeph/README.md | 65 +- plugins/zeph/docs/guide/01-setup.md | 33 +- plugins/zeph/docs/guide/04-design.md | 2 +- .../docs/guide/10-recipes-and-pitfalls.md | 2 +- plugins/zeph/docs/harness.md | 5 +- plugins/zeph/hooks/hooks.json | 71 + plugins/zeph/lib/LICENSE-tokeneconomizer.txt | 21 + plugins/zeph/lib/UPSTREAM.md | 58 + plugins/zeph/lib/tokeneconomizer/__init__.py | 21 + plugins/zeph/lib/tokeneconomizer/config.py | 152 ++ plugins/zeph/lib/tokeneconomizer/domain.py | 77 + plugins/zeph/lib/tokeneconomizer/ledger.py | 41 + .../lib/tokeneconomizer/loopguard/__init__.py | 27 + .../lib/tokeneconomizer/loopguard/envelope.py | 205 +++ .../lib/tokeneconomizer/loopguard/judge.py | 102 ++ .../lib/tokeneconomizer/loopguard/rules.py | 198 +++ .../tokeneconomizer/loopguard/shell_edits.py | 332 ++++ .../lib/tokeneconomizer/loopguard/state.py | 258 +++ .../lib/tokeneconomizer/loopguard/turn.py | 660 ++++++++ .../tokeneconomizer/microskills/__init__.py | 20 + .../tokeneconomizer/microskills/distiller.py | 882 ++++++++++ .../tokeneconomizer/microskills/envfacts.py | 628 ++++++++ .../tokeneconomizer/microskills/lifecycle.py | 203 +++ .../tokeneconomizer/microskills/observe.py | 885 ++++++++++ .../lib/tokeneconomizer/microskills/stage.py | 182 +++ plugins/zeph/lib/tokeneconomizer/names.py | 11 + .../lib/tokeneconomizer/plugin/__init__.py | 31 + .../lib/tokeneconomizer/plugin/accounting.py | 79 + .../lib/tokeneconomizer/plugin/adapter.py | 164 ++ .../zeph/lib/tokeneconomizer/plugin/cli.py | 1123 +++++++++++++ .../zeph/lib/tokeneconomizer/plugin/config.py | 494 ++++++ .../lib/tokeneconomizer/plugin/context.py | 111 ++ .../lib/tokeneconomizer/plugin/controller.py | 514 ++++++ .../lib/tokeneconomizer/plugin/denylist.py | 583 +++++++ .../zeph/lib/tokeneconomizer/plugin/fold.py | 630 ++++++++ .../lib/tokeneconomizer/plugin/history.py | 534 ++++++ .../zeph/lib/tokeneconomizer/plugin/hook.py | 106 ++ .../lib/tokeneconomizer/plugin/hookqueue.py | 163 ++ .../zeph/lib/tokeneconomizer/plugin/hosts.py | 1427 +++++++++++++++++ .../zeph/lib/tokeneconomizer/plugin/judge.py | 120 ++ .../zeph/lib/tokeneconomizer/plugin/paths.py | 305 ++++ .../zeph/lib/tokeneconomizer/plugin/probe.py | 252 +++ .../lib/tokeneconomizer/plugin/repomap.py | 227 +++ .../lib/tokeneconomizer/plugin/repomap_gen.py | 96 ++ .../zeph/lib/tokeneconomizer/plugin/repos.py | 885 ++++++++++ .../lib/tokeneconomizer/plugin/sidecall.py | 1074 +++++++++++++ .../zeph/lib/tokeneconomizer/plugin/store.py | 158 ++ .../lib/tokeneconomizer/plugin/toolcheck.py | 296 ++++ .../lib/tokeneconomizer/plugin/winspawn.py | 93 ++ plugins/zeph/lib/tokeneconomizer/pricing.py | 291 ++++ plugins/zeph/lib/tokeneconomizer/stage.py | 29 + .../lib/tokeneconomizer/toolprune/__init__.py | 18 + .../lib/tokeneconomizer/toolprune/codex.py | 578 +++++++ .../lib/tokeneconomizer/toolprune/stage.py | 199 +++ .../lib/tokeneconomizer/toolprune/tools.py | 104 ++ .../lib/tokeneconomizer/trace/__init__.py | 77 + .../lib/tokeneconomizer/trace/antigravity.py | 231 +++ .../zeph/lib/tokeneconomizer/trace/calls.py | 115 ++ .../zeph/lib/tokeneconomizer/trace/catalog.py | 216 +++ .../zeph/lib/tokeneconomizer/trace/claude.py | 398 +++++ .../trace/claude_tool_catalog.json | 26 + .../zeph/lib/tokeneconomizer/trace/codex.py | 334 ++++ .../zeph/lib/tokeneconomizer/trace/copilot.py | 167 ++ .../zeph/lib/tokeneconomizer/trace/cursor.py | 113 ++ .../zeph/lib/tokeneconomizer/trace/droid.py | 399 +++++ .../zeph/lib/tokeneconomizer/trace/grok.py | 238 +++ .../zeph/lib/tokeneconomizer/trace/hermes.py | 328 ++++ .../zeph/lib/tokeneconomizer/trace/jsonl.py | 25 + .../lib/tokeneconomizer/trace/opencode.py | 215 +++ plugins/zeph/lib/tokeneconomizer/trace/pi.py | 169 ++ plugins/zeph/scripts/te | 63 + plugins/zeph/scripts/te-hook | 68 + plugins/zeph/scripts/te-hook.cmd | 82 + plugins/zeph/scripts/te.cmd | 80 + plugins/zeph/scripts/te_bootstrap.py | 393 +++++ plugins/zeph/skills/arena/SKILL.md | 2 +- plugins/zeph/skills/doc/SKILL.md | 1 + plugins/zeph/skills/failure-map/SKILL.md | 13 +- plugins/zeph/skills/help/SKILL.md | 23 +- plugins/zeph/skills/interrogate/SKILL.md | 3 + plugins/zeph/skills/pilot/SKILL.md | 4 +- .../pilot/playbooks/multi-phase-plan.md | 5 +- plugins/zeph/skills/pilot/worker.md | 2 + .../LICENSE-ponytail.txt | 21 + .../principle-laziness-protocol/SKILL.md | 7 + plugins/zeph/skills/setup-zeph/SKILL.md | 68 - plugins/zeph/skills/setup/SKILL.md | 82 + plugins/zeph/skills/swarm/SKILL.md | 4 +- plugins/zeph/skills/ui/LICENSE-unslop.txt | 396 +++++ plugins/zeph/skills/ui/SKILL.md | 16 +- plugins/zeph/skills/ui/references/slop.md | 103 ++ .../zeph/skills/unslop/LICENSE-ponytail.txt | 21 + plugins/zeph/skills/unslop/SKILL.md | 5 + scripts/check.ts | 41 +- 97 files changed, 20307 insertions(+), 123 deletions(-) create mode 100644 plugins/zeph/hooks/hooks.json create mode 100644 plugins/zeph/lib/LICENSE-tokeneconomizer.txt create mode 100644 plugins/zeph/lib/UPSTREAM.md create mode 100644 plugins/zeph/lib/tokeneconomizer/__init__.py create mode 100644 plugins/zeph/lib/tokeneconomizer/config.py create mode 100644 plugins/zeph/lib/tokeneconomizer/domain.py create mode 100644 plugins/zeph/lib/tokeneconomizer/ledger.py create mode 100644 plugins/zeph/lib/tokeneconomizer/loopguard/__init__.py create mode 100644 plugins/zeph/lib/tokeneconomizer/loopguard/envelope.py create mode 100644 plugins/zeph/lib/tokeneconomizer/loopguard/judge.py create mode 100644 plugins/zeph/lib/tokeneconomizer/loopguard/rules.py create mode 100644 plugins/zeph/lib/tokeneconomizer/loopguard/shell_edits.py create mode 100644 plugins/zeph/lib/tokeneconomizer/loopguard/state.py create mode 100644 plugins/zeph/lib/tokeneconomizer/loopguard/turn.py create mode 100644 plugins/zeph/lib/tokeneconomizer/microskills/__init__.py create mode 100644 plugins/zeph/lib/tokeneconomizer/microskills/distiller.py create mode 100644 plugins/zeph/lib/tokeneconomizer/microskills/envfacts.py create mode 100644 plugins/zeph/lib/tokeneconomizer/microskills/lifecycle.py create mode 100644 plugins/zeph/lib/tokeneconomizer/microskills/observe.py create mode 100644 plugins/zeph/lib/tokeneconomizer/microskills/stage.py create mode 100644 plugins/zeph/lib/tokeneconomizer/names.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/__init__.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/accounting.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/adapter.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/cli.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/config.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/context.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/controller.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/denylist.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/fold.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/history.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/hook.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/hookqueue.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/hosts.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/judge.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/paths.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/probe.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/repomap.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/repomap_gen.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/repos.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/sidecall.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/store.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/toolcheck.py create mode 100644 plugins/zeph/lib/tokeneconomizer/plugin/winspawn.py create mode 100644 plugins/zeph/lib/tokeneconomizer/pricing.py create mode 100644 plugins/zeph/lib/tokeneconomizer/stage.py create mode 100644 plugins/zeph/lib/tokeneconomizer/toolprune/__init__.py create mode 100644 plugins/zeph/lib/tokeneconomizer/toolprune/codex.py create mode 100644 plugins/zeph/lib/tokeneconomizer/toolprune/stage.py create mode 100644 plugins/zeph/lib/tokeneconomizer/toolprune/tools.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/__init__.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/antigravity.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/calls.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/catalog.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/claude.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/claude_tool_catalog.json create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/codex.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/copilot.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/cursor.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/droid.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/grok.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/hermes.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/jsonl.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/opencode.py create mode 100644 plugins/zeph/lib/tokeneconomizer/trace/pi.py create mode 100755 plugins/zeph/scripts/te create mode 100755 plugins/zeph/scripts/te-hook create mode 100644 plugins/zeph/scripts/te-hook.cmd create mode 100644 plugins/zeph/scripts/te.cmd create mode 100644 plugins/zeph/scripts/te_bootstrap.py create mode 100644 plugins/zeph/skills/principle-laziness-protocol/LICENSE-ponytail.txt delete mode 100644 plugins/zeph/skills/setup-zeph/SKILL.md create mode 100644 plugins/zeph/skills/setup/SKILL.md create mode 100644 plugins/zeph/skills/ui/LICENSE-unslop.txt create mode 100644 plugins/zeph/skills/ui/references/slop.md create mode 100644 plugins/zeph/skills/unslop/LICENSE-ponytail.txt diff --git a/.github/README b/.github/README index 0454aa0..e9f96d3 100644 --- a/.github/README +++ b/.github/README @@ -12,8 +12,8 @@ A few skills you won't find elsewhere: benny triages a production alert and writes the RCA failure-map maps every exit of an endpoint, with its status, severity and log line, before you write it - ui builds or restyles a UI, then reviews it against - interface guidelines + ui builds, cleans up or restyles a UI, then reviews it + against interface guidelines doc writes RFCs, design docs and runbooks traced to the code interrogate sends reviewers with different lenses to break a diff @@ -44,7 +44,7 @@ Codex, Cursor and other agents, skills only: npx skills add adarshba/zeph -Then pick models with /zeph:setup-zeph and start real work with +Then pick models with /zeph:setup and start real work with /zeph:pilot. Unsure which skill fits? Ask /zeph:help. Claude Code installs a cached copy. After a skill changes, run @@ -56,13 +56,13 @@ Skills pilot default entry point for any non-trivial task help which skill, playbook or principle fits - setup-zeph pick the model and effort for each role + setup pick the model and effort for each role how, why how a subsystem works; why it was built that way interrogate reviewers with different lenses try to break a diff arena, swarm parallel attempts at one thing; parallel workers on slices failure-map every exit of an endpoint, its status, severity and log line doc RFCs, design docs and runbooks traced to the code - ui build or restyle a UI, then review it against guidelines + ui build, clean up or restyle a UI, then review it against guidelines tdd failing test first, then the fix unslop strip AI tells from writing benny production alert triage and incident RCA diff --git a/README.md b/README.md index 9b057b2..67368d3 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,32 @@ One skill set for Claude Code, Codex and Cursor. A router, `/zeph:pilot`, picks a playbook for your task, and every change gets proven before it's called done. +## Start here + +After [installing](#install), you need three commands: + +| Command | Use it to | +|---|---| +| `/zeph:pilot` | do a task | +| `/zeph:help` | ask what to type | +| `/zeph:setup` | pick your models, once | + +Say what you want, and what done looks like: + +```text +/zeph:pilot the export button downloads an empty file. fix it. done means a failing test now passes. +/zeph:pilot add a --json flag to status. done means the text output is unchanged. +/zeph:pilot why is the nightly job slow? change nothing. done means you name the slow step and its time. +/zeph:pilot check on pr 123. done means ci is green and every comment has a reply. +/zeph:pilot write an rfc for moving sessions to redis. done means it has no open questions. +``` + +Every other skill is pilot's toolbox. It picks one up when a step needs it, so you don't have to learn them. + +- **You need** Python 3.10+ for the hooks, `gh` for the PR playbooks and `bun` for the GitHub PR watcher. +- **In the background**, on Claude Code only, [hooks](#background-hooks) watch for stuck loops, which can cost a small model call, and propose tool deny rules. +- **Other agents** drop the `zeph:` prefix. + ![zeph's pilot fixing a failing test](docs/demo.gif) A real run: pilot picks the bug-fix playbook, fixes an off-by-one, tests go 2/3 → 3/3. @@ -12,7 +38,7 @@ A few skills you won't find elsewhere: - [`benny`](plugins/zeph/automations/benny/README.md) triages a production alert and writes the RCA. - [`failure-map`](plugins/zeph/skills/failure-map/SKILL.md) maps every exit of an endpoint, with its status, severity and log line, before you write it. -- [`ui`](plugins/zeph/skills/ui/SKILL.md) builds or restyles a UI, then reviews it against interface guidelines. +- [`ui`](plugins/zeph/skills/ui/SKILL.md) builds, cleans up or restyles a UI, then reviews it against interface guidelines. - [`doc`](plugins/zeph/skills/doc/SKILL.md) writes RFCs, design docs and runbooks with every claim traced to the code. - [`interrogate`](plugins/zeph/skills/interrogate/SKILL.md) sends reviewers with different lenses to break a diff. @@ -35,7 +61,7 @@ Codex, Cursor and other agents, skills only: npx skills add adarshba/zeph ``` -Then run `/zeph:setup-zeph` to pick models, and start real work with `/zeph:pilot`. Unsure which skill fits? Ask `/zeph:help`. The [plugin README](plugins/zeph/README.md) lists every skill. +The [plugin README](plugins/zeph/README.md) lists every skill. Claude Code installs a cached copy. After you change a skill, run `claude plugin update zeph@zeph` and start a new session. While editing, `claude --plugin-dir plugins/zeph` loads the working copy directly. @@ -48,14 +74,19 @@ Claude Code installs a cached copy. After you change a skill, run `claude plugin | `plugins/zeph/automations/benny/` | benny: production alert triage and incident RCA | | `plugins/zeph/agents/` | Subagents: `pilot-agent`, `comment-sicko` | | `plugins/zeph/docs/` | The guide and the harness map | +| `plugins/zeph/hooks/`, `plugins/zeph/scripts/`, `plugins/zeph/lib/` | TokenEconomizer's hooks, launchers and vendored package | | `scripts/check.ts` | The repository check | +## Background hooks + +On Claude Code, zeph also runs [TokenEconomizer](https://github.com/microsoft/TokenEconomizer)'s hooks (MIT). They guard against stuck loops and propose tool deny rules that you apply yourself. A turn that looks stuck costs a small model call. Learning repo facts is off by default. State is in `~/.tokeneconomizer`. What each one does, and how to turn it off, is in the [plugin README](plugins/zeph/README.md#background-hooks-tokeneconomizer). Do not also install the standalone tokeneconomizer plugin. + ## Check ```sh bun install bun run check # manifests, names, frontmatter, links, harness-neutral prose -bun run check:full # plus the bundled script tests and a live routing smoke +bun run check:full # plus the bundled script tests, the TokenEconomizer hook and a live routing smoke ``` Every PR passes `bun run check:full` before merge. [CONTRIBUTING.md](CONTRIBUTING.md) has the rules. diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 7c3ebe1..9a98d58 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -6,3 +6,7 @@ zeph is MIT. These files adapt work published under other terms. Each keeps its |---|---|---|---|---| | `plugins/zeph/skills/ui/SKILL.md` | [anthropics/skills frontend-design](https://github.com/anthropics/skills/tree/41bbe19d1a1a7eaab5e7bb9050a417e5c6cffc8f/skills/frontend-design) | `41bbe19d1a1a7eaab5e7bb9050a417e5c6cffc8f` | Apache-2.0 | `plugins/zeph/skills/ui/LICENSE-frontend-design.txt` | | `plugins/zeph/skills/ui/references/guidelines.md` | [vercel-labs/web-interface-guidelines](https://github.com/vercel-labs/web-interface-guidelines/tree/434b7f91364665f2f733b310ec54809bf8f37937) | `434b7f91364665f2f733b310ec54809bf8f37937` | MIT, Copyright (c) 2025 Vercel Labs | `plugins/zeph/skills/ui/references/guidelines.md` | +| `plugins/zeph/skills/ui/references/slop.md` | [heydamir/unslop](https://github.com/heydamir/unslop/tree/8091f22aaf303843caf45528541f746b4767e3de/skills/unslop/references/signs.md) | `8091f22aaf303843caf45528541f746b4767e3de` | CC BY 4.0, Damir Sokolovsky | `plugins/zeph/skills/ui/LICENSE-unslop.txt` | +| `plugins/zeph/lib/UPSTREAM.md` | [microsoft/TokenEconomizer](https://github.com/microsoft/TokenEconomizer/tree/7993da53b42288263e2837c96707a2fc30f90066) (`lib/tokeneconomizer/`, `scripts/`, `hooks/`) | `7993da53b42288263e2837c96707a2fc30f90066` | MIT, Copyright (c) 2026 Microsoft | `plugins/zeph/lib/LICENSE-tokeneconomizer.txt` | +| `plugins/zeph/skills/principle-laziness-protocol/SKILL.md` | [DietrichGebert/ponytail](https://github.com/DietrichGebert/ponytail/tree/ebd8654c2c627f721eb8f9c0d1bd4090a29f9e10/skills) (`ponytail`) | `ebd8654c2c627f721eb8f9c0d1bd4090a29f9e10` | MIT, Copyright (c) 2026 DietrichGebert | `plugins/zeph/skills/principle-laziness-protocol/LICENSE-ponytail.txt` | +| `plugins/zeph/skills/unslop/SKILL.md` | [DietrichGebert/ponytail](https://github.com/DietrichGebert/ponytail/tree/ebd8654c2c627f721eb8f9c0d1bd4090a29f9e10/skills) (`ponytail`, `ponytail-review`) | `ebd8654c2c627f721eb8f9c0d1bd4090a29f9e10` | MIT, Copyright (c) 2026 DietrichGebert | `plugins/zeph/skills/unslop/LICENSE-ponytail.txt` | diff --git a/plugins/zeph/README.md b/plugins/zeph/README.md index 49d23af..343711e 100644 --- a/plugins/zeph/README.md +++ b/plugins/zeph/README.md @@ -4,6 +4,32 @@ if you want to go fast, go deep first. zeph is one skill set for claude code, codex and any other agent harness. a router, [`/pilot`](./skills/pilot/SKILL.md), picks a playbook for your task, and every change gets proven before it's called done. +## start here + +after [installing](#install), you need three commands: + +| command | use it to | +|---|---| +| [`/zeph:pilot`](./skills/pilot/SKILL.md) | do a task | +| [`/zeph:help`](./skills/help/SKILL.md) | ask what to type | +| [`/zeph:setup`](./skills/setup/SKILL.md) | pick your models, once | + +say what you want, and what done looks like: + +``` +/zeph:pilot the export button downloads an empty file. fix it. done means a failing test now passes. +/zeph:pilot add a --json flag to status. done means the text output is unchanged. +/zeph:pilot why is the nightly job slow? change nothing. done means you name the slow step and its time. +/zeph:pilot check on pr 123. done means ci is green and every comment has a reply. +/zeph:pilot write an rfc for moving sessions to redis. done means it has no open questions. +``` + +every other skill is pilot's toolbox. it picks one up when a step needs it, so you don't have to learn them. + +- **you need** python 3.10+ for the hooks, `gh` for the pr playbooks and `bun` for the github pr watcher. +- **in the background**, on claude code only, [hooks](#background-hooks-tokeneconomizer) watch for stuck loops, which can cost a small model call, and propose tool deny rules. +- **other agents** drop the `zeph:` prefix. + ![zeph's pilot fixing a failing test](../../docs/demo.gif) a real run: pilot picks the bug-fix playbook, fixes an off-by-one, tests go 2/3 → 3/3. @@ -12,7 +38,7 @@ a few skills you won't find elsewhere: - [`/benny`](./automations/benny/README.md) triages a production alert and writes the rca. - [`/failure-map`](./skills/failure-map/SKILL.md) maps every exit of an endpoint, with its status, severity and log line, before you write it. -- [`/ui`](./skills/ui/SKILL.md) builds or restyles a ui, then reviews it against interface guidelines. +- [`/ui`](./skills/ui/SKILL.md) builds, cleans up or restyles a ui, then reviews it against interface guidelines. - [`/doc`](./skills/doc/SKILL.md) writes rfcs, design docs and runbooks with every claim traced to the code. - [`/interrogate`](./skills/interrogate/SKILL.md) sends reviewers with different lenses to break a diff. @@ -43,12 +69,12 @@ skills use neutral terms, and the [harness map](./docs/harness.md) translates ea two steps: -1. run [`/setup-zeph`](./skills/setup-zeph/SKILL.md), pick a reasoning budget, and choose which models you want. +1. run [`/setup`](./skills/setup/SKILL.md) and pick a reasoning budget. change a model only if you want to. 2. use [`/pilot`](./skills/pilot/SKILL.md) whenever you're doing anything that requires rigor. new here? the [zeph guide](./docs/guide/README.md) walks you through a first real task, from setup and prompting through verification and overnight runs. stuck, or unsure which skill fits? ask [`/help`](./skills/help/SKILL.md). -that's it. the other skills are situational, and the mode skill uses them for you as needed. out of the box, code delegates (feature, refactoring, bug fix, perf, hillclimb), prose, and judgment go to opus at high effort, and no role runs above xhigh. fable runs only when you name it. the default panel is three opus seats with different lenses. [`/setup-zeph`](./skills/setup-zeph/SKILL.md) changes any of it. +that's it. the other skills are situational, and the mode skill uses them for you as needed. out of the box, code delegates (feature, refactoring, bug fix, perf, hillclimb), prose, and judgment go to opus at high effort, and no role runs above xhigh. fable runs only when you name it. the default panel is three opus seats with different lenses. [`/setup`](./skills/setup/SKILL.md) changes any of it. ## usage @@ -144,12 +170,12 @@ a [`/pilot`](./skills/pilot/SKILL.md) invocation attaches it to one message, so | [`/benny`](./automations/benny/README.md) | a production alert fired or an incident needs its rca. triages read-only and drafts one thread verdict, or the full rca with five whys. set up with `/setup-benny`. | | [`/blast-radius`](./skills/blast-radius/SKILL.md) | you have a small-looking change and want to know what else it could break, with the one fact it's safe because of proven by running code, not asserted. | | [`/architect`](./skills/architect/SKILL.md) | you're about to write code that crosses a function boundary and want the caller's usage, types, and module shape settled first. | -| [`/failure-map`](./skills/failure-map/SKILL.md) | you're writing, changing, or reviewing an endpoint, webhook, or handler. maps every exit with its failure category, status, severity, and log line before code, and checks that a dev can find each failure from one id. | +| [`/failure-map`](./skills/failure-map/SKILL.md) | you're writing, changing, or reviewing an endpoint, webhook, or handler. maps every exit with its failure category, status, severity, and log line before code, and checks that a dev can find each failure from one id. also loads on its own when you work on or discuss one. | | [`/arena`](./skills/arena/SKILL.md) | you want N parallel attempts at the same thing, then to grab the best parts of each. | | [`/swarm`](./skills/swarm/SKILL.md) | you want N parallel workers across different slices or races, then one aggregated report. | | [`/interrogate`](./skills/interrogate/SKILL.md) | you have a diff and want reviewers with different lenses to try to break it, keeping only findings a run proves. | | [`/automate-me`](./skills/automate-me/SKILL.md) | you want your own `-mode` skill, drafted from how you've actually worked. | -| [`/setup-zeph`](./skills/setup-zeph/SKILL.md) | you want to pick which models zeph uses per role. detects your models and writes a config rule. | +| [`/setup`](./skills/setup/SKILL.md) | you want to pick which models zeph uses per role. detects your models, writes a config rule, then offers optional extras. | | [`/reflect`](./skills/reflect/SKILL.md) | a long task landed and you want the recipe captured as a skill edit. | | [`/correct`](./skills/correct/SKILL.md) | you keep correcting agents for the same mistakes. mines history for mistake classes, fixes each at the highest level that works (architecture, then types, lint, and ci, then tests, with docs last), and keeps a table pairing each rule with what enforces it. | | [`/teach`](./skills/teach/SKILL.md) | you want to actually understand a change or subsystem, not just have it summarized. runs how + why and weaves one plain explanation, built up diagram by diagram. | @@ -168,7 +194,7 @@ a [`/pilot`](./skills/pilot/SKILL.md) invocation attaches it to one message, so | [`/bro`](./skills/bro/SKILL.md) | you want the last message restated in plain human language, no jargon. | | [`/technical-writing`](./skills/technical-writing/SKILL.md) | layered prose standard (Diátaxis + Google developer style + STE + Global English) for docs, readmes, PR descriptions, commit messages. | | [`/doc`](./skills/doc/SKILL.md) | you need a whole rfc, design doc, architecture write-up, or runbook. traces every claim to the code, draws one diagram, settles each open question, and has a fresh reviewer check the claims. | -| [`/ui`](./skills/ui/SKILL.md) | you're building or restyling a ui and want a deliberate visual direction, or want a ui or accessibility review. reports `file:line` findings against interface guidelines. | +| [`/ui`](./skills/ui/SKILL.md) | you're building, cleaning up or restyling a ui and want a deliberate visual direction, or want a ui or accessibility review. reports `file:line` findings against interface guidelines. | @@ -294,10 +320,35 @@ most harnesses already have a great plan mode which works great with zeph. but p type [`/automate-me`](./skills/automate-me/SKILL.md). it mines your recent transcripts, drafts a `-mode` skill from how you've actually worked, and routes through zeph underneath. you keep zeph as the base and end up with your own routing skill alongside `pilot`. -models are configurable too. type [`/setup-zeph`](./skills/setup-zeph/SKILL.md). it detects the models you have access to and writes a small always-applied rule mapping each role (code, judgment, the review panels) to a model. every skill reads it and falls back to sensible defaults when the rule is absent, so you override only what you want. +models are configurable too. type [`/setup`](./skills/setup/SKILL.md). it detects the models you have access to and writes a small always-applied rule mapping each role (code, judgment, the review panels) to a model. every skill reads it and falls back to sensible defaults when the rule is absent, so you override only what you want. when a default changes, a rule written before the change still pins the old value. delete that role's line to pick up the new default. +## background hooks: tokeneconomizer + +on Claude Code, zeph also runs the hooks of [TokenEconomizer](https://github.com/microsoft/TokenEconomizer) (MIT, vendored in `lib/`, see [UPSTREAM.md](lib/UPSTREAM.md)). There is no slash command. The hooks: + +- inject repo facts learned from earlier sessions, when `microskills` is on (off by default). +- redirect a turn that looks stuck in a failing loop, when `loopguard` is on (on by default). A small model call through your `claude` CLI judges the turn, and that call counts toward your usage. +- propose deny rules for tools a repo's sessions never use (`toolprune`). Its default is `propose`: nothing is written until you apply them. `toolprune=auto` writes them to `.claude/settings.local.json` by itself. + +state lives in `~/.tokeneconomizer`; set `TOKENECONOMIZER_HOME` to move it. The hooks need Python 3.10 or newer. Without one they do nothing. + +run the command line as `~/.tokeneconomizer/bin/te` (the launcher appears after the first session starts): + +```sh +~/.tokeneconomizer/bin/te config show # each mechanism, on or off +~/.tokeneconomizer/bin/te toolprune # what it proposes for this repo +~/.tokeneconomizer/bin/te toolprune apply # write those deny rules +~/.tokeneconomizer/bin/te config set --global loopguard=off # stuck-loop guard off +~/.tokeneconomizer/bin/te config set --global toolprune=off # tool pruning off +TE_DISABLE=1 # environment: every hook answers {} at once +``` + +without `--global`, `config set` changes only the repository you are in. + +do not also install the standalone tokeneconomizer plugin. Both would run the same hooks and share one state directory. + ## license MIT diff --git a/plugins/zeph/docs/guide/01-setup.md b/plugins/zeph/docs/guide/01-setup.md index efc6b3d..3b0a9a4 100644 --- a/plugins/zeph/docs/guide/01-setup.md +++ b/plugins/zeph/docs/guide/01-setup.md @@ -7,37 +7,46 @@ In this page you install the plugin, pick which models zeph uses, and run your f In Claude Code, run: ```text -/plugin marketplace add +/plugin marketplace add adarshba/zeph /plugin install zeph@zeph ``` -Claude Code prefixes plugin commands, so each command in this guide takes a `zeph:` prefix there, such as `/zeph:setup-zeph`. The [harness map](../harness.md) covers the other differences between harnesses. +Claude Code prefixes plugin commands, so each command in this guide takes a `zeph:` prefix there, such as `/zeph:setup`. The [harness map](../harness.md) covers the other differences between harnesses. ## Pick your models Run: ```text -/setup-zeph +/setup ``` -[`/setup-zeph`](../../skills/setup-zeph/SKILL.md) detects the models you have access to, asks for a reasoning budget, shows you each role (code delegates, judgment, the review panels), and asks what you want. Answer the questions. It writes the models rule, a small rule every zeph skill reads. +[`/setup`](../../skills/setup/SKILL.md) detects the models you have access to and asks one thing, your reasoning budget. It writes the models rule, a small rule every zeph skill reads, with the default model for each role (code delegates, judgment, the review panels). Then it shows you the roles. To change one, say which, as in `use haiku for swarm workers`. The defaults are the same as the `large` budget. Every role runs on Opus at `high` reasoning, and no role runs above `xhigh`. Fable runs only when you name it for a task. `medium` lowers each role one level and `small` lowers it two, and both spend fewer tokens. -You only override what you care about. A role with no line in the rule keeps the skill's default. To restore a default, delete that role's line. A rerun of `/setup-zeph` keeps any role whose model differs from the default. When a default changes, a rule written before the change still pins the old value. Delete that role's line to pick up the new default. +You only override what you care about. A role with no line in the rule keeps the skill's default. To restore a default, delete that role's line. A rerun of `/setup` keeps any role whose model differs from the default. When a default changes, a rule written before the change still pins the old value. Delete that role's line to pick up the new default. -You might be wondering what happens if you use Auto. Set a role to `inherit-parent` or `auto` and zeph omits the subagent `model` field, so the subagent inherits your parent chat model. Both values mean the same thing, and neither is a model slug. For a panel role the value is a list, and one subagent runs per entry, so the list length sets the panel size. Setup also configures `swarm workers`, the default model for every `/swarm` worker unless a race names a model for each arm. +You might be wondering what happens if you use Auto. Set a role to `inherit-parent` or `auto` and its subagent runs on your parent chat model. The [harness map](../harness.md) says how. Both values mean the same thing, and neither is a model slug. For a panel role the value is a list, and one subagent runs per entry, so the list length sets the panel size. Setup also configures `swarm workers`, the default model for every `/swarm` worker unless a race names a model for each arm. -## Accept the verification offers, or don't +## Pick the optional extras, or don't -At the end of setup, `/setup-zeph` looks for a way to prove app behavior in your project, either a `verify-*` skill or an existing harness. If it finds neither, it offers once to generate one with [`/create-verification-skill`](../../skills/create-verification-skill/SKILL.md). +After the roles, setup on Claude Code tells you what [runs in the background](../../README.md#background-hooks-tokeneconomizer) and how to turn it off. Then it asks one question, "want the optional extras?" Pick any, or none. An extra you don't pick changes nothing. -Say yes and it writes `verify-/` in the project skills folder, a project-local skill that teaches agents to drive your app the way a user does. It proves the skill works once before handing it over. Say no and setup moves on. You can run `/create-verification-skill` yourself any time. [Verify and ship](./06-verify-and-ship.md#create-a-project-verification-skill) covers it in depth. +| Extra | What you get | +|---|---| +| Verification skill | agents drive your app and prove changes work | +| Formal verification skill | agents prove one key property of your code | +| Automation scan | a read-only list of hooks, skills, subagents and MCP servers worth adding | +| Advisor setup | a cheaper main model with a stronger advisor, where your harness has one | -If you're new to zeph, say yes. An agent that can check its own work keeps going until the check passes. An agent that can't hands every result back to you to check by hand. Of everything in this guide, the verification skill pays off the most. +Setup lists the verification skills only when your project doesn't have one yet. -Then setup offers once to generate a formal verification skill with [`/create-formal-verification-skill`](../../skills/create-formal-verification-skill/SKILL.md), unless the project already has one. Tests check the cases someone thought to write. A formal verification skill checks one key property of your code, such as "a job never runs twice at once", in every case within a stated scope. Say yes when your code has concurrency, retries, a state machine, or a parser, where a bug is costly and tests rarely reach the case that breaks. Otherwise say no, and run it later if that changes. [Verify and ship](./06-verify-and-ship.md#prove-a-property-with-a-formal-verification-skill) covers it. +The verification skill comes from [`/create-verification-skill`](../../skills/create-verification-skill/SKILL.md). It writes `verify-/` in the project skills folder, a project-local skill that teaches agents to drive your app the way a user does. It proves the skill works once before handing it over. You can run `/create-verification-skill` yourself any time. [Verify and ship](./06-verify-and-ship.md#create-a-project-verification-skill) covers it in depth. + +If you're new to zeph, pick it. An agent that can check its own work keeps going until the check passes. An agent that can't hands every result back to you to check by hand. Of everything in this guide, the verification skill pays off the most. + +The formal verification skill comes from [`/create-formal-verification-skill`](../../skills/create-formal-verification-skill/SKILL.md). Tests check the cases someone thought to write. A formal verification skill checks one key property of your code, such as "a job never runs twice at once", in every case within a stated scope. Pick it when your code has concurrency, retries, a state machine, or a parser, where a bug is costly and tests rarely reach the case that breaks. Otherwise skip it, and run it later if that changes. [Verify and ship](./06-verify-and-ship.md#prove-a-property-with-a-formal-verification-skill) covers it. After setup, start a new chat. The model rule applies to new sessions. @@ -45,7 +54,7 @@ After setup, start a new chat. The model rule applies to new sessions. zeph spends extra tokens on subagents and review panels. That's the price of the rigor. To spend fewer: -- Rerun `/setup-zeph` and pick a smaller reasoning budget or cheaper models. A strong model in the main chat with cheaper, faster models in the code roles is a good split. +- Rerun `/setup` and pick a smaller reasoning budget or cheaper models. A strong model in the main chat with cheaper, faster models in the code roles is a good split. - Set a role to `auto` or `inherit-parent` so it runs on the chat's own model. - Shorten a panel list. Each entry runs one subagent. - Save `/pilot` for work that needs rigor. A small, obvious edit doesn't. diff --git a/plugins/zeph/docs/guide/04-design.md b/plugins/zeph/docs/guide/04-design.md index e5df4cf..fa92c40 100644 --- a/plugins/zeph/docs/guide/04-design.md +++ b/plugins/zeph/docs/guide/04-design.md @@ -38,7 +38,7 @@ flowchart LR H --> I[Verify] ``` -The panel comes from your [`/setup-zeph`](../../skills/setup-zeph/SKILL.md) configuration, and you can adjust it per task. Ask for more candidates when the decision matters, fewer when it doesn't: +The panel comes from your [`/setup`](../../skills/setup/SKILL.md) configuration, and you can adjust it per task. Ask for more candidates when the decision matters, fewer when it doesn't: ```text /arena this, 5 candidates. the cache key format is expensive to change later. diff --git a/plugins/zeph/docs/guide/10-recipes-and-pitfalls.md b/plugins/zeph/docs/guide/10-recipes-and-pitfalls.md index 0470a58..63a5c31 100644 --- a/plugins/zeph/docs/guide/10-recipes-and-pitfalls.md +++ b/plugins/zeph/docs/guide/10-recipes-and-pitfalls.md @@ -173,7 +173,7 @@ To watch the catch-up instead, run [`/ketchup-video`](../../skills/ketchup-video - **Correcting the same mistake by hand.** A correction in chat helps one run. `/correct` fixes the repo so no later run repeats it. - **Using `/arena` for coverage.** `/arena` repeats one design or code brief, then picks a base and grafts the best parts. `/swarm` partitions slices or declared race arms and aggregates one report. - **Accepting every review comment.** Bots and humans both file real catches and noise in one list. `/interrogate` keeps only the findings a rerun proves and lists what it dropped and why, and you can override either way. -- **Treating `auto` as a model slug.** `auto` and `inherit-parent` mean "omit the model field so the subagent inherits the parent chat model." [Setup](./01-setup.md) covers the roles. +- **Treating `auto` as a model slug.** `auto` and `inherit-parent` mean "run the subagent on the parent chat model." [Setup](./01-setup.md) covers the roles. - **Reporting success off a green build.** A build proves it compiles. Ask for the real command, flow, stored value, or profile, and expect the evidence in the reply. - **Writing a `SKILL.md` freehand.** Route it through the [Authoring or modifying a skill playbook](../../skills/pilot/playbooks/authoring-a-skill.md) so validation and review happen. diff --git a/plugins/zeph/docs/harness.md b/plugins/zeph/docs/harness.md index 8b82588..f3233e6 100644 --- a/plugins/zeph/docs/harness.md +++ b/plugins/zeph/docs/harness.md @@ -33,7 +33,7 @@ Skills write a model as ` `, such as `opus high`. | Term in skills | Claude Code | Cursor | | --- | --- | --- | | ` `, such as `opus high` | `model: "opus"`, `effort: "high"`. `model` takes `opus`, `sonnet`, `haiku`, `fable`. | `claude---`, with `-fast` on Opus 5.5: `opus high` is `claude-opus-5-5-high-fast` | -| `inherit-parent`, `auto` | Omit `model`. | Omit `model` and spawn a general-purpose subagent. | +| `inherit-parent`, `auto` | Run on the parent chat's model. A subagent takes the first of: the call's `model`, the agent definition's `model`, `CLAUDE_CODE_SUBAGENT_MODEL`, the parent's model. So omit `model` only when that variable is unset. When it is set, pass the parent's alias. | Omit `model` and spawn a general-purpose subagent. | | the models rule | `~/.claude/rules/zeph-models.md`. Every new session loads it, so its role lines are already in context. If not, read it. A missing file or line means the skill's default. | `~/.cursor/rules/zeph-models.mdc`, with `alwaysApply: true` frontmatter | ## Paths @@ -63,9 +63,10 @@ Skills write a model as ` `, such as `opus high`. | the app-driving skill | `/run` | `control-ui` or `control-cli` from `cursor-team-kit` | | review bots | Bot comments on a PR, such as Bugbot's, are ordinary review threads. Skip a step that starts or configures a bot that the PR doesn't have. | Bugbot | -## setup-zeph +## setup The models rule is the one rule zeph writes outside its own folder. - **Claude Code.** The detected models are the `model` values the `Agent` tool schema lists, each with an effort from its `effort` values. Write each as ` `, such as `opus high`. Write `~/.claude/rules/zeph-models.md` with no frontmatter. Never put the role lines in `CLAUDE.md` or `AGENTS.md`. +- **Claude Code advisor setup.** `~/.claude/settings.json` holds `"model": "sonnet"`, `"advisorModel": "opus"` and `"env": {"CLAUDE_CODE_SUBAGENT_MODEL": "haiku"}`. A `model` passed on a spawn wins over that variable. The advisor is experimental, spends tokens at its own model's rate and is not offered by every provider. Models rule on a yes: `sonnet high` for every role except `swarm workers`, which is `haiku high`. Cursor has no equivalent. - **Cursor.** The detected models are the slugs the `Task` tool accepts. Write `~/.cursor/rules/zeph-models.mdc` with `alwaysApply: true` frontmatter. diff --git a/plugins/zeph/hooks/hooks.json b/plugins/zeph/hooks/hooks.json new file mode 100644 index 0000000..48de93a --- /dev/null +++ b/plugins/zeph/hooks/hooks.json @@ -0,0 +1,71 @@ +{ + "description": "TokenEconomizer: inject learned repo facts at session start, guard prompt-turns against failing loops, and fold each finished session into what is learned.", + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/scripts/te-hook\"", + "timeout": 15 + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/scripts/te-hook\"", + "timeout": 20 + } + ] + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/scripts/te-hook\"", + "timeout": 60 + } + ] + } + ], + "PostToolUseFailure": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/scripts/te-hook\"", + "timeout": 60 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/scripts/te-hook\"", + "timeout": 10 + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/scripts/te-hook\"", + "timeout": 10 + } + ] + } + ] + } +} diff --git a/plugins/zeph/lib/LICENSE-tokeneconomizer.txt b/plugins/zeph/lib/LICENSE-tokeneconomizer.txt new file mode 100644 index 0000000..9003ea9 --- /dev/null +++ b/plugins/zeph/lib/LICENSE-tokeneconomizer.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/zeph/lib/UPSTREAM.md b/plugins/zeph/lib/UPSTREAM.md new file mode 100644 index 0000000..ece66ef --- /dev/null +++ b/plugins/zeph/lib/UPSTREAM.md @@ -0,0 +1,58 @@ +# TokenEconomizer (vendored) + +Upstream: microsoft/TokenEconomizer, MIT, Copyright (c) 2026 Microsoft. +Commit: `7993da53b42288263e2837c96707a2fc30f90066`. + +## What is copied + +- `tokeneconomizer/` -> `lib/tokeneconomizer/`: every `.py` and `.json` file of the package. No `.md`, no `__pycache__`. +- `plugin/scripts/{te,te-hook,te_bootstrap.py,te.cmd,te-hook.cmd}` -> `scripts/`, exec bits kept. +- `plugin/hooks/hooks.json` -> `hooks/hooks.json`. Claude Code reads this file by convention. +- `LICENSE` -> `lib/LICENSE-tokeneconomizer.txt`. + +## What is not copied + +- `plugin/slash-commands/`: zeph has no slash commands for it. Use the `te` command line. +- Every other host's hook file under `plugin/hooks/` and `plugin/hooks.json`, the other hosts' manifests, and `plugin/{hermes,opencode,pi,codex-skills}`. +- The upstream README, `tests/`, `experiments/`, `docs/`. + +## Local patches + +Two edits to code, both under `lib/tokeneconomizer/plugin/`. + +### 1. Commands in notices (`controller.py`, method `_cmd`) + +The Claude branch no longer names a slash command. It prints the path of the launcher the hooks +write (`paths.launcher_path`). Before: + + if self.host.name in ("claude", "copilot"): # Copilot's TUI runs plugin commands too + ... + return f"te --host {self.host.name} {name}" + +After: + + if self.host.name == "copilot": # Copilot's TUI runs plugin commands too + ... + te = (shlex.quote(launcher_path(self.ctx.env).replace(os.sep, "/")) # not on PATH + if self.host.name == "claude" else "te") + return f"{te} --host {self.host.name} {name}" + +The edit also imports `shlex` and `launcher_path`. + +Why: zeph does not ship the standalone plugin's `/tokeneconomizer:` commands, and `te` is not +on PATH, so a bare `te` in a notice does not run. + +### 2. `toolprune` defaults to `propose` (`config.py`) + +`LiveConfig.toolprune` and `ON_VALUE["toolprune"]` are `"propose"`, upstream `"auto"`. The docstring in +`config.py` and one bullet in `denylist.py` say so. A `toolprune` set in a config file or in +`TE_TOOLPRUNE` still wins, `auto` included. + +Why: `auto` writes deny rules into a repository's `.claude/settings.local.json` without being asked. + +## How to update + +1. Check out the new upstream commit and set it in this file and in `THIRD_PARTY.md`. +2. Copy the files listed above again. Keep the exec bits. +3. Reapply both patches above. Drop one only if upstream now does the same. +4. Run `bun run check`, then `bun run check:full` if the hook needs a live check. diff --git a/plugins/zeph/lib/tokeneconomizer/__init__.py b/plugins/zeph/lib/tokeneconomizer/__init__.py new file mode 100644 index 0000000..eb858fb --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/__init__.py @@ -0,0 +1,21 @@ +"""TokenEconomizer: experience-driven black-box cost control for coding agents. + +The agent stays as it is (Claude Code, Codex, Copilot CLI, Pi). Three mechanisms read its +finished sessions and change what the next ones pay for: + + * `microskills` -- micro-skill synthesis and injection: short repository facts learned from + recurring failures, stated at the start of the next session; + * `toolprune` -- tool pruning: tool definitions a repository never uses, proposed for the + agent's deny list; + * `loopguard` -- failure-loop intervention: a turn stuck repeating the same failure is + redirected once, then stopped or flagged. + +They share one trace reader (`trace`), one cost ledger (`ledger`, `pricing`) and one domain +interface (`domain.DomainAdapter`). `plugin` runs them inside real sessions through each agent's +hooks; the mechanisms never import it. Stdlib only. +""" +from .config import EconomizerConfig, InjectionConfig, SpiralConfig, ToolingConfig +from . import ledger, trace + +__all__ = ["EconomizerConfig", "InjectionConfig", "ToolingConfig", "SpiralConfig", "ledger", + "trace"] diff --git a/plugins/zeph/lib/tokeneconomizer/config.py b/plugins/zeph/lib/tokeneconomizer/config.py new file mode 100644 index 0000000..4740136 --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/config.py @@ -0,0 +1,152 @@ +"""The mechanisms' own configuration, one dataclass each (the plugin's settings are +`plugin.config`): + + * `InjectionConfig` -- micro-skills: which distiller renders the block (`envfacts`, the paid + `distiller`, or both), its caps, and the proposer's cadence; + * `ToolingConfig` -- tool pruning: the evidence threshold, the optional per-task judge, and + Codex's capability controller; + * `SpiralConfig` -- the loop guard as a benchmark harness runs it (the plugin's guard takes + its settings from `plugin.config`). + +`EconomizerConfig` is their union, and `from_args` maps a harness's command-line flags onto it; +unknown attributes default off, so a partial args object is fine. +""" +from dataclasses import dataclass, field + + +@dataclass +class InjectionConfig: + """Injection (learned per-repo operating manual) stage. + + `propose_every` is the paid proposer cadence (one LLM tick per this many tasks). The + injection Stage is the single source of truth for it and rebinds the distiller module + global at build time. Default 5 -- first injection a few tasks earlier and more + revision/grounding ticks over a stream. + """ + enabled: bool = False + propose_every: int = 5 + # Which distiller(s) render the prefix: + # distiller -- the generic paid-proposer manual (`injection.Distiller`); + # envfacts -- LLM-free environment facts learned from recurring evidence + # shapes (`envfacts.EnvFactsDistiller`). Makes NO paid call; + # envfacts+distiller -- both, the free layer first and its claims handed to the + # proposer as already-stated. Paid (the proposer). + profile: str = "distiller" + # Caps on the environment-fact block (`envfacts`): at most this many facts, and this many + # tokens (~4 characters each) for the whole block. 0 keeps envfacts.MAX_FACTS / MAX_TOKENS. + max_facts: int = 0 + max_tokens: int = 0 + + PROFILES = ("distiller", "envfacts", "envfacts+distiller") + + def __post_init__(self): + if self.profile not in self.PROFILES: + raise ValueError(f"injection profile {self.profile!r} is not one of {self.PROFILES}") + + @property + def paid(self): + """True when this stage will make a paid between-task LLM call.""" + return bool(self.enabled and "distiller" in self.profile) + + +@dataclass +class ToolingConfig: + """Tool pruning. + + Evidence pruning (Claude Code / Copilot): + * evidence -- drop a tool loaded-but-unused for >= this many tasks (>0 on). + * evidence_reaudit -- periodically reload the full catalog every this many tasks. + * judge -- add a per-task instruction-aware LLM tool judge. + + Codex capability pruning: + * codex_untool -- enable the evidence-gated, resolve-safe capability controller. + """ + evidence: int = 0 + evidence_reaudit: int = 0 + judge: bool = False + codex_untool: bool = False + + @property + def enabled(self): + return bool(self.evidence or self.codex_untool) + + +@dataclass +class SpiralConfig: + """The loop guard in a benchmark harness (generic for Claude/Copilot; Codex-native for + Codex).""" + guard: bool = False # generic loop guard (Claude / Copilot) + judge: bool = False # sampled LLM trace-judge for the abort decision + nudge: bool = False # rung-1 same-container nudge before abort + nudge_llm: bool = False # LLM-written nudge redirect (vs the count template) + aggr: str = "default" # aggressiveness: conservative | default | aggressive + frozen_envelope: float = None # pre-registered resolved-turn envelope for SHORT + # streams where within-stream p90 never warms up; + # None = learn within-stream only. + codex_spiral: bool = False # Codex-native controller (post-green finalize) + # Which Codex policy: "post-green" (the shipped finalize rule alone) or "defensive" + # (finalize plus every deterministic spiral signature, two distinct nudges per task, + # never an abort). + codex_spiral_profile: str = "post-green" + CODEX_SPIRAL_PROFILES = ("post-green", "defensive") + + def __post_init__(self): + if self.codex_spiral_profile not in self.CODEX_SPIRAL_PROFILES: + raise ValueError(f"codex_spiral_profile must be one of " + f"{self.CODEX_SPIRAL_PROFILES}, got {self.codex_spiral_profile!r}") + + @property + def enabled(self): + return bool(self.guard or self.codex_spiral) + + +def needs_optimizer(config): + """Whether ANY enabled mechanism will make a paid between-task LLM call. + + The three clauses mirror `te_bench.facade.Economizer.__init__` exactly -- it resolves an + optimizer runner for injection when `injection.paid` (enabled AND a profile that + carries the paid `distiller`; the LLM-free `envfacts` profile never calls), for pruning when + `tooling.judge`, and for spiral when the guard is on AND it has a judge or an LLM + nudge writer. Kept as one predicate because callers OUTSIDE the facade need the + aggregate answer: a harness whose mechanism transport must be preflighted should not + pay for (or depend on) that probe when the arm will never call it. Arm `mode` is NOT + the test -- `spiral-only` and `untool-only` are `standalone` and do make paid calls. + + experiments/tests/test_optimizer_basis.py asserts this agrees with the facade for every + arm in the registry, so the two cannot drift. + """ + return bool( + config.injection.paid + or config.tooling.judge + or (config.spiral.guard and (config.spiral.judge or config.spiral.nudge_llm)) + ) + + +@dataclass +class EconomizerConfig: + injection: InjectionConfig = field(default_factory=InjectionConfig) + tooling: ToolingConfig = field(default_factory=ToolingConfig) + spiral: SpiralConfig = field(default_factory=SpiralConfig) + + @classmethod + def from_args(cls, args): + injection = InjectionConfig( + enabled=bool(getattr(args, "inject", False)), + propose_every=int(getattr(args, "propose_every", 0) + or InjectionConfig.propose_every), + profile=str(getattr(args, "inject_profile", "") or InjectionConfig.profile)) + tooling = ToolingConfig( + evidence=int(getattr(args, "untool_evidence", 0)), + evidence_reaudit=int(getattr(args, "untool_evidence_reaudit", 0)), + judge=bool(getattr(args, "untool_judge", False)), + codex_untool=bool(getattr(args, "codex_untool", False))) + spiral = SpiralConfig( + guard=bool(getattr(args, "spiral_guard", False)), + judge=bool(getattr(args, "spiral_judge", False)), + nudge=bool(getattr(args, "spiral_nudge", False)), + nudge_llm=bool(getattr(args, "spiral_nudge_llm", False)), + aggr=getattr(args, "spiral_aggr", "default"), + frozen_envelope=getattr(args, "spiral_frozen_envelope", None), + codex_spiral=bool(getattr(args, "codex_spiral", False)), + codex_spiral_profile=getattr(args, "codex_spiral_profile", None) or "post-green") + return cls(injection=injection, tooling=tooling, spiral=spiral) diff --git a/plugins/zeph/lib/tokeneconomizer/domain.py b/plugins/zeph/lib/tokeneconomizer/domain.py new file mode 100644 index 0000000..1b4f844 --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/domain.py @@ -0,0 +1,77 @@ +"""`DomainAdapter`: everything the mechanisms need to know about where they run. + +The mechanisms are domain-neutral; what is specific to a domain -- how its logs read, which +tools are its work surface, which words name its interpreters and test runners -- enters only +through these methods. The plugin's adapter is `plugin.adapter.LiveAdapter` (a real repository +in a person's session); the benchmark adapters live in `experiments/te_bench/adapters/`. + + load_trajectory -> every mechanism's view of a finished session + tool_usage -> the tools a session used (tool pruning's evidence) + parse_catalog -> the tools a session loaded (what pruning may propose) + protected_tools -> the work surface pruning never touches + inapplicable_tools -> tools no task in this domain can use, by construction + hardcoded_exclusions -> that set, less the tools seen in use so far + spiral_snapshot -> a finished trajectory's loop signals, for the guard's envelope + problem_statements -> {task_id: task text} for the optional per-task tool judge + env_vocabulary -> (optional) the `microskills.Vocabulary` naming this domain's + interpreters, runners, package tools, fetchers and probes + +Running a task and grading it is not on this protocol: that is the caller's job (the plugin's +host hooks, or a benchmark harness). +""" +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class DomainAdapter(Protocol): + """Everything the mechanisms need to know about a task domain.""" + + name: str + + # ---- reading a finished session ---- + def load_trajectory(self, path): + """-> [(tool_name, args_dict, result_text, success_bool)] over a saved session log.""" + ... + + def tool_usage(self, path): + """-> {tool_name: count} over a saved session log.""" + ... + + def parse_catalog(self, run_dir_path, agent): + """-> {tool_name: description} the agent loaded for a task ({} if unavailable).""" + ... + + def parse_catalog_with_source(self, run_dir_path, agent): + """-> ({tool: desc}, source_name) -- OPTIONAL. source_name is None when no catalog + source produced anything, which pruning reports as a defect rather than reading as + "no tools loaded". The default falls back to parse_catalog with source 'unknown'.""" + return self.parse_catalog(run_dir_path, agent), "unknown" + + # ---- tool pruning ---- + def protected_tools(self): + """-> frozenset of tools that must never be dropped (the work surface).""" + ... + + def inapplicable_tools(self): + """-> tuple of tools inapplicable by construction for a single task.""" + ... + + def hardcoded_exclusions(self, used_tools): + """-> the tools to drop without evidence, given those seen in use so far.""" + ... + + # ---- loop guard ---- + def spiral_snapshot(self, path): + """-> a finished trajectory's loop-signal snapshot, for the envelope tracker.""" + ... + + # ---- per-task judge inputs ---- + def problem_statements(self): + """-> {task_id: problem statement}, for the optional per-task tool judge.""" + ... + + # ---- micro-skill vocabulary (optional) ---- + def env_vocabulary(self): + """-> a `microskills.Vocabulary` for this domain (default: Python/git).""" + from .microskills import PYTHON_GIT + return PYTHON_GIT diff --git a/plugins/zeph/lib/tokeneconomizer/ledger.py b/plugins/zeph/lib/tokeneconomizer/ledger.py new file mode 100644 index 0000000..7e781e8 --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/ledger.py @@ -0,0 +1,41 @@ +"""One cost definition for every mechanism. + +The cost of a task (a session, in the plugin) is the agent's EXECUTION cost plus every +mechanism's LLM OVERHEAD, both on the cache-aware effective basis of `pricing.effective_tokens`: + + task_cost(t) = effective_exec(t) + overhead(t) + amortized(T) = (1/T) * sum_{t<=T} task_cost(t) + +`overhead()` sums the per-mechanism token fields a mechanism records. Every field is real LLM +spend made on the agent's behalf, so a mechanism that adds paid proposer, judge or redirect calls +pays for them in the same account as the work they are meant to save. The plugin's session +ledger (`plugin.accounting`) and the experiments' aggregation scripts both read this one +definition, so the recorded and the reported cost cannot drift apart. +""" +from . import pricing + +# Per-task mechanism-overhead token fields, by owning mechanism. All are real +# mechanism-internal LLM cost that must be amortized into the honest task cost. +OVERHEAD_KEYS = ( + "optimizer_tokens", # injection: paid between-task manual proposer (manual4) + "untool_classify_tokens", # untooling: one-shot tool-classifier LLM call + "untool_judge_tokens", # untooling: per-task instruction-aware tool judge + "codex_untool_adapt_tokens", # codex untooling: repository capability classifier + "spiral_judge_tokens", # spiral: paid live trace-judge + "spiral_nudge_writer_tokens", # spiral: targeted-nudge writer +) + + +def _num(x): + return x if isinstance(x, (int, float)) else 0 + + +def overhead(row): + """Sum every mechanism-overhead token field present on a stream row.""" + return sum(_num(row.get(k)) for k in OVERHEAD_KEYS) + + +def effective_exec(row): + """Cache-aware effective execution cost of a task (pricing.effective_tokens).""" + return pricing.effective_tokens(row) + diff --git a/plugins/zeph/lib/tokeneconomizer/loopguard/__init__.py b/plugins/zeph/lib/tokeneconomizer/loopguard/__init__.py new file mode 100644 index 0000000..0789328 --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/loopguard/__init__.py @@ -0,0 +1,27 @@ +"""Failure-loop intervention: notice a prompt-turn stuck in a failing loop, redirect it once, +then stop it (headless) or tell the person (interactive). + + * `state` -- `SpiralState`, the per-call fold of a trajectory's loop signals; + * `rules` -- thresholds, the free gate, the strict heuristic, `assess_abort`, the redirect; + * `envelope` -- the per-repository length of turns that ended well, and its storage; + * `shell_edits` -- edits made through the shell, counted like edit-tool edits; + * `turn` -- `TurnGuard`, the guard for one prompt-turn, one tool call at a time; + * `judge` -- the optional paid stuck judge and redirect writer. + +Stdlib only; never imports the plugin runtime. +""" +from .envelope import (EnvelopeTracker, base_thresholds, load_envelope, record_turn, + save_envelope, thresholds) +from .judge import llm_nudge_writer, llm_stuck_judge +from .rules import (DEFAULT_THRESHOLDS, SPIRAL_LEVELS, assess_abort, gate_for_judge, is_stuck, + nudge_text, scaled_thresholds) +from .shell_edits import fold_shell_edits, shell_edit_targets +from .state import SpiralState, canon_tool, completed_calls, state_from_trajectory +from .turn import VERIFY_RE, TurnGuard + +__all__ = ["EnvelopeTracker", "base_thresholds", "load_envelope", "record_turn", + "save_envelope", "thresholds", "llm_nudge_writer", "llm_stuck_judge", + "DEFAULT_THRESHOLDS", "SPIRAL_LEVELS", "assess_abort", "gate_for_judge", "is_stuck", + "nudge_text", "scaled_thresholds", "fold_shell_edits", "shell_edit_targets", + "SpiralState", "canon_tool", "completed_calls", "state_from_trajectory", + "VERIFY_RE", "TurnGuard"] diff --git a/plugins/zeph/lib/tokeneconomizer/loopguard/envelope.py b/plugins/zeph/lib/tokeneconomizer/loopguard/envelope.py new file mode 100644 index 0000000..b2d8cc9 --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/loopguard/envelope.py @@ -0,0 +1,205 @@ +"""The per-repository envelope: how long a turn that ended well usually runs. + +`EnvelopeTracker` learns, from turns that ended well only, a percentile of their lengths (the +envelope past which a stuck trajectory may be acted on) and the detector thresholds on top of +the preset level. A turn's own outcome only ever gates LATER turns. The functions below keep a +tracker in a repository's state store between sessions, under the store's lock, since two +sessions in one repository share it. +""" +import math + +from .rules import scaled_thresholds + + +def _percentile(xs, p): + """Linear-interpolated p-th percentile of xs (0<=p<=100). xs need not be sorted.""" + if not xs: + return None + xs = sorted(xs) + n = len(xs) + if n == 1: + return float(xs[0]) + i = (p / 100.0) * (n - 1) + lo = int(i) + frac = i - lo + if lo + 1 >= n: + return float(xs[-1]) + return xs[lo] + frac * (xs[lo + 1] - xs[lo]) + + +class EnvelopeTracker: + """Per-repo resolved-turn envelope AND runtime-learned detection thresholds. + + Envelope: margin * the p of turn-counts among RESOLVED tasks seen so far. Using a + PERCENTILE (default p90), not the max, makes the gate robust to a single very-long + resolve — empirically one 115-turn xarray resolve set a max-based envelope to ~144 and + disabled the guard for every 40-60-turn spiral below it; p90 ignores that lone outlier + (envelope ~32) while staying HIGH on repos like matplotlib where long resolves are + COMMON (so productive-long tasks stay protected). Stays None until >=min_samples + resolved tasks exist (don't trust a percentile of a handful of points), so we never + abort on a repo we know little about yet. + + Thresholds: `thresholds()` derives the FULL detector threshold dict from the SAME + resolved-task history, so the guard adapts to the agent/repo's actual turn scale + instead of the hardcoded Copilot-scale DEFAULT_THRESHOLDS, whose backstop lies above + Claude Code's 80-turn cap. Turn-scale gates + scale DOWN to the learned distribution; signal gates keep DEFAULT as a FLOOR so the + learned dict is never MORE trigger-happy than the hand-tuned one (resolve-safety). Fed + only by RESOLVED tasks (same causal rule as the envelope), so a task's own outcome can + only gate FUTURE tasks, never itself.""" + def __init__(self, margin=None, pct=None, min_samples=None, level="default", + frozen_envelope=None): + # `level` selects the aggressiveness preset (SPIRAL_LEVELS). It sets the BASE + # thresholds this tracker starts from AND the envelope margin/percentile/min-samples; + # explicit margin/pct/min_samples args still win over the preset when given. + self.level = level + self.base_thr = scaled_thresholds(level) + self.margin = margin or self.base_thr["envelope_margin"] + self.pct = pct if pct is not None else self.base_thr["envelope_pct"] + self.min_samples = (min_samples if min_samples is not None + else self.base_thr["envelope_min_samples"]) + # FROZEN envelope (pre-registered hyperparameter): when set, `envelope` returns this + # value from task 1, bypassing the >=min_samples warm-up. For SHORT streams (Web-Bench + # = 20 tasks, ~5 resolved at ~25% Pass@1) the percentile never reaches min_samples, so + # a within-stream-learned envelope would stay None the whole run and the guard would + # never engage. A frozen scalar (calibrated once from SWE-bench/held-out, IDENTICAL + # across all streams -- a fixed hyperparameter, NOT a prior pooled across the streams) + # lets the guard engage while preserving stream independence. None => today's behavior. + self.frozen_envelope = frozen_envelope + self.resolved_turns = [] # all RESOLVED tasks' turn counts (for the percentile) + self.resolved_snaps = [] # per-resolved-task SpiralState.snapshot() dicts (signals) + + def update(self, turns, resolved, snapshot=None): + """Record a completed task. Only RESOLVED tasks feed the baseline. `snapshot` is an + optional SpiralState.snapshot() dict (edit_churn/distinct_edit_files/error_outputs/ + stagnation/...) captured from that task's trajectory; when omitted only the + turn-envelope learns (back-compat with callers that don't reconstruct the state).""" + if resolved and turns: + self.resolved_turns.append(turns) + if snapshot: + self.resolved_snaps.append(snapshot) + + @property + def envelope(self): + if len(self.resolved_turns) < self.min_samples: + # cold start: fall back to the frozen pre-registered envelope if one was set + # (short-stream case); else None == "don't trust a handful of points yet". + return self.frozen_envelope + return _percentile(self.resolved_turns, self.pct) * self.margin + + def thresholds(self, max_turns=None): + """Return the detector threshold dict to hand to is_stuck/gate_for_judge/ + assess_abort. Starts from the LEVEL-scaled base (scaled_thresholds(self.level); == + DEFAULT_THRESHOLDS for level 'default') and, once >=min_samples RESOLVED tasks + exist, overrides the learned keys from this stream's resolved-task distribution. + Before warm-up (or with no data) it returns the base verbatim, so behavior is + unchanged until the stream has learned enough — exactly like the envelope gating + None today. Learned signal-gates floor against the SCALED base, so an 'aggressive' + level genuinely lowers those floors (and 'conservative' raises them). Pass + `max_turns` (the run's turn cap) to make the hard backstop REACHABLE under the cap.""" + base = self.base_thr + thr = dict(base) + env = self.envelope + # cap-aware backstop: reachable even under a tight turn cap. The Copilot-scale + # `backstop_mult * envelope` (~110 turns) lies above Claude's 80-turn cap, so it is + # clamped under 0.9*cap and an extreme outlier still aborts in-cap. + if env is not None: + bt = env * thr["backstop_mult"] + if max_turns: + bt = min(bt, 0.9 * max_turns) + thr["backstop_turns"] = bt + if len(self.resolved_turns) < self.min_samples: + return thr # cold start: level-scaled base (+ backstop_turns if env exists) + + # --- turn-scale gates: relative to the learned resolved-turn distribution. On a + # short-turn agent (Claude p90~35) this drops the judge gate from 18 -> ~10 so the + # guard can engage before the cap; on a long-turn agent (Copilot p90~150+) the + # clamp keeps it at the base ceiling (no change). --- + p90t = _percentile(self.resolved_turns, 90) or 0 + + def _clamp(v, lo, hi): + return int(max(lo, min(hi, round(v)))) + thr["gate_min_turns"] = _clamp(0.6 * p90t, 6, base["gate_min_turns"]) + thr["min_turns"] = _clamp(0.6 * p90t, 8, base["min_turns"]) + + # --- signal gates: treat RESOLVED runs as the "normal" band and sit just ABOVE its + # p90, but never BELOW the (level-scaled) base floor (so the learned dict is never + # more trigger-happy than the level asks — protects resolve-safety on churny-but- + # productive repos, where this RAISES the bar). Needs the per-task snapshots. --- + if self.resolved_snaps: + def _sig(key): + return [s.get(key, 0) or 0 for s in self.resolved_snaps] + thr["edit_churn"] = max(base["edit_churn"], + math.ceil((_percentile(_sig("edit_churn"), 90) or 0) + 1)) + thr["distinct_edit_files"] = max( + base["distinct_edit_files"], + math.ceil((_percentile(_sig("distinct_edit_files"), 90) or 0) + 1)) + thr["error_outputs"] = max( + base["error_outputs"], + math.ceil((_percentile(_sig("error_outputs"), 90) or 0) + 1)) + thr["gate_error_outputs"] = max(base["gate_error_outputs"], + thr["error_outputs"]) + thr["stagnation"] = max(base["stagnation"], + round(_percentile(_sig("stagnation"), 90) or 0, 3)) + return thr + + +# ---- the per-repository envelope --------------------------------------------------------- +ENVELOPE_HISTORY = 500 # recent ended-green turns kept for the percentile + + +# Overrides that shape the envelope itself, passed to the tracker; the rest are pinned over the +# thresholds it returns. +_ENVELOPE_KEYS = {"envelope_margin": "margin", "envelope_pct": "pct", + "envelope_min_samples": "min_samples"} + + +def load_envelope(store, level="default", overrides=None): + d = store.read("envelope.json") or {} + ov = overrides or {} + tracker = EnvelopeTracker(level=level, **{ + arg: ov[key] for key, arg in _ENVELOPE_KEYS.items() if key in ov}) + tracker.resolved_turns = [int(x) for x in d.get("resolved_turns", []) if x] + tracker.resolved_snaps = [s for s in d.get("resolved_snaps", []) if isinstance(s, dict)] + return tracker + + +def thresholds(tracker, overrides=None): + """The thresholds a turn is checked against: the preset, what this repository's history + learned on top of it, then a person's pinned values (``), which win.""" + thr = tracker.thresholds(max_turns=None) + for key, value in (overrides or {}).items(): + if key not in _ENVELOPE_KEYS: + thr[key] = value + if "backstop_mult" in (overrides or {}) and tracker.envelope is not None: + thr["backstop_turns"] = tracker.envelope * thr["backstop_mult"] + return thr + + +def base_thresholds(level="default", overrides=None): + """The thresholds before any learning: the preset with a person's pinned values on top. + What `te config show` reports, so the numbers a setting replaces are visible.""" + thr = scaled_thresholds(level) + thr.update(overrides or {}) + return thr + + +def save_envelope(store, tracker): + store.write("envelope.json", { + "level": tracker.level, + "resolved_turns": tracker.resolved_turns[-ENVELOPE_HISTORY:], + "resolved_snaps": tracker.resolved_snaps[-ENVELOPE_HISTORY:]}) + + +def record_turn(store, guard, level="default", stopped_normally=True, overrides=None): + """Fold a finished turn into the envelope -- under the store lock, since two sessions in + one repository share it. Only turns that ended green feed it, as only resolved tasks fed + the experiments' envelope; a turn's own outcome gates only later turns.""" + # The snapshot is of the WHOLE turn (`guard.whole`), not the post-nudge segment: the + # experiments snapshot a resolved task's full trajectory (`spiral_snapshot(transcript)`). + with store.locked("envelope"): + tracker = load_envelope(store, level, overrides) + tracker.update(guard.cum_turns, guard.resolved_proxy(stopped_normally), + snapshot=guard.whole.snapshot()) + save_envelope(store, tracker) + return tracker diff --git a/plugins/zeph/lib/tokeneconomizer/loopguard/judge.py b/plugins/zeph/lib/tokeneconomizer/loopguard/judge.py new file mode 100644 index 0000000..0d4142f --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/loopguard/judge.py @@ -0,0 +1,102 @@ +"""The loop guard's two optional paid calls: a stuck judge and a redirect writer. + +Both read the same leakage-safe digest of the agent's recent actions +(`SpiralState.recent_digest`: commands, searches, edited file basenames, error signatures -- +never file contents or the task text). The judge decides stuck-versus-productive when the free +gate is open; the writer turns the redirect from a count template into one that names the +pattern it sees. Each returns its effective-token cost so the caller can charge it to the +session's ledger, and falls back to the free path on any failure. +""" +import json +import re + +from ..pricing import runner_effective_or_approx as _runner_effective_or_approx + +STUCK_JUDGE_SYSTEM = ( + "You monitor an AI coding agent that is partway through ONE task in a software repo. " + "A cheap heuristic flagged its recent process as a possible UNPRODUCTIVE LOOP. Read " + "the leakage-safe digest of its RECENT actions and judge whether it is genuinely " + "STUCK — repeating the same kind of edit/test/failure with no progress toward green " + "tests, unlikely to recover if it keeps going the same way — versus still making " + "real progress (changing failures, narrowing the problem, exploring new hypotheses).\n\n" + "Judge ONLY the workflow from the digest; do NOT infer the task's solution or which " + "lines to change. Favor SPARING (stuck=false) when there is any sign of progress; " + "only return stuck=true with high confidence for a clear, repetitive dead-end.\n" + "Return ONLY a JSON object: {\"stuck\": bool, \"confidence\": <0.0-1.0>, " + "\"reason\": \"\"}." +) + + +def llm_stuck_judge(digest, runner, model="agent"): + """The sampled stuck judge. `digest` is a leakage-safe recent-process string + (`SpiralState.recent_digest()`). Returns a verdict dict + {stuck: bool|None, confidence: float, reason: str, _tokens: number}; stuck=None on any + failure (the caller treats None/ambiguous by falling back to the envelope gate). + `_tokens` is the REAL token cost of this paid judge call (input+output+cache, from the + runner's usage block; a char-based approximation if the runner couldn't recover it) so + the caller can charge it to the ledger. 0 when no call was made.""" + if runner is None or not digest: + return {"stuck": None, "confidence": 0.0, "reason": "no-runner", "_tokens": 0} + prompt = (STUCK_JUDGE_SYSTEM + "\n\nRecent process digest:\n" + digest + + "\n\nReturn the JSON verdict:") + try: + raw, _real = runner(prompt, model) + except Exception as e: + return {"stuck": None, "confidence": 0.0, + "reason": f"runner-error:{e}"[:60], "_tokens": 0} + raw = raw or "" + # EFFECTIVE (cache-aware) cost when the runner recovered usage; else approximate on the + # SAME basis: an uncached one-shot -> prompt is fresh input (weight 1), reply is output + # (weight 5). Keeps mechanism cost comparable to exec's cache-aware effective tokens. + _tokens = _runner_effective_or_approx(runner, prompt, raw, _real) + verdict = {"stuck": None, "confidence": 0.0, "reason": "", "_tokens": _tokens} + m = re.search(r"\{.*\}", raw, re.S) + if m: + try: + obj = json.loads(m.group(0)) + verdict["stuck"] = (bool(obj["stuck"]) if "stuck" in obj + and obj["stuck"] is not None else None) + verdict["confidence"] = max(0.0, min(1.0, float(obj.get("confidence", 0) or 0))) + verdict["reason"] = str(obj.get("reason", ""))[:160] + except Exception: + pass + return verdict + + +NUDGE_WRITER_SYSTEM = ( + "An AI coding agent is stuck in a REPETITIVE, UNPRODUCTIVE loop partway through one " + "task in a software repo. You are given a leakage-safe digest of its RECENT ACTIONS " + "only (tool names, shell commands, searched patterns, edited file BASENAMES, and " + "error SIGNATURES — never file contents or the task description). Write a SHORT " + "redirect (2-4 sentences) addressed to the agent that: (1) names the specific " + "repetitive pattern you actually see in the digest (e.g. re-editing the same file, " + "re-running the same test to the same failure); (2) proposes a MATERIALLY DIFFERENT " + "next step (a different file/root-cause to consider, re-reading the failing test's " + "expectation, verifying a new hypothesis before editing again).\n" + "HARD CONSTRAINTS: Do NOT tell it to stop, give up, or reduce effort — only redirect. " + "Do NOT infer the task's solution, name specific line numbers to change, or reference " + "any code/identifier you cannot see in the digest. Output ONLY the redirect as plain " + "text — no preamble, no JSON, no headings." +) + + +def llm_nudge_writer(digest, runner, model="agent"): + """The sampled redirect writer. `digest` is the same leakage-safe recent-process + string the judge reads. Returns {"text": str, "_tokens": number}: a targeted redirect and + the effective token cost of the call, on the judge's basis. On any failure returns + {"text": "", "_tokens": 0} so the caller falls back to `rules.nudge_text`.""" + if runner is None or not digest: + return {"text": "", "_tokens": 0} + prompt = (NUDGE_WRITER_SYSTEM + "\n\nRecent process digest:\n" + digest + + "\n\nWrite the redirect:") + try: + raw, _real = runner(prompt, model) + except Exception: + return {"text": "", "_tokens": 0} + raw = (raw or "").strip() + if not raw: + return {"text": "", "_tokens": 0} + # EFFECTIVE (cache-aware) cost when the runner recovered usage; else approximate on the + # SAME model-priced basis as llm_stuck_judge. + _tokens = _runner_effective_or_approx(runner, prompt, raw, _real) + return {"text": raw[:1200], "_tokens": _tokens} diff --git a/plugins/zeph/lib/tokeneconomizer/loopguard/rules.py b/plugins/zeph/lib/tokeneconomizer/loopguard/rules.py new file mode 100644 index 0000000..a9c6801 --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/loopguard/rules.py @@ -0,0 +1,198 @@ +"""When a trajectory counts as stuck, and what to do about it. + +Three tiers, cheapest first: + + * `gate_for_judge` -- free, every call: is the recent trace worth a paid look at all? + * a paid judge -- optional (`judge.llm_stuck_judge`), only when the gate is open; + * `is_stuck` -- the strict heuristic decision used when no judge is wired: churn or + scatter, AND sustained errors, AND repeated identical failures. + +`assess_abort` runs the cascade against a per-repository envelope (how long a turn that ended +well usually runs, `envelope.EnvelopeTracker`) with a hard backstop the judge cannot veto. +`nudge_text` is the redirect the guard sends first: it mirrors only the agent's own actions +back at it, carries no outside knowledge, and never tells it to stop. +""" +# ---- detector thresholds ----------------------------------------------------- +# The "stuck" signature (calibrated on the measured separation: spirals showed first- +# 40-turn edit_churn ~6 vs ~1.5 normal, distinct_edit_files ~2.5 vs ~1, error_outputs +# ~9 vs ~3). We require a CONJUNCTION (churn AND errors/scatter AND some repetition) +# so productive-but-hard tasks (high activity, but CHANGING failures) are spared. +DEFAULT_THRESHOLDS = { + "min_turns": 20, # don't judge stuck before the solve loop has run a while + "edit_churn": 4, # >=4 edits to one file + "distinct_edit_files": 3, # OR edits scattered across >=3 files + "error_outputs": 6, # sustained error density + "stagnation": 0.20, # >=20% of failures are repeats of an earlier one + "envelope_margin": 1.25, # restart/abort only beyond margin x the resolved-turn pctl + "envelope_pct": 90, # use the p90 of resolved turns (NOT max): one very long + # resolve would set a max-based envelope far out (see + # EnvelopeTracker); p90 ignores the lone outlier. + "envelope_min_samples": 5, # need >=5 resolved tasks before trusting the percentile + "judge_confidence": 0.7, # LLM trace-judge must be >=this confident to drive an abort + "backstop_mult": 2.5, # HARD backstop: beyond this multiple of the envelope, a + # stuck trajectory aborts REGARDLESS of the judge's verdict. + # A judge can read multi-file thrashing far past the envelope + # as "exploration"; it must not be able to veto such an + # outlier. + # ---- cheap GATE to the judge (Tier-0): permissive "worth a paid look?" trigger. + # Sensitive on purpose (catch candidates); the judge supplies precision. Far cheaper + # to evaluate than the judge, and far more permissive than is_stuck (which is the + # strict heuristic DECISION used only in the no-judge fallback). + "gate_min_turns": 18, # don't wake the judge before the loop has had time to form + "gate_error_outputs": 8, # OR: a lot of errors even without an exact repeat +} + + +# A single LEVEL scales the thresholds the guard starts from (the per-repository +# EnvelopeTracker then learns on top, flooring learned signal gates against it). 'default' is +# DEFAULT_THRESHOLDS exactly. 'aggressive' mainly wakes the nudge -- lower judge confidence, an +# earlier gate, `nudge_on_ambiguous` -- and pulls the backstop in modestly (2.5x -> 1.8x); +# 'conservative' spares harder, for churny-but-productive repositories. +# nudge_on_ambiguous: a judge-AMBIGUOUS trajectory past the envelope gets the redirect +# (never a stop) instead of being spared outright. Only 'aggressive' sets it. +SPIRAL_LEVELS = { + "conservative": { + "judge_confidence": 0.85, "envelope_margin": 1.5, "backstop_mult": 3.5, + "stagnation": 0.30, "gate_min_turns": 24, "min_turns": 28, + "edit_churn": 5, "error_outputs": 8, "envelope_min_samples": 7, + }, + "default": {}, # verbatim DEFAULT_THRESHOLDS — reproduces pre-knob behavior exactly + "aggressive": { + "judge_confidence": 0.55, "envelope_margin": 1.0, "backstop_mult": 1.8, + "stagnation": 0.12, "gate_min_turns": 12, "min_turns": 14, + "edit_churn": 3, "error_outputs": 4, "envelope_min_samples": 3, + "nudge_on_ambiguous": True, + }, +} + + +def scaled_thresholds(level="default"): + """Return DEFAULT_THRESHOLDS overlaid with the named LEVEL's overrides (see + SPIRAL_LEVELS). Unknown level falls back to 'default' (verbatim defaults). This is the + BASE the EnvelopeTracker starts from; per-repo learning floors on top of it.""" + thr = dict(DEFAULT_THRESHOLDS) + thr.update(SPIRAL_LEVELS.get(level, SPIRAL_LEVELS["default"])) + return thr + + +def gate_for_judge(state, thr=None): + """TIER-0 (free, every turn): cheap rule-based trigger deciding whether the recent + trace is worth ELEVATING to the paid LLM judge. Permissive — it only needs a sign of + POSSIBLE trouble after the loop has had time to form: a repeated identical failure + (the cheapest 'no progress' signal) OR a high error density. Productive trajectories + (changing failures, few repeats) mostly keep this gate CLOSED, so the judge is rarely + consulted; the judge then makes the precise stuck-vs-productive call. This separation + is what keeps the judge from being a per-step tax.""" + thr = thr or DEFAULT_THRESHOLDS + if state.turns < thr["gate_min_turns"]: + return False + return (state.repeated_fail_sigs >= 1 + or state.error_outputs >= thr["gate_error_outputs"]) + + +def is_stuck(state, thr=None): + """Strict heuristic 'this looks like an unproductive loop' classifier — the DECISION + used only in the no-judge fallback. Must have run a while AND show churn/scatter AND + repeated identical failures (stagnation): the last term is what separates a doomed + spiral from a productive hard grind. (When the judge is wired, gate_for_judge is the + cheap trigger and the judge is the decision; is_stuck is not used.)""" + thr = thr or DEFAULT_THRESHOLDS + if state.turns < thr["min_turns"]: + return False + churny = (state.edit_churn >= thr["edit_churn"] + or state.distinct_edit_files >= thr["distinct_edit_files"]) + noisy = state.error_outputs >= thr["error_outputs"] + repeating = state.stagnation >= thr["stagnation"] + return churny and noisy and repeating + + +def assess_abort(state, envelope=None, judge=None, thr=None): + """Decide whether to abort, TRACE-FIRST, as an explicit TWO-TIER cascade. Returns + (abort: bool, reason: str). + + TIER 0 — cheap rule-based GATE (free, every turn): gate_for_judge(). Decides only + whether the recent trace is WORTH a paid look. Permissive; productive trajectories + mostly keep it closed, so the judge is rarely consulted (this is what makes the + judge not a per-step tax). + TIER 1 — paid LLM JUDGE (only when the gate is open, and the caller additionally + rate-limits it): reads a leakage-safe digest of the RECENT actions and decides + stuck-vs-productive. The judge — not the step count — drives the outcome: + - STUCK, confidence>=judge_confidence -> ABORT, even within the envelope (a + clearly-doomed loop shouldn't burn tokens up to the envelope first); + - PRODUCTIVE -> SPARE, even past the envelope (progress shows in the trace); + - ambiguous -> defer to the envelope fallback. + FALLBACK — when NO judge is wired (judge=None): the strict is_stuck() heuristic plus + the per-repo resolved-turn envelope (the Phase-1.5 behavior), so the guard still + works cheaply without an LLM. + """ + thr = thr or DEFAULT_THRESHOLDS + + # HARD BACKSTOP (checked BEFORE the judge): an extreme outlier — far past the + # envelope AND stuck by the strict heuristic — aborts regardless of any judge + # verdict. The judge cannot veto this; it exists because an LLM judge can read thrashing + # far past the envelope as "exploration". + # `backstop_turns` (learned, cap-aware) is preferred when the tracker supplied it, so + # the backstop stays REACHABLE under a tight turn cap; else fall back to the + # multiplier-on-envelope form (the Copilot-scale behavior). + backstop_turns = thr.get("backstop_turns") + if backstop_turns is None and envelope is not None: + backstop_turns = envelope * thr["backstop_mult"] + if (backstop_turns is not None + and state.turns >= backstop_turns + and is_stuck(state, thr)): + return True, (f"backstop:{state.turns}>={backstop_turns:.0f}" + f"turns stagnation={state.stagnation:.2f}") + + if judge is not None: + # TWO-TIER: gate -> judge. The gate opens on the cheap rule-based trigger OR when + # the trajectory is already PAST this repo's typical resolved length (envelope) — + # an over-envelope run is worth a paid judge look even without an exact repeated + # failure yet, which is what lets the guard engage on a short-turn agent whose + # spirals hit the cap before accumulating a repeat signature. + # `gate_over_envelope=False` (the plugin's) leaves the gate to the trouble signs alone. + over_envelope = (envelope is not None and state.turns >= envelope + and thr.get("gate_over_envelope", True)) + if not (gate_for_judge(state, thr) or over_envelope): + return False, "gate-closed" + try: + v = judge(state.recent_digest(envelope=envelope)) # caller rate-limits + except Exception: + v = None + if not v: + return False, "judge-throttled" + conf = float(v.get("confidence", 0) or 0) + if v.get("stuck") and conf >= thr["judge_confidence"]: + return True, f"judge-stuck@{conf:.2f}:{str(v.get('reason',''))[:60]}" + if v.get("stuck") is False: + return False, "judge-productive" + # judge AMBIGUOUS (stuck=None): do NOT abort on the (possibly under-calibrated, + # early-stream) envelope alone: a resolvable task can run just past an envelope + # learned from few turns. Ambiguity => SPARE; the hard backstop + # (2.5x envelope AND is_stuck, checked above) remains the only envelope-driven kill, + # and it sits well beyond any resolvable task's length. + return False, "judge-ambiguous-spared" + + # FALLBACK (no judge): strict heuristic + envelope safety gate. + if not is_stuck(state, thr): + return False, "not-stuck" + if envelope is not None and state.turns >= envelope: + return True, f"envelope:{state.turns}>={envelope:.0f}" + return False, "stuck-but-within-envelope" + + +def nudge_text(state): + """The redirect: mirror the agent's OWN repeated actions back at it. Contains + nothing but a summary of what it already did — leakage-safe by construction, and + framed to REDIRECT effort, never to stop it.""" + busiest = max(state.edit_counts.items(), key=lambda kv: kv[1])[0] \ + if state.edit_counts else "one file" + return ( + "Process check (automated): so far you've made " + f"{sum(state.edit_counts.values())} edits across " + f"{state.distinct_edit_files} file(s) (most to `{busiest}`) and run " + f"{state.test_runs} verification(s), and the same failure has recurred " + f"{state.repeated_fail_sigs} time(s) without the tests going green. This " + "looks like a repetitive loop. Do NOT stop — instead step back and try a " + "MATERIALLY DIFFERENT hypothesis: re-read the failing test's expectation, " + "consider a different file or root cause than the ones you've been editing, " + "and verify the new hypothesis directly before editing again.") diff --git a/plugins/zeph/lib/tokeneconomizer/loopguard/shell_edits.py b/plugins/zeph/lib/tokeneconomizer/loopguard/shell_edits.py new file mode 100644 index 0000000..45a12c4 --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/loopguard/shell_edits.py @@ -0,0 +1,332 @@ +"""Edits made through the shell, which an edit-tool counter does not see. + +`SpiralState` counts an edit only when an edit TOOL makes it (Edit/Write/str_replace). An agent +that edits through Bash -- `sed -i`, `perl -pi`, a redirect or `tee` into a source file, an +inline Python script that writes the file back, `patch`/`git apply`, 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 them +after the regular update, so the call still counts once. +""" +import re +import shlex + +from .state import basename + +# `<<<` is a here-string: its word is the input itself, so no body follows on the next lines. +_HEREDOC_START = re.compile(r"(?", ">>", ">|", "&>", "&>>"} # redirects that write their operand +_SKIP_OPERAND = {"<", "<<", "<<<", "<&", ">&", "<>"} # input, heredoc tags, fd duplication +# Redirect and `tee` targets count only when they look like source, so `> out.log` or +# `| tee /tmp/run.txt` -- capturing output -- is not mistaken for an edit. +_SOURCE_FILE = re.compile( + r"\.(?:py|pyi|pyx|pxd|js|jsx|mjs|cjs|ts|tsx|rs|go|java|kt|kts|scala|c|cc|cpp|cxx|h|hh|hpp|" + r"rb|php|cs|swift|m|mm|sh|bash|zsh|lua|jl|ex|exs|erl|hs|ml|clj|sql|toml|ya?ml|json|cfg|ini|" + r"conf|md|rst|html?|css|scss|vue|svelte|xml|gradle|properties|in)$", re.I) +_PYTHON = re.compile(r"(?:^|[\s/;&|(])python\d?(?:\.\d+)?\b") +_PY_OPEN_LIT = re.compile(r"open\(\s*(['\"])([^'\"\n]+)\1\s*,\s*(['\"])([^'\"]*)\3") +_PY_OPEN_VAR = re.compile(r"open\(\s*([A-Za-z_]\w*)\s*,\s*(['\"])([^'\"]*)\2") +_PY_WRITE_PATH_LIT = re.compile( + r"(?:pathlib\.)?Path\(\s*(['\"])([^'\"\n]+)\1\s*\)\.write_(?:text|bytes)\(") +_PY_WRITE_PATH_VAR = re.compile(r"\b([A-Za-z_]\w*)\.write_(?:text|bytes)\(") +# 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): + return bool(path) and not path.startswith(("/dev/", "/proc/", "/tmp/")) + + +def _unquote(t): + return t[1:-1] if len(t) >= 2 and t[0] == t[-1] and t[0] in "'\"" else t + + +def _split_heredocs(cmd): + """(the command's shell text without heredoc bodies, the bodies).""" + shell, bodies, tag, body = [], [], None, [] + for line in cmd.split("\n"): + if tag is not None: + if line.strip() == tag: + bodies.append("\n".join(body)) + tag, body = None, [] + else: + body.append(line) + continue + shell.append(line) + m = _HEREDOC_START.search(line) + if m: + tag = m.group(2) + if tag is not None: + bodies.append("\n".join(body)) + return "\n".join(shell), bodies + + +def _tokens(text): + """Shell words and operators. Quotes stay on quoted words, so a quoted `'>'` or `'|'` is + never read as an operator; ValueError on unbalanced quotes.""" + lex = shlex.shlex(text, posix=False, punctuation_chars="();<>|&\n") + lex.whitespace = " \t\r" + lex.whitespace_split = True + return list(lex) + + +def _commands(shell): + """(simple commands as unquoted word lists, the files their redirects write).""" + try: + streams = [_tokens(shell)] + except ValueError: # one bad line must not hide the others + streams = [] + for line in shell.split("\n"): + try: + streams.append(_tokens(line) + ["\n"]) + except ValueError: + continue + cmds, writes = [], [] + for toks in streams: + cur, i = [], 0 + while i < len(toks): + t = toks[i] + if t in _OPS: + if cur: + cmds.append(cur) + cur = [] + elif t in _OUT or t in _SKIP_OPERAND: + if cur and cur[-1].isdigit(): # `2>`: the fd number is not an operand + cur.pop() + if t in _OUT and i + 1 < len(toks) and toks[i + 1] not in _OPS: + writes.append(_unquote(toks[i + 1])) + i += 1 + else: + cur.append(_unquote(t)) + i += 1 + if cur: + cmds.append(cur) + return cmds, writes + + +def _inplace_files(tokens, inplace_flag, script_flag): + """File operands of an in-place editor (`sed -i`, `perl -pi`), or [] if not in place. + `script_flag(t)` says where an option puts the script: "next" for the following word + (`-e`, `--file`), "inline" for the option itself (`-e's/a/b/'`, `--expression=...`).""" + if not any(inplace_flag(t) for t in tokens[1:]): + return [] + files, have_script, skip = [], False, False + for t in tokens[1:]: + if skip: + skip, have_script = False, True + continue + if not t or t.startswith("-"): + where = script_flag(t) if t else None + if where == "next": + skip = True # the next token is the script + elif where == "inline": + have_script = True + continue + if not have_script: + have_script = True # the first operand is the script + continue + files.append(t) + return files + + +def _short_script_flag(t, script_letters, stop_letters): + """Where a short-option cluster such as `-ne`, `-pe's/a/b/'` or `-i.bak` puts the script. + A letter in `stop_letters` takes the rest of the word as its own value (`-i.bak`).""" + if t.startswith("--") or len(t) < 2: + return None + for k, c in enumerate(t[1:], start=2): + if c in stop_letters: + return None + if c in script_letters: + return "inline" if t[k:] else "next" + return None + + +def _sed_script_flag(t): + if t in ("--expression", "--file"): + return "next" + if t.startswith(("--expression=", "--file=")): + return "inline" + return _short_script_flag(t, "ef", "i") + + +# perl options whose value is the rest of the word: `-Ilib`, `-Mwarnings`, `-CSD`, `-F/,/` ... +_PERL_VALUE_LETTERS = "IMmxdDCF" + + +def _perl_script_flag(t): + return _short_script_flag(t, "eE", "i" + _PERL_VALUE_LETTERS) # `-i.bak`, `-Mmod` ... + + +def _perl_inplace_flag(t): + """Whether a perl option cluster turns on `-i`: `-pi`, `-0pi`, `-0777pi`, `-i.bak`. The + `i` in `-Ilib`, `-Mwarnings` or `-e'...'` belongs to that option's value, and the digits + in `-0777` or `-l0` are the value of `-0` or `-l`, not the end of the cluster.""" + if not t.startswith("-") or t.startswith("--"): + return False + for c in t[1:]: + if c == "i": + return True + if c in "eE" + _PERL_VALUE_LETTERS: + return False + return False + + +def _py_writes(text): + """Paths an inline Python script writes; "(script)" for a write whose path this cannot + resolve.""" + out = [] + for m in _PY_OPEN_LIT.finditer(text): + if set(m.group(4)) & set("wax+"): + out.append(m.group(2)) + variables = [m.group(1) for m in _PY_OPEN_VAR.finditer(text) if set(m.group(3)) & set("wax+")] + out += [m.group(2) for m in _PY_WRITE_PATH_LIT.finditer(text)] + variables += [m.group(1) for m in _PY_WRITE_PATH_VAR.finditer(text)] + for var in dict.fromkeys(variables): + found = re.findall(rf"\b{re.escape(var)}\s*=\s*(?:(?:pathlib\.)?Path\(\s*)?(['\"])" + rf"([^'\"\n]+)\1", text) + loop = re.search(rf"\bfor\s+{re.escape(var)}\s+in\s+[\[(]([^\])]*)[\])]", text) + paths = [p for _, p in found] + if loop: + paths += re.findall(r"['\"]([^'\"\n]+)['\"]", loop.group(1)) + out += paths or ["(script)"] + return out + + +# git's own options that take the next word as their value (`git -C repo apply x.diff`). +_GIT_VALUE_OPTS = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", + "--attr-source"} + + +def _git_args(tokens): + """The words of a git command from its subcommand on, past git's own options such as + `-C `, `-c =` or `--no-pager`; [] for any other command.""" + if tokens[0].rsplit("/", 1)[-1] != "git": + return [] + i = 1 + while i < len(tokens) and tokens[i].startswith("-"): + i += 2 if tokens[i] in _GIT_VALUE_OPTS else 1 + return tokens[i:] + + +def _restored(tokens): + """The paths a `git checkout -- ` or `git restore ` puts back; [] for any other + command.""" + args = _git_args(tokens) + if len(args) < 2 or args[0] not in ("checkout", "restore"): + return [] + rest = (args[args.index("--") + 1:] if "--" in args + else args[1:] if args[0] == "restore" else []) + return [t for t in rest if not t.startswith("-")] + + +# The commands that run another one, and which of their own options take the next word as a +# value: `sudo -u bob sed -i ...`, `env -u VAR ...`, `timeout -s KILL 60 ...`, `nice -n 10 ...`. +_WRAPPERS = { + "sudo": {"-u", "-g", "-p", "-C", "-D", "-R", "-r", "-t", "-T", "-U", "--user", "--group", + "--prompt", "--close-from", "--chdir", "--chroot", "--role", "--type", + "--command-timeout", "--other-user"}, + "env": {"-u", "-C", "-S", "--unset", "--chdir", "--split-string"}, + "timeout": {"-s", "-k", "--signal", "--kill-after"}, + "nice": {"-n", "--adjustment"}, + "time": {"-f", "-o", "--format", "--output"}, + "command": set(), + "nohup": set(), +} + + +def _past_wrapper(tokens): + """The words after a wrapper such as `sudo` or `timeout`, its own options and, for + `timeout`, the duration.""" + takes_value = _WRAPPERS[tokens[0]] + i = 1 + while i < len(tokens) and tokens[i].startswith("-"): + t = tokens[i] + i += 1 + if t == "--": + break + if t.startswith("--"): + if t in takes_value: # `--user bob`, not `--user=bob` + i += 1 + continue + for n, letter in enumerate(t[1:], 2): # `-Eu bob`, `-ubob`, `-n10`, `-10` + if "-" + letter in takes_value: + if n == len(t): # the value is the next word + i += 1 + break + if tokens[0] == "timeout": + i += 1 + return tokens[i:] + + +def _bare(cmds): + """Each command with the `sudo -u bob`, `env -u VAR`, `timeout 60`, `VAR=1` ... before it + dropped; empty ones left out.""" + out = [] + for tokens in cmds: + while tokens: + if tokens[0] in _WRAPPERS: + tokens = _past_wrapper(tokens) + elif tokens[0] == "rtk" and len(tokens) > 1: # trace.strip_rtk_prefix + tokens = tokens[2:] if tokens[1] == "proxy" and len(tokens) > 2 else tokens[1:] + elif re.match(r"^\w+=", tokens[0]): + tokens = tokens[1:] + else: + break + if tokens: + out.append(tokens) + return out + + +def shell_revert_targets(cmd): + """Basenames of the files a shell command puts back with `git checkout --` or `git + restore`: `shell_edit_targets` counts them as written, which they are; the loop guard counts + them as edits only for a file the turn edited.""" + if not isinstance(cmd, str) or not cmd.strip(): + return [] + shell, _ = _split_heredocs(cmd) + cmds, _ = _commands(shell) + names = [basename(p) for tokens in _bare(cmds) for p in _restored(tokens) if _not_scratch(p)] + return list(dict.fromkeys(n for n in names if n)) + + +def shell_edit_targets(cmd): + """Basenames of the files a shell command writes, in order, without repeats.""" + if not isinstance(cmd, str) or not cmd.strip(): + return [] + shell, bodies = _split_heredocs(cmd) + cmds, writes = _commands(shell) + found = [w for w in writes if _SOURCE_FILE.search(w)] + for tokens in _bare(cmds): + head = tokens[0].rsplit("/", 1)[-1] + if head == "sed": + found += _inplace_files( + tokens, lambda t: bool(re.match(r"^(?:-[a-zA-Z]*i|--in-place)", t)), + _sed_script_flag) + elif head == "perl": + found += _inplace_files(tokens, _perl_inplace_flag, _perl_script_flag) + 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 _git_args(tokens)[:1] == ["apply"]: + found.append("(patch)") + else: + found += _restored(tokens) + if _PYTHON.search(shell): + found += _py_writes("\n".join([shell] + bodies)) + names = [p if p.startswith("(") else basename(p) + for p in found if p.startswith("(") or _not_scratch(p)] + return list(dict.fromkeys(n for n in names if n)) + + +def fold_shell_edits(st, names): + """Count `names` as edits in a SpiralState, and say so in its action log.""" + for b in names: + st.edit_order.append(b) + st.edit_counts[b] = st.edit_counts.get(b, 0) + 1 + if names and st.recent: + shown = ", ".join(names[:4]) + (", ..." if len(names) > 4 else "") + st.recent[-1] = f"{st.recent[-1]} [edits {shown}]" diff --git a/plugins/zeph/lib/tokeneconomizer/loopguard/state.py b/plugins/zeph/lib/tokeneconomizer/loopguard/state.py new file mode 100644 index 0000000..74c17d5 --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/loopguard/state.py @@ -0,0 +1,258 @@ +"""What the loop guard reads off a trajectory: a per-call fold of its failure-loop signals. + +`SpiralState` is updated once per completed tool call and keeps only counts and a short, +leakage-safe action log: edits per file, files edited, error outputs, verification runs, and how +often a failure repeats one seen before (`stagnation`, the signal that separates a loop from a +hard but productive grind). `completed_calls` turns one streamed line of any agent's output into +the calls it completes, so the same fold runs live and over a saved log. +""" +import hashlib +import json +import re + +from ..trace import load_trajectory as _load_trajectory, tool_kind + +# An output that RAN code to verify behavior (the test/repro step of the edit->test +# loop). +TEST_RUN_RE = re.compile( + r"(runtests(\.py)?|\bpytest\b|py\.test|manage\.py\s+test|python\s+-m\s+unittest|" + r"\btox\b|\bnox\b|\btrial\b|python\d?\s+-c\b)", re.IGNORECASE) +ERR_RE = re.compile( + r"(Traceback \(most recent call last\)|\b\w*Error\b|\bFAILED\b|\bassert\b|" + r"Exception|errors during collection|" + # Other ecosystems' failing-test summaries, which name no error: TAP (`node --test`) + # `# fail 2` and `not ok 3`, mocha's and rspec's counts, JUnit's, and Go's `--- FAIL: T` + # and `FAILpkg` (not unittest's `FAIL: test_x`, which would change the line a Python + # failure is known by, and so which failures count as repeats). + r"^# fail [1-9]|^not ok \d|\b[1-9]\d* (?:failing|failures?)\b|Failures: [1-9]|" + r"^(?-i:--- FAIL: |FAIL\t|FAIL$))", re.IGNORECASE | re.MULTILINE) +_EDIT_TOOLS = ("edit", "str_replace", "create") +# Tools whose output is the content of files, not the outcome of running anything: a test file +# full of `assert` read back is not a failure, nor is reading it twice a repeated one. +_CONTENT_TOOLS = ("view", "grep", "glob") + +# Normalize agent-specific tool names to the copilot-style canonical names the folding +# logic below keys on, so ONE code path handles both the Copilot stream schema and Claude +# Code's stream-json (which names tools Bash/Read/Edit/Write/Grep/Glob/MultiEdit). Unknown +# names pass through unchanged. +_TOOL_CANON = { + "bash": "bash", "shell": "bash", "powershell": "bash", + "read": "view", "view": "view", + "grep": "grep", + "glob": "glob", + "edit": "edit", "multiedit": "edit", "str_replace": "edit", + "apply_patch": "edit", + "write": "create", "create": "create", +} + + +def canon_tool(name): + return _TOOL_CANON.get(tool_kind(name), name or "?") + + +def completed_calls(line, pend): + """Schema-agnostic fold of ONE streamed JSONL line into completed (name, args, result) + tool calls, so the live guards work for BOTH the Copilot stream + (tool.execution_start/complete) AND Claude Code's stream-json (assistant.tool_use / + user.tool_result). `pend` is a caller-owned dict {callId -> {name,args}} carried across + lines to pair a start/tool_use with its later complete/tool_result. Yields a list of + completed calls finished on THIS line (0, 1, or — for a Claude user msg batching + several tool_results — more). Tool names are canonicalized so downstream keying is + uniform; unpaired results fall back to name '?'.""" + try: + ev = json.loads(line) + except Exception: + return [] + if not isinstance(ev, dict): + return [] + t = ev.get("type") + out = [] + # ---- Codex exec --json schema ---- + if t == "item.completed": + item = ev.get("item") or {} + kind = item.get("type") + if kind == "command_execution": + out.append(("bash", {"command": item.get("command") or ""}, + item.get("aggregated_output") or "")) + elif kind == "file_change": + changes = item.get("changes") or [] + paths = [c.get("path") for c in changes + if isinstance(c, dict) and c.get("path")] + out.append(("edit", {"path": paths[0] if paths else "", + "paths": paths, "changes": changes}, "")) + return out + # ---- Copilot schema ---- + if t == "tool.execution_start": + d = ev.get("data", {}) if isinstance(ev.get("data"), dict) else {} + pend[d.get("toolCallId")] = {"name": d.get("toolName"), + "args": d.get("arguments", {}) or {}} + return out + if t == "tool.execution_complete": + d = ev.get("data", {}) if isinstance(ev.get("data"), dict) else {} + info = pend.pop(d.get("toolCallId"), {"name": "?", "args": {}}) + res = d.get("result") or {} + c = res.get("content") if isinstance(res, dict) else "" + out.append((canon_tool(info["name"]), info.get("args") or {}, + c if isinstance(c, str) else "")) + return out + # ---- Claude Code stream-json schema ---- + if t == "assistant": + for b in (ev.get("message", {}) or {}).get("content", []) or []: + if isinstance(b, dict) and b.get("type") == "tool_use": + pend[b.get("id")] = {"name": b.get("name"), + "args": b.get("input", {}) or {}} + return out + if t == "user": + for b in (ev.get("message", {}) or {}).get("content", []) or []: + if isinstance(b, dict) and b.get("type") == "tool_result": + info = pend.pop(b.get("tool_use_id"), {"name": "?", "args": {}}) + c = b.get("content") + if isinstance(c, list): # content can be a list of text blocks + c = "\n".join(x.get("text", "") for x in c if isinstance(x, dict)) + out.append((canon_tool(info["name"]), info.get("args") or {}, + c if isinstance(c, str) else "")) + return out + return out + + +def basename(p): + """The last component of a path in either separator: Claude Code on Windows names the file + an edit tool changed `C:\\repo\\pkg\\mod.py`, and a shell edit of it `pkg/mod.py`.""" + return p.replace("\\", "/").rstrip("/").split("/")[-1] if p else (p or "") + + +def _failure_sig(text): + """A normalized signature of a failing output: drop numbers/addresses/paths so two + runs that fail the SAME way hash identically (used to detect 'no progress' — the + same failure recurring after edits). Leakage-safe: a hash, never the content.""" + if not text: + return None + first = None + for ln in text.splitlines(): + if ERR_RE.search(ln): + first = ln + break + if first is None: + return None + norm = re.sub(r"0x[0-9a-f]+|\d+|/\S+", "", first) + return hashlib.md5(norm.strip().encode("utf-8", "replace")).hexdigest()[:10] + + +class SpiralState: + """Compact, incremental fold of one trajectory's spiral signals. Cheap to update + per event so it can run live.""" + __slots__ = ("turns", "edit_counts", "edit_order", "error_outputs", + "test_runs", "fail_sigs", "repeated_fail_sigs", "recent") + + def __init__(self): + self.turns = 0 + self.edit_counts = {} # basename -> #edits + self.edit_order = [] # ordered basenames of edit targets + self.error_outputs = 0 # tool outputs carrying an error/failure marker + self.test_runs = 0 # code-execution verification steps + self.fail_sigs = {} # failure signature -> count + self.repeated_fail_sigs = 0 # # of failing outputs that REPEAT an earlier sig + self.recent = [] # leakage-safe rolling log of recent actions (for the + # LLM trace-judge); process-only, never fix content + + # ---- derived signals ---- + @property + def edit_churn(self): + return max(self.edit_counts.values()) if self.edit_counts else 0 + + @property + def distinct_edit_files(self): + return len(self.edit_counts) + + @property + def stagnation(self): + """Fraction of failing outputs that repeat an earlier identical failure (the + agent edited but the SAME failure came back = no progress). 0 when no fails.""" + total = sum(self.fail_sigs.values()) + return (self.repeated_fail_sigs / total) if total else 0.0 + + def update(self, tool_name, args, result_text, failed=None): + """Fold one completed tool call into the state. `failed` is what the agent reported + about the call -- True for a non-zero exit or a tool error, False for success, None when + it did not say -- and decides whether its output can be a failing one: a call known to + have succeeded is not, a content tool only when the tool itself failed, and otherwise + the output's own markers decide.""" + self.turns += 1 + args = args if isinstance(args, dict) else {} + tool_name = canon_tool(tool_name) # accept Copilot- or Claude-named tools + action = tool_name or "?" + if tool_name in _EDIT_TOOLS: + # A patch names every file it changes in `paths`; any other edit names one. + paths = args.get("paths") + if not isinstance(paths, (list, tuple)) or not paths: + paths = [args.get("path") or args.get("filePath") or args.get("file_path") + or args.get("relative_path")] + names = list(dict.fromkeys(basename(p) for p in paths if isinstance(p, str))) + names = [b for b in names if b] + for b in names: + self.edit_order.append(b) + self.edit_counts[b] = self.edit_counts.get(b, 0) + 1 + if names: + action = f"edit {', '.join(names)}" + cmd = args.get("command", "") if tool_name == "bash" else "" + if cmd: + short = re.sub(r"\s+", " ", cmd.strip())[:90] + action = f"$ {short}" + if TEST_RUN_RE.search(cmd): + self.test_runs += 1 + elif tool_name in ("grep", "glob"): + action = f"{tool_name} {str(args.get('pattern') or '')[:40]}" + elif tool_name == "view": + action = f"view {basename(args.get('path') or args.get('file_path') or '')}" + fail = None + can_fail = failed is True if tool_name in _CONTENT_TOOLS else failed is not False + if result_text and can_fail and ERR_RE.search(result_text): + self.error_outputs += 1 + sig = _failure_sig(result_text) + if sig: + fail = sig + if sig in self.fail_sigs: + self.repeated_fail_sigs += 1 + self.fail_sigs[sig] = self.fail_sigs.get(sig, 0) + 1 + # rolling leakage-safe action log (tool name / command / search / error-SIGNATURE + # only — no file contents, edit bodies, or view output), capped to recent window. + tag = f" [err#{fail}]" if fail else "" + self.recent.append(f"{self.turns:>3}: {action}{tag}") + if len(self.recent) > 40: + self.recent = self.recent[-40:] + + def recent_digest(self, n=24, envelope=None): + """A compact, LEAKAGE-SAFE digest of the agent's RECENT PROCESS (last n actions) + for the LLM trace-judge: commands/searches/edited-basenames and error-SIGNATURE + markers only — never fix content, edit bodies, view output, or the issue text. + `envelope` (this repo's typical resolved-task length) is passed as CONTEXT so the + judge can recognize an abnormally-long trajectory as a likely dead-end.""" + head = (f"turns={self.turns} edit_churn={self.edit_churn} " + f"distinct_edit_files={self.distinct_edit_files} " + f"error_outputs={self.error_outputs} test_runs={self.test_runs} " + f"repeated_identical_failures={self.repeated_fail_sigs} " + f"stagnation={self.stagnation:.2f}") + if envelope: + ratio = self.turns / envelope if envelope else 0 + head += (f"\nrepo_context: tasks here usually RESOLVE within ~{envelope:.0f} " + f"turns; this trajectory is at {self.turns} turns = {ratio:.1f}x that " + f"typical length. Tests are still NOT green. A trajectory far past " + f"the typical resolved length with recurring failures is likely a " + f"dead-end loop, even if it touches many files.") + return head + "\nRecent actions (oldest->newest):\n" + "\n".join(self.recent[-n:]) + + def snapshot(self): + return {"turns": self.turns, "edit_churn": self.edit_churn, + "distinct_edit_files": self.distinct_edit_files, + "error_outputs": self.error_outputs, "test_runs": self.test_runs, + "stagnation": round(self.stagnation, 3), + "repeated_fail_sigs": self.repeated_fail_sigs} + + +def state_from_trajectory(path, load_trajectory=None): + """The final `SpiralState` of a saved session log (`trace.load_trajectory` by default).""" + load_trajectory = load_trajectory or _load_trajectory + st = SpiralState() + for name, args, res, ok in load_trajectory(path): + st.update(name, args, res, failed=None if ok is None else not ok) + return st diff --git a/plugins/zeph/lib/tokeneconomizer/loopguard/turn.py b/plugins/zeph/lib/tokeneconomizer/loopguard/turn.py new file mode 100644 index 0000000..bfd0c7f --- /dev/null +++ b/plugins/zeph/lib/tokeneconomizer/loopguard/turn.py @@ -0,0 +1,660 @@ +"""`TurnGuard`: the loop guard for one prompt-turn, one tool call at a time. + +Each tool call arrives as a separate hook process, so the guard's state is on disk between +calls (`to_dict` / `TurnGuard(data=...)`). Per call it folds the result into a `SpiralState`, +checks the cumulative backstop, and asks `rules.assess_abort` (gate -> optional paid judge -> +envelope fallback) whether the turn is stuck; the first stuck verdict is answered with a +redirect, a later one with a stop 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 person + already splits work into short turns, and a whole session folded as one trajectory looks + stuck merely by being long. + * The redirect is delivered mid-turn, attached to the tool result. + * There is no grader, so the per-repository envelope learns from turns that ENDED GREEN: the + agent stopped on its own, the guard did not stop it, and no verification after its last edit + failed (`resolved_proxy`). +""" +import os +import re +import shlex +import time + +from ..trace import RTK_WORDS +from .rules import DEFAULT_THRESHOLDS, assess_abort, is_stuck, nudge_text +from .shell_edits import (_split_heredocs, fold_shell_edits, shell_edit_targets, + shell_revert_targets) +from .state import ERR_RE, TEST_RUN_RE, SpiralState, canon_tool + +_SLOTS = SpiralState.__slots__ + +# What counts as running the project's own checks, across ecosystems. Broader than +# `state.TEST_RUN_RE` (the Python vocabulary the guard's thresholds were tuned on); used ONLY +# for the ended-green proxy, never to change what `SpiralState` counts. A runner +# is often named by path (`python tests/runtests.py`, `.venv/bin/pytest`, `./node_modules/.bin/ +# jest`): without the optional directories those turns showed no verification at all, so a turn +# whose last test run failed still counted as ended green and fed the envelope. +# `python` with the interpreter's own options before what it runs (`python -W error -m pytest`, +# `python -X dev -m pytest`, `python -u tests/runtests.py`); they are case-sensitive. +_PYTHON = (r"python\d?(?:\.\d+)?" + r"(?-i:(?:\s+(?:-[bBdEiIOPqsSuvx]+|-[WX]\s*[^\s\-]\S*))*)") +# Gradle's options and other tasks before the test task (`./gradlew clean test`, `./gradlew +# --offline test`), but not a task it is told to leave out: `./gradlew build -x test` runs no +# tests. The option is case-sensitive, as the other option letters here are. +_GRADLE_EXCLUDE = r"(?-i:-x|--exclude-task)" +_GRADLE_TASKS = (r"(?:\s+(?:" + _GRADLE_EXCLUDE + r"\s+\S+|(?!" + _GRADLE_EXCLUDE + r"\s)\S+))*" + r"\s+") +# Unless Maven is told to skip the tests (`mvn test -DskipTests`, `-D skipTests`, +# `--define=maven.test.skip=TRUE`): it then passes without running any. Gradle reads no such +# property: `./gradlew test -DskipTests` runs them. Read within the one command. +_UNLESS_MVN_SKIPS_TESTS = (r"(?![^;&|\n]*\s(?-i:(?:-D\s*|--define[=\s]\s*)" + r"(?:skipTests|maven\.test\.skip(?:\.exec)?)(?:=(?i:true))?)(?!\S))") +# A value of one of make's options or variables: a word, or a `$(...)`/`${...}` whose brackets +# `_pieces` has turned into spaces (`-j$(nproc)` reads `-j$ nproc`). +_MAKE_VALUE = r"(?:\$\s*\w+|[^\s\-]\S*)" + + +def _options(value): + """A command's own options before what it runs: one of `value` with the value it takes (a + word, or a `$(...)` read as `_MAKE_VALUE` reads one), any other as a flag, which may carry + its value after `=` (`--filter=web`). Case-sensitive. An option of `value` before a space is + read only that way, so a long line of options that runs no tests does not backtrack + exponentially.""" + return (r"(?-i:(?:\s+(?:" + value + r"\s+" + _MAKE_VALUE + r"|(?!" + value + r"\s)" + r"-[-\w]+(?:=(?:\$\s*\w+|\S*))?))*)") + + +# A JavaScript test runner, run by its name (`jest`, `npx vitest run`) or by a package manager +_JS_RUNNERS = r"(?:jest|vitest|mocha|ava|playwright\s+test)" +# A package manager running the test script, or a runner, past its own options (`npm -w web +# test`, `pnpm --filter web test`, `pnpm -r test`, `yarn --cwd web test`, `yarn workspace web +# test`), of which these take a value. Each has its own: npm's `-w` names a workspace, pnpm's is +# `--workspace-root`, a flag. `t` and `tst` are npm's and pnpm's aliases of `test`, and pnpm and +# yarn run an installed runner by its name (`pnpm vitest run`, `yarn jest`). +_NPM_TEST = (r"npm" + _options(r"(?:-[wC]|--(?:workspace|prefix|loglevel|script-shell|" + r"userconfig))") + + r"\s+(?:(?:run(?:-script)?\s+)?test|t|tst)") +_PNPM_TEST = (r"pnpm" + _options(r"(?:-[FC]|--(?:filter|filter-prod|dir|workspace-packages|" + r"env-file|reporter|loglevel|test-pattern|" + r"changed-files-ignore-pattern))") + + r"\s+(?:(?:run\s+)?test|t|tst|(?:exec\s+)?" + _JS_RUNNERS + r")") +_YARN_TEST = (r"yarn" + _options(r"--cwd") + r"(?:\s+workspace\s+" + _MAKE_VALUE + r")?" + r"\s+(?:run\s+)?(?:test|" + _JS_RUNNERS + r")") +VERIFY_RE = re.compile( + r"(?i)(?:^|[\s;&|(])(?:(?:~?/)?(?:[\w.\-]+/)*" + _PYTHON + r"\s+)?" + r"(?:~?/)?(?:[\w.\-]+/)*(?:pytest|py\.test|tox|nox|" + + _PYTHON + r"\s+-m\s+(?:pytest|unittest|tox|nox)|" + # coverage.py measuring a test run (`coverage run -m pytest`, `python -m coverage run + # manage.py test`), past its own options, of which these take a value + r"(?:-m\s+)?coverage\s+run(?:\s+(?:--(?:rcfile|source|omit|include|data-file|context|" + r"concurrency|debug|save-signal)(?:=|\s+)\S+|-[-\w]+))*\s+" + r"(?:-m\s+(?:pytest|unittest)|(?:[\w.\-]+/)*(?:manage\.py\s+test|runtests(?:\.py)?))|" + r"manage\.py\s+test|runtests(?:\.py)?|" + _JS_RUNNERS + r"|" + + _NPM_TEST + r"|" + _PNPM_TEST + r"|" + _YARN_TEST + r"|" + r"bun\s+(?:run\s+)?test|go\s+test|cargo\s+(?:test|nextest)|" + r"(?:mvn|mvnw|\./mvnw)" + _UNLESS_MVN_SKIPS_TESTS + r"\s+(?:\S+\s+)*test|" + # also a Gradle subproject's test task by its path, `./gradlew :app:test`, but not an + # option's value (`--exclude-task=:app:test`) or a task of a subproject named `test` + r"(?:gradle|gradlew|\./gradlew)" + _GRADLE_TASKS + r"(?!-)(?:\S*:)?test(?!:)|" + # make's own options and variables before the target (`make -j8 check`, `make -C build + # test`, `make V=1 test`, `make -j$(nproc) check`, whose `$(nproc)` reaches here as + # `$ nproc`). They are case-sensitive. `-C`, `-f`, `-I`, `-o` and `-W` always take a value, + # `-j` and `-l` may; the generic option does not also read one of them with its value, so + # a long line of options does not backtrack exponentially. + r"make(?-i:(?:\s+(?:-[CfIjloW]\s*" + _MAKE_VALUE + r"|" + r"--(?:directory|file|makefile|include-dir|jobs|load-average|old-file|assume-old|" + r"what-if|new-file|assume-new)\s+" + _MAKE_VALUE + r"|" + r"-(?![CfIoW]|[jl][^\s\-])[-\w]+(?:=(?:\$\s*\w+|\S*))?|\w+=(?:\$\s*\w+|\S*)))*)" + r"\s+(?:test|check)|" + # the other Python runners the micro-skills observer reads as test runs: Twisted's `trial`, + # nose (`nosetests`, `python -m nose`) and `python -m django test` + r"trial|nosetests|" + _PYTHON + r"\s+-m\s+(?:nose|django\s+test)|" + r"ctest|rspec|phpunit|dotnet\s+test|swift\s+test|mix\s+test|" + # Ruby: `rake test`, `bin/rails test`, and `ruby` given a test file (`ruby -Itest + # test/models/user_test.rb`), but not `ruby -e '...'`, a syntax check (`ruby -wc x.rb`) or a + # script that is not a test (`ruby repro.rb`): the options it takes are spelled out, and + # case-sensitive, so `-W` does not also take `-wc` under the pattern's `(?i)`. + r"rake(?:\s+\w+=\S*)*\s+(?:test|spec)(?::[\w:]+)?|rails\s+test(?::[\w:]+)?|" + r"ruby(?-i:\s+(?:-[Ir](?:\S+|\s+[^\s\-]\S*)|-C\s*\S+|-W[0-2]?(?::\S+)?|" + r"--[\w\-]+(?:=\S+)?|-[abdf-zABDF-Z]+))*\s+" + r"(?:[\w.\-~]*/)*(?:test_[\w.\-]*|[\w.\-]*_(?:test|spec))\.rb|" + r"deno\s+test|node\s+--test|bazel\s+test|(?:\./)?bin/test|" + # `hatch test` (Hatch 1.10+: pytest in its test environment), but not with `-s`/`--show`, + # which only shows the environments; short flags combine (`-ps`), and after `--` they are + # pytest's (`hatch test -- -s` runs the tests) + r"hatch\s+test(?!(?:\s+(?!--(?:\s|$))\S+)*?\s+(?:--show|-[rpca]*s[rpca]*)(?:\s|$)))" + r"(?![\w.\-/])") + +# A command line's exit status is its LAST command's, so it may not be the test run's: `npm test +# 2>&1 | tail -n 8` exits with `tail`'s status, `pytest | grep FAILED` with `grep`'s, `python -m +# unittest; echo "exit=$?"` and `npm test || true` with 0, and `pytest -q; git diff` with +# `git`'s. For such a test run the runner's own summary line decides (`runner_verdict`). Without +# one, a run whose status was replaced (a pipe, `||`, a report of the status) is read by its +# output's markers, as a call whose status is unknown is; a run followed by other commands keeps +# the status the agent reported, since their output is in the result too. +_SHELLS = {"sh", "bash", "zsh", "dash", "ksh"} +_QUOTED_RE = re.compile(r"'[^']*'|\"(?:\\.|[^\"\\])*\"") +_SEP_RE = re.compile(r"(&&|\|\||\|&|(?)\||;|\n)") # `|`, but not the `>|` redirect +# A runner asked for its help, version or test list, not to run the tests; and pytest asked +# only to show its fixtures, markers, setup plan or cache, or to set up fixtures, which runs none. +_NOT_A_RUN_RE = re.compile(r"\s(?:-h|--help|--version|--collect-only|--co|--list\S*|" + r"--fixtures(?:-per-test)?|--funcargs|--markers|--setup-plan|" + r"--setup-only|--cache-show(?:=\S*)?)(?!\S)") +# A launcher's own options, which stand between it and the command it runs. Some take a value, +# which is then a word of its own: `uv run --extra test pytest`, `uv run --group dev pytest`, +# `uv run --with pytest-cov pytest`. microskills already reads them before the command +# (`observe._RUN_OPTION_RE`), so it learns those runs; the loop guard has to see past them too, +# or a failing `uv run --extra test pytest` is no verification and its turn ends green. +_LAUNCHER_OPTIONS = (r"(?:--with(?:-editable|-requirements)?|--extra|--(?:only-|no-)?group|" + r"--python|-p|--package|--project|--directory|--env-file|--index|" + r"--pyproject)(?:=|\s+)[^\s-]\S*" + r"|--|--?[A-Za-z][\w-]*(?:=\S+)?") +# What may precede the command itself: `FOO=1 timeout 60 npm test`, `env -u VAR`, `nice -n 10`, +# `sudo -u bob`, `time -p`, and a launcher that runs it in the project's environment, `uv run +# pytest`, `npx jest`, `bundle exec rspec`. `command -v pytest` looks the runner up; only +# `command -p` runs it. +_PREFIX_RE = re.compile(r"^\s*(?:(?:\w+=\S*|nohup|command(?:\s+-p)?(?:\s+--)?|" + # time's options; `-f` and `-o` take a value + r"time(?:\s+(?:-[fo](?:\s+\S+|\S+)|--(?:format|output)(?:=|\s+)\S+|" + r"-[pvaq]+|--(?:portability|verbose|append|quiet)))*|" + r"exec(?:\s+(?:-a\s*[^\s-]\S*|-[cl]+))*(?:\s+--)?|" + # sudo's options; these letters and long forms take a value + r"sudo(?:\s+(?:-\w*[ugpCDRrtTU]\s*[^\s-]\S*|--(?:user|group|prompt|" + r"close-from|chdir|chroot|role|type|command-timeout|other-user)" + r"(?:=|\s+)\S+|-[-\w]*(?:=\S*)?))*|" + r"nice(?:\s+(?:-n\s*|--adjustment(?:=|\s+))?[-+]?\d+)?|" + # env's options; `-u`, `-C` and their long forms take a value + r"env(?:\s+(?:(?:-[uC]|--unset|--chdir)(?:=|\s*)[^\s-]\S*|-[-\w]*))*|" + r"timeout(?:\s+(?:-\S+|[A-Z]+|\d\S*))+|" + # `conda run -n ml`, `mamba run -p ./env`, `micromamba run -r /opt -n ml`: + # the environment's name or path, and the other options that take a value + r"(?:conda|mamba|micromamba)\s+run(?:\s+(?:(?:-[npr]|--name|--prefix|" + r"--root-prefix|--cwd)(?:=|\s*)[^\s-]\S*|-[-\w]*))*|" + # `pixi run -e test`: pixi's options, of which these take a value, but + # not its dry run (`-n`, also among short flags as `-xn`, `--dry-run`), + # which only prints the command + r"pixi\s+run(?:\s+(?:(?:-[epmws]|--(?:environment|platform|manifest-path|" + r"workspace|script|config-file|auth-file|concurrent-downloads|" + r"concurrent-solves|pinning-strategy|pypi-keyring-provider|" + r"tls-root-certs))(?:=|\s*)[^\s-]\S*|" + r"(?!-[A-Za-z]*n[A-Za-z]*(?:\s|$)|--dry-run(?:\s|$))-[-\w]*(?:=\S*)?))*|" + r"(?:(?:uv|poetry|pipenv|pdm|hatch|rye)\s+run|npx|bunx|" + r"(?:npm|pnpm|yarn)\s+(?:exec|dlx)|bundle\s+exec|xvfb-run)" + r"(?:\s+(?:" + _LAUNCHER_OPTIONS + r"))*|" + # rtk's prefix, `rtk pytest`, `rtk proxy npm test` (trace.RTK_WORDS) + + RTK_WORDS + r"(?=\s+\S)|" + # `dotenv -e .env.local -- npx vitest run`: dotenv-cli's options, then `--` + r"dotenv(?:\s+(?!--(?:\s|$))\S+)*\s+--)\s+)*") +# What only reports on the run before it: `echo "exit=$?"`, `true`, `exit 0`. +_REPORT_RE = re.compile(r"^\s*(?:echo|printf|true|:|exit)(?:\s|$)") +_RANK = {"own": 0, "hidden": 1, "mixed": 2} + + +def _pieces(cmd): + """`cmd` as its commands and the separators between them (`[cmd, sep, cmd, ...]`), with + quoted text masked and heredoc bodies left out, and whether it sets `pipefail`. A command + recorded as `bash -lc '