Compare commits

...

48 Commits

Author SHA1 Message Date
lilleman e0634e52bb File the deploy-release checkout refusal on a reordered settings.json
CI / tests (pull_request) Successful in 2m33s
2026-11-12 01:09:17 +01:00
lilleman 595e2f8c4b Move item 328 back to 0.9.0, the release after the 0.8.0 it audits
CI / tests (pull_request) Successful in 2m20s
2026-11-12 00:45:51 +01:00
lilleman 70cb7bd1be Cut release 0.8.0
CI / tests (pull_request) Successful in 2m19s
2026-11-12 00:38:47 +01:00
lilleman c1f08668b7 Move every planned item one release later 2026-11-12 00:38:47 +01:00
lilleman 05806b517d Answer architecture round 1: 0 🔴, 4 🟡 (0 misread); item 330 replays only the judge, on the Fable 5.2 rungs, and the four decisions' rewording is filed as question item 331
CI / tests (pull_request) Successful in 2m22s
2026-11-12 00:24:40 +01:00
lilleman 93c81c48ab Answer prose round 1: 0 🔴, 5 🟡 (0 misread); fixed in the stability round 1 commit 2026-11-12 00:20:18 +01:00
lilleman a713fd6a88 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); the changelog names the moves and the retired rungs, the replays are filed as item 330 2026-11-12 00:20:18 +01:00
lilleman 6e67cc59fa Answer stability round 1: 0 🔴, 7 🟡 (0 misread); placeholder rungs in docstrings, rung-free test names, the decision note and changelog name every move 2026-11-12 00:20:18 +01:00
lilleman 071d6cf1cd Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-12 00:05:50 +01:00
lilleman 8e46ef69b1 Rebuild the routing ladder for Fable 5.2 from the index read 2026-11-11
CI / tests (pull_request) Successful in 2m36s
2026-11-12 00:04:08 +01:00
lilleman 968cc37661 Record the index read for item 292 and the ladder it proposes 2026-11-11 23:38:27 +01:00
lilleman 2ca4d0f8db Drop item 313
CI / tests (pull_request) Successful in 2m34s
2026-11-11 23:23:30 +01:00
lilleman 4d132e9a3c Finish item 329
CI / tests (pull_request) Successful in 2m35s
2026-11-11 22:41:56 +01:00
lilleman 3f1967a24f Merge origin/main, refiling the Mattermost DM item as 329 since main filed its own 325 2026-11-11 22:41:47 +01:00
lilleman d2d5e10e19 Answer stability round 2: 1 🔴, 0 🟡 (0 misread); read an error answer's body guarded, so one cut short names its status 2026-11-11 22:39:45 +01:00
lilleman b6c14ba223 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); fixed in the stability round 1 commit
CI / tests (pull_request) Successful in 2m25s
2026-11-11 22:37:52 +01:00
lilleman 313e129b20 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); DM a routing call and a crash, fixed in the stability round 1 commit 2026-11-11 22:37:52 +01:00
lilleman 23af106b47 Answer stability round 1: 1 🔴, 5 🟡 (0 misread); catch a broken HTTP answer, drop typed keys before the DM, DM every stop but Ctrl-C and a crash, inject home and http, and test the gaps 2026-11-11 22:37:52 +01:00
lilleman aacfe7d3d3 Answer stability round 2: 0 🔴, 3 🟡 (0 misread); keep item 313 as a question for the human, restore the decision's expiry, and make the sweep list general
CI / tests (pull_request) Successful in 2m28s
2026-11-11 22:35:08 +01:00
lilleman a0b8cf7882 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to fix
CI / tests (pull_request) Successful in 2m28s
2026-11-11 22:31:39 +01:00
lilleman f5201cb638 Answer prose round 1: 0 🔴, 9 🟡 (0 misread); record why item 313 was dropped, tighten the decision's evidence and reorder the changelog 2026-11-11 22:31:39 +01:00
lilleman 14ae30a731 Answer stability round 1: 1 🔴, 5 🟡 (0 misread); drop item 313's launch order, sweep before the suite, hand the passing commit at launch, and fix step 3 2026-11-11 22:31:39 +01:00
lilleman f10170bf8b Answer security round 1: 0 🔴, 0 🟡 (0 misread); follow no redirect, so the token reaches only the server named
CI / tests (pull_request) Successful in 2m22s
2026-11-11 22:25:34 +01:00
lilleman 5588270e43 DM the human on Mattermost for each question, release ready to cut and exit 1 of loop-claude
CI / tests (pull_request) Successful in 2m32s
2026-11-11 22:24:06 +01:00
lilleman b1037248a5 Items 270, 313, 317: the worker runs tests, static analysis and a docs sweep before each stability round; launch one agent of a type before the rest; one-line reviewer descriptions
CI / tests (pull_request) Successful in 2m24s
2026-11-11 22:22:06 +01:00
lilleman c9514fe8b4 Append the reading-cost figure of the last finished chunk 2026-11-11 22:20:04 +01:00
lilleman 079c651105 File item 325: DM the human on Mattermost when loop-claude needs them 2026-11-11 22:16:06 +01:00
lilleman 9da3431e25 Finish item 284: file items 325 to 327 from the 0.7.0 audit, and the 0.8.0 audit as item 328
CI / tests (pull_request) Successful in 2m25s
2026-11-11 22:13:24 +01:00
lilleman cd2ac5d727 Answer stability round 2: 1 🔴, 2 🟡 (0 misread); run Stryker as @stryker-mutator/core, pass an interrupted tool SIGINT before the kill, test SIGHUP, and print a failed Stryker or Infection run's whole report
CI / tests (pull_request) Successful in 2m24s
2026-11-11 21:59:52 +01:00
lilleman 563e8cdc3c Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); run Stryker only where a package.json is above a file, and name the files with none in a Not mutated line 2026-11-11 21:50:16 +01:00
lilleman f70bed52fe Kill mutate-changes' surviving mutants: test a deleted file, a mutmut results that cannot start, an interrupt's speed, and a process group already gone 2026-11-11 21:27:53 +01:00
lilleman 6a803b168b Answer prose round 1: 0 🔴, 6 🟡 (0 misread); state the decision's evidence with its scope, and say the checks before review instead of a gate 2026-11-11 21:12:13 +01:00
lilleman b74268b941 Answer product-owner round 1: 1 🔴, 2 🟡 (0 misread); run the project's own mutation command where its README documents one, mutation-test what no run covered with another tool or by hand, and rerun before each stability round 2026-11-11 21:12:12 +01:00
lilleman 581c8721a0 Answer stability round 1: 3 🔴, 5 🟡 (0 misread); run only a Stryker the project installed, tell mutmut's setup fault from no test, pin cargo-mutants' diff prefixes, keep -x, end the tool and report its scratch folder on SIGTERM, and test option-like names; with product-owner's and prose's code fixes 2026-11-11 21:12:08 +01:00
lilleman 63369d5944 Drop mutate-changes' --no-renames, which a diff limited to the changed paths makes moot, and test the reason each of its failures gives
CI / tests (pull_request) Successful in 2m25s
2026-11-11 20:31:28 +01:00
lilleman 11804ac6aa Parse each mutants/ copy once when reporting mutmut's mutants, and kill more survivors with tests of by_folder, the in-diff tools' folder and their start failures 2026-11-11 20:19:02 +01:00
lilleman 4c9bc080bb Kill mutate-changes' surviving mutants with tests of its other tools, its git config, its output and the files it copies, and move its runs to their own test file 2026-11-11 20:01:42 +01:00
lilleman 38c64c9f12 Say in mutate-changes --help that mutmut counts only the code a test runs in its own process 2026-11-11 19:40:13 +01:00
lilleman aa777819e8 Run mutate-changes in-process in its tests, so mutmut sees the code they reach, and kill the mutants of mutmut_setup and mutmut_mutants that change behaviour 2026-11-11 19:39:40 +01:00
lilleman 8f253dae3b Finish item 293
CI / tests (pull_request) Successful in 2m23s
2026-11-11 19:25:01 +01:00
lilleman 7afc59a9d7 Merge remote-tracking branch 'origin/main' into item-293
# Conflicts:
#	AGENTS.md
#	agents/stability-reviewer.md
#	docs/reading-cost.md
#	todo.md
2026-11-11 19:24:50 +01:00
lilleman 42a637d718 Leave out the test of each failing subtest, which pytest 9.2 reports only as SUBFAILED<description> <test> 2026-11-11 19:22:10 +01:00
lilleman 79e8ce1368 Have mutmut copy each entry of the folder rather than '.', which copied mutants/ into itself and collected the tests twice 2026-11-11 19:14:49 +01:00
lilleman e99eef43b9 Leave out a failing test file by its absolute path, since pytest 9.2 under mutmut 3.8.1 reports nodeids as mutants/<path> 2026-11-11 19:04:24 +01:00
lilleman 25967807ff Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to fix 2026-11-11 18:59:54 +01:00
lilleman a52ebb94bf Run mutation tests on a chunk's changed lines before review with bin/mutate-changes, and hand stability-reviewer the survivors
CI / tests (pull_request) Successful in 2m14s
2026-11-11 18:58:31 +01:00
lilleman 55bb6c12ce Re-score item 293's L as 4 and record how mutmut 3's mutants map to source lines 2026-11-11 18:24:31 +01:00
lilleman 96a2d1ce7b Append reading-cost figures 2026-11-11 18:24:31 +01:00
51 changed files with 2389 additions and 274 deletions
+8
View File
@@ -64,11 +64,17 @@
!bin/loop_state/**/*.py
!bin/machine_load/
!bin/machine_load/*.py
!bin/mattermost-dm
!bin/mattermost_dm/
!bin/mattermost_dm/*.py
!bin/metric-bench
!bin/metric_bench/
!bin/metric_bench/*.py
!bin/model_routing/
!bin/model_routing/*.py
!bin/mutate-changes
!bin/mutate_changes/
!bin/mutate_changes/*.py
!bin/rank_todo.py
!bin/reading-cost
!bin/reading_cost/
@@ -100,6 +106,7 @@
!bin/score_outcomes/
!bin/score_outcomes/*.py
!bin/settings_filter.py
!bin/setup.cfg
!bin/statusline.py
!bin/subagent-rung
!bin/subagent_rung/
@@ -142,5 +149,6 @@
!workflow-bench/compare.py
!workflow-bench/review_git.py
!workflow-bench/run-prompt.md
!workflow-bench/setup.cfg
!workflow-bench/test_bench.py
!workflow-bench/test_review_git.py
+6 -1
View File
@@ -1,7 +1,12 @@
# Changelog
## Unreleased
## 0.8.0
- The routing ladder now tops out at Fable 5.2, ordered by the Artificial Analysis Intelligence Index read 2026-11-11: Sonnet 5.5 at high, Opus 5.5 at medium, Fable 5.2 at low and medium, Opus 5.5 at xhigh, Fable 5.2 at high and max. On an Opus 5.5 project, L 4 workers, E + I 5 reviews and a worker's first escalation now run on Fable 5.2 at low, where they ran on Opus 5.5 at high; E + I 6 reviews on Fable 5.2 at medium, where they ran on Opus 5.5 at xhigh; E + I 7 on Opus 5.5 at xhigh, where they ran on Opus 5.5 at max; and E + I 8 on Fable 5.2 at high, where they ran on Fable 5.1 at max. On a Sonnet 5.5 project, E + I 6, 7 and 8 reviews now run on Fable 5.2 at low, Fable 5.2 at medium and Opus 5.5 at xhigh, where they ran on Opus 5.5 at high, xhigh and max. The judge climbs with the reviews. A Fable 5.2 project starts on Fable 5.2 at low. Update `~/.claude` while no loop is mid-chunk: a chunk that stepped up to Opus 5.5 at high or max, or Fable 5.1 at max, finds its rung gone and restarts on its item's rung.
- loop-claude now sends you a Mattermost DM from a bot for each question it asks, each release ready to cut, each routing call and each stop but Ctrl-C, where `~/.claude/.env` names the server, the bot's token and your username. `bin/mattermost-dm` sends one by hand; `mattermost-dm --help` names the keys. A DM that fails is one line on loop-claude's terminal, and the loop goes on.
- larv-review's worker now runs the project's tests and static analysis, and checks the docs for each name its change touches, before each stability round, and hands stability-reviewer the commit that passed; the reviewer doesn't run them again on it.
- stability-reviewer, product-owner-reviewer and systems-architect have one-line descriptions, which shrinks the agent listing every session carries.
- `mutate-changes` mutation-tests the lines a branch changes, running cargo-mutants, Infection, mutmut or Stryker by each file's language, and prints each mutant that no test kills. Where a project's README documents no mutation command of its own, larv-review now runs it before each stability round and hands stability-reviewer the mutants that survive.
- loop-claude now asks each worker to name the items its chunk takes on one line, as in `Chunk items: 12 (L 3, E + I 5), 14 (L 2, E + I 4)`, and scores them from `todo.md` on the default branch. That line, not the judge, now sets the items loop-inbox lists, and how far an item beyond the one the chunk was routed on lifts the worker, its reviewers and the judge. The judge still reports escalations and whether a release is ready to cut.
- `~/.claude` holds no `AGENTS.md` any more, so each session in your projects starts about 3,600 tokens smaller, and a session in `~/code/claude-config` loads its `CLAUDE.md` once instead of twice.
- A project's `AGENTS.md` may group decision titles into project principles, and each new decision is checked against them: a principle covers it, it breaks one, or it suggests a new one for you to approve.
+8 -14
View File
@@ -69,6 +69,8 @@ Then pick a model with `/model`.
Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt.
To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude/.env`, in the keys `~/.claude/bin/mattermost-dm --help` names, and run `chmod 600 ~/.claude/.env`. Without that file, loop-claude sends no DM.
## Update
Move `~/.claude` to the newest release:
@@ -103,7 +105,9 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them.
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
- `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how.
- `mattermost-dm [<message>]` sends a message, or else stdin, from the Mattermost bot to the human; `~/.claude/.env` names the server, the bot's token and the human, and `mattermost-dm --help` names its keys. `loop-claude --help` says when loop-claude sends one.
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
@@ -115,7 +119,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `todo-item add …` files an item in a project's `todo.md`, taking `Next ID` as the item's ID, and `todo-item finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`; both rank the file, and `todo-item --help` states the flags.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py` and `failure.py`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool.
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
@@ -126,7 +130,8 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
- `loop_claude` runs `chunk-preflight` as a process of its own.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, loop-inbox, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds the files loop-claude and loop-inbox share: the question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), their paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes both tools.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`.
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read.
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `records/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new.
@@ -144,18 +149,7 @@ Test on the host with `uvx --python "$(command -v python3)" --with pytest-xdist=
CI runs `ci.sh` on every pull request, and `main` merges nothing until it passes. The script runs the same tests on the committed HEAD in a pinned Python container; run it under `run-heavy` to reproduce a CI failure, with Docker on `PATH`.
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/results.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start.
```ini
[mutmut]
source_paths=score_outcomes/results.py
also_copy=.
pytest_add_cli_args_test_selection=score_outcomes/
pytest_add_cli_args=-k
not ScoreOutcomesTool
```
Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with pytest==9.2.0 'mutmut>=3,<4' results`, and `uvx --with pytest==9.2.0 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
To mutation-test the lines a branch changes, run `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix 'uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"'` in its checkout.
## Tracking a new file
+1 -1
View File
@@ -1,6 +1,6 @@
---
name: "product-owner-reviewer"
description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n<example>\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n<commentary>\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n<commentary>\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?).\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n<commentary>\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n</commentary>\\n</example>"
description: "Use this agent to review a change to an external surface (API, UI, CLI, SDK, webhook) from an end customer's view: ease of use, edge cases and persona fit."
tools: Read, Grep, Glob, Write
---
+4 -4
View File
@@ -1,6 +1,6 @@
---
name: "stability-reviewer"
description: "Use this agent when code has been written or modified and needs review for stability, bug prevention, and adherence to coding best practices. This includes after implementing new features, refactoring existing code, or fixing bugs. The agent focuses on defensive programming, error handling, edge cases, and compliance with the project's technical principles.\\n\\nExamples:\\n\\n- user: \"Please implement a retry mechanism for our API client\"\\n assistant: \"Here is the retry mechanism implementation: [code written]\"\\n Since significant code was written, use the Agent tool to launch the stability-reviewer agent to review the new code for stability and best practices.\\n assistant: \"Now let me use the stability-reviewer agent to review this implementation for stability concerns.\"\\n\\n- user: \"Refactor the payment processing module to use the new gateway\"\\n assistant: \"I've refactored the payment processing module. Let me now use the Agent tool to launch the stability-reviewer agent to check for any stability issues or violations of our technical principles.\"\\n\\n- user: \"Can you review what I just wrote?\"\\n assistant: \"I'll use the Agent tool to launch the stability-reviewer agent to thoroughly review your recent changes.\"\\n\\n- After any significant code change, proactively launch the stability-reviewer agent to catch issues before they reach production."
description: "Use this agent to review changed code for stability: bugs, error handling, edge cases and the project's technical principles, after a feature, refactor or fix."
color: orange
tools: Bash, Read, Grep, Glob, Write
---
@@ -11,9 +11,9 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file under `~/.claude/principles/`**, the shared principles, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently.
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them.
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff <diff file>`, Infection `--git-diff-lines`, Stryker `--mutate <file>:<lines>`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling and run-heavy, as in step 4, on a scratch copy: the tools write files. Under run-heavy, a container that sets neither memory limit gets the slot's share, in MiB in `RUN_HEAVY_MEMORY`. Set the tool's concurrency so that its parallel test runs together fit in that share. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch.
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you run them unless your prompt hands you a passing run on the head (step 4).
4. **Verify, don't just read.** Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Judge the surviving mutants.** Your prompt hands you what the project's mutation command printed on the change, with the commit it ran on: the mutants of changed lines that no test kills, or the message of a run that failed. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. Where the prompt doesn't hand you any output, or names a commit other than the head, run the command yourself in the change's checkout, through run-heavy as in step 4: the one the project's README documents, else `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix '<how the project runs its tools>'`. `~/.claude/bin/mutate-changes --help` says which tool it runs for each language, how to set `--jobs`, and what it prints. Mutation-test the changed code that no run mutated, in a language mutate-changes doesn't cover or where a run failed, with a widely deployed mutation tool limited to the changed lines, else with mutants you make by hand. Report the wall time and mutant count in Coverage & Verification, or why nothing was mutated.
6. **Two passes minimum, then hunt absences.**
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
- *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity).
+1 -1
View File
@@ -1,6 +1,6 @@
---
name: systems-architect
description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n<example>\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n<commentary>\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n<commentary>\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n<commentary>\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n<commentary>\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n</commentary>\\n</example>"
description: "Use this agent to design a system or review architecture: patterns, component boundaries, fitness for purpose and long-term maintainability, not individual PR lines."
tools: Read, Grep, Glob, WebFetch, WebSearch, Write
---
You are an elite Systems Architect with decades of experience designing software systems that endure for as long as their horizon demands. Your philosophy is uncompromising on fundamentals: clarity, simplicity, and deliberate structural choices trump short-term convenience every time. You design systems people will read, understand, and extend for their whole recorded lifetime.
+9 -9
View File
@@ -115,7 +115,7 @@ class Main(unittest.TestCase):
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
@@ -151,13 +151,13 @@ class Main(unittest.TestCase):
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]][-1], ("claude-sonnet-5-5", "high"))
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"), out)
def test_a_fable_project_tries_no_rung_below_opus_at_max_and_its_report_names_fable(self):
(self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-fable-5-1"}))
code, out, err = self.run_main(["claude-fable-5-1"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
def test_a_fable_project_tries_no_rung_below_opus_at_medium_and_its_report_names_fable(self):
(self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-fable-5-2"}))
code, out, err = self.run_main(["claude-fable-5-2"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
self.assertEqual(code, 0, err)
self.assertEqual([(model, effort) for model, effort, _ in self.calls][-1], ("claude-opus-5-5", "max"))
self.assertTrue(out.splitlines()[0].startswith("Replayed 1 verdicts of claude-fable-5-1 projects"), out)
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-opus-5-5 at max effort\n"), out)
self.assertEqual([(model, effort) for model, effort, _ in self.calls][-1], ("claude-opus-5-5", "medium"))
self.assertTrue(out.splitlines()[0].startswith("Replayed 1 verdicts of claude-fable-5-2 projects"), out)
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-opus-5-5 at medium effort\n"), out)
def test_stops_at_the_projects_rung_and_names_none_when_it_misses(self):
code, out, _ = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted and rung == REFERENCE, f"said {INTERRUPTED if interrupted else FINISHED}"))
@@ -192,9 +192,9 @@ class Main(unittest.TestCase):
self.assertEqual(self.run_main(argv, unused)[0], 1)
def test_exits_1_for_a_model_no_project_runs_on(self):
code, _, err = self.run_main(["claude-fable-5-1"], unused)
code, _, err = self.run_main(["claude-fable-5-2"], unused)
self.assertEqual(code, 1)
self.assertIn("no archived verdicts of projects on claude-fable-5-1", err)
self.assertIn("no archived verdicts of projects on claude-fable-5-2", err)
def test_exits_1_on_an_unreadable_models_file(self):
(self.home / ".claude" / "loop-claude-models.json").write_text("[")
+8 -3
View File
@@ -14,6 +14,7 @@ from loop_state.waiting.listing import listed, shown
from loop_state.waiting.talk import make_way, TALK
from loop_claude.stop import needs_human, needs_terminal, Stop
from model_routing.ladder import Rung
from loop_claude.direct_message import tell
ANSWER_QUESTION = "answer the question above"
# ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
@@ -42,10 +43,14 @@ class Talked:
def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop:
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
say(f"\n{question}", effects)
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
on_terminal = effects.on_terminal()
if on_terminal:
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
effects.discard_typed()
# After the discard, so an answer typed while the DM sends counts; before the terminal check, so a loop that cannot ask still tells the human what it would have asked.
tell(f"loop-claude in {session.root} asks:\n\n{question}", effects)
if stop := needs_terminal(ANSWER_QUESTION, on_terminal):
return stop
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
effects.discard_typed()
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
with listed(questions, ask, effects):
answer = first_answer(ask, questions, effects) if answer_here else OpenOnTerminal()
+4 -4
View File
@@ -88,7 +88,7 @@ def markdown_launch(choice: ReviewChoice) -> list[str]:
def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]:
"""A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on.
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they read: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.`
For a worker one rung below the project's, routed by item 3 of E + I 5, they read: `Launch each reviewer with the Agent tool set to <rung>, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to <rung>, the project's rung.`
"""
together = {EACH_REVIEWER: choice.reviewers, EACH_SEAT: choice.seat, THE_SECURITY_PASS: choice.security}
launched: dict[Rung, list[str]] = {}
@@ -101,7 +101,7 @@ def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[s
def taken_in_launches(choice: ReviewChoice) -> list[str]:
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since loop-claude reads a taken-in item's E + I only as the cycle ends, and routes on it from the next cycle. None where no higher E + I picks a higher rung.
For a worker on Opus 5.5 at medium, on an Opus 5.5 project, routed by an item of E + I 6, it reads: `Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.`
For a worker on the project's rung, routed by an item of E + I 6, it reads: `Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `<rung>` from 7 and `<rung>` from 8.`
"""
if not choice.higher:
return []
@@ -122,7 +122,7 @@ def escalation(route: Route, project: Rung | None) -> list[str]:
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs.
For a worker on Opus 5.5 at high, on an Opus 5.5 project, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort max`.`
For a worker one rung above the project's, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `<rung>`, one rung above yours, and on each further trigger one rung higher, up to `<rung>`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `<rung>`.`
"""
if project is None or route.rung not in LADDER[:-1]:
return []
@@ -144,7 +144,7 @@ def escalation(route: Route, project: Rung | None) -> list[str]:
def reruns(route: Route, project: Rung | None) -> list[str]:
"""The sentence naming the rung one above a reviewer's and the one above a seat's, on which each reruns when it asks, leaving out either that is already on the top rung. None off the ladder.
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by an item of E + I 4, it reads: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.`
For a worker one rung below the project's, routed by an item of E + I 4, it reads: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `<rung>`.`
"""
if project is None or route.rung not in LADDER:
return []
+7
View File
@@ -0,0 +1,7 @@
from loop_effects.effects import Effects, say
def tell(text: str, effects: Effects) -> None:
"""DMs text to the human. Where the DM fails, it says why on stderr and goes on: the DM only copies what the terminal shows, so its failure never stops the loop."""
if failed := effects.dm(text):
say(f"could not DM you on Mattermost: {failed.reason}", effects)
+7
View File
@@ -22,6 +22,7 @@ from loop_claude.project.records import read_records
from claude_code.session import session_named
from loop_state.running_loops import shown_running
from loop_claude.stop import Stop
from loop_claude.direct_message import tell
@@ -30,8 +31,14 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
stop = run_loop(argv, env, paths, launcher, cwd, effects)
except KeyboardInterrupt:
stop = Stop(130, "")
except Exception as crash:
tell(f"loop-claude in {cwd} crashed: {crash!r}", effects)
raise
if stop.reason:
say(stop.reason, effects, stdout=not stop.code)
# Every stop but the human's own Ctrl-C and the help is DMed, so a loop left overnight never ends unseen. A loop given no task prints the help.
if stop.code != 130 and stop.reason != HELP:
tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects)
return stop.code
+2
View File
@@ -14,6 +14,7 @@ from routing_figures.render import render
from model_routing.ladder import Rung
from routing_figures import state
from loop_claude.stop import Stop
from loop_claude.direct_message import tell
from records.utc_stamp import utc
@@ -54,6 +55,7 @@ def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) ->
bullets = "".join(f"- {call.sentence()}\n" for call in new)
question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
say(f"\n{question}", loop.effects)
tell(f"loop-claude in {loop.root} asks:\n\n{question}", loop.effects)
if not loop.effects.on_terminal():
say("Not on a terminal: the calls are raised again at the next measurement.", loop.effects)
return None
+3
View File
@@ -33,6 +33,9 @@ interrupts of every loop on the machine. The first answer counts, from either pl
- Enter alone, on loop-claude's terminal: stops the loop.
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
Where ~/.claude/.env exists, loop-claude also sends the human each question, each release ready
to cut and each stop as a Mattermost DM, as bin/mattermost-dm sends it. Two stops are left out:
Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
as bin/loop_state/running_loops.py describes.
+19 -19
View File
@@ -444,15 +444,15 @@ class Cycles(unittest.TestCase):
("claude-sonnet-5-5", "high"),
("claude-sonnet-5-5", "high"),
("claude-opus-5-5", "medium"),
("claude-opus-5-5", "high"),
("claude-fable-5-2", "low"),
("claude-sonnet-5-5", "high"),
])
self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)})
self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2.", argument(workers[0], "-p"))
self.assertIn("on one line, as in `Chunk items: ", argument(workers[0], "-p"))
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
checkout = Checkout(self)
@@ -501,14 +501,14 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.code, 130)
workers = [call for call in run.calls if call["role"] == "worker"]
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in workers], [
("claude-opus-5-5", "high"),
("claude-opus-5-5", "xhigh"),
("claude-opus-5-5", "xhigh"),
("claude-opus-5-5", "high"),
("claude-fable-5-2", "low"),
("claude-fable-5-2", "medium"),
("claude-fable-5-2", "medium"),
("claude-fable-5-2", "low"),
])
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
checkout = Checkout(self)
@@ -522,11 +522,11 @@ class Cycles(unittest.TestCase):
], terminal_input="/talk\n", before_typing=ANSWERING)
self.assertEqual(run.code, 130)
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-opus-5-5", "high"), ("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "xhigh")])
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-fable-5-2", "low"), ("claude-fable-5-2", "medium"), ("claude-fable-5-2", "medium")])
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
self.assertNotIn("at max effort", "".join(outcomes))
self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self):
checkout = Checkout(self)
@@ -551,13 +551,13 @@ class Cycles(unittest.TestCase):
worker(say="next chunk"),
])
self.assertEqual(run.code, 130)
self.assertEqual([argument(call, "--effort") for call in run.calls if call["role"] == "judge"], ["medium", "xhigh", "medium"])
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"], [("claude-opus-5-5", "medium"), ("claude-fable-5-2", "medium"), ("claude-opus-5-5", "medium")])
workers = [call for call in run.calls if call["role"] == "worker"]
self.assertEqual({argument(call, "--effort") for call in workers}, {"high"})
self.assertIn("Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 6 taken into the chunk.", argument(workers[1], "-p"))
self.assertIn("Launch each reviewer with the Agent tool set to model fable, effort medium, the rung picked by an item of E + I 6 taken into the chunk.", argument(workers[1], "-p"))
outcomes = "".join(checkout.archived().values())
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
self.assertIn('Judge: claude-opus-5-5 at xhigh effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
self.assertIn('Judge: claude-fable-5-2 at medium effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self):
checkout = Checkout(self)
@@ -565,12 +565,12 @@ class Cycles(unittest.TestCase):
checkout.commit_plan(TODO)
run = checkout.run([worker(), judge(), worker(), judge()])
self.assertEqual(run.code, 130)
self.assertEqual(argument(run.calls[-1], "--effort"), "xhigh")
self.assertEqual((argument(run.calls[-1], "--model"), argument(run.calls[-1], "--effort")), ("claude-fable-5-2", "medium"))
checkout.git("rm", "--quiet", "todo.md")
checkout.git("commit", "--quiet", "-m", "drop the plan")
run = checkout.run([worker()])
self.assertIsNotNone(argument(run.calls[0], "--resume"))
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-opus-5-5", "xhigh"))
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "medium"))
def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self):
checkout = Checkout(self)
@@ -702,10 +702,10 @@ class Cycles(unittest.TestCase):
checkout.commit_plan(CHEAP)
run = checkout.run([step for _ in range(6) for step in (worker(), judge())] + [worker()])
self.assertEqual(run.code, 2)
stepped = '<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stopped: '
stepped = '<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stopped: '
self.assertEqual(len([outcome for outcome in checkout.archived().values() if stepped in outcome]), 1)
run = checkout.run([worker()])
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-opus-5-5", "xhigh")])
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-fable-5-2", "medium")])
def test_five_unfinished_verdicts_and_a_finished_one_do_not_add_up_to_six(self):
checkout = Checkout(self)
+158 -88
View File
@@ -92,8 +92,11 @@ def a_loop(effects, **fields):
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()):
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=()):
self.calls = []
# Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent.
self.dms = []
self.dm_failures = list(dm_failures)
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
# Without a script, every read finds all memory available.
self.free_memory = list(free_memory)
@@ -108,6 +111,7 @@ class FakeEffects:
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
claude_on_terminal=self.on_terminal_claude,
discard_typed=lambda: self.calls.append(("discard_typed", None)),
dm=self.dm,
execv=self.execv,
git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)),
input=lambda prompt: self.answer("input", prompt),
@@ -123,6 +127,10 @@ class FakeEffects:
stream_claude=self.stream,
)
def dm(self, text):
self.dms.append(text)
return self.dm_failures.pop(0) if self.dm_failures else None
def memory(self):
self.calls.append(("memory", None))
return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16)
@@ -240,7 +248,7 @@ class Transitions(unittest.TestCase):
states.transition(state, event)
def test_a_rulings_step_up_reaches_the_worker_it_resumes_through_the_answer_the_human_types_and_no_further(self):
stepped_to = Route(Rung("claude-opus-5-5", "high"), escalated_at=3)
stepped_to = Route(Rung("claude-fable-5-2", "low"), escalated_at=3)
interrupt, quoted = Interrupt("e", "q", "round 2: 🔴"), QuotedAnswer("e", "q", "A.", "round 2: 🔴")
for state, event, after in (
(states.Judging("/t"), states.Ruled(quoted, stepped_to), states.Working(quoted, 1, True)),
@@ -495,7 +503,7 @@ class Cycles(unittest.TestCase):
for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)):
with self.subTest(ruling=ruling):
self.assertIsNone(run.ruling_step_up(cycle, ruling))
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), routing.StepUp(cycle.route, Route(Routing.XHIGH, 3, 3, 4, escalated_at=3)))
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), routing.StepUp(cycle.route, Route(Routing.TWO_UP, 3, 3, 4, escalated_at=3)))
def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self):
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)]
@@ -504,8 +512,8 @@ class Cycles(unittest.TestCase):
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.HIGH, 179, 2, 5, escalated_at=4))
self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "high"])
self.assertEqual(concluded.route, Route(Routing.ONE_UP, 179, 2, 5, escalated_at=4))
self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "low"])
def test_an_escalation_quoted_from_before_the_workers_last_step_up_steps_nothing_and_a_later_one_reaches_the_verdict(self):
for escalation, verdict in (("round 2: 🔴", Unfinished("working", entries_read=4)), ("working", Unfinished("working", "working", entries_read=4))):
@@ -546,7 +554,7 @@ class Cycles(unittest.TestCase):
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
typed = resumed[resumed.index("-p") + 1]
self.assertIn("Your request for a higher rung went through: loop-claude runs you on claude-opus-5-5 at medium effort.", typed)
self.assertIn(" Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 179's E + I of 5 picks.", typed)
self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 179's E + I of 5 picks.", typed)
self.assertNotIn("went through", first[first.index("-p") + 1])
def test_a_typed_answer_past_the_quoted_answers_cap_reaches_the_worker_with_its_own_question(self):
@@ -727,6 +735,24 @@ class Interrupts(unittest.TestCase):
self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n"))
self.assertEqual(fake.calls, [])
def test_dms_the_question_naming_the_project_on_a_terminal_or_off_one(self):
for on_terminal in (True, False):
with self.subTest(on_terminal=on_terminal):
fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal)
self.put(fake)
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks:\n\nWhich one?"])
def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self):
fake = FakeEffects(inputs=["Use B."])
seen = []
effects = dataclasses.replace(fake.effects(), dm=lambda text: seen.append(list(fake.calls)))
self.assertEqual(self.put(fake, effects=effects)[0], "Use B.")
self.assertEqual(seen, [[("discard_typed", None)]])
def test_says_why_a_dm_failed_and_still_takes_the_answer(self):
fake = FakeEffects(inputs=["Use B."], dm_failures=[Failure("cannot reach https://chat.example: timed out")])
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n"))
def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self):
fake = FakeEffects(inputs=[" Use B. "])
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n"))
@@ -964,6 +990,8 @@ class RoutingCheck(unittest.TestCase):
self.assertIn(f"change nothing until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6])
self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue())
self.assertIn("routing figures: full", said.getvalue())
[sent] = fake.dms
self.assertTrue(sent.startswith(f"loop-claude in {self.loop(fake).root} asks:\n\nloop-claude's routing figures call for a routing change:\n- {new[0].sentence()}\n"), sent)
class ModelPrompt(unittest.TestCase):
@@ -1011,9 +1039,9 @@ def interrupted(likelihood=0, escalated_at=None):
class Routing(unittest.TestCase):
OPUS = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-opus-5-5", "high")
XHIGH = Rung("claude-opus-5-5", "xhigh")
MAX = Rung("claude-opus-5-5", "max")
ONE_UP = Rung("claude-fable-5-2", "low")
TWO_UP = Rung("claude-fable-5-2", "medium")
THREE_UP = Rung("claude-opus-5-5", "xhigh")
SONNET = Rung("claude-sonnet-5-5", "high")
def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self):
@@ -1041,7 +1069,7 @@ class Routing(unittest.TestCase):
self.assertEqual(routing.routed_item(todo.replace(first, "") + first, NO_CUT).id, 3)
def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self):
self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO, NO_CUT)), Route(self.HIGH, 3, 4, 5))
self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO, NO_CUT)), Route(self.ONE_UP, 3, 4, 5))
cheap = routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT)
self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5))
self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS))
@@ -1049,13 +1077,13 @@ class Routing(unittest.TestCase):
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
once = routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished())
self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1))
self.assertEqual(routing.next_route(self.OPUS, once, unfinished()), Route(self.HIGH, 3, 3, 4))
self.assertEqual(routing.next_route(self.OPUS, once, unfinished()), Route(self.ONE_UP, 3, 3, 4))
self.assertEqual(routing.next_route(self.OPUS, Route(LADDER[-1], unfinished=1), unfinished()).rung, LADDER[-1])
def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.HIGH)
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH), unfinished(4)).rung, self.XHIGH)
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.XHIGH)
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.ONE_UP)
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP), unfinished(4)).rung, self.TWO_UP)
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.TWO_UP)
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
low = Route(self.SONNET, 3, 1, 3, unfinished=1)
@@ -1064,30 +1092,30 @@ class Routing(unittest.TestCase):
self.assertEqual(routing.next_route(self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS)
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.HIGH, 3, 4, 5), unfinished(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.MAX, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.MAX, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH), unfinished(escalated_at=7)), Route(self.XHIGH, unfinished=1))
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.HIGH, 3, 2, 4, unfinished=1))
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1))
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.ONE_UP, 3, 2, 4, unfinished=1))
def test_keeps_the_mark_through_a_step_no_escalation_took(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.HIGH, 3, 3, 4, escalated_at=5))
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.ONE_UP, 3, 3, 4, escalated_at=5))
def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.MAX, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2))
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2))
def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.HIGH, 3, 1, 3, escalated_at=2))
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.ONE_UP, 3, 1, 3, escalated_at=2))
def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.XHIGH, 3, 3, 4, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.MAX, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.MAX, 3, 4, 5, unfinished=1))
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 3, 4, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, unfinished=1))
def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self):
taken = Route(self.OPUS, 3, 3, 4).taking_in(6)
@@ -1106,65 +1134,65 @@ class Routing(unittest.TestCase):
self.assertEqual(routing.next_route(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
def test_runs_the_judge_on_the_rung_its_chunks_items_e_plus_i_picks_never_below_the_projects(self):
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 5)), self.HIGH)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.XHIGH, 3, 4, 5)), self.HIGH)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.SONNET, 3, 2, 7)), self.MAX)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 5)), self.ONE_UP)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.TWO_UP, 3, 4, 5)), self.ONE_UP)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.SONNET, 3, 2, 7)), self.THREE_UP)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(Rung("claude-haiku-5-5", "max"), 3, 1, 3)), self.OPUS)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.HIGH)), self.OPUS)
self.assertEqual(routing.judge_rung("judge-model", Route(self.HIGH, 3, 4, 5)), Rung("judge-model"))
self.assertEqual(routing.judge_rung("claude-sonnet-5-5", Route(self.HIGH, 3, 4, 5)), Rung("claude-sonnet-5-5"))
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.ONE_UP)), self.OPUS)
self.assertEqual(routing.judge_rung("judge-model", Route(self.ONE_UP, 3, 4, 5)), Rung("judge-model"))
self.assertEqual(routing.judge_rung("claude-sonnet-5-5", Route(self.ONE_UP, 3, 4, 5)), Rung("claude-sonnet-5-5"))
def test_runs_the_judge_on_the_rung_the_highest_e_plus_i_taken_in_picks(self):
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)), self.XHIGH)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, escape_and_impact_taken_in=5)), self.HIGH)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)), self.TWO_UP)
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, escape_and_impact_taken_in=5)), self.ONE_UP)
def test_refuses_a_route_whose_item_has_levels_off_their_scales_or_levels_without_an_item(self):
for item, likelihood, escape_and_impact in ((3, 0, 5), (3, 5, 5), (3, 4, 1), (3, 4, 9), (0, 4, 5), (0, 4, 0), (0, 0, 5)):
with self.subTest(item=item, likelihood=likelihood, escape_and_impact=escape_and_impact):
with self.assertRaises(ValueError):
Route(self.HIGH, item, likelihood, escape_and_impact)
Route(self.ONE_UP, item, likelihood, escape_and_impact)
def test_refuses_a_route_taking_in_an_e_plus_i_off_its_scale_or_not_above_its_items(self):
for taken_in in (1, 9, -1, 5, 4):
with self.subTest(taken_in=taken_in):
with self.assertRaises(ValueError):
Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=taken_in)
Route(self.ONE_UP, 3, 4, 5, escape_and_impact_taken_in=taken_in)
def test_takes_a_route_whose_item_holds_each_levels_lowest_value(self):
self.assertEqual(Route(self.HIGH, 3, 1, 2).escape_and_impact, 2)
self.assertEqual(Route(self.ONE_UP, 3, 1, 2).escape_and_impact, 2)
def test_routes_nothing_on_an_item_without_e_or_i(self):
without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |")
self.assertIsNone(routing.routed_item(without_i, NO_CUT))
def test_archives_the_route_as_a_json_worker_line_it_reads_back_field_by_field(self):
route = Route(self.HIGH, 3, 4, 5)
self.assertEqual(route.worker_line(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5}')
route = Route(self.ONE_UP, 3, 4, 5)
self.assertEqual(route.worker_line(), '{"model": "claude-fable-5-2", "effort": "low", "item": 3, "likelihood": 4, "escape_and_impact": 5}')
self.assertEqual(route_from(route.worker_line()), route)
self.assertEqual(Route(Rung("worker-model")).worker_line(), '{"model": "worker-model"}')
self.assertEqual(route_from('{"model": "worker-model"}'), Route(Rung("worker-model")))
marked = Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12)
self.assertEqual(marked.worker_line(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}')
marked = Route(self.ONE_UP, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12)
self.assertEqual(marked.worker_line(), '{"model": "claude-fable-5-2", "effort": "low", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}')
self.assertEqual(route_from(marked.worker_line()), marked)
self.assertEqual(route_from(Route(self.HIGH, escalated_at=3).worker_line()), Route(self.HIGH, escalated_at=3))
self.assertEqual(route_from(Route(self.ONE_UP, escalated_at=3).worker_line()), Route(self.ONE_UP, escalated_at=3))
def test_leaves_the_count_of_unfinished_verdicts_out_of_the_worker_line_so_a_rerun_restarts_it(self):
self.assertEqual(route_from(Route(self.HIGH, 3, 4, 5, unfinished=1).worker_line()), Route(self.HIGH, 3, 4, 5))
self.assertEqual(route_from(Route(self.ONE_UP, 3, 4, 5, unfinished=1).worker_line()), Route(self.ONE_UP, 3, 4, 5))
def test_reads_no_route_from_a_worker_line_that_route_worker_line_could_not_have_written(self):
for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": ', "worker-model", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5"):
for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": ', "worker-model", "claude-fable-5-2 at low effort, routed by item 3's L of 4 and E + I of 5"):
with self.subTest(line=line):
self.assertIsNone(route_from(line))
def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self):
item = routing.routed_item(TODO, NO_CUT)
archived = Route(self.XHIGH, 3, 4, 5)
archived = Route(self.TWO_UP, 3, 4, 5)
def never():
raise AssertionError("not asked")
self.assertEqual(chunk_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model")))
self.assertEqual(chunk_start.routed(archived, self.OPUS, "claude-opus-5-5", never, never), archived)
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived)
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.HIGH, 3, 4, 5))
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.ONE_UP, 3, 4, 5))
self.assertEqual(chunk_start.routed(Route(self.SONNET), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
cheap = Route(self.SONNET, 4, 2, 3)
self.assertEqual(chunk_start.routed(cheap, self.OPUS, "claude-opus-5-5", never, never), cheap)
@@ -1196,7 +1224,7 @@ class RouteSources(unittest.TestCase):
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
archive = pathlib.Path(home, "archive")
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
route = Route(Rung("claude-opus-5-5", "high"), 3, 4, 5)
route = Route(Rung("claude-fable-5-2", "low"), 3, 4, 5)
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)))
transcript.parent.mkdir(parents=True)
@@ -1229,7 +1257,7 @@ class Steps(unittest.TestCase):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-fable-5-2", "low"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
def test_an_unfinished_chunk_keeps_the_items_its_verdict_found_taken_in_and_a_finished_one_drops_them(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS), items_taken_in=(3,))
@@ -1238,7 +1266,7 @@ class Steps(unittest.TestCase):
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
raised = Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=5)
raised = Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=5)
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1))
def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self):
@@ -1248,7 +1276,7 @@ class Steps(unittest.TestCase):
def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=9))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
@@ -1262,10 +1290,10 @@ class Steps(unittest.TestCase):
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4))
with contextlib.redirect_stderr(io.StringIO()):
close.closed_cycle(after, self.OPUS, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4))
blocked = pathlib.Path(home, "blocked")
blocked.write_text("")
stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, a_loop(FakeEffects().effects(), session=opened))
@@ -1382,80 +1410,80 @@ class WorkerArgs(unittest.TestCase):
def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self):
opus = Rung("claude-opus-5-5", "medium")
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS)
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", below)
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below)
self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self):
opus = Rung("claude-opus-5-5", "medium")
level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus, self.FACTS)
self.assertIn(f"item 3's L of 3. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", level)
self.assertIn(f"item 3's L of 3. Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", level)
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus, self.FACTS)
self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below)
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 6), opus))
self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below)
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), opus))
def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self):
opus = Rung("claude-opus-5-5", "medium")
taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8."
taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8."
self.assertIn(f"item 3's L of 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), opus))
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 4), opus))
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), opus))
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), opus))
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), opus))
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(Rung("m")), None))
def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self):
opus = Rung("claude-opus-5-5", "medium")
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort max, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), opus))
self.assertIn(" Launch each reviewer with the Agent tool set to model opus, effort high, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), opus))
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), opus))
self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), opus))
def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self):
opus = Rung("claude-opus-5-5", "medium")
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus, self.FACTS)
stepped_up = prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus)
self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-opus-5-5 at high effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up)
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus, self.FACTS)
stepped_up = prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus)
self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up)
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), opus))
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), None))
self.assertIn(f"item 3's L of 4.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", above)
self.assertIn(f"item 3's L of 4.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", above)
def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self):
opus = Rung("claude-opus-5-5", "medium")
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS)
self.assertIn("item 3's L of 3. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", fresh)
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus))
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "max"), 3, 4, 5), opus))
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus))
self.assertIn("item 3's L of 3. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", fresh)
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus))
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), opus))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus))
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours;", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 5), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus))
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self):
opus = Rung("claude-opus-5-5", "medium")
offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`."
offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`."
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus))
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus))
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus))
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), opus))
def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self):
opus = Rung("claude-opus-5-5", "medium")
markdown = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium."
self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 7), opus, self.FACTS))
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus))
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus))
self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self):
opus = Rung("claude-opus-5-5", "medium")
both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`."
both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), opus).endswith(both))
self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus).endswith(both))
self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both))
self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort xhigh`, and a comprehension seat with `model opus, effort high`."))
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 7), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort max`, and a comprehension seat with `model opus, effort high`."))
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`."))
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`."))
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 7), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`."))
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."))
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS))
self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
fable = Rung("claude-fable-5-1", "max")
fable = Rung("claude-fable-5-2", "max")
self.assertNotIn("rerun", prompts.resumed("", Route(fable), fable))
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
@@ -1712,12 +1740,12 @@ class LoopRuns(unittest.TestCase):
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(handed)}"))
def test_decodes_every_field_of_the_state_and_its_route(self):
state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-opus-5-5", "high"), 3, 4, 5, 1, 7, 9), unfinished_run=2, items_taken_in=(12, 14))
state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2, items_taken_in=(12, 14))
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state)
self.assertEqual(set(reload.LOOP_RUN_FIELDS), {field.name for field in dataclasses.fields(main.LoopRun)})
def test_rejects_a_field_of_another_type_or_an_unknown_field(self):
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-opus-5-5", "high"), 3, 4, 5, 1, 7, 9), unfinished_run=2))
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2))
for path, wrong in ((("unfinished_run",), "2"), (("unfinished_run",), True), (("route", "unfinished"), 1.0), (("route", "escalated_at"), "9"), (("route", "item"), True), (("route", "rung"), "claude-opus-5-5"), (("route", "rung", "model"), None), (("route",), "r"), (("route", "extra"), 1), (("route", "model"), "claude-opus-5-5"), (("route", "effort"), "high")):
with self.subTest(path=path, wrong=wrong):
handed = json.loads(json.dumps(state))
@@ -1728,7 +1756,7 @@ class LoopRuns(unittest.TestCase):
self.assertIsNone(reload.decode_handed(json.dumps(handed)))
def test_rejects_a_state_or_rung_missing_a_required_field(self):
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-opus-5-5", "high"))))
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"))))
for path in (("cycle_number",), ("root",), ("task",), ("unfinished_evidence",), ("route", "rung"), ("route", "rung", "model")):
with self.subTest(path=path):
handed = json.loads(json.dumps(state))
@@ -1746,7 +1774,7 @@ class LoopRuns(unittest.TestCase):
self.assertIsNone(reload.decode_handed("not json"))
def test_decodes_a_route_inside_the_state_or_none(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-opus-5-5", "high"), 3, 4, 5, 1))
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1))
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state)
unrouted = dataclasses.replace(state, route=None)
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(unrouted))), unrouted)
@@ -1787,6 +1815,48 @@ class LoopRuns(unittest.TestCase):
self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
class StopDms(unittest.TestCase):
def run_main(self, argv, fake):
with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()):
code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "loop-claude"), CWD, fake.effects())
return code, said.getvalue()
def test_dms_the_reason_of_a_stop_with_exit_2_such_as_a_chunk_left_unfinished_too_often(self):
fake = FakeEffects()
with unittest.mock.patch.object(main, "run_loop", return_value=Stop(2, "the human is needed to look at the chunk, but it stayed unfinished")):
self.assertEqual(self.run_main(["do it"], fake)[0], 2)
self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the human is needed to look at the chunk, but it stayed unfinished"])
def test_skips_the_dm_where_ctrl_c_stopped_the_loop(self):
fake = FakeEffects()
with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt):
self.assertEqual(self.run_main(["do it"], fake)[0], 130)
self.assertEqual(fake.dms, [])
def test_dms_a_crash_before_it_reaches_the_terminal(self):
fake = FakeEffects()
with unittest.mock.patch.object(main, "run_loop", side_effect=RuntimeError("boom")), self.assertRaises(RuntimeError):
self.run_main(["do it"], fake)
self.assertEqual(fake.dms, [f"loop-claude in {CWD} crashed: RuntimeError('boom')"])
def test_dms_the_reason_where_a_loop_given_a_task_stops_with_exit_1(self):
fake = FakeEffects()
code, said = self.run_main([main.RELOAD_FLAG, "3"], fake)
self.assertEqual(code, 1)
self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: 3"])
def test_says_why_the_dm_of_a_stop_failed_after_the_reason(self):
fake = FakeEffects(dm_failures=[Failure("cannot reach https://chat.example: timed out")])
self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n"))
def test_skips_the_dm_where_it_prints_its_help(self):
for argv, code in (([], 1), (["--help"], 0)):
with self.subTest(argv=argv):
fake = FakeEffects()
self.assertEqual(self.run_main(argv, fake)[0], code)
self.assertEqual(fake.dms, [])
class HelpLimits(unittest.TestCase):
def test_help_wraps_at_100_columns(self):
self.assertEqual([line for line in usage.HELP.splitlines() if len(line) > 100], [])
+6
View File
@@ -4,6 +4,7 @@ A change here, such as to how input reads a line, changes every tool that runs o
"""
import dataclasses
import os
import pathlib
import select
import signal
import subprocess
@@ -13,6 +14,8 @@ import time
import typing
import uuid
from mattermost_dm.dm import dm, http_json
from failure import Failure
from git_cli import git_repo
from machine_load.memory import Memory, read_memory
@@ -44,6 +47,8 @@ class Effects:
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
# Drops what was typed on the terminal and not yet read.
discard_typed: typing.Callable[[], None]
# Sends the human a direct message on Mattermost, as `mattermost-dm` does; a Failure where it could not.
dm: typing.Callable[[str], Failure | None]
execv: typing.Callable[[str, list[str]], None]
git: git_repo.Git
input: typing.Callable[[str], str]
@@ -80,6 +85,7 @@ def system_effects() -> Effects:
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
claude_on_terminal=claude_on_terminal,
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
dm=lambda text: dm(text, pathlib.Path.home(), http_json),
execv=os.execv,
git=git_repo.git,
input=input,
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from mattermost_dm import dm, main
sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: dm.read_config(dm.env_file(pathlib.Path.home())), dm.http_json, sys.stderr))
View File
+135
View File
@@ -0,0 +1,135 @@
"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4."""
import dataclasses
import http.client
import json
import pathlib
import typing
import urllib.error
import urllib.parse
import urllib.request
from failure import Failure
KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT")
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
TIMEOUT = 10
# Sends a request, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""Refuses every redirect, which Mattermost's API never sends: urllib would resend the token to the new location, even one off https."""
def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None:
return None
OPENER = urllib.request.build_opener(NoRedirect)
@dataclasses.dataclass(frozen=True)
class Config:
url: str
token: str
recipient: str
def env_file(home: pathlib.Path) -> pathlib.Path:
return home / ".claude" / ".env"
def read_config(path: pathlib.Path) -> Config | Failure:
"""The server, bot token and recipient that path's KEY=value lines hold."""
try:
mode = path.stat().st_mode
text = path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path} does not exist; it needs {', '.join(KEYS[:-1])} and {KEYS[-1]}")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"cannot read {path}: {failure}")
if mode & 0o077:
return Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}")
values = parse_env(text)
if missing := [key for key in KEYS if not values.get(key)]:
return Failure(f"{path} lacks {' and '.join(missing)}")
url, token, recipient = (values[key] for key in KEYS)
if not url.startswith("https://"):
return Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear")
return Config(url.rstrip("/"), token, recipient)
def parse_env(text: str) -> dict[str, str]:
values = {}
for line in text.splitlines():
key, equals, value = line.partition("=")
if not equals or key.lstrip().startswith("#"):
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
value = value[1:-1]
values[key.strip()] = value
return values
def send(config: Config, message: str, http: Http) -> Failure | None:
api = f"{config.url}/api/v4"
bot = id_of(http("GET", f"{api}/users/me", config.token, None), "GET /api/v4/users/me")
if isinstance(bot, Failure):
return bot
recipient = id_of(http("GET", f"{api}/users/username/{urllib.parse.quote(config.recipient)}", config.token, None), f"GET /api/v4/users/username/{config.recipient}")
if isinstance(recipient, Failure):
return recipient
channel = id_of(http("POST", f"{api}/channels/direct", config.token, [bot, recipient]), "POST /api/v4/channels/direct")
if isinstance(channel, Failure):
return channel
posted = id_of(http("POST", f"{api}/posts", config.token, {"channel_id": channel, "message": message}), "POST /api/v4/posts")
return posted if isinstance(posted, Failure) else None
def id_of(answer: object, request: str) -> str | Failure:
if isinstance(answer, Failure):
return answer
found = answer.get("id") if isinstance(answer, dict) else None
return found if isinstance(found, str) and found else Failure(f"{request} answered without an id")
def http_json(method: str, url: str, token: str, body: object) -> object:
"""The JSON that url answers; a Failure naming the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON."""
request_name = f"{method} {urllib.parse.urlsplit(url).path}"
data = None if body is None else json.dumps(body).encode()
request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, method=method)
try:
with OPENER.open(request, timeout=TIMEOUT) as response:
raw = response.read()
except urllib.error.HTTPError as failure:
with failure:
return Failure(f"{request_name} answered {failure.code}: {error_message(failure) or failure.reason}")
except http.client.HTTPException as failure:
return Failure(f"{request_name} got a broken answer: {failure!r}")
except (OSError, ValueError) as failure:
server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", ""))
return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}")
try:
return json.loads(raw)
except ValueError:
return Failure(f"{request_name} answered with something other than JSON")
def error_message(failure: urllib.error.HTTPError) -> str:
"""Mattermost's message in an error answer; empty where the body is cut short, breaks HTTP or holds none."""
try:
answer = json.loads(failure.read())
except (http.client.HTTPException, OSError, ValueError):
return ""
message = answer.get("message") if isinstance(answer, dict) else None
return message if isinstance(message, str) else ""
def dm(text: str, home: pathlib.Path, http: Http) -> Failure | None:
"""Sends text as home's .claude/.env configures it. A machine without that file hasn't asked for DMs, so there the DM is skipped."""
path = env_file(home)
if not path.exists():
return None
config = read_config(path)
return config if isinstance(config, Failure) else send(config, text, http)
+43
View File
@@ -0,0 +1,43 @@
"""Send a direct message from the Mattermost bot to the human.
usage: mattermost-dm [<message>]
Sends <message>, or else stdin, from the bot to the recipient that ~/.claude/.env names. That file
holds three KEY=value lines, and only its owner may read it, since it holds the bot's token:
MATTERMOST_URL=https://chat.example
MATTERMOST_TOKEN=<the bot's access token>
MATTERMOST_RECIPIENT=<the recipient's username>
Exit 0 once the message is sent.
Exit 1, saying why, when Mattermost cannot be reached or refuses the message.
Exit 2, saying why, on misuse: bad arguments, an empty message, or a ~/.claude/.env that is
missing or unreadable, lacks a key, names a server off https, or that others may read.
"""
import typing
from mattermost_dm.dm import Config, Http, send
from failure import Failure
USAGE = "usage: mattermost-dm [<message>]"
def main(argv: list[str], stdin: typing.TextIO, config: typing.Callable[[], Config | Failure], http: Http, stderr: typing.TextIO) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if len(argv) > 1:
print(f"mattermost-dm: takes one message, or none to read stdin; got {len(argv)} arguments\n{USAGE}", file=stderr)
return 2
message = (argv[0] if argv else stdin.read()).strip()
if not message:
print("mattermost-dm: the message is empty", file=stderr)
return 2
found = config()
if isinstance(found, Failure):
print(f"mattermost-dm: {found.reason}", file=stderr)
return 2
if failed := send(found, message, http):
print(f"mattermost-dm: {failed.reason}", file=stderr)
return 1
return 0
+268
View File
@@ -0,0 +1,268 @@
import http.server
import io
import json
import pathlib
import socket
import subprocess
import sys
import tempfile
import threading
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from mattermost_dm import dm, main
from failure import Failure
from test_env import isolated_env
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mattermost-dm"
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path:
path = pathlib.Path(folder) / ".env"
path.write_text(text)
path.chmod(mode)
return path
class FakeServer:
"""Mattermost's answers by method and path, recording each request it gets."""
def __init__(self, answers: dict[tuple[str, str], object]) -> None:
self.answers = answers
self.requests: list[tuple[str, str, str, object]] = []
def __call__(self, method: str, url: str, token: str, body: object) -> object:
self.requests.append((method, url, token, body))
return self.answers[(method, url.removeprefix("https://chat.example"))]
def mattermost() -> FakeServer:
return FakeServer({
("GET", "/api/v4/users/me"): {"id": "bot-id"},
("GET", "/api/v4/users/username/lilleman"): {"id": "human-id"},
("POST", "/api/v4/channels/direct"): {"id": "channel-id"},
("POST", "/api/v4/posts"): {"id": "post-id"},
})
class ReadConfig(unittest.TestCase):
def test_reads_the_server_the_token_and_the_recipient_skipping_blanks_comments_and_quotes(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, '# larvit-bot\n\nMATTERMOST_URL = https://chat.example/\nMATTERMOST_TOKEN="secret-token"\nMATTERMOST_RECIPIENT=\'lilleman\'\nOTHER=1\n')
self.assertEqual(dm.read_config(path), dm.Config("https://chat.example", "secret-token", "lilleman"))
def test_names_the_file_and_the_keys_it_needs_where_the_file_is_missing(self):
with tempfile.TemporaryDirectory() as folder:
path = pathlib.Path(folder) / ".env"
self.assertEqual(dm.read_config(path), Failure(f"{path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
def test_names_each_key_missing_or_empty(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=\n")
self.assertEqual(dm.read_config(path), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
def test_refuses_a_file_that_group_or_others_can_read_since_it_holds_the_token(self):
with tempfile.TemporaryDirectory() as folder:
for mode in (0o640, 0o604):
with self.subTest(mode=oct(mode)):
path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n", mode)
self.assertEqual(dm.read_config(path), Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}"))
def test_refuses_a_server_off_https_which_would_send_the_token_in_the_clear(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, "MATTERMOST_URL=http://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n")
self.assertEqual(dm.read_config(path), Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear"))
class Send(unittest.TestCase):
def test_finds_both_users_opens_their_direct_channel_and_posts_the_message_there(self):
server = mattermost()
self.assertIsNone(dm.send(CONFIG, "Which one?", server))
self.assertEqual(server.requests, [
("GET", "https://chat.example/api/v4/users/me", "secret-token", None),
("GET", "https://chat.example/api/v4/users/username/lilleman", "secret-token", None),
("POST", "https://chat.example/api/v4/channels/direct", "secret-token", ["bot-id", "human-id"]),
("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}),
])
def test_stops_at_the_first_failed_request(self):
server = mattermost()
server.answers[("GET", "/api/v4/users/username/lilleman")] = Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username.")
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username."))
self.assertEqual(len(server.requests), 2)
def test_fails_on_an_answer_without_an_id_or_one_that_is_not_an_object(self):
for answer in ({"status": "OK"}, ["channel-id"], {"id": ""}):
with self.subTest(answer=answer):
server = mattermost()
server.answers[("POST", "/api/v4/channels/direct")] = answer
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/channels/direct answered without an id"))
self.assertEqual(len(server.requests), 3)
def test_fails_where_the_post_itself_fails(self):
server = mattermost()
server.answers[("POST", "/api/v4/posts")] = Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions.")
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions."))
class Recorded(http.server.BaseHTTPRequestHandler):
"""Answers each request with the server's next scripted status and body, recording what it got."""
def do_GET(self) -> None:
self.answer()
def do_POST(self) -> None:
self.answer()
def answer(self) -> None:
length = int(self.headers.get("Content-Length") or 0)
self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined]
status, body = self.server.script.pop(0) # type: ignore[attr-defined]
if status is None:
# Raw bytes, as a server that breaks HTTP sends them.
self.wfile.write(body)
self.close_connection = True
return
self.send_response(status)
if 300 <= status < 400:
self.send_header("Location", "/elsewhere")
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def log_message(self, format: str, *args: object) -> None:
pass
class HttpJson(unittest.TestCase):
def serve(self, *script: tuple[int, bytes]) -> str:
server = http.server.HTTPServer(("127.0.0.1", 0), Recorded)
server.script = list(script) # type: ignore[attr-defined]
server.got = [] # type: ignore[attr-defined]
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
self.server = server
return f"http://127.0.0.1:{server.server_port}"
def test_sends_the_token_as_a_bearer_and_the_body_as_json_and_reads_the_json_answer(self):
base = self.serve((201, b'{"id": "post-id"}'))
self.assertEqual(dm.http_json("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
[(method, path, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", {"message": "hi"}))
def test_names_the_request_the_status_and_mattermosts_message_on_an_error(self):
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
base = self.serve((302, b"{}"))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
def test_sends_no_body_with_a_get(self):
base = self.serve((200, b'{"id": "bot-id"}'))
dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((headers.get("Content-Length"), body), (None, b""))
def test_fails_on_an_answer_that_breaks_http(self):
for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"):
with self.subTest(raw=raw):
base = self.serve((None, raw))
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed)
def test_names_the_status_of_an_error_whose_body_is_cut_short(self):
base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}"))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error"))
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
silent = socket.socket()
self.addCleanup(silent.close)
silent.bind(("127.0.0.1", 0))
silent.listen(1)
base = f"http://127.0.0.1:{silent.getsockname()[1]}"
with unittest.mock.patch.object(dm, "TIMEOUT", 0.2):
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure(f"cannot reach {base}: timed out"))
def test_fails_on_an_answer_that_is_not_json(self):
base = self.serve((200, b"<html>"))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON"))
def test_fails_naming_the_server_it_cannot_reach(self):
base = self.serve()
self.server.server_close()
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
self.assertIsInstance(failed, Failure)
self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed)
class Dm(unittest.TestCase):
def home_with(self, home: str, text: str) -> pathlib.Path:
folder = pathlib.Path(home, ".claude")
folder.mkdir()
return env_file(str(folder), text)
def test_sends_through_the_env_file_under_home(self):
with tempfile.TemporaryDirectory() as home:
self.home_with(home, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
server = mattermost()
self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server))
self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}))
def test_skips_the_dm_on_a_machine_without_the_env_file(self):
with tempfile.TemporaryDirectory() as home:
server = mattermost()
self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server))
self.assertEqual(server.requests, [])
def test_fails_naming_the_mistake_where_the_env_file_is_there_but_wrong(self):
with tempfile.TemporaryDirectory() as home:
path = self.home_with(home, "MATTERMOST_URL=https://chat.example\n")
self.assertEqual(dm.dm("Which one?", pathlib.Path(home), mattermost()), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
class Main(unittest.TestCase):
def run_main(self, argv: list[str], stdin: str = "", config: object = CONFIG, server: object = None) -> tuple[int, str]:
stderr = io.StringIO()
sent = server or mattermost()
code = main.main(argv, io.StringIO(stdin), lambda: config, sent, stderr) # type: ignore[arg-type]
return code, stderr.getvalue()
def test_sends_its_argument_or_else_stdin_and_exits_0(self):
for argv, stdin in ((["Which one?"], ""), ([], "Which one?\n")):
with self.subTest(argv=argv):
server = mattermost()
self.assertEqual(self.run_main(argv, stdin, server=server), (0, ""))
self.assertEqual(server.requests[-1][3], {"channel_id": "channel-id", "message": "Which one?"})
def test_exits_2_on_misuse_naming_it(self):
missing = Failure("/h/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")
for argv, stdin, config, said in (
([], " \n", CONFIG, "mattermost-dm: the message is empty\n"),
(["a", "b"], "", CONFIG, f"mattermost-dm: takes one message, or none to read stdin; got 2 arguments\n{main.USAGE}\n"),
(["hi"], "", missing, f"mattermost-dm: {missing.reason}\n"),
):
with self.subTest(argv=argv, stdin=stdin):
self.assertEqual(self.run_main(argv, stdin, config), (2, said))
def test_exits_1_naming_why_the_send_failed(self):
server = mattermost()
server.answers[("GET", "/api/v4/users/me")] = Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.")
self.assertEqual(self.run_main(["hi"], server=server), (1, "mattermost-dm: GET /api/v4/users/me answered 401: Invalid or expired session, please login again.\n"))
def test_the_launcher_prints_help_and_reads_the_env_file_under_home(self):
with tempfile.TemporaryDirectory() as home:
env = {**isolated_env(), "HOME": home}
helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env)
self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0]))
sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env)
self.assertEqual((sent.returncode, sent.stderr), (2, f"mattermost-dm: {home}/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT\n"))
if __name__ == "__main__":
unittest.main()
+4 -3
View File
@@ -51,10 +51,11 @@ class Rung:
LADDER = (
Rung("claude-sonnet-5-5", "high"),
Rung("claude-opus-5-5", "medium"),
Rung("claude-opus-5-5", "high"),
Rung("claude-fable-5-2", "low"),
Rung("claude-fable-5-2", "medium"),
Rung("claude-opus-5-5", "xhigh"),
Rung("claude-opus-5-5", "max"),
Rung("claude-fable-5-1", "max"),
Rung("claude-fable-5-2", "high"),
Rung("claude-fable-5-2", "max"),
)
# The rungs a task's L steps its worker from the project's rung.
WORKER_STEPS = {1: -1, 2: -1, 3: 0, 4: 1}
+8 -10
View File
@@ -9,19 +9,17 @@ from release_plan.todo_table import LEVELS
from review_rules.review_passes import REVIEWERS
OPUS = Rung("claude-opus-5-5", "medium")
FABLE_LOW = Rung("claude-fable-5-2", "low")
class Ladder(unittest.TestCase):
def test_runs_from_sonnet_at_high_effort_to_fable_at_max_with_opus_at_medium_between(self):
self.assertEqual(LADDER[0], Rung("claude-sonnet-5-5", "high"))
self.assertEqual(LADDER[1], OPUS)
self.assertEqual(LADDER[-1], Rung("claude-fable-5-1", "max"))
self.assertEqual(len(LADDER), 6)
def test_holds_each_rung_once_since_a_rung_s_position_sets_every_step(self):
self.assertEqual(len(set(LADDER)), len(LADDER))
def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self):
self.assertEqual(project_rung("claude-opus-5-5"), OPUS)
self.assertEqual(project_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(project_rung("claude-fable-5-2"), FABLE_LOW)
self.assertIsNone(project_rung("claude-opus-5"))
self.assertIsNone(project_rung("opus"))
@@ -39,7 +37,7 @@ class Ladder(unittest.TestCase):
self.assertEqual(worker_rung(LADDER[0], 1), LADDER[0])
self.assertEqual(review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER[-1])
self.assertEqual(stepped_up(LADDER[-1]), LADDER[-1])
self.assertEqual(stepped_up(OPUS), Rung("claude-opus-5-5", "high"))
self.assertEqual(stepped_up(OPUS), FABLE_LOW)
def test_steps_a_worker_for_every_level_on_ls_scale(self):
self.assertEqual(set(WORKER_STEPS), set(range(1, LEVELS["L"] + 1)))
@@ -49,7 +47,7 @@ class Ladder(unittest.TestCase):
def test_plans_on_the_rung_l_picks_but_never_below_the_projects(self):
self.assertEqual(planning_rung(OPUS, 1), OPUS)
self.assertEqual(planning_rung(OPUS, 4), Rung("claude-opus-5-5", "high"))
self.assertEqual(planning_rung(OPUS, 4), FABLE_LOW)
def test_names_each_rung_by_a_family_the_agent_tool_takes(self):
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model sonnet", "model opus", "model fable"})
@@ -89,7 +87,7 @@ class Ladder(unittest.TestCase):
self.assertEqual(Rung.from_agent("sonnet", ""), Rung("claude-sonnet-5-5", "high"))
def test_reads_an_unknown_family_or_an_effort_off_the_ladder_as_a_rung_off_it(self):
for model, effort in (("gpt", "high"), ("gpt", ""), ("opus", "low"), ("haiku", "bogus")):
for model, effort in (("gpt", "high"), ("gpt", ""), ("opus", "low"), ("opus", "high"), ("haiku", "bogus")):
with self.subTest(model=model, effort=effort):
self.assertNotIn(Rung.from_agent(model, effort), LADDER)
self.assertEqual(Rung.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
@@ -97,9 +95,9 @@ class Ladder(unittest.TestCase):
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
sonnet, fable = LADDER[0], LADDER[-1]
self.assertEqual(review_rung(OPUS, sonnet, 4, "stability"), OPUS)
self.assertEqual(review_rung(OPUS, sonnet, 5, "stability"), Rung("claude-opus-5-5", "high"))
self.assertEqual(review_rung(OPUS, sonnet, 5, "stability"), FABLE_LOW)
self.assertEqual(review_rung(OPUS, fable, 5, "stability"), fable)
self.assertEqual(review_rung(OPUS, Rung("claude-opus-5-5", "high"), 7, "stability"), Rung("claude-opus-5-5", "max"))
self.assertEqual(review_rung(OPUS, FABLE_LOW, 7, "stability"), Rung("claude-opus-5-5", "xhigh"))
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER[-1]] * len(REVIEWERS) + [OPUS, OPUS])
+1 -1
View File
@@ -5,7 +5,7 @@ from model_routing.route import Route
from model_routing.ladder import Rung
OPUS = Rung("claude-opus-5-5", "medium")
FABLE = Rung("claude-fable-5-1", "max")
FABLE = Rung("claude-fable-5-2", "max")
class Chosen(unittest.TestCase):
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
import pathlib
import signal
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from mutate_changes import main
# Python ends on SIGTERM or SIGHUP without running a finally, which would leave the scratch copy and the tool running. As
# SystemExit, the run unwinds as on Ctrl-C.
for number in (signal.SIGHUP, signal.SIGTERM):
signal.signal(number, lambda number, frame: sys.exit(128 + number))
sys.exit(main.main(sys.argv[1:]))
View File
+63
View File
@@ -0,0 +1,63 @@
"""Which lines of a file a branch adds or changes, which mutation tool mutates the file, and in which folder."""
import os
import posixpath
import re
import typing
# A hunk header of `git diff -U0`. The new side's count is 0 where the hunk only deletes, and left out where it is 1.
HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)
STRYKER = (".cjs", ".cts", ".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx")
TOOLS = {".php": "infection", ".py": "mutmut", ".rs": "cargo-mutants", **dict.fromkeys(STRYKER, "stryker")}
TEST_FOLDERS = frozenset({"__tests__", "test", "tests"})
TEST_NAME = re.compile(r"test_.*\.py|.*_test\.py|conftest\.py|.*\.(?:spec|test)\.[^.]+")
def added_lines(diff: str) -> frozenset[int]:
"""The line numbers, in the new file, that a `git diff -U0` of one file adds or changes."""
return frozenset(line for hunk in HUNK.finditer(diff) for line in range(int(hunk[1]), int(hunk[1]) + int(hunk[2] or 1)))
def runs(lines: typing.Iterable[int]) -> list[tuple[int, int]]:
"""The lines as runs of consecutive numbers, each as its first and last line, in order."""
found: list[tuple[int, int]] = []
for line in sorted(lines):
if found and found[-1][1] == line - 1:
found[-1] = (found[-1][0], line)
else:
found.append((line, line))
return found
def tool_for(path: str) -> str | None:
"""The tool that mutates a file, by its extension; None for a test file, or a language none of the tools covers."""
return None if is_test(path) else TOOLS.get(posixpath.splitext(path)[1])
def is_test(path: str) -> bool:
folders, name = posixpath.split(path)
return bool(TEST_FOLDERS & set(folders.split("/")) or TEST_NAME.fullmatch(name))
def not_mutated(paths: list[str]) -> list[str]:
"""A line naming the paths in a language no tool covers, then one naming the test files, leaving out a line that would name none."""
uncovered = [path for path in paths if tool_for(path) is None and not is_test(path)]
tests = [path for path in paths if is_test(path)]
lines = (("Not mutated, as no tool covers their language", uncovered), ("Not mutated, as test files", tests))
return [f"{text}: {', '.join(found)}." for text, found in lines if found]
def by_folder(top: str, changed: dict[str, frozenset[int]], configs: tuple[str, ...]) -> dict[str, dict[str, frozenset[int]]]:
"""The changed files by the nearest folder above each that holds one of configs, "." for top where none does, each file by its
path from that folder."""
grouped: dict[str, dict[str, frozenset[int]]] = {}
for path, lines in changed.items():
folder = posixpath.dirname(path)
while folder and not any(os.path.isfile(os.path.join(top, folder, name)) for name in configs):
folder = posixpath.dirname(folder)
grouped.setdefault(folder or ".", {})[posixpath.relpath(path, folder or ".")] = lines
return grouped
def label(folder: str) -> str:
"""A folder from the checkout's top, as a report names it."""
return "the checkout's top" if folder == "." else folder
+79
View File
@@ -0,0 +1,79 @@
"""Mutate a branch's changed lines with cargo-mutants, Stryker and Infection, each of which takes the changed lines itself."""
import os
import pathlib
from mutate_changes.changed_lines import by_folder, label, runs
from mutate_changes.tool_process import failed, Ran, remove, run_tool, scratch_folder
from failure import Failure
from git_cli.git_repo import git
# cargo-mutants' exit codes for a run that finished: every mutant caught, some missed, and some timed out.
CARGO_FINISHED = frozenset({0, 2, 3})
CARGO_OUTCOMES = ("caught", "missed", "timeout", "unviable")
def run_cargo_mutants(top: str, base: str, paths: list[str], prefix: str | None, jobs: int) -> list[str] | Failure:
"""A line with cargo-mutants' mutant count, then a line per mutant it missed or that timed out, as `<path>:<line>:<column>: <outcome>: <mutation>`.
cargo-mutants runs in top."""
# cargo-mutants finds each file's path after a b/, a prefix that settings such as diff.mnemonicPrefix change.
diff = git("diff", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", base, "--", *paths, cwd=top)
if isinstance(diff, Failure):
return diff
scratch = scratch_folder(top)
if isinstance(scratch, Failure):
return scratch
try:
pathlib.Path(scratch, "branch.diff").write_text(diff, encoding="utf-8")
relative = os.path.relpath(scratch, top)
ran = run_tool(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top, prefix)
if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED:
return ran if isinstance(ran, Failure) else failed("cargo mutants", ran)
outcomes = {outcome: outcome_lines(pathlib.Path(scratch, "mutants.out", f"{outcome}.txt")) for outcome in CARGO_OUTCOMES}
except OSError as failure:
return Failure(f"could not hand cargo-mutants the diff or read its outcomes in {scratch}: {failure}")
finally:
remove(scratch)
uncaught = [f"{location}: {outcome}: {mutation}" for outcome in ("missed", "timeout") for location, _, mutation in (line.partition(": ") for line in outcomes[outcome])]
return [f"cargo-mutants: {sum(map(len, outcomes.values()))} mutants on changed lines, {len(uncaught)} not caught.", *uncaught]
def outcome_lines(path: pathlib.Path) -> list[str]:
return path.read_text(encoding="utf-8", errors="replace").splitlines() if path.is_file() else []
# Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't
# tell from a run that broke, so either fails the run.
def run_stryker(top: str, changed: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure:
"""For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line
naming the files with no package.json above them, if any.
Stryker runs in the nearest folder above each file that holds a package.json. npx runs the project's own @stryker-mutator/core, else
one an earlier npx run cached, and installs none."""
report: list[str] = []
unplaced: list[str] = []
for folder, files in sorted(by_folder(top, changed, ("package.json",)).items()):
# by_folder falls back to top, where no package.json means there is no Stryker to run.
if not os.path.isfile(os.path.join(top, folder, "package.json")):
unplaced = sorted(files)
continue
mutate = ",".join(f"{path}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines))
ran = run_tool(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder), prefix)
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else whole_output(f"Stryker in {label(folder)}", ran)
report.extend([f"Stryker in {label(folder)}:", *ran.output.splitlines()])
return [*report, *([f"Not mutated, as no package.json is above them: {', '.join(unplaced)}."] if unplaced else [])]
def run_infection(top: str, base: str, prefix: str | None, jobs: int) -> list[str] | Failure:
"""A line naming where Infection ran, top, then its own report of the mutants on the lines the branch changes since base."""
ran = run_tool(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top, prefix)
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else whole_output("Infection", ran)
return ["Infection in the checkout's top:", *ran.output.splitlines()]
def whole_output(name: str, ran: Ran) -> Failure:
"""A tool's exit code and its whole output. Stryker and Infection also exit nonzero on a mutation score below the project's threshold,
where the output is the report of what survived."""
return Failure("\n".join([f"{name} exited {ran.code}:", *ran.output.splitlines()]))
+144
View File
@@ -0,0 +1,144 @@
"""Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill.
usage: mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]
Run it in a checkout, under ~/.claude/bin/run-heavy. It diffs the working tree's tracked files against the merge base of HEAD and
--base, by default the default branch: origin's as last fetched, else main or master. It picks the tool by each changed file's
extension, and leaves out test files: test_*.py, *_test.py, conftest.py, *.test.* and *.spec.*, and any file under a tests/, test/
or __tests__/ folder.
- .py: mutmut 3, in a scratch copy of the nearest folder above the file that holds a setup.cfg or a pyproject.toml, else of the
checkout's top. It mutates each function or method a changed line falls in, and counts the mutants on changed lines. The
folder's setup.cfg settings stay, but source_paths and also_copy are set, and pytest leaves out each test that fails without a
mutant; the report names their files. mutmut sees only the code a test runs in its own process, so a mutant that only a child
process reaches, such as a tool a test starts, shows as `no tests`. A pyproject.toml with a [tool.mutmut] section fails the run.
- .rs: cargo-mutants, as `cargo mutants --in-diff`, in the checkout's top.
- .cjs, .cts, .js, .jsx, .mjs, .mts, .ts, .tsx: Stryker, as `npx --no --package=@stryker-mutator/core stryker run --mutate` on the
changed lines, in the nearest folder above the file that holds a package.json. A file with no package.json above it isn't
mutated. npx runs the project's own @stryker-mutator/core, else one an earlier npx run cached, and installs none.
- .php: Infection, as `vendor/bin/infection --git-diff-lines`, in the checkout's top.
--prefix is shell text that runs each tool: sh runs `<prefix> "$@"` in the tool's folder, which $PWD names, with the tool's command
as "$@". For example, 'uvx --from "mutmut>=3,<4"'. Without --prefix, the command runs as it is. A container must mount $PWD and
run there, as 'docker compose -f "$(git rev-parse --show-toplevel)/compose.yaml" run --rm -v "$PWD:$PWD" -w "$PWD" app' does. "$1"
is the command's first word, mutmut, cargo, npx or vendor/bin/infection, so a prefix can pick what to run per tool:
'case "$1" in mutmut) set -- uvx --from "mutmut>=3,<4" "$@";; esac;'.
--jobs sets how many tests each tool runs at once, 4 by default: one heavy slot's CPUs. Under run-heavy, a container that sets
neither memory limit gets the slot's share, in MiB in RUN_HEAVY_MEMORY; set --jobs so that that many test runs fit in it.
It prints:
- for mutmut, per folder, a line with the mutant count, then a line per mutant on a changed line that is not killed, as
`<path>:<line>: <status>: <the line as mutated>`, or `<path>: <status>: <name>, on a line mutate-changes cannot find`;
- for cargo-mutants, a line with the mutant count, then a line per mutant it missed or that timed out, as
`<path>:<line>:<column>: <outcome>: <mutation>`;
- for Stryker and Infection, a line naming the folder the tool ran in, then the tool's own report;
- a line naming the changed JavaScript and TypeScript files with no package.json above them;
- a line naming the changed files in a language no tool covers, then one naming the changed test files, none of which it mutates;
- last, the wall time.
Exit 1, saying why, on an unknown or repeated argument, an option without its value, or a --jobs that is no whole number from 1.
Exit 1 too when git fails, a file cannot be read or copied, a tool cannot start, or a tool fails before it reports. Stryker and
Infection also exit nonzero on a mutation score below a threshold the project sets, which fails the run as well and prints their
whole report.
"""
import sys
import time
from mutate_changes.changed_lines import added_lines, not_mutated, tool_for
from machine_load.slots import CPUS_PER_SLOT
from git_cli.git_repo import default_ref, git, top
from failure import Failure
from mutate_changes.in_diff_tools import run_cargo_mutants, run_infection, run_stryker
from mutate_changes.mutmut_tool import run_mutmut
USAGE = "usage: mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]"
# A panel of three readers, seated as the README's audience, picked the command's name and these options on 2026-11-11.
OPTIONS = ("--base", "--jobs", "--prefix")
def main(argv: list[str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
given = options(argv)
if isinstance(given, Failure):
print(f"{given.reason}; {USAGE}", file=sys.stderr)
return 1
started = time.monotonic()
report = mutate(given)
if isinstance(report, Failure):
print(report.reason, file=sys.stderr)
return 1
print("\n".join([*report, f"mutate-changes took {took(time.monotonic() - started)}."]))
return 0
def options(argv: list[str]) -> dict[str, str] | Failure:
given: dict[str, str] = {}
rest = list(argv)
while rest:
name, equals, value = rest.pop(0).partition("=")
if name not in OPTIONS or name in given:
return Failure(f"unknown or repeated argument {name}")
if not equals and not rest:
return Failure(f"{name} needs a value")
given[name] = value if equals else rest.pop(0)
if not given.get("--jobs", "1").isdecimal() or int(given.get("--jobs", "1")) < 1:
return Failure(f"--jobs takes a whole number from 1, not {given['--jobs']}")
return given
def mutate(given: dict[str, str]) -> list[str] | Failure:
"""Each tool's report on the lines the branch adds, then the lines naming the changed files no tool mutates."""
checkout = top()
if isinstance(checkout, Failure):
return checkout
base = given.get("--base") or default_ref(cwd=checkout)
if isinstance(base, Failure):
return base
found = git("merge-base", base, "HEAD", cwd=checkout)
if isinstance(found, Failure):
return found
merge_base = found.strip()
names = git("diff", "--name-only", "-z", "--diff-filter=d", merge_base, cwd=checkout)
if isinstance(names, Failure):
return names
paths = list(filter(None, names.split("\0")))
changed = changed_by_tool(checkout, merge_base, paths)
if isinstance(changed, Failure):
return changed
prefix, jobs = given.get("--prefix"), int(given.get("--jobs", CPUS_PER_SLOT))
report = [] if changed else ["No tool ran: the branch adds no line to a file that a tool mutates."]
for tool, files in sorted(changed.items()):
if tool == "cargo-mutants":
lines = run_cargo_mutants(checkout, merge_base, sorted(files), prefix, jobs)
elif tool == "infection":
lines = run_infection(checkout, merge_base, prefix, jobs)
elif tool == "stryker":
lines = run_stryker(checkout, files, prefix, jobs)
else:
lines = run_mutmut(checkout, files, prefix, jobs)
if isinstance(lines, Failure):
return lines
report.extend(lines)
return [*report, *not_mutated(paths)]
def changed_by_tool(checkout: str, merge_base: str, paths: list[str]) -> dict[str, dict[str, frozenset[int]]] | Failure:
"""Each tool's files among paths, by path from the checkout's top, with the lines the working tree adds since merge_base."""
changed: dict[str, dict[str, frozenset[int]]] = {}
for path in paths:
if (tool := tool_for(path)) is None:
continue
diff = git("diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", merge_base, "--", path, cwd=checkout, errors="replace")
if isinstance(diff, Failure):
return diff
if lines := added_lines(diff):
changed.setdefault(tool, {})[path] = lines
return changed
def took(seconds: float) -> str:
whole = round(seconds)
return f"{whole // 60} min {whole % 60} s" if whole >= 60 else f"{whole} s"
+102
View File
@@ -0,0 +1,102 @@
"""Which of mutmut 3's mutants the changed lines hold, from their names, `mutmut results` and the copy of each file mutmut writes under mutants/.
mutmut names a mutant `<module>.<key>__mutmut_<number>`. The key is x_<function> for a function at a module's top, and xǁ<class>ǁ<method> for a method of a class there; mutmut mutates no other code. Its mutants/ copy of a file holds the original of each function mutmut mutates, as `<key>__mutmut_orig`, and each mutant as a changed copy of that original."""
import ast
import functools
from typing import NamedTuple
from collections.abc import Sequence
def function_keys(source: str, lines: frozenset[int]) -> list[str]:
"""mutmut's key of each function or method that one of the lines falls in, decorators included, in source order."""
keys = []
for node in ast.parse(source).body:
inner = node.body if isinstance(node, ast.ClassDef) else [node]
for function in inner:
if isinstance(function, (ast.AsyncFunctionDef, ast.FunctionDef)) and lines & set(range(first_line(function), (function.end_lineno or function.lineno) + 1)):
keys.append(f"xǁ{node.name}ǁ{function.name}" if isinstance(node, ast.ClassDef) else f"x_{function.name}")
return keys
def first_line(function: ast.AsyncFunctionDef | ast.FunctionDef) -> int:
return min([function.lineno, *(decorator.lineno for decorator in function.decorator_list)])
def module(path: str) -> str:
"""The module name mutmut gives a file, from its path relative to the folder mutmut runs in."""
return path.removesuffix(".py").replace("/", ".").removeprefix("src.")
def mutant_globs(path: str, keys: list[str]) -> list[str]:
"""The `mutmut run` patterns that pick each function's mutants. Each pattern has no __mutmut_, so it also matches the function's own name, and mutmut runs only the tests that reach one of the functions."""
return [f"{module(path)}.{key}*".replace(".__init__.", ".") for key in keys]
def named(name: str, paths: list[str]) -> tuple[str, str, int] | None:
"""Of the paths given, the one holding the mutant called name, with the mutant's function key and number; None where none holds it."""
prefix, _, number = name.rpartition("__mutmut_")
_, _, key = prefix.rpartition(".")
found = [path for path in paths if f"{module(path)}.{key}".replace(".__init__.", ".") == prefix]
return (found[0], key, int(number)) if found and number.isdigit() else None
def statuses(results: str) -> dict[str, str]:
"""Each mutant's status by name, from the ` <name>: <status>` lines `mutmut results --all true` prints."""
return {name: status for name, _, status in (line.strip().partition(": ") for line in results.splitlines()) if "__mutmut_" in name and status}
def mutated_line(source: str, copy: str, key: str, number: int) -> tuple[int, str] | None:
"""The source line a mutant changes, with that line as the mutant has it; None where the mutants/ copy lacks the mutant, or holds an original unlike the source.
A mutant keeps the original's lines, so the first line where they differ sits at the same offset from the source function's def."""
module, copied = parsed(source), parsed(copy)
if module is None or copied is None:
return None
function = defined(module.tree, key)
original, mutant = copied.functions.get(f"{key}__mutmut_orig"), copied.functions.get(f"{key}__mutmut_{number}")
if function is None or original is None or mutant is None:
return None
expected = as_named(module.lines, function, function.name)
kept, changed = (as_named(copied.lines, node, function.name) for node in (original, mutant))
if kept != expected:
return None
offset = next((index for index, (was, now) in enumerate(zip(kept, changed)) if was != now), None)
return None if offset is None else (function.lineno + offset, changed[offset].strip())
class Parsed(NamedTuple):
tree: ast.Module
functions: dict[str, ast.AsyncFunctionDef | ast.FunctionDef]
lines: tuple[str, ...]
# mutated_line reads the same source and mutants/ copy for each of a file's mutants, and a copy holds every mutant, so parsing it
# anew for each one made the report take minutes.
@functools.lru_cache(maxsize=4)
def parsed(text: str) -> Parsed | None:
"""A module's tree, each function or method in it by name, and its lines; None where it isn't valid Python."""
try:
tree = ast.parse(text)
except SyntaxError:
return None
functions = {node.name: node for node in ast.walk(tree) if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef))}
return Parsed(tree, functions, tuple(text.splitlines()))
def defined(tree: ast.Module, key: str) -> ast.AsyncFunctionDef | ast.FunctionDef | None:
"""The function or method mutmut's key names, from a module's top or a class there."""
if key.startswith("x_"):
scope, name = tree.body, key.removeprefix("x_")
elif len(parts := key.split("ǁ")) == 3:
_, owner, name = parts
classes = [node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == owner]
scope = classes[0].body if classes else []
else:
return None
return next((node for node in scope if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)) and node.name == name), None)
def as_named(lines: Sequence[str], function: ast.AsyncFunctionDef | ast.FunctionDef, name: str) -> list[str]:
"""A function's lines from its def line on, decorators left out, with name in place of the function's own name on the def line."""
spanned = lines[function.lineno - 1:function.end_lineno]
return [spanned[0].replace(function.name, name), *spanned[1:]]
+54
View File
@@ -0,0 +1,54 @@
"""The setup.cfg that has mutmut mutate a branch's changed files, and the tests left out because they fail before any mutant."""
import configparser
import io
import re
from failure import Failure
SUMMARY = re.compile(r"^=+ short test summary info =+$", re.MULTILINE)
# A line of pytest's short summary for a test that failed or errored; the test's message, where it fits, follows " - ". A failed subtest's line
# names its test after a description in [] or (), which may hold spaces, and pytest reports no line for the test itself.
REPORTED = re.compile(r"^(?:(?:ERROR|FAILED) (\S.*?)|SUBFAILED.*?[\])] (\S+::\S+))(?: - .*)?$", re.MULTILINE)
class CaseKept(configparser.ConfigParser):
"""Keeps each key as written, since the project's other sections are copied over unchanged."""
def optionxform(self, optionstr: str) -> str:
return optionstr
def mutmut_config(existing: str, sources: list[str], copied: list[str], left: list[str]) -> str | Failure:
"""The setup.cfg that has mutmut mutate the sources, copy every entry of the folder, which the sources' tests import, and pass pytest the options that leave tests out.
copied names each file and folder at the folder's top. Not ".": mutmut makes mutants/ before it copies, so "." would copy mutants/ into itself and
pytest would collect the tests twice. existing is the project's own setup.cfg, empty where it has none. Its settings stay, though its comments go, and its [mutmut] pytest_add_cli_args come before the options that leave tests out."""
config = CaseKept(interpolation=None)
try:
config.read_string(existing)
except configparser.Error as failure:
return Failure(f"could not read setup.cfg: {failure}")
if not config.has_section("mutmut"):
config.add_section("mutmut")
section = config["mutmut"]
section["source_paths"] = listed(sources)
section["also_copy"] = listed(copied)
if left:
section["pytest_add_cli_args"] = "\n".join(filter(None, [section.get("pytest_add_cli_args", ""), listed(left)]))
written = io.StringIO()
config.write(written)
return written.getvalue()
def listed(items: list[str]) -> str:
"""Items as a [mutmut] list, one per line, each % doubled: mutmut 3 reads setup.cfg with configparser's default interpolation."""
return "\n".join(item.replace("%", "%%") for item in items)
def left_out(output: str) -> list[str]:
"""The pytest options that leave out each test a failed run's short summary reports: --deselect for a test, --ignore for a file that failed to collect."""
summary = SUMMARY.split(output)
if len(summary) < 2:
return []
nodeids = dict.fromkeys(test or subtests_test for test, subtests_test in REPORTED.findall(summary[-1]))
return [f"--deselect={nodeid}" if "::" in nodeid else f"--ignore={nodeid}" for nodeid in nodeids]
+188
View File
@@ -0,0 +1,188 @@
"""Mutate the changed lines of a branch's Python files with mutmut 3, in a scratch copy of the folder each file's tests run from.
mutmut reads its settings from the folder it runs in, writes beside them, and names each module by its path from there. So each file is
mutated from the nearest folder above it, up to the checkout's top, that holds a setup.cfg or a pyproject.toml: the folder its tests
import it from."""
import dataclasses
import os
import pathlib
import posixpath
import shutil
import tomllib
from mutate_changes.changed_lines import by_folder, label
from mutate_changes.tool_process import failed, Ran, remove, run_tool, scratch_folder
from failure import Failure
from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses
from git_cli.git_repo import git
from mutate_changes.mutmut_setup import left_out, mutmut_config
CAUGHT = frozenset({"caught by type check", "killed"})
CONFIGS = ("pyproject.toml", "setup.cfg")
# Where a test fails before any mutant, a run with these lists every such test, not only the first, so that the next run can leave
# them all out. Each mutant's run would take them too, and run every test where the first that fails is enough.
LIST_FAILURES = ["--maxfail=0", "--continue-on-collection-errors"]
# What mutmut 3.8 prints where no mutant matches the patterns, where no test reaches a mutated function, and where a test fails unmutated.
NO_MUTANT = "Filtered for specific mutants, but nothing matches"
NO_TEST = "Stopping early, because we could not find any test case for any mutant"
STATS_FAILED = "failed to collect stats. runner returned"
@dataclasses.dataclass(frozen=True)
class Folder:
"""The changed files mutmut mutates from one folder."""
path: str # from the checkout's top; "." for the top itself
files: dict[str, frozenset[int]] # each file by its path from the folder, with its changed lines
sources: dict[str, str]
keys: dict[str, list[str]] # mutmut's key of each function or method a changed line falls in
setup: str # the folder's setup.cfg, empty where it has none
@property
def label(self) -> str:
return label(self.path)
def run_mutmut(top: str, changed: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure:
"""For each folder mutmut runs in, a line on what it mutated and left out, then a line per mutant on a changed line that its tests don't kill.
changed maps each file, by its path from top, to its changed lines."""
report: list[str] = []
for path, files in sorted(by_folder(top, changed, CONFIGS).items()):
lines = mutate_folder(top, path, files, prefix, jobs)
if isinstance(lines, Failure):
return lines
report.extend(lines)
return report
def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure:
root = os.path.join(top, path)
folder = read_folder(root, path, files)
if isinstance(folder, Failure):
return folder
globs = [glob for file in sorted(files) for glob in mutant_globs(file, folder.keys[file])]
if not globs:
return [f"mutmut in {folder.label}: no changed line falls in a function or method, the only code mutmut mutates."]
listed = git("ls-files", "-z", "--cached", "--others", "--exclude-standard", cwd=root)
if isinstance(listed, Failure):
return listed
scratch = scratch_folder(top)
if isinstance(scratch, Failure):
return scratch
try:
copy = os.path.join(scratch, "copy")
copied = copy_files(root, listed.split("\0"), copy)
return mutate_copy(copy, copied, folder, ["mutmut", "run", "--max-children", str(jobs), *globs], prefix)
except OSError as failure:
return Failure(f"could not set mutmut up in {scratch}, a copy of {root}: {failure}")
finally:
remove(scratch)
def read_folder(root: str, path: str, files: dict[str, frozenset[int]]) -> Folder | Failure:
setup = project_setup(root)
if isinstance(setup, Failure):
return setup
sources, keys = {}, {}
for file, lines in files.items():
try:
sources[file] = pathlib.Path(root, file).read_text(encoding="utf-8")
keys[file] = function_keys(sources[file], lines)
except (OSError, SyntaxError, UnicodeDecodeError) as failure:
return Failure(f"could not read {os.path.join(root, file)}: {failure}")
return Folder(path, files, sources, keys, setup)
def project_setup(root: str) -> str | Failure:
"""The folder's setup.cfg, empty where it has none. A Failure where its pyproject.toml sets mutmut up, since mutmut then reads no setup.cfg."""
try:
pyproject = pathlib.Path(root, "pyproject.toml")
tool = tomllib.loads(pyproject.read_text(encoding="utf-8")).get("tool") if pyproject.is_file() else None
if isinstance(tool, dict) and "mutmut" in tool:
return Failure(f"{pyproject} sets mutmut up under [tool.mutmut]; move that to setup.cfg's [mutmut], since mutate-changes sets mutmut up only there")
setup = pathlib.Path(root, "setup.cfg")
return setup.read_text(encoding="utf-8") if setup.is_file() else ""
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as failure:
return Failure(f"could not read the mutmut settings in {root}: {failure}")
def copy_files(root: str, paths: list[str], copy: str) -> list[str]:
"""Copy each file git lists in root, tracked or untracked but not ignored, into copy, keeping symlinks as symlinks, and return the names of the files and folders at copy's top.
Leaves out mutmut's own mutants/."""
copied = set()
for path in paths:
source, target = os.path.join(root, path), os.path.join(copy, path)
gone_or_submodule = not os.path.lexists(source) or os.path.isdir(source) and not os.path.islink(source)
if not path or path.split("/")[0] == "mutants" or gone_or_submodule:
continue
os.makedirs(os.path.dirname(target), exist_ok=True)
shutil.copy2(source, target, follow_symlinks=False)
copied.add(path.split("/")[0])
return sorted(copied)
def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], prefix: str | None) -> list[str] | Failure:
ran = run_until_stats_pass(copy, copied, folder, argv, prefix)
if isinstance(ran, Failure):
return ran
output, left = ran
if not os.path.isdir(os.path.join(copy, "mutants")):
return Failure(f"mutmut in {folder.label} wrote no mutants/ in {copy}; --prefix must run it in $PWD")
if NO_MUTANT in output:
return [f"mutmut in {folder.label}: none of the functions the changed lines fall in has a mutant."]
results = run_tool(["mutmut", "results", "--all", "true"], copy, prefix)
if isinstance(results, Failure) or results.code:
return results if isinstance(results, Failure) else failed(f"mutmut results in {folder.label}", results)
shown, counted = not_killed(folder, statuses(results.output), copy)
unreached = " No test reaches them." if NO_TEST in output else ""
left_files = sorted({option.partition("=")[2].partition("::")[0] for option in left})
left_note = f" Left out the tests that fail without a mutant, in {', '.join(left_files)}." if left else ""
return [f"mutmut in {folder.label}: {counted} mutants on changed lines, {len(shown)} not killed.{unreached}{left_note}", *shown]
def run_until_stats_pass(copy: str, copied: list[str], folder: Folder, argv: list[str], prefix: str | None) -> tuple[str, list[str]] | Failure:
"""mutmut's output, and the options that left out each test that fails before any mutant: mutmut runs no mutant while one fails."""
ran = configured_run(copy, copied, folder, [], argv, prefix)
left: list[str] = []
if isinstance(ran, Ran) and STATS_FAILED in ran.output:
ran = configured_run(copy, copied, folder, LIST_FAILURES, argv, prefix)
if isinstance(ran, Ran) and STATS_FAILED in ran.output and (left := left_out(ran.output)):
ran = configured_run(copy, copied, folder, left, argv, prefix)
if isinstance(ran, Failure):
return ran
if ran.code and NO_MUTANT not in ran.output and NO_TEST not in ran.output:
return failed(f"mutmut run in {folder.label}", ran)
return ran.output, left
def configured_run(copy: str, copied: list[str], folder: Folder, options: list[str], argv: list[str], prefix: str | None) -> Ran | Failure:
config = mutmut_config(folder.setup, sorted(folder.files), copied, options)
if isinstance(config, Failure):
return Failure(f"{folder.label}: {config.reason}")
pathlib.Path(copy, "setup.cfg").write_text(config, encoding="utf-8")
return run_tool(argv, copy, prefix)
def not_killed(folder: Folder, found: dict[str, str], copy: str) -> tuple[list[str], int]:
"""A line per mutant on a changed line that its tests don't kill, in order of path and line, and how many mutants the changed lines hold."""
copies: dict[str, str] = {}
shown: list[tuple[str, int, str]] = []
counted = 0
# Sorted by name, a file's mutants come one after another, so mutated_line parses its copy once.
for name, status in sorted(found.items()):
hit = named(name, list(folder.files))
if hit is None or hit[1] not in folder.keys[hit[0]]:
continue
file, key, number = hit
if file not in copies:
mutated = pathlib.Path(copy, "mutants", file)
copies[file] = mutated.read_text(encoding="utf-8", errors="replace") if mutated.is_file() else ""
where = mutated_line(folder.sources[file], copies[file], key, number)
if where and where[0] not in folder.files[file]:
continue
counted += 1
if status not in CAUGHT:
line, text = where or (0, f"{name}, on a line mutate-changes cannot find")
shown.append((posixpath.normpath(posixpath.join(folder.path, file)), line, f"{status}: {text}"))
return [f"{file}:{line}: {text}" if line else f"{file}: {text}" for file, line, text in sorted(shown)], counted
+279
View File
@@ -0,0 +1,279 @@
import configparser
import os
import pathlib
import signal
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from mutate_changes.changed_lines import added_lines, by_folder, not_mutated, runs, tool_for
from mutate_changes.mutmut_tool import copy_files
from failure import Failure
from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses
from test_env import isolated_env
from mutate_changes.mutmut_setup import left_out, mutmut_config
from mutate_changes import main
from mutate_changes.tool_process import run_tool, scratch_folder
SOURCE = "def double(n):\n\treturn n * 2\n\n\nclass Pt:\n\tdef moved(self, by=1):\n\t\treturn self.x + by\n"
# The shape of the file mutmut 3 writes under mutants/: the original of each function and its mutants, with the original's lines.
COPY = """from inspect import signature as _mutmut_signature
def x_double__mutmut_orig(n):
return n * 2
def x_double__mutmut_1(n):
return n / 2
class Pt:
def xǁPtǁmoved__mutmut_orig(self, by=1):
return self.x + by
def xǁPtǁmoved__mutmut_1(self, by=2):
return self.x + by
def xǁPtǁmoved__mutmut_2(self, by=1):
return self.x - by
"""
def read_as_mutmut(text: str, key: str) -> list[str]:
"""A [mutmut] list as mutmut 3 reads it from setup.cfg: with configparser's default interpolation, one item per line."""
config = configparser.ConfigParser()
config.read_string(text)
return [item for item in config.get("mutmut", key).split("\n") if item]
class ChangedLines(unittest.TestCase):
def test_added_lines_are_the_new_side_of_each_hunk_and_a_deleting_hunk_adds_none(self):
diff = "diff --git a/x.py b/x.py\n--- a/x.py\n+++ b/x.py\n@@ -3,0 +4,2 @@ def f():\n+a\n+b\n@@ -10 +12 @@\n-c\n+d\n@@ -20,3 +23,0 @@\n-e\n-f\n-g\n"
self.assertEqual(added_lines(diff), {4, 5, 12})
def test_runs_join_consecutive_lines(self):
self.assertEqual(runs({10, 1, 2, 3, 7, 9}), [(1, 3), (7, 7), (9, 10)])
def test_the_tool_follows_the_extension_and_test_files_get_none(self):
expected = {
"bin/x/main.py": "mutmut",
"src/lib.rs": "cargo-mutants",
"src/Order.php": "infection",
"web/app.tsx": "stryker",
"web/app.mjs": "stryker",
"bin/x/test_main.py": None,
"bin/x/main_test.py": None,
"pkg/conftest.py": None,
"tests/helpers.py": None,
"web/app.test.ts": None,
"web/app.spec.js": None,
"web/__tests__/a.js": None,
"README.md": None,
}
for path, tool in expected.items():
with self.subTest(path):
self.assertEqual(tool_for(path), tool)
def test_each_file_goes_to_the_nearest_folder_above_it_that_holds_one_of_the_configs(self):
with tempfile.TemporaryDirectory() as top:
for config in ("pkg/setup.cfg", "pkg/inner/lib/pyproject.toml", "web/package.json"):
pathlib.Path(top, config).parent.mkdir(parents=True, exist_ok=True)
pathlib.Path(top, config).write_text("")
lines = frozenset({1})
grouped = by_folder(top, {"pkg/inner/deep.py": lines, "pkg/inner/lib/x.py": lines, "top.py": lines}, ("pyproject.toml", "setup.cfg"))
self.assertEqual(grouped, {"pkg": {"inner/deep.py": lines}, "pkg/inner/lib": {"x.py": lines}, ".": {"top.py": lines}})
self.assertEqual(by_folder(top, {"web/src/a.ts": lines, "pkg/b.ts": lines}, ("package.json",)), {"web": {"src/a.ts": lines}, ".": {"pkg/b.ts": lines}})
def test_not_mutated_names_the_files_no_tool_covers_then_the_test_files(self):
self.assertEqual(not_mutated(["README.md", "a.py", "b.go", "test_a.py", "web/a.test.ts"]), ["Not mutated, as no tool covers their language: README.md, b.go.", "Not mutated, as test files: test_a.py, web/a.test.ts."])
self.assertEqual((not_mutated(["a.py", "test_a.py"]), not_mutated(["a.py", "b.go"]), not_mutated([])), (["Not mutated, as test files: test_a.py."], ["Not mutated, as no tool covers their language: b.go."], []))
class MutmutSetup(unittest.TestCase):
def test_the_config_mutates_the_sources_and_copies_each_entry_of_the_folder(self):
for existing in ("", "[mutmut]\nsource_paths = old.py\nalso_copy = old\n"):
with self.subTest(existing):
text = mutmut_config(existing, ["x/a.py", "b.py"], ["b.py", "x"], [])
self.assertEqual(read_as_mutmut(text, "source_paths"), ["x/a.py", "b.py"])
self.assertEqual(read_as_mutmut(text, "also_copy"), ["b.py", "x"])
def test_the_config_keeps_the_projects_settings_and_appends_the_tests_left_out(self):
existing = "[tool:pytest]\naddopts = -q\n\n[mutmut]\npytest_add_cli_args = -k\n not Slow\ndebug = true\n"
text = mutmut_config(existing, ["a.py"], ["a.py", "t"], ["--deselect=t/test_a.py::T::test_b[50%]"])
self.assertEqual(read_as_mutmut(text, "pytest_add_cli_args"), ["-k", "not Slow", "--deselect=t/test_a.py::T::test_b[50%]"])
self.assertEqual(read_as_mutmut(text, "debug"), ["true"])
config = configparser.ConfigParser()
config.read_string(text)
self.assertEqual(config.get("tool:pytest", "addopts"), "-q")
def test_the_tests_left_out_are_the_only_pytest_options_where_the_project_sets_none(self):
self.assertEqual(read_as_mutmut(mutmut_config("", ["a.py"], ["a.py"], ["--ignore=t.py"]), "pytest_add_cli_args"), ["--ignore=t.py"])
def test_a_setup_cfg_that_cannot_be_read_fails(self):
failed = mutmut_config("[mutmut]\na = 1\na = 2\n", ["a.py"], ["a.py"], [])
assert isinstance(failed, Failure)
self.assertIn("could not read setup.cfg", failed.reason)
def test_left_out_names_each_test_the_summary_reports_failing(self):
output = textwrap.dedent("""\
==== short test summary info ====
FAILED fake.py::t - these two lines are a test's own output, above the summary
ERROR root:x.py:3 a log line
=========================== short test summary info ============================
FAILED repo_checks/test_repo_checks.py::Repo::test_a - AssertionError: x - y
ERROR larv_review/test_larv_review.py - FileNotFoundError: SKILL.md
FAILED a/test_b.py::T::test_c
SUBFAILED[['--jobs', '0']] a/test_d.py::T::test_e - AssertionError: 1 != 0
SUBFAILED[['--jobs']] a/test_d.py::T::test_e - AssertionError: 1 != 0
SUBFAILED[m] (path='/dev/zero', kind='a b') a/test_d.py::T::test_f
2 failed, 1 error in 3.10s
failed to collect stats. runner returned 1
""")
self.assertEqual(left_out(output), ["--deselect=repo_checks/test_repo_checks.py::Repo::test_a", "--ignore=larv_review/test_larv_review.py", "--deselect=a/test_b.py::T::test_c", "--deselect=a/test_d.py::T::test_e", "--deselect=a/test_d.py::T::test_f"])
def test_left_out_is_empty_without_a_summary(self):
self.assertEqual(left_out("failed to collect stats. runner returned 1\n"), [])
class MutmutMutants(unittest.TestCase):
def test_function_keys_name_the_functions_and_methods_a_changed_line_falls_in(self):
source = SOURCE + "\n\n@cached\ndef later():\n\treturn 1\n"
self.assertEqual(function_keys(source, frozenset({2, 7})), ["x_double", "xǁPtǁmoved"])
self.assertEqual(function_keys(source, frozenset({10})), ["x_later"])
self.assertEqual(function_keys(source, frozenset({3, 5})), [])
def test_mutant_globs_follow_mutmuts_module_names(self):
self.assertEqual(mutant_globs("pkg/__init__.py", ["x_f"]), ["pkg.x_f*"])
self.assertEqual(mutant_globs("src/pkg/mod.py", ["x_f", "xǁPtǁmoved"]), ["pkg.mod.x_f*", "pkg.mod.xǁPtǁmoved*"])
def test_named_finds_a_mutants_file_function_and_number(self):
paths = ["pkg/__init__.py", "src/pkg/mod.py"]
self.assertEqual(named("pkg.x_f__mutmut_3", paths), ("pkg/__init__.py", "x_f", 3))
self.assertEqual(named("pkg.mod.xǁPtǁmoved__mutmut_12", paths), ("src/pkg/mod.py", "xǁPtǁmoved", 12))
self.assertIsNone(named("other.x_f__mutmut_1", paths))
def test_statuses_read_mutmut_results(self):
results = " pkg.x_f__mutmut_1: survived\n pkg.x_f__mutmut_2: no tests\n\n pkg.x_f__mutmut_3: killed\n pkg.x_f__mutmut_4:\n mutants: 4\n"
self.assertEqual(statuses(results), {"pkg.x_f__mutmut_1": "survived", "pkg.x_f__mutmut_2": "no tests", "pkg.x_f__mutmut_3": "killed"})
def test_a_mutated_line_is_the_first_line_the_mutant_changes_at_its_place_in_the_source(self):
self.assertEqual(mutated_line(SOURCE, COPY, "x_double", 1), (2, "return n / 2"))
self.assertEqual(mutated_line(SOURCE, COPY, "xǁPtǁmoved", 1), (6, "def moved(self, by=2):"))
self.assertEqual(mutated_line(SOURCE, COPY, "xǁPtǁmoved", 2), (7, "return self.x - by"))
def test_a_mutant_the_copy_lacks_or_a_copy_unlike_the_source_has_no_line(self):
self.assertIsNone(mutated_line(SOURCE, COPY, "x_double", 9))
self.assertIsNone(mutated_line(SOURCE.replace("n * 2", "n * 2 + 1"), COPY, "x_double", 1))
self.assertIsNone(mutated_line(SOURCE, COPY + "def x_double__mutmut_2(n):\n\treturn n * 2\n", "x_double", 2))
def test_a_key_the_source_does_not_define_has_no_line(self):
for key in ("x_double", "x_nope", "xǁNopeǁmoved", "xǁPtǁnope"):
with self.subTest(key):
self.assertIsNone(mutated_line("import os\n\n\nclass Pt:\n\tpass\n", COPY, key, 1))
def test_a_mutated_line_is_found_in_the_function_or_method_its_key_names_among_others(self):
others = "import os\n\n\ndef triple(n):\n\treturn n * 3\n\n\nclass Q:\n\tdef moved(self, by=1):\n\t\treturn 0\n\n\n"
self.assertEqual(mutated_line(others + SOURCE, COPY, "x_double", 1), (14, "return n / 2"))
self.assertEqual(mutated_line(others + SOURCE, COPY, "xǁPtǁmoved", 2), (19, "return self.x - by"))
self.assertIsNone(mutated_line(SOURCE, "def broken(:\n", "x_double", 1))
class MutmutTool(unittest.TestCase):
def test_copy_files_copies_what_is_listed_but_mutmuts_own_folder_and_names_the_entries_at_the_top(self):
with tempfile.TemporaryDirectory() as temp:
root, copy = pathlib.Path(temp, "root"), pathlib.Path(temp, "copy")
for path in ("a.py", "d/b.py", "mutants/x.py", "sub/c.py"):
(root / path).parent.mkdir(parents=True, exist_ok=True)
(root / path).write_text("")
(root / "link").symlink_to("a.py")
(root / "dirlink").symlink_to("d")
# The list names a submodule as one path, a folder, and ends with an empty path.
listed = ["", "mutants/x.py", "gone.py", "sub", "a.py", "d/b.py", "dirlink", "link"]
self.assertEqual(copy_files(str(root), listed, str(copy)), ["a.py", "d", "dirlink", "link"])
walked = sorted(os.path.relpath(os.path.join(folder, name), copy) for folder, folders, files in os.walk(copy) for name in folders + files)
self.assertEqual(walked, ["a.py", "d", "d/b.py", "dirlink", "link"])
self.assertEqual((os.readlink(copy / "link"), os.readlink(copy / "dirlink")), ("a.py", "d"))
class ToolProcess(unittest.TestCase):
def test_git_lists_nothing_in_a_scratch_folder(self):
with tempfile.TemporaryDirectory() as top:
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": "/dev/null"}
subprocess.run(["git", "init", "-q", top], check=True, env=env)
scratch = scratch_folder(top)
pathlib.Path(scratch, "copy.py").write_text("")
status = subprocess.run(["git", "status", "--porcelain", "--untracked-files=all"], capture_output=True, check=True, cwd=top, encoding="utf-8", env=env).stdout
self.assertEqual((os.path.dirname(scratch), os.path.basename(scratch)[:16], status), (top, ".mutate-changes-", ""))
def test_a_scratch_folder_it_cannot_make_is_a_failure(self):
self.assertRegex(scratch_folder("/nonexistent/top").reason, "^could not make a scratch folder in /nonexistent/top: ")
def test_an_interrupted_run_ends_at_once_with_each_process_the_tool_started(self):
with tempfile.TemporaryDirectory() as folder:
# sh starts the sleep in the background, where it ignores SIGINT, so only the kill after the tool ends stops it.
self.assertLess(self.interrupted(folder, "sleep 60 & echo $! > started; wait;"), 30)
self.assert_ends(int(pathlib.Path(folder, "started").read_text()))
def test_an_interrupt_reaches_the_tool_before_the_run_kills_it(self):
# A container's CLI, such as docker compose, stops its container on the SIGINT it is passed, and can't once killed.
with tempfile.TemporaryDirectory() as folder:
self.interrupted(folder, "trap 'echo > stopped; exit 130' INT; echo $$ > started; while :; do sleep 0.1; done;")
self.assertTrue(pathlib.Path(folder, "stopped").is_file())
def test_an_interrupted_tool_that_ignores_sigint_is_killed_after_the_grace_period(self):
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch("mutate_changes.tool_process.GRACE_SECONDS", 0.5):
self.assertLess(self.interrupted(folder, "trap '' INT; echo $$ > started; sleep 60;"), 30)
self.assert_ends(int(pathlib.Path(folder, "started").read_text()))
def test_an_interrupt_ends_the_run_where_the_tool_s_processes_end_first(self):
killpg = os.killpg
def then_gone(group: int, number: int) -> None:
killpg(group, number)
raise ProcessLookupError
with unittest.mock.patch("os.killpg", then_gone), tempfile.TemporaryDirectory() as folder:
self.interrupted(folder, "sleep 60 & echo $! > started; wait;")
def interrupted(self, folder: str, script: str) -> float:
"""Run script as the prefix of a tool in folder, interrupt run_tool once script writes folder/started, and return how long run_tool took."""
started = pathlib.Path(folder, "started")
def interrupt():
while not started.is_file() or not started.read_text().strip():
time.sleep(0.05)
os.kill(os.getpid(), signal.SIGINT)
threading.Thread(target=interrupt, daemon=True).start()
began = time.monotonic()
with self.assertRaises(KeyboardInterrupt):
run_tool(["true"], folder, script)
return time.monotonic() - began
def assert_ends(self, pid: int) -> None:
for _ in range(200):
if ended(pid):
return
time.sleep(0.05)
self.fail(f"process {pid}, which the tool started, still runs")
def ended(pid: int) -> bool:
"""Whether a process has ended: gone, or a zombie its parent has yet to reap."""
try:
return pathlib.Path(f"/proc/{pid}/stat").read_text().split(") ")[1][0] == "Z"
except (FileNotFoundError, ProcessLookupError):
return True
class Took(unittest.TestCase):
def test_took_rounds_to_the_second_and_counts_minutes_from_one(self):
self.assertEqual([main.took(seconds) for seconds in (59.4, 59.6, 61, 3725.4)], ["59 s", "1 min 0 s", "1 min 1 s", "62 min 5 s"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,438 @@
"""mutate-changes run on a branch, against fake mutation tools that log how they were called."""
import contextlib
import io
import os
import pathlib
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from mutate_changes.test_mutate_changes import ended
from test_env import isolated_env
from mutate_changes import main
from mutate_changes.in_diff_tools import run_cargo_mutants
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes"
SETUP = "[mutmut]\ndo_not_mutate = *_old.py\n"
PASSED = ["mutmut in pkg: 2 mutants on changed lines, 1 not killed.", "pkg/calc.py:6: survived: return n / 3"]
NOT_MUTATED = ["Not mutated, as no tool covers their language: README.md.", "Not mutated, as test files: pkg/test_calc.py."]
# Stands in for mutmut, run through --prefix as `python3 <this> <log> <mode> mutmut ...` in the scratch copy. It logs each call with
# the folder it runs in and the setup.cfg it finds there, then writes a mutants/ copy and prints results, both shaped like mutmut 3's.
# In mode locks, it also leaves a folder in the copy that nobody may delete from.
FAKE_MUTMUT = r"""import os, pathlib, sys
log, mode, args = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3:]
config = pathlib.Path("setup.cfg").read_text()
with log.open("a") as written:
written.write(f"{os.getcwd()}\n{' '.join(args)}\n{config}---\n")
if args[:2] == ["mutmut", "results"]:
if mode == "results-fail" or args[2:] != ["--all", "true"]:
sys.exit("mutmut results broke")
double, triple_1, triple_2 = ("no tests",) * 3 if mode == "no-test" else ("survived", "survived", "killed")
# The branch doesn't change aside.py, so mutate-changes skips its mutant, which comes first in name order.
print(f" aside.x_f__mutmut_1: survived\n calc.x_double__mutmut_1: {double}\n calc.x_triple__mutmut_1: {triple_1}\n calc.x_triple__mutmut_2: {triple_2}")
elif mode == "fails-once" and not ("--deselect=test_calc.py::test_slow[n=1]" in config and "--ignore=test_io.py" in config):
print("==== short test summary info ====\nFAILED test_calc.py::test_slow[n=1] - boom\nERROR test_io.py - FileNotFoundError\nfailed to collect stats. runner returned 1")
sys.exit(1)
else:
if mode != "elsewhere":
pathlib.Path("mutants").mkdir(exist_ok=True)
if mode not in ("elsewhere", "no-copy"):
functions = ["x_double__mutmut_orig(n): # doubles\n\treturn n * 2", "x_double__mutmut_1(n): # doubles\n\treturn n / 2", "x_triple__mutmut_orig(n):\n\treturn n * 3", "x_triple__mutmut_1(n):\n\treturn n / 3", "x_triple__mutmut_2(n):\n\treturn n * 4"]
pathlib.Path("mutants/calc.py").write_bytes(b"# \xff is not UTF-8\n" + "".join(f"def {function}\n" for function in functions).encode())
if mode == "locks":
pathlib.Path("locked/inner").mkdir(parents=True)
pathlib.Path("locked").chmod(0o555)
if mode == "no-test":
print("Stopping early, because we could not find any test case for any mutant. It seems that the selected tests do not cover any code that we mutated.")
sys.exit(1)
if mode == "setup-fault":
print("Stopping early, because tests recorded trampoline hits but none match any mutant key. This usually means imports bypass the mutants.")
sys.exit(1)
"""
# cargo-mutants, Infection and Stryker, which log the folder they run in and how they were called, and exit with the code the test
# gives. cargo-mutants also logs the diff it is given and writes its outcome files, all but unviable.txt, as a run without an
# unviable mutant does; with CAUGHT_UNREADABLE set, nobody may read caught.txt, and with OUTPUT_LOCKED, nobody may delete from mutants.out.
FAKE_TOOLS = r"""import os, pathlib, sys
log, code, args = pathlib.Path(sys.argv[1]), int(sys.argv[2]), sys.argv[3:]
with log.open("a") as written:
written.write(f"{os.getcwd()}\n{' '.join(args)}\n")
if args[0] == "cargo":
written.write(pathlib.Path(args[args.index("--in-diff") + 1]).read_text())
outcomes = pathlib.Path(args[args.index("--output") + 1], "mutants.out")
outcomes.mkdir()
(outcomes / "caught.txt").write_bytes(b"src/lib.rs:2:7: replace + with - in add, \xff not being UTF-8\n")
(outcomes / "missed.txt").write_text("src/lib.rs:2:5: replace add(a: i32, b: i32) -> i32 with 0\n")
(outcomes / "timeout.txt").write_text("src/lib.rs:2:7: replace + with * in add\n")
if os.environ.get("CAUGHT_UNREADABLE"):
(outcomes / "caught.txt").chmod(0)
if os.environ.get("OUTPUT_LOCKED"):
outcomes.chmod(0o555)
print(f"{args[0]} reports")
sys.exit(code)
"""
@contextlib.contextmanager
def stdin_holding(text: str):
"""This process's stdin, the one a child inherits, as a pipe holding text."""
read, write = os.pipe()
os.write(write, text.encode())
os.close(write)
saved = os.dup(0)
os.dup2(read, 0)
os.close(read)
try:
yield
finally:
os.dup2(saved, 0)
os.close(saved)
class MutateChangesRuns(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.temp = pathlib.Path(temp.name)
self.checkout = self.temp / "proj"
(self.checkout / "pkg").mkdir(parents=True)
(self.checkout / "pkg" / "setup.cfg").write_text(SETUP)
(self.checkout / "pkg" / "calc.py").write_text("def double(n):\n\treturn n * 2\n")
(self.checkout / "pkg" / "test_calc.py").write_text("")
self.git("init", "-q", "-b", "main")
self.commit()
self.git("checkout", "-q", "-b", "work")
# git lists the README first, and mutate-changes mutates no Markdown.
(self.checkout / "README.md").write_text("Doubles and triples.\n")
(self.checkout / "pkg" / "calc.py").write_text("def double(n): # doubles\n\treturn n * 2\n\n\ndef triple(n):\n\treturn n * 3\n")
(self.checkout / "pkg" / "test_calc.py").write_text("# changed, but a test file is not mutated\n")
self.commit()
# Settings a user may have that change what git diff prints, and a file git lists as untracked and one it ignores.
for name, value in (("color.diff", "always"), ("diff.mnemonicPrefix", "true"), ("diff.relative", "true"), ("diff.external", "true"), ("diff.blank.textconv", "true")):
self.git("config", name, value)
(self.checkout / ".git" / "info").mkdir(exist_ok=True)
(self.checkout / ".git" / "info" / "attributes").write_text("* diff=blank\n")
(self.checkout / ".git" / "info" / "exclude").write_text("*.log\n")
(self.checkout / "pkg" / "fixture.txt").write_text("")
(self.checkout / "pkg" / "run.log").write_text("")
(self.temp / "fake_mutmut.py").write_text(FAKE_MUTMUT)
(self.temp / "fake_tools.py").write_text(FAKE_TOOLS)
self.log = self.temp / "calls.log"
def git(self, *args):
return subprocess.run(["git", *args], check=True, capture_output=True, cwd=self.checkout, encoding="utf-8", env={**isolated_env(), "GIT_CONFIG_GLOBAL": "/dev/null"}).stdout
def commit(self):
self.git("add", ".")
self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x")
def run_tool(self, *args, cwd=None, env=None):
"""Run mutate-changes in this process, from cwd, else the checkout: mutmut counts only the code a test reaches in its own process."""
before = os.getcwd()
os.chdir(cwd or self.checkout)
try:
with unittest.mock.patch.dict(os.environ, {**isolated_env(), **(env or {})}, clear=True), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:
code = main.main(list(args))
finally:
os.chdir(before)
return subprocess.CompletedProcess(args, code, out.getvalue(), err.getvalue())
def faked(self, mode):
return ["--prefix", f"python3 {self.temp / 'fake_mutmut.py'} {self.log} {mode}"]
def change_rust_php_and_typescript(self):
"""Commit a Rust, a PHP and a TypeScript file, then change them: Rust's line 2 in the index, PHP's line 2 with a byte that is
not UTF-8, and TypeScript's lines 1 and 4. Also change line 1 of a TypeScript file in web/. The top and web/ each hold a package.json."""
(self.checkout / "src").mkdir()
(self.checkout / "web" / "src").mkdir(parents=True)
(self.checkout / "package.json").write_text("{}\n")
(self.checkout / "web" / "package.json").write_text("{}\n")
(self.checkout / "web" / "src" / "app.ts").write_text("export const two = 2;\n")
(self.checkout / "src" / "lib.rs").write_text("pub fn add(a: i32, b: i32) -> i32 {\n\ta + b\n}\n")
(self.checkout / "src" / "Calc.php").write_text("<?php\nfunction add($a, $b) { return $a + $b; }\n")
(self.checkout / "src" / "calc.ts").write_text("export function add(a: number, b: number) {\n\treturn a + b;\n}\nexport const one = 1;\n")
self.commit()
(self.checkout / "src" / "lib.rs").write_text("pub fn add(a: i32, b: i32) -> i32 {\n\tb + a\n}\n")
self.git("add", "src/lib.rs")
(self.checkout / "src" / "Calc.php").write_bytes(b"<?php\nfunction add($a, $b) { return $b + $a; } // caf\xe9\n")
(self.checkout / "src" / "calc.ts").write_text("export function add(b: number, a: number) {\n\treturn a + b;\n}\nexport const one = 2;\n")
(self.checkout / "web" / "src" / "app.ts").write_text("export const two = 3;\n")
def path_with_git(self):
"""A PATH that finds git and no mutation tool."""
tools = self.temp / "tools"
tools.mkdir()
(tools / "git").symlink_to(shutil.which("git"))
return tools
def test_prints_each_mutant_on_a_changed_line_that_its_tests_do_not_kill(self):
ran = self.run_tool(*self.faked("passes"), "--jobs", "2")
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:-1], ran.stderr), (0, [*PASSED, *NOT_MUTATED], ""))
self.assertRegex(ran.stdout.splitlines()[-1], r"^mutate-changes took \d+ s\.$")
calls = self.log.read_text()
# mutmut's stats and mutant runs stop at the first test that fails, unless an option tells pytest otherwise.
self.assertNotIn("--maxfail=0", calls)
self.assertRegex(calls, rf"(?m)^{re.escape(str(self.checkout.resolve()))}/\.mutate-changes-\w+/copy$")
self.assertIn("mutmut run --max-children 2 calc.x_double* calc.x_triple*\n", calls)
self.assertIn("do_not_mutate = *_old.py\n", calls)
self.assertIn("source_paths = calc.py\n", calls)
self.assertIn("also_copy = calc.py\n\tfixture.txt\n\tsetup.cfg\n\ttest_calc.py\n", calls)
self.assertEqual((self.checkout / "pkg" / "setup.cfg").read_text(), SETUP)
self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "pkg"])
def test_runs_alike_from_a_folder_in_the_checkout(self):
ran = self.run_tool(*self.faked("passes"), cwd=self.checkout / "pkg")
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:2]), (0, PASSED), ran.stderr)
def test_leaves_out_the_tests_that_fail_before_any_mutant_and_names_them(self):
ran = self.run_tool(*self.faked("fails-once"))
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(ran.stdout.splitlines()[:2], ["mutmut in pkg: 2 mutants on changed lines, 1 not killed. Left out the tests that fail without a mutant, in test_calc.py, test_io.py.", "pkg/calc.py:6: survived: return n / 3"])
runs = self.log.read_text().split("---\n")[:3]
self.assertEqual(["--maxfail=0" in run for run in runs], [False, True, False])
self.assertIn("--deselect=test_calc.py::test_slow[n=1]", runs[2])
def test_says_where_no_test_reaches_the_mutants(self):
ran = self.run_tool(*self.faked("no-test"))
self.assertEqual(ran.stdout.splitlines()[:3], ["mutmut in pkg: 2 mutants on changed lines, 2 not killed. No test reaches them.", "pkg/calc.py:6: no tests: return n * 4", "pkg/calc.py:6: no tests: return n / 3"], ran.stderr)
def test_a_run_that_stops_early_for_another_reason_fails_the_run(self):
ran = self.run_tool(*self.faked("setup-fault"))
self.assertEqual((ran.returncode, ran.stderr.splitlines()[0]), (1, "mutmut run in pkg exited 1:"))
def test_a_prefix_that_runs_mutmut_elsewhere_fails_the_run(self):
ran = self.run_tool(*self.faked("elsewhere"))
self.assertEqual(ran.returncode, 1)
self.assertRegex(ran.stderr, rf"^mutmut in pkg wrote no mutants/ in {re.escape(str(self.checkout.resolve()))}/\.mutate-changes-\w+/copy; --prefix must run it in \$PWD\n$")
def test_names_a_mutant_whose_line_it_cannot_find(self):
ran = self.run_tool(*self.faked("no-copy"))
self.assertEqual(ran.stdout.splitlines()[:3], ["mutmut in pkg: 3 mutants on changed lines, 2 not killed.", "pkg/calc.py: survived: calc.x_double__mutmut_1, on a line mutate-changes cannot find", "pkg/calc.py: survived: calc.x_triple__mutmut_1, on a line mutate-changes cannot find"], ran.stderr)
def test_a_pyproject_toml_that_sets_mutmut_up_fails_the_run(self):
(self.checkout / "pkg" / "setup.cfg").unlink()
(self.checkout / "pkg" / "pyproject.toml").write_text("[tool.mutmut]\nmax_stack_depth = 8\n")
ran = self.run_tool(*self.faked("passes"))
self.assertEqual(ran.returncode, 1)
self.assertIn("[tool.mutmut]", ran.stderr)
(self.checkout / "pkg" / "pyproject.toml").write_text("[tool.pytest.ini_options]\naddopts = \"-q\"\n")
ran = self.run_tool(*self.faked("passes"))
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:2]), (0, PASSED), ran.stderr)
def test_a_changed_file_or_setting_it_cannot_read_fails_the_run(self):
pkg = self.checkout.resolve() / "pkg"
for name, text, reason in (
("calc.py", "def double(n:\n", f"could not read {pkg}/calc.py: "),
("pyproject.toml", "[tool\n", f"could not read the mutmut settings in {pkg}: "),
("setup.cfg", "[mutmut\n", "pkg: could not read setup.cfg: "),
):
with self.subTest(name):
(pkg / name).write_text(text)
ran = self.run_tool(*self.faked("passes"))
self.assertEqual(ran.returncode, 1)
self.assertRegex(ran.stderr, f"^{re.escape(reason)}")
self.git("checkout", "HEAD", "--", "pkg")
(pkg / "pyproject.toml").unlink(missing_ok=True)
def test_a_scratch_folder_it_cannot_make_fails_the_run(self):
top = self.checkout.resolve()
self.addCleanup(top.chmod, 0o755)
failed = f"^could not make a scratch folder in {re.escape(str(top))}: "
top.chmod(0o555)
self.assertRegex(self.run_tool(*self.faked("passes")).stderr, failed)
top.chmod(0o755)
self.change_rust_php_and_typescript()
top.chmod(0o555)
self.assertRegex(self.run_tool("--base", "HEAD").stderr, failed)
def test_a_file_it_cannot_copy_fails_the_run(self):
(self.checkout / "pkg" / "fixture.txt").chmod(0)
ran = self.run_tool(*self.faked("passes"))
top = re.escape(str(self.checkout.resolve()))
self.assertRegex(ran.stderr, rf"^could not set mutmut up in {top}/\.mutate-changes-\w+, a copy of {top}/pkg: ")
self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "pkg"])
def test_a_scratch_folder_it_cannot_remove_is_named_and_the_report_stands(self):
top = re.escape(str(self.checkout.resolve()))
self.addCleanup(lambda: [path.chmod(0o755) for path in self.checkout.glob(".mutate-changes-*/**/*") if path.is_dir()])
ran = self.run_tool(*self.faked("locks"))
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:2]), (0, PASSED))
self.assertRegex(ran.stderr, rf"^could not remove {top}/\.mutate-changes-\w+: .*\n$")
self.change_rust_php_and_typescript()
ran = self.run_tool("--base", "HEAD", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", env={"OUTPUT_LOCKED": "1"})
self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "cargo-mutants: 3 mutants on changed lines, 2 not caught."))
self.assertRegex(ran.stderr, rf"^could not remove {top}/\.mutate-changes-\w+: .*\n$")
def test_a_signal_that_ends_the_run_ends_the_tool_and_removes_the_scratch_copy(self):
started = self.temp / "sleep.pid"
for number in (signal.SIGHUP, signal.SIGTERM):
with self.subTest(number.name):
started.unlink(missing_ok=True)
launched = subprocess.Popen([str(TOOL), "--prefix", f"sleep 60 & echo $! > {started}; wait;"], cwd=self.checkout, env=isolated_env(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
while launched.poll() is None and not (started.is_file() and started.read_text().strip()):
time.sleep(0.05)
launched.send_signal(number)
self.assertEqual(launched.wait(timeout=30), 128 + number)
self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "pkg"])
for _ in range(200):
if ended(int(started.read_text())):
break
time.sleep(0.05)
else:
self.fail("the sleep the tool started still runs")
def test_a_tool_that_fails_fails_the_run_with_the_end_of_its_output(self):
ran = self.run_tool("--prefix", "seq 45; echo broken >&2; printf '\\377'; false")
self.assertEqual((ran.returncode, ran.stderr), (1, "\n".join(["mutmut run in pkg exited 1:", *map(str, range(8, 46)), "broken", "�"]) + "\n"))
def test_mutmut_results_that_fails_fails_the_run(self):
ran = self.run_tool(*self.faked("results-fail"))
self.assertEqual((ran.returncode, ran.stderr), (1, "mutmut results in pkg exited 1:\nmutmut results broke\n"))
def test_a_tool_gets_an_empty_input_in_place_of_the_terminal(self):
# A tool that reads its input, such as a test that asks a question, gets an end of file instead of waiting on the terminal.
with stdin_holding("y\n"):
ran = self.run_tool("--prefix", "cat; false")
self.assertEqual(ran.stderr, "mutmut run in pkg exited 1:\n")
def test_without_a_prefix_each_tool_runs_from_path(self):
tools = self.path_with_git()
ran = self.run_tool(env={"PATH": str(tools)})
self.assertEqual(ran.returncode, 1)
self.assertRegex(ran.stderr, "^mutmut run .* could not start: ")
(tools / "mutmut").write_text(f'#!/bin/sh\nexec {sys.executable} {self.temp / "fake_mutmut.py"} {self.log} passes mutmut "$@"\n')
(tools / "mutmut").chmod(0o755)
ran = self.run_tool(env={"PATH": str(tools)})
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:2]), (0, PASSED), ran.stderr)
def test_a_mutmut_results_that_cannot_start_fails_the_run(self):
tools = self.path_with_git()
(tools / "mutmut").write_text(f'#!/bin/sh\n[ "$1" = run ] && {shutil.which("rm")} "$0"\nexec {sys.executable} {self.temp / "fake_mutmut.py"} {self.log} passes mutmut "$@"\n')
(tools / "mutmut").chmod(0o755)
ran = self.run_tool(env={"PATH": str(tools)})
self.assertEqual(ran.returncode, 1)
self.assertRegex(ran.stderr, "^mutmut results --all true could not start: ")
def test_rust_php_and_typescript_go_to_cargo_mutants_and_infection_at_the_top_and_to_stryker_by_package(self):
self.change_rust_php_and_typescript()
ran = self.run_tool("--base", "HEAD", "--jobs=3", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", cwd=self.checkout / "src")
report = ["cargo-mutants: 3 mutants on changed lines, 2 not caught.", "src/lib.rs:2:5: missed: replace add(a: i32, b: i32) -> i32 with 0", "src/lib.rs:2:7: timeout: replace + with * in add"]
stryker_reports = ["Stryker in the checkout's top:", "npx reports", "Stryker in web:", "npx reports"]
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:-1]), (0, [*report, "Infection in the checkout's top:", "vendor/bin/infection reports", *stryker_reports]), ran.stderr)
cargo, infection, stryker, web = self.log.read_text().split(f"{self.checkout.resolve()}")[1:]
command, diff = cargo.removeprefix("\n").split("\n", 1)
self.assertRegex(command, r"^cargo mutants --in-diff (\.mutate-changes-\w+)/branch\.diff --output \1 --jobs 3$")
self.assertEqual([line for line in diff.splitlines() if line[:1] in "+-"], ["--- a/src/lib.rs", "+++ b/src/lib.rs", "-\ta + b", "+\tb + a"])
self.assertEqual(infection, f"\nvendor/bin/infection --git-diff-lines --git-diff-base={self.git('rev-parse', 'HEAD').strip()} --threads=3 --show-mutations=max --no-progress\n")
self.assertEqual(stryker, "\nnpx --no --package=@stryker-mutator/core stryker run --mutate src/calc.ts:1-1,src/calc.ts:4-4 --concurrency 3 --reporters clear-text\n")
self.assertEqual(web, "/web\nnpx --no --package=@stryker-mutator/core stryker run --mutate src/app.ts:1-1 --concurrency 3 --reporters clear-text\n")
self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "package.json", "pkg", "src", "web"])
def test_a_javascript_file_with_no_package_json_above_it_is_named_and_not_mutated(self):
(self.checkout / "presentation").mkdir()
(self.checkout / "presentation" / "render.js").write_text("export const one = 1;\n")
self.git("add", "presentation/render.js")
ran = self.run_tool(*self.faked("passes"))
skipped = "Not mutated, as no package.json is above them: presentation/render.js."
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:-1], ran.stderr), (0, [*PASSED, skipped, *NOT_MUTATED], ""))
self.assertNotIn("npx", self.log.read_text())
def test_a_stryker_or_infection_run_that_exits_nonzero_fails_the_run_with_its_whole_output(self):
self.change_rust_php_and_typescript()
self.git("checkout", "HEAD", "--", "src/lib.rs")
# Either exits nonzero on a mutation score below the project's threshold, where its output is the report of what survived.
fails = ["--base", "HEAD", "--prefix", "seq 45; exit 1"]
whole = "".join(f"{n}\n" for n in range(1, 46))
self.assertEqual(self.run_tool(*fails).stderr, f"Infection exited 1:\n{whole}")
self.git("checkout", "HEAD", "--", "src/Calc.php")
self.assertEqual(self.run_tool(*fails).stderr, f"Stryker in the checkout's top exited 1:\n{whole}")
def test_a_changed_file_named_like_an_option_is_mutated(self):
for name in ("-x.py", "-x.rs"):
(self.checkout / name).write_text("")
self.commit()
(self.checkout / "-x.py").write_text("def f():\n\treturn 1\n")
(self.checkout / "-x.rs").write_text("fn f() {}\n")
base = self.git("rev-parse", "HEAD").strip()
self.assertEqual(main.changed_by_tool(str(self.checkout), base, ["-x.py", "-x.rs"]), {"cargo-mutants": {"-x.rs": frozenset({1})}, "mutmut": {"-x.py": frozenset({1, 2})}})
ran = run_cargo_mutants(str(self.checkout), base, ["-x.rs"], f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", 1)
self.assertIsInstance(ran, list)
self.assertIn("+++ b/-x.rs\n", self.log.read_text())
def test_a_tool_that_cannot_start_fails_the_run(self):
self.change_rust_php_and_typescript()
path = str(self.path_with_git())
# The tools run in the order of their names, so undoing the change of the one that failed lets the next one run.
for tool, undone in (("cargo mutants", "src/lib.rs"), ("vendor/bin/infection", "src/Calc.php"), ("npx --no --package=@stryker-mutator/core stryker", "src/calc.ts")):
with self.subTest(tool):
ran = self.run_tool("--base", "HEAD", env={"PATH": path})
self.assertEqual(ran.returncode, 1)
self.assertRegex(ran.stderr, f"^{re.escape(tool)} .* could not start: ")
self.git("checkout", "HEAD", "--", undone)
def test_cargo_mutants_fails_the_run_unless_it_finished(self):
self.change_rust_php_and_typescript()
# The other tools fail on any code but 0.
self.git("checkout", "HEAD", "--", "src/Calc.php", "src/calc.ts", "web/src/app.ts")
for code, failed in ((0, False), (1, True), (2, False), (3, False), (4, True)):
with self.subTest(code):
ran = self.run_tool("--base", "HEAD", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} {code}")
self.assertEqual((ran.returncode, ran.stderr), (1, f"cargo mutants exited {code}:\ncargo reports\n") if failed else (0, ""))
def test_cargo_mutants_outcomes_it_cannot_read_fail_the_run(self):
self.change_rust_php_and_typescript()
ran = self.run_tool("--base", "HEAD", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", env={"CAUGHT_UNREADABLE": "1"})
self.assertEqual(ran.returncode, 1)
self.assertRegex(ran.stderr, rf"^could not hand cargo-mutants the diff or read its outcomes in {re.escape(str(self.checkout.resolve()))}/\.mutate-changes-\w+: ")
self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "package.json", "pkg", "src", "web"])
def test_a_branch_that_adds_no_line_a_tool_mutates_says_so_and_names_what_it_changes(self):
# A file the branch deletes is no longer there to mutate, so the report doesn't name it.
(self.checkout / "pkg" / "old.md").write_text("Gone.\n")
self.commit()
(self.checkout / "pkg" / "old.md").unlink()
ran = self.run_tool(*self.faked("passes"), "--base", "HEAD")
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:-1]), (0, ["No tool ran: the branch adds no line to a file that a tool mutates."]))
(self.checkout / "README.md").write_text("Doubles.\n")
(self.checkout / "pkg" / "test_calc.py").write_text("")
(self.checkout / "pkg" / "calc.py").write_text("def double(n): # doubles\n\treturn n * 2\n")
ran = self.run_tool(*self.faked("passes"), "--base", "HEAD")
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:-1]), (0, ["No tool ran: the branch adds no line to a file that a tool mutates.", *NOT_MUTATED]))
self.assertRegex(ran.stdout.splitlines()[-1], r"^mutate-changes took \d+ s\.$")
self.assertFalse(self.log.exists())
def test_help_prints_the_usage(self):
for flag in ("-h", "--help"):
with self.subTest(flag):
ran = self.run_tool(flag)
self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill."))
def test_unknown_arguments_fail_saying_why(self):
usage = "usage: mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]"
for args, reason in (
(["--jobs", "0"], "--jobs takes a whole number from 1, not 0"),
(["--jobs", "x"], "--jobs takes a whole number from 1, not x"),
(["--jobs", "²"], "--jobs takes a whole number from 1, not ²"),
(["--jobs"], "--jobs needs a value"),
(["--colour"], "unknown or repeated argument --colour"),
(["--base", "a", "--base", "b"], "unknown or repeated argument --base"),
):
with self.subTest(args):
ran = self.run_tool(*args)
self.assertEqual((ran.returncode, ran.stderr), (1, f"{reason}; {usage}\n"))
def test_the_launcher_runs_the_tool(self):
# Run from the launcher's folder: there, under mutmut, the child finds the setup.cfg that mutmut's mutated code reads.
ran = subprocess.run([str(TOOL), "--help"], capture_output=True, cwd=TOOL.parent, encoding="utf-8", env=isolated_env())
self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill."))
if __name__ == "__main__":
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
"""Start a mutation tool, through --prefix's shell text where the run gives one, and wait for it; and make and remove its scratch folder."""
import contextlib
import dataclasses
import os
import pathlib
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
from failure import Failure
GRACE_SECONDS = 10 # how long an interrupted tool has to stop on the SIGINT it is passed, before it is killed
@dataclasses.dataclass(frozen=True)
class Ran:
code: int
output: str # stdout and stderr, as the tool interleaved them
def run_tool(argv: list[str], cwd: str, prefix: str | None) -> Ran | Failure:
"""Run a tool in cwd, reading each byte of its output that is not UTF-8 as U+FFFD.
With a prefix, sh runs `<prefix> "$@"` with argv as its arguments, so the prefix keeps its own quoting and each of argv stays one word."""
command = ["sh", "-c", f'{prefix} "$@"', "sh", *argv] if prefix else argv
try:
# In a session of its own, the tool and each process it starts share one process group, which ends whole below.
process = subprocess.Popen(command, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", start_new_session=True)
except OSError as failure:
return Failure(f"{shlex.join(argv)} could not start: {failure.strerror}")
try:
output = process.communicate()[0]
except BaseException:
# The run is ending, as on Ctrl-C or the SIGTERM the launcher turns into SystemExit, so end what the tool started too. Ctrl-C
# reaches only this process, so pass the tool SIGINT first: a container's CLI, such as docker compose, then stops its container.
try:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGINT)
with contextlib.suppress(subprocess.TimeoutExpired):
process.wait(timeout=GRACE_SECONDS)
finally:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGKILL)
process.wait()
raise
return Ran(process.returncode, output)
def failed(name: str, ran: Ran) -> Failure:
"""A tool's exit code and the last 40 lines of its output, which hold its error."""
return Failure("\n".join([f"{name} exited {ran.code}:", *ran.output.splitlines()[-40:]]))
def scratch_folder(top: str) -> str | Failure:
"""A new folder in top for one tool's files. It holds a .gitignore of `*`, as pytest's cache folder does, so git lists none of them."""
try:
scratch = tempfile.mkdtemp(prefix=".mutate-changes-", dir=top)
pathlib.Path(scratch, ".gitignore").write_text("*\n", encoding="utf-8")
except OSError as failure:
return Failure(f"could not make a scratch folder in {top}: {failure}")
return scratch
def remove(scratch: str) -> None:
"""Remove a scratch folder, saying on stderr where it can't: the run's report holds, so the run doesn't fail."""
try:
shutil.rmtree(scratch)
except OSError as failure:
print(f"could not remove {scratch}: {failure}", file=sys.stderr)
+1 -1
View File
@@ -230,7 +230,7 @@ class Main(unittest.TestCase):
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
+3 -1
View File
@@ -20,9 +20,11 @@ class Price:
return self.input * 2
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Where a chunk records its cost, only the proportions between one model's messages matter, so these may be a little off.
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06, and Fable 5.2's on 2026-11-03), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Where a chunk records its cost, only the proportions between one model's messages matter, so these may be a little off.
PRICES = {
# Archived chunks that ran on Fable 5.1 are still priced from here.
"claude-fable-5-1": Price(10, 0.25, 50),
"claude-fable-5-2": Price(8, 0.2, 40),
"claude-haiku-5-5": Price(0.1, 0.01, 0.5),
"claude-opus-5-5": Price(4, 0.2, 20),
"claude-sonnet-5-5": Price(2, 0.2, 10),
+5 -5
View File
@@ -30,12 +30,12 @@ from routing_figures.render import render
from model_routing.route import Route
LOW = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-opus-5-5", "high")
HIGH = Rung("claude-fable-5-2", "low")
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
def message(id_, at, *parts, model="claude-opus-5-5", usage=None):
"""Costs $2 on Opus 5.5, whose output is $20 per million tokens, and $1 on Sonnet 5.5, whose output is $10."""
"""Writes 100k output tokens: $2 on Opus 5.5, $1 on Sonnet 5.5 and $4 on Fable 5.2, at $20, $10 and $40 per million."""
return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": usage or {"output_tokens": 100_000}}}
@@ -164,10 +164,10 @@ class Measured(unittest.TestCase):
message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")),
message("m3", "2026-10-14T10:31:00Z", call("Agent", "a2", subagent_type="Explore")),
]
subagents = [subagent_of("Explore", "a1", [result("r", "x")]), subagent_of("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-opus-5-5")])]
subagents = [subagent_of("Explore", "a1", [result("r", "x")]), subagent_of("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-fable-5-2")])]
found = chunk_figures(chunk_of("log", [kept], worker, subagents), "/h")
self.assertEqual(found.delegated, {"sonnet at high effort": 1, str(HIGH): 1})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 6.0})
self.assertEqual(found.delegated, {"sonnet at low effort": 1, str(HIGH): 1})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 8.0})
def test_names_a_subagent_by_its_meta_or_else_its_call_or_else_unknown(self):
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Plan"))]
+1 -1
View File
@@ -3,7 +3,7 @@ from command_lines.docker_command import docker_subcommand
from command_lines.shell_command import launched, tool_name
# Each mutation tool, and the words that make its call a mutation run when one of them follows it within two words; where the set is empty, every call is one.
MUTATORS = {"cargo": {"mutants"}, "infection": set(), "mutmut": {"run"}, "stryker": {"run"}}
MUTATORS = {"cargo": {"mutants"}, "infection": set(), "mutate-changes": set(), "mutmut": {"run"}, "stryker": {"run"}}
# Flags with which a tool only prints its help, version or list, so a call that carries one is light. Not -h, which docker run reads as the container's hostname.
LIGHT_FLAGS = frozenset({"--help", "--list", "--version"})
BUILDS = (["build"], ["buildx", "build"], ["compose", "build"])
+1 -1
View File
@@ -77,7 +77,7 @@ RULES: dict[RuleName, Rule] = {
),
"run-heavy": Rule(
"a heavy command, which loads the machine for minutes, runs under ~/.claude/bin/run-heavy, so sessions running at once cannot starve the machine",
"a docker build, docker buildx build or docker compose build, and a run of cargo mutants, Infection, mutmut or Stryker, the mutation tools stability-reviewer names, whether direct, through a launcher such as uvx, or inside docker run, docker exec or docker compose run or exec. A gate script is not checked, since no program can tell it from a light one",
"a docker build, docker buildx build or docker compose build, and a run of mutate-changes, or of cargo mutants, Infection, mutmut or Stryker, the mutation tools it runs, whether direct, through a launcher such as uvx, or inside docker run, docker exec or docker compose run or exec. A gate script is not checked, since no program can tell it from a light one",
),
"todo-rank-check": Rule(
"while todo.md has changes, staged or not, a git commit waits until rank_todo.py --check passes on it: the checkout's own bin/rank_todo.py where the checkout is of this setup's repo, else ~/.claude/bin/rank_todo.py",
+5 -5
View File
@@ -115,12 +115,12 @@ class CommandBreaches(unittest.TestCase):
self.assertEqual(checked("git commit -m 'Answer the question in the README'"), [])
def test_a_docker_build_or_a_mutation_run_outside_run_heavy_breaks_run_heavy(self):
for command in ["docker build -t x .", "cd /w && docker buildx build .", "docker compose build", "docker compose -f x.yml --verbose build app", "uvx --with pytest 'mutmut>=3,<4' run", "cargo mutants --in-diff d", "npx stryker run", "vendor/bin/infection --git-diff-lines", "docker compose run --rm app mutmut run", "docker run --rm -m 4g --memory-swap 4g -v /w:/w rust:1.90.0 cargo mutants", "docker compose exec app npx stryker run", "docker run -h box -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "nice -n 19 docker build .", "env DOCKER_BUILDKIT=1 docker build .", "time -p docker compose build", "docker --tlscacert ca.pem build .", "docker --tlscert c.pem --tlskey k.pem build .", "docker buildx --builder b build .", "docker container run -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "uvx mutmut --verbose run"]:
for command in ["docker build -t x .", "cd /w && docker buildx build .", "docker compose build", "docker compose -f x.yml --verbose build app", "uvx --with pytest 'mutmut>=3,<4' run", "cargo mutants --in-diff d", "npx stryker run", "vendor/bin/infection --git-diff-lines", "docker compose run --rm app mutmut run", "docker run --rm -m 4g --memory-swap 4g -v /w:/w rust:1.90.0 cargo mutants", "docker compose exec app npx stryker run", "docker run -h box -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "nice -n 19 docker build .", "env DOCKER_BUILDKIT=1 docker build .", "time -p docker compose build", "docker --tlscacert ca.pem build .", "docker --tlscert c.pem --tlskey k.pem build .", "docker buildx --builder b build .", "docker container run -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "uvx mutmut --verbose run", "~/.claude/bin/mutate-changes", "cd /w && mutate-changes --base main"]:
with self.subTest(command):
self.assertEqual(checked(command), ["run-heavy"])
def test_a_heavy_command_under_run_heavy_or_a_light_docker_or_mutmut_call_passes(self):
for command in ["~/.claude/bin/run-heavy docker build -t x .", "/home/me/.claude/bin/run-heavy uvx mutmut run", "nice -n 19 ~/.claude/bin/run-heavy docker build .", "env X=1 run-heavy docker compose run app mutmut run", "docker images", "docker compose run --rm app go vet", "docker compose run app make build", "uvx 'mutmut>=3,<4' results", "echo docker build", "npx prettier --check infection.json5", "echo mutmut run", "env", "docker build --help", "cargo mutants --list", "infection --version", "uvx mutmut a b run"]:
for command in ["~/.claude/bin/run-heavy docker build -t x .", "/home/me/.claude/bin/run-heavy uvx mutmut run", "nice -n 19 ~/.claude/bin/run-heavy docker build .", "env X=1 run-heavy docker compose run app mutmut run", "docker images", "docker compose run --rm app go vet", "docker compose run app make build", "uvx 'mutmut>=3,<4' results", "echo docker build", "npx prettier --check infection.json5", "echo mutmut run", "env", "docker build --help", "cargo mutants --list", "infection --version", "uvx mutmut a b run", "~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --jobs 2", "~/.claude/bin/mutate-changes --help"]:
with self.subTest(command):
self.assertEqual(checked(command), [])
@@ -216,8 +216,8 @@ class OverrideLog(unittest.TestCase):
class ReviewerRung(unittest.TestCase):
# A worker routed to Sonnet 5.5 at high, on a project whose rung is Opus 5.5 at medium, with its reviewers on the project's rung.
ENVIRON = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
# The same project, with a worker, and so its reviewers, routed above it to Fable 5.1 at max.
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-1 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
# The same project, with a worker, and so its reviewers, routed above it to Fable 5.2 at max.
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
def refused(self, given: dict, environ: dict[str, str] = ENVIRON) -> list[str]:
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ))
@@ -260,7 +260,7 @@ class ReviewerRung(unittest.TestCase):
def test_a_reviewer_on_the_project_rung_or_a_rerun_above_it_passes(self):
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "medium"}), [])
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "high"}), [])
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "fable", "effort": "low"}), [])
def test_an_agent_calls_prompt_is_the_text_scanned_for_a_marker(self):
call = Call("Agent", {"subagent_type": "prose-reviewer", "prompt": "Review. # rule-override reviewer-rung: trust me"}, "/r")
+1 -1
View File
@@ -64,7 +64,7 @@ class FirstReply(unittest.TestCase):
class DownFrom(unittest.TestCase):
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
self.assertEqual(down_from(Rung("claude-opus-5-5", "high"), MIDDLE), [Rung("claude-opus-5-5", "high"), REFERENCE, MIDDLE])
self.assertEqual(down_from(Rung("claude-fable-5-2", "low"), MIDDLE), [Rung("claude-fable-5-2", "low"), REFERENCE, MIDDLE])
self.assertEqual(down_from(REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
+2
View File
@@ -0,0 +1,2 @@
# mutate-changes runs mutmut from this folder, since the tests here import their modules from it.
[mutmut]
+3 -3
View File
@@ -17,13 +17,13 @@ class SubagentRung(unittest.TestCase):
def test_prints_the_agent_tools_model_and_effort_for_the_rung_an_l_picks(self):
self.assertEqual(main.agent_args("claude-opus-5-5", 3), "model opus, effort medium")
self.assertEqual(main.agent_args("claude-opus-5-5", 2), "model sonnet, effort high")
self.assertEqual(main.agent_args("claude-opus-5-5", 4), "model opus, effort high")
self.assertEqual(main.agent_args("claude-opus-5-5", 4), "model fable, effort low")
self.assertEqual(main.agent_args("claude-sonnet-5-5", 1), "model sonnet, effort high")
self.assertIsNone(main.agent_args("claude-haiku-5-5", 1))
def test_a_planning_task_never_runs_below_the_projects_rung(self):
self.assertEqual(main.agent_args("claude-opus-5-5", 1, planning=True), "model opus, effort medium")
self.assertEqual(main.agent_args("claude-opus-5-5", 4, planning=True), "model opus, effort high")
self.assertEqual(main.agent_args("claude-opus-5-5", 4, planning=True), "model fable, effort low")
self.assertEqual(self.run_tool("--plan", "claude-opus-5-5", "2").stdout, "model opus, effort medium\n")
def test_picks_nothing_for_a_model_off_the_ladder(self):
@@ -38,7 +38,7 @@ class SubagentRung(unittest.TestCase):
def test_the_launcher_prints_the_rung_and_exits_0_on_the_ladder(self):
on = self.run_tool("claude-opus-5-5", "4")
self.assertEqual((on.returncode, on.stdout, on.stderr), (0, "model opus, effort high\n", ""))
self.assertEqual((on.returncode, on.stdout, on.stderr), (0, "model fable, effort low\n", ""))
def test_the_launcher_prints_nothing_and_says_why_and_exits_0_off_the_ladder(self):
off = self.run_tool("claude-opus-5", "4")
+26 -6
View File
@@ -23,7 +23,9 @@ Each project principle states one rule that the decisions below apply; their ent
- review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker unless the fix changes only prose, and never for the judge
- review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
- review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
- review: the worker mutation-tests a chunk's changed lines before each stability round, in place of measuring test coverage
- review: the worker runs the project's tests and static analysis and checks the docs for each changed name before each stability round, and hands stability-reviewer the commit
- review: agents of one type launch in one message, not one a message before the others
- routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
- routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, steps one rung up as the judge interrupts or quotes an answer, or next cycle, up to two rungs above the rung its item picks
@@ -338,16 +340,32 @@ A trial checked that it keeps goal 1.1. It replayed the 6 latest first rounds th
2026-10-29, lilleman: it runs only in the release review. `review: the architecture and principles passes run only in the release review…` says why.
## review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
## review: the worker mutation-tests a chunk's changed lines before each stability round, in place of measuring test coverage
2026-10-13, lilleman through todo item 108, implemented by claude. Serves goals 1.1 and 1.4. Coverage counts the lines a test runs, so a test without a meaningful assertion still raises it. A surviving mutant shows a test that would let behaviour break. Every mutant of an untested changed line survives, so mutation testing of the changed lines also shows what a coverage drop on them would. Coverage would also catch a deleted test; the stability reviewer sees one in the diff without it. Measuring coverage beside it would add cost without raising quality, so todo item 69 was dropped and `principles/technical-principles.md` replaced "Test coverage should not decline" with the mutant rule.
2026-10-13, lilleman through todo item 108, implemented by claude; moved before review on 2026-11-11 through todo item 293. Serves goals 1.1 and 1.4. Coverage counts the lines a test runs, so a test without a meaningful assertion still raises it. A surviving mutant shows a test that would let behaviour break. Every mutant of an untested changed line survives, so mutation testing of the changed lines also shows what a coverage drop on them would. Coverage would also catch a deleted test; the stability reviewer sees one in the diff without it. Measuring coverage beside it would add cost without raising quality, so todo item 69 was dropped and `principles/technical-principles.md` replaced "Test coverage should not decline" with the mutant rule.
The reviewer limits each run to the changed lines, so its cost grows with the chunk. The tools are widely deployed, each with its own way to limit a run to a diff: cargo-mutants `--in-diff` (https://mutants.rs/in-diff.html), Infection `--git-diff-lines` (https://infection.github.io/guide/command-line-options.html), Stryker's mutation ranges (https://stryker-mutator.io/docs/stryker-js/configuration/). mutmut has no such option, so the reviewer mutates the changed files and keeps the mutants on changed lines. On 2026-10-13 mutmut 3 ran on this repo's `larv_review/rounds.py` in under two seconds, set up as README → "Test" says.
The worker runs the project's mutation command, `bin/mutate-changes` where the README documents none, kills the survivors that change behaviour, runs it again, and hands stability-reviewer what is left to judge. Before the move, stability-reviewer ran the mutation tools by hand in 133 of its 144 reports, and 223 of its 428 round-1 findings from 2026-11-02 to 2026-11-10 (52%) were test gaps. One command finds the survivors the same way every time, and the reviewer spends its round on what remains. The worker runs it before each stability round, not once: each fix moves the head, and a reviewer handed a run on an older commit runs it again inside review.
The run is limited to the changed lines, so its cost grows with the chunk. The tools are widely deployed, each with its own way to limit a run to a diff: cargo-mutants `--in-diff` (https://mutants.rs/in-diff.html), Infection `--git-diff-lines` (https://infection.github.io/guide/command-line-options.html), Stryker's mutation ranges (https://stryker-mutator.io/docs/stryker-js/configuration/). mutmut has no such option, so mutate-changes mutates only the functions and methods the changed lines fall in, through mutmut's mutant-name patterns, and counts the mutants on changed lines.
The run has no time cap. Limiting it to the changed lines already bounds it by the chunk's size, and no published standard gives a cap to copy. Each run's wall time in the reviewer's report shows when the premise below fails.
Valid while a mutation run on a chunk's changed lines stays cheap beside the review itself.
## review: the worker runs the project's tests and static analysis and checks the docs for each changed name before each stability round, and hands stability-reviewer the commit
2026-11-11, lilleman through todo item 270, implemented by claude. Serves goal 1.4: a check the worker can run is run once before review, not in each reviewer's round. A subagent counted by keyword, from their headings, the new 🔴 and 🟡 findings in the stability and product-owner round-2 reports modified in the 60 days before 2026-11-11: 73 and 18, from 148 and 75 reports, so the shares are rough. About 29% were an untested branch or surviving mutant and 9% a weak assertion; `bin/mutate-changes` finds both before review since item 293. About 21% were a README, CHANGELOG, help line or comment that the change had made false, and 1% a lint or type error. The rest, edge-case logic (18%), false comments the change didn't cause and wording, need judgement, so they stay with the reviewer.
Stability reviewers ran the whole suite in 52 of this repo's 63 reports from the last 60 days, and the worker's run on the same commit gives the same result. So the worker sweeps for each name, flag, path and number the change touches, runs the suite and analysis as the project's README documents them, and hands the reviewer the passing commit; the reviewer runs them only for another commit. The sweep is the worker's reading, not a program, since a stale claim has no fixed spelling.
Valid while the worker's run on a commit finds what a reviewer's run on it would, and while stale-doc findings in round 2 fall below the 21% measured.
## review: agents of one type launch in one message, not one a message before the others
2026-11-11, claude, in the stability review of the chunk that took the plan item proposing it; lilleman dropped that item the same day. Serves goals 1.4 and 1.5. Anthropic's prompt caching docs say a cache entry is readable only once the first response that wrote it has started, and the item measured 748 comprehension seats, 153 security passes and 130 general-purpose subagents that each wrote their own prefix, $99 from 2026-09-30 to 2026-11-11. Launching one agent of a type before the rest, to read its cache, doesn't pay: a foreground Agent call returns only when its agent has finished, and larv-review runs reviewers in the foreground, so each later launch group would wait one agent's whole run, a seat's median 1.6 minutes, to save a prefix of about 14k tokens. The stability reviewer also found, in the transcripts of 73 seats started within 90 seconds of an earlier seat, that each already read the shared prefix.
Valid while a foreground Agent call returns only when its agent has finished.
## routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass or the branch changes only Markdown no agent follows, which reviews on the project's rung; the seats and the security pass always on the project's
2026-10-14, lilleman. Serves goals 1.1 and 1.4.
@@ -444,11 +462,11 @@ Only Opus 5.5 was replayed, so the judge of a project on another model keeps the
Valid while the archived verdicts show what a judge should return, and until a new model joins the ladder: replay then.
## routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
## routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
2026-10-14, lilleman. Serves goal 1.4, and goal 1.3: one ladder, the same in every project, read by loop-claude and by the worker through `bin/subagent-rung`. The judge's rung is set by `routing: on a model judge-replay covered`. `bin/model_routing/ladder.py` holds the rungs and the steps.
The rungs, least competent first: Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The 2026-10-29 note below took Haiku 5.5 off. They first were: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models, read 2026-10-14), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). That cut drops Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index falls among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scores it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price.
The rungs, least competent first: Sonnet 5.5 at high; Opus 5.5 at medium; Fable 5.2 at low and medium; Opus 5.5 at xhigh; Fable 5.2 at high and max. The 2026-11-11 note below put them so. Before it they were Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max, after the 2026-10-29 note took Haiku 5.5 off. They first were: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). The first cut, from the index read 2026-10-14, dropped Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index fell among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scored it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price. Fable 5.2 at max tops the index outright, so that exception has ended.
A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. A model off the ladder routes nothing: claude runs it at the effort its settings give. A task's L steps its worker from the project's rung: 1 and 2 one down, 3 none, 4 one up. Its E + I steps its reviewers up from the project's rung: 4 or less none, 5 one up, 6 two up, 7 three up, 8 four up. A step past either end stops there. A worker errs more the more it changes and the newer that is, which L scores; review must look harder the further a defect would escape and the more it would break, which E + I scores (goals 1.1 and 1.4). Size raises L, so a large change runs its worker higher. The steps spread the values this repo's plan held when rescored on 2026-10-16, L 1 to 4 and E + I 2 to 7, so a worker on most items runs at or below the project's rung, and a review climbs only where a defect would escape far or break much. lilleman approved the steps on 2026-10-16 as a guess. `score-outcomes` reports how well L, E and I each order finished chunks by review rounds and 🔴 findings. A change to the ladder or the steps is lilleman's.
@@ -462,6 +480,8 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default
2026-11-08, lilleman kept the steps, starting the re-tune with 54 `item-*` branches merged since the steps took effect, 36 of them chunks that each shipped one item scored with L, E and I, in place of waiting for 50 such chunks. Mean review rounds past each pass's first rose with L: 1.57 at L 1, 2.15 at L 2, 2.75 at L 3 and 3.50 at L 4. E + I ordered neither rounds nor 🔴 findings between 3 and 5, and no chunk scored an E + I of 7 or more, so nothing supports changing the steps for E + I 6 to 8. L 1 and L 2 share the Sonnet 5.5 rung yet differ in 🔴 (1 of 7 chunks against 6 of 12), so a 🔴 follows the item more than the rung, and nothing moves L 2. `todo.md` item 273 re-tunes the E + I steps once 10 chunks score an E + I of 6 or more.
2026-11-11, lilleman approved the rungs for Fable 5.2 from the index read that day. Its score and cost per task, for each effort from low to max: Sonnet 5.5 26 $0.51, 31 $0.78, 42 $1.64, 50 $4.09, 55 $10.02; Opus 5.5 35 $0.98, 48 $2.45, 52 $3.46, 57 $6.05, 59 $10.04; Fable 5.2 54 $3.10, 56 $3.80, 62 $9.08, 62 $14.83, 65 $26.54. The cut drops Opus 5.5 at high, since Fable 5.2 at low scores more for less; Opus 5.5 at max, since Fable 5.2 at high scores more for less; and Fable 5.2 at xhigh, which ties Fable 5.2 at high at a higher cost. Sonnet 5.5 at high stays the bottom rung, as the 2026-10-29 note chose. With Haiku 5.5 off, the cut alone would also keep Sonnet 5.5 at low and medium and Opus 5.5 at low, below it. On an Opus 5.5 project, an L 4 worker, an E + I 5 review and a worker's first escalation now run on Fable 5.2 at low, where they ran on Opus 5.5 at high; E + I 8 runs on Fable 5.2 at high, where it ran on Fable 5.1 at max. Three steps land on a rung the index scores lower than before: E + I 6 on Fable 5.2 at medium, 56 against Opus 5.5 at xhigh's 57; E + I 7 on Opus 5.5 at xhigh, 57 against Opus 5.5 at max's 59; and an L 3 worker's escalation stops, without lilleman's yes, at Fable 5.2 at medium, where it stopped at Opus 5.5 at xhigh. On a Sonnet 5.5 project, E + I 6 runs on Fable 5.2 at low, 54 against Opus 5.5 at high's 52; E + I 7 on Fable 5.2 at medium, 56 against Opus 5.5 at xhigh's 57; and E + I 8 on Opus 5.5 at xhigh, 57 against Opus 5.5 at max's 59. Fable 5.2 at max, on top, is reached only one rung up from Fable 5.2 at high, as by a reviewer's rerun. A Fable 5.2 project's rung is Fable 5.2 at low, so its L 1 and L 2 workers run on Opus 5.5 at medium.
Valid while the index ranks these models, and while no newer model joins the catalog.
## routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, when it names a chunk item that picks a higher rung, or when it cites an escalation trigger the judge finds
+64
View File
@@ -1600,3 +1600,67 @@ Read most (opens and searches):
- `CLAUDE.md` 2
- `bin/loop_claude/cycle/judge.py` 2
- `bin/loop_claude/project/records.py` 2
## Reading cost, chunk 47c4f6512691, finished 2026-11-11T17:21:45Z
82731 new input tokens before the first commit.
Read most (opens and searches):
- `todo.md` 8
- `bin/loop_claude/cycle/judge.py` 4
- `rules/todo-items.md` 4
- `bin/loop_claude/cycle/prompts.py` 2
- `bin/loop_claude/cycle/run.py` 2
- `bin/loop_claude/escalation_mark.py` 2
- `bin/loop_claude/verdicts.py` 2
- `bin/loop_claude/routing.py` 1
- `docs/decisions.md` 1
## Reading cost, chunk 3fba05e72d95, finished 2026-11-11T21:05:07Z
86411 new input tokens before the first commit.
Read most (opens and searches):
- `todo.md` 7
- `skills/larv-review/SKILL.md` 4
- `README.md` 2
- `docs/decisions.md` 2
- `CLAUDE.md` 1
- `agents/stability-reviewer.md` 1
- `bin/reading-cost` 1
- `bin/rule_hook/heavy_command.py` 1
## Reading cost, chunk bea37a41be15, finished 2026-11-11T21:18:42Z
174175 new input tokens before the first commit.
Read most (opens and searches):
- `todo.md` 18
- `README.md` 4
- `bin/command_patterns/main.py` 3
- `bin/command_patterns/tally.py` 3
- `skills/larv-review/SKILL.md` 3
- `CHANGELOG.md` 1
- `bin/command_patterns/__init__.py` 1
- `bin/rule_hook/round_cap.py` 1
- `skills/larv-review/review-findings.md` 1
## Reading cost, chunk 55da7e2b543f, finished 2026-11-11T22:37:26Z
101795 new input tokens before the first commit.
Read most (opens and searches):
- `docs/decisions.md` 10
- `todo.md` 9
- `skills/larv-review/SKILL.md` 7
- `agents/stability-reviewer.md` 4
- `README.md` 3
- `skills/comprehension-panel/SKILL.md` 2
- `CHANGELOG.md` 1
- `agents/product-owner-reviewer.md` 1
- `agents/systems-architect.md` 1
- `bin/mutate-changes` 1
+11 -10
View File
@@ -794,18 +794,19 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<div class="eyebrow">Right model for the job</div>
<h2>The model ladder</h2>
<p class="lead">Easy work runs on a cheaper model. Risky work gets a stronger one, and stronger reviewers.</p>
<div class="diagram" role="img" aria-label="Six rungs from cheapest to strongest: Sonnet 5.5 high, Opus 5.5 medium, high, xhigh, max, Fable 5.1 max.">
<div class="diagram" role="img" aria-label="Seven rungs from cheapest to strongest: Sonnet 5.5 high, Opus 5.5 medium, Fable 5.2 low, Fable 5.2 medium, Opus 5.5 xhigh, Fable 5.2 high, Fable 5.2 max.">
<svg viewBox="0 0 960 300">
<defs><marker id="ah7" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path class="head" d="M0,0 L10,5 L0,10 z"/></marker></defs>
<g>
<rect class="box" x="20" y="230" width="140" height="50" rx="5"/><text class="t" x="34" y="252" style="font-size:15px">Sonnet 5.5</text><text class="s" x="34" y="270">high</text>
<rect class="worker" x="174" y="192" width="140" height="88" rx="5"/><text class="t" x="188" y="214" style="font-size:15px">Opus 5.5</text><text class="s" x="188" y="232">medium</text>
<rect class="box" x="328" y="154" width="140" height="126" rx="5"/><text class="t" x="342" y="176" style="font-size:15px">Opus 5.5</text><text class="s" x="342" y="194">high</text>
<rect class="box" x="482" y="116" width="140" height="164" rx="5"/><text class="t" x="496" y="138" style="font-size:15px">Opus 5.5</text><text class="s" x="496" y="156">xhigh</text>
<rect class="box" x="636" y="78" width="140" height="202" rx="5"/><text class="t" x="650" y="100" style="font-size:15px">Opus 5.5</text><text class="s" x="650" y="118">max</text>
<rect class="box" x="790" y="40" width="150" height="240" rx="5"/><text class="t" x="804" y="62" style="font-size:15px">Fable 5.1</text><text class="s" x="804" y="80">max</text>
<rect class="box" x="20" y="230" width="120" height="50" rx="5"/><text class="t" x="32" y="252" style="font-size:15px">Sonnet 5.5</text><text class="s" x="32" y="270">high</text>
<rect class="worker" x="154" y="198" width="120" height="82" rx="5"/><text class="t" x="166" y="220" style="font-size:15px">Opus 5.5</text><text class="s" x="166" y="238">medium</text>
<rect class="box" x="288" y="166" width="120" height="114" rx="5"/><text class="t" x="300" y="188" style="font-size:15px">Fable 5.2</text><text class="s" x="300" y="206">low</text>
<rect class="box" x="422" y="134" width="120" height="146" rx="5"/><text class="t" x="434" y="156" style="font-size:15px">Fable 5.2</text><text class="s" x="434" y="174">medium</text>
<rect class="box" x="556" y="102" width="120" height="178" rx="5"/><text class="t" x="568" y="124" style="font-size:15px">Opus 5.5</text><text class="s" x="568" y="142">xhigh</text>
<rect class="box" x="690" y="70" width="120" height="210" rx="5"/><text class="t" x="702" y="92" style="font-size:15px">Fable 5.2</text><text class="s" x="702" y="110">high</text>
<rect class="box" x="824" y="38" width="120" height="242" rx="5"/><text class="t" x="836" y="60" style="font-size:15px">Fable 5.2</text><text class="s" x="836" y="78">max</text>
</g>
<text class="lbl" x="188" y="266" style="font-weight:700;fill:var(--worker)">project's rung</text>
<text class="lbl" x="166" y="266" style="font-weight:700;fill:var(--worker)">project's rung</text>
<text class="lbl" x="20" y="24" style="font-weight:700">CHEAPER</text>
<text class="lbl" x="940" y="24" text-anchor="end" style="font-weight:700">STRONGER</text>
<path class="edge" d="M100,24 L860,24" marker-end="url(#ah7)"/>
@@ -1005,7 +1006,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
</tbody></table></div>
<h3 class="group">Models</h3>
<div class="tablewrap"><table class="src-t"><colgroup><col style="width:4%"><col style="width:24%"><col style="width:72%"></colgroup><tbody>
<tr id="src-25"><td>25</td><td><b>The model ladder, and no Haiku</b></td><td><span class="kind r">Benchmark</span> The rungs follow the Artificial Analysis Intelligence Index, except Fable 5.1 at max: the index scores it below Opus 5.5 at high, and the human put it on top for the hardest tasks.<br><span class="kind m">Own measurement</span> A chunk on Haiku 5.5 ran 2 h 17 min and wrote 3.1M tokens. The chunk before it, on Sonnet 5.5, took 29 min and 111k. Chunks on Haiku took 7.8 extra review rounds, against 2.8 on Sonnet. So Haiku left the ladder.</td></tr>
<tr id="src-25"><td>25</td><td><b>The model ladder, and no Haiku</b></td><td><span class="kind r">Benchmark</span> The rungs follow the Artificial Analysis Intelligence Index: a rung stays only where no cheaper one scores as high.<br><span class="kind m">Own measurement</span> A chunk on Haiku 5.5 ran 2 h 17 min and wrote 3.1M tokens. The chunk before it, on Sonnet 5.5, took 29 min and 111k. Chunks on Haiku took 7.8 extra review rounds, against 2.8 on Sonnet. So Haiku left the ladder.</td></tr>
<tr id="src-26"><td>26</td><td><b>Judge and reviewers never run below the project's model</b></td><td><span class="kind m">Own measurement</span> 39 judge verdicts were replayed. The reference judge reproduced 31; on those, Opus 5.5 at medium missed none, and Sonnet 5.5 mislabelled 3 interrupts. A replay of review rounds: Sonnet 5.5 missed 44–55% of what the project's model found.</td></tr>
</tbody></table></div>
<h3 class="group">The machine</h3>
@@ -1028,7 +1029,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
<dt>Pass</dt><dd>One kind of review, such as Stability. It runs in rounds.</dd>
<dt>Round</dt><dd>One review by one reviewer. At most two per pass per chunk, five in the release review.</dd>
<dt>Gate</dt><dd>The checks a PR must pass to merge: tests, CI, plan format.</dd>
<dt>Rung</dt><dd>A model at an effort level, such as "Opus 5.5 at high".</dd>
<dt>Rung</dt><dd>A model at an effort level, such as "Opus 5.5 at xhigh".</dd>
<dt>Release review</dt><dd>A release's last chunk: whole-project review before you cut it.</dd>
<dt>Worktree</dt><dd>A separate git checkout per chunk, so your main checkout stays untouched.</dd>
</dl>
+1 -1
View File
@@ -39,7 +39,7 @@
"includeCoAuthoredBy": false,
"mcpServers": {},
"modelSettings": {
"claude-fable-5-1": {
"claude-fable-5-2": {
"effortLevel": "high"
}
},
+6 -2
View File
@@ -28,6 +28,10 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de
**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree, unless loop-claude's prompt shows that `chunk-preflight` already ran it there, and commit what it appends to `docs/reading-cost.md`; the commit re-enters no pass. Resolve a merge conflict in that file by putting the default branch's figures first and dropping a figure for a chunk the default branch already holds. On `Rising:`, file a plan item titled `**Lower the reading cost of the files a chunk reads most before its first commit.**`, scored per `~/.claude/rules/todo-items.md` with the tool's medians and files as its detail; where the plan already holds it, leave it as it is: `docs/reading-cost.md` holds the figures. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. Leave the plan as it is on any other output. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it.
**Tests and static analysis.** Where the branch changes code, config or tests, before each stability round: search the project's Markdown, the help and error text in code, and the comments beside the code for each flag, name, path and number the change renames, removes or changes, and fix each line it made false. Commit, then run the project's test suite and static analysis in the chunk's worktree as its README documents them, and fix a failure before going on. Hand stability-reviewer the commit they last passed on; a fix from the mutation tests below moves the head, so run them again after it, and the reviewer doesn't run them again on that commit.
**Mutation tests.** Where the branch changes code, run the project's mutation command in the chunk's worktree, with every change committed, before each stability round: the one the project's README documents, else `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix '<how the project runs its tools>'`. `mutate-changes --help` says how to set `--prefix` and `--jobs`. Where a mutant of a changed line survives and changes behaviour, kill it: add or strengthen a test that fails on it, commit, and run the command again. Hand stability-reviewer what the last run printed, with the commit it ran on. On exit 1, repair what its message names and run it again; when you cannot, hand the reviewer the message.
## 3. Passes
A pass is one kind of review, a row of the table, named by its first column. Its trigger says when it first runs, on the chunk's branch; "Re-entry" says when a fix reruns it. Its reviewer reports the findings.
@@ -174,7 +178,7 @@ Launch override-reviewer with each line `rule-hook overrides` prints that no ear
### Stability and product-owner
Launch the reviewer with the change — stability-reviewer also with the places per "Comprehension check" → "Places", product-owner-reviewer with the external surface it touches. Each reports only a defect, a requirement of the plan or the goals the change breaks, a breach of a technical principle, or, for stability-reviewer, a place per "Comprehension check" → "Places"; drop any other finding. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). The defect a persona hits is as often in wording or an upgrade path as in code, so a product-owner fix is as often a message or a doc.
Launch the reviewer with the change — stability-reviewer also with the places per "Comprehension check" → "Places", the commit §2's tests and static analysis last passed on, and what the mutation command printed, with its commit, per §2 → "Mutation tests", product-owner-reviewer with the external surface it touches. Each reports only a defect, a requirement of the plan or the goals the change breaks, a breach of a technical principle, or, for stability-reviewer, a place per "Comprehension check" → "Places"; drop any other finding. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). The defect a persona hits is as often in wording or an upgrade path as in code, so a product-owner fix is as often a message or a doc.
### Prose
@@ -184,7 +188,7 @@ Launch prose-reviewer with what the diff touched and every section this review c
1. Merge `origin/<default branch>` into this branch unless the head already holds it.
2. Run `~/.claude/bin/rank_todo.py --check todo.md`; a failure is a finding.
3. Run the project's test suite locally unless the last stability round, or a later run, left the head verified green.
3. Run the project's test suite locally unless a run at the head, §2's or a stability round's, left it verified green.
4. Watch the forge's checks until every one passes. A red check is a finding.
5. No CI configured → the gate is local tests only; note it in the summary.
6. Everything green → mark the PR ready with `~/.claude/bin/chunk-pr ready`.
+105 -79
View File
@@ -6,95 +6,99 @@
`Bar = 0.1`
`Next ID = 325`
`Next ID = 333`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 293 | 0.8.0 | | | **Run mutation tests on a chunk's changed lines in the worker's pre-review gate, through one command that picks the tool by language, and hand stability-reviewer the surviving mutants.** | 3 | 2 | 3 | 6 | 5 | 1.1 by 5, 1.4 by 4, 1.5 by 2 | 2.8 |
| 284 | 0.8.0 | | owner | **Script each step that 0.7.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.6 |
| 270 | 0.8.0 | | | **Move each check a review pass repeats across chunks, other than the mutation tests item 293 moves, into the worker's pre-review gate, starting with the passes most often taken to a second round.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 3, 1.4 by 3 | 2.5 |
| 292 | 0.8.0 | | owner | **Rebuild the routing ladder for Fable 5.2, placing each of its efforts by the Artificial Analysis Intelligence Index beside Opus 5.5's and Sonnet 5.5's, and replace Fable 5.1 wherever it is named.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 4, 1.4 by 3 | 2.4 |
| 320 | 0.8.0 | | | **Bench a worker below the project's rung with the advisor tool against the same worker alone and the project's rung, and file the switch if it wins.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3, 1.1 by 2 | 2.0 |
| 315 | 0.8.0 | | | **Start each reviewer under `agents/` without `CLAUDE.md`, and hand it the vocabulary, the prose rules and the project's decision titles.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 6 | 2.0 |
| 312 | 0.8.0 | | | **Research the tooling agents read, search and run commands with, and file an item for each tool that cuts tokens a replay shows keep quality.** | 1 | 2 | 1 | 2 | 3 | 1.4 by 3, 1.5 by 2 | 2.0 |
| 305 | 0.8.0 | | | **Record with each archived verdict the claude-config commit that ran it, the raw tokens each model spent by kind, and each choice of the worker's that the human reversed, so a change to the setup can be judged before and after.** | 3 | 2 | 3 | 6 | 5 | 1.4 by 4, 1.2 by 3 | 1.8 |
| 318 | 0.8.0 | | | **Let `review-replay` qualify a rung whose recall is no lower than the project's rung's own replay, and replay Opus 5.5 at low effort on the prose pass.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 5 | 1.7 |
| 308 | 0.8.0 | 293 | | **Skip a stability round 2 whose every must-fix finding named a surviving mutant or a failing test that the pre-review gate now kills.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3, 1.5 by 2 | 1.6 |
| 295 | 0.8.0 | | | **Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 2, 1.5 by 2 | 1.6 |
| 319 | 0.8.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.4 |
| 309 | 0.8.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.3 |
| 299 | 0.8.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 |
| 311 | 0.8.0 | | | **Hand each worker's claude a Bash output ceiling that saves longer output to a file, and refuse a Read of a session transcript under `~/.claude/projects`.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3 | 1.2 |
| 316 | 0.8.0 | | | **Launch comprehension seats as an agent type of their own under `agents/`, without `CLAUDE.md` and the skill and agent listings a general-purpose subagent carries.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 |
| 310 | 0.8.0 | | | **Compact a waiting worker's session shortly before its prompt cache expires, only when the human has not answered an interrupt by then.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3 | 1.0 |
| 298 | 0.8.0 | | | **Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.** | 3 | 3 | 3 | 7 | 4 | 1.4 by 2, 1.5 by 1 | 1.0 |
| 313 | 0.8.0 | | | **Launch the first agent of each type in a parallel wave one message before the others of that type, so they read its prompt cache.** | 1 | 2 | 2 | 3 | 2 | 1.4 by 2 | 0.9 |
| 317 | 0.8.0 | | | **Cut the descriptions of stability-reviewer, product-owner-reviewer and systems-architect to one line each.** | 1 | 1 | 1 | 1 | 1 | 1.4 by 1 | 0.5 |
| 303 | 0.9.0 | | defect | **Archive each judge run's prompt and json reply beside the verdict it gave, so judge cost, replays and backups cover the judge as they cover the worker.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3, 3 by 2 | 4.8 |
| 304 | 0.9.0 | 303 | defect | **Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 2, 3 by 2 | 4.4 |
| 306 | 0.9.0 | | | **Set a strategy that keeps loop-claude's archive and larv-review's review folders backed up and small over the years, compressing older entries without losing any.** | 3 | 2 | 4 | 7 | 5 | 3 by 5 | 3.9 |
| 302 | 0.9.0 | | | **Call a scoring run for an item whose tagline makes the comprehension floor its target, and not for one that only names the floor, such as in a quoted decision title.** | 2 | 2 | 3 | 5 | 3 | code health by 2 | 3.6 |
| 287 | 0.9.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 |
| 288 | 0.9.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.6 |
| 77 | 0.9.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 |
| 321 | 0.9.0 | 318 | | **Evaluate the review passes that run on a rung item 318 qualified, against the chunks before them, and revert any pass whose findings or later fixes worsened.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 3, 1.4 by 2 | 2.3 |
| 273 | 0.9.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.3 |
| 268 | 0.9.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 5 | 2.2 |
| 171 | 0.9.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 2.0 |
| 300 | 0.9.0 | | owner | **Restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality first: today the comprehension floor run at 52da15e scored Locality 6.00, Shape 6.25, Self-sufficiency 6.38 and Overall 6.38.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 2.0 |
| 264 | 0.9.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 5 | 2.0 |
| 323 | 0.9.0 | | | **Count a release review as landed once its pull request has merged, whatever its commits are titled.** | 3 | 2 | 3 | 6 | 3 | 1.4 by 3, 1.5 by 2 | 2.0 |
| 149 | 0.9.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 1.8 |
| 165 | 0.9.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 1.8 |
| 151 | 0.9.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 1.8 |
| 68 | 0.9.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 1.8 |
| 102 | 0.9.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 1.7 |
| 135 | 0.9.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 1.7 |
| 5 | 0.9.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 1.6 |
| 291 | 0.9.0 | | owner | **Let `principles/technical-principles.md` → "Sane defaults" allow a library whose README goals ask that it work with no config to default the clock and randomness in its public constructor, where a documented option overrides each.** | 1 | 2 | 3 | 4 | 1 | 1.2 by 3 | 1.4 |
| 156 | 0.9.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 1.4 |
| 196 | 0.9.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 1.3 |
| 260 | 0.9.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.3 |
| 51 | 0.9.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 1.3 |
| 201 | 0.9.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 1.3 |
| 267 | 0.9.0 | | | **Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop.** | 2 | 1 | 3 | 4 | 2 | 1.5 by 3 | 1.3 |
| 4 | 0.9.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 1.3 |
| 324 | 0.9.0 | | | **Count in the routing figures the finished chunks whose worker wrote no `Chunk items:` line.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 2, 1.4 by 1 | 1.2 |
| 187 | 0.9.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.2 |
| 266 | 0.9.0 | | | **Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3 | 1.2 |
| 181 | 0.9.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
| 193 | 0.9.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 1.0 |
| 194 | 0.9.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
| 265 | 0.9.0 | | | **Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.** | 3 | 2 | 2 | 5 | 4 | 1.5 by 3 | 1.0 |
| 169 | 0.9.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 0.8 |
| 197 | 0.9.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 0.4 |
| 1 | 0.10.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 |
| 331 | 0.9.0 | | question | **Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.** | 1 | 1 | 1 | 1 | 2 | 1.4 by 2 | 0.9 |
| 330 | 0.9.0 | | | **Replay the judge on each Fable 5.2 rung an Opus 5.5 project's E + I climbs it to, and keep it off any rung that misses an interrupt.** | 3 | 3 | 2 | 6 | 3 | 1.2 by 4, 1.1 by 3 | 2.9 |
| 328 | 0.9.0 | | owner | **Script each step that 0.8.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.6 |
| 320 | 0.9.0 | | | **Bench a worker below the project's rung with the advisor tool against the same worker alone and the project's rung, and file the switch if it wins.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3, 1.1 by 2 | 2.0 |
| 315 | 0.9.0 | | | **Start each reviewer under `agents/` without `CLAUDE.md`, and hand it the vocabulary, the prose rules and the project's decision titles.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 6 | 2.0 |
| 312 | 0.9.0 | | | **Research the tooling agents read, search and run commands with, and file an item for each tool that cuts tokens a replay shows keep quality.** | 1 | 2 | 1 | 2 | 3 | 1.4 by 3, 1.5 by 2 | 2.0 |
| 325 | 0.9.0 | | | **Give this repo's test suite one command that runs it as README → Test says, prints the failing tests and pytest's summary line, and saves the whole log to a file whose path it prints.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3, 1.5 by 2 | 2.0 |
| 305 | 0.9.0 | | | **Record with each archived verdict the claude-config commit that ran it, the raw tokens each model spent by kind, and each choice of the worker's that the human reversed, so a change to the setup can be judged before and after.** | 3 | 2 | 3 | 6 | 5 | 1.4 by 4, 1.2 by 3 | 1.8 |
| 318 | 0.9.0 | | | **Let `review-replay` qualify a rung whose recall is no lower than the project's rung's own replay, and replay Opus 5.5 at low effort on the prose pass.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 5 | 1.7 |
| 308 | 0.9.0 | | | **Skip a stability round 2 whose every must-fix finding named a surviving mutant or a failing test, both of which the worker now checks before review.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3, 1.5 by 2 | 1.6 |
| 295 | 0.9.0 | | | **Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 2, 1.5 by 2 | 1.6 |
| 319 | 0.9.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.4 |
| 309 | 0.9.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.3 |
| 299 | 0.9.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 |
| 311 | 0.9.0 | | | **Hand each worker's claude a Bash output ceiling that saves longer output to a file, and refuse a Read of a session transcript under `~/.claude/projects`.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3 | 1.2 |
| 316 | 0.9.0 | | | **Launch comprehension seats as an agent type of their own under `agents/`, without `CLAUDE.md` and the skill and agent listings a general-purpose subagent carries.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 |
| 310 | 0.9.0 | | | **Compact a waiting worker's session shortly before its prompt cache expires, only when the human has not answered an interrupt by then.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3 | 1.0 |
| 298 | 0.9.0 | | | **Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.** | 3 | 3 | 3 | 7 | 4 | 1.4 by 2, 1.5 by 1 | 1.0 |
| 326 | 0.9.0 | | | **Let `chunk-pr ready` take the pull request's final title and set it as it marks the pull request ready.** | 2 | 1 | 3 | 4 | 2 | 1.4 by 1, 1.5 by 1 | 0.9 |
| 332 | 0.9.0 | | defect | **Let `deploy-release` move a checkout whose `settings.json` differs from the release only by a `/model` pick or the key order Claude Code writes.** | 2 | 2 | 2 | 4 | 2 | 1.5 by 2 | 0.9 |
| 327 | 0.9.0 | | | **Have `larv-review` print a round commit's title prefix, counted from the round's report, and have rule-hook refuse a round title whose counts differ from it.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 1, 1.4 by 1 | 0.7 |
| 303 | 0.10.0 | | defect | **Archive each judge run's prompt and json reply beside the verdict it gave, so judge cost, replays and backups cover the judge as they cover the worker.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3, 3 by 2 | 4.8 |
| 304 | 0.10.0 | 303 | defect | **Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 2, 3 by 2 | 4.4 |
| 306 | 0.10.0 | | | **Set a strategy that keeps loop-claude's archive and larv-review's review folders backed up and small over the years, compressing older entries without losing any.** | 3 | 2 | 4 | 7 | 5 | 3 by 5 | 3.9 |
| 302 | 0.10.0 | | | **Call a scoring run for an item whose tagline makes the comprehension floor its target, and not for one that only names the floor, such as in a quoted decision title.** | 2 | 2 | 3 | 5 | 3 | code health by 2 | 3.6 |
| 287 | 0.10.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 |
| 288 | 0.10.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.6 |
| 77 | 0.10.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 |
| 321 | 0.10.0 | 318 | | **Evaluate the review passes that run on a rung item 318 qualified, against the chunks before them, and revert any pass whose findings or later fixes worsened.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 3, 1.4 by 2 | 2.3 |
| 273 | 0.10.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.3 |
| 268 | 0.10.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 5 | 2.2 |
| 171 | 0.10.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 2.0 |
| 300 | 0.10.0 | | owner | **Restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality first: today the comprehension floor run at 52da15e scored Locality 6.00, Shape 6.25, Self-sufficiency 6.38 and Overall 6.38.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 2.0 |
| 264 | 0.10.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 5 | 2.0 |
| 323 | 0.10.0 | | | **Count a release review as landed once its pull request has merged, whatever its commits are titled.** | 3 | 2 | 3 | 6 | 3 | 1.4 by 3, 1.5 by 2 | 2.0 |
| 149 | 0.10.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 1.8 |
| 165 | 0.10.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 1.8 |
| 151 | 0.10.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 1.8 |
| 68 | 0.10.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 1.8 |
| 102 | 0.10.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 1.7 |
| 135 | 0.10.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 1.7 |
| 5 | 0.10.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 1.6 |
| 291 | 0.10.0 | | owner | **Let `principles/technical-principles.md` → "Sane defaults" allow a library whose README goals ask that it work with no config to default the clock and randomness in its public constructor, where a documented option overrides each.** | 1 | 2 | 3 | 4 | 1 | 1.2 by 3 | 1.4 |
| 156 | 0.10.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 1.4 |
| 196 | 0.10.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 1.3 |
| 260 | 0.10.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.3 |
| 51 | 0.10.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 1.3 |
| 201 | 0.10.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 1.3 |
| 267 | 0.10.0 | | | **Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop.** | 2 | 1 | 3 | 4 | 2 | 1.5 by 3 | 1.3 |
| 4 | 0.10.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 1.3 |
| 324 | 0.10.0 | | | **Count in the routing figures the finished chunks whose worker wrote no `Chunk items:` line.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 2, 1.4 by 1 | 1.2 |
| 187 | 0.10.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.2 |
| 266 | 0.10.0 | | | **Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3 | 1.2 |
| 181 | 0.10.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
| 193 | 0.10.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 1.0 |
| 194 | 0.10.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
| 265 | 0.10.0 | | | **Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.** | 3 | 2 | 2 | 5 | 4 | 1.5 by 3 | 1.0 |
| 169 | 0.10.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 0.8 |
| 197 | 0.10.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 0.4 |
| 1 | 0.11.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 |
## Details
### 293. Run mutation tests on a chunk's changed lines in the worker's pre-review gate, through one command that picks the tool by language, and hand stability-reviewer the surviving mutants.
### 331. Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.
Of stability-reviewer's 428 round-1 findings from 2026-11-02 to 2026-11-10, 223 (52%) were test gaps, such as a surviving mutant or an unpinned boundary, and 31 of its 50 round 2s held one. 133 of its 144 reports ran mutation tests by hand: today the reviewer picks and runs mutmut, Stryker, cargo-mutants or Infection itself, per `agents/stability-reviewer.md` step 5. A command run once before review, on the lines the branch changed, finds the same survivors deterministically, so the worker kills them before review and the reviewer judges only what remains. This takes over the stability half of item 270. Ship it alone: the nearest finished items, 227, 210, 180 and 73, changed 261 to 402 lines and took 3 to 8 rounds past the first.
The architect's 🔀 answer on PR #493 (item 292): four decisions expire "when a new model joins the ladder". Fable 5.2 joined above every project model's rung, and none of these replays tested a rung above the project's, so the event fired with nothing new to test. Every later ladder rebuild would fire all four again.
### 284. Script each step that 0.7.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.
- `review: each pass keeps a reviewer of its own`: the merge trials ran on Opus 5.5 at medium. Reword the "Valid" line to name that rung.
- `review: the principles audit runs only in the release review…`: its trial ran on the project's rung. Reword the line to name that rung.
- `routing: a review pass runs below the project's rung only on a rung that a replay…`: `review-replay` tests only rungs below the project's rung. Have the line expire when those rungs change, the event item 196 names ("until a cheaper model joins the ladder").
- `routing: on a model judge-replay covered, the judge runs…`: the replay tested the project's rung and below, while the climb above rests on the ladder's order alone. Have the line name both, and point the climb at item 330.
lilleman asked, on 2026-10-16, for a standing audit each release, so the loop keeps moving work a program does as well from the model to scripts (goals 1.4 and 1.5). This audit reads the archived transcripts of the chunks that shipped release 0.7.0 for every step that chunks repeated by hand, before, during or after review. It keeps the steps whose answer a program computes the same way each time, such as a lookup, a check, a prompt assembled for a reviewer, a cleanup. File one item per such step, with the time and tokens it cost, into the next release with items left. Leave a step that needs judgement with the model. Run item 283's tool first, once it has shipped.
Recommendation: reword all four as above. They are decisions the repo held before item 292, so the rewording is lilleman's call.
The chunk that ships this item files a copy of this audit in the release after this item's own, to audit this item's release, rewording "0.7.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it.
### 330. Replay the judge on each Fable 5.2 rung an Opus 5.5 project's E + I climbs it to, and keep it off any rung that misses an interrupt.
### 270. Move each check a review pass repeats across chunks, other than the mutation tests item 293 moves, into the worker's pre-review gate, starting with the passes most often taken to a second round.
Item 292 put Fable 5.2 on the routing ladder. On an Opus 5.5 project the judge now climbs with its chunk's E + I onto Fable 5.2 at low, medium and high, at E + I 5, 6 and 8. Fable 5.2 has never returned a judge verdict, and the 2026-10-15 replay showed that another model can miss an interrupt in kind, not only in strength. `routing: on a model judge-replay covered, the judge runs …` rests on that replay.
The review folders under `~/.local/state/larv-review/`, review replays left out, hold a stability round 2 beside 137 of 211 round-1 reports (65%), product-owner 73 of 173 (42%) and prose 8 of 277 (3%), on 2026-11-08. The architecture and principles passes run up to five rounds in a release review, so they don't compare. From 2026-11-02 to 2026-11-10, 223 of stability's 428 round-1 findings (52%) were test gaps, and 31 of its 50 round 2s held one; item 293 moves the mutation tests that find most of them. Check which kinds of finding the other round 2s repeat, such as an unhandled error or a product-owner wording fix. Move only a check a program or the worker can run before review; leave judgement with the reviewer.
`bin/judge-replay` replays only the project's rung and the rungs below it (`down_from` in `judge_replay/main.py`), so as it stands it never runs a Fable 5.2 rung. Give it the rungs the judge climbs to as well, run `bin/judge-replay claude-opus-5-5`, and record the result in that decision. Where a Fable 5.2 rung misses an interrupt the reference judge returns, keep the judge off it until a decision says otherwise.
### 292. Rebuild the routing ladder for Fable 5.2, placing each of its efforts by the Artificial Analysis Intelligence Index beside Opus 5.5's and Sonnet 5.5's, and replace Fable 5.1 wherever it is named.
The review passes need no replay: `review-replay` tests only rungs below the project's rung, which item 292 left as they were.
Fable 5.2 (`claude-fable-5-2`) has been released. The ladder in `bin/model_routing/ladder.py` tops out at `Rung("claude-fable-5-1", "max")`, and the decision `routing: one ladder of (model, effort) rungs` holds "while no newer model joins the catalog", so it is due for a rebuild.
### 328. Script each step that 0.8.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.
Read the index again (https://artificialanalysis.ai/leaderboards/models), at each effort it scores, with its cost per task. Rebuild the ladder by the decision's cut: a rung stays only where no cheaper rung scores as high. Fable 5.2 may earn more than one rung, and a cheaper effort of it may push an Opus 5.5 rung off. Where the order changes which rung a project's model starts on, or how far the L and E + I steps reach, say so in the decision. The rungs are the human's choice (`CLAUDE.md` → "Working loop", "Ask, don't guess"), so propose the new ladder with the index's figures and get the human's approval before changing code.
lilleman asked, on 2026-10-16, for a standing audit each release, so the loop keeps moving work a program does as well from the model to scripts (goals 1.4 and 1.5). This audit reads the archived transcripts of the chunks that shipped release 0.8.0 for every step that chunks repeated by hand, before, during or after review. It keeps the steps whose answer a program computes the same way each time, such as a lookup, a check, a prompt assembled for a reviewer, a cleanup. File one item per such step, with the time and tokens it cost, into the next release with items left. Leave a step that needs judgement with the model. Run `command-patterns 0.8.0` first; its table names the patterns, and `read_threads` and `calls` in `bin/command_patterns/tally.py` open the calls of one pattern. The 0.7.0 audit found that most steps its chunks repeated were already scripted by that release's own tools, so a step a shipped item already covers is not filed.
Then replace `claude-fable-5-1` where it is named: `ladder.py`, `bin/routing_figures/prices.py` (Fable 5.2's prices), `settings.json` → `modelSettings`, the tests in `bin/model_routing/`, `bin/loop_claude/`, `bin/judge_replay/` and `bin/rule_hook/`, `docs/decisions.md` and `presentation/index.html`. Keep Fable 5.1 in `prices.py` while archived chunks that ran on it are still priced from there.
The chunk that ships this item files a copy of this audit in release 0.10.0, the release after this item's own, to audit release 0.9.0, rewording "0.8.0" to "0.9.0", and marks the copy `owner`, so the audit recurs each release until lilleman drops it.
### 320. Bench a worker below the project's rung with the advisor tool against the same worker alone and the project's rung, and file the switch if it wins.
@@ -112,6 +116,16 @@ lilleman, 2026-11-11: besides an output ceiling, keep evaluating better tooling.
Run a research round like that of 2026-11-11: a lead on the project's rung plans the searches, cheaper subagents search and distil sourced findings, and the lead checks every claim it relies on against this archive's measured spend. File an item for each tool that a replay could test. lilleman, 2026-11-11: repeat the round once per claude-config release, not per project. When this item's chunk finishes, file the next round into the next claude-config release with items left, so the check comes back periodically.
The 0.8.0 audit (item 284) measured: over the 35 chunks that shipped 0.7.0, workers made 36 Edit calls but about 250 `python3` heredocs that replace a string in a file and write it back, about 120k command tokens of the 135k that all 375 `python3` calls took. They read files with `sed` in 493 Bash calls and `cat` in 188, for 351k and 328k result tokens, beside 691 Read calls. Edit refuses a file not read with the Read tool, so a worker that read a file with `sed` or `cat` probably edits it through python. Check that cause, and whether reading through Read, or an Edit that accepts such a file, cuts tokens and keeps quality.
### 325. Give this repo's test suite one command that runs it as README → Test says, prints the failing tests and pytest's summary line, and saves the whole log to a file whose path it prints.
The 0.8.0 audit (item 284) measured, over the 35 chunks that shipped 0.7.0: 163 to 176 Bash calls ran pytest, mutation runs excluded, in 29 chunks, for about 32k command tokens and 3,000 to 3,500 s of wall time. Each worker typed README → Test's incantation, with its pins, and cut the output with its own `| tail -N`: 14 spellings (tail sizes 1, 2, 3, 4, 5, 6, 8, 12, 15, 20, 25, 30 and 70, or no tail in 44 calls). A short tail cuts a failing run's evidence, and a long run without one floods the context.
Add one command, beside the README's Test section, that runs the suite as README → Test says, passes on any test paths or pytest options it is given, prints each failing test with its error and pytest's summary line, and saves the whole log to a file whose path it prints. Point README → Test at it, so the pins live in one place. Write its tests first: a passing run, a failing one, and a run that cannot start.
Left with the model: which tests to run, reading the failures and fixing them.
### 305. Record with each archived verdict the claude-config commit that ran it, the raw tokens each model spent by kind, and each choice of the worker's that the human reversed, so a change to the setup can be judged before and after.
Three records the archive lacks, asked for by lilleman on 2026-11-11 after the token research of that day.
@@ -128,11 +142,11 @@ Today a rung qualifies only if it re-finds every finding the project's rung foun
lilleman approved on 2026-11-11 as somewhat risky, with a close evaluation in the next release: item 321. Revise the decision `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…`, and its title at the head of `docs/decisions.md`.
### 308. Skip a stability round 2 whose every must-fix finding named a surviving mutant or a failing test that the pre-review gate now kills.
### 308. Skip a stability round 2 whose every must-fix finding named a surviving mutant or a failing test, both of which the worker now checks before review.
Rounds past the first cost $846 of the $9,154 the archive measured from 2026-09-30 to 2026-11-11; stability's were $281 over 440 runs. Once item 293 runs the mutation tests in the worker's gate, a 🔴 that named a surviving mutant or a failing test has a mechanical answer: the gate's run on the fix kills the mutant, or the test passes. A round 2 whose every 🔴 and 🟡 is of that kind needs no reviewer.
Rounds past the first cost $846 of the $9,154 the archive measured from 2026-09-30 to 2026-11-11; stability's were $281 over 440 runs. Now that the worker runs `mutate-changes` before each stability round (`skills/larv-review/SKILL.md` §2 → "Mutation tests"), a 🔴 that named a surviving mutant or a failing test has a mechanical answer: a run of `mutate-changes` on the fix shows the mutant killed, or the test passes. A round 2 whose every 🔴 and 🟡 is of that kind needs no reviewer.
Round 2 still matters elsewhere: 53 of 241 archived stability reports of round 2 or later open with BLOCK. So first count, from the archived round 2s, the BLOCKs the gate's run on the fix would not have raised, and ship the skip only if none falls in a round it would skip. Evidence: one review round scored F1 0.376 and a second 0.26 to 0.30 with more false positives (arXiv 2603.16244, `claude -p` with Opus 4.6, 30 artifacts). Revise larv-review §3 → "Re-entry" and the decision `review: a fix for a 🔴 reruns the pass that found it…`.
Round 2 still matters elsewhere: 53 of 241 archived stability reports of round 2 or later open with BLOCK. So first count, from the archived round 2s, the BLOCKs that a run of `mutate-changes` and the tests on the fix would not have raised, and ship the skip only if none falls in a round it would skip. Evidence: one review round scored F1 0.376 and a second 0.26 to 0.30 with more false positives (arXiv 2603.16244, `claude -p` with Opus 4.6, 30 artifacts). Revise larv-review §3 → "Re-entry" and the decision `review: a fix for a 🔴 reruns the pass that found it…`.
### 295. Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file.
@@ -178,15 +192,27 @@ Probe first that `claude -p "/compact" --resume <id>` compacts a session: the Ag
153 `Judge cost:` entries total $109.76, a median of about $0.76 a verdict at every rung, and the cost follows the size of the records, not the transcript: about 76k characters in log and 188k in claude-config. In 224 of 251 recent verdicts (89%) the evidence sits in the worker's final message. A missed interrupt is the costly error, so the bar is zero changed interrupts and zero new rejections across the replay. The judge is about 4.5% of dollars, so the saving is small; each cycle also gets faster.
### 313. Launch the first agent of each type in a parallel wave one message before the others of that type, so they read its prompt cache.
### 326. Let `chunk-pr ready` take the pull request's final title and set it as it marks the pull request ready.
A cache entry is readable only once the first response that wrote it has started ("If you need cache hits for parallel requests, wait for the first response before sending subsequent requests", Anthropic's prompt caching docs). Between 2026-09-30 and 2026-11-11, 748 comprehension seats started within 90 seconds of another seat in the same chunk and each still wrote its own prefix, $73; so did 153 security passes ($17) and 130 general-purpose subagents ($9). Different agent types share no prefix, so only agents of one type gain.
The 0.8.0 audit (item 284) measured, over the 35 chunks that shipped 0.7.0: 30 `tea pr edit` calls in 18 chunks, about 2.0k command tokens. 17 of them, in 15 chunks, retitled a draft pull request the worker had opened with a provisional title; the rest looked up `tea pr edit --help`, rewrote a description or toggled the draft. On Gitea, `chunk-pr ready` already rewrites the title, dropping `WIP: `, so setting the final title there is the same call.
Change `skills/comprehension-panel/SKILL.md` → "Parallel" and `skills/larv-review/SKILL.md` → "Waves": launch one agent of a type, and the others of that type in the next message. Quality doesn't change, since every agent gets the same prompt and model; the cost is one extra worker turn, about $0.02, and a few seconds. Check: the first-turn `cache_read_input_tokens` of seats two to four in the next scoring run.
Let `chunk-pr ready` take an optional final title and set it as it marks the pull request ready, on GitHub and on Gitea, and refuse a title of more than one line. `bin/chunk_pr/main.py:42` `forge` is a place the comprehension seats found hard; where the change touches it, make it easier to read, or leave it to item 287.
### 317. Cut the descriptions of stability-reviewer, product-owner-reviewer and systems-architect to one line each.
Left with the model: wording the title.
Their descriptions, 7.5 KB together, sit in the agent listing of every worker and general-purpose subagent in every project, about 0.7% of spend. larv-review launches them by name, so its routing doesn't depend on them. The one downside: a session outside larv-review relies on a description to decide when to launch an agent unasked, so a one-line description makes that less likely. Keep the line specific enough that a reader knows when to pick each. lilleman approved on 2026-11-11.
### 332. Let `deploy-release` move a checkout whose `settings.json` differs from the release only by a `/model` pick or the key order Claude Code writes.
On 2026-11-12, moving `~/.claude` from v0.7.0 to v0.8.0, `deploy-release` failed at `git checkout --quiet --detach v0.8.0`: "Your local changes to the following files would be overwritten by checkout: settings.json". Claude Code had rewritten the file with `"model": "opus"` and its keys in another order. The `settings` clean filter drops the model and sorts the keys, so `git diff` showed no change and the tool's own check passed, but checkout compares the file as it is on disk. `deploy-release --help` says a model picked with `/model` doesn't block the move.
The move worked after `git checkout -- settings.json`, with the model added back by hand. Have the tool set aside a change the clean filter removes, move, and restore the model pick, or tell the user to pick it again, as it already does when the move changes `settings.json`. Test it with a working file that differs from HEAD only by the model and the key order.
### 327. Have `larv-review` print a round commit's title prefix, counted from the round's report, and have rule-hook refuse a round title whose counts differ from it.
The 0.8.0 audit (item 284) measured, over the 35 chunks that shipped 0.7.0: 72 commit calls in 33 chunks titled `Answer <pass> round <n>: R 🔴, Y 🟡 (K misread); <what changed>`, about 11k command tokens, most of them the summary. Each worker counts R, Y and K by hand. All three are in the round's report, `<pass>-round-<n>.md` in the review folder: R and Y are its finding headings, and K counts the findings the reviewer marked `[misread]`, as `bin/review_rules/round_titles.py` says. That module parses the counts for `score-outcomes`, which reports them as goal 1.1's signal, and rule-hook's `round_cap.py` checks only the round number, so nothing checks today that the counts match the report. Of the 8 titles whose report the audit could match, none miscounted; one report wrote its markers at line start rather than in `###` headings, so the reports' format varies by reviewer.
Add a `larv-review` subcommand that prints a round title's prefix, up to and including the `;`, from the round's report, and have rule-hook refuse a round title whose counts differ from it. Pin the marker format in each reviewer's definition under `agents/`, or count every format the reports use today. Where the report is missing, say so and let the commit through.
Left with the model: the summary after the `;`, and answering the findings.
### 303. Archive each judge run's prompt and json reply beside the verdict it gave, so judge cost, replays and backups cover the judge as they cover the worker.
+2
View File
@@ -0,0 +1,2 @@
# mutate-changes runs mutmut from this folder, since the tests here import their modules from it.
[mutmut]